repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
codeka/wwmmo
common/src/main/kotlin/au/com/codeka/warworlds/common/XmlIterator.kt
1
1491
package au.com.codeka.warworlds.common import org.w3c.dom.Element import org.w3c.dom.Node /** * This is an implementation of [Iterator] which lets us more easily iterator over * Java XML nodes. */ object XmlIterator { /** * This iterator iterates child elements of the given parent element. */ fun childElements(elem: Element, name: String? = null): Iterable<Element> { var node: Node? node = elem.firstChild while (node != null) { if (node.nodeType == Node.ELEMENT_NODE && (name == null || node.nodeName == name)) { break } node = node.nextSibling } val firstNode = node return object : Iterable<Element> { override fun iterator(): Iterator<Element> { return object : Iterator<Element> { var childNode = firstNode private fun findNext(startingNode: Node?): Node? { var n = startingNode!!.nextSibling while (n != null) { if (n.nodeType == Node.ELEMENT_NODE && (name == null || n.nodeName == name)) { return n } n = n.nextSibling } return null } override fun hasNext(): Boolean { return childNode != null } override fun next(): Element { val nextElement = childNode as Element childNode = findNext(childNode) return nextElement } } } } } }
mit
90b1954f6792a2039776d1a037cefedc
26.62963
82
0.547954
4.630435
false
false
false
false
peervalhoegen/SudoQ
sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/sudoku/Utils.kt
1
2853
package de.sudoq.model.sudoku import kotlin.math.abs //fun oneplusone (): Int = 2 /** * Determines the group shape from a constraint holding the positions * @param c the constraint * @return shape of constraint as enum */ fun getGroupShape(c: Constraint): Utils.ConstraintShape { return getGroupShape(c.getPositions()) } fun getGroupShape(pList: List<Position>): Utils.ConstraintShape { return when { Utils.isRow(pList) -> Utils.ConstraintShape.Row Utils.isColumn(pList) -> Utils.ConstraintShape.Column Utils.isDiagonal(pList) -> Utils.ConstraintShape.Diagonal else -> Utils.ConstraintShape.Block } } /** * Utils class todo kotlin doesn't need functions to be in a class -> refactor */ object Utils { @JvmStatic fun positionToRealWorld(p: Position): Position { return Position( p.x + 1, p.y + 1 ) } @JvmStatic fun symbolToRealWorld(symbol: Int): Int { require(symbol >= 0) { "Symbol is below 0, so there is no real world equivalent" } return symbol + 1 } //Todo return enum probably prettier //This is bad for localization /* * analyses whether the list of positions constitutes a roe/col/diag/block * TODO currently only tests for alignment but not continuity! * */ @JvmStatic fun classifyGroup(pl: List<Position>): String { assert(pl.size >= 2) return when (getGroupShape(pl)) { ConstraintShape.Row -> "row " + (pl[0].y + 1) ConstraintShape.Column -> "col " + (pl[0].x + 1) ConstraintShape.Diagonal -> "a diagonal" else -> "a block containing (" + positionToRealWorld(pl[0]) + ")" } } fun isRow(list: List<Position>): Boolean { assert(list.size >= 2) val ycoord = list[0].y for (pos in list) if (pos.y != ycoord) return false return true } fun isColumn(list: List<Position>): Boolean { assert(list.size >= 2) val xcoord = list[0].x for (pos in list) if (pos.x != xcoord) return false return true } fun isDiagonal(list: List<Position>): Boolean { assert(list.size >= 2) var diag = true val diff = list[0].distance(list[1]) //gradient = diff-vector val reference = list[1] for (i in 2 until list.size) { val d = reference.distance(list[i]) if (abs(d.x * diff.y) != abs(diff.x * d.y)) //ratio comparison trick: a/b==c/d <=> a*d == b*c, abs for 180° difference diag = false } return diag } /** Shapes of the constraints as the user would classify them */ enum class ConstraintShape { Row, Column, Diagonal, Block, Other //Never change the order!!! string-arrays in the xml-values depend on it! } }
gpl-3.0
7dd269acfe924f0e344315102886b308
29.351064
130
0.602384
3.859269
false
false
false
false
TeamWizardry/LibrarianLib
modules/foundation/src/main/kotlin/com/teamwizardry/librarianlib/foundation/block/FoundationBlockProperties.kt
1
5661
package com.teamwizardry.librarianlib.foundation.block import net.minecraft.block.* import net.minecraft.block.AbstractBlock.IExtendedPositionPredicate import net.minecraft.block.AbstractBlock.IPositionPredicate import net.minecraft.block.material.Material import net.minecraft.block.material.MaterialColor import net.minecraft.block.material.PushReaction import net.minecraft.entity.EntityType import net.minecraft.util.Direction import net.minecraft.util.math.BlockPos import net.minecraft.world.IBlockReader import net.minecraftforge.common.ToolType import kotlin.math.max import java.util.function.Function import java.util.function.ToIntFunction /** * Similar to [Block.Properties], but adds flammability and the ability to compose properties using [applyFrom]. */ public class FoundationBlockProperties: BlockPropertiesBuilder<FoundationBlockProperties> { /** * Backing data for the [BlockPropertiesBuilder] builder methods. Just a reference to `this` */ override val blockProperties: FoundationBlockProperties get() = this // Vanilla properties public var material: Material? = null public var mapColor: Function<BlockState, MaterialColor>? = null public var blocksMovement: Boolean? = null // default: true public var soundType: SoundType? = null // default: SoundType.STONE public var lightLevel: ToIntFunction<BlockState>? = null // default: 0 public var hardnessAndResistance: Pair<Float, Float>? = null // default: 0f, 0f public var requiresTool: Boolean? = null // default: false public var ticksRandomly: Boolean? = null // default: false public var slipperiness: Float? = null // default: 0.6f public var speedFactor: Float? = null // default: 1.0f public var jumpFactor: Float? = null // default: 1.0f /** Sets loot table information */ public var noDrops: Boolean? = null // default: false public var isSolid: Boolean? = null // default: true public var isAir: Boolean? = null // default: false public var variableOpacity: Boolean? = null // default: false public var harvestLevel: Int? = null // default: -1 public var harvestTool: ToolType? = null public var lootFrom: Block? = null public var allowsSpawn: IExtendedPositionPredicate<EntityType<*>>? = null public var isOpaque: IPositionPredicate? = null public var suffocates: IPositionPredicate? = null /** If it blocks vision on the client side. */ public var blocksVision: IPositionPredicate? = null public var needsPostProcessing: IPositionPredicate? = null public var emissiveRendering: IPositionPredicate? = null // Foundation properties public var flammability: Int? = null public var fireSpreadSpeed: Int? = null //region Builders /** * Creates a vanilla [Block.Properties] object based on this one */ public val vanillaProperties: AbstractBlock.Properties get() { val properties = AbstractBlock.Properties.create( material ?: GENERIC_MATERIAL, mapColor ?: Function { MaterialColor.AIR } ) if (blocksMovement == false) properties.doesNotBlockMovement() soundType?.also { properties.sound(it) } lightLevel?.also { properties.setLightLevel(it) } hardnessAndResistance?.also { properties.hardnessAndResistance(it.first, it.second) } if (ticksRandomly == true) properties.tickRandomly() slipperiness?.also { properties.slipperiness(it) } speedFactor?.also { properties.speedFactor(it) } jumpFactor?.also { properties.jumpFactor(it) } if (noDrops == true) properties.noDrops() lootFrom?.also { properties.lootFrom(it) } if (isSolid == false) properties.notSolid() if (isAir == true) properties.setAir() if (variableOpacity == true) properties.variableOpacity() harvestLevel?.also { properties.harvestLevel(it) } harvestTool?.also { properties.harvestTool(it) } requiresTool?.also { properties.setRequiresTool() } allowsSpawn?.also { properties.setAllowsSpawn(it) } isOpaque?.also { properties.setOpaque(it) } suffocates?.also { properties.setSuffocates(it) } blocksVision?.also { properties.setBlocksVision(it) } needsPostProcessing?.also { properties.setNeedsPostProcessing(it) } emissiveRendering?.also { properties.setEmmisiveRendering(it) } return properties } public fun getFlammabilityImpl(state: BlockState?, world: IBlockReader?, pos: BlockPos?, face: Direction?): Int { return flammability ?: 0 } public fun getFireSpreadSpeedImpl(state: BlockState?, world: IBlockReader?, pos: BlockPos?, face: Direction?): Int { return fireSpreadSpeed ?: 0 } /** * True if this block is sourcing its properties from another block's table */ public val usesExternalLoot: Boolean get() = lootFrom != null private inline fun build(block: () -> Unit): FoundationBlockProperties { block() return this } private companion object { private val GENERIC_MATERIAL = Material( MaterialColor.AIR, // materialMapColor false, // liquid true, // solid true, // doesBlockMovement true, // opaque false, // canBurn false, // replaceable PushReaction.NORMAL // mobilityFlag ) } }
lgpl-3.0
4e514efed0cf55b94d835c912d246c24
40.328467
120
0.666667
4.565323
false
false
false
false
mvarnagiris/expensius
app-core/src/main/kotlin/com/mvcoding/expensius/feature/login/LoginPresenter.kt
1
6147
/* * Copyright (C) 2017 Mantas Varnagiris. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package com.mvcoding.expensius.feature.login import com.mvcoding.expensius.RxSchedulers import com.mvcoding.expensius.data.ParameterDataSource import com.mvcoding.expensius.extensions.putInList import com.mvcoding.expensius.feature.ErrorView import com.mvcoding.expensius.feature.Resolution.POSITIVE import com.mvcoding.expensius.feature.ResolvableErrorView import com.mvcoding.expensius.feature.RxState import com.mvcoding.expensius.feature.login.LoginPresenter.Destination.APP import com.mvcoding.expensius.feature.toError import com.mvcoding.expensius.model.AuthProvider import com.mvcoding.expensius.model.AuthProvider.ANONYMOUS import com.mvcoding.expensius.model.AuthProvider.GOOGLE import com.mvcoding.expensius.model.GoogleToken import com.mvcoding.expensius.model.Login import com.mvcoding.expensius.model.Login.AnonymousLogin import com.mvcoding.expensius.model.Login.GoogleLogin import com.mvcoding.mvp.Presenter import rx.Observable import rx.Subscription class LoginPresenter( private val destination: Destination, private val loginSource: ParameterDataSource<Login, Unit>, private val schedulers: RxSchedulers) : Presenter<LoginPresenter.View>() { private val rxState = RxState<State>(State.WaitingForLoginSelection) override fun onViewAttached(view: View) { super.onViewAttached(view) rxState.registerState(State.WaitingForLoginSelection::class) { stateWaitingForLoginSelection(view) } rxState.registerState(State.AskingForGoogleToken::class) { stateAskingForGoogleToken(view) } rxState.registerState(State.LoggingIn::class) { stateLoggingIn(view, it.login) } rxState.registerState(State.ResolvableFailedLogin::class) { stateResolvableFailedLogin(view, it.login, it.throwable) } rxState.subscribe() } override fun onViewDetached(view: View) { super.onViewDetached(view) rxState.unsubscribe() } private fun stateWaitingForLoginSelection(view: View): List<Subscription> { if (destination == APP) view.showAllLoginOptions() else view.showAllLoginOptionsExceptSkip() return listOf( view.googleLogins().subscribeUntilDetached { requestGoogleToken() }, view.skipLogins().subscribeUntilDetached { loginAnonymously() }) } private fun stateAskingForGoogleToken(view: View): List<Subscription> { return view.showGoogleTokenRequest() .subscribeUntilDetached { when (it) { is GoogleTokenResult.SuccessfulGoogleTokenResult -> login(it.googleToken, forceLogin = false) is GoogleTokenResult.FailedGoogleTokenResult -> showError(view, it.throwable) } } .putInList() } private fun stateLoggingIn(view: View, login: Login): List<Subscription> { view.showLoggingIn(login.toAuthProvider()) return loginSource.data(login) .subscribeOn(schedulers.io) .observeOn(schedulers.main) .subscribeUntilDetached({ view.displayDestination(destination) }, { showError(view, it, login) }) .putInList() } private fun stateResolvableFailedLogin(view: View, login: Login, throwable: Throwable): List<Subscription> { waitForLoginSelection() return view.showResolvableError(throwable.toError()) .subscribeUntilDetached { if (it == POSITIVE && login is GoogleLogin) login(login.googleToken, forceLogin = true) } .putInList() } private fun waitForLoginSelection() = rxState.setState(State.WaitingForLoginSelection) private fun requestGoogleToken() = rxState.setState(State.AskingForGoogleToken) private fun login(googleToken: GoogleToken, forceLogin: Boolean) = rxState.setState(State.LoggingIn(GoogleLogin(googleToken, forceLogin))) private fun loginAnonymously() = rxState.setState(State.LoggingIn(AnonymousLogin)) private fun failWithResolvableError(login: Login, throwable: Throwable) = rxState.setState(State.ResolvableFailedLogin(login, throwable)) private fun showError(view: View, throwable: Throwable, login: Login? = null) { val error = throwable.toError() if (error.isResolvable() && login != null) failWithResolvableError(login, throwable) else { waitForLoginSelection() view.showError(error) } } private fun Login.toAuthProvider() = when (this) { is AnonymousLogin -> ANONYMOUS is GoogleLogin -> GOOGLE } interface View : Presenter.View, ErrorView, ResolvableErrorView { fun googleLogins(): Observable<Unit> fun skipLogins(): Observable<Unit> fun showAllLoginOptions() fun showAllLoginOptionsExceptSkip() fun showGoogleTokenRequest(): Observable<GoogleTokenResult> fun showLoggingIn(authProvider: AuthProvider) fun displayDestination(destination: Destination) } sealed class GoogleTokenResult { data class SuccessfulGoogleTokenResult(val googleToken: GoogleToken) : GoogleTokenResult() data class FailedGoogleTokenResult(val throwable: Throwable) : GoogleTokenResult() } enum class Destination { RETURN, APP, SUPPORT_DEVELOPER } private sealed class State { object WaitingForLoginSelection : State() object AskingForGoogleToken : State() data class LoggingIn(val login: Login) : State() data class ResolvableFailedLogin(val login: Login, val throwable: Throwable) : State() } }
gpl-3.0
e9cb1e57833f72deaee2f17d2e206f62
43.230216
142
0.718074
4.635747
false
false
false
false
androidx/androidx
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/awt/ComposeDialog.desktop.kt
3
5827
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.awt import androidx.compose.runtime.Composable import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.window.DialogWindowScope import org.jetbrains.skiko.GraphicsApi import java.awt.Component import java.awt.Window import java.awt.event.MouseListener import java.awt.event.MouseMotionListener import java.awt.event.MouseWheelListener import javax.swing.JDialog /** * ComposeDialog is a dialog for building UI using Compose for Desktop. * ComposeDialog inherits javax.swing.JDialog. */ class ComposeDialog( owner: Window? = null, modalityType: ModalityType = ModalityType.MODELESS ) : JDialog(owner, modalityType) { private val delegate = ComposeWindowDelegate(this, ::isUndecorated) init { contentPane.add(delegate.pane) } override fun add(component: Component) = delegate.add(component) override fun remove(component: Component) = delegate.remove(component) /** * Composes the given composable into the ComposeDialog. * * @param content Composable content of the ComposeDialog. */ @OptIn(ExperimentalComposeUiApi::class) fun setContent( content: @Composable DialogWindowScope.() -> Unit ) = setContent( onPreviewKeyEvent = { false }, onKeyEvent = { false }, content = content ) /** * Composes the given composable into the ComposeDialog. * * @param onPreviewKeyEvent This callback is invoked when the user interacts with the hardware * keyboard. It gives ancestors of a focused component the chance to intercept a [KeyEvent]. * Return true to stop propagation of this event. If you return false, the key event will be * sent to this [onPreviewKeyEvent]'s child. If none of the children consume the event, * it will be sent back up to the root using the onKeyEvent callback. * @param onKeyEvent This callback is invoked when the user interacts with the hardware * keyboard. While implementing this callback, return true to stop propagation of this event. * If you return false, the key event will be sent to this [onKeyEvent]'s parent. * @param content Composable content of the ComposeWindow. */ @ExperimentalComposeUiApi fun setContent( onPreviewKeyEvent: ((KeyEvent) -> Boolean) = { false }, onKeyEvent: ((KeyEvent) -> Boolean) = { false }, content: @Composable DialogWindowScope.() -> Unit ) { val scope = object : DialogWindowScope { override val window: ComposeDialog get() = this@ComposeDialog } delegate.setContent( onPreviewKeyEvent, onKeyEvent, ) { scope.content() } } override fun dispose() { delegate.dispose() super.dispose() } override fun setUndecorated(value: Boolean) { super.setUndecorated(value) delegate.undecoratedWindowResizer.enabled = isUndecorated && isResizable } override fun setResizable(value: Boolean) { super.setResizable(value) delegate.undecoratedWindowResizer.enabled = isUndecorated && isResizable } /** * `true` if background of the window is transparent, `false` otherwise * Transparency should be set only if window is not showing and `isUndecorated` is set to * `true`, otherwise AWT will throw an exception. */ var isTransparent: Boolean by delegate::isTransparent /** * Registers a task to run when the rendering API changes. */ fun onRenderApiChanged(action: () -> Unit) { delegate.onRenderApiChanged(action) } /** * Retrieve underlying platform-specific operating system handle for the root window where * ComposeDialog is rendered. Currently returns HWND on Windows, Window on X11 and NSWindow * on macOS. */ val windowHandle: Long get() = delegate.windowHandle /** * Returns low-level rendering API used for rendering in this ComposeDialog. API is * automatically selected based on operating system, graphical hardware and `SKIKO_RENDER_API` * environment variable. */ val renderApi: GraphicsApi get() = delegate.renderApi // We need overridden listeners because we mix Swing and AWT components in the // org.jetbrains.skiko.SkiaLayer, they don't work well together. // TODO(demin): is it possible to fix that without overriding? override fun addMouseListener(listener: MouseListener) = delegate.addMouseListener(listener) override fun removeMouseListener(listener: MouseListener) = delegate.removeMouseListener(listener) override fun addMouseMotionListener(listener: MouseMotionListener) = delegate.addMouseMotionListener(listener) override fun removeMouseMotionListener(listener: MouseMotionListener) = delegate.removeMouseMotionListener(listener) override fun addMouseWheelListener(listener: MouseWheelListener) = delegate.addMouseWheelListener(listener) override fun removeMouseWheelListener(listener: MouseWheelListener) = delegate.removeMouseWheelListener(listener) }
apache-2.0
74ecf6d4380754d492041ca47e1732b8
36.352564
98
0.710142
4.768412
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/stories/viewer/StoryVolumeViewModel.kt
1
757
package org.thoughtcrime.securesms.stories.viewer import androidx.lifecycle.ViewModel import io.reactivex.rxjava3.core.Flowable import org.thoughtcrime.securesms.util.rx.RxStore class StoryVolumeViewModel : ViewModel() { private val store = RxStore(StoryVolumeState()) val state: Flowable<StoryVolumeState> = store.stateFlowable val snapshot: StoryVolumeState get() = store.state override fun onCleared() { store.dispose() } fun mute() { store.update { it.copy(isMuted = true) } } fun unmute() { store.update { it.copy(isMuted = false) } } fun onVolumeDown(level: Int) { store.update { it.copy(level = level) } } fun onVolumeUp(level: Int) { store.update { it.copy(isMuted = false, level = level) } } }
gpl-3.0
dfda22a9c80a39734e1dccb944f8e9c2
22.65625
61
0.702774
3.604762
false
false
false
false
androidx/androidx
compose/animation/animation-graphics/src/androidMain/kotlin/androidx/compose/animation/graphics/vector/compat/XmlAnimatedVectorParser.android.kt
3
2837
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.animation.graphics.vector.compat import android.content.res.Resources import android.util.AttributeSet import androidx.compose.animation.graphics.ExperimentalAnimationGraphicsApi import androidx.compose.animation.graphics.res.loadAnimatorResource import androidx.compose.animation.graphics.vector.AnimatedImageVector import androidx.compose.animation.graphics.vector.AnimatedVectorTarget import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.vectorResource import org.xmlpull.v1.XmlPullParser private const val TagAnimatedVector = "animated-vector" private const val TagAnimatedVectorTarget = "target" private fun parseAnimatedVectorTarget( res: Resources, theme: Resources.Theme?, attrs: AttributeSet ): AnimatedVectorTarget { return attrs.attrs( res, theme, AndroidVectorResources.STYLEABLE_ANIMATED_VECTOR_DRAWABLE_TARGET ) { a -> AnimatedVectorTarget( a.getString( AndroidVectorResources.STYLEABLE_ANIMATED_VECTOR_DRAWABLE_TARGET_NAME ) ?: "", loadAnimatorResource( theme, res, a.getResourceId( AndroidVectorResources.STYLEABLE_ANIMATED_VECTOR_DRAWABLE_TARGET_ANIMATION, 0 ) ) ) } } @ExperimentalAnimationGraphicsApi internal fun XmlPullParser.parseAnimatedImageVector( res: Resources, theme: Resources.Theme?, attrs: AttributeSet ): AnimatedImageVector { return attrs.attrs(res, theme, AndroidVectorResources.STYLEABLE_ANIMATED_VECTOR_DRAWABLE) { a -> val drawableId = a.getResourceId( AndroidVectorResources.STYLEABLE_ANIMATED_VECTOR_DRAWABLE_DRAWABLE, 0 ) val targets = mutableListOf<AnimatedVectorTarget>() forEachChildOf(TagAnimatedVector) { if (eventType == XmlPullParser.START_TAG && name == TagAnimatedVectorTarget) { targets.add(parseAnimatedVectorTarget(res, theme, attrs)) } } AnimatedImageVector( ImageVector.vectorResource(theme, res, drawableId), targets ) } }
apache-2.0
2e5d69e919d457a3d270d414b06b17d5
35.371795
100
0.701445
4.689256
false
false
false
false
google/ide-perf
src/main/java/com/google/idea/perf/cvtracer/CachedValueTracerController.kt
1
4880
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.perf.cvtracer import com.google.idea.perf.util.ExecutorWithExceptionLogging import com.google.idea.perf.util.GlobMatcher import com.google.idea.perf.util.formatNsInMs import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager.getApplication import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Disposer import com.intellij.util.text.Matcher import java.util.concurrent.TimeUnit.MILLISECONDS import java.util.concurrent.atomic.AtomicBoolean import kotlin.system.measureNanoTime class CachedValueTracerController( private val view: CachedValueTracerView, parentDisposable: Disposable ) : Disposable { companion object { private val LOG = Logger.getInstance(CachedValueTracerController::class.java) private const val REFRESH_DELAY_MS = 30L } // For simplicity we run all tasks on a single-thread executor. // Most data structures below are assumed to be accessed only from this executor. private val executor = ExecutorWithExceptionLogging("CachedValue Tracer", 1) private val dataRefreshLoopStarted = AtomicBoolean() private var filter: Matcher = GlobMatcher.create("*") private var groupMode = GroupOption.CLASS private val eventConsumer = CachedValueEventConsumer() init { Disposer.register(parentDisposable, this) eventConsumer.install() } override fun dispose() { executor.shutdownNow() eventConsumer.uninstall() } fun startDataRefreshLoop() { check(dataRefreshLoopStarted.compareAndSet(false, true)) val refreshLoop = { updateRefreshTimeUi(measureNanoTime(::updateUi)) } executor.scheduleWithFixedDelay(refreshLoop, 0L, REFRESH_DELAY_MS, MILLISECONDS) } private fun updateUi() { val newStats = getNewStats() getApplication().invokeAndWait { view.listView.setStats(newStats) } } private fun updateRefreshTimeUi(refreshTime: Long) { getApplication().invokeAndWait { val timeText = formatNsInMs(refreshTime) view.refreshTimeLabel.text = "Refresh Time: %9s".format(timeText) } } fun handleRawCommandFromEdt(text: String) { executor.execute { handleCommand(text) } } private fun handleCommand(text: String) { when (val command = parseCachedValueTracerCommand(text)) { is CachedValueTracerCommand.Clear -> { eventConsumer.clear() updateUi() } is CachedValueTracerCommand.Reset -> { eventConsumer.clear() filter = GlobMatcher.create("*") updateUi() } is CachedValueTracerCommand.Filter -> { val pattern = command.pattern if (pattern != null) { filter = GlobMatcher.create("*$pattern*") updateUi() } } is CachedValueTracerCommand.ClearFilters -> { filter = GlobMatcher.create("*") updateUi() } is CachedValueTracerCommand.GroupBy -> { if (command.groupOption != null) { groupMode = command.groupOption updateUi() } } else -> { LOG.warn("Unknown command: $text") } } } private fun getNewStats(): List<MutableCachedValueStats> { return eventConsumer.getSnapshot() .filter { filter.matches(it.location.className) } .groupBy { describeStackFrame(it.location) } .map { (description, stats) -> MutableCachedValueStats( description, computeTimeNs = stats.sumOf { it.computeTimeNs }, hits = stats.sumOf { it.hits }, misses = stats.sumOf { it.computeCount } ) } } private fun describeStackFrame(f: StackTraceElement): String { return when (groupMode) { GroupOption.CLASS -> f.className GroupOption.STACK_TRACE -> "${f.className}#${f.methodName}(${f.lineNumber})" } } }
apache-2.0
863f34aa47c2cb60b1f14df02caf65bf
34.882353
88
0.631967
4.979592
false
false
false
false
Soya93/Extract-Refactoring
plugins/settings-repository/src/RepositoryService.kt
2
2739
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository import com.intellij.openapi.ui.Messages import com.intellij.util.exists import com.intellij.util.io.URLUtil import com.intellij.util.isDirectory import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.transport.URIish import org.jetbrains.settingsRepository.git.createBareRepository import java.awt.Container import java.io.IOException import java.nio.file.Path import java.nio.file.Paths interface RepositoryService { fun checkUrl(uriString: String, messageParent: Container? = null): Boolean { val uri = URIish(uriString) val isFile: Boolean if (uri.scheme == URLUtil.FILE_PROTOCOL) { isFile = true } else { isFile = uri.scheme == null && uri.host == null } if (messageParent != null && isFile && !checkFileRepo(uriString, messageParent)) { return false } return true } fun checkFileRepo(url: String, messageParent: Container): Boolean { val suffix = "/${Constants.DOT_GIT}" val file = Paths.get(if (url.endsWith(suffix)) url.substring(0, url.length - suffix.length) else url) if (file.exists()) { if (!file.isDirectory()) { //noinspection DialogTitleCapitalization Messages.showErrorDialog(messageParent, "Specified path is not a directory", "Specified Path is Invalid") return false } else if (isValidRepository(file)) { return true } } else if (!file.isAbsolute) { Messages.showErrorDialog(messageParent, icsMessage("specify.absolute.path.dialog.message"), "") return false } if (Messages.showYesNoDialog(messageParent, icsMessage("init.dialog.message"), icsMessage("init.dialog.title"), Messages.getQuestionIcon()) == Messages.YES) { try { createBareRepository(file) return true } catch (e: IOException) { Messages.showErrorDialog(messageParent, icsMessage("init.failed.message", e.message), icsMessage("init.failed.title")) return false } } else { return false } } // must be protected, kotlin bug fun isValidRepository(file: Path): Boolean }
apache-2.0
b86f5792f88e14bccacaad395a805463
32.414634
162
0.69989
4.20092
false
false
false
false
jean79/yested
src/main/kotlin/net/yested/ext/sweetalert/sweetalert.kt
2
2474
package net.yested.ext.sweetalert data class SwalOptions( /** * The title of the modal. It can either be added to the object under the key "title" or passed as the first parameter of the function. */ val title:String, /** * A description for the modal. It can either be added to the object under the key "text" or passed as the second parameter of the function. */ val text:String? = null, /** * The type of the modal. SweetAlert comes with 4 built-in types which will show a corresponding icon animation: "warning", "error", "success" and "info". It can either be put in the array under the key "type" or passed as the third parameter of the function. */ val type:String? = null, /** * If set to true, the user can dismiss the modal by clicking outside it. */ val allowOutsideClick:Boolean = false, /** * Use this to change the text on the "Confirm"-button. If showCancelButton is set as true, the confirm button will automatically show "Confirm" instead of "OK". */ val showCancelButton:Boolean = false, /** * Use this to change the background color of the "Confirm"-button (must be a HEX value). */ val confirmButtonText:String = "OK", /** * */ val confirmButtonColor:String = "#AEDEF4", /** * Use this to change the text on the "Cancel"-button. */ val cancelButtonText:String = "Cancel", /** * Set to false if you want the modal to stay open even if the user presses the "Confirm"-button. This is especially useful if the function attached to the "Confirm"-button is another SweetAlert. */ val closeOnConfirm:Boolean = true, val closeOnCancel:Boolean = true, /** * Add a customized icon for the modal. Should contain a string with the path to the image. */ val imageUrl:String? = null, /** * If imageUrl is set, you can specify imageSize to describes how big you want the icon to be in px. Pass in a string with two values separated by an "x". The first value is the width, the second is the height. */ val imageSize:String? = "80x80", val timer: Number? = null ) external fun swal(option:SwalOptions, handler:Function1<Boolean?, Unit>? = definedExternally):Unit
mit
7de7fca8a48fd793fc7fd99e081dd647
37.061538
267
0.615198
4.457658
false
false
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/lang/core/psi/elements/ElmLetInExpr.kt
1
1419
package org.elm.lang.core.psi.elements import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.PsiErrorElement import com.intellij.psi.util.PsiTreeUtil import org.elm.lang.core.psi.* /** * A let-in expression * * For example: * ``` * let * x = 320 * y = 480 * in * x + y * ``` */ class ElmLetInExpr(node: ASTNode) : ElmPsiElementImpl(node), ElmAtomTag { /** * The local declaration bindings. * * In a well-formed program, there will be at least one element. */ val valueDeclarationList: List<ElmValueDeclaration> get() = PsiTreeUtil.getChildrenOfTypeAsList(this, ElmValueDeclaration::class.java) /** * The body expression. * * In a well-formed program, this will be non-null */ val expression: ElmExpressionTag? get() = findChildByClass(ElmExpressionTag::class.java) /** The `let` element. In a well formed program, this will not return null */ val letKeyword: PsiElement get() = findNotNullChildByType(ElmTypes.LET) /** The `in` element. In a well formed program, this will not return null */ val inKeyword: PsiElement? get() = findChildByType(ElmTypes.IN) ?: // If there's no valueDeclarationList, the in keyword is enclosed in an error element (lastChild as? PsiErrorElement)?.firstChild?.takeIf { it.elementType == ElmTypes.IN } }
mit
d334c55566804f9153c62d22f154a87c
29.191489
93
0.668781
3.930748
false
false
false
false
google/android-auto-companion-android
trustagent/src/com/google/android/libraries/car/trustagent/blemessagestream/SppManager.kt
1
6068
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.car.trustagent.blemessagestream import android.annotation.SuppressLint import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothSocket import android.content.Context import androidx.annotation.VisibleForTesting import androidx.core.content.ContextCompat import com.google.android.libraries.car.trustagent.util.loge import com.google.android.libraries.car.trustagent.util.logi import java.io.ByteArrayOutputStream import java.io.IOException import java.nio.ByteBuffer import java.nio.ByteOrder import java.util.UUID import java.util.concurrent.Executor import java.util.concurrent.Executors /** * Handles reading and receiving data from an Spp connection. Will start new thread to handle * [ConnectTask] and [ReadMessageTask]. * * @property serviceUuid Service record UUID of the RFCOMM socket. */ class SppManager( context: Context, override val bluetoothDevice: BluetoothDevice, private val serviceUuid: UUID ) : BluetoothConnectionManager() { internal var connectTask: ConnectTask? = null @VisibleForTesting internal var writeExecutor: Executor = Executors.newSingleThreadExecutor() @VisibleForTesting internal var readMessageTask: ReadMessageTask? = null private val connectionExecutor = Executors.newSingleThreadExecutor() private val taskCallbackExecutor = ContextCompat.getMainExecutor(context) private var connectedSocket: BluetoothSocket? = null @SuppressLint("MissingPermission") override var deviceName = bluetoothDevice.name private set @VisibleForTesting internal val connectTaskCallback = object : ConnectTask.Callback { override fun onConnectionSuccess(socket: BluetoothSocket) { logi(TAG, "Connected, remote device is ${bluetoothDevice.address}") connectedSocket = socket readMessageTask?.cancel() // Start the task to manage the connection and perform transmissions readMessageTask = ReadMessageTask(socket.inputStream, readMessageTaskCallback, taskCallbackExecutor) connectionExecutor.execute(readMessageTask) connectionCallbacks.forEach { it.onConnected() } } override fun onConnectionAttemptFailed() { connectionCallbacks.forEach { it.onConnectionFailed() } } } @VisibleForTesting internal val readMessageTaskCallback = object : ReadMessageTask.Callback { override fun onMessageReceived(message: ByteArray) { messageCallbacks.forEach { it.onMessageReceived(message) } } override fun onMessageReadError() { disconnect() } } override val maxWriteSize: Int = MAX_WRITE_SIZE /** Start the [ConnectTask] to initiate a connection to a remote device. */ override fun connect() { // TODO(b/162537040): add retry logic for SPP logi(TAG, "Attempt connect to remote device.") // Cancel any thread attempting to make a connection connectTask?.cancel() // Start the task to connect with the given device connectTask = ConnectTask(bluetoothDevice, true, serviceUuid, connectTaskCallback, taskCallbackExecutor) connectionExecutor.execute(connectTask) } override fun disconnect() { // Cancel the task that attempts to establish the connection connectTask?.cancel() connectTask = null // Cancel any task currently running a connection readMessageTask?.cancel() readMessageTask = null connectedSocket?.close() connectionCallbacks.forEach { it.onDisconnected() } } /** * Sends [message] to a connected device. * * The delivery of data is notified through [MessageCallback.onMessageSent]. This method should * not be invoked again before the callback; otherwise the behavior is undefined. * * @return `true` if the request to send data was initiated successfully; `false` otherwise. */ override fun sendMessage(message: ByteArray): Boolean { val dataReadyToSend = wrapWithArrayLength(message) if (connectedSocket == null) { loge(TAG, "Attempted to send data when device is disconnected. Ignoring.") return false } writeExecutor.execute { try { connectedSocket?.outputStream?.let { it.write(dataReadyToSend) logi(TAG, "Sent message to remote device with length: " + dataReadyToSend.size) messageCallbacks.forEach { it.onMessageSent(message) } } } catch (e: IOException) { loge(TAG, "Exception during write", e) disconnect() } } return true } companion object { const val LENGTH_BYTES_SIZE = 4 private const val TAG = "SppManager" // TODO(b/166538373): Currently its an arbitrary number, should update after getting more // testing data. private const val MAX_WRITE_SIZE = 700 /** * Wrap the raw byte array with array length. * * Should be called every time when server wants to send a message to client. * * @param rawData Original data * @return The wrapped data * @throws IOException If there are some errors writing data */ @VisibleForTesting internal fun wrapWithArrayLength(rawData: ByteArray): ByteArray { val length = rawData.size val lengthBytes = ByteBuffer.allocate(LENGTH_BYTES_SIZE).order(ByteOrder.LITTLE_ENDIAN).putInt(length).array() val outputStream = ByteArrayOutputStream() outputStream.write(lengthBytes + rawData) return outputStream.toByteArray() } } }
apache-2.0
330e140c2b6a8d15d9231e6b3dc57f04
34.27907
100
0.726269
4.755486
false
false
false
false
arkon/LISTEN.moe-Unofficial-Android-App
app/src/main/java/me/echeung/moemoekyun/ui/fragment/UserFragment.kt
1
4157
package me.echeung.moemoekyun.ui.fragment import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import me.echeung.moemoekyun.R import me.echeung.moemoekyun.adapter.SongsListAdapter import me.echeung.moemoekyun.client.RadioClient import me.echeung.moemoekyun.client.api.library.Library import me.echeung.moemoekyun.client.auth.AuthUtil import me.echeung.moemoekyun.databinding.FragmentUserBinding import me.echeung.moemoekyun.ui.activity.auth.AuthActivityUtil import me.echeung.moemoekyun.ui.base.SongsListBaseFragment import me.echeung.moemoekyun.ui.view.SongList import me.echeung.moemoekyun.util.SongActionsUtil import me.echeung.moemoekyun.util.SongSortUtil import me.echeung.moemoekyun.util.ext.launchIO import me.echeung.moemoekyun.util.ext.launchUI import me.echeung.moemoekyun.util.ext.popupMenu import me.echeung.moemoekyun.viewmodel.RadioViewModel import me.echeung.moemoekyun.viewmodel.UserViewModel import org.koin.android.ext.android.inject class UserFragment : SongsListBaseFragment<FragmentUserBinding>() { private val radioClient: RadioClient by inject() private val authUtil: AuthUtil by inject() private val songSortUtil: SongSortUtil by inject() private val radioViewModel: RadioViewModel by inject() private val userViewModel: UserViewModel by inject() init { layout = R.layout.fragment_user broadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { when (intent.action) { AuthActivityUtil.AUTH_EVENT, SongActionsUtil.FAVORITE_EVENT -> initUserContent() } } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = super.onCreateView(inflater, container, savedInstanceState) binding.radioVm = radioViewModel binding.userVm = userViewModel binding.songListVm = songListVm initUserContent() return view } override fun onPause() { super.onPause() binding.query.clearFocus() } override fun initSongList(binding: FragmentUserBinding): SongList { initFilterMenu() return SongList( requireActivity(), songListVm, binding.favoritesList.list, binding.favoritesList.refreshLayout, binding.query, LIST_ID, this::loadSongs ) } private fun initFilterMenu() { binding.overflowBtn.setOnClickListener { view -> view.popupMenu( R.menu.menu_sort, { songSortUtil.initSortMenu(LIST_ID, this) }, songList::handleMenuItemClick ) } } private fun loadSongs(adapter: SongsListAdapter) { launchIO { try { val favorites = radioClient.api.getUserFavorites() launchUI { songList.showLoading(false) adapter.songs = favorites userViewModel.hasFavorites = favorites.isNotEmpty() } } catch (e: Exception) { launchUI { songList.showLoading(false) } } } } private fun initUserContent() { songList.showLoading(true) if (authUtil.isAuthenticated) { getUserInfo() songList.loadSongs() } } private fun getUserInfo() { launchIO { val user = radioClient.api.getUserInfo() userViewModel.user = user user.avatarImage?.let { userViewModel.avatarUrl = Library.CDN_AVATAR_URL + it } user.bannerImage?.let { userViewModel.bannerUrl = Library.CDN_BANNER_URL + it } } } companion object { private const val LIST_ID = "FAVORITES_LIST" } }
mit
681c4ae03846e266ff7b6394f53e6615
29.566176
116
0.645177
4.833721
false
false
false
false
bastman/kotlin-spring-jpa-examples
src/main/kotlin/com/example/demo/api/realestate/handler/properties/crud/search/request.kt
1
6176
package com.example.demo.api.realestate.handler.properties.crud.search import com.example.demo.api.realestate.domain.jpa.entities.PropertyType import com.example.demo.api.realestate.domain.jpa.entities.QueryDslEntity.qProperty import com.example.demo.api.realestate.handler.common.request.QueryDslRequestParser import com.fasterxml.jackson.annotation.JsonValue import com.querydsl.core.types.OrderSpecifier import com.querydsl.core.types.dsl.BooleanExpression import io.swagger.annotations.ApiModel import java.time.Instant import java.util.* import javax.validation.constraints.Max import javax.validation.constraints.Min import com.example.demo.api.realestate.handler.common.request.QueryDslOperation as Op typealias Filters = List<FieldAndValues> typealias Sorting = List<SortField> private object FieldNames { const val id = "id" const val createdAt = "createdAt" const val modifiedAt = "modifiedAt" const val name = "name" const val type = "type" const val address_country = "address.country" const val address_city = "address.city" const val address_zip = "address.zip" const val address_street = "address.street" const val address_number = "address.street" const val address_district = "address.number" const val address_neighborhood = "address.neighborhood" } data class SearchPropertiesRequest( @get:[Min(0)] val offset: Long = 0, @get:[Min(1) Max(100)] val limit: Long = 100, val filter: Filters? = null, val search: Filters? = null, val orderBy: Sorting? = null ) @ApiModel("SearchPropertiesRequest.FieldAndValues") data class FieldAndValues(val field: FilterField, val values: List<String>) @ApiModel("SearchPropertiesRequest.SortableField") enum class SortField( fieldName: String, fieldOperation: String, val orderSpecifierSupplier: () -> OrderSpecifier<*> ) { modifiedAt_asc(FieldNames.modifiedAt, Op.ASC, { qProperty.modified.asc() }), modifiedAt_desc(FieldNames.modifiedAt, Op.DESC, { qProperty.modified.desc() }), createdAt_asc(FieldNames.createdAt, Op.ASC, { qProperty.created.asc() }), createdAt_desc(FieldNames.createdAt, Op.DESC, { qProperty.created.desc() }), name_asc(FieldNames.name, Op.ASC, { qProperty.name.asc() }), name_desc(FieldNames.name, Op.DESC, { qProperty.name.desc() }), type_asc(FieldNames.type, Op.ASC, { qProperty.type.asc() }), type_desc(FieldNames.type, Op.DESC, { qProperty.type.desc() }), ; @get:JsonValue val fieldExpression: String = "$fieldName-$fieldOperation" override fun toString(): String { return fieldExpression } fun toOrderSpecifier(): OrderSpecifier<*> { return orderSpecifierSupplier() } } @ApiModel("SearchPropertiesRequest.FilterField") enum class FilterField( fieldName: String, fieldOperation: String, val predicateSupplier: (FilterField, String) -> BooleanExpression ) { modifiedAt_goe(FieldNames.modifiedAt, Op.GOE, { field, value: String -> qProperty.modified.goe(value.toInstant(field)) }), modifiedAt_loe(FieldNames.modifiedAt, Op.GOE, { field, value: String -> qProperty.modified.loe(value.toInstant(field)) }), createdAt_goe(FieldNames.createdAt, Op.GOE, { field, value: String -> qProperty.created.goe(value.toInstant(field)) }), createdAt_loe(FieldNames.createdAt, Op.GOE, { field, value: String -> qProperty.created.loe(value.toInstant(field)) }), name_like(FieldNames.name, Op.LIKE, { _, value: String -> qProperty.name.likeIgnoreCase(value) }), id_eq(FieldNames.id, Op.LIKE, { field, value: String -> qProperty.id.eq(value.toUUID(field)) }), type_eq(FieldNames.type, Op.LIKE, { field, value: String -> qProperty.type.eq(value.toPropertyType(field)) }), address_country_like(FieldNames.address_country, Op.LIKE, { _, value: String -> qProperty.address.country.likeIgnoreCase(value) }), address_city_like(FieldNames.address_city, Op.LIKE, { _, value: String -> qProperty.address.city.likeIgnoreCase(value) }), address_zip_like(FieldNames.address_zip, Op.LIKE, { _, value: String -> qProperty.address.zip.likeIgnoreCase(value) }), address_street_like(FieldNames.address_street, Op.LIKE, { _, value: String -> qProperty.address.street.likeIgnoreCase(value) }), address_number_like(FieldNames.address_number, Op.LIKE, { _, value: String -> qProperty.address.number.likeIgnoreCase(value) }), address_district_like(FieldNames.address_district, Op.LIKE, { _, value: String -> qProperty.address.district.likeIgnoreCase(value) }), address_neighborhood_like(FieldNames.address_neighborhood, Op.LIKE, { _, value: String -> qProperty.address.neighborhood.likeIgnoreCase(value) }), ; @get:JsonValue val fieldExpression: String = "$fieldName-$fieldOperation" override fun toString(): String = fieldExpression fun toBooleanExpression(values: List<String>): List<BooleanExpression> { return values.map { value -> predicateSupplier(this, value) }.toList() } } fun Filters?.toWhereExpressionDsl(): List<BooleanExpression> { return this?.flatMap { it.field.toBooleanExpression(it.values) } ?: emptyList() } fun Sorting?.toOrderByExpressionDsl(): List<OrderSpecifier<*>> { return this?.map { it.toOrderSpecifier() } ?: emptyList() } private fun String.toInstant(field: FilterField): Instant { return QueryDslRequestParser.asInstant( fieldValue = this, fieldExpression = field.fieldExpression ) } private fun String.toUUID(field: FilterField): UUID { return QueryDslRequestParser.asUUID( fieldValue = this, fieldExpression = field.fieldExpression ) } private fun String.toPropertyType(field: FilterField): PropertyType { return QueryDslRequestParser.asPropertyType( fieldValue = this, fieldExpression = field.fieldExpression ) }
mit
3681625de6d09b7f8f5e6a34addd4067
32.032086
85
0.687662
3.969152
false
false
false
false
mike-neck/kuickcheck
core/src/main/kotlin/org/mikeneck/kuickcheck/generator/StringGenerator.kt
1
4887
/* * Copyright 2016 Shinya Mochida * * Licensed under the Apache License,Version2.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.mikeneck.kuickcheck.generator import org.mikeneck.kuickcheck.Generator import org.mikeneck.kuickcheck.generator.internal.* internal class StringGenerator(chars: String, length: Int = 50) : Generator<String> { val size: SizeGenerator val string: Generator<SizedWrapper<String>> init { size = intSizeGenerator(length) string = if (chars.isEmpty()) throw IllegalArgumentException("Generator cannot generate string with initial empty string.") else RandomString(chars) } override fun invoke(): String { return upto(size) { string.invoke() }.joinToString("") } } private fun intSizeGenerator(length: Int) = if (length <= 0) throw IllegalArgumentException("Length should be larger than 0.[input: $length]") else if (1 < length) IntGenerator(2, length) else Size1SizeGenerator() private fun <T : SizedWrapper<U>, U> upto(size: SizeGenerator, f: () -> T): List<T> { val s = size.invoke() val l = mutableListOf<T>() var c = 0 while (c < s) { if (c + 1 == s) { while (true) { val g = f.invoke() if (g.size == 1) { l.add(g) return l.toList() } } } val g = f.invoke() c += g.size l.add(g) } return l.toList() } internal class RandomString(chars: String) : Generator<SizedWrapper<String>> { val entry: List<IntWrapper> val indices: Generator<Int> init { val set: MutableSet<IntWrapper> = mutableSetOf() var i: Int = 0 while (i < chars.length) { val c = chars[i] if (Character.isSurrogate(c)) { i++ val l = chars[i] if (Character.isSurrogatePair(c, l) == false) continue val cp = Character.toCodePoint(c, l) set.add(IntWrapper(cp, 2)) } else { set.add(IntWrapper(c.toInt(), 1)) } i++ } entry = set.toList() indices = if (entry.size == 1) Size1SizeGenerator() else IntGenerator(1, entry.size) } override fun invoke(): SizedWrapper<String> { val codePoint = entry[indices.invoke() - 1] return codePoint.string() } } internal class AllStringGenerator(length: Int = 50) : Generator<String> { val size: SizeGenerator = if (length <= 0) throw IllegalArgumentException("Length should be larger than 0.[input: $length]") else if (length == 1) Size1SizeGenerator() else IntGenerator(1, length) override fun invoke(): String { return upto(size) { OneSizedAllString.invoke() }.joinToString("") } } fun Char.intGeneratorTo(endInclusive: Char): Generator<Int> = IntGenerator(this.toInt(), endInclusive.toInt()) internal object OneSizedAllString : Generator<SizedWrapper<String>> { val allChars: Generator<Int> = IntGenerator(0, Character.MAX_VALUE.toInt()) val highSurrogates: Generator<Int> = Char.MIN_HIGH_SURROGATE.intGeneratorTo(Char.MAX_HIGH_SURROGATE) val lowSurrogates: Generator<Int> = Char.MIN_LOW_SURROGATE.intGeneratorTo(Char.MAX_LOW_SURROGATE) override fun invoke(): SizedWrapper<String> { val c = allChars.invoke().toChar() return if (Character.isSurrogate(c)) createSurrogateString(c) else NormalString(c.toString()) } fun createSurrogateString(c: Char): SizedWrapper<String> { return if (Character.isHighSurrogate(c)) stringWithHighSurrogate(c) else stringWithLowSurrogate(c) } fun stringWithHighSurrogate(high: Char): SurrogateString { while (true) { val l = lowSurrogates.invoke().toChar() if (Character.isSurrogatePair(high, l)) { val cp = Character.toCodePoint(high, l) return SurrogateString(String(Character.toChars(cp))) } } } fun stringWithLowSurrogate(low: Char): SurrogateString { while (true) { val h = highSurrogates.invoke().toChar() if (Character.isSurrogatePair(h, low)) { val cp = Character.toCodePoint(h, low) return SurrogateString(String(Character.toChars(cp))) } } } }
apache-2.0
1049e6670dfa37c702b489077d8b6bb7
32.244898
142
0.619398
4.035508
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/lang/UpdateFacilitySpec.kt
1
2120
/* * Copyright (C) 2021 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.xquery.lang import com.intellij.navigation.ItemPresentation import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSpecificationType import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSpecificationVersion import uk.co.reecedunn.intellij.plugin.xpm.lang.impl.W3CSpecification import uk.co.reecedunn.intellij.plugin.xpm.resources.XpmIcons import javax.swing.Icon @Suppress("MemberVisibilityCanBePrivate") object UpdateFacilitySpec : ItemPresentation, XpmSpecificationType { // region ItemPresentation override fun getPresentableText(): String = "XQuery Update Facility" override fun getLocationString(): String? = null override fun getIcon(unused: Boolean): Icon = XpmIcons.W3.Product // endregion // region XpmSpecificationType override val id: String = "xquery-update" override val presentation: ItemPresentation get() = this // endregion // region Versions val REC_1_0_20110317: XpmSpecificationVersion = W3CSpecification( this, "1.0-20110317", "1.0", "https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/" ) val NOTE_3_0_20170124: XpmSpecificationVersion = W3CSpecification( this, "3.0-20170124", "3.0 (Working Group Note 24 January 2017)", "https://www.w3.org/TR/2017/NOTE-xquery-update-30-20170124/" ) val versions: List<XpmSpecificationVersion> = listOf( REC_1_0_20110317, NOTE_3_0_20170124 ) // endregion }
apache-2.0
98627d07b5ec4b12a71a77f90661bae4
31.121212
75
0.717925
4.02277
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/course_list/notification/RemindAppNotificationDelegate.kt
1
5635
package org.stepik.android.view.course_list.notification import android.app.PendingIntent import android.content.Context import android.content.Intent import androidx.core.app.TaskStackBuilder import org.stepic.droid.R import org.stepic.droid.analytic.Analytic import org.stepic.droid.core.ScreenManager import org.stepic.droid.notifications.NotificationBroadcastReceiver import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepic.droid.ui.activities.MainFeedActivity import org.stepic.droid.util.AppConstants import org.stepic.droid.util.DateTimeHelper import org.stepik.android.domain.course_list.interactor.RemindAppNotificationInteractor import org.stepik.android.view.notification.NotificationDelegate import org.stepik.android.view.notification.StepikNotificationManager import org.stepik.android.view.notification.helpers.NotificationHelper import java.util.Calendar import javax.inject.Inject class RemindAppNotificationDelegate @Inject constructor( private val context: Context, private val remindAppNotificationInteractor: RemindAppNotificationInteractor, private val sharedPreferenceHelper: SharedPreferenceHelper, private val analytic: Analytic, private val screenManager: ScreenManager, private val notificationHelper: NotificationHelper, stepikNotificationManager: StepikNotificationManager ) : NotificationDelegate("show_new_user_notification", stepikNotificationManager) { companion object { private const val NEW_USER_REMIND_NOTIFICATION_ID = 4L } override fun onNeedShowNotification() { if (remindAppNotificationInteractor.hasUserInteractedWithApp()) { analytic.reportEvent(Analytic.Notification.REMIND_HIDDEN) return } val dayType = if (!sharedPreferenceHelper.isNotificationWasShown(SharedPreferenceHelper.NotificationDay.DAY_ONE)) { SharedPreferenceHelper.NotificationDay.DAY_ONE } else if (!sharedPreferenceHelper.isNotificationWasShown(SharedPreferenceHelper.NotificationDay.DAY_SEVEN)) { SharedPreferenceHelper.NotificationDay.DAY_SEVEN } else { null } val deleteIntent = Intent(context, NotificationBroadcastReceiver::class.java) deleteIntent.action = AppConstants.NOTIFICATION_CANCELED_REMINDER val deletePendingIntent = PendingIntent.getBroadcast(context, 0, deleteIntent, PendingIntent.FLAG_CANCEL_CURRENT) // now we can show notification val intent = screenManager.getCatalogIntent(context) intent.action = AppConstants.OPEN_NOTIFICATION_FOR_ENROLL_REMINDER val analyticDayTypeName = dayType?.name ?: "" intent.putExtra(MainFeedActivity.reminderKey, analyticDayTypeName) val taskBuilder: TaskStackBuilder = TaskStackBuilder .create(context) .addNextIntent(intent) val title = context.resources.getString(R.string.stepik_free_courses_title) val remindMessage = context.resources.getString(R.string.local_remind_message) val notification = notificationHelper.makeSimpleNotificationBuilder(stepikNotification = null, justText = remindMessage, taskBuilder = taskBuilder, title = title, deleteIntent = deletePendingIntent, id = NEW_USER_REMIND_NOTIFICATION_ID ) showNotification(NEW_USER_REMIND_NOTIFICATION_ID, notification.build()) if (!sharedPreferenceHelper.isNotificationWasShown(SharedPreferenceHelper.NotificationDay.DAY_ONE)) { afterLocalNotificationShown(SharedPreferenceHelper.NotificationDay.DAY_ONE) } else if (!sharedPreferenceHelper.isNotificationWasShown(SharedPreferenceHelper.NotificationDay.DAY_SEVEN)) { afterLocalNotificationShown(SharedPreferenceHelper.NotificationDay.DAY_SEVEN) } scheduleRemindAppNotification() } fun scheduleRemindAppNotification() { val isFirstDayNotificationShown = sharedPreferenceHelper.isNotificationWasShown(SharedPreferenceHelper.NotificationDay.DAY_ONE) val isSevenDayNotificationShown = sharedPreferenceHelper.isNotificationWasShown(SharedPreferenceHelper.NotificationDay.DAY_SEVEN) if (remindAppNotificationInteractor.isNotificationShown()) { // already shown. // do not show again return } if (remindAppNotificationInteractor.hasUserInteractedWithApp()) { return } // now we can plan alarm val now = DateTimeHelper.nowUtc() val scheduleMillis: Long val dayDiff: Int = when { !isFirstDayNotificationShown -> 1 !isSevenDayNotificationShown -> 7 else -> return } val calendar = Calendar.getInstance() val nowHour = calendar.get(Calendar.HOUR_OF_DAY) calendar.set(Calendar.HOUR_OF_DAY, 12) val nowAt12 = calendar.timeInMillis scheduleMillis = when { nowHour < 12 -> nowAt12 + AppConstants.MILLIS_IN_24HOURS * dayDiff nowHour >= 19 -> nowAt12 + AppConstants.MILLIS_IN_24HOURS * (dayDiff + 1) else -> now + AppConstants.MILLIS_IN_24HOURS * dayDiff } sharedPreferenceHelper.saveNewUserRemindTimestamp(scheduleMillis) scheduleNotificationAt(scheduleMillis) } private fun afterLocalNotificationShown(day: SharedPreferenceHelper.NotificationDay) { analytic.reportEvent(Analytic.Notification.REMIND_SHOWN, day.name) sharedPreferenceHelper.setNotificationShown(day) } }
apache-2.0
a1f2012f3d9123cb1f8954833311d125
44.821138
137
0.730257
5.212766
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/elvis/kt6694ExactAnnotationForElvis.kt
5
726
interface PsiElement { fun <T: PsiElement> findChildByType(i: Int): T? = if (i == 42) JetOperationReferenceExpression() as T else throw Exception() } interface JetSimpleNameExpression : PsiElement { fun getReferencedNameElement(): PsiElement } class JetOperationReferenceExpression : JetSimpleNameExpression { override fun getReferencedNameElement() = this } class JetLabelReferenceExpression : JetSimpleNameExpression { public override fun getReferencedNameElement(): PsiElement = findChildByType(42) ?: this } fun box(): String { val element = JetLabelReferenceExpression().getReferencedNameElement() return if (element is JetOperationReferenceExpression) "OK" else "fail" }
apache-2.0
d391d4151a746fc86904f080d49f6c12
37.210526
86
0.750689
5.26087
false
false
false
false
robovm/robovm-studio
platform/platform-tests/testSrc/com/intellij/options/MockStreamProvider.kt
4
1412
package com.intellij.options import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.impl.stores.StreamProvider import com.intellij.openapi.util.io.FileUtil import com.intellij.util.SmartList import java.io.File import java.io.FileInputStream import java.io.InputStream class MockStreamProvider(private val myBaseDir: File) : StreamProvider { override fun isApplicable(fileSpec: String, roamingType: RoamingType) = roamingType === RoamingType.PER_USER override fun saveContent(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) { FileUtil.writeToFile(File(myBaseDir, fileSpec), content, 0, size) } override fun loadContent(fileSpec: String, roamingType: RoamingType): InputStream? { val file = File(myBaseDir, fileSpec) //noinspection IOResourceOpenedButNotSafelyClosed return if (file.exists()) FileInputStream(file) else null } override fun listSubFiles(fileSpec: String, roamingType: RoamingType): Collection<String> { if (roamingType !== RoamingType.PER_USER) { return emptyList() } val files = File(myBaseDir, fileSpec).listFiles() ?: return emptyList() val names = SmartList<String>() for (file in files) { names.add(file.getName()) } return names } override fun delete(fileSpec: String, roamingType: RoamingType) { FileUtil.delete(File(myBaseDir, fileSpec)) } }
apache-2.0
8ca338ba91d0524dd80283b56150c0d0
34.3
110
0.750708
4.358025
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/ComposeController.kt
1
2145
package eu.kanade.tachiyomi.ui.base.controller import android.os.Bundle import android.view.LayoutInflater import android.view.View import androidx.activity.OnBackPressedDispatcherOwner import androidx.compose.runtime.Composable import eu.kanade.tachiyomi.databinding.ComposeControllerBinding import eu.kanade.tachiyomi.util.view.setComposeContent import nucleus.presenter.Presenter abstract class FullComposeController<P : Presenter<*>>(bundle: Bundle? = null) : NucleusController<ComposeControllerBinding, P>(bundle), ComposeContentController { override fun createBinding(inflater: LayoutInflater) = ComposeControllerBinding.inflate(inflater) override fun onViewCreated(view: View) { super.onViewCreated(view) binding.root.apply { setComposeContent { ComposeContent() } } } override fun handleBack(): Boolean { val dispatcher = (activity as? OnBackPressedDispatcherOwner)?.onBackPressedDispatcher ?: return false return if (dispatcher.hasEnabledCallbacks()) { dispatcher.onBackPressed() true } else { false } } } /** * Basic Compose controller without a presenter. */ abstract class BasicFullComposeController(bundle: Bundle? = null) : BaseController<ComposeControllerBinding>(bundle), ComposeContentController { override fun createBinding(inflater: LayoutInflater) = ComposeControllerBinding.inflate(inflater) override fun onViewCreated(view: View) { super.onViewCreated(view) binding.root.apply { setComposeContent { ComposeContent() } } } // Let Compose view handle this override fun handleBack(): Boolean { val dispatcher = (activity as? OnBackPressedDispatcherOwner)?.onBackPressedDispatcher ?: return false return if (dispatcher.hasEnabledCallbacks()) { dispatcher.onBackPressed() true } else { false } } } interface ComposeContentController { @Composable fun ComposeContent() }
apache-2.0
84ccb4556de3250aa6211d53ff06fd78
27.986486
109
0.680653
5.244499
false
false
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/services/AlarmSoundServiceHelper.kt
1
3331
package info.nightscout.androidaps.services import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.IBinder import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.interfaces.NotificationHolder import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import javax.inject.Inject import javax.inject.Singleton /* This code replaces following val alarm = Intent(context, AlarmSoundService::class.java) alarm.putExtra("soundId", n.soundId) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(alarm) else context.startService(alarm) it fails randomly with error Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{e317f7e u0 info.nightscout.nsclient/info.nightscout.androidaps.services.AlarmSoundService} */ @Singleton class AlarmSoundServiceHelper @Inject constructor( private val aapsLogger: AAPSLogger, private val notificationHolder: NotificationHolder ) { fun startAlarm(context: Context, sound: Int, reason: String) { aapsLogger.debug(LTag.CORE, "Starting alarm from $reason") val connection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName?, service: IBinder?) { // The binder of the service that returns the instance that is created. val binder: AlarmSoundService.LocalBinder = service as AlarmSoundService.LocalBinder val alarmSoundService: AlarmSoundService = binder.getService() context.startForegroundService(getServiceIntent(context, sound)) // This is the key: Without waiting Android Framework to call this method // inside Service.onCreate(), immediately call here to post the notification. alarmSoundService.startForeground(notificationHolder.notificationID, notificationHolder.notification) // Release the connection to prevent leaks. context.unbindService(this) } override fun onServiceDisconnected(name: ComponentName?) { } } try { context.bindService(getServiceIntent(context, sound), connection, Context.BIND_AUTO_CREATE) } catch (ignored: RuntimeException) { // This is probably a broadcast receiver context even though we are calling getApplicationContext(). // Just call startForegroundService instead since we cannot bind a service to a // broadcast receiver context. The service also have to call startForeground in // this case. context.startForegroundService(getServiceIntent(context, sound)) } } fun stopService(context: Context, reason: String) { aapsLogger.debug(LTag.CORE, "Stopping alarm from $reason") val alarm = Intent(context, AlarmSoundService::class.java) context.stopService(alarm) } private fun getServiceIntent(context: Context, sound: Int): Intent { val alarm = Intent(context, AlarmSoundService::class.java) alarm.putExtra(ErrorHelperActivity.SOUND_ID, sound) return alarm } }
agpl-3.0
ce2bfd03a0bd708fe180a79e555a81ee
42.842105
186
0.716902
5.132512
false
false
false
false
ThoseGrapefruits/intellij-rust
src/main/kotlin/org/rust/lang/inspections/ApproxConstantInspection.kt
1
2965
package org.rust.lang.inspections import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import org.rust.lang.core.psi.RustLitExpr import org.rust.lang.core.psi.RustVisitor class ApproxConstantInspection : LocalInspectionTool() { override fun getGroupDisplayName() = "Rust" override fun getDisplayName() = "Approximate Constants" override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return object : RustVisitor() { override fun visitLitExpr(o: RustLitExpr) { analyzeLiteral(o.floatLiteral ?: return, holder) } } } private fun analyzeLiteral(psiElement: PsiElement, holder: ProblemsHolder) { val text = psiElement.text .filter { it != '_' } .removeSuffix("f32") .removeSuffix("f64") // Parse the float literal and skip inspection on failure val value = try { text.toDouble() } catch (e: NumberFormatException) { return } val constant = KNOWN_CONSTS.find { it.matches(value) } ?: return val type = if (psiElement.text.endsWith("f32")) "f32" else "f64" holder.registerProblem(psiElement, type, constant) } companion object { val KNOWN_CONSTS = listOf( PredefinedConstant("E", Math.E, 4), PredefinedConstant("FRAC_1_PI", 1.0 / Math.PI, 4), PredefinedConstant("FRAC_1_SQRT_2", 1.0 / Math.sqrt(2.0), 5), PredefinedConstant("FRAC_2_PI", 2.0 / Math.PI, 5), PredefinedConstant("FRAC_2_SQRT_PI", 2.0 / Math.sqrt(Math.PI), 5), PredefinedConstant("FRAC_PI_2", Math.PI / 2.0, 5), PredefinedConstant("FRAC_PI_3", Math.PI / 3.0, 5), PredefinedConstant("FRAC_PI_4", Math.PI / 4.0, 5), PredefinedConstant("FRAC_PI_6", Math.PI / 6.0, 5), PredefinedConstant("FRAC_PI_8", Math.PI / 8.0, 5), PredefinedConstant("LN_10", Math.log(10.0), 5), PredefinedConstant("LN_2", Math.log(2.0), 5), PredefinedConstant("LOG10_E", Math.log10(Math.E), 5), PredefinedConstant("LOG2_E", Math.log(Math.E) / Math.log(2.0), 5), PredefinedConstant("PI", Math.PI, 3), PredefinedConstant("SQRT_2", Math.sqrt(2.0), 5) ) } } data class PredefinedConstant(val name: String, val value: Double, val minDigits: Int) { val accuracy = Math.pow(0.1, minDigits.toDouble()) fun matches(value: Double): Boolean { return Math.abs(value - this.value) < accuracy } } private fun ProblemsHolder.registerProblem(element: PsiElement, type: String, constant: PredefinedConstant) { registerProblem(element, "Approximate value of `std::$type::consts::${constant.name}` found. Consider using it directly.") }
mit
4b8169628e1c4892fa6fa3fa28a6741f
38.533333
126
0.630017
3.870757
false
false
false
false
Maccimo/intellij-community
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/ModuleEntityImpl.kt
2
28458
package com.intellij.workspaceModel.storage.bridgeEntities.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableReferableWorkspaceEntity import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.PersistentEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.SoftLinkable import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.extractOneToOneChild import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent import com.intellij.workspaceModel.storage.referrersx import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ModuleEntityImpl: ModuleEntity, WorkspaceEntityBase() { companion object { internal val CONTENTROOTS_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, ContentRootEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) internal val CUSTOMIMLDATA_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, ModuleCustomImlDataEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) internal val GROUPPATH_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, ModuleGroupPathEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) internal val JAVASETTINGS_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, JavaModuleSettingsEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) internal val EXMODULEOPTIONS_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, ExternalSystemModuleOptionsEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) internal val FACETS_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, FacetEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) val connections = listOf<ConnectionId>( CONTENTROOTS_CONNECTION_ID, CUSTOMIMLDATA_CONNECTION_ID, GROUPPATH_CONNECTION_ID, JAVASETTINGS_CONNECTION_ID, EXMODULEOPTIONS_CONNECTION_ID, FACETS_CONNECTION_ID, ) } @JvmField var _name: String? = null override val name: String get() = _name!! @JvmField var _type: String? = null override val type: String? get() = _type @JvmField var _dependencies: List<ModuleDependencyItem>? = null override val dependencies: List<ModuleDependencyItem> get() = _dependencies!! override val contentRoots: List<ContentRootEntity> get() = snapshot.extractOneToManyChildren<ContentRootEntity>(CONTENTROOTS_CONNECTION_ID, this)!!.toList() override val customImlData: ModuleCustomImlDataEntity? get() = snapshot.extractOneToOneChild(CUSTOMIMLDATA_CONNECTION_ID, this) override val groupPath: ModuleGroupPathEntity? get() = snapshot.extractOneToOneChild(GROUPPATH_CONNECTION_ID, this) override val javaSettings: JavaModuleSettingsEntity? get() = snapshot.extractOneToOneChild(JAVASETTINGS_CONNECTION_ID, this) override val exModuleOptions: ExternalSystemModuleOptionsEntity? get() = snapshot.extractOneToOneChild(EXMODULEOPTIONS_CONNECTION_ID, this) override val facets: List<FacetEntity> get() = snapshot.extractOneToManyChildren<FacetEntity>(FACETS_CONNECTION_ID, this)!!.toList() override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ModuleEntityData?): ModifiableWorkspaceEntityBase<ModuleEntity>(), ModuleEntity.Builder { constructor(): this(ModuleEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ModuleEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isNameInitialized()) { error("Field ModuleEntity#name should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field ModuleEntity#entitySource should be initialized") } if (!getEntityData().isDependenciesInitialized()) { error("Field ModuleEntity#dependencies should be initialized") } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CONTENTROOTS_CONNECTION_ID, this) == null) { error("Field ModuleEntity#contentRoots should be initialized") } } else { if (this.entityLinks[EntityLink(true, CONTENTROOTS_CONNECTION_ID)] == null) { error("Field ModuleEntity#contentRoots should be initialized") } } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(FACETS_CONNECTION_ID, this) == null) { error("Field ModuleEntity#facets should be initialized") } } else { if (this.entityLinks[EntityLink(true, FACETS_CONNECTION_ID)] == null) { error("Field ModuleEntity#facets should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } override var name: String get() = getEntityData().name set(value) { checkModificationAllowed() getEntityData().name = value changedProperty.add("name") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var type: String? get() = getEntityData().type set(value) { checkModificationAllowed() getEntityData().type = value changedProperty.add("type") } override var dependencies: List<ModuleDependencyItem> get() = getEntityData().dependencies set(value) { checkModificationAllowed() getEntityData().dependencies = value changedProperty.add("dependencies") } // List of non-abstract referenced types var _contentRoots: List<ContentRootEntity>? = emptyList() override var contentRoots: List<ContentRootEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<ContentRootEntity>(CONTENTROOTS_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CONTENTROOTS_CONNECTION_ID)] as? List<ContentRootEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CONTENTROOTS_CONNECTION_ID)] as? List<ContentRootEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(CONTENTROOTS_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CONTENTROOTS_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CONTENTROOTS_CONNECTION_ID)] = value } changedProperty.add("contentRoots") } override var customImlData: ModuleCustomImlDataEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(CUSTOMIMLDATA_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, CUSTOMIMLDATA_CONNECTION_ID)] as? ModuleCustomImlDataEntity } else { this.entityLinks[EntityLink(true, CUSTOMIMLDATA_CONNECTION_ID)] as? ModuleCustomImlDataEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, CUSTOMIMLDATA_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneChildOfParent(CUSTOMIMLDATA_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, CUSTOMIMLDATA_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, CUSTOMIMLDATA_CONNECTION_ID)] = value } changedProperty.add("customImlData") } override var groupPath: ModuleGroupPathEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(GROUPPATH_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, GROUPPATH_CONNECTION_ID)] as? ModuleGroupPathEntity } else { this.entityLinks[EntityLink(true, GROUPPATH_CONNECTION_ID)] as? ModuleGroupPathEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, GROUPPATH_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneChildOfParent(GROUPPATH_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, GROUPPATH_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, GROUPPATH_CONNECTION_ID)] = value } changedProperty.add("groupPath") } override var javaSettings: JavaModuleSettingsEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(JAVASETTINGS_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, JAVASETTINGS_CONNECTION_ID)] as? JavaModuleSettingsEntity } else { this.entityLinks[EntityLink(true, JAVASETTINGS_CONNECTION_ID)] as? JavaModuleSettingsEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, JAVASETTINGS_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneChildOfParent(JAVASETTINGS_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, JAVASETTINGS_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, JAVASETTINGS_CONNECTION_ID)] = value } changedProperty.add("javaSettings") } override var exModuleOptions: ExternalSystemModuleOptionsEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(EXMODULEOPTIONS_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, EXMODULEOPTIONS_CONNECTION_ID)] as? ExternalSystemModuleOptionsEntity } else { this.entityLinks[EntityLink(true, EXMODULEOPTIONS_CONNECTION_ID)] as? ExternalSystemModuleOptionsEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, EXMODULEOPTIONS_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneChildOfParent(EXMODULEOPTIONS_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, EXMODULEOPTIONS_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, EXMODULEOPTIONS_CONNECTION_ID)] = value } changedProperty.add("exModuleOptions") } // List of non-abstract referenced types var _facets: List<FacetEntity>? = emptyList() override var facets: List<FacetEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<FacetEntity>(FACETS_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, FACETS_CONNECTION_ID)] as? List<FacetEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, FACETS_CONNECTION_ID)] as? List<FacetEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(FACETS_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, FACETS_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, FACETS_CONNECTION_ID)] = value } changedProperty.add("facets") } override fun getEntityData(): ModuleEntityData = result ?: super.getEntityData() as ModuleEntityData override fun getEntityClass(): Class<ModuleEntity> = ModuleEntity::class.java } } class ModuleEntityData : WorkspaceEntityData.WithCalculablePersistentId<ModuleEntity>(), SoftLinkable { lateinit var name: String var type: String? = null lateinit var dependencies: List<ModuleDependencyItem> fun isNameInitialized(): Boolean = ::name.isInitialized fun isDependenciesInitialized(): Boolean = ::dependencies.isInitialized override fun getLinks(): Set<PersistentEntityId<*>> { val result = HashSet<PersistentEntityId<*>>() for (item in dependencies) { when (item) { is ModuleDependencyItem.Exportable -> { when (item) { is ModuleDependencyItem.Exportable.ModuleDependency -> { result.add(item.module) } is ModuleDependencyItem.Exportable.LibraryDependency -> { result.add(item.library) } } } is ModuleDependencyItem.SdkDependency -> { } is ModuleDependencyItem.InheritedSdkDependency -> { } is ModuleDependencyItem.ModuleSourceDependency -> { } } } return result } override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) { for (item in dependencies) { when (item) { is ModuleDependencyItem.Exportable -> { when (item) { is ModuleDependencyItem.Exportable.ModuleDependency -> { index.index(this, item.module) } is ModuleDependencyItem.Exportable.LibraryDependency -> { index.index(this, item.library) } } } is ModuleDependencyItem.SdkDependency -> { } is ModuleDependencyItem.InheritedSdkDependency -> { } is ModuleDependencyItem.ModuleSourceDependency -> { } } } } override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) { // TODO verify logic val mutablePreviousSet = HashSet(prev) for (item in dependencies) { when (item) { is ModuleDependencyItem.Exportable -> { when (item) { is ModuleDependencyItem.Exportable.ModuleDependency -> { val removedItem_item_module = mutablePreviousSet.remove(item.module) if (!removedItem_item_module) { index.index(this, item.module) } } is ModuleDependencyItem.Exportable.LibraryDependency -> { val removedItem_item_library = mutablePreviousSet.remove(item.library) if (!removedItem_item_library) { index.index(this, item.library) } } } } is ModuleDependencyItem.SdkDependency -> { } is ModuleDependencyItem.InheritedSdkDependency -> { } is ModuleDependencyItem.ModuleSourceDependency -> { } } } for (removed in mutablePreviousSet) { index.remove(this, removed) } } override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean { var changed = false val dependencies_data = dependencies.map { val _it = it val res_it = when (_it) { is ModuleDependencyItem.Exportable -> { val __it = _it val res__it = when (__it) { is ModuleDependencyItem.Exportable.ModuleDependency -> { val __it_module_data = if (__it.module == oldLink) { changed = true newLink as ModuleId } else { null } var __it_data = __it if (__it_module_data != null) { __it_data = __it_data.copy(module = __it_module_data) } __it_data } is ModuleDependencyItem.Exportable.LibraryDependency -> { val __it_library_data = if (__it.library == oldLink) { changed = true newLink as LibraryId } else { null } var __it_data = __it if (__it_library_data != null) { __it_data = __it_data.copy(library = __it_library_data) } __it_data } } res__it } is ModuleDependencyItem.SdkDependency -> { _it } is ModuleDependencyItem.InheritedSdkDependency -> { _it } is ModuleDependencyItem.ModuleSourceDependency -> { _it } } if (res_it != null) { res_it } else { it } } if (dependencies_data != null) { dependencies = dependencies_data } return changed } override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ModuleEntity> { val modifiable = ModuleEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): ModuleEntity { val entity = ModuleEntityImpl() entity._name = name entity._type = type entity._dependencies = dependencies entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun persistentId(): PersistentEntityId<*> { return ModuleId(name) } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ModuleEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ModuleEntityData if (this.name != other.name) return false if (this.entitySource != other.entitySource) return false if (this.type != other.type) return false if (this.dependencies != other.dependencies) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ModuleEntityData if (this.name != other.name) return false if (this.type != other.type) return false if (this.dependencies != other.dependencies) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + name.hashCode() result = 31 * result + type.hashCode() result = 31 * result + dependencies.hashCode() return result } }
apache-2.0
94239b30aa033591516e19ab0e50fe7b
45.050162
224
0.551374
5.989897
false
false
false
false
Maccimo/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/XParentEntityImpl.kt
2
14894
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class XParentEntityImpl: XParentEntity, WorkspaceEntityBase() { companion object { internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(XParentEntity::class.java, XChildEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) internal val OPTIONALCHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(XParentEntity::class.java, XChildWithOptionalParentEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true) internal val CHILDCHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(XParentEntity::class.java, XChildChildEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) val connections = listOf<ConnectionId>( CHILDREN_CONNECTION_ID, OPTIONALCHILDREN_CONNECTION_ID, CHILDCHILD_CONNECTION_ID, ) } @JvmField var _parentProperty: String? = null override val parentProperty: String get() = _parentProperty!! override val children: List<XChildEntity> get() = snapshot.extractOneToManyChildren<XChildEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() override val optionalChildren: List<XChildWithOptionalParentEntity> get() = snapshot.extractOneToManyChildren<XChildWithOptionalParentEntity>(OPTIONALCHILDREN_CONNECTION_ID, this)!!.toList() override val childChild: List<XChildChildEntity> get() = snapshot.extractOneToManyChildren<XChildChildEntity>(CHILDCHILD_CONNECTION_ID, this)!!.toList() override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: XParentEntityData?): ModifiableWorkspaceEntityBase<XParentEntity>(), XParentEntity.Builder { constructor(): this(XParentEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity XParentEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isParentPropertyInitialized()) { error("Field XParentEntity#parentProperty should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field XParentEntity#entitySource should be initialized") } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) { error("Field XParentEntity#children should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) { error("Field XParentEntity#children should be initialized") } } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(OPTIONALCHILDREN_CONNECTION_ID, this) == null) { error("Field XParentEntity#optionalChildren should be initialized") } } else { if (this.entityLinks[EntityLink(true, OPTIONALCHILDREN_CONNECTION_ID)] == null) { error("Field XParentEntity#optionalChildren should be initialized") } } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDCHILD_CONNECTION_ID, this) == null) { error("Field XParentEntity#childChild should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] == null) { error("Field XParentEntity#childChild should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } override var parentProperty: String get() = getEntityData().parentProperty set(value) { checkModificationAllowed() getEntityData().parentProperty = value changedProperty.add("parentProperty") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } // List of non-abstract referenced types var _children: List<XChildEntity>? = emptyList() override var children: List<XChildEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<XChildEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<XChildEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<XChildEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value } changedProperty.add("children") } // List of non-abstract referenced types var _optionalChildren: List<XChildWithOptionalParentEntity>? = emptyList() override var optionalChildren: List<XChildWithOptionalParentEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<XChildWithOptionalParentEntity>(OPTIONALCHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, OPTIONALCHILDREN_CONNECTION_ID)] as? List<XChildWithOptionalParentEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, OPTIONALCHILDREN_CONNECTION_ID)] as? List<XChildWithOptionalParentEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(OPTIONALCHILDREN_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, OPTIONALCHILDREN_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, OPTIONALCHILDREN_CONNECTION_ID)] = value } changedProperty.add("optionalChildren") } // List of non-abstract referenced types var _childChild: List<XChildChildEntity>? = emptyList() override var childChild: List<XChildChildEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<XChildChildEntity>(CHILDCHILD_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] as? List<XChildChildEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] as? List<XChildChildEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(CHILDCHILD_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CHILDCHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] = value } changedProperty.add("childChild") } override fun getEntityData(): XParentEntityData = result ?: super.getEntityData() as XParentEntityData override fun getEntityClass(): Class<XParentEntity> = XParentEntity::class.java } } class XParentEntityData : WorkspaceEntityData<XParentEntity>() { lateinit var parentProperty: String fun isParentPropertyInitialized(): Boolean = ::parentProperty.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<XParentEntity> { val modifiable = XParentEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): XParentEntity { val entity = XParentEntityImpl() entity._parentProperty = parentProperty entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return XParentEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as XParentEntityData if (this.parentProperty != other.parentProperty) return false if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as XParentEntityData if (this.parentProperty != other.parentProperty) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + parentProperty.hashCode() return result } }
apache-2.0
79a093f977ad8b9d13907091f1a2bebf
44.972222
258
0.59769
5.969539
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/expressions/operators/handlers/binary/IsIgnoreCaseHandler.kt
1
845
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.expressions.operators.handlers.binary import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDataType import com.maddyhome.idea.vim.vimscript.model.datatypes.VimInt import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString object IsIgnoreCaseHandler : BinaryOperatorHandler() { override fun performOperation(left: VimDataType, right: VimDataType): VimDataType { return if (left is VimString && right is VimString) { VimInt(if (left.value.compareTo(right.value, ignoreCase = true) == 0) 1 else 0) } else { VimInt(if (left == right) 1 else 0) } } }
mit
1efd64ad1446185e75fed46d4674cf79
34.208333
85
0.745562
3.858447
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/neuralprocessor/batchfeedforward/MultiBatchFeedforwardProcessor.kt
1
4732
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.neuralprocessor.batchfeedforward import com.kotlinnlp.simplednn.core.layers.StackedLayersParameters import com.kotlinnlp.simplednn.core.neuralprocessor.NeuralProcessor import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray /** * The neural processor that acts on more networks of stacked-layers, performing operations with the same input batch * and obtaining more outputs for each element. * * It forwards the same sequence of X arrays using N different networks and obtaining N outputs for each element of the * sequence. * * @property model the parameters of more stacked-layers networks * @param dropouts the probability of dropout for each stacked layer of each network * @property propagateToInput whether to propagate the errors to the input during the backward * @property id an identification number useful to track a specific processor */ class MultiBatchFeedforwardProcessor<InputNDArrayType: NDArray<InputNDArrayType>>( val model: List<StackedLayersParameters>, dropouts: List<List<Double>>, override val propagateToInput: Boolean, override val id: Int = 0 ) : NeuralProcessor< List<InputNDArrayType>, // InputType List<List<DenseNDArray>>, // OutputType List<List<DenseNDArray>>, // ErrorsType List<DenseNDArray> // InputErrorsType > { /** * The neural processor that acts on networks of stacked-layers, performing operations through with mini-batches. * * @property model the parameters of more stacked-layers networks * @param dropout the probability of dropout for each stacked layer of each network (default 0.0) * @param propagateToInput whether to propagate the errors to the input during the [backward] * @param id an identification number useful to track a specific processor */ constructor( model: List<StackedLayersParameters>, dropout: Double = 0.0, propagateToInput: Boolean, id: Int = 0 ): this( model = model, dropouts = model.map { List(it.numOfLayers) { dropout } }, propagateToInput = propagateToInput, id = id ) /** * The feed-forward processors to encode each input batch. */ private val encoders: List<BatchFeedforwardProcessor<InputNDArrayType>> = this.model.zip(dropouts).map { (params, processorDropouts) -> BatchFeedforwardProcessor<InputNDArrayType>( model = params, dropouts = processorDropouts, propagateToInput = this.propagateToInput) } /** * @param copy whether the returned errors must be a copy or a reference (actually without effect, the errors are * always copied!) * * @return the errors of the input batch accumulated from all the networks */ override fun getInputErrors(copy: Boolean): List<DenseNDArray> { val inputErrors: List<DenseNDArray> = this.encoders[0].getInputErrors(copy = true) for (encoderIndex in 1 until (this.model.size - 1)) { inputErrors.zip(this.encoders[encoderIndex].getInputErrors(copy = false)).forEach { (baseErrors, errors) -> baseErrors.assignSum(errors) } } return inputErrors } /** * @param copy whether the returned errors must be a copy or a reference * * @return the parameters errors of all the networks */ override fun getParamsErrors(copy: Boolean) = this.encoders.flatMap { it.getParamsErrors(copy = copy) } /** * For each network, execute the forward of the same input batch to the output. * * @param input the input batch * * @return the outputs of all the networks for each element of the input batch */ override fun forward(input: List<InputNDArrayType>): List<List<DenseNDArray>> { val encodersOutputs: List<List<DenseNDArray>> = this.encoders.map { it.forward(input) } return List( size = input.size, init = { elementIndex -> List(size = this.encoders.size, init = { encoderIndex -> encodersOutputs[encoderIndex][elementIndex] }) } ) } /** * Execute the backward for each network, given their output errors. * * @param outputErrors the output errors of each network */ override fun backward(outputErrors: List<List<DenseNDArray>>) { this.encoders.forEachIndexed { encoderIndex, encoder -> encoder.backward(outputErrors.map { it[encoderIndex] } ) } } }
mpl-2.0
86ed96254dd470a50c543115e4a45787
36.555556
119
0.711116
4.515267
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/arrays/ActivableArray.kt
1
5371
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.arrays import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction import com.kotlinnlp.simplednn.simplemath.ndarray.* import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray /** * The [ActivableArray] is a wrapper of an [NDArray] in which values are modified according * to the activation function being used (e.g. Tanh, Sigmoid, ReLU, ELU). * * @property size the size of the [values] */ open class ActivableArray<NDArrayType : NDArray<NDArrayType>>(val size: Int) { companion object { /** * [ActivableArray] factory by values. * * @param values the initial values to assign to the [ActivableArray] * * @return an [ActivableArray] with the values already initialized */ operator fun <T : NDArray<T>> invoke(values: T): ActivableArray<T> { val array = ActivableArray<T>(size = values.length) array.assignValues(values) return array } } /** * An [NDArray] containing the values of this [ActivableArray] */ val values get() = this._values /** * An [NDArray] containing the values of this [ActivableArray] */ protected lateinit var _values: NDArrayType /** * An [NDArray] containing the values not activated of this [ActivableArray] (respect on the last call of activate()) */ val valuesNotActivated: NDArrayType get() = this._valuesNotActivated ?: this._values /** * The function used to activate this [ActivableArray] (e.g. Tanh, Sigmoid, ReLU, ELU) */ protected var activationFunction: ActivationFunction? = null /** * Whether this array has an activation function */ val hasActivation: Boolean get() = this.activationFunction != null /** * An [NDArray] containing the values not activated of this [ActivableArray] (respect on the last call of activate()) */ protected var _valuesNotActivated: NDArrayType? = null /** * Assign values to the array * @param values values to assign to this [ActivableArray] */ open fun assignValues(values: NDArrayType) { require(values.length == this.size) if (::_values.isInitialized) this._values.assignValues(values) else this._values = values.copy() } /** * Assign values as product of [a] and [b]. * This method optimizes the calculation avoiding the creation of a new [NDArray] when [values] are already set. * If [values] are still not initialized a new [NDArray] is created. * * @param a the first factor * @param b the second factor * * @return the values assigned */ fun assignValuesByProd(a: NDArrayType, b: NDArrayType): NDArrayType { require(a.length == this.size && b.length == this.size) { "Invalid arrays size" } if (::_values.isInitialized) this._values.assignProd(a, b) else this._values = a.prod(b) return this._values } /** * @param activationFunction the activation function (can be set as null) * * @return set the activation function of this [ActivableArray] */ open fun setActivation(activationFunction: ActivationFunction?) { this.activationFunction = activationFunction } /** * Activate the array memorizing the values not activated and setting the new activated values */ fun activate() { if (this.hasActivation) { if (this._valuesNotActivated == null) { this._valuesNotActivated = this._values.copy() } else { this._valuesNotActivated!!.assignValues(this._values) } this._values.assignValues(this.activationFunction!!.f(this._valuesNotActivated as DenseNDArray)) } } /** * Activate the array without modifying it, but only returning the values * @return the activated values */ fun getActivatedValues(): DenseNDArray = this.activationFunction!!.f(this.valuesNotActivated as DenseNDArray) /** * Calculate the derivative of the activation calculated in [valuesNotActivated]. * Note: when possible the optimized derivative is used (most of the common activation functions contain the activated * values themselves in their derivatives). * * @return the derivative of the activation calculated in [valuesNotActivated] */ fun calculateActivationDeriv(): DenseNDArray = try { this.activationFunction!!.dfOptimized(this._values as DenseNDArray) } catch (e: NotImplementedError) { this.activationFunction!!.df(this._valuesNotActivated as DenseNDArray) } /** * * @return a clone of this [ActivableArray] */ open fun clone(): ActivableArray<NDArrayType> { val clonedArray = ActivableArray<NDArrayType>(size = this.size) if (::_values.isInitialized) clonedArray.assignValues(this._values) if (this.hasActivation) { if (this._valuesNotActivated != null && this._valuesNotActivated != this._values) { clonedArray._valuesNotActivated = this._valuesNotActivated!!.copy() } clonedArray.setActivation(this.activationFunction!!) } return clonedArray } }
mpl-2.0
85dcbb5901151ebdae7e124becfe1c0d
30.046243
120
0.684789
4.183022
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/userflags/resolver/UserFlagsHelper.kt
1
3858
package org.wordpress.android.userflags.resolver import org.wordpress.android.localcontentmigration.LocalContentEntity.UserFlags import org.wordpress.android.localcontentmigration.LocalContentEntityData.UserFlagsData import org.wordpress.android.localcontentmigration.LocalMigrationContentResolver import org.wordpress.android.localcontentmigration.LocalMigrationError.FeatureDisabled.UserFlagsDisabled import org.wordpress.android.localcontentmigration.LocalMigrationError.MigrationAlreadyAttempted.UserFlagsAlreadyAttempted import org.wordpress.android.localcontentmigration.LocalMigrationError.NoUserFlagsFoundError import org.wordpress.android.localcontentmigration.LocalMigrationError.PersistenceError.FailedToSaveUserFlags import org.wordpress.android.localcontentmigration.LocalMigrationResult.Failure import org.wordpress.android.localcontentmigration.LocalMigrationResult.Success import org.wordpress.android.localcontentmigration.thenWith import org.wordpress.android.resolver.ResolverUtility import org.wordpress.android.ui.prefs.AppPrefsWrapper import org.wordpress.android.userflags.JetpackLocalUserFlagsFlag import org.wordpress.android.userflags.UserFlagsAnalyticsTracker import org.wordpress.android.userflags.UserFlagsAnalyticsTracker.ErrorType import javax.inject.Inject class UserFlagsHelper @Inject constructor( private val jetpackLocalUserFlagsFlag: JetpackLocalUserFlagsFlag, private val appPrefsWrapper: AppPrefsWrapper, private val userFlagsAnalyticsTracker: UserFlagsAnalyticsTracker, private val localMigrationContentResolver: LocalMigrationContentResolver, private val resolverUtility: ResolverUtility, ) { fun migrateUserFlags() = if (!jetpackLocalUserFlagsFlag.isEnabled()) { Failure(UserFlagsDisabled) } else if (!appPrefsWrapper.getIsFirstTryUserFlagsJetpack()) { Failure(UserFlagsAlreadyAttempted) } else { userFlagsAnalyticsTracker.trackStart() localMigrationContentResolver.getResultForEntityType<UserFlagsData>(UserFlags) } .thenWith(::checkIfEmpty) .thenWith(::updateUserFlagsData) .thenWith(::success) private fun checkIfEmpty(userFlagsData: UserFlagsData) = if (userFlagsData.flags.isEmpty()) { userFlagsAnalyticsTracker.trackFailed(ErrorType.NoUserFlagsFoundError) Failure(NoUserFlagsFoundError) } else { Success(userFlagsData) } private fun updateUserFlagsData(userFlagsData: UserFlagsData) = runCatching { val userFlags = userFlagsData.flags val qsStatusList = userFlagsData.quickStartStatusList val qsTaskList = userFlagsData.quickStartTaskList for ((key, value) in userFlags) { val userFlagPrefKey = UserFlagsPrefKey(key) when (value) { is String -> appPrefsWrapper.setString(userFlagPrefKey, value) is Long -> appPrefsWrapper.setLong(userFlagPrefKey, value) is Int -> appPrefsWrapper.setInt(userFlagPrefKey, value) is Boolean -> appPrefsWrapper.setBoolean(userFlagPrefKey, value) is Collection<*> -> { val stringSet = value.filterIsInstance<String>().toSet() appPrefsWrapper.setStringSet(userFlagPrefKey, stringSet) } } } if (!resolverUtility.copyQsDataWithIndexes(qsStatusList, qsTaskList)) { userFlagsAnalyticsTracker.trackFailed(ErrorType.UpdateUserFlagsError) Failure(FailedToSaveUserFlags) } else { Success(userFlagsData) } }.getOrElse { Failure(FailedToSaveUserFlags) } private fun success(userFlagsData: UserFlagsData) = run { appPrefsWrapper.saveIsFirstTryUserFlagsJetpack(false) userFlagsAnalyticsTracker.trackSuccess() Success(userFlagsData) } }
gpl-2.0
91d58a0364e852dff2dfd7539723ee76
49.103896
122
0.761794
4.952503
false
false
false
false
Yusuzhan/kotlin-koans
src/iii_conventions/MyDateUtil.kt
1
1135
package iii_conventions import iii_conventions.TimeInterval.* import java.util.* fun MyDate.nextDay() = addTimeIntervals(DAY, 1) operator fun MyDate.plus(timeInterval: TimeInterval): MyDate{ return this.addTimeIntervals(timeInterval, 1) } operator fun MyDate.plus(r: RepeatedTimeInterval): MyDate{ return this.addTimeIntervals(r.ti, r.n) } operator fun TimeInterval.times(n: Int): RepeatedTimeInterval{ return RepeatedTimeInterval(this, n) } class RepeatedTimeInterval(val ti: TimeInterval, val n: Int){ } fun MyDate.addTimeIntervals(timeInterval: TimeInterval, number: Int): MyDate { val c = Calendar.getInstance() c.set(year + if (timeInterval == YEAR) number else 0, month, dayOfMonth) var timeInMillis = c.timeInMillis val millisecondsInADay = 24 * 60 * 60 * 1000L timeInMillis += number * when (timeInterval) { DAY -> millisecondsInADay WEEK -> 7 * millisecondsInADay YEAR -> 0L } val result = Calendar.getInstance() result.timeInMillis = timeInMillis return MyDate(result.get(Calendar.YEAR), result.get(Calendar.MONTH), result.get(Calendar.DATE)) }
mit
6b5a790daa1c1d9f9c236bd4c8742802
28.894737
99
0.723348
4.157509
false
false
false
false
ingokegel/intellij-community
plugins/devkit/intellij.devkit.uiDesigner/src/ConvertFormNotificationProvider.kt
1
1877
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.devkit.uiDesigner import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiManager import com.intellij.psi.search.ProjectScope import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotifications import com.intellij.ui.LightColors import com.intellij.uiDesigner.editor.UIFormEditor import org.jetbrains.idea.devkit.util.PsiUtil class ConvertFormNotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>() { companion object { private val KEY = Key.create<EditorNotificationPanel>("convert.form.notification.panel") } override fun getKey(): Key<EditorNotificationPanel> = KEY override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? { if (fileEditor !is UIFormEditor) return null if (!PsiUtil.isIdeaProject(project)) return null val formPsiFile = PsiManager.getInstance(project).findFile(file) ?: return null val classToBind = fileEditor.editor.rootContainer.classToBind ?: return null val psiClass = JavaPsiFacade.getInstance(project).findClass(classToBind, ProjectScope.getProjectScope(project)) ?: return null return EditorNotificationPanel(LightColors.RED, EditorNotificationPanel.Status.Error).apply { setText(DevKitUIDesignerBundle.message("convert.form.editor.notification.label")) /* todo IDEA-282478 createActionLabel(DevKitBundle.message("convert.form.editor.notification.link.convert")) { convertFormToUiDsl(psiClass, formPsiFile) } */ } } }
apache-2.0
d0245c7340e702e78bce0e692b489ae6
43.690476
130
0.794885
4.623153
false
false
false
false
GunoH/intellij-community
platform/lang-impl/testSources/com/intellij/openapi/roots/moduleRootModelTestUtils.kt
12
4666
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.roots import com.intellij.openapi.application.runReadAction import com.intellij.openapi.application.runWriteActionAndWait import com.intellij.openapi.module.Module import com.intellij.openapi.roots.impl.RootConfigurationAccessor import com.intellij.testFramework.assertions.Assertions import org.assertj.core.api.Assertions.assertThat internal fun checkModuleRootModelConsistency(rootModel: ModuleRootModel) { assertThat(rootModel.contentRoots).containsExactly(*rootModel.contentEntries.mapNotNull { it.file }.toTypedArray()) assertThat(rootModel.contentRootUrls).containsExactly(*rootModel.contentEntries.map { it.url }.toTypedArray()) assertThat(rootModel.excludeRoots).containsExactly( *rootModel.contentEntries.flatMap { it.excludeFolderFiles.asIterable() }.toTypedArray()) assertThat(rootModel.excludeRootUrls).containsExactly( *rootModel.contentEntries.flatMap { it.excludeFolderUrls.asIterable() }.toTypedArray()) val allSourceRoots = rootModel.contentEntries.flatMap { it.sourceFolderFiles.asIterable() } assertThat(rootModel.sourceRoots).containsExactly(*allSourceRoots.toTypedArray()) assertThat(rootModel.getSourceRoots(true)).containsExactly(*allSourceRoots.toTypedArray()) assertThat(rootModel.getSourceRoots(false)).containsExactly(*rootModel.contentEntries.flatMap { contentEntry -> contentEntry.sourceFolders.filter { !it.isTestSource }.mapNotNull { it.file }.asIterable() }.toTypedArray()) val allSourceRootUrls = rootModel.contentEntries.flatMap { contentEntry -> contentEntry.sourceFolders.map { it.url }.asIterable() } assertThat(rootModel.sourceRootUrls).containsExactly(*allSourceRootUrls.toTypedArray()) assertThat(rootModel.getSourceRootUrls(true)).containsExactly(*allSourceRootUrls.toTypedArray()) assertThat(rootModel.getSourceRootUrls(false)).containsExactly(*rootModel.contentEntries.flatMap { contentEntry -> contentEntry.sourceFolders.filter { !it.isTestSource }.map { it.url }.asIterable() }.toTypedArray()) assertThat(rootModel.dependencyModuleNames).containsExactly( *rootModel.orderEntries.filterIsInstance(ModuleOrderEntry::class.java).map { it.moduleName }.toTypedArray()) val moduleDependencies = rootModel.orderEntries.filterIsInstance(ModuleOrderEntry::class.java).mapNotNull { it.module }.toTypedArray() assertThat(rootModel.moduleDependencies).containsExactly(*moduleDependencies) assertThat(rootModel.getModuleDependencies(true)).containsExactly(*moduleDependencies) assertThat(rootModel.getModuleDependencies(false)).containsExactly( *rootModel.orderEntries.filterIsInstance( ModuleOrderEntry::class.java).filter { it.scope != DependencyScope.TEST }.mapNotNull { it.module }.toTypedArray() ) } internal fun checkContentEntryConsistency(entry: ContentEntry) { assertThat(entry.sourceFolderFiles).containsExactly(*entry.sourceFolders.mapNotNull { it.file }.toTypedArray()) assertThat(entry.excludeFolderFiles).containsExactly(*entry.excludeFolders.mapNotNull { it.file }.toTypedArray()) assertThat(entry.excludeFolderUrls).containsExactly(*entry.excludeFolders.map { it.url }.toTypedArray()) } internal fun commitModifiableRootModel(model: ModifiableRootModel, assertChanged: Boolean = true): ModuleRootManager { assertThat(model.isChanged).isEqualTo(assertChanged) checkModuleRootModelConsistency(model) runWriteActionAndWait { model.commit() } val moduleRootManager = ModuleRootManager.getInstance(model.module) checkModuleRootModelConsistency(moduleRootManager) return moduleRootManager } internal fun createModifiableModel(module: Module, accessor: RootConfigurationAccessor = RootConfigurationAccessor()): ModifiableRootModel { return runReadAction { val moduleRootManager = ModuleRootManagerEx.getInstanceEx(module) checkModuleRootModelConsistency(moduleRootManager) val model = moduleRootManager.getModifiableModel(accessor) checkModuleRootModelConsistency(model) model } } internal fun dropModuleSourceEntry(model: ModuleRootModel, additionalEntries: Int): List<OrderEntry> { val orderEntries = model.orderEntries Assertions.assertThat(orderEntries).hasSize(additionalEntries + 1) model.orderEntries.filterIsInstance<ModuleSourceOrderEntry>().single() return model.orderEntries.filter { it !is ModuleSourceOrderEntry } } internal fun getSingleLibraryOrderEntry(model: ModuleRootModel): LibraryOrderEntry = dropModuleSourceEntry(model, 1).single() as LibraryOrderEntry
apache-2.0
aa371957c3813221fd21220eb060c9e6
56.604938
140
0.810544
5.314351
false
false
false
false
GunoH/intellij-community
plugins/kotlin/util/test-generator-fir/test/org/jetbrains/kotlin/fir/testGenerator/FirGenerateTests.kt
1
11853
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.fir.testGenerator import org.jetbrains.kotlin.fir.testGenerator.codeinsight.generateK2CodeInsightTests import org.jetbrains.kotlin.idea.fir.analysis.providers.AbstractIdeKotlinAnnotationsResolverTest import org.jetbrains.kotlin.idea.fir.analysis.providers.sessions.AbstractSessionsInvalidationTest import org.jetbrains.kotlin.idea.fir.analysis.providers.trackers.AbstractProjectWideOutOfBlockKotlinModificationTrackerTest import org.jetbrains.kotlin.idea.fir.completion.AbstractFirKeywordCompletionTest import org.jetbrains.kotlin.idea.fir.completion.AbstractHighLevelJvmBasicCompletionTest import org.jetbrains.kotlin.idea.fir.completion.AbstractHighLevelMultiFileJvmBasicCompletionTest import org.jetbrains.kotlin.idea.fir.completion.AbstractK2MultiPlatformCompletionTest import org.jetbrains.kotlin.idea.fir.completion.test.handlers.AbstractFirKeywordCompletionHandlerTest import org.jetbrains.kotlin.idea.fir.completion.test.handlers.AbstractHighLevelBasicCompletionHandlerTest import org.jetbrains.kotlin.idea.fir.completion.test.handlers.AbstractHighLevelJavaCompletionHandlerTest import org.jetbrains.kotlin.idea.fir.completion.wheigher.AbstractHighLevelWeigherTest import org.jetbrains.kotlin.idea.fir.documentation.AbstractFirQuickDocTest import org.jetbrains.kotlin.idea.fir.findUsages.AbstractFindUsagesFirTest import org.jetbrains.kotlin.idea.fir.findUsages.AbstractFindUsagesWithDisableComponentSearchFirTest import org.jetbrains.kotlin.idea.fir.findUsages.AbstractKotlinFindUsagesWithLibraryFirTest import org.jetbrains.kotlin.idea.fir.findUsages.AbstractKotlinFindUsagesWithStdlibFirTest import org.jetbrains.kotlin.idea.fir.imports.AbstractFirJvmOptimizeImportsTest import org.jetbrains.kotlin.idea.fir.low.level.api.AbstractFirLibraryModuleDeclarationResolveTest import org.jetbrains.kotlin.idea.fir.parameterInfo.AbstractFirParameterInfoTest import org.jetbrains.kotlin.idea.fir.quickfix.AbstractHighLevelQuickFixMultiFileTest import org.jetbrains.kotlin.idea.fir.quickfix.AbstractHighLevelQuickFixTest import org.jetbrains.kotlin.idea.fir.refactoring.rename.AbstractFirRenameTest import org.jetbrains.kotlin.idea.fir.refactoring.rename.AbstractFirSimpleRenameTest import org.jetbrains.kotlin.idea.fir.resolve.AbstractFirReferenceResolveTest import org.jetbrains.kotlin.idea.fir.search.AbstractHLImplementationSearcherTest import org.jetbrains.kotlin.idea.fir.shortenRefs.AbstractFirShortenRefsTest import org.jetbrains.kotlin.idea.fir.uast.* import org.jetbrains.kotlin.testGenerator.generator.TestGenerator import org.jetbrains.kotlin.testGenerator.model.* import org.jetbrains.kotlin.testGenerator.model.Patterns.DIRECTORY import org.jetbrains.kotlin.testGenerator.model.Patterns.KT_OR_KTS_WITHOUT_DOTS import org.jetbrains.kotlin.testGenerator.model.Patterns.KT_WITHOUT_DOTS import org.jetbrains.kotlin.testGenerator.model.Patterns.KT_WITHOUT_DOT_AND_FIR_PREFIX import org.jetbrains.kotlin.testGenerator.model.Patterns.KT_WITHOUT_FIR_PREFIX fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) { generateK2Tests() } fun generateK2Tests(isUpToDateCheck: Boolean = false) { System.setProperty("java.awt.headless", "true") TestGenerator.write(assembleWorkspace(), isUpToDateCheck) } private fun assembleWorkspace(): TWorkspace = workspace { generateK2CodeInsightTests() generateK2Fe10BindingsTests() generateK2NavigationTests() generateK2DebuggerTests() generateK2HighlighterTests() generateK2RefactoringsTests() generateK2SearchTests() testGroup("base/fir/analysis-api-providers") { testClass<AbstractProjectWideOutOfBlockKotlinModificationTrackerTest> { model("outOfBlockProjectWide", pattern = KT_WITHOUT_DOTS or Patterns.JAVA) } testClass<AbstractSessionsInvalidationTest> { model("sessionInvalidation", pattern = DIRECTORY, isRecursive = false) } testClass<AbstractIdeKotlinAnnotationsResolverTest> { model("annotationsResolver", pattern = KT_WITHOUT_DOTS) } } testGroup("fir-low-level-api-ide-impl") { testClass<AbstractFirLibraryModuleDeclarationResolveTest> { model("libraryModuleResolve", isRecursive = false) } } testGroup("fir", testDataPath = "../idea/tests/testData") { testClass<AbstractFirReferenceResolveTest> { model("resolve/references", pattern = KT_WITHOUT_DOTS) } testClass<AbstractHighLevelQuickFixTest> { val pattern = Patterns.forRegex("^([\\w\\-_]+)\\.kt$") model("quickfix/abstract", pattern = pattern) model("quickfix/addExclExclCall", pattern = pattern) model("quickfix/addInitializer", pattern = pattern) model("quickfix/addPropertyAccessors", pattern = pattern) model("quickfix/checkArguments", pattern = pattern, isRecursive = false) model("quickfix/conflictingImports", pattern = pattern) model("quickfix/expressions", pattern = pattern) model("quickfix/lateinit", pattern = pattern) model("quickfix/localVariableWithTypeParameters", pattern = pattern) model("quickfix/modifiers", pattern = pattern, isRecursive = false) model("quickfix/nullables", pattern = pattern) model("quickfix/override", pattern = pattern, isRecursive = false) model("quickfix/override/typeMismatchOnOverride", pattern = pattern, isRecursive = false) model("quickfix/removeRedundantSpreadOperator", pattern = pattern) model("quickfix/replaceInfixOrOperatorCall", pattern = pattern) model("quickfix/replaceWithArrayCallInAnnotation", pattern = pattern) model("quickfix/replaceWithDotCall", pattern = pattern) model("quickfix/replaceWithSafeCall", pattern = pattern) model("quickfix/specifyVisibilityInExplicitApiMode", pattern = pattern) model("quickfix/supercalls", pattern = pattern) model("quickfix/surroundWithArrayOfForNamedArgumentsToVarargs", pattern = pattern) model("quickfix/variables/changeMutability", pattern = pattern, isRecursive = false) model("quickfix/variables/removeValVarFromParameter", pattern = pattern) model("quickfix/when", pattern = pattern) model("quickfix/wrapWithSafeLetCall", pattern = pattern) model("quickfix/typeAddition", pattern = pattern) model("quickfix/typeMismatch/casts", pattern = pattern) model("quickfix/typeMismatch/componentFunctionReturnTypeMismatch", pattern = pattern) model("quickfix/typeMismatch/typeMismatchOnReturnedExpression", pattern = pattern) model("quickfix/toString", pattern = pattern) model("quickfix/specifySuperType", pattern = pattern) } testClass<AbstractHighLevelQuickFixMultiFileTest> { model("quickfix/autoImports", pattern = Patterns.forRegex("""^(\w+)\.((before\.Main\.\w+)|(test))$"""), testMethodName = "doTestWithExtraFile") } testClass<AbstractFirShortenRefsTest> { model("shortenRefsFir", pattern = KT_WITHOUT_DOTS, testMethodName = "doTestWithMuting") } testClass<AbstractFirParameterInfoTest> { model( "parameterInfo", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.kt$"), isRecursive = true, excludedDirectories = listOf("withLib1/sharedLib", "withLib2/sharedLib", "withLib3/sharedLib") ) } testClass<AbstractFirJvmOptimizeImportsTest> { model("editor/optimizeImports/jvm", pattern = KT_WITHOUT_DOTS) model("editor/optimizeImports/common", pattern = KT_WITHOUT_DOTS) } } testGroup("fir", testDataPath = "../completion/testData") { testClass<AbstractHighLevelJvmBasicCompletionTest> { model("basic/common", pattern = KT_WITHOUT_FIR_PREFIX) model("basic/java", pattern = KT_WITHOUT_FIR_PREFIX) model("../../idea-fir/testData/completion/basic/common", testClassName = "CommonFir") } testClass<AbstractHighLevelBasicCompletionHandlerTest> { model("handlers/basic", pattern = KT_WITHOUT_DOT_AND_FIR_PREFIX) } testClass<AbstractHighLevelJavaCompletionHandlerTest> { model("handlers/injava", pattern = Patterns.JAVA) } testClass<AbstractFirKeywordCompletionHandlerTest> { model("handlers/keywords", pattern = KT_WITHOUT_DOT_AND_FIR_PREFIX) } testClass<AbstractHighLevelWeigherTest> { model("weighers/basic", pattern = KT_OR_KTS_WITHOUT_DOTS) } testClass<AbstractHighLevelMultiFileJvmBasicCompletionTest> { model("basic/multifile", pattern = DIRECTORY, isRecursive = false) } testClass<AbstractK2MultiPlatformCompletionTest> { model("multiPlatform", isRecursive = false, pattern = DIRECTORY) } testClass<AbstractFirKeywordCompletionTest> { model("keywords", isRecursive = false, pattern = KT_WITHOUT_FIR_PREFIX) model( "../../idea-fir/testData/completion/keywords", testClassName = "KeywordsFir", isRecursive = false, pattern = KT_WITHOUT_FIR_PREFIX ) } } testGroup("refactorings/rename.k2", testDataPath = "../../idea/tests/testData") { testClass<AbstractFirRenameTest> { model("refactoring/rename", pattern = Patterns.TEST, flatten = true) } } testGroup("fir", testDataPath = "../idea/tests/testData/findUsages") { testClass<AbstractFindUsagesFirTest> { model("kotlin", pattern = Patterns.forRegex("""^(.+)\.0\.(kt|kts)$""")) model("java", pattern = Patterns.forRegex("""^(.+)\.0\.java$""")) model("propertyFiles", pattern = Patterns.forRegex("""^(.+)\.0\.properties$""")) } testClass<AbstractFindUsagesWithDisableComponentSearchFirTest> { model("kotlin/conventions/components", pattern = Patterns.forRegex("""^(.+)\.0\.(kt|kts)$""")) } testClass<AbstractKotlinFindUsagesWithLibraryFirTest> { model("libraryUsages", pattern = Patterns.forRegex("""^(.+)\.0\.kt$""")) } testClass<AbstractKotlinFindUsagesWithStdlibFirTest> { model("stdlibUsages", pattern = Patterns.forRegex("""^(.+)\.0\.kt$""")) } } testGroup("fir") { testClass<AbstractHLImplementationSearcherTest> { model("search/implementations", pattern = KT_WITHOUT_DOTS) } testClass<AbstractFirQuickDocTest> { model("quickDoc", pattern = Patterns.forRegex("""^([^_]+)\.(kt|java)$""")) } } testGroup("uast/uast-kotlin-fir") { testClass<AbstractFirUastDeclarationTest> { model("declaration") } testClass<AbstractFirUastTypesTest> { model("type") } testClass<AbstractFirUastValuesTest> { model("value") } } testGroup("uast/uast-kotlin-fir", testDataPath = "../uast-kotlin/tests/testData") { testClass<AbstractFirLegacyUastDeclarationTest> { model("") } testClass<AbstractFirLegacyUastIdentifiersTest> { model("") } testClass<AbstractFirLegacyUastResolveEverythingTest> { model("") } testClass<AbstractFirLegacyUastTypesTest> { model("") } testClass<AbstractFirLegacyUastValuesTest> { model("") } } }
apache-2.0
a1c48fa614d65489e9d594e56f8527a3
45.304688
155
0.698642
4.849836
false
true
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/internal/ml/completion/JarCompletionModelProvider.kt
12
1854
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.ml.completion import com.intellij.internal.ml.* import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.TestOnly abstract class JarCompletionModelProvider(@Nls(capitalization = Nls.Capitalization.Title) private val displayName: String, @NonNls private val resourceDirectory: String) : RankingModelProvider { private val lazyModel: DecisionFunction by lazy { val metadata = FeaturesInfo.buildInfo(ResourcesModelMetadataReader(this::class.java, resourceDirectory)) createModel(metadata) } override fun getModel(): DecisionFunction = lazyModel override fun getDisplayNameInSettings(): String = displayName protected abstract fun createModel(metadata: ModelMetadata): DecisionFunction @TestOnly fun assertModelMetadataConsistent() { try { val decisionFunction = model decisionFunction.version() val unknownRequiredFeatures = decisionFunction.getUnknownFeatures(decisionFunction.requiredFeatures) assert(unknownRequiredFeatures.isEmpty()) { "All required features should be known, but $unknownRequiredFeatures unknown" } val featuresOrder = decisionFunction.featuresOrder val unknownUsedFeatures = decisionFunction.getUnknownFeatures(featuresOrder.map { it.featureName }.distinct()) assert(unknownUsedFeatures.isEmpty()) { "All used features should be known, but $unknownUsedFeatures unknown" } val features = DoubleArray(featuresOrder.size) decisionFunction.predict(features) } catch (e: InconsistentMetadataException) { throw AssertionError("Model metadata inconsistent", e) } } }
apache-2.0
b4793e9e3eed151aaf7984a57ee735f4
43.142857
140
0.763215
5.065574
false
false
false
false
mvmike/min-cal-widget
app/src/main/kotlin/cat/mvmike/minimalcalendarwidget/infrastructure/activity/PermissionsActivity.kt
1
1470
// Copyright (c) 2016, Miquel Martí <[email protected]> // See LICENSE for licensing information package cat.mvmike.minimalcalendarwidget.infrastructure.activity import android.Manifest import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.PackageManager import androidx.core.app.ActivityCompat import cat.mvmike.minimalcalendarwidget.application.RedrawWidgetUseCase private const val READ_CALENDAR_PERM = 225 class PermissionsActivity : Activity() { companion object { fun start(context: Context) = context.startActivity( Intent(context, PermissionsActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ) } override fun onStart() { super.onStart() setResult(RESULT_CANCELED) ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CALENDAR), READ_CALENDAR_PERM) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode.isReadCalendarPermission() && grantResults.isPermissionGranted()) { setResult(RESULT_OK) RedrawWidgetUseCase.execute(this) } finish() } private fun Int.isReadCalendarPermission() = this == READ_CALENDAR_PERM private fun IntArray.isPermissionGranted() = this.size == 1 && this[0] == PackageManager.PERMISSION_GRANTED }
bsd-3-clause
a8f4984a6a9904fca3464cacf7673198
33.97619
115
0.725664
4.785016
false
false
false
false
matiuri/Sudoku
core/src/kotlin/com/github/matiuri/sudoku/game/Tools.kt
1
5667
package com.github.matiuri.sudoku.game import com.badlogic.gdx.math.MathUtils.random import mati.advancedgdx.AdvancedGame import java.util.* object Tools { fun generate(cells: Array<Array<Cell>>) { val cols: Array<List<Cell>> = colsList(cells) val rows: Array<List<Cell>> = rowsList(cells) val blocks: Array<List<Cell>> = blocksList(cells) cells.forEach { it.forEach { it.number = 0 it.usrnum = 0 it.solverPossibilities.clear() it.hidden = false } } cells.forEach { it.forEach { cell -> val related: Set<Cell> = relatedCells(blocks, cell, cols, rows) var candidate: Int val attempts: MutableSet<Int> = HashSet() do { if (attempts.size == 9) { throw IllegalStateException("Impossible Game, Generator") } candidate = random(1, 9) attempts.add(candidate) } while (related.filter { it.num != cell.num }.fold(false) { f, c -> c.number == candidate || f }) cell.number = candidate cell.usrnum = cell.number } } } fun remove(cells: Array<Array<Cell>>, difficulty: Int = 30) { AdvancedGame.log.d(this.javaClass.simpleName, "Attempting to remove cells") (1..difficulty).forEach { var cell: Cell val possibleCells = cells.flatMap { it.asIterable() }.filter { !it.hidden } val tries: MutableSet<Cell> = HashSet() do { val possibilities = possibleCells.filter { !tries.contains(it) } if (possibilities.isEmpty()) throw IllegalStateException("Impossible Game, Generator") cell = possibilities[random(0, possibilities.size - 1)] cell.hidden = true cell.usrnum = 0 var failed: Boolean try { AdvancedGame.log.d(this.javaClass.simpleName, "Attempting to solve") solve(cells) cell.usrnum = 0 failed = false } catch (e: IllegalStateException) { cell.hidden = false cell.usrnum = cell.number tries.add(cell) failed = true } AdvancedGame.log.d(this.javaClass.simpleName, "$failed") } while (failed) } AdvancedGame.log.d(this.javaClass.simpleName, "Removed") } private fun solve(cells: Array<Array<Cell>>) { val cols: Array<List<Cell>> = colsList(cells) val rows: Array<List<Cell>> = rowsList(cells) val blocks: Array<List<Cell>> = blocksList(cells) cells.forEach { it.forEach { it.usrnum = 0 it.solverPossibilities.clear() } } var solved: Boolean = false while (!solved) { cells.forEach { it.filter { it.hidden && it.usrnum == 0 }.forEach { cell -> cell.solverPossibilities.clear() val related = relatedCells(blocks, cell, cols, rows).filter { it.num != cell.num } (1..9).filter { i -> related.fold(true) { f, c -> (c.hidden || c.number != i) && (!c.hidden || c.usrnum != i) && f } }.forEach { cell.solverPossibilities.add(it) } } } var impossible: Boolean = true cells.forEach { it.filter { it.hidden && it.usrnum == 0 && it.solverPossibilities.size == 1 }.forEach { impossible = false it.usrnum = it.solverPossibilities.first() } } if (impossible) throw IllegalStateException("Impossible Game, Solver") solved = cells.fold(true) { f_, c_ -> f_ && c_.fold(true) { f, c -> f && (!c.hidden || c.number == c.usrnum) } } AdvancedGame.log.d(this.javaClass.simpleName, "Solving try") } } private fun relatedCells(blocks: Array<List<Cell>>, cell: Cell, cols: Array<List<Cell>>, rows: Array<List<Cell>>): Set<Cell> { val col: Int = cell.col - 1 val row: Int = cell.row - 1 val block: Int = cell.block - 1 return cols[col].union(rows[row].union(blocks[block])) } private fun blocksList(cells: Array<Array<Cell>>): Array<List<Cell>> { val blocks: Array<List<Cell>> = Array(9) { i -> val list: MutableList<Cell> = ArrayList() cells.forEach { it.filter { it.block == i + 1 }.forEach { list.add(it) } } list } return blocks } private fun rowsList(cells: Array<Array<Cell>>): Array<List<Cell>> { val rows: Array<List<Cell>> = Array(9) { i -> val list: MutableList<Cell> = ArrayList() cells.forEach { it.filter { it.row == i + 1 }.forEach { list.add(it) } } list } return rows } private fun colsList(cells: Array<Array<Cell>>): Array<List<Cell>> { val cols: Array<List<Cell>> = Array(9) { i -> val list: MutableList<Cell> = ArrayList() cells.forEach { it.filter { it.col == i + 1 }.forEach { list.add(it) } } list } return cols } }
gpl-3.0
09b32c4a812048bb17f3040902c6e35e
37.815068
118
0.494794
4.372685
false
false
false
false
ClearVolume/scenery
src/test/kotlin/graphics/scenery/tests/examples/volumes/BDVExample.kt
1
4935
package graphics.scenery.tests.examples.volumes import bdv.spimdata.XmlIoSpimDataMinimal import org.joml.Vector3f import graphics.scenery.Camera import graphics.scenery.DetachedHeadCamera import graphics.scenery.PointLight import graphics.scenery.SceneryBase import graphics.scenery.backends.Renderer import graphics.scenery.volumes.Colormap import graphics.scenery.volumes.TransferFunction import graphics.scenery.volumes.Volume import net.imagej.ops.OpService import net.imglib2.histogram.Histogram1d import org.scijava.Context import org.scijava.ui.UIService import org.scijava.ui.behaviour.ClickBehaviour import org.scijava.widget.FileWidget import tpietzsch.example2.VolumeViewerOptions import java.util.* import kotlin.math.roundToInt import kotlin.system.measureTimeMillis /** * BDV Rendering Example * * @author Ulrik Günther <[email protected]> */ class BDVExample: SceneryBase("BDV Rendering example", 1280, 720) { var volume: Volume? = null var maxCacheSize = 512 val context = Context(UIService::class.java, OpService::class.java) val ui = context.getService(UIService::class.java) val ops = context.getService(OpService::class.java) override fun init() { val files = ArrayList<String>() val fileFromProperty = System.getProperty("bdvXML") if(fileFromProperty != null) { files.add(fileFromProperty) } else { val file = ui.chooseFile(null, FileWidget.OPEN_STYLE) files.add(file.absolutePath) } if(files.size == 0) { throw IllegalStateException("You have to select a file, sorry.") } logger.info("Loading BDV XML from ${files.first()}") renderer = hub.add(Renderer.createRenderer(hub, applicationName, scene, windowWidth, windowHeight)) val cam: Camera = DetachedHeadCamera() with(cam) { perspectiveCamera(50.0f, windowWidth, windowHeight) scene.addChild(this) } val options = VolumeViewerOptions().maxCacheSizeInMB(maxCacheSize) val v = Volume.fromSpimData(XmlIoSpimDataMinimal().load(files.first()), hub, options) v.name = "volume" v.colormap = Colormap.get("hot") v.transferFunction = TransferFunction.ramp(0.02f, 0.4f) v.viewerState.sources.firstOrNull()?.spimSource?.getSource(0, 0)?.let { rai -> var h: Any? val duration = measureTimeMillis { h = ops.run("image.histogram", rai, 1024) } val histogram = h as? Histogram1d<*> ?: return@let logger.info("Got histogram $histogram for t=0 l=0 in $duration ms") logger.info("min: ${histogram.min()} max: ${histogram.max()} bins: ${histogram.binCount} DFD: ${histogram.dfd().modePositions().firstOrNull()?.joinToString(",")}") histogram.forEachIndexed { index, longType -> val relativeCount = (longType.get().toFloat()/histogram.totalCount().toFloat()) * histogram.binCount val bar = "*".repeat(relativeCount.roundToInt()) val position = (index.toFloat()/histogram.binCount.toFloat())*(65536.0f/histogram.binCount.toFloat()) logger.info("%.3f: $bar".format(position)) } } scene.addChild(v) volume = v val lights = (0 until 3).map { PointLight(radius = 15.0f) } lights.mapIndexed { i, light -> light.spatial().position = Vector3f(2.0f * i - 4.0f, i - 1.0f, 0.0f) light.emissionColor = Vector3f(1.0f, 1.0f, 1.0f) light.intensity = 50.0f scene.addChild(light) } } override fun inputSetup() { setupCameraModeSwitching() val nextTimePoint = ClickBehaviour { _, _ -> volume?.nextTimepoint() } val prevTimePoint = ClickBehaviour { _, _ -> volume?.previousTimepoint() } val tenTimePointsForward = ClickBehaviour { _, _ -> val current = volume?.currentTimepoint ?: 0 volume?.goToTimepoint(current + 10) } val tenTimePointsBack = ClickBehaviour { _, _ -> val current = volume?.currentTimepoint ?: 0 volume?.goToTimepoint(current - 10) } inputHandler?.addBehaviour("prev_timepoint", prevTimePoint) inputHandler?.addKeyBinding("prev_timepoint", "H") inputHandler?.addBehaviour("10_prev_timepoint", tenTimePointsBack) inputHandler?.addKeyBinding("10_prev_timepoint", "shift H") inputHandler?.addBehaviour("next_timepoint", nextTimePoint) inputHandler?.addKeyBinding("next_timepoint", "L") inputHandler?.addBehaviour("10_next_timepoint", tenTimePointsForward) inputHandler?.addKeyBinding("10_next_timepoint", "shift L") } companion object { @JvmStatic fun main(args: Array<String>) { BDVExample().main() } } }
lgpl-3.0
51fc8d43d4e0107a4881c9f02fef80c0
36.097744
175
0.645318
4.125418
false
false
false
false
jovr/imgui
core/src/main/kotlin/imgui/api/settingsIniUtilities.kt
2
4273
package imgui.api import imgui.ImGui.findSettingsHandler import imgui.internal.sections.SettingsHandler import java.io.File import java.nio.file.Paths /* Settings/.Ini Utilities - The disk functions are automatically called if io.IniFilename != NULL (default is "imgui.ini"). - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually. */ interface settingsIniUtilities { /** call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename). */ fun loadIniSettingsFromDisk(iniFilename: String?) { if (iniFilename == null) return val file = File(Paths.get(iniFilename).toUri()) if (file.exists() && file.canRead()) loadIniSettingsFromMemory(file.readLines()) } /** call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source. * * Zero-tolerance, no error reporting, cheap .ini parsing */ fun loadIniSettingsFromMemory(lines: List<String>) { assert(g.initialized) //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()"); // assert(!g.settingsLoaded && g.frameCount == 0) // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter). // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy.. // Call pre-read handlers // Some types will clear their data (e.g. dock information) some types will allow merge/override (window) for (handler in g.settingsHandlers) handler.readInitFn?.invoke(g, handler) var entryHandler: SettingsHandler? = null var entryData: Any? = null for (i in lines.indices) { val line = lines[i].trim() if (line.isNotEmpty() && line.isNotBlank()) { // Skip new lines markers, then find end of the line if (line[0] == '[' && line.last() == ']') { // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code. val firstCloseBracket = line.indexOf(']') if (firstCloseBracket != -1 && line[firstCloseBracket + 1] == '[') { val type = line.substring(1, firstCloseBracket) val name = line.substring(firstCloseBracket + 2, line.lastIndex) entryHandler = findSettingsHandler(type) entryData = entryHandler?.readOpenFn?.invoke(g, entryHandler, name) // val typeHash = hash(type) // settings = findWindowSettings(typeHash) ?: createNewWindowSettings(name) } } else if (entryHandler != null && entryData != null) // Let type handler parse the line entryHandler.readLineFn!!(g, entryHandler, entryData, line) } } g.settingsLoaded = true // Call post-read handlers for (handler in g.settingsHandlers) handler.applyAllFn?.invoke(g, handler) } /** this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext). */ fun saveIniSettingsToDisk(iniFilename: String?) { g.settingsDirtyTimer = 0f if (iniFilename == null) return val file = File(Paths.get(iniFilename).toUri()) if (file.exists() && file.canWrite()) file.writeText(saveIniSettingsToMemory()) } /** Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer */ fun saveIniSettingsToMemory(): String { g.settingsDirtyTimer = 0f val buf = StringBuilder() for (handler in g.settingsHandlers) handler.writeAllFn!!(g, handler, buf) g.settingsIniData = buf.toString() return g.settingsIniData } }
mit
d5da378cfff7a1558c5adf17557a6f2f
46.488889
181
0.628364
4.44641
false
false
false
false
KDE/kdeconnect-android
src/org/kde/kdeconnect/Helpers/VolumeHelper.kt
1
562
/* * SPDX-FileCopyrightText: 2021 Art Pinch <[email protected]> * * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ package org.kde.kdeconnect.Helpers const val DEFAULT_MAX_VOLUME = 100 const val DEFAULT_VOLUME_STEP = 5 fun calculateNewVolume(currentVolume: Int, maxVolume: Int, stepPercent: Int): Int { val adjustedStepPercent = stepPercent.coerceIn(-100, 100) val step = maxVolume * adjustedStepPercent / 100 val newVolume = currentVolume + step return newVolume.coerceIn(0, maxVolume) }
gpl-2.0
38bb383c9f581a79316ba2c2bee8a350
25.809524
87
0.741993
3.534591
false
false
false
false
dahlstrom-g/intellij-community
platform/testFramework/src/com/intellij/project/TestProjectManager.kt
1
7808
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.project import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.startup.StartupManagerEx import com.intellij.openapi.application.AccessToken import com.intellij.openapi.command.impl.DummyProject import com.intellij.openapi.command.impl.UndoManagerImpl import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ex.ProjectEx import com.intellij.openapi.project.impl.ProjectExImpl import com.intellij.openapi.project.impl.ProjectImpl import com.intellij.openapi.project.impl.ProjectManagerExImpl import com.intellij.project.TestProjectManager.Companion.getCreationPlace import com.intellij.testFramework.LeakHunter import com.intellij.testFramework.TestApplicationManager.Companion.publishHeapDump import com.intellij.util.containers.UnsafeWeakList import com.intellij.util.ref.GCUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.NotNull import java.nio.file.Path import java.util.* import java.util.concurrent.TimeUnit private const val MAX_LEAKY_PROJECTS = 5 private val LEAK_CHECK_INTERVAL = TimeUnit.MINUTES.toMillis(30) private var CHECK_START = System.currentTimeMillis() private val LOG_PROJECT_LEAKAGE = System.getProperty("idea.log.leaked.projects.in.tests", "true")!!.toBoolean() var totalCreatedProjectsCount = 0 @ApiStatus.Internal open class TestProjectManager : ProjectManagerExImpl() { companion object { @JvmStatic fun getInstanceExIfCreated(): TestProjectManager? { return ProjectManager.getInstanceIfCreated() as TestProjectManager? } @JvmStatic fun getCreationPlace(project: Project): String { return "$project ${(if (project is ProjectEx) project.creationTrace else null) ?: ""}" } } var totalCreatedProjectCount = 0 private set private val projects = WeakHashMap<Project, String>() @Volatile private var isTracking = false private val trackingProjects = UnsafeWeakList<Project>() override fun newProject(projectFile: Path, options: OpenProjectTask): Project? { checkProjectLeaksInTests() val project = super.newProject(projectFile, options) if (project != null && LOG_PROJECT_LEAKAGE) { projects.put(project, null) } return project } override fun handleErrorOnNewProject(t: Throwable) { throw t } override fun openProject(project: Project): Boolean { if (project is ProjectExImpl && project.isLight) { project.setTemporarilyDisposed(false) val isInitialized = StartupManagerEx.getInstanceEx(project).startupActivityPassed() if (isInitialized) { addToOpened(project) // events already fired return true } } return super.openProject(project) } // method is not used and will be deprecated soon but still have to ensure that every created Project instance is tracked override fun loadProject(file: Path): Project { val project = super.loadProject(file) trackProject(project) return project } private fun trackProject(project: @NotNull Project) { if (isTracking) { synchronized(this) { if (isTracking) { trackingProjects.add(project) } } } } override fun instantiateProject(projectStoreBaseDir: Path, options: OpenProjectTask): ProjectImpl { val project = super.instantiateProject(projectStoreBaseDir, options) totalCreatedProjectCount++ trackProject(project) return project } override fun closeProject(project: Project, saveProject: Boolean, dispose: Boolean, checkCanClose: Boolean): Boolean { if (isTracking) { synchronized(this) { if (isTracking) { trackingProjects.remove(project) } } } val result = super.closeProject(project, saveProject, dispose, checkCanClose) val undoManager = UndoManager.getGlobalInstance() as UndoManagerImpl // test may use WrapInCommand (it is ok - in this case HeavyPlatformTestCase will call dropHistoryInTests) if (!undoManager.isInsideCommand) { undoManager.dropHistoryInTests() } return result } /** * Start tracking of created projects. Call [AccessToken.finish] to stop tracking and assert that no leaked projects. */ @Synchronized fun startTracking(): AccessToken { if (isTracking) { throw IllegalStateException("Tracking is already started") } return object : AccessToken() { override fun finish() { synchronized(this@TestProjectManager) { isTracking = false var error: StringBuilder? = null for (project in trackingProjects) { if (error == null) { error = StringBuilder() } error.append(project.toString()) error.append("\nCreation trace: ") error.append((project as ProjectEx).creationTrace) } trackingProjects.clear() if (error != null) { throw IllegalStateException(error.toString()) } } } } } private fun getLeakedProjectCount() = getLeakedProjects().count() private fun getLeakedProjects(): Sequence<Project> { // process queue projects.remove(DummyProject.getInstance()) return projects.keys.asSequence() } private fun checkProjectLeaksInTests() { if (!LOG_PROJECT_LEAKAGE || getLeakedProjectCount() < MAX_LEAKY_PROJECTS) { return } val currentTime = System.currentTimeMillis() if ((currentTime - CHECK_START) < LEAK_CHECK_INTERVAL) { // check every N minutes return } var i = 0 while (i < 3 && getLeakedProjectCount() >= MAX_LEAKY_PROJECTS) { GCUtil.tryGcSoftlyReachableObjects() i++ } CHECK_START = currentTime if (getLeakedProjectCount() >= MAX_LEAKY_PROJECTS) { System.gc() val copy = getLeakedProjects().toCollection(UnsafeWeakList()) projects.clear() if (copy.iterator().asSequence().count() >= MAX_LEAKY_PROJECTS) { reportLeakedProjects(copy) throw AssertionError("Too many projects leaked, again.") } } } override fun isRunStartUpActivitiesEnabled(project: Project): Boolean { val runStartUpActivitiesFlag = project.getUserData(ProjectExImpl.RUN_START_UP_ACTIVITIES) return runStartUpActivitiesFlag == null || runStartUpActivitiesFlag } } private fun reportLeakedProjects(leakedProjects: Iterable<Project>) { val hashCodes = HashSet<Int>() for (project in leakedProjects) { hashCodes.add(System.identityHashCode(project)) } val dumpPath = publishHeapDump("leakedProjects") val leakers = StringBuilder() leakers.append("Too many projects leaked (hashCodes=$hashCodes): \n") LeakHunter.processLeaks(LeakHunter.allRoots(), ProjectImpl::class.java, { hashCodes.contains(System.identityHashCode(it)) }, { leaked: ProjectImpl?, backLink: Any? -> val hashCode = System.identityHashCode(leaked) leakers.append("Leaked project found:").append(leaked) .append(", hash=").append(hashCode) .append(", place=").append(getCreationPlace(leaked!!)).append('\n') .append(backLink).append('\n') .append("-----\n") hashCodes.remove(hashCode) !hashCodes.isEmpty() }) leakers.append("\nPlease see `").append(dumpPath).append("` for a memory dump") throw AssertionError(leakers.toString()) }
apache-2.0
7f2b63358c1a00a5c08bd4eca7fce874
34.330317
123
0.686988
4.729255
false
true
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/apigateway/src/main/kotlin/com/kotlin/gateway/DeleteRestApi.kt
1
1530
//snippet-sourcedescription:[DeleteRestApi.kt demonstrates how to delete an existing RestApi resource.] //snippet-keyword:[SDK for Kotlin] //snippet-keyword:[Code Sample] //snippet-service:[Amazon API Gateway] //snippet-sourcetype:[full-example] //snippet-sourcedate:[11/03/2021] //snippet-sourceauthor:[scmacdon - aws] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.gateway // snippet-start:[apigateway.kotlin.delete_api.import] import aws.sdk.kotlin.services.apigateway.ApiGatewayClient import aws.sdk.kotlin.services.apigateway.model.DeleteRestApiRequest import kotlin.system.exitProcess // snippet-end:[apigateway.kotlin.delete_api.import] suspend fun main(args:Array<String>) { val usage = """ Usage: <restApiId> Where: restApiId - The string identifier of an existing RestApi. (for example, xxxx99ewyg). """ if (args.size != 1) { println(usage) exitProcess(1) } val restApiId = args[0] deleteAPI(restApiId) } // snippet-start:[apigateway.kotlin.delete_api.main] suspend fun deleteAPI(restApiIdVal: String?) { val request = DeleteRestApiRequest { restApiId = restApiIdVal } ApiGatewayClient { region = "us-east-1" }.use { apiGateway -> apiGateway.deleteRestApi(request) println("The API was successfully deleted") } } // snippet-end:[apigateway.kotlin.delete_api.main]
apache-2.0
4f7ad4aa41c892a68da992a93b8745c0
26.37037
103
0.685621
3.731707
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/streaming/StreamManager.kt
1
6067
package jp.juggler.subwaytooter.streaming import jp.juggler.subwaytooter.AppState import jp.juggler.subwaytooter.api.TootApiCallback import jp.juggler.subwaytooter.api.TootApiClient import jp.juggler.subwaytooter.api.entity.Acct import jp.juggler.subwaytooter.api.entity.TootInstance import jp.juggler.subwaytooter.column.Column import jp.juggler.subwaytooter.pref.PrefB import jp.juggler.subwaytooter.table.HighlightWord import jp.juggler.subwaytooter.table.SavedAccount import jp.juggler.util.LogCategory import jp.juggler.util.launchDefault import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ClosedReceiveChannelException import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean import kotlin.collections.set class StreamManager(val appState: AppState) { companion object { private val log = LogCategory("StreamManager") val traceDelivery = "false".toBoolean() // 画面ONの間は定期的に状況を更新する const val updateInterval = 5000L } val context = appState.context private val queue = Channel<suspend () -> Unit>(capacity = Channel.UNLIMITED) private val handler = appState.handler private val isScreenOn = AtomicBoolean(false) private val acctGroups = ConcurrentHashMap<Acct, StreamGroupAcct>() val client = TootApiClient( appState.context, callback = object : TootApiCallback { override suspend fun isApiCancelled() = false } ) private val updateConnection: suspend () -> Unit = { val isScreenOn = isScreenOn.get() val newMap = HashMap<Acct, StreamGroupAcct>() val errorAcct = HashSet<Acct>() suspend fun prepareAcctGroup(accessInfo: SavedAccount): StreamGroupAcct? { val acct = accessInfo.acct if (errorAcct.contains(acct)) return null var acctGroup = newMap[acct] if (acctGroup == null) { var (ti, ri) = TootInstance.getEx(client, account = accessInfo) if (ti == null) { log.d("can't get server info. ${ri?.error}") val tiOld = acctGroups[acct]?.ti if (tiOld == null) { errorAcct.add(acct) return null } ti = tiOld } acctGroup = StreamGroupAcct(this, accessInfo, ti) newMap[acct] = acctGroup } return acctGroup } if (isScreenOn && !PrefB.bpDontUseStreaming(appState.pref)) { for (column in appState.columnList) { val accessInfo = column.accessInfo if (column.isDispose.get() || column.dontStreaming || accessInfo.isNA) continue prepareAcctGroup(accessInfo)?.let { acctGroup -> column.getStreamDestination()?.let { acctGroup.addSpec(it) } } } } if (newMap.size != acctGroups.size) { log.d("updateConnection: acctGroups.size changed. ${acctGroups.size} => ${newMap.size}") } // 新構成にないサーバは破棄する acctGroups.entries.toList().forEach { if (!newMap.containsKey(it.key)) { it.value.dispose() acctGroups.remove(it.key) } } // 追加.変更されたサーバをマージする newMap.entries.forEach { when (val current = acctGroups[it.key]) { null -> acctGroups[it.key] = it.value.apply { initialize() } else -> current.merge(it.value) } } // ハイライトツリーを読み直す val highlightTrie = HighlightWord.nameSet acctGroups.values.forEach { // パーサーを更新する it.parser.highlightTrie = highlightTrie // 接続を更新する it.updateConnection() } } private val procInterval = object : Runnable { override fun run() { enqueue(updateConnection) handler.removeCallbacks(this) if (isScreenOn.get()) handler.postDelayed(this, updateInterval) } } ////////////////////////////////////////////////// // methods fun enqueue(block: suspend () -> Unit) = launchDefault { queue.send(block) } // UIスレッドから呼ばれる fun updateStreamingColumns() { handler.post(procInterval) } // 画面表示開始時に呼ばれる fun onScreenStart() { isScreenOn.set(true) handler.post(procInterval) } // 画面表示終了時に呼ばれる fun onScreenStop() { isScreenOn.set(false) handler.post(procInterval) } // カラムヘッダの表示更新から、インジケータを取得するために呼ばれる // UIスレッドから呼ばれる // returns StreamStatus.Missing if account is NA or all columns are non-streaming. fun getStreamStatus(column: Column): StreamStatus = acctGroups[column.accessInfo.acct]?.getStreamStatus(column.internalId) ?: StreamStatus.Missing // returns null if account is NA or all columns are non-streaming. fun getConnection(column: Column): StreamConnection? = acctGroups[column.accessInfo.acct]?.getConnection(column.internalId) //////////////////////////////////////////////////////////////// init { launchDefault { while (true) { try { queue.receive().invoke() } catch (_: ClosedReceiveChannelException) { // 発生しない } catch (ex: Throwable) { log.trace(ex, "error.") } } } } }
apache-2.0
0069594ba9a2c8260ae1727f93bd63a6
31.654971
100
0.569765
4.556611
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/features/settings/backup/synchronization/SyncUtils.kt
1
3635
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets.features.settings.backup.synchronization import android.accounts.AccountManager import android.content.ContentResolver import android.content.Context import android.os.Bundle import androidx.core.content.getSystemService import de.dreier.mytargets.BuildConfig import de.dreier.mytargets.features.settings.SettingsManager /** * Static helper methods for working with the sync framework. */ object SyncUtils { private const val ONE_DAY: Long = 86400 // 1 day (in seconds) const val CONTENT_AUTHORITY = BuildConfig.APPLICATION_ID + ".provider" var isSyncAutomaticallyEnabled: Boolean get() { val account = GenericAccountService.account return ContentResolver.getSyncAutomatically(account, CONTENT_AUTHORITY) } set(enabled) { val account = GenericAccountService.account ContentResolver.setSyncAutomatically(account, CONTENT_AUTHORITY, enabled) if (enabled) { ContentResolver.addPeriodicSync( account, CONTENT_AUTHORITY, Bundle(), SettingsManager.backupInterval.days * ONE_DAY ) } else { ContentResolver.removePeriodicSync(account, CONTENT_AUTHORITY, Bundle()) } } /** * Create an entry for this application in the system account list, if it isn't already there. * * @param context Context */ fun createSyncAccount(context: Context) { // Create account, if it's missing. (Either first run, or user has deleted account.) val account = GenericAccountService.account val accountManager = context.getSystemService<AccountManager>()!! if (accountManager.addAccountExplicitly(account, null, null)) { // Inform the system that this account supports sync ContentResolver.setIsSyncable(account, CONTENT_AUTHORITY, 1) // Inform the system that this account is eligible for auto sync when the network is up ContentResolver.setSyncAutomatically(account, CONTENT_AUTHORITY, false) } } /** * Helper method to trigger an immediate sync ("refresh"). * * This should only be used when we need to preempt the normal sync schedule. Typically, this * means the user has pressed the "refresh" button. * * Note that SYNC_EXTRAS_MANUAL will cause an immediate sync, without any optimization to * preserve battery life. If you know new data is available (perhaps via a GCM notification), * but the user is not actively waiting for that data, you should omit this flag; this will give * the OS additional freedom in scheduling your sync request. */ fun triggerBackup() { val b = Bundle() // Disable sync backoff and ignore sync preferences. In other words...perform sync NOW! b.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true) b.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true) ContentResolver.requestSync(GenericAccountService.account, CONTENT_AUTHORITY, b) } }
gpl-2.0
169f4b9f740646edc4584d66f29027aa
40.781609
100
0.69326
4.912162
false
false
false
false
googlecodelabs/tv-recommendations-kotlin
step_1/src/main/java/com/android/tv/classics/workers/TvMediaSynchronizer.kt
1
7766
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tv.classics.workers import android.content.Context import android.net.Uri import android.util.Log import androidx.work.Worker import androidx.work.WorkerParameters import com.android.tv.classics.R import com.android.tv.classics.models.TvMediaBackground import com.android.tv.classics.utils.TvLauncherUtils import com.android.tv.classics.models.TvMediaDatabase import com.android.tv.classics.models.TvMediaMetadata import com.android.tv.classics.models.TvMediaCollection import org.json.JSONArray import org.json.JSONObject import java.nio.charset.StandardCharsets /** Maps a JSONArray of strings */ private fun <T>JSONArray.mapString(transform: (String) -> T): List<T> = (0 until length()).map { transform(getString(it)) } /** Maps a JSONArray of objects */ private fun <T>JSONArray.mapObject(transform: (JSONObject) -> T): List<T> = (0 until length()).map { transform(getJSONObject(it)) } /** Worker that parses metadata from our assets folder and synchronizes the database */ class TvMediaSynchronizer(private val context: Context, params: WorkerParameters) : Worker(context, params) { /** Helper data class used to pass results around functions */ private data class FeedParseResult( val metadata: List<TvMediaMetadata>, val collections: List<TvMediaCollection>, val backgrounds: List<TvMediaBackground>) override fun doWork(): Result = try { synchronize(context) Result.success() } catch (exc: Exception) { Result.failure() } companion object { private val TAG = TvMediaSynchronizer::class.java.simpleName /** Fetches the metadata feed from our assets folder and parses its metadata */ private fun parseMediaFeed(context: Context): FeedParseResult { // Reads JSON input into a JSONArray // We are using a local file, in your app you most likely will be using a remote URL val stream = context.resources.assets.open("media-feed.json") val data = JSONObject( String(stream.readBytes(), StandardCharsets.UTF_8)) // Initializes an empty list to populate with metadata metadata val metadatas: MutableList<TvMediaMetadata> = mutableListOf() // Traverses the feed and maps each collection val feed = data.getJSONArray("feed") val collections = feed.mapObject { obj -> val collection = TvMediaCollection( id = obj.getString("id"), title = obj.getString("title"), description = obj.getString("description"), artUri = obj.getString("image")?.let { Uri.parse(it) }) // Traverses the collection and map each content item metadata val subItemsMetadata = obj.getJSONArray("items").mapObject { subItem -> TvMediaMetadata( collectionId = collection.id, id = subItem.getString("id"), title = subItem.getString("title"), ratings = subItem.optJSONArray("ratings")?.mapString { x -> x }, contentUri = subItem.getString("url")?.let { Uri.parse(it) }!!, playbackDurationMillis = subItem.getLong("duration") * 1000, year = subItem.getInt("year"), author = subItem.getString("director"), description = subItem.getString("description"), artUri = subItem.getString("art")?.let { Uri.parse(it) }) } // Adds all the subitems to the flat list metadatas.addAll(subItemsMetadata) // Returns parsed collection collection } // Gets background images from metadata feed as well val bgArray = data.getJSONArray("backgrounds") val backgrounds = (0 until bgArray.length()).map { idx -> TvMediaBackground("$idx", Uri.parse(bgArray.getString(idx))) } return FeedParseResult(metadatas, collections, backgrounds) } /** Parses metadata from our assets folder and synchronizes the database */ @Synchronized fun synchronize(context: Context) { Log.d(TAG, "Starting synchronization work") val database = TvMediaDatabase.getInstance(context) val feed = parseMediaFeed(context) // Gets a list of the metadata IDs for comparisons val metadataIdList = feed.metadata.map { it.id } // Deletes items in our database that have been deleted from the metadata feed // NOTE: It's important to keep the things added to the TV launcher in sync database.metadata().findAll() .filter { !metadataIdList.contains(it.id) } .forEach { database.metadata().delete(it) // Removes programs no longer present from TV launcher TvLauncherUtils.removeProgram(context, it) // Removes programs no longer present from Watch Next row TvLauncherUtils.removeFromWatchNext(context, it) } database.collections().findAll() .filter { !feed.collections.contains(it) } .forEach { database.collections().delete(it) // Removes channels from TV launcher TvLauncherUtils.removeChannel(context, it) } database.backgrounds().findAll() .filter { !feed.backgrounds.contains(it) } .forEach { database.backgrounds().delete(it) } // Upon insert, we will replace all metadata already added so we can update titles, // images, descriptions, etc. Note that we overloaded the `equals` function in our data // class to avoid replacing metadata which has an updated state such as playback // position. database.metadata().insert(*feed.metadata.toTypedArray()) database.collections().insert(*feed.collections.toTypedArray()) database.backgrounds().insert(*feed.backgrounds.toTypedArray()) // Inserts the first collection as the "default" channel val defaultChannelTitle = context.getString(R.string.default_channel_name) val defaultChannelArtUri = TvLauncherUtils.resourceUri( context.resources, R.mipmap.ic_channel_logo) val defaultChannelCollection = feed.collections.first().copy( title = defaultChannelTitle, artUri = defaultChannelArtUri) val defaultChannelUri = TvLauncherUtils.upsertChannel( context, defaultChannelCollection, database.metadata().findByCollection(defaultChannelCollection.id)) // Inserts the rest of the collections as channels that user can add to home screen // TODO: step 5 add more channels. // TODO: End of step 5. } } }
apache-2.0
9ff2f1ae86967764c56c267cd00b3341
44.952663
99
0.625547
4.965473
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/FinalFieldsEntityImpl.kt
1
7766
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.deft.api.annotations.Default import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class FinalFieldsEntityImpl(val dataSource: FinalFieldsEntityData) : FinalFieldsEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val descriptor: AnotherDataClass get() = dataSource.descriptor override var description: String = dataSource.description override var anotherVersion: Int = dataSource.anotherVersion override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: FinalFieldsEntityData?) : ModifiableWorkspaceEntityBase<FinalFieldsEntity>(), FinalFieldsEntity.Builder { constructor() : this(FinalFieldsEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity FinalFieldsEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isDescriptorInitialized()) { error("Field FinalFieldsEntity#descriptor should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as FinalFieldsEntity this.entitySource = dataSource.entitySource this.descriptor = dataSource.descriptor this.description = dataSource.description this.anotherVersion = dataSource.anotherVersion if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var descriptor: AnotherDataClass get() = getEntityData().descriptor set(value) { checkModificationAllowed() getEntityData().descriptor = value changedProperty.add("descriptor") } override var description: String get() = getEntityData().description set(value) { checkModificationAllowed() getEntityData().description = value changedProperty.add("description") } override var anotherVersion: Int get() = getEntityData().anotherVersion set(value) { checkModificationAllowed() getEntityData().anotherVersion = value changedProperty.add("anotherVersion") } override fun getEntityData(): FinalFieldsEntityData = result ?: super.getEntityData() as FinalFieldsEntityData override fun getEntityClass(): Class<FinalFieldsEntity> = FinalFieldsEntity::class.java } } class FinalFieldsEntityData : WorkspaceEntityData<FinalFieldsEntity>() { lateinit var descriptor: AnotherDataClass var description: String = "Default description" var anotherVersion: Int = 0 fun isDescriptorInitialized(): Boolean = ::descriptor.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<FinalFieldsEntity> { val modifiable = FinalFieldsEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): FinalFieldsEntity { return getCached(snapshot) { val entity = FinalFieldsEntityImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return FinalFieldsEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return FinalFieldsEntity(descriptor, entitySource) { this.description = [email protected] this.anotherVersion = [email protected] } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as FinalFieldsEntityData if (this.entitySource != other.entitySource) return false if (this.descriptor != other.descriptor) return false if (this.description != other.description) return false if (this.anotherVersion != other.anotherVersion) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as FinalFieldsEntityData if (this.descriptor != other.descriptor) return false if (this.description != other.description) return false if (this.anotherVersion != other.anotherVersion) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + descriptor.hashCode() result = 31 * result + description.hashCode() result = 31 * result + anotherVersion.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + descriptor.hashCode() result = 31 * result + description.hashCode() result = 31 * result + anotherVersion.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.add(AnotherDataClass::class.java) collector.sameForAllEntities = true } }
apache-2.0
bbfedc5a7e8569035d8db4c00601d92e
32.765217
133
0.73281
5.507801
false
false
false
false
apache/isis
incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/demo2_0_0/RESTFUL_DOMAIN_TYPES.kt
2
56132
/* * 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 org.apache.causeway.client.kroviz.snapshots.demo2_0_0 import org.apache.causeway.client.kroviz.snapshots.Response object RESTFUL_DOMAIN_TYPES : Response() { override val url = "http://localhost:8080/restful/domain-types" override val str = """ { "links": [ { "rel": "self", "href": "http://localhost:8080/restful/domain-types", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/type-list\"" } ], "values": [ { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.lang.Float", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.value.LocalResourcePath", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewayApplib.MetaModelServicesMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.api.permission.dom.ApplicationPermissionMode", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.EventsDemoMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demoapp.utils.DemoStub", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewayApplib.TranslationServicePoMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.TupleDemoMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.model.dom.user.HasUsername_open", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.time.ZonedDateTime", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewayApplib.SwaggerServiceMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.persistence.jdo.datanucleus.jdosupport.mixins.Persistable_datanucleusVersionTimestamp", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.model.app.user.ApplicationUser_permissions", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.lang.Integer", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demoapp.dom.actions.depargs.DependentArgsActionDemo_useDisable", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.Primitives", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.model.dom.tenancy.ApplicationTenancy_addUser", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.mixins.dto.Dto_downloadXsd", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/tabMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.math.BigDecimal", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.model.dom.permission.ApplicationPermission_viewing", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.lang.Character", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.lang.Long", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.ApplicationRole", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.model.dom.permission.ApplicationPermission_allow", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.api.permission.dom.ApplicationPermission", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.math.BigInteger", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.model.dom.tenancy.ApplicationTenancy_removeUser", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.model.dom.permission.ApplicationPermission_veto", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.model.dom.user.ApplicationUser_addRole", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demoapp.dom.actions.depargs.DependentArgsActionDemo_useChoices", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.TooltipMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewayApplib.ConfigurationProperty", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/byte", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/double", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.mixins.metamodel.Object_objectIdentifier", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.FileNode", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.util.Set", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.valuetypes.asciidoc.applib.value.AsciiDoc", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demoapp.dom.actions.depargs.DependentArgsActionDemo_useAutoComplete", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.core.metamodel.services.appfeat.ApplicationFeature", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.Homepage", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.ApplicationClassMember", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.value.Markup", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.Blob", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.services.bookmark.BookmarkHolder_lookup", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.viewer.wicket.viewer.mixins.Object_clearHints", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demoapp.dom.actions.depargs.DependentArgsActionDemo_useDefault", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.api.role.ApplicationRole", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.AssociatedActionDemoTask", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.services.menu.MenuBarsService.Type", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.lang.Double", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.time.LocalDateTime", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.AsyncAction", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.api.user.ApplicationUserStatus", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demoapp.dom.events.EventsDemo.UiButtonEvent", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/long", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.services.jaxb.JaxbService.CausewaySchemas", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.Errors", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.lang.String", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewayExtFixtures.FixtureScripts", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.ApplicationPermission", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demoapp.dom.types.blob.BlobDemo_downloadLogo", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.mixins.metamodel.Object_downloadMetaModelXml", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.AssociatedAction", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.mixins.metamodel.Object_objectType", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.services.layout.LayoutService.Style", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.model.dom.role.ApplicationRole_addUser", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.testing.fixtures.applib.fixturescripts.FixtureScripts.NonPersistedObjectsStrategy", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.services.swagger.SwaggerService.Visibility", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.NumberConstant", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewayApplib.ConfigurationMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.TupleDemo", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.mixins.dto.Dto_downloadXml", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demoapp.eventLogWriter", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.DependentArgs", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.Jee", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.ApplicationClassCollection", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.joda.time.LocalDateTime", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.mixins.layout.Object_downloadLayoutXml", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.ApplicationPermissionMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/char", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.persistence.jdo.datanucleus.jdosupport.mixins.Persistable_datanucleusIdLong", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.FeaturedTypesMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.api.user.ApplicationUser", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.EventLogEntry", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.api.user.AccountType", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.UserPermissionViewModel", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.util.SortedSet", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.util.Date", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.Tab", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.TreeDemoMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/float", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.persistence.jdo.datanucleus.jdosupport.mixins.Persistable_datanucleusVersionLong", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demoapp.dom.actions.depargs.Parity", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.core.metamodel.services.appfeat.ApplicationFeatureType", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.core.commons.internal.ioc.spring.BeanAdapterSpring", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.lang.Short", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.ApplicationUserMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.time.LocalTime", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.services.bookmark.BookmarkHolder_object", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.testing.fixtures.applib.fixturescripts.FixtureScript", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.lang.Byte", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.value.Blob", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.time.OffsetTime", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.ApplicationClassAction", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.services.swagger.SwaggerService.Format", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.testing.fixtures.applib.fixturescripts.FixtureScriptsSpecification", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.core.commons.collections.Can", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/void", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.ApplicationUser", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.Tooltip", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.sql.Timestamp", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.util.Collection", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.Text", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.model.dom.permission.ApplicationPermission_updateRole", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.ApplicationClassProperty", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.model.dom.permission.ApplicationPermission_changing", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.ApplicationTenancyMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.api.tenancy.ApplicationTenancy", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.util.List", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.Tree", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.time.OffsetDateTime", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.mixins.layout.Object_rebuildMetamodel", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.ApplicationTenancy", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.ApplicationClass", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.graph.Vertex", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.time.LocalDate", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.graph.SimpleEdge", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.Temporal", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewayApplib.LayoutServiceMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.util.SortedMap", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.valuetypes.sse.applib.value.ListeningMarkup", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.value.Clob", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.Events", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.model.dom.permission.ApplicationPermission_delete", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.AbstractService", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.value.Password", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.MeService", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.joda.time.LocalTime", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demoapp.dom.types.tuple.ComplexNumber", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.persistence.jdo.datanucleus.jdosupport.mixins.Persistable_downloadJdoMetadata", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.api.permission.dom.ApplicationPermissionRule", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.lang.Boolean", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.ErrorMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.JeeMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.AsyncDemoTask", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.ApplicationFeatureViewModels", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewayExtFixture.FixtureResult", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.graph.tree.LazyTreeNode", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.model.app.feature.ApplicationFeatureViewModel", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demoapp.dom.tree.FileNode.Type", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.DependentArgsDemoItem", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.joda.time.DateTime", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.AssociatedActionMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.ApplicationPackage", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/int", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.sql.Date", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.joda.time.LocalDate", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.AsyncActionMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demo.DependentArgsActionMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.mixins.layout.Object_openRestApi", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.annotation.SemanticsOf", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/demoapp.dom.actions.depargs.DependentArgsActionDemo_useHide", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.model.app.user.ApplicationUser_filterPermissions", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.applib.graph.tree.TreeNode", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/boolean", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/short", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.model.app.feature.ApplicationPermission_feature", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/causewaysecurity.ApplicationRoleMenu", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.lang.Object", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/java.lang.Class", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.restfulobjects:rels/domain-type", "href": "http://localhost:8080/restful/domain-types/org.apache.causeway.extensions.secman.model.dom.role.ApplicationRole_removeUser", "method": "GET", "type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" } ], "extensions": {} } """ }
apache-2.0
77c78620cb44836d6c33e248adf0feea
51.022243
171
0.592104
3.89508
false
false
false
false
chengpo/my-blog
src/main/java/com/monkeyapp/blog/models/ContentProvider.kt
1
2311
package com.monkeyapp.blog.models import com.monkeyapp.blog.di.BlogParameters import com.monkeyapp.blog.di.InputStreamProvider import org.commonmark.parser.Parser import org.commonmark.renderer.html.HtmlRenderer import java.io.BufferedReader import java.io.InputStreamReader import java.util.stream.Collectors class ContentProvider(private val inputStreamProvider: InputStreamProvider, private val contentReader: ContentReader) { private val htmlFormatter = HtmlFormatter() fun contentOf(path: String): String { return inputStreamProvider .streamOf(path) .let(::InputStreamReader) .let(::BufferedReader) .use(contentReader::read) .let(htmlFormatter::format) } } interface ContentReader { fun read(reader: BufferedReader): String } class CompleteContentReader : ContentReader { override fun read(reader: BufferedReader): String { return reader .lines() .collect(Collectors.joining(System.lineSeparator())) } } class PartialContentReader(private val blogParameters: BlogParameters): ContentReader { override fun read(reader: BufferedReader): String { return reader .lines() .limit(blogParameters.partialFileLines()) .collect(Collectors.joining(System.lineSeparator())) } } class ContentProviderFactory(dependencies: Dependencies) { private val inputStreamProvider = dependencies.inputStreamProvider() private val blogParameters = dependencies.blogParameters() fun completeContentProvider(): ContentProvider { return ContentProvider( inputStreamProvider, CompleteContentReader()) } fun partialContentProvider(): ContentProvider { return ContentProvider( inputStreamProvider, PartialContentReader(blogParameters)) } interface Dependencies { fun inputStreamProvider(): InputStreamProvider fun blogParameters(): BlogParameters } } class HtmlFormatter { private val parser: Parser = Parser.builder().build() private val renderer = HtmlRenderer.builder().build() fun format(markdownContent: String): String { return parser.parse(markdownContent).run(renderer::render) } }
mit
966348cd6e72889184f2deca9b497956
29.813333
87
0.698832
5.101545
false
false
false
false
JetBrains/intellij-community
platform/extensions/src/com/intellij/openapi/extensions/ExtensionPointName.kt
1
11359
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("DeprecatedCallableAddReplaceWith", "ReplaceGetOrSet") package com.intellij.openapi.extensions import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.impl.ExtensionComponentAdapter import com.intellij.openapi.extensions.impl.ExtensionPointImpl import com.intellij.openapi.extensions.impl.ExtensionProcessingHelper.computeIfAbsent import com.intellij.openapi.extensions.impl.ExtensionProcessingHelper.computeSafeIfAny import com.intellij.openapi.extensions.impl.ExtensionProcessingHelper.findFirstSafe import com.intellij.openapi.extensions.impl.ExtensionProcessingHelper.forEachExtensionSafe import com.intellij.openapi.extensions.impl.ExtensionProcessingHelper.getByGroupingKey import com.intellij.openapi.extensions.impl.ExtensionProcessingHelper.getByKey import com.intellij.util.ThreeState import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.NonNls import java.util.concurrent.CancellationException import java.util.function.* import java.util.function.Function import java.util.stream.Stream /** * Provides access to an [extension point](https://www.jetbrains.org/intellij/sdk/docs/basics/plugin_structure/plugin_extension_points.html). Instances of this class can be safely stored in static final fields. * * For project-level and module-level extension points use [ProjectExtensionPointName] instead to make it evident that corresponding * [AreaInstance] must be passed. */ class ExtensionPointName<T : Any>(name: @NonNls String) : BaseExtensionPointName<T>(name) { companion object { @JvmStatic fun <T : Any> create(name: @NonNls String): ExtensionPointName<T> = ExtensionPointName(name) } /** * Consider using [.getExtensionList]. */ val extensions: Array<T> get() = getPointImpl(null).extensions val extensionList: List<T> get() = getPointImpl(null).extensionList /** * Invokes the given consumer for each extension registered in this extension point. Logs exceptions thrown by the consumer. */ fun forEachExtensionSafe(consumer: Consumer<in T>) { forEachExtensionSafe(getPointImpl(null), consumer) } fun findFirstSafe(predicate: Predicate<in T>): T? { return findFirstSafe(predicate, getPointImpl(null)) } fun <R> computeSafeIfAny(processor: Function<in T, out R?>): R? { return computeSafeIfAny(processor, getPointImpl(null)) } val extensionsIfPointIsRegistered: List<T> get() = getExtensionsIfPointIsRegistered(null) fun getExtensionsIfPointIsRegistered(areaInstance: AreaInstance?): List<T> { @Suppress("DEPRECATION") val area = areaInstance?.extensionArea ?: Extensions.getRootArea() return area?.getExtensionPointIfRegistered<T>(name)?.extensionList ?: emptyList() } @Deprecated("Use {@code getExtensionList().stream()}", ReplaceWith("getExtensionList().stream()")) fun extensions(): Stream<T> { return getPointImpl(null).extensions() } fun hasAnyExtensions(): Boolean = getPointImpl(null).size() != 0 /** * Consider using [ProjectExtensionPointName.getExtensions] */ fun getExtensionList(areaInstance: AreaInstance?): List<T> = getPointImpl(areaInstance).extensionList /** * Consider using [ProjectExtensionPointName.getExtensions] */ fun getExtensions(areaInstance: AreaInstance?): Array<T> = getPointImpl(areaInstance).extensions @Deprecated("Use app-level app extension point.") fun extensions(areaInstance: AreaInstance?): Stream<T> { return getPointImpl(areaInstance).extensionList.stream() } @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated("""use {@link #getPoint()} to access application-level extensions and {@link ProjectExtensionPointName#getPoint(AreaInstance)} to access project-level and module-level extensions""") fun getPoint(areaInstance: AreaInstance?): ExtensionPoint<T> = getPointImpl(areaInstance) val point: ExtensionPoint<T> get() = getPointImpl(null) fun <V : T> findExtension(instanceOf: Class<V>): V? { return getPointImpl(null).findExtension(instanceOf, false, ThreeState.UNSURE) } @ApiStatus.Internal fun <V> findExtensions(instanceOf: Class<V>): List<T> { return getPointImpl(null).findExtensions(instanceOf) } fun <V : T> findExtensionOrFail(exactClass: Class<V>): V { return getPointImpl(null).findExtension(exactClass, true, ThreeState.UNSURE)!! } fun <V : T> findFirstAssignableExtension(instanceOf: Class<V>): V? { return getPointImpl(null).findExtension(instanceOf, true, ThreeState.NO) } /** * Do not use it if there is any extension point listener, because in this case behaviour is not predictable - * events will be fired during iteration, and probably it will be not expected. * * Use only for interface extension points, not for bean. * * Due to internal reasons, there is no easy way to implement hasNext in a reliable manner, * so, `next` may return `null` (in this case stop iteration). * * Possible use cases: * 1. Conditional iteration (no need to create all extensions if iteration will be stopped due to some condition). * 2. Iterated only once per application (no need to cache extension list internally). */ @ApiStatus.Internal fun getIterable(): Iterable<T?> = getPointImpl(null) @ApiStatus.Internal fun lazySequence(): Sequence<T> { return getPointImpl(null).iterator().asSequence().filterNotNull() } @ApiStatus.Internal fun processWithPluginDescriptor(consumer: BiConsumer<in T, in PluginDescriptor>) { getPointImpl(null).processWithPluginDescriptor( /* shouldBeSorted = */true, consumer) } fun addExtensionPointListener(listener: ExtensionPointListener<T>, parentDisposable: Disposable?) { getPointImpl(null).addExtensionPointListener(listener, false, parentDisposable) } fun addExtensionPointListener(listener: ExtensionPointListener<T>) { getPointImpl(null).addExtensionPointListener(listener, false, null) } fun addExtensionPointListener(areaInstance: AreaInstance, listener: ExtensionPointListener<T>) { getPointImpl(areaInstance).addExtensionPointListener(listener, false, null) } fun removeExtensionPointListener(listener: ExtensionPointListener<T>) { getPointImpl(null).removeExtensionPointListener(listener) } fun addChangeListener(listener: Runnable, parentDisposable: Disposable?) { getPointImpl(null).addChangeListener(listener, parentDisposable) } /** * Build cache by arbitrary key using provided key to value mapper. Values with the same key merge into list. Return values by key. * * To exclude extension from cache, return null key. * * `cacheId` is required because it's dangerous to rely on identity of functional expressions. * JLS doesn't specify whether a new instance is produced or some common instance is reused for lambda expressions (see 15.27.4). */ @ApiStatus.Experimental fun <K : Any> getByGroupingKey(key: K, cacheId: Class<*>, keyMapper: Function<T, K?>): List<T> { return getByGroupingKey(point = getPointImpl(null), cacheId = cacheId, key = key, keyMapper = keyMapper) } /** * Build cache by arbitrary key using provided key to value mapper. Return value by key. * * To exclude extension from cache, return null key. */ @ApiStatus.Experimental fun <K : Any> getByKey(key: K, cacheId: Class<*>, keyMapper: Function<T, K?>): T? { return getByKey(getPointImpl(null), key, cacheId, keyMapper) } /** * Build cache by arbitrary key using provided key to value mapper. Return value by key. * * To exclude extension from cache, return null key. */ @ApiStatus.Experimental fun <K : Any, V : Any> getByKey(key: K, cacheId: Class<*>, keyMapper: Function<T, K?>, valueMapper: Function<T, V?>): V? { return getByKey(point = getPointImpl(null), key = key, cacheId = cacheId, keyMapper = keyMapper, valueMapper = valueMapper) } @ApiStatus.Experimental fun <K : Any, V : Any> computeIfAbsent(key: K, cacheId: Class<*>, valueMapper: Function<K, V>): V { return computeIfAbsent(point = getPointImpl(null), key = key, cacheId = cacheId, valueProducer = valueMapper) } /** * Cache some value per extension point. */ @ApiStatus.Experimental fun <V : Any> computeIfAbsent(cacheId: Class<*>, valueMapper: Supplier<V>): V { return computeIfAbsent(getPointImpl(null), cacheId, valueMapper) } @ApiStatus.Internal interface LazyExtension<T> { val id: String? val instance: T? val implementationClassName: String val implementationClass: Class<T>? val pluginDescriptor: PluginDescriptor } @ApiStatus.Internal fun filterableLazySequence(): Sequence<LazyExtension<T>> { val point = getPointImpl(null) val adapters = point.sortedAdapters return LazyExtensionSequence(point = point, adapters = adapters) } private class LazyExtensionSequence<T : Any>( private val point: ExtensionPointImpl<T>, private val adapters: List<ExtensionComponentAdapter>, ) : Sequence<LazyExtension<T>> { override fun iterator(): Iterator<LazyExtension<T>> { return object : Iterator<LazyExtension<T>> { private var currentIndex = 0 override fun next(): LazyExtension<T> { val adapter = adapters.get(currentIndex++) return object : LazyExtension<T> { override val id: String? get() = adapter.orderId override val instance: T? get() = createOrError(adapter = adapter, point = point) override val implementationClassName: String get() = adapter.assignableToClassName override val implementationClass: Class<T>? get() { try { return adapter.getImplementationClass(point.componentManager) } catch (e: CancellationException) { throw e } catch (e: Throwable) { logger<ExtensionPointName<T>>().error(point.componentManager.createError(e, adapter.pluginDescriptor.pluginId)) return null } } override val pluginDescriptor: PluginDescriptor get() = adapter.pluginDescriptor } } override fun hasNext(): Boolean = currentIndex < adapters.size } } } @ApiStatus.Internal inline fun processExtensions(consumer: (extension: T, pluginDescriptor: PluginDescriptor) -> Unit) { val point = getPointImpl(null) for (adapter in point.sortedAdapters) { val extension = createOrError(adapter, point) ?: continue consumer(extension, adapter.pluginDescriptor) } } } @PublishedApi internal fun <T : Any> createOrError(adapter: ExtensionComponentAdapter, point: ExtensionPointImpl<T>): T? { try { return adapter.createInstance(point.componentManager) } catch (e: CancellationException) { throw e } catch (e: Throwable) { logger<ExtensionPointName<T>>().error(point.componentManager.createError(e, adapter.pluginDescriptor.pluginId)) return null } }
apache-2.0
b15e3959b4e99ee23132f8e07592cd59
37.771331
210
0.715116
4.480868
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/ui/compose/settings/SettingsViewModel.kt
1
6925
package com.nononsenseapps.feeder.ui.compose.settings import android.app.Application import android.os.PowerManager import androidx.compose.runtime.Immutable import androidx.core.content.getSystemService import androidx.lifecycle.viewModelScope import com.nononsenseapps.feeder.archmodel.DarkThemePreferences import com.nononsenseapps.feeder.archmodel.FeedItemStyle import com.nononsenseapps.feeder.archmodel.ItemOpener import com.nononsenseapps.feeder.archmodel.LinkOpener import com.nononsenseapps.feeder.archmodel.Repository import com.nononsenseapps.feeder.archmodel.SortingOptions import com.nononsenseapps.feeder.archmodel.SwipeAsRead import com.nononsenseapps.feeder.archmodel.SyncFrequency import com.nononsenseapps.feeder.archmodel.ThemeOptions import com.nononsenseapps.feeder.base.DIAwareViewModel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.buffer import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import org.kodein.di.DI import org.kodein.di.instance class SettingsViewModel(di: DI) : DIAwareViewModel(di) { private val repository: Repository by instance() private val context: Application by instance() fun setCurrentTheme(value: ThemeOptions) { repository.setCurrentTheme(value) } fun setPreferredDarkTheme(value: DarkThemePreferences) { repository.setPreferredDarkTheme(value) } fun setCurrentSorting(value: SortingOptions) { repository.setCurrentSorting(value) } fun setShowFab(value: Boolean) { repository.setShowFab(value) } fun setSyncOnResume(value: Boolean) { repository.setSyncOnResume(value) } fun setSyncOnlyOnWifi(value: Boolean) = viewModelScope.launch { repository.setSyncOnlyOnWifi(value) } fun setSyncOnlyWhenCharging(value: Boolean) = viewModelScope.launch { repository.setSyncOnlyWhenCharging(value) } fun setLoadImageOnlyOnWifi(value: Boolean) { repository.setLoadImageOnlyOnWifi(value) } fun setShowThumbnails(value: Boolean) { repository.setShowThumbnails(value) } fun setUseDetectLanguage(value: Boolean) { repository.setUseDetectLanguage(value) } fun setUseDynamicTheme(value: Boolean) { repository.setUseDynamicTheme(value) } fun setMaxCountPerFeed(value: Int) { repository.setMaxCountPerFeed(value) } fun setItemOpener(value: ItemOpener) { repository.setItemOpener(value) } fun setLinkOpener(value: LinkOpener) { repository.setLinkOpener(value) } fun setSyncFrequency(value: SyncFrequency) = viewModelScope.launch { repository.setSyncFrequency(value) } fun setFeedItemStyle(value: FeedItemStyle) { repository.setFeedItemStyle(value) } fun setBlockList(value: Iterable<String>) { repository.setBlockList(value) } fun setSwipeAsRead(value: SwipeAsRead) { repository.setSwipeAsRead(value) } private val batteryOptimizationIgnoredFlow: Flow<Boolean> = repository.resumeTime.map { val powerManager: PowerManager? = context.getSystemService() powerManager?.isIgnoringBatteryOptimizations(context.packageName) == true }.buffer(1) private val _viewState = MutableStateFlow(SettingsViewState()) val viewState: StateFlow<SettingsViewState> get() = _viewState.asStateFlow() init { viewModelScope.launch { combine( repository.currentTheme, repository.preferredDarkTheme, repository.currentSorting, repository.showFab, repository.syncOnResume, repository.syncOnlyOnWifi, repository.syncOnlyWhenCharging, repository.loadImageOnlyOnWifi, repository.showThumbnails, repository.maximumCountPerFeed, repository.itemOpener, repository.linkOpener, repository.syncFrequency, batteryOptimizationIgnoredFlow, repository.feedItemStyle, repository.swipeAsRead, repository.blockList, repository.useDetectLanguage, repository.useDynamicTheme, ) { params: Array<Any> -> @Suppress("UNCHECKED_CAST") SettingsViewState( currentTheme = params[0] as ThemeOptions, darkThemePreference = params[1] as DarkThemePreferences, currentSorting = params[2] as SortingOptions, showFab = params[3] as Boolean, syncOnResume = params[4] as Boolean, syncOnlyOnWifi = params[5] as Boolean, syncOnlyWhenCharging = params[6] as Boolean, loadImageOnlyOnWifi = params[7] as Boolean, showThumbnails = params[8] as Boolean, maximumCountPerFeed = params[9] as Int, itemOpener = params[10] as ItemOpener, linkOpener = params[11] as LinkOpener, syncFrequency = params[12] as SyncFrequency, batteryOptimizationIgnored = params[13] as Boolean, feedItemStyle = params[14] as FeedItemStyle, swipeAsRead = params[15] as SwipeAsRead, blockList = params[16] as Set<String>, useDetectLanguage = params[17] as Boolean, useDynamicTheme = params[18] as Boolean, ) }.collect { _viewState.value = it } } } } @Immutable data class SettingsViewState( val currentTheme: ThemeOptions = ThemeOptions.SYSTEM, val darkThemePreference: DarkThemePreferences = DarkThemePreferences.BLACK, val currentSorting: SortingOptions = SortingOptions.NEWEST_FIRST, val showFab: Boolean = true, val feedItemStyle: FeedItemStyle = FeedItemStyle.CARD, val blockList: Set<String> = emptySet(), val syncOnResume: Boolean = false, val syncOnlyOnWifi: Boolean = false, val syncOnlyWhenCharging: Boolean = false, val loadImageOnlyOnWifi: Boolean = false, val showThumbnails: Boolean = false, val maximumCountPerFeed: Int = 100, val itemOpener: ItemOpener = ItemOpener.READER, val linkOpener: LinkOpener = LinkOpener.CUSTOM_TAB, val syncFrequency: SyncFrequency = SyncFrequency.EVERY_1_HOURS, val batteryOptimizationIgnored: Boolean = false, val swipeAsRead: SwipeAsRead = SwipeAsRead.ONLY_FROM_END, val useDetectLanguage: Boolean = true, val useDynamicTheme: Boolean = true, )
gpl-3.0
ea37454354286df866a880e6eb5fe1f0
35.835106
91
0.679278
4.84944
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/toolboks/i18n/Localization.kt
2
5294
package io.github.chrislo27.toolboks.i18n import com.badlogic.gdx.Gdx import com.badlogic.gdx.files.FileHandle import com.badlogic.gdx.utils.I18NBundle import com.badlogic.gdx.utils.Json import com.badlogic.gdx.utils.ObjectMap import io.github.chrislo27.toolboks.Toolboks import java.util.* import kotlin.properties.Delegates /** * Pretties up the libGDX localization system. */ object Localization { val DEFAULT_BASE_HANDLE: FileHandle by lazy { Gdx.files.internal("localization/default") } val DEFAULT_LANG_DEFINITION_FILE: FileHandle by lazy { Gdx.files.internal("localization/langs.json") } var currentIndex: Int by Delegates.observable(0) { _, old, _ -> listeners.keys.forEach { it.invoke(bundles[old]) } } var currentBundle: ToolboksBundle get() { return bundles[currentIndex] } set(value) { val index = bundles.indexOf(value) if (index != -1) { currentIndex = index } } val bundles: MutableList<ToolboksBundle> = mutableListOf() private val listeners: MutableMap<(oldBundle: ToolboksBundle) -> Unit, Unit> = HashMap() /** * Base, Lang */ private var lastLoadedFiles: Pair<FileHandle, FileHandle> = DEFAULT_BASE_HANDLE to DEFAULT_LANG_DEFINITION_FILE fun addListener(listener: (oldBundle: ToolboksBundle) -> Unit) { listeners[listener] = Unit } fun removeListener(listener: (oldBundle: ToolboksBundle) -> Unit) { listeners.remove(listener, Unit) } fun createBundle(locale: NamedLocale, baseHandle: FileHandle = DEFAULT_BASE_HANDLE): ToolboksBundle { return ToolboksBundle(locale, I18NBundle.createBundle(baseHandle, locale.locale, "UTF-8")) } fun getBundlesFromLangFile(langDefFile: FileHandle = DEFAULT_LANG_DEFINITION_FILE, baseHandle: FileHandle = DEFAULT_BASE_HANDLE): List<ToolboksBundle> { lastLoadedFiles = baseHandle to langDefFile return Json().fromJson(Array<LanguageObject>::class.java, langDefFile) .map(LanguageObject::toNamedLocale) .map { createBundle(it, baseHandle) } } fun loadBundlesFromLangFile(langDefFile: FileHandle = DEFAULT_LANG_DEFINITION_FILE, baseHandle: FileHandle = DEFAULT_BASE_HANDLE): List<ToolboksBundle> { val list = getBundlesFromLangFile(langDefFile, baseHandle) bundles.clear() bundles.addAll(list) return list } @Suppress("UNCHECKED_CAST") fun logMissingLocalizations() { val keys: List<String> = bundles.firstOrNull()?.bundle?.let { bundle -> val field = bundle::class.java.getDeclaredField("properties") field.isAccessible = true val map = field.get(bundle) as ObjectMap<String, String> map.keys().toList() } ?: return val missing: List<Pair<ToolboksBundle, List<String>>> = bundles.drop(1).map { tbundle -> val bundle = tbundle.bundle val field = bundle::class.java.getDeclaredField("properties") field.isAccessible = true val map = field.get(bundle) as ObjectMap<String, String> tbundle to (keys.map { key -> if (!map.containsKey(key)) { key } else { "" } }.filter { !it.isBlank() }).sorted() } missing.filter { it.second.isNotEmpty() }.forEach { Toolboks.LOGGER.warn("Missing ${it.second.size} keys for bundle ${it.first.locale}:${it.second.joinToString( separator = "") { "\n * $it" }}") } } fun reloadAll(loadFromLangDef: Boolean) { if (!loadFromLangDef) { val old = bundles.toList() bundles.clear() old.mapTo(bundles) { createBundle(it.locale) } } else { loadBundlesFromLangFile(lastLoadedFiles.second, lastLoadedFiles.first) } } fun cycle(direction: Int) { if (bundles.isEmpty()) { error("No bundles found") } currentIndex = (currentIndex + direction).let { (if (it < 0) { bundles.size - 1 } else if (it >= bundles.size) { 0 } else { it }) } } private fun checkMissing(key: String): Boolean { if (currentBundle.missing[key] != null) { return true } try { currentBundle.bundle[key] } catch (e: MissingResourceException) { currentBundle.missing[key] = true Toolboks.LOGGER.warn("Missing content for I18N key $key in bundle ${currentBundle.locale}") return true } return false } operator fun get(key: String): String { if (checkMissing(key)) return key return currentBundle.bundle[key] } operator fun get(key: String, vararg args: Any?): String { if (checkMissing(key)) return key return currentBundle.bundle.format(key, *args) } }
gpl-3.0
1dc3b845381bceda28828c85af6f659f
30.517857
120
0.582735
4.400665
false
false
false
false
allotria/intellij-community
plugins/ide-features-trainer/src/training/learn/lesson/general/refactorings/RefactoringMenuLessonBase.kt
2
2626
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.learn.lesson.general.refactorings import com.intellij.idea.ActionsBundle import com.intellij.refactoring.rename.inplace.InplaceRefactoring import com.intellij.ui.components.JBList import training.dsl.* import training.dsl.LessonUtil.restoreIfModifiedOrMoved import training.learn.LessonsBundle import training.learn.course.KLesson import training.util.adaptToNotNativeLocalization import javax.swing.JList abstract class RefactoringMenuLessonBase(lessonId: String) : KLesson(lessonId, LessonsBundle.message("refactoring.menu.lesson.name")) { fun LessonContext.extractParameterTasks() { lateinit var showPopupTaskId: TaskContext.TaskId actionTask("Refactorings.QuickListPopupAction") { showPopupTaskId = taskId restoreIfModifiedOrMoved() LessonsBundle.message("refactoring.menu.show.refactoring.list", action(it)) } if (!adaptToNotNativeLocalization) { task(ActionsBundle.message("action.IntroduceParameter.text").dropMnemonic()) { text(LessonsBundle.message("refactoring.menu.introduce.parameter.eng", strong(it))) triggerByUiComponentAndHighlight(highlightBorder = false, highlightInside = false) { ui: JList<*> -> ui.model.size > 0 && ui.model.getElementAt(0).toString().contains(it) } restoreAfterStateBecomeFalse { focusOwner !is JBList<*> } test { type("pa") } } } task("IntroduceParameter") { val message = if (adaptToNotNativeLocalization) { LessonsBundle.message("refactoring.menu.introduce.parameter", strong(ActionsBundle.message("action.IntroduceParameter.text").dropMnemonic()), LessonUtil.rawEnter()) } else LessonsBundle.message("refactoring.menu.start.refactoring", action("EditorChooseLookupItem"), LessonUtil.actionName(it)) text(message) trigger(it) stateCheck { hasInplaceRename() } restoreState(delayMillis = defaultRestoreDelay, restoreId = showPopupTaskId) { focusOwner !is JBList<*> } test { invokeActionViaShortcut("ENTER") } } task { text(LessonsBundle.message("refactoring.menu.finish.refactoring", LessonUtil.rawEnter())) stateCheck { !hasInplaceRename() } test(waitEditorToBeReady = false) { invokeActionViaShortcut("ENTER") } } } private fun TaskRuntimeContext.hasInplaceRename() = editor.getUserData(InplaceRefactoring.INPLACE_RENAMER) != null }
apache-2.0
7a173d831747f0329855c9f09bb6464d
40.68254
140
0.720107
4.871985
false
false
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/refactoring/rename/impl/FileUpdates.kt
2
4809
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.refactoring.rename.impl import com.intellij.injected.editor.DocumentWindow import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.refactoring.suggested.range import com.intellij.util.DocumentUtil import com.intellij.util.io.write import com.intellij.util.text.StringOperation import org.jetbrains.annotations.ApiStatus import java.nio.file.Path @ApiStatus.Internal class FileUpdates( val filesToAdd: List<Pair<Path, CharSequence>>, val filesToMove: List<Pair<VirtualFile, Path>>, val filesToRemove: List<VirtualFile>, val documentModifications: List<Pair<RangeMarker, CharSequence>> ) { fun doUpdate() { ApplicationManager.getApplication().assertWriteAccessAllowed() for (virtualFile: VirtualFile in filesToRemove) { if (!virtualFile.isValid) { LOG.warn("Cannot apply rename patch: invalid file to remove. File: $virtualFile") continue } virtualFile.delete(this) } val byDocument = documentModifications.groupBy { (rangeMarker: RangeMarker, _) -> rangeMarker.document } for ((document: Document, modifications: List<Pair<RangeMarker, CharSequence>>) in byDocument) { DocumentUtil.executeInBulk(document, true) { for ((rangeMarker: RangeMarker, replacement: CharSequence) in modifications) { if (!rangeMarker.isValid) { LOG.warn("Cannot apply rename patch: invalid range marker. Document: $document, marker: $rangeMarker") continue } document.replaceString(rangeMarker.startOffset, rangeMarker.endOffset, replacement) rangeMarker.dispose() } } } for ((virtualFile: VirtualFile, path: Path) in filesToMove) { if (!virtualFile.isValid) { LOG.warn("Cannot apply rename patch: invalid file to move. File: $virtualFile") continue } val parentPath: Path = path.parent ?: continue val parentFile: VirtualFile = VfsUtil.findFile(parentPath, false) ?: continue virtualFile.move(this, parentFile) val newFileName: String = path.fileName.toString() if (virtualFile.name != newFileName) { virtualFile.rename(this, newFileName) } } for ((path: Path, content: CharSequence) in filesToAdd) { path.write(content) } } fun preview(): Map<VirtualFile, CharSequence> { ApplicationManager.getApplication().assertReadAccessAllowed() val byDocument = documentModifications.groupBy { (rangeMarker: RangeMarker, _) -> rangeMarker.document } val documentOperations = HashMap<Document, MutableList<StringOperation>>(byDocument.size) for ((document: Document, modifications: List<Pair<RangeMarker, CharSequence>>) in byDocument) { val operations: List<StringOperation> = modifications.mapNotNull { (rangeMarker: RangeMarker, replacement: CharSequence) -> rangeMarker.range?.let { range -> StringOperation.replace(range, replacement) } } if (document is DocumentWindow) { documentOperations.getOrPut(document.delegate) { ArrayList() } += operations.flatMap { operation -> val range = operation.range document.prepareReplaceString(range.startOffset, range.endOffset, operation.replacement) } } else { documentOperations.getOrPut(document) { ArrayList() } += operations } } val fileText = HashMap<VirtualFile, CharSequence>(byDocument.size) for ((document, operations) in documentOperations) { check(document !is DocumentWindow) val virtualFile: VirtualFile = requireNotNull(FileDocumentManager.getInstance().getFile(document)) fileText[virtualFile] = StringOperation.applyOperations(document.charsSequence, operations) } return fileText } companion object { internal val LOG: Logger = Logger.getInstance(FileUpdates::class.java) fun merge(left: FileUpdates?, right: FileUpdates?): FileUpdates? { return when { left == null -> right right == null -> left else -> FileUpdates( filesToAdd = left.filesToAdd + right.filesToAdd, filesToMove = left.filesToMove + right.filesToMove, filesToRemove = left.filesToRemove + right.filesToRemove, documentModifications = left.documentModifications + right.documentModifications ) } } } }
apache-2.0
5c73d99db860590d363ad5487017cdaf
39.411765
140
0.707424
4.728614
false
false
false
false
leafclick/intellij-community
platform/object-serializer/src/IonObjectSerializer.kt
1
7503
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.serialization import com.amazon.ion.IonException import com.amazon.ion.IonType import com.amazon.ion.IonWriter import com.amazon.ion.impl.bin._Private_IonManagedBinaryWriterBuilder import com.amazon.ion.system.IonReaderBuilder import com.amazon.ion.system.IonTextWriterBuilder import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.util.ParameterizedTypeImpl import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.lang.reflect.Type import java.nio.file.Path import kotlin.experimental.or private const val FORMAT_VERSION = 3 internal class IonObjectSerializer { val readerBuilder: IonReaderBuilder = IonReaderBuilder.standard().immutable() // by default only fields (including private) private val propertyCollector = PropertyCollector(PropertyCollector.COLLECT_PRIVATE_FIELDS or PropertyCollector.COLLECT_FINAL_FIELDS) internal val bindingProducer = IonBindingProducer(propertyCollector) @Throws(IOException::class) fun writeVersioned(obj: Any, out: OutputStream, expectedVersion: Int, configuration: WriteConfiguration = defaultWriteConfiguration, originalType: Type? = null) { createIonWriterBuilder(configuration.binary, out).use { writer -> writer.stepIn(IonType.STRUCT) writer.setFieldName("version") writer.writeInt(expectedVersion.toLong()) writer.setFieldName("formatVersion") writer.writeInt(FORMAT_VERSION.toLong()) writer.setFieldName("data") doWrite(obj, writer, configuration, originalType) writer.stepOut() } } @Throws(IOException::class) fun <T : Any> readVersioned(objectClass: Class<T>, input: InputStream, inputName: Path, expectedVersion: Int, configuration: ReadConfiguration, originalType: Type? = null): T? { readerBuilder.build(input).use { reader -> @Suppress("UNUSED_VARIABLE") var isVersionChecked = 0 fun logVersionMismatch(prefix: String, currentVersion: Int) { LOG.info("$prefix version mismatch (file=$inputName, currentVersion: $currentVersion, expectedVersion=$expectedVersion, objectClass=$objectClass)") } try { reader.next() } catch (e: IonException) { // corrupted file LOG.debug(e) return null } reader.stepIn() while (reader.next() != null) { when (val fieldName = reader.fieldName) { "version" -> { val currentVersion = reader.intValue() if (currentVersion != expectedVersion) { logVersionMismatch("App", currentVersion) return null } @Suppress("UNUSED_CHANGED_VALUE") isVersionChecked++ } "formatVersion" -> { val currentVersion = reader.intValue() if (currentVersion != FORMAT_VERSION) { logVersionMismatch("Format", currentVersion) return null } @Suppress("UNUSED_CHANGED_VALUE") isVersionChecked++ } "data" -> { if (isVersionChecked != 2) { // if version was not specified - consider data as invalid return null } val context = createReadContext(reader, configuration) try { return doRead(objectClass, originalType, context) } finally { context.errors.report(LOG) } } else -> LOG.warn("Unknown field: $fieldName (file=$inputName, expectedVersion=$expectedVersion, objectClass=$objectClass)") } } reader.stepOut() return null } } fun write(obj: Any, out: OutputStream, configuration: WriteConfiguration = defaultWriteConfiguration, originalType: Type? = null) { createIonWriterBuilder(configuration.binary, out).use { writer -> doWrite(obj, writer, configuration, originalType) } } private fun doWrite(obj: Any, writer: IonWriter, configuration: WriteConfiguration, originalType: Type?) { val aClass = obj.javaClass val writeContext = WriteContext(writer, configuration.filter ?: DEFAULT_FILTER, ObjectIdWriter(), configuration, bindingProducer) bindingProducer.getRootBinding(aClass, originalType ?: aClass).serialize(obj, writeContext) } fun <T> read(objectClass: Class<T>, reader: ValueReader, configuration: ReadConfiguration, originalType: Type? = null): T { reader.use { reader.next() val context = createReadContext(reader, configuration) try { return doRead(objectClass, originalType, context) } finally { context.errors.report(LOG) } } } // reader cursor must be already pointed to struct private fun <T> doRead(objectClass: Class<T>, originalType: Type?, context: ReadContext): T { when (context.reader.type) { IonType.NULL -> throw SerializationException("root value is null") null -> throw SerializationException("empty input") else -> { val binding = bindingProducer.getRootBinding(objectClass, originalType ?: objectClass) @Suppress("UNCHECKED_CAST") return binding.deserialize(context, hostObject = null) as T } } } fun <T> readList(itemClass: Class<T>, reader: ValueReader, configuration: ReadConfiguration): List<T> { @Suppress("UNCHECKED_CAST") return read(List::class.java, reader, configuration, ParameterizedTypeImpl(List::class.java, itemClass)) as List<T> } private fun createReadContext(reader: ValueReader, configuration: ReadConfiguration): ReadContext { return ReadContextImpl(reader, ObjectIdReader(), bindingProducer, configuration) } } private val DEFAULT_FILTER = object : SerializationFilter { override fun isSkipped(value: Any?) = false } private data class ReadContextImpl(override val reader: ValueReader, override val objectIdReader: ObjectIdReader, override val bindingProducer: BindingProducer, override val configuration: ReadConfiguration) : ReadContext { private var byteArrayOutputStream: BufferExposingByteArrayOutputStream? = null override val errors = ReadErrors() override fun allocateByteArrayOutputStream(): BufferExposingByteArrayOutputStream { var result = byteArrayOutputStream if (result == null) { result = BufferExposingByteArrayOutputStream(8 * 1024) byteArrayOutputStream = result } else { result.reset() } return result } override fun createSubContext(reader: ValueReader) = ReadContextImpl(reader, objectIdReader, bindingProducer, configuration) } internal val binaryWriterBuilder by lazy { val binaryWriterBuilder = _Private_IonManagedBinaryWriterBuilder .create(PooledBlockAllocatorProvider()) .withPaddedLengthPreallocation(0) .withStreamCopyOptimization(true) binaryWriterBuilder } private val textWriterBuilder by lazy { // line separator is not configurable and platform-dependent (https://github.com/amzn/ion-java/issues/57) IonTextWriterBuilder.pretty().immutable() } private fun createIonWriterBuilder(binary: Boolean, out: OutputStream): IonWriter { return when { binary -> binaryWriterBuilder.newWriter(out) else -> textWriterBuilder.build(out) } }
apache-2.0
c2dc5dcf0c0a986362f8f5a117f78074
35.965517
179
0.690924
4.724811
false
true
false
false
zdary/intellij-community
platform/built-in-server/src/org/jetbrains/ide/ToolboxRestService.kt
1
6952
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.ide import com.google.gson.JsonElement import com.google.gson.JsonObject import com.google.gson.JsonParser import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.util.Disposer import com.intellij.util.concurrency.AppExecutorUtil import io.netty.buffer.Unpooled import io.netty.channel.ChannelHandlerContext import io.netty.handler.codec.http.* import io.netty.util.concurrent.Future import io.netty.util.concurrent.GenericFutureListener import org.jetbrains.io.addCommonHeaders import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit val toolboxHandlerEP: ExtensionPointName<ToolboxServiceHandler<*>> = ExtensionPointName.create("com.intellij.toolboxServiceHandler") interface ToolboxServiceHandler<T> { /** * Specifies a request, it is actually the last part of the path, * e.g. `http://localhost:port/api/toolbox/update-notification */ val requestName : String /** * This method is executed synchronously for the handler to parser * request parameters, it may throw an exception on malformed inputs, */ fun parseRequest(request: JsonElement) : T /** * This function is executes on a background thread to handle a Toolbox * request. The implementation allows to send a response after a long * while back to Toolbox. * * The [lifetime] should be used to bind all necessary * resources to the underlying Toolbox connection. It can * be disposed during the execution of this method. * * Use the [onResult] to pass a result back to Toolbox and * to close the connection. The [lifetime] is disposed after * the connection is closed too, it must not be used after [onResult] * callback is executed */ fun handleToolboxRequest( lifetime: Disposable, request: T, onResult: (JsonElement) -> Unit, ) } private fun findToolboxHandlerByUri(requestUri: String): ToolboxServiceHandler<*>? = toolboxHandlerEP.findFirstSafe { requestUri.endsWith("/" + it.requestName.trim('/')) } private fun interface ToolboxInnerHandler { fun handleToolboxRequest( lifetime: Disposable, onResult: (JsonElement) -> Unit, ) } private fun <T> wrapHandler(handler: ToolboxServiceHandler<T>, request: JsonElement): ToolboxInnerHandler { val param = handler.parseRequest(request) return object : ToolboxInnerHandler { override fun handleToolboxRequest(lifetime: Disposable, onResult: (JsonElement) -> Unit) { handler.handleToolboxRequest(lifetime, param, onResult) } override fun toString(): String = "ToolboxInnerHandler{$handler, $param}" } } internal class ToolboxRestService : RestService() { internal companion object { @Suppress("SSBasedInspection") private val LOG = logger<ToolboxRestService>() } override fun getServiceName() = "toolbox" override fun isSupported(request: FullHttpRequest): Boolean { val token = System.getProperty("toolbox.notification.token") ?: return false if (request.headers()["Authorization"] != "toolbox $token") return false val requestUri = request.uri().substringBefore('?') if (findToolboxHandlerByUri(requestUri) == null) return false return super.isSupported(request) } override fun isMethodSupported(method: HttpMethod) = method == HttpMethod.POST override fun execute(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): String? { val requestJson = createJsonReader(request).use { JsonParser.parseReader(it) } val channel = context.channel() val toolboxRequest : ToolboxInnerHandler = try { val handler = findToolboxHandlerByUri(urlDecoder.path()) if (handler == null) { sendStatus(HttpResponseStatus.NOT_FOUND, false, channel) return null } wrapHandler(handler, requestJson) } catch (t: Throwable) { LOG.warn("Failed to process parameters of $request. ${t.message}", t) sendStatus(HttpResponseStatus.BAD_REQUEST, false, channel) return null } val lifetime = Disposer.newDisposable("toolbox-service-request") val response = DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK) response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=utf-8") response.addCommonHeaders() response.headers().remove(HttpHeaderNames.ACCEPT_RANGES) response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, must-revalidate") //NON-NLS response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED) response.headers().set(HttpHeaderNames.LAST_MODIFIED, Date(Calendar.getInstance().timeInMillis)) channel.write(response) val heartbeatDelay = System.getProperty("toolbox.heartbeat.millis", "1000").toLong() val heartbeat = context.executor().scheduleWithFixedDelay( object: Runnable { private fun handleError(t: Throwable) { LOG.debug("Failed to write next heartbeat. ${t.message}", t) Disposer.dispose(lifetime) } private val futureListener = GenericFutureListener<Future<in Void>> { f -> f.cause()?.let { t -> handleError(t) } } override fun run() { try { channel .writeAndFlush(Unpooled.copiedBuffer(" ", Charsets.UTF_8)) .addListener(futureListener) } catch (t: Throwable) { handleError(t) } } }, heartbeatDelay, heartbeatDelay, TimeUnit.MILLISECONDS) Disposer.register(lifetime) { heartbeat.cancel(false) } val callback = CompletableFuture<JsonElement?>() AppExecutorUtil.getAppExecutorService().submit { toolboxRequest.handleToolboxRequest(lifetime) { r -> callback.complete(r) } } callback .exceptionally { e -> LOG.warn("The future completed with exception. ${e.message}", e) JsonObject().apply { addProperty("status", "error") } } .thenAcceptAsync( { json -> //kill the heartbeat, it may close the lifetime too runCatching { heartbeat.cancel(false) heartbeat.await() } //no need to do anything if it's already disposed if (Disposer.isDisposed(lifetime)) { //closing the channel just in case runCatching { channel.close() } return@thenAcceptAsync } runCatching { channel.write(Unpooled.copiedBuffer(gson.toJson(json), Charsets.UTF_8)) } runCatching { channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT) } Disposer.dispose(lifetime) }, AppExecutorUtil.getAppExecutorService() ) return null } }
apache-2.0
7bda3411d9ac88745f5084a7a6a346ca
36.176471
140
0.704977
4.564675
false
false
false
false
romannurik/muzei
main/src/main/java/com/google/android/apps/muzei/TutorialFragment.kt
1
6143
/* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei import android.Manifest import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.graphics.drawable.AnimatedVectorDrawable import android.os.Build import android.os.Bundle import android.util.TypedValue import android.view.View import android.view.animation.OvershootInterpolator import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.launch import androidx.activity.result.registerForActivityResult import androidx.annotation.RequiresApi import androidx.core.animation.doOnEnd import androidx.core.content.edit import androidx.core.content.res.ResourcesCompat import androidx.fragment.app.Fragment import androidx.preference.PreferenceManager import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.analytics import com.google.firebase.ktx.Firebase import net.nurik.roman.muzei.R import net.nurik.roman.muzei.databinding.TutorialFragmentBinding class TutorialFragment : Fragment(R.layout.tutorial_fragment) { companion object { const val PREF_SEEN_TUTORIAL = "seen_tutorial" } private val runningAnimators = mutableListOf<AnimatorSet>() @RequiresApi(Build.VERSION_CODES.TIRAMISU) private val notificationPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission(), Manifest.permission.POST_NOTIFICATIONS ) { // We don't actually care if the user disables notifications from Muzei; // they can always re-enable them from the Notification Settings option // on the Sources screen } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val binding = TutorialFragmentBinding.bind(view).content binding.iconAffordance.setOnClickListener { Firebase.analytics.logEvent(FirebaseAnalytics.Event.TUTORIAL_COMPLETE, null) PreferenceManager.getDefaultSharedPreferences(requireContext()).edit { putBoolean(PREF_SEEN_TUTORIAL, true) } } if (savedInstanceState == null) { val animateDistance = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100f, resources.displayMetrics) val mainTextView = binding.mainText.apply { alpha = 0f translationY = -animateDistance / 5 } val subTextView = binding.subText.apply { alpha = 0f translationY = -animateDistance / 5 } val affordanceView = binding.iconAffordance.apply { alpha = 0f translationY = animateDistance } val iconTextView = binding.iconText.apply { alpha = 0f translationY = animateDistance } runningAnimators.add(AnimatorSet().apply { startDelay = 500 duration = 250 playTogether( ObjectAnimator.ofFloat(mainTextView, View.ALPHA, 1f), ObjectAnimator.ofFloat(subTextView, View.ALPHA, 1f)) doOnEnd { runningAnimators.remove(this) } start() }) runningAnimators.add(AnimatorSet().apply { startDelay = 2000 duration = 500 // Bug in older versions where set.setInterpolator didn't work val interpolator = OvershootInterpolator() val a1 = ObjectAnimator.ofFloat(affordanceView, View.TRANSLATION_Y, 0f) val a2 = ObjectAnimator.ofFloat(iconTextView, View.TRANSLATION_Y, 0f) val a3 = ObjectAnimator.ofFloat(mainTextView, View.TRANSLATION_Y, 0f) val a4 = ObjectAnimator.ofFloat(subTextView, View.TRANSLATION_Y, 0f) a1.interpolator = interpolator a2.interpolator = interpolator a3.interpolator = interpolator a4.interpolator = interpolator playTogether( ObjectAnimator.ofFloat(affordanceView, View.ALPHA, 1f), ObjectAnimator.ofFloat(iconTextView, View.ALPHA, 1f), a1, a2, a3, a4) doOnEnd { if (isAdded && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val avd = ResourcesCompat.getDrawable(resources, R.drawable.avd_tutorial_icon_emanate, context?.theme) as AnimatedVectorDrawable binding.iconEmanate.setImageDrawable(avd) avd.start() } runningAnimators.remove(this) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { notificationPermissionLauncher.launch() } } start() }) } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val avd = ResourcesCompat.getDrawable(resources, R.drawable.avd_tutorial_icon_emanate, context?.theme) as AnimatedVectorDrawable binding.iconEmanate.setImageDrawable(avd) avd.start() } } override fun onDestroyView() { runningAnimators.forEach { it.removeAllListeners() it.cancel() } super.onDestroyView() } }
apache-2.0
a3f56d24b247a6be577b59ae29bfe188
41.082192
94
0.632102
5.140586
false
false
false
false
leafclick/intellij-community
plugins/markdown/src/org/intellij/plugins/markdown/ui/preview/IntelliJImageGeneratingProvider.kt
1
6198
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.ui.preview import com.intellij.openapi.util.Ref import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.ast.ASTNode import org.intellij.markdown.ast.findChildOfType import org.intellij.markdown.ast.getTextInNode import org.intellij.markdown.html.GeneratingProvider import org.intellij.markdown.html.HtmlGenerator import org.intellij.markdown.html.TransparentInlineHolderProvider import org.intellij.markdown.html.entities.EntityConverter import org.intellij.markdown.parser.LinkMap import java.net.URI internal abstract class LinkGeneratingProvider(private val baseURI: URI?) : GeneratingProvider { override fun processNode(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { val info = getRenderInfo(text, node) ?: return fallbackProvider.processNode(visitor, text, node) renderLink(visitor, text, node, info) } protected open fun makeAbsoluteUrl(destination: CharSequence): CharSequence { if (destination.startsWith('#')) { return destination } try { return baseURI?.resolve(destination.toString())?.toString() ?: destination } catch (e: IllegalArgumentException) { return destination } } open fun renderLink(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode, info: RenderInfo) { visitor.consumeTagOpen(node, "a", "href=\"${makeAbsoluteUrl(info.destination)}\"", info.title?.let { "title=\"$it\"" }) labelProvider.processNode(visitor, text, info.label) visitor.consumeTagClose("a") } abstract fun getRenderInfo(text: String, node: ASTNode): RenderInfo? data class RenderInfo(val label: ASTNode, val destination: CharSequence, val title: CharSequence?) companion object { val fallbackProvider = TransparentInlineHolderProvider() val labelProvider = TransparentInlineHolderProvider(1, -1) } } internal class IntelliJImageGeneratingProvider(linkMap: LinkMap, baseURI: URI?) : LinkGeneratingProvider(applySchemeReplacementToUri(baseURI)) { companion object { private val REGEX = Regex("[^a-zA-Z0-9 ]") private fun getPlainTextFrom(node: ASTNode, text: String): CharSequence { return REGEX.replace(node.getTextInNode(text), "") } } private val referenceLinkProvider = ReferenceLinksGeneratingProvider(linkMap, baseURI) private val inlineLinkProvider = InlineLinkGeneratingProvider(baseURI) override fun makeAbsoluteUrl(destination: CharSequence): CharSequence { val destinationEx = if (SystemInfo.isWindows) StringUtil.replace(destination.toString(), "%5C", "/") else destination.toString() if (destinationEx.startsWith('#')) { return destinationEx } return super.makeAbsoluteUrl(destinationEx) } override fun getRenderInfo(text: String, node: ASTNode): RenderInfo? { node.findChildOfType(MarkdownElementTypes.INLINE_LINK)?.let { return inlineLinkProvider.getRenderInfo(text, it) } return (node.findChildOfType(MarkdownElementTypes.FULL_REFERENCE_LINK) ?: node.findChildOfType(MarkdownElementTypes.SHORT_REFERENCE_LINK))?.let { referenceLinkProvider.getRenderInfo(text, it) } } override fun renderLink(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode, info: RenderInfo) { visitor.consumeTagOpen(node, "img", "src=\"${makeAbsoluteUrl(info.destination)}\"", "alt=\"${getPlainTextFrom(info.label, text)}\"", info.title?.let { "title=\"$it\"" }, autoClose = true) } } internal class ReferenceLinksGeneratingProvider(private val linkMap: LinkMap, baseURI: URI?) : LinkGeneratingProvider(baseURI) { override fun getRenderInfo(text: String, node: ASTNode): RenderInfo? { val label = node.children.firstOrNull { it.type == MarkdownElementTypes.LINK_LABEL } ?: return null val linkInfo = linkMap.getLinkInfo(label.getTextInNode(text)) ?: return null val linkTextNode = node.children.firstOrNull { it.type == MarkdownElementTypes.LINK_TEXT } return RenderInfo( linkTextNode ?: label, EntityConverter.replaceEntities(linkInfo.destination, true, true), linkInfo.title?.let { EntityConverter.replaceEntities(it, true, true) } ) } } internal class InlineLinkGeneratingProvider(baseURI: URI?) : LinkGeneratingProvider(baseURI) { override fun getRenderInfo(text: String, node: ASTNode): RenderInfo? { val label = node.findChildOfType(MarkdownElementTypes.LINK_TEXT) ?: return null return RenderInfo( label, node.findChildOfType(MarkdownElementTypes.LINK_DESTINATION)?.getTextInNode(text)?.let { LinkMap.normalizeDestination(it, true) } ?: "", node.findChildOfType(MarkdownElementTypes.LINK_TITLE)?.getTextInNode(text)?.let { LinkMap.normalizeTitle(it) } ) } } private val schemeRepls = mutableMapOf<String, String>() /** * Registers a scheme replacement. * Currently used with JCEF for a custom scheme to replace "file://". */ internal fun registerSchemeReplacement(originalScheme: String, replacingScheme: String) { schemeRepls[originalScheme] = replacingScheme } /** * Returns a replacement for the scheme, or same scheme when no replacement is registered. */ @JvmOverloads internal fun getSchemeReplacement(scheme: String, replacementExists: Ref<Boolean>? = null): String { val newScheme = schemeRepls[scheme] replacementExists?.set(newScheme != null) return newScheme ?: scheme } /** * Applies scheme replacement to URI's scheme. */ internal fun applySchemeReplacementToUri(uri: URI?): URI? { if (uri == null) return null val wasReplaced = Ref<Boolean>() val newScheme = getSchemeReplacement(uri.scheme, wasReplaced) return if (wasReplaced.get()) URI(newScheme, uri.authority, uri.path, uri.query, uri.fragment) else uri }
apache-2.0
6e57afddc46c11c97b469016cb9f97ee
38.234177
144
0.727815
4.405117
false
false
false
false
prangbi/LottoPop-Android
LottoPop/app/src/main/java/com/prangbi/android/lottopop/base/Definition.kt
1
636
package com.prangbi.android.lottopop.base /** * Created by Prangbi on 2017. 7. 15.. */ class Definition { companion object { // Server Info const val SERVER_URL = "http://m.nlotto.co.kr" const val TERMS_URL = "https://raw.githubusercontent.com/prangbi/ServiceInfo/master/LottoPop/Terms.txt" const val NLOTTO_START_DATE = "2002-12-07 21:00" // 20시 40분 추첨 시작 const val PLOTTO_START_DATE = "2011-07-06 20:00" // 19시 40분 추첨 시작 // Database const val DB_NAME = "lottopop.db" const val DB_VERSION = 1 const val COUNT_PER_PAGE = 10 } }
mit
da4ff5ea9a1e08dd3062e46b70969622
31.210526
111
0.619281
3.06
false
false
false
false
blokadaorg/blokada
android5/app/src/main/java/model/StatsModel.kt
1
2295
/* * This file is part of Blokada. * * 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 https://mozilla.org/MPL/2.0/. * * Copyright © 2021 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package model import com.squareup.moshi.JsonClass import engine.Host import java.util.* /** * Public structures used by other components. */ data class Stats( val allowed: Int, val denied: Int, val entries: List<HistoryEntry> ) data class HistoryEntry( val name: String, val type: HistoryEntryType, val time: Date, val requests: Int, val device: String = "", val pack: String? = null ) enum class HistoryEntryType { blocked, passed, passed_allowed, // Passed because its on user Allowed list blocked_denied, // Blocked because its on user Denied list } @JsonClass(generateAdapter = true) data class Allowed(val value: List<String>) { fun allow(name: String) = when (name) { in value -> this else -> Allowed(value = value + name) } fun unallow(name: String) = when (name) { in value -> Allowed(value = value - name) else -> this } } @JsonClass(generateAdapter = true) data class Denied(val value: List<String>) { fun deny(name: String) = when (name) { in value -> this else -> Denied(value = value + name) } fun undeny(name: String) = when (name) { in value -> Denied(value = value - name) else -> this } } @JsonClass(generateAdapter = true) data class AdsCounter( val persistedValue: Long, val runtimeValue: Long = 0 ) { fun get() = persistedValue + runtimeValue fun roll() = AdsCounter(persistedValue = persistedValue + runtimeValue) } /** * Structures internal to StatsService used to persist the entries. */ @JsonClass(generateAdapter = true) data class StatsPersisted( val entries: Map<String, StatsPersistedEntry> ) @JsonClass(generateAdapter = true) data class StatsPersistedKey( val host: Host, val type: HistoryEntryType ) @JsonClass(generateAdapter = true) class StatsPersistedEntry( var lastEncounter: Long, var occurrences: Int )
mpl-2.0
a41a3cd01a69da98c756753e88973b51
21.271845
75
0.664778
3.760656
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/api/components/reactnativestripesdk/AuBECSDebitFormView.kt
2
5045
package abi43_0_0.host.exp.exponent.modules.api.components.reactnativestripesdk import android.content.res.ColorStateList import android.graphics.Color import android.widget.FrameLayout import abi43_0_0.com.facebook.react.bridge.ReadableMap import abi43_0_0.com.facebook.react.uimanager.ThemedReactContext import abi43_0_0.com.facebook.react.uimanager.UIManagerModule import abi43_0_0.com.facebook.react.uimanager.events.EventDispatcher import com.google.android.material.shape.CornerFamily import com.google.android.material.shape.MaterialShapeDrawable import com.google.android.material.shape.ShapeAppearanceModel import com.stripe.android.databinding.BecsDebitWidgetBinding import com.stripe.android.model.PaymentMethodCreateParams import com.stripe.android.view.BecsDebitWidget import com.stripe.android.view.StripeEditText class AuBECSDebitFormView(private val context: ThemedReactContext) : FrameLayout(context) { private lateinit var becsDebitWidget: BecsDebitWidget private var mEventDispatcher: EventDispatcher? = context.getNativeModule(UIManagerModule::class.java)?.eventDispatcher private var formStyle: ReadableMap? = null fun setCompanyName(name: String?) { becsDebitWidget = BecsDebitWidget(context = context, companyName = name as String) setFormStyle(this.formStyle) addView(becsDebitWidget) setListeners() } fun setFormStyle(value: ReadableMap?) { this.formStyle = value if (!this::becsDebitWidget.isInitialized || value == null) { return } val binding = BecsDebitWidgetBinding.bind(becsDebitWidget) val textColor = getValOr(value, "textColor", null) val textErrorColor = getValOr(value, "textErrorColor", null) val placeholderColor = getValOr(value, "placeholderColor", null) val fontSize = getIntOrNull(value, "fontSize") val borderWidth = getIntOrNull(value, "borderWidth") val backgroundColor = getValOr(value, "backgroundColor", null) val borderColor = getValOr(value, "borderColor", null) val borderRadius = getIntOrNull(value, "borderRadius") ?: 0 textColor?.let { (binding.accountNumberEditText as StripeEditText).setTextColor(Color.parseColor(it)) (binding.bsbEditText as StripeEditText).setTextColor(Color.parseColor(it)) (binding.emailEditText as StripeEditText).setTextColor(Color.parseColor(it)) (binding.nameEditText).setTextColor(Color.parseColor(it)) } textErrorColor?.let { (binding.accountNumberEditText as StripeEditText).setErrorColor(Color.parseColor(it)) (binding.bsbEditText as StripeEditText).setErrorColor(Color.parseColor(it)) (binding.emailEditText as StripeEditText).setErrorColor(Color.parseColor(it)) (binding.nameEditText).setErrorColor(Color.parseColor(it)) } placeholderColor?.let { (binding.accountNumberEditText as StripeEditText).setHintTextColor(Color.parseColor(it)) (binding.bsbEditText as StripeEditText).setHintTextColor(Color.parseColor(it)) (binding.emailEditText as StripeEditText).setHintTextColor(Color.parseColor(it)) (binding.nameEditText).setHintTextColor(Color.parseColor(it)) } fontSize?.let { (binding.accountNumberEditText as StripeEditText).textSize = it.toFloat() (binding.bsbEditText as StripeEditText).textSize = it.toFloat() (binding.emailEditText as StripeEditText).textSize = it.toFloat() (binding.nameEditText).textSize = it.toFloat() } becsDebitWidget.background = MaterialShapeDrawable( ShapeAppearanceModel() .toBuilder() .setAllCorners(CornerFamily.ROUNDED, (borderRadius * 2).toFloat()) .build() ).also { shape -> shape.strokeWidth = 0.0f shape.strokeColor = ColorStateList.valueOf(Color.parseColor("#000000")) shape.fillColor = ColorStateList.valueOf(Color.parseColor("#FFFFFF")) borderWidth?.let { shape.strokeWidth = (it * 2).toFloat() } borderColor?.let { shape.strokeColor = ColorStateList.valueOf(Color.parseColor(it)) } backgroundColor?.let { shape.fillColor = ColorStateList.valueOf(Color.parseColor(it)) } } } fun onFormChanged(params: PaymentMethodCreateParams) { val billingDetails = params.toParamMap()["billing_details"] as HashMap<*, *> val auBecsDebit = params.toParamMap()["au_becs_debit"] as HashMap<*, *> val formDetails: MutableMap<String, Any> = mutableMapOf( "accountNumber" to auBecsDebit["account_number"] as String, "bsbNumber" to auBecsDebit["bsb_number"] as String, "name" to billingDetails["name"] as String, "email" to billingDetails["email"] as String ) mEventDispatcher?.dispatchEvent( FormCompleteEvent(id, formDetails) ) } private fun setListeners() { becsDebitWidget.validParamsCallback = object : BecsDebitWidget.ValidParamsCallback { override fun onInputChanged(isValid: Boolean) { becsDebitWidget.params?.let { params -> onFormChanged(params) } } } } }
bsd-3-clause
edebff668e6fcbf44b2ff6120cc932c9
40.694215
120
0.735382
4.429324
false
false
false
false
smmribeiro/intellij-community
plugins/git4idea/src/git4idea/GitPushUtil.kt
10
5158
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea import com.intellij.dvcs.DvcsUtil import com.intellij.dvcs.push.PushSpec import com.intellij.dvcs.ui.DvcsBundle import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.ui.messages.MessagesService import com.intellij.openapi.util.NlsContexts import git4idea.branch.GitBranchUtil import git4idea.i18n.GitBundle import git4idea.push.GitPushOperation import git4idea.push.GitPushSource import git4idea.push.GitPushSupport import git4idea.push.GitPushTarget import git4idea.repo.GitRemote import git4idea.repo.GitRepository import git4idea.validators.GitRefNameValidator import org.jetbrains.annotations.Nls import java.util.concurrent.CompletableFuture object GitPushUtil { @JvmStatic fun findOrPushRemoteBranch(project: Project, progressIndicator: ProgressIndicator, repository: GitRepository, remote: GitRemote, localBranch: GitLocalBranch, dialogMessages: BranchNameInputDialogMessages): CompletableFuture<GitRemoteBranch> { val gitPushSupport = DvcsUtil.getPushSupport(GitVcs.getInstance(project)) as? GitPushSupport ?: return CompletableFuture.failedFuture(ProcessCanceledException()) val existingPushTarget = findPushTarget(repository, remote, localBranch) if (existingPushTarget != null) { val localHash = repository.branches.getHash(localBranch) val remoteHash = repository.branches.getHash(existingPushTarget.branch) if (localHash == remoteHash) return CompletableFuture.completedFuture(existingPushTarget.branch) } val pushTarget = existingPushTarget ?: inputPushTarget(repository, remote, localBranch, dialogMessages) ?: return CompletableFuture.failedFuture(ProcessCanceledException()) val future = CompletableFuture<GitRemoteBranch>() ProgressManager.getInstance().runProcessWithProgressAsynchronously( object : Task.Backgroundable(repository.project, DvcsBundle.message("push.process.pushing"), true) { override fun run(indicator: ProgressIndicator) { indicator.text = DvcsBundle.message("push.process.pushing") val pushSpec = PushSpec(GitPushSource.create(localBranch), pushTarget) val pushResult = GitPushOperation(repository.project, gitPushSupport, mapOf(repository to pushSpec), null, false, false) .execute().results[repository] ?: error("Missing push result") check(pushResult.error == null) { GitBundle.message("push.failed.error.message", pushResult.error.orEmpty()) } } override fun onSuccess() { future.complete(pushTarget.branch) } override fun onThrowable(error: Throwable) { future.completeExceptionally(error) } override fun onCancel() { future.completeExceptionally(ProcessCanceledException()) } }, progressIndicator) return future } private fun inputPushTarget(repository: GitRepository, remote: GitRemote, localBranch: GitLocalBranch, dialogMessages: BranchNameInputDialogMessages): GitPushTarget? { val branchName = MessagesService.getInstance().showInputDialog(repository.project, null, dialogMessages.inputMessage, dialogMessages.title, null, localBranch.name, null, null, dialogMessages.inputComment) ?: return null //always set tracking return GitPushTarget(GitStandardRemoteBranch(remote, GitRefNameValidator.getInstance().cleanUpBranchName(branchName)), true) } data class BranchNameInputDialogMessages( @NlsContexts.DialogTitle val title: String, @NlsContexts.DialogMessage val inputMessage: String, @Nls(capitalization = Nls.Capitalization.Sentence) val inputComment: String ) @JvmStatic fun findPushTarget(repository: GitRepository, remote: GitRemote, branch: GitLocalBranch): GitPushTarget? { return GitPushTarget.getFromPushSpec(repository, remote, branch) ?: GitBranchUtil.getTrackInfoForBranch(repository, branch) ?.takeIf { it.remote == remote } // use tracking information only for branches with the same local and remote name ?.takeIf { it.remoteBranch.nameForRemoteOperations == branch.name } ?.let { GitPushTarget(it.remoteBranch, false) } } }
apache-2.0
a3bc2d7600ebb88c1ed972a838a67371
46.759259
158
0.677976
5.510684
false
false
false
false
tensorflow/examples
lite/examples/model_personalization/android/app/src/main/java/org/tensorflow/lite/examples/modelpersonalization/fragments/CameraFragment.kt
1
22399
/* * Copyright 2022 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tensorflow.lite.examples.modelpersonalization.fragments import android.annotation.SuppressLint import android.content.res.Configuration import android.graphics.Bitmap import android.os.Bundle import android.os.Handler import android.os.Looper import android.os.SystemClock import android.util.Log import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.Toast import androidx.appcompat.content.res.AppCompatResources import androidx.camera.core.Preview import androidx.camera.core.ImageAnalysis import androidx.camera.core.Camera import androidx.camera.core.CameraSelector import androidx.camera.core.AspectRatio import androidx.camera.core.ImageProxy import androidx.camera.lifecycle.ProcessCameraProvider import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.Navigation import org.tensorflow.lite.examples.modelpersonalization.MainViewModel import org.tensorflow.lite.examples.modelpersonalization.R import org.tensorflow.lite.examples.modelpersonalization.TransferLearningHelper import org.tensorflow.lite.examples.modelpersonalization.TransferLearningHelper.Companion.CLASS_FOUR import org.tensorflow.lite.examples.modelpersonalization.TransferLearningHelper.Companion.CLASS_ONE import org.tensorflow.lite.examples.modelpersonalization.TransferLearningHelper.Companion.CLASS_THREE import org.tensorflow.lite.examples.modelpersonalization.TransferLearningHelper.Companion.CLASS_TWO import org.tensorflow.lite.examples.modelpersonalization.databinding.FragmentCameraBinding import org.tensorflow.lite.support.label.Category import java.util.Locale import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.ExecutorService import java.util.concurrent.Executors class CameraFragment : Fragment(), TransferLearningHelper.ClassifierListener { companion object { private const val TAG = "Model Personalization" private const val LONG_PRESS_DURATION = 500 private const val SAMPLE_COLLECTION_DELAY = 300 } private var _fragmentCameraBinding: FragmentCameraBinding? = null private val fragmentCameraBinding get() = _fragmentCameraBinding!! private lateinit var transferLearningHelper: TransferLearningHelper private lateinit var bitmapBuffer: Bitmap private val viewModel: MainViewModel by activityViewModels() private var preview: Preview? = null private var imageAnalyzer: ImageAnalysis? = null private var camera: Camera? = null private var cameraProvider: ProcessCameraProvider? = null private var previousClass: String? = null /** Blocking camera operations are performed using this executor */ private lateinit var cameraExecutor: ExecutorService // When the user presses the "add sample" button for some class, // that class will be added to this queue. It is later extracted by // InferenceThread and processed. private val addSampleRequests = ConcurrentLinkedQueue<String>() private var sampleCollectionButtonPressedTime: Long = 0 private var isCollectingSamples = false private val sampleCollectionHandler = Handler(Looper.getMainLooper()) private val onAddSampleTouchListener = View.OnTouchListener { view, motionEvent -> when (motionEvent.action) { MotionEvent.ACTION_DOWN -> { isCollectingSamples = true sampleCollectionButtonPressedTime = SystemClock.uptimeMillis() sampleCollectionHandler.post(object : Runnable { override fun run() { val timePressed = SystemClock.uptimeMillis() - sampleCollectionButtonPressedTime view.findViewById<View>(view.id).performClick() if (timePressed < LONG_PRESS_DURATION) { sampleCollectionHandler.postDelayed( this, LONG_PRESS_DURATION.toLong() ) } else if (isCollectingSamples) { val className: String = getClassNameFromResourceId(view.id) addSampleRequests.add(className) sampleCollectionHandler.postDelayed( this, SAMPLE_COLLECTION_DELAY.toLong() ) } } }) } MotionEvent.ACTION_UP -> { sampleCollectionHandler.removeCallbacksAndMessages(null) isCollectingSamples = false } } true } override fun onResume() { super.onResume() if (!PermissionsFragment.hasPermissions(requireContext())) { Navigation.findNavController( requireActivity(), R.id.fragment_container ).navigate(CameraFragmentDirections.actionCameraToPermissions()) } } override fun onDestroyView() { _fragmentCameraBinding = null super.onDestroyView() // Shut down our background executor cameraExecutor.shutdown() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _fragmentCameraBinding = FragmentCameraBinding.inflate(inflater, container, false) return fragmentCameraBinding.root } @SuppressLint("MissingPermission", "ClickableViewAccessibility") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) transferLearningHelper = TransferLearningHelper( context = requireContext(), classifierListener = this ) cameraExecutor = Executors.newSingleThreadExecutor() viewModel.numThreads.observe(viewLifecycleOwner) { transferLearningHelper.numThreads = it transferLearningHelper.close() if (viewModel.getTrainingState() != MainViewModel.TrainingState.PREPARE) { // If the model is training, continue training with old image // sets. viewModel.setTrainingState(MainViewModel.TrainingState.TRAINING) transferLearningHelper.startTraining() } } viewModel.trainingState.observe(viewLifecycleOwner) { updateTrainingButtonState() } viewModel.captureMode.observe(viewLifecycleOwner) { isCaptureMode -> if (isCaptureMode) { viewModel.getNumberOfSample()?.let { updateNumberOfSample(it) } // Unhighlight all class buttons highlightResult(null) } // Update the UI after switch to training mode. updateTrainingButtonState() } viewModel.numberOfSamples.observe(viewLifecycleOwner) { // Update the number of samples updateNumberOfSample(it) updateTrainingButtonState() } with(fragmentCameraBinding) { if (viewModel.getCaptureMode()!!) { btnTrainingMode.isChecked = true } else { btnInferenceMode.isChecked = true } llClassOne.setOnClickListener { addSampleRequests.add(CLASS_ONE) } llClassTwo.setOnClickListener { addSampleRequests.add(CLASS_TWO) } llClassThree.setOnClickListener { addSampleRequests.add(CLASS_THREE) } llClassFour.setOnClickListener { addSampleRequests.add(CLASS_FOUR) } llClassOne.setOnTouchListener(onAddSampleTouchListener) llClassTwo.setOnTouchListener(onAddSampleTouchListener) llClassThree.setOnTouchListener(onAddSampleTouchListener) llClassFour.setOnTouchListener(onAddSampleTouchListener) btnPauseTrain.setOnClickListener { viewModel.setTrainingState(MainViewModel.TrainingState.PAUSE) transferLearningHelper.pauseTraining() } btnResumeTrain.setOnClickListener { viewModel.setTrainingState(MainViewModel.TrainingState.TRAINING) transferLearningHelper.startTraining() } btnStartTrain.setOnClickListener { // Start training process viewModel.setTrainingState(MainViewModel.TrainingState.TRAINING) transferLearningHelper.startTraining() } radioButton.setOnCheckedChangeListener { _, checkedId -> if (checkedId == R.id.btnTrainingMode) { // Switch to training mode. viewModel.setCaptureMode(true) } else { if (viewModel.getTrainingState() == MainViewModel.TrainingState.PREPARE) { fragmentCameraBinding.btnTrainingMode.isChecked = true fragmentCameraBinding.btnInferenceMode.isChecked = false Toast.makeText( requireContext(), "Inference can only " + "start after training is done.", Toast .LENGTH_LONG ).show() } else { // Pause the training process and switch to inference mode. transferLearningHelper.pauseTraining() viewModel.setTrainingState(MainViewModel.TrainingState.PAUSE) viewModel.setCaptureMode(false) } } } viewFinder.post { // Set up the camera and its use cases setUpCamera() } } } // Initialize CameraX, and prepare to bind the camera use cases private fun setUpCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext()) cameraProviderFuture.addListener( { // CameraProvider cameraProvider = cameraProviderFuture.get() // Build and bind the camera use cases bindCameraUseCases() }, ContextCompat.getMainExecutor(requireContext()) ) } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) imageAnalyzer?.targetRotation = fragmentCameraBinding.viewFinder.display.rotation } // Declare and bind preview, capture and analysis use cases @SuppressLint("UnsafeOptInUsageError") private fun bindCameraUseCases() { // CameraProvider val cameraProvider = cameraProvider ?: throw IllegalStateException("Camera initialization failed.") // CameraSelector - makes assumption that we're only using the back camera val cameraSelector = CameraSelector.Builder() .requireLensFacing(CameraSelector.LENS_FACING_BACK).build() // Preview. Only using the 4:3 ratio because this is the closest to our models preview = Preview.Builder() .setTargetAspectRatio(AspectRatio.RATIO_4_3) .setTargetRotation(fragmentCameraBinding.viewFinder.display.rotation) .build() // ImageAnalysis. Using RGBA 8888 to match how our models work imageAnalyzer = ImageAnalysis.Builder() .setTargetAspectRatio(AspectRatio.RATIO_4_3) .setTargetRotation(fragmentCameraBinding.viewFinder.display.rotation) .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888) .build() // The analyzer can then be assigned to the instance .also { it.setAnalyzer(cameraExecutor) { image -> if (!::bitmapBuffer.isInitialized) { // The image rotation and RGB image buffer are initialized only once // the analyzer has started running bitmapBuffer = Bitmap.createBitmap( image.width, image.height, Bitmap.Config.ARGB_8888 ) } val sampleClass = addSampleRequests.poll() if (sampleClass != null) { addSample(image, sampleClass) viewModel.increaseNumberOfSample(sampleClass) } else { if (viewModel.getCaptureMode() == false) { classifyImage(image) } } image.close() } } // Must unbind the use-cases before rebinding them cameraProvider.unbindAll() try { // A variable number of use-cases can be passed here - // camera provides access to CameraControl & CameraInfo camera = cameraProvider.bindToLifecycle( this, cameraSelector, preview, imageAnalyzer ) // Attach the viewfinder's surface provider to preview use case preview?.setSurfaceProvider(fragmentCameraBinding.viewFinder.surfaceProvider) } catch (exc: Exception) { Log.e(TAG, "Use case binding failed", exc) } } private fun classifyImage(image: ImageProxy) { // Copy out RGB bits to the shared bitmap buffer image.use { bitmapBuffer.copyPixelsFromBuffer(image.planes[0].buffer) } val imageRotation = image.imageInfo.rotationDegrees // Pass Bitmap and rotation to the transfer learning helper for // processing and classification. transferLearningHelper.classify(bitmapBuffer, imageRotation) } private fun addSample(image: ImageProxy, className: String) { // Copy out RGB bits to the shared bitmap buffer image.use { bitmapBuffer.copyPixelsFromBuffer(image.planes[0].buffer) } val imageRotation = image.imageInfo.rotationDegrees // Pass Bitmap and rotation to the transfer learning helper for // processing and prepare training data. transferLearningHelper.addSample(bitmapBuffer, className, imageRotation) } @SuppressLint("NotifyDataSetChanged") override fun onError(error: String) { activity?.runOnUiThread { Toast.makeText(requireContext(), error, Toast.LENGTH_SHORT).show() } } @SuppressLint("NotifyDataSetChanged") override fun onResults( results: List<Category>?, inferenceTime: Long ) { activity?.runOnUiThread { // Update the result in inference mode. if (viewModel.getCaptureMode() == false) { // Show result results?.let { list -> // Highlight the class which is highest score. list.maxByOrNull { it.score }?.let { highlightResult(it.label) } updateScoreClasses(list) } fragmentCameraBinding.tvInferenceTime.text = String.format("%d ms", inferenceTime) } } } // Show the loss number after each training. override fun onLossResults(lossNumber: Float) { String.format( Locale.US, "Loss: %.3f", lossNumber ).let { fragmentCameraBinding.tvLossConsumerPause.text = it fragmentCameraBinding.tvLossConsumerResume.text = it } } // Show the accurate score of each class. private fun updateScoreClasses(categories: List<Category>) { categories.forEach { val view = getClassButtonScore(it.label) (view as? TextView)?.text = String.format( Locale.US, "%.1f", it.score ) } } // Get the class button which represent for the label private fun getClassButton(label: String): View? { return when (label) { CLASS_ONE -> fragmentCameraBinding.llClassOne CLASS_TWO -> fragmentCameraBinding.llClassTwo CLASS_THREE -> fragmentCameraBinding.llClassThree CLASS_FOUR -> fragmentCameraBinding.llClassFour else -> null } } // Get the class button score which represent for the label private fun getClassButtonScore(label: String): View? { return when (label) { CLASS_ONE -> fragmentCameraBinding.tvNumberClassOne CLASS_TWO -> fragmentCameraBinding.tvNumberClassTwo CLASS_THREE -> fragmentCameraBinding.tvNumberClassThree CLASS_FOUR -> fragmentCameraBinding.tvNumberClassFour else -> null } } // Get the class name from resource id private fun getClassNameFromResourceId(id: Int): String { return when (id) { fragmentCameraBinding.llClassOne.id -> CLASS_ONE fragmentCameraBinding.llClassTwo.id -> CLASS_TWO fragmentCameraBinding.llClassThree.id -> CLASS_THREE fragmentCameraBinding.llClassFour.id -> CLASS_FOUR else -> { "" } } } // Highlight the current label and unhighlight the previous label private fun highlightResult(label: String?) { // skip the previous position if it is no position. previousClass?.let { setClassButtonHighlight(getClassButton(it), false) } if (label != null) { setClassButtonHighlight(getClassButton(label), true) } previousClass = label } private fun setClassButtonHighlight(view: View?, isHighlight: Boolean) { view?.run { background = AppCompatResources.getDrawable( context, if (isHighlight) R.drawable.btn_default_highlight else R.drawable.btn_default ) } } // Update the number of samples. If there are no label in the samples, // set it 0. private fun updateNumberOfSample(numberOfSamples: Map<String, Int>) { fragmentCameraBinding.tvNumberClassOne.text = if (numberOfSamples .containsKey(CLASS_ONE) ) numberOfSamples.getValue(CLASS_ONE) .toString() else "0" fragmentCameraBinding.tvNumberClassTwo.text = if (numberOfSamples .containsKey(CLASS_TWO) ) numberOfSamples.getValue(CLASS_TWO) .toString() else "0" fragmentCameraBinding.tvNumberClassThree.text = if (numberOfSamples .containsKey(CLASS_THREE) ) numberOfSamples.getValue(CLASS_THREE) .toString() else "0" fragmentCameraBinding.tvNumberClassFour.text = if (numberOfSamples .containsKey(CLASS_FOUR) ) numberOfSamples.getValue(CLASS_FOUR) .toString() else "0" } private fun updateTrainingButtonState() { with(fragmentCameraBinding) { tvInferenceTime.visibility = if (viewModel .getCaptureMode() == true ) View.GONE else View.VISIBLE btnCollectSample.visibility = if ( viewModel.getTrainingState() == MainViewModel.TrainingState.PREPARE && (viewModel.getNumberOfSample()?.size ?: 0) == 0 && viewModel .getCaptureMode() == true ) View.VISIBLE else View.GONE btnStartTrain.visibility = if ( viewModel.getTrainingState() == MainViewModel.TrainingState.PREPARE && (viewModel.getNumberOfSample()?.size ?: 0) > 0 && viewModel .getCaptureMode() == true ) View.VISIBLE else View.GONE btnPauseTrain.visibility = if (viewModel.getTrainingState() == MainViewModel .TrainingState.TRAINING && viewModel .getCaptureMode() == true ) View.VISIBLE else View.GONE btnResumeTrain.visibility = if (viewModel.getTrainingState() == MainViewModel .TrainingState.PAUSE && viewModel .getCaptureMode() == true ) View.VISIBLE else View.GONE // Disable adding button when it is training or in inference mode. (viewModel.getCaptureMode() == true && viewModel.getTrainingState() != MainViewModel.TrainingState.TRAINING).let { enable -> llClassOne.isClickable = enable llClassTwo.isClickable = enable llClassThree.isClickable = enable llClassFour.isClickable = enable } } } }
apache-2.0
357e816cf8161d6bfb64de72a486a5f3
39.069767
101
0.604714
5.612378
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/lang/KslVectorAccessorI4.kt
1
718
package de.fabmax.kool.modules.ksl.lang // common vec4 component swizzles - defined in a separate file to avoid JVM signature clashes val KslVectorExpression<KslTypeInt4, KslTypeInt1>.xy get() = int2("xy") val KslVectorExpression<KslTypeInt4, KslTypeInt1>.xz get() = int2("xz") val KslVectorExpression<KslTypeInt4, KslTypeInt1>.yz get() = int2("xz") val KslVectorExpression<KslTypeInt4, KslTypeInt1>.rg get() = int2("rg") val KslVectorExpression<KslTypeInt4, KslTypeInt1>.rb get() = int2("rb") val KslVectorExpression<KslTypeInt4, KslTypeInt1>.gb get() = int2("gb") val KslVectorExpression<KslTypeInt4, KslTypeInt1>.xyz get() = int3("xyz") val KslVectorExpression<KslTypeInt4, KslTypeInt1>.rgb get() = int3("rgb")
apache-2.0
de8ed8489db5e545a2ae713437345602
50.285714
93
0.768802
3.502439
false
false
false
false
siosio/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/util/ProgressUtil.kt
1
1309
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.core.util import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.ProgressIndicatorUtils import com.intellij.openapi.project.Project fun <T : Any> runInReadActionWithWriteActionPriorityWithPCE(f: () -> T): T = runInReadActionWithWriteActionPriority(f) ?: throw ProcessCanceledException() fun <T : Any> runInReadActionWithWriteActionPriority(f: () -> T): T? { if (with(ApplicationManager.getApplication()) { isDispatchThread && isUnitTestMode }) { return f() } var r: T? = null val complete = ProgressIndicatorUtils.runInReadActionWithWriteActionPriority { r = f() } if (!complete) return null return r!! } fun <T : Any> Project.runSynchronouslyWithProgress(progressTitle: String, canBeCanceled: Boolean, action: () -> T): T? { var result: T? = null ProgressManager.getInstance().runProcessWithProgressSynchronously({ result = action() }, progressTitle, canBeCanceled, this) return result }
apache-2.0
e03a9c75485a95ea7bb6d6843dd77e53
39.9375
158
0.752483
4.392617
false
false
false
false
jwren/intellij-community
platform/diff-impl/src/com/intellij/diff/editor/DiffRequestProcessorEditorBase.kt
1
2281
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.diff.editor import com.intellij.diff.DiffContext import com.intellij.diff.util.DiffUserDataKeysEx import com.intellij.diff.util.DiffUtil import com.intellij.diff.util.FileEditorBase import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diff.DiffBundle import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.util.CheckedDisposable import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VirtualFile import java.awt.BorderLayout import java.awt.event.ContainerAdapter import java.awt.event.ContainerEvent import javax.swing.JComponent import javax.swing.JPanel @Suppress("LeakingThis") abstract class DiffRequestProcessorEditorBase( private val file: DiffVirtualFileBase, component: JComponent, private val disposable: CheckedDisposable, private val context: DiffContext ) : FileEditorBase() { companion object { private val LOG = logger<DiffRequestProcessorEditorBase>() } private val panel = MyPanel(component) init { Disposer.register(disposable, Disposable { firePropertyChange(FileEditor.PROP_VALID, true, false) }) DiffRequestProcessorEditorCustomizer.customize(file, this, context) } override fun getComponent(): JComponent = panel override fun dispose() { if (!DiffUtil.isUserDataFlagSet(DiffUserDataKeysEx.DIFF_IN_EDITOR_WITH_EXPLICIT_DISPOSABLE, context)) { Disposer.dispose(disposable) } super.dispose() } override fun isValid(): Boolean = !isDisposed && !disposable.isDisposed override fun getFile(): VirtualFile = file override fun getName(): String = DiffBundle.message("diff.file.editor.name") private inner class MyPanel(component: JComponent) : JPanel(BorderLayout()) { init { add(component, BorderLayout.CENTER) addContainerListener(object : ContainerAdapter() { override fun componentRemoved(e: ContainerEvent?) { if (isDisposed) return LOG.error("DiffRequestProcessor cannot be shown twice, see com.intellij.ide.actions.SplitAction.FORBID_TAB_SPLIT, file: $file") } }) } } }
apache-2.0
c0fee4eb808a201452b5eb450d957a72
33.044776
137
0.7637
4.403475
false
false
false
false
chemickypes/Glitchy
glitch/src/main/java/me/bemind/glitch/Utils.kt
1
489
package me.bemind.glitch import android.graphics.Path /** * Created by angelomoroni on 23/07/17. */ fun getPathFromShape (shape: GShape, path: Path? = null) : Path { val p = path?:Path() p.rewind() for(i in 0 until shape.vertices.size){ val point = shape.vertices[i] if(i == 0){ p.moveTo(point.x.toFloat(),point.y.toFloat()) }else{ p.lineTo(point.x.toFloat(),point.y.toFloat()) } } p.close() return p }
apache-2.0
a4f3a0eb3a986b4829dd7d4dabeec19b
19.416667
65
0.568507
3.196078
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/openapi/application/rw/InternalReadAction.kt
3
4757
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.application.rw import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ReadAction.CannotReadException import com.intellij.openapi.application.ReadConstraint import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.progress.blockingContext import kotlinx.coroutines.* import kotlin.coroutines.coroutineContext import kotlin.coroutines.resume internal class InternalReadAction<T>( private val constraints: List<ReadConstraint>, private val blocking: Boolean, private val action: () -> T ) { private val application: ApplicationEx = ApplicationManager.getApplication() as ApplicationEx suspend fun runReadAction(): T { check(!application.isDispatchThread) { "Must not call from EDT" } if (application.isReadAccessAllowed) { val unsatisfiedConstraint = findUnsatisfiedConstraint() check(unsatisfiedConstraint == null) { "Cannot suspend until constraints are satisfied while holding the read lock: $unsatisfiedConstraint" } return blockingContext(action) } return coroutineScope { readLoop() } } private fun findUnsatisfiedConstraint(): ReadConstraint? { for (constraint in constraints) { if (!constraint.isSatisfied()) { return constraint } } return null } private suspend fun readLoop(): T { val loopJob = coroutineContext.job while (true) { loopJob.ensureActive() if (application.isWriteActionPending || application.isWriteActionInProgress) { yieldToPendingWriteActions() // Write actions are executed on the write thread => wait until write action is processed. } when (val readResult = tryReadAction(loopJob)) { is ReadResult.Successful -> return readResult.value is ReadResult.UnsatisfiedConstraint -> readResult.waitForConstraint.join() is ReadResult.WritePending -> Unit // retry } } } private suspend fun tryReadAction(loopJob: Job): ReadResult<T> = blockingContext { if (blocking) { tryReadBlocking(loopJob) } else { tryReadCancellable(loopJob) } } private fun tryReadBlocking(loopJob: Job): ReadResult<T> { var result: ReadResult<T>? = null application.tryRunReadAction { result = insideReadAction(loopJob) } return result ?: ReadResult.WritePending } private fun tryReadCancellable(loopJob: Job): ReadResult<T> = try { cancellableReadActionInternal(loopJob) { insideReadAction(loopJob) } } catch (e: CancellationException) { if (e.cause is CannotReadException) { ReadResult.WritePending } else { throw e } } private fun insideReadAction(loopJob: Job): ReadResult<T> { val unsatisfiedConstraint = findUnsatisfiedConstraint() return if (unsatisfiedConstraint == null) { ReadResult.Successful(action()) } else { ReadResult.UnsatisfiedConstraint(waitForConstraint(loopJob, unsatisfiedConstraint)) } } } private sealed class ReadResult<out T> { class Successful<T>(val value: T) : ReadResult<T>() class UnsatisfiedConstraint(val waitForConstraint: Job) : ReadResult<Nothing>() object WritePending : ReadResult<Nothing>() } /** * Suspends the execution until the write thread queue is processed. */ private suspend fun yieldToPendingWriteActions() { // the runnable is executed on the write thread _after_ the current or pending write action yieldUntilRun(ApplicationManager.getApplication()::invokeLater) } private fun waitForConstraint(loopJob: Job, constraint: ReadConstraint): Job { return CoroutineScope(loopJob).launch(Dispatchers.Unconfined + CoroutineName("waiting for constraint '$constraint'")) { check(ApplicationManager.getApplication().isReadAccessAllowed) // schedule while holding read lock yieldUntilRun(constraint::schedule) check(constraint.isSatisfied()) // Job is finished, readLoop may continue the next attempt } } private suspend fun yieldUntilRun(schedule: (Runnable) -> Unit) { suspendCancellableCoroutine<Unit> { continuation -> schedule(ResumeContinuationRunnable(continuation)) } } private class ResumeContinuationRunnable(continuation: CancellableContinuation<Unit>) : Runnable { @Volatile private var myContinuation: CancellableContinuation<Unit>? = continuation init { continuation.invokeOnCancellation { myContinuation = null // it's not possible to unschedule the runnable, so we make it do nothing instead } } override fun run() { myContinuation?.resume(Unit) } }
apache-2.0
0d418cd027bda65595bbf28658ea0431
31.360544
127
0.72798
4.868987
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/test/java/androidx/compose/ui/text/TextSpanParagraphStyleTest.kt
3
6338
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text import com.google.common.truth.Truth.assertThat import kotlin.reflect.KClass import kotlin.reflect.KFunction import kotlin.reflect.KParameter import kotlin.reflect.KProperty1 import kotlin.reflect.KType import kotlin.reflect.full.memberProperties import kotlin.reflect.full.primaryConstructor import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class TextSpanParagraphStyleTest { @Test fun spanStyle_constructor_is_covered_by_TextStyle() { val spanStyleParameters = constructorParams(SpanStyle::class).toMutableSet().filter { it.name != "platformStyle" && it.name != "textForegroundStyle" } val textStyleParameters = mutableSetOf<Parameter>() // In case of multiple constructors, all constructors together should cover // all SpanStyle parameters. for (constructor in TextStyle::class.constructors) { // for every SpanStyle parameter, expecting that parameter to be in TextStyle // this guards that if a parameter is added to SpanStyle, it should be added // to TextStyle textStyleParameters += constructorParams(constructor).toSet().filter { it.name != "platformStyle" } } assertThat(textStyleParameters).containsAtLeastElementsIn(spanStyleParameters) } @Test fun spanStyle_properties_is_covered_by_TextStyle() { val spanStyleProperties = memberProperties(SpanStyle::class).filter { it.name != "platformStyle" && it.name != "textForegroundStyle" } val textStyleProperties = memberProperties(TextStyle::class).filter { it.name != "platformStyle" } assertThat(textStyleProperties).containsAtLeastElementsIn(spanStyleProperties) } @Test fun paragraphStyle_is_covered_by_TextStyle() { val paragraphStyleProperties = memberProperties(ParagraphStyle::class).filter { it.name != "platformStyle" } val textStyleProperties = memberProperties(TextStyle::class).filter { it.name != "platformStyle" } assertThat(textStyleProperties).containsAtLeastElementsIn(paragraphStyleProperties) } @Test fun paragraphStyle_properties_is_covered_by_TextStyle() { val paragraphStyleProperties = memberProperties(ParagraphStyle::class).filter { it.name != "platformStyle" } val textStyleProperties = memberProperties(TextStyle::class).filter { it.name != "platformStyle" } assertThat(textStyleProperties).containsAtLeastElementsIn(paragraphStyleProperties) } @Test fun textStyle_covered_by_ParagraphStyle_and_SpanStyle() { val spanStyleParameters = allConstructorParams(SpanStyle::class).filter { it.name != "platformStyle" && it.name != "textForegroundStyle" } val paragraphStyleParameters = allConstructorParams(ParagraphStyle::class).filter { it.name != "platformStyle" } val allParameters = (spanStyleParameters + paragraphStyleParameters).toMutableSet() val textStyleParameters = allConstructorParams(TextStyle::class).filter { it.name != "platformStyle" && it.name != "spanStyle" && it.name != "paragraphStyle" } // for every TextStyle parameter, expecting that parameter to be in either ParagraphStyle // or SpanStyle // this guards that if a parameter is added to TextStyle, it should be added // to one of SpanStyle or ParagraphStyle assertThat(allParameters).containsAtLeastElementsIn(textStyleParameters) } @Test fun testStyle_properties_is_covered_by_ParagraphStyle_and_SpanStyle() { val spanStyleProperties = memberProperties(SpanStyle::class).filter { it.name != "platformStyle" && it.name != "textForegroundStyle" } val paragraphStyleProperties = memberProperties(ParagraphStyle::class).filter { it.name != "platformStyle" } val allProperties = spanStyleProperties + paragraphStyleProperties val textStyleProperties = memberProperties(TextStyle::class).filter { it.name != "spanStyle" && it.name != "paragraphStyle" && it.name != "platformStyle" } assertThat(allProperties).containsAtLeastElementsIn(textStyleProperties) } private fun <T : Any> constructorParams(clazz: KClass<T>): List<Parameter> { return clazz.primaryConstructor?.let { constructorParams(it) } ?: listOf() } private fun <T : Any> allConstructorParams(clazz: KClass<T>): Set<Parameter> { return clazz.constructors.flatMap { ctor -> constructorParams(ctor) }.toSet() } private fun <T : Any> constructorParams(constructor: KFunction<T>): List<Parameter> { return constructor.parameters.map { Parameter(it) } } private fun <T : Any> memberProperties(clazz: KClass<T>): Collection<Property> { return clazz.memberProperties.map { Property(it) } } private data class Parameter( val name: String?, val type: KType, val optional: Boolean, val isVarArg: Boolean, val kind: KParameter.Kind ) { constructor(parameter: KParameter) : this( parameter.name, parameter.type, parameter.isOptional, parameter.isVararg, parameter.kind ) } private data class Property( val name: String?, val type: KType ) { constructor(parameter: KProperty1<*, *>) : this(parameter.name, parameter.returnType) } }
apache-2.0
458c099b8da16ce56248c07615359b25
38.123457
97
0.676081
4.816109
false
true
false
false
mkoslacz/Moviper
sample-super-rx-ai-kotlin/src/main/java/com/mateuszkoslacz/moviper/rxsample/viper/entity/User.kt
1
717
package com.mateuszkoslacz.moviper.rxsample.viper.entity import com.google.gson.annotations.SerializedName /** * Created by jjodelka on 17/10/16. */ class User { @SerializedName("organizations_url") var organizationsUrl: String? = null @SerializedName("avatar_url") var avatarUrl: String? = null @SerializedName("gists_url") var gistsUrl: String? = null @SerializedName("html_url") var htmlUrl: String? = null var location: String? = null var company: String? = null var email: String? = null var name: String? = null var blog: String? = null var type: String? = null var url: String? = null var id: String? = null var login: String? = null }
apache-2.0
7ecec6fe13e41aaf2067cc54ce8bc41a
24.607143
56
0.662483
3.773684
false
false
false
false
androidx/androidx
benchmark/benchmark-macro/src/main/java/androidx/benchmark/macro/ProfileInstallBroadcast.kt
3
10082
/* * 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.benchmark.macro import android.os.Build import android.util.Log import androidx.annotation.RequiresApi import androidx.benchmark.Shell import androidx.profileinstaller.ProfileInstallReceiver import androidx.profileinstaller.ProfileInstaller internal object ProfileInstallBroadcast { private val receiverName = ProfileInstallReceiver::class.java.name /** * Returns null on success, error string on suppress-able error, or throws if profileinstaller * not up to date. * * Returned error strings aren't thrown, to let the calling function decide strictness. */ fun installProfile(packageName: String): String? { Log.d(TAG, "Profile Installer - Install profile") // For baseline profiles, we trigger this broadcast to force the baseline profile to be // installed synchronously val action = ProfileInstallReceiver.ACTION_INSTALL_PROFILE // Use an explicit broadcast given the app was force-stopped. when (val result = Shell.amBroadcast("-a $action $packageName/$receiverName")) { null, // 0 is returned by the platform by default, and also if no broadcast receiver // receives the broadcast. 0 -> { return "The baseline profile install broadcast was not received. " + "This most likely means that the profileinstaller library is missing " + "from the target apk." } ProfileInstaller.RESULT_INSTALL_SUCCESS -> { return null // success! } ProfileInstaller.RESULT_ALREADY_INSTALLED -> { throw RuntimeException( "Unable to install baseline profile. This most likely means that the " + "latest version of the profileinstaller library is not being used. " + "Please use the latest profileinstaller library version " + "in the target app." ) } ProfileInstaller.RESULT_UNSUPPORTED_ART_VERSION -> { val sdkInt = Build.VERSION.SDK_INT throw RuntimeException( if (sdkInt <= 23) { "Baseline profiles aren't supported on this device version," + " as all apps are fully ahead-of-time compiled." } else { "The device SDK version ($sdkInt) isn't supported" + " by the target app's copy of profileinstaller." + if (sdkInt in 31..33) { " Please use profileinstaller `1.2.1`" + " or newer for API 31-33 support" } else { "" } } ) } ProfileInstaller.RESULT_BASELINE_PROFILE_NOT_FOUND -> { return "No baseline profile was found in the target apk." } ProfileInstaller.RESULT_NOT_WRITABLE, ProfileInstaller.RESULT_DESIRED_FORMAT_UNSUPPORTED, ProfileInstaller.RESULT_IO_EXCEPTION, ProfileInstaller.RESULT_PARSE_EXCEPTION -> { throw RuntimeException("Baseline Profile wasn't successfully installed") } else -> { throw RuntimeException( "unrecognized ProfileInstaller result code: $result" ) } } } /** * Uses skip files for avoiding interference from ProfileInstaller when using * [CompilationMode.None]. * * Operation name is one of `WRITE_SKIP_FILE` or `DELETE_SKIP_FILE`. * * Returned error strings aren't thrown, to let the calling function decide strictness. */ fun skipFileOperation( packageName: String, @Suppress("SameParameterValue") operation: String ): String? { Log.d(TAG, "Profile Installer - Skip File Operation: $operation") // Redefining constants here, because these are only defined in the latest alpha for // ProfileInstaller. // Use an explicit broadcast given the app was force-stopped. val action = "androidx.profileinstaller.action.SKIP_FILE" val operationKey = "EXTRA_SKIP_FILE_OPERATION" val extras = "$operationKey $operation" val result = Shell.amBroadcast("-a $action -e $extras $packageName/$receiverName") return when { result == null || result == 0 -> { // 0 is returned by the platform by default, and also if no broadcast receiver // receives the broadcast. "The baseline profile skip file broadcast was not received. " + "This most likely means that the `androidx.profileinstaller` library " + "used by the target apk is old. Please use `1.2.0-alpha03` or newer. " + "For more information refer to the release notes at " + "https://developer.android.com/jetpack/androidx/releases/profileinstaller." } operation == "WRITE_SKIP_FILE" && result == 10 -> { // RESULT_INSTALL_SKIP_FILE_SUCCESS null // success! } operation == "DELETE_SKIP_FILE" && result == 11 -> { // RESULT_DELETE_SKIP_FILE_SUCCESS null // success! } else -> { throw RuntimeException( "unrecognized ProfileInstaller result code: $result" ) } } } /** * Save any in-memory profile data in the target app to disk, so it can be used for compilation. * * Returned error strings aren't thrown, to let the calling function decide strictness. */ @RequiresApi(24) fun saveProfile(packageName: String): String? { Log.d(TAG, "Profile Installer - Save Profile") val action = "androidx.profileinstaller.action.SAVE_PROFILE" return when (val result = Shell.amBroadcast("-a $action $packageName/$receiverName")) { null, 0 -> { // 0 is returned by the platform by default, and also if no broadcast receiver // receives the broadcast. "The save profile broadcast event was not received. " + "This most likely means that the `androidx.profileinstaller` library " + "used by the target apk is old. Please use `1.3.0-alpha01` or newer. " + "For more information refer to the release notes at " + "https://developer.android.com/jetpack/androidx/releases/profileinstaller." } 12 -> { // RESULT_SAVE_PROFILE_SIGNALLED // For safety, since this is async, we wait before returning // Empirically, this is extremely fast (< 10ms) Thread.sleep(500) null // success! } else -> { // We don't bother supporting RESULT_SAVE_PROFILE_SKIPPED here, // since we already perform SDK_INT checks and use @RequiresApi(24) throw RuntimeException( "unrecognized ProfileInstaller result code: $result" ) } } } private fun benchmarkOperation( packageName: String, @Suppress("SameParameterValue") operation: String ): String? { Log.d(TAG, "Profile Installer - Benchmark Operation: $operation") // Redefining constants here, because these are only defined in the latest alpha for // ProfileInstaller. // Use an explicit broadcast given the app was force-stopped. val action = "androidx.profileinstaller.action.BENCHMARK_OPERATION" val operationKey = "EXTRA_BENCHMARK_OPERATION" val result = Shell.amBroadcast( "-a $action -e $operationKey $operation $packageName/$receiverName" ) return when (result) { null, 0, 16 /* BENCHMARK_OPERATION_UNKNOWN */ -> { // 0 is returned by the platform by default, and also if no broadcast receiver // receives the broadcast. // NOTE: may need to update this over time for different versions, // based on operation string "The $operation broadcast was not received. " + "This most likely means that the `androidx.profileinstaller` library " + "used by the target apk is old. Please use `1.3.0-alpha02` or newer. " + "For more information refer to the release notes at " + "https://developer.android.com/jetpack/androidx/releases/profileinstaller." } 15 -> { // RESULT_BENCHMARK_OPERATION_FAILURE "The $operation broadcast failed." } 14 -> { // RESULT_BENCHMARK_OPERATION_SUCCESS null // success! } else -> { throw RuntimeException( "unrecognized ProfileInstaller result code: $result" ) } } } fun dropShaderCache(packageName: String): String? = benchmarkOperation( packageName, "DROP_SHADER_CACHE" ) }
apache-2.0
20381bf56942c23a40b03bed6c12f696
44.624434
100
0.577564
5.146503
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/codegen/java/JavaFunSpec.kt
3
3891
/* * 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.room.compiler.codegen.java import androidx.room.compiler.codegen.L import androidx.room.compiler.codegen.VisibilityModifier import androidx.room.compiler.codegen.XAnnotationSpec import androidx.room.compiler.codegen.XCodeBlock import androidx.room.compiler.codegen.XFunSpec import androidx.room.compiler.codegen.XTypeName import androidx.room.compiler.processing.XNullability import com.squareup.javapoet.CodeBlock import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.ParameterSpec import com.squareup.kotlinpoet.javapoet.JTypeName import javax.lang.model.element.Modifier internal class JavaFunSpec( override val name: String, internal val actual: MethodSpec ) : JavaLang(), XFunSpec { internal class Builder( override val name: String, internal val actual: MethodSpec.Builder ) : JavaLang(), XFunSpec.Builder { override fun addAnnotation(annotation: XAnnotationSpec) { require(annotation is JavaAnnotationSpec) actual.addAnnotation(annotation.actual) } override fun addCode(code: XCodeBlock) = apply { require(code is JavaCodeBlock) actual.addCode(code.actual) } override fun addParameter( typeName: XTypeName, name: String, annotations: List<XAnnotationSpec> ) = apply { actual.addParameter( ParameterSpec.builder(typeName.java, name, Modifier.FINAL) .apply { if (typeName.nullability == XNullability.NULLABLE) { addAnnotation(NULLABLE_ANNOTATION) } else if (typeName.nullability == XNullability.NONNULL) { addAnnotation(NONNULL_ANNOTATION) } }.build() ) // TODO(b/247247439): Add other annotations } override fun callSuperConstructor(vararg args: XCodeBlock) = apply { actual.addStatement( "super($L)", CodeBlock.join( args.map { check(it is JavaCodeBlock) it.actual }, ", " ) ) } override fun returns(typeName: XTypeName) = apply { if (typeName.java == JTypeName.VOID) { return@apply } // TODO(b/247242374) Add nullability annotations for non-private methods if (!actual.modifiers.contains(Modifier.PRIVATE)) { if (typeName.nullability == XNullability.NULLABLE) { actual.addAnnotation(NULLABLE_ANNOTATION) } else if (typeName.nullability == XNullability.NONNULL) { actual.addAnnotation(NONNULL_ANNOTATION) } } actual.returns(typeName.java) } override fun build() = JavaFunSpec(name, actual.build()) } } internal fun VisibilityModifier.toJavaVisibilityModifier() = when (this) { VisibilityModifier.PUBLIC -> Modifier.PUBLIC VisibilityModifier.PROTECTED -> Modifier.PROTECTED VisibilityModifier.PRIVATE -> Modifier.PRIVATE }
apache-2.0
ce7092a6d08ab58f8ebef41afc9f5c13
35.716981
84
0.62606
5.059818
false
false
false
false
SDS-Studios/ScoreKeeper
app/src/main/java/io/github/sdsstudios/ScoreKeeper/ViewHolders/EditTextItem.kt
1
2004
package io.github.sdsstudios.ScoreKeeper.ViewHolders import android.content.Context import android.support.design.widget.TextInputLayout import android.text.Editable import android.text.TextWatcher import io.github.sdsstudios.ScoreKeeper.R import ir.coderz.ghostadapter.Binder import kotlin.reflect.KMutableProperty0 /** * Created by sethsch1 on 06/11/17. */ abstract class EditTextItem<T>( val ctx: Context, private val mHintId: Int ) : BaseViewItem<T>() { private lateinit var mTextInputLayout: TextInputLayout @Binder open fun bind(viewHolder: EditTextHolder) { viewHolder.apply { mTextInputLayout = textInputLayout textInputLayout.hint = ctx.getString(mHintId) if (option != null) { editText.setText(option?.get().toString()) editText.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) {} override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun onTextChanged(s: CharSequence?, p1: Int, p2: Int, p3: Int) { if (s.isNullOrBlank() && option?.name != "notes") { textInputLayout.error = ctx.getString(R.string.error_can_not_be_empty) error = true return } if (textInputLayout.error != null) { textInputLayout.error = null error = false } setData(option!!, s.toString(), textInputLayout) } }) } } } abstract fun setData(option: KMutableProperty0<T>, data: String, textInputLayout: TextInputLayout) override var error = false get() = mTextInputLayout.error != null }
gpl-3.0
030f02a0966e6db667647424b3085e5d
31.868852
99
0.556886
5.164948
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/checker/WhenNonExhaustive.kt
7
2777
fun nonExhaustiveInt(x: Int) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'else' branch">when</error>(x) { 0 -> false } fun nonExhaustiveBoolean(b: Boolean) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'true' branch or 'else' branch instead">when</error>(b) { false -> 0 } fun nonExhaustiveNullableBoolean(b: Boolean?) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'null' branch or 'else' branch instead">when</error>(b) { false -> 0 true -> 1 } enum class Color { RED, GREEN, BLUE } fun nonExhaustiveEnum(c: Color) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'RED', 'BLUE' branches or 'else' branch instead">when</error>(c) { Color.GREEN -> 0xff00 } fun nonExhaustiveNullable(c: Color?) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'GREEN', 'null' branches or 'else' branch instead">when</error>(c) { Color.RED -> 0xff Color.BLUE -> 0xff0000 } fun whenOnEnum(c: Color) { <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'RED' branch or 'else' branch instead">when</error>(c) { Color.BLUE -> {} Color.GREEN -> {} } } enum class EnumInt { A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15 } fun whenOnLongEnum(i: EnumInt) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', ... branches or 'else' branch instead">when</error> (i) { EnumInt.A7 -> 7 } sealed class Variant { object Singleton : Variant() class Something : Variant() object Another : Variant() } fun nonExhaustiveSealed(v: Variant) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'Another', 'is Something' branches or 'else' branch instead">when</error>(v) { Variant.Singleton -> false } fun nonExhaustiveNullableSealed(v: Variant?) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'Another', 'null' branches or 'else' branch instead">when</error>(v) { Variant.Singleton -> false is Variant.Something -> true } sealed class Empty fun nonExhaustiveEmpty(e: Empty) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'else' branch">when</error>(<warning descr="[UNUSED_EXPRESSION] The expression is unused">e</warning>) {} fun nonExhaustiveNullableEmpty(e: Empty?) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'else' branch">when</error>(<warning descr="[UNUSED_EXPRESSION] The expression is unused">e</warning>) {}
apache-2.0
a68090555157a7dba41a090a3a935dce
41.723077
233
0.683111
3.39072
false
false
false
false
GunoH/intellij-community
plugins/refactoring-detector/src/com/intellij/refactoring/detector/semantic/diff/SemanticDiffRefactoringProcessor.kt
7
1946
package com.intellij.refactoring.detector.semantic.diff import com.intellij.diff.DiffContext import com.intellij.diff.DiffExtension import com.intellij.diff.FrameDiffTool.DiffViewer import com.intellij.diff.requests.DiffRequest import com.intellij.diff.tools.combined.COMBINED_DIFF_MODEL import com.intellij.diff.tools.combined.COMBINED_DIFF_VIEWER_KEY import com.intellij.openapi.application.runInEdt import com.intellij.openapi.application.runReadAction import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.changes.actions.diff.ChangeDiffRequestProducer import com.intellij.refactoring.detector.RefactoringDetectorBundle import org.jetbrains.research.kotlinrminer.ide.KotlinRMiner import org.jetbrains.research.refactorinsight.kotlin.impl.data.KotlinRefactoringBuilder class SemanticDiffRefactoringProcessor : DiffExtension() { override fun onViewerCreated(viewer: DiffViewer, context: DiffContext, request: DiffRequest) { if (!Registry.`is`("enable.semantic.inlays.in.combined.diff")) return val project = context.project ?: return val combinedDiffViewer = context.getUserData(COMBINED_DIFF_VIEWER_KEY) ?: return val combinedDiffModel = context.getUserData(COMBINED_DIFF_MODEL) ?: return val changes = combinedDiffModel.requests.values .asSequence() .filterIsInstance<ChangeDiffRequestProducer>() .map(ChangeDiffRequestProducer::getChange) .toList() if (changes.isEmpty()) return runBackgroundableTask(RefactoringDetectorBundle.message("progress.find.refactoring.title")) { val refactorings = runReadAction { KotlinRMiner.detectRefactorings(project, changes) } val refactoringEntry = KotlinRefactoringBuilder.convertRefactorings(refactorings) context.putUserData(REFACTORING_ENTRY, refactoringEntry) runInEdt { combinedDiffViewer.rediff() } } } }
apache-2.0
c11810569d32cdcc08d2ab2566a8e59a
42.244444
97
0.801131
4.515081
false
false
false
false
siosio/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/tree/base.kt
1
4945
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.nj2k.tree import com.intellij.psi.PsiElement import org.jetbrains.kotlin.nj2k.tree.visitors.JKVisitor import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty interface JKElement { val parent: JKElement? fun detach(from: JKElement) fun attach(to: JKElement) } private class JKChild<T : JKElement>(val value: Int) : ReadWriteProperty<JKTreeElement, T> { override operator fun getValue(thisRef: JKTreeElement, property: KProperty<*>): T { @Suppress("UNCHECKED_CAST") return thisRef.children[value] as T } override operator fun setValue(thisRef: JKTreeElement, property: KProperty<*>, value: T) { @Suppress("UNCHECKED_CAST") (thisRef.children[this.value] as T).detach(thisRef) thisRef.children[this.value] = value value.attach(thisRef) } } private class JKListChild<T : JKElement>(val value: Int) : ReadWriteProperty<JKTreeElement, List<T>> { override operator fun getValue(thisRef: JKTreeElement, property: KProperty<*>): List<T> { @Suppress("UNCHECKED_CAST") return thisRef.children[value] as List<T> } override operator fun setValue(thisRef: JKTreeElement, property: KProperty<*>, value: List<T>) { @Suppress("UNCHECKED_CAST") (thisRef.children[this.value] as List<T>).forEach { it.detach(thisRef) } thisRef.children[this.value] = value value.forEach { it.attach(thisRef) } } } abstract class JKTreeElement : JKElement, JKFormattingOwner, Cloneable { override val trailingComments: MutableList<JKComment> = mutableListOf() override val leadingComments: MutableList<JKComment> = mutableListOf() override var hasTrailingLineBreak = false override var hasLeadingLineBreak = false override var parent: JKElement? = null override fun detach(from: JKElement) { val prevParent = parent require(from == prevParent) { "Incorrect detach: From: $from, Actual: $prevParent" } parent = null } override fun attach(to: JKElement) { check(parent == null) parent = to } open fun accept(visitor: JKVisitor) = visitor.visitTreeElement(this) private var childNum = 0 protected fun <T : JKTreeElement, U : T> child(v: U): ReadWriteProperty<JKTreeElement, T> { children.add(childNum, v) v.attach(this) return JKChild(childNum++) } protected inline fun <reified T : JKTreeElement> children(): ReadWriteProperty<JKTreeElement, List<T>> { return children(emptyList()) } protected fun <T : JKTreeElement> children(v: List<T>): ReadWriteProperty<JKTreeElement, List<T>> { children.add(childNum, v) v.forEach { it.attach(this) } return JKListChild(childNum++) } open fun acceptChildren(visitor: JKVisitor) { forEachChild { it.accept(visitor) } } private inline fun forEachChild(block: (JKTreeElement) -> Unit) { children.forEach { @Suppress("UNCHECKED_CAST") if (it is JKTreeElement) block(it) else (it as? List<JKTreeElement>)?.forEach { block(it) } } } private var valid: Boolean = true fun invalidate() { forEachChild { it.detach(this) } valid = false } fun onAttach() { check(valid) } var children: MutableList<Any> = mutableListOf() private set @Suppress("UNCHECKED_CAST") open fun copy(): JKTreeElement { val cloned = clone() as JKTreeElement val deepClonedChildren = cloned.children.map { when (it) { is JKTreeElement -> it.copy() is List<*> -> (it as List<JKTreeElement>).map { it.copy() } else -> error("Tree is corrupted") } } deepClonedChildren.forEach { child -> when (child) { is JKTreeElement -> { child.detach(this) child.attach(cloned) } is List<*> -> (child as List<JKTreeElement>).forEach { it.detach(this) it.attach(cloned) } } } cloned.children = deepClonedChildren.toMutableList() return cloned } } abstract class JKAnnotationMemberValue : JKTreeElement() interface PsiOwner { var psi: PsiElement? } class PsiOwnerImpl(override var psi: PsiElement? = null) : PsiOwner interface JKTypeArgumentListOwner : JKFormattingOwner { var typeArgumentList: JKTypeArgumentList } interface JKTypeParameterListOwner : JKFormattingOwner { var typeParameterList: JKTypeParameterList }
apache-2.0
44808b980c1a01cac7d649d7d3929e3e
29.90625
158
0.62912
4.557604
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedEqualsInspection.kt
3
2673
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.intentions.conventionNameCalls.isAnyEquals import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.util.OperatorNameConventions class UnusedEqualsInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return object : KtVisitorVoid() { private fun reportIfNotUsedAsExpression(expression: KtExpression) { val context = expression.safeAnalyzeNonSourceRootCode() if (context != BindingContext.EMPTY && !expression.isUsedAsExpression(context)) { holder.registerProblem(expression, KotlinBundle.message("unused.equals.expression")) } } override fun visitBinaryExpression(expression: KtBinaryExpression) { super.visitBinaryExpression(expression) if (expression.operationToken == KtTokens.EQEQ) { val parent = expression.parent val shouldReport = when { parent.parent is KtIfExpression -> true parent is KtBlockExpression -> parent.parent !is KtCodeFragment || parent.statements.lastOrNull() != expression else -> false } if (shouldReport) { reportIfNotUsedAsExpression(expression) } } } override fun visitCallExpression(expression: KtCallExpression) { super.visitCallExpression(expression) val calleeExpression = expression.calleeExpression as? KtSimpleNameExpression ?: return if (calleeExpression.getReferencedNameAsName() != OperatorNameConventions.EQUALS) return if (!expression.isAnyEquals()) return reportIfNotUsedAsExpression(expression.getQualifiedExpressionForSelectorOrThis()) } } } }
apache-2.0
ed5eef6ae923214db581de30692455a5
45.103448
158
0.681631
6.144828
false
false
false
false
smmribeiro/intellij-community
plugins/ide-features-trainer/src/training/actions/DumpFeaturesTrainerText.kt
1
3183
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:Suppress("HardCodedStringLiteral") package training.actions import com.intellij.ide.CopyPasteManagerEx import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.dsl.builder.bind import com.intellij.ui.dsl.builder.panel import training.dsl.LearningBalloonConfig import training.dsl.LessonContext import training.dsl.RuntimeTextContext import training.dsl.TaskContext import training.dsl.impl.LessonExecutorUtil import training.learn.CourseManager import training.learn.course.KLesson import java.awt.datatransfer.StringSelection import javax.swing.JComponent private enum class IftDumpMode { TEXT_ONLY, CODE_POSITIONS } private class DumpFeaturesTrainerText : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val dialog = object : DialogWrapper(project) { var mode = IftDumpMode.TEXT_ONLY override fun createCenterPanel(): JComponent = panel { buttonsGroup { row { radioButton("Text only", IftDumpMode.TEXT_ONLY) radioButton("Code positions", IftDumpMode.CODE_POSITIONS) } }.bind(::mode) } init { init() title = "What Do You Want to Copy?" } } dialog.show() val lessonsForModules = CourseManager.instance.lessonsForModules val buffer = StringBuffer() for (x in lessonsForModules) { if (x is KLesson) { buffer.append(x.name) buffer.append(":\n") x.lessonContent(ApplyTaskLessonContext(buffer, project, dialog.mode)) buffer.append('\n') } } CopyPasteManagerEx.getInstance().setContents(StringSelection(buffer.toString())) } } private class TextCollector(private val buffer: StringBuffer, override val project: Project) : TaskContext() { override fun text(text: String, useBalloon: LearningBalloonConfig?) { buffer.append(text) buffer.append('\n') } override fun runtimeText(callback: RuntimeTextContext.() -> String?) { // TODO: think how to dump it } } private class ApplyTaskLessonContext(private val buffer: StringBuffer, private val project: Project, private val mode: IftDumpMode) : LessonContext() { private var internalTaskNumber = 0 private var taskVisualIndex = 1 override fun task(taskContent: TaskContext.() -> Unit) { buffer.append("($internalTaskNumber -> $taskVisualIndex) ") if (mode == IftDumpMode.TEXT_ONLY) { val taskContext: TaskContext = TextCollector(buffer, project) taskContent(taskContext) } if (mode == IftDumpMode.CODE_POSITIONS) { buffer.append(LessonExecutorUtil.getTaskCallInfo()) buffer.append('\n') } val taskProperties = LessonExecutorUtil.taskProperties(taskContent, project) if (taskProperties.hasDetection && taskProperties.messagesNumber > 0) { taskVisualIndex++ } internalTaskNumber++ } }
apache-2.0
a8d8ef1541c0dd461c0bec6cd7efeac5
32.166667
151
0.722275
4.295547
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinWhileConditionFixer.kt
6
821
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.editor.fixers import com.intellij.psi.PsiElement import org.jetbrains.kotlin.psi.KtWhileExpression class KotlinWhileConditionFixer : MissingConditionFixer<KtWhileExpression>() { override val keyword = "while" override fun getElement(element: PsiElement?) = element as? KtWhileExpression override fun getCondition(element: KtWhileExpression) = element.condition override fun getLeftParenthesis(element: KtWhileExpression) = element.leftParenthesis override fun getRightParenthesis(element: KtWhileExpression) = element.rightParenthesis override fun getBody(element: KtWhileExpression) = element.body }
apache-2.0
0a5ae9bc9f30a15218506b96dcce0dd1
53.733333
158
0.805116
4.857988
false
false
false
false
smmribeiro/intellij-community
plugins/jps-cache/src/com/intellij/jps/cache/diffExperiment/JpsCacheTools.kt
5
5976
package com.intellij.jps.cache.diffExperiment import com.github.luben.zstd.Zstd import com.github.luben.zstd.ZstdInputStream import com.google.common.collect.Maps import com.google.common.hash.Hashing import com.google.common.io.CountingInputStream import com.google.common.io.Files import com.google.gson.Gson import com.intellij.openapi.util.io.FileUtil import com.intellij.util.concurrency.AppExecutorUtil import java.io.File import java.io.InputStream import java.io.Reader import java.nio.charset.StandardCharsets import java.nio.file.FileVisitResult import java.nio.file.Path import java.nio.file.SimpleFileVisitor import java.nio.file.attribute.BasicFileAttributes import java.util.concurrent.ExecutorService import java.util.concurrent.Future import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException import kotlin.math.ceil import java.nio.file.Files as NioFiles data class JpsCacheFileInfo(val size: Long, val path: String, @Volatile var hash: Long = 0) { companion object { private const val minSizeToZip = 512 private fun archive(uncompressed: ByteArray): ByteArray { return Zstd.compress(uncompressed) } } private val shouldArchive = size > minSizeToZip fun forUploading(srcFolder: File): ByteArray = File(srcFolder, path).readBytes().let { bytes -> if (shouldArchive) archive(bytes) else bytes } fun afterDownloading(destFolder: File, dataStream: InputStream): Long { val countingDataStream = CountingInputStream(dataStream) val dest = File(destFolder, path).apply { parentFile.mkdirs() } (if (shouldArchive) ZstdInputStream(countingDataStream) else countingDataStream).use { stream -> dest.writeBytes(stream.readBytes()) } return countingDataStream.count } fun getUrl(baseUrl: String) = "$baseUrl/$path/$hash" } class JpsCacheTools(val secondsToWaitForFuture: Long) { companion object { private const val EXPECTED_NUMBER_OF_FILES = 60_000 private val HASH_FUNCTION = Hashing.murmur3_128() private const val MANIFESTS_PATH = "manifests" } inner class ExecutionApi { private val futures = mutableListOf<Future<*>>() fun execute(code: () -> Unit) { futures.add(executor.submit(code)) } fun waitForFutures(statusListener: ((completed: Int) -> Unit)? = null): Boolean { val step: Int = ceil(futures.size.toDouble() / 100).toInt() var completed = 0 var percent = 0 try { futures.forEach { it.get(secondsToWaitForFuture, TimeUnit.SECONDS) statusListener?.let { completed++ val newPercent = completed / step if (newPercent != percent) { percent = newPercent it(newPercent) } } } return true } catch (_: TimeoutException) { return false } } } private val executor: ExecutorService init { val numOfThreads = Runtime.getRuntime().availableProcessors() - 1 executor = AppExecutorUtil.createBoundedApplicationPoolExecutor("JPS_Cache", numOfThreads) } fun getJsonByState(files: Collection<JpsCacheFileInfo>): String = Gson().toJson(ArrayList(files)) fun getStateByJsonFile(jsonFilePath: Path): List<JpsCacheFileInfo> = getStateByReader( Files.newReader(jsonFilePath.toFile(), StandardCharsets.UTF_8)) fun getZippedManifestUrl(baseUrl: String, commitHash: String) = "$baseUrl/$MANIFESTS_PATH/$commitHash" @JvmOverloads fun getStateByFolder(rootPath: Path, existing: Map<String, JpsCacheFileInfo>? = null): List<JpsCacheFileInfo> { val rootFile = rootPath.toFile() val result: MutableList<JpsCacheFileInfo> = ArrayList(EXPECTED_NUMBER_OF_FILES) withExecutor { executor -> NioFiles.walkFileTree(rootPath, object : SimpleFileVisitor<Path>() { override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { val relativePath = FileUtil.getRelativePath(rootFile, file.toFile())!!.replace(File.separatorChar, '/') val fileSize = attrs.size() val fileInfo = JpsCacheFileInfo(fileSize, relativePath) result.add(fileInfo) existing?.get(relativePath)?.let { existingInfo -> if (existingInfo.size != fileSize) { return FileVisitResult.CONTINUE } } executor.execute { fileInfo.hash = getHash(file) } return FileVisitResult.CONTINUE } }) } return result } fun withExecutor(statusListener: ((completed: Int) -> Unit)? = null, code: (executeApi: ExecutionApi) -> Unit): Boolean { val api = ExecutionApi() code(api) return api.waitForFutures(statusListener) } fun getFilesToUpdate(folder: Path, toState: List<JpsCacheFileInfo>): List<JpsCacheFileInfo> { val toStateMap = mapFromList(toState) val currentState = getStateByFolder(folder, toStateMap) return getFilesToUpdate(currentState, toStateMap) } fun getFilesToUpdate(fromState: List<JpsCacheFileInfo>, toState: List<JpsCacheFileInfo>): List<JpsCacheFileInfo> { return getFilesToUpdate(fromState, mapFromList(toState)) } private fun getFilesToUpdate(fromState: List<JpsCacheFileInfo>, toState: Map<String, JpsCacheFileInfo>): List<JpsCacheFileInfo> = Maps.difference(mapFromList(fromState), toState).let { difference -> difference.entriesOnlyOnRight().map { it.value } + difference.entriesDiffering().values.map { it.rightValue() } } private fun getHash(file: Path): Long = Files.asByteSource(file.toFile()).hash(HASH_FUNCTION).asLong() private fun mapFromList(list: List<JpsCacheFileInfo>): Map<String, JpsCacheFileInfo> = list.associateBy { it.path } private fun getStateByReader(readerWithJson: Reader): List<JpsCacheFileInfo> = Gson().fromJson(readerWithJson, Array<JpsCacheFileInfo>::class.java).toList() }
apache-2.0
3b09ca645037d097498deab542c66ebc
35.662577
123
0.701807
4.333575
false
false
false
false
triplesic/springboot-kotlin-boilerplate
src/main/kotlin/org/triplesic/kotlin/boilerplate/entity/Token.kt
1
851
package org.triplesic.kotlin.boilerplate.entity import java.time.LocalDateTime import javax.persistence.* import javax.validation.constraints.NotNull @Entity data class Token( @TableGenerator(name = "token_gen", table = "ID_GEN", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VAL", pkColumnValue = "tokn_gen", initialValue = 10, allocationSize = 100) @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "token_gen") var id: Long = 0L, @Lob @NotNull @Column(length = 1000) var value: String = "", var userId: Long = 0L, var createdDate: LocalDateTime = LocalDateTime.now(), var revisedDate: LocalDateTime = LocalDateTime.now(), var expiredDate: LocalDateTime = LocalDateTime.now() )
mit
94d1deed9f1182df7275486e66246a9a
36.043478
84
0.623972
4.432292
false
false
false
false
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/Screens.kt
1
5299
package com.ivanovsky.passnotes.presentation import androidx.fragment.app.FragmentFactory import com.github.terrakok.cicerone.androidx.FragmentScreen import com.ivanovsky.passnotes.presentation.about.AboutFragment import com.ivanovsky.passnotes.presentation.debugmenu.DebugMenuFragment import com.ivanovsky.passnotes.presentation.filepicker.FilePickerFragment import com.ivanovsky.passnotes.presentation.filepicker.model.FilePickerArgs import com.ivanovsky.passnotes.presentation.group_editor.GroupEditorArgs import com.ivanovsky.passnotes.presentation.group_editor.GroupEditorFragment import com.ivanovsky.passnotes.presentation.groups.GroupsArgs import com.ivanovsky.passnotes.presentation.groups.GroupsFragment import com.ivanovsky.passnotes.presentation.newdb.NewDatabaseFragment import com.ivanovsky.passnotes.presentation.note.NoteFragment import com.ivanovsky.passnotes.presentation.note_editor.NoteEditorArgs import com.ivanovsky.passnotes.presentation.note_editor.NoteEditorFragment import com.ivanovsky.passnotes.presentation.search.SearchFragment import com.ivanovsky.passnotes.presentation.selectdb.SelectDatabaseArgs import com.ivanovsky.passnotes.presentation.selectdb.SelectDatabaseFragment import com.ivanovsky.passnotes.presentation.server_login.ServerLoginArgs import com.ivanovsky.passnotes.presentation.server_login.ServerLoginFragment import com.ivanovsky.passnotes.presentation.settings.app.AppSettingsFragment import com.ivanovsky.passnotes.presentation.settings.database.DatabaseSettingsFragment import com.ivanovsky.passnotes.presentation.settings.main.MainSettingsFragment import com.ivanovsky.passnotes.presentation.storagelist.Action import com.ivanovsky.passnotes.presentation.storagelist.StorageListFragment import com.ivanovsky.passnotes.presentation.unlock.UnlockFragment import java.util.UUID object Screens { class UnlockScreen : FragmentScreen { override fun createFragment(factory: FragmentFactory) = UnlockFragment.newInstance() } class SelectDatabaseScreen(private val args: SelectDatabaseArgs) : FragmentScreen { override fun createFragment(factory: FragmentFactory) = SelectDatabaseFragment.newInstance(args) companion object { val RESULT_KEY = SelectDatabaseScreen::class.simpleName + "_result" } } // File and Storage class StorageListScreen(private val action: Action) : FragmentScreen { override fun createFragment(factory: FragmentFactory) = StorageListFragment.newInstance(action) companion object { val RESULT_KEY = StorageListScreen::class.simpleName + "_result" } } class FilePickerScreen(private val args: FilePickerArgs) : FragmentScreen { override fun createFragment(factory: FragmentFactory) = FilePickerFragment.newInstance(args) companion object { val RESULT_KEY = FilePickerScreen::class.simpleName + "_result" } } // Network class ServerLoginScreen(private val args: ServerLoginArgs) : FragmentScreen { override fun createFragment(factory: FragmentFactory) = ServerLoginFragment.newInstance(args) companion object { val RESULT_KEY = ServerLoginScreen::class.simpleName + "_result" } } // Database class NewDatabaseScreen : FragmentScreen { override fun createFragment(factory: FragmentFactory) = NewDatabaseFragment.newInstance() } // View Notes and Groups class GroupsScreen(private val args: GroupsArgs) : FragmentScreen { override fun createFragment(factory: FragmentFactory) = GroupsFragment.newInstance(args) } class GroupEditorScreen(private val args: GroupEditorArgs) : FragmentScreen { override fun createFragment(factory: FragmentFactory) = GroupEditorFragment.newInstance(args) } class NoteEditorScreen(private val args: NoteEditorArgs) : FragmentScreen { override fun createFragment(factory: FragmentFactory) = NoteEditorFragment.newInstance(args) } class NoteScreen(private val noteUid: UUID) : FragmentScreen { override fun createFragment(factory: FragmentFactory) = NoteFragment.newInstance(noteUid) } class SearchScreen : FragmentScreen { override fun createFragment(factory: FragmentFactory) = SearchFragment.newInstance() } class AboutScreen : FragmentScreen { override fun createFragment(factory: FragmentFactory) = AboutFragment.newInstance() } // Settings class MainSettingsScreen : FragmentScreen { override fun createFragment(factory: FragmentFactory) = MainSettingsFragment.newInstance() } class AppSettingsScreen : FragmentScreen { override fun createFragment(factory: FragmentFactory) = AppSettingsFragment.newInstance() } class DatabaseSettingsScreen : FragmentScreen { override fun createFragment(factory: FragmentFactory) = DatabaseSettingsFragment.newInstance() } // Debug class DebugMenuScreen : FragmentScreen { override fun createFragment(factory: FragmentFactory) = DebugMenuFragment.newInstance() } }
gpl-2.0
42e70ad907fba824df15f9d70adf7075
38.259259
87
0.751274
5.246535
false
false
false
false
kerubistan/kerub
src/main/kotlin/com/github/kerubistan/kerub/planner/issues/violations/vstorage/StorageRedundancyExpectationViolationDetector.kt
2
1487
package com.github.kerubistan.kerub.planner.issues.violations.vstorage import com.github.kerubistan.kerub.model.VirtualStorageDevice import com.github.kerubistan.kerub.model.expectations.StorageRedundancyExpectation import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.issues.violations.VStorageViolationDetector object StorageRedundancyExpectationViolationDetector : VStorageViolationDetector<StorageRedundancyExpectation> { override fun check( entity: VirtualStorageDevice, expectation: StorageRedundancyExpectation, state: OperationalState ) = if (expectation.outOfBox) { checkOutOfTheBox(entity, expectation, state) } else { checkLocal(entity, expectation, state) } private fun checkLocal( entity: VirtualStorageDevice, expectation: StorageRedundancyExpectation, state: OperationalState ) = state.vStorage[entity.id]?.dynamic?.allocations?.let { it.sumBy { it.getRedundancyLevel() .toInt() + 1 } - 1 } ?: 0 >= expectation.nrOfCopies /* This may not be correct when doing gluster or ceph, because there it will probably be just a single allocation while it will still have replicas on several boxes */ private fun checkOutOfTheBox( entity: VirtualStorageDevice, expectation: StorageRedundancyExpectation, state: OperationalState ) = state.vStorage[entity.id]?.dynamic?.allocations?.distinctBy { it.hostId }?.size ?: 0 >= expectation.nrOfCopies }
apache-2.0
909e7c88d0247cde852e14ec2f52395b
33.604651
115
0.776732
4.224432
false
false
false
false
seventhroot/elysium
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/command/character/set/CharacterSetDeadCommand.kt
1
7889
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.characters.bukkit.command.character.set import com.rpkit.characters.bukkit.RPKCharactersBukkit import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import org.apache.commons.lang.BooleanUtils import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.conversations.* import org.bukkit.entity.Player /** * Character set dead command. * Sets character's dead state. */ class CharacterSetDeadCommand(private val plugin: RPKCharactersBukkit): CommandExecutor { private val conversationFactory: ConversationFactory init { conversationFactory = ConversationFactory(plugin) .withModality(true) .withFirstPrompt(DeadPrompt()) .withEscapeSequence("cancel") .thatExcludesNonPlayersWithMessage(plugin.messages["not-from-console"]) .addConversationAbandonedListener { event -> if (!event.gracefulExit()) { val conversable = event.context.forWhom if (conversable is Player) { conversable.sendMessage(plugin.messages["operation-cancelled"]) } } } } override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { if (sender is Player) { if (sender.hasPermission("rpkit.characters.command.character.set.dead")) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender) if (minecraftProfile != null) { val character = characterProvider.getActiveCharacter(minecraftProfile) if (character != null) { if (args.isNotEmpty()) { val dead = BooleanUtils.toBoolean(args[0]) if (dead && sender.hasPermission("rpkit.characters.command.character.set.dead.yes") || !dead && sender.hasPermission("rpkit.characters.command.character.set.dead.no")) { character.isDead = dead characterProvider.updateCharacter(character) sender.sendMessage(plugin.messages["character-set-dead-valid"]) character.showCharacterCard(minecraftProfile) } else { sender.sendMessage(plugin.messages["no-permission-character-set-dead-" + if (dead) "yes" else "no"]) } } else { conversationFactory.buildConversation(sender).begin() } } else { sender.sendMessage(plugin.messages["no-character"]) } } else { sender.sendMessage(plugin.messages["no-minecraft-profile"]) } } else { sender.sendMessage(plugin.messages["no-permission-character-set-dead"]) } } else { sender.sendMessage(plugin.messages["not-from-console"]) } return true } private inner class DeadPrompt: BooleanPrompt() { override fun acceptValidatedInput(context: ConversationContext, input: Boolean): Prompt { val conversable = context.forWhom if (conversable is Player) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(conversable) if (minecraftProfile != null) { val character = characterProvider.getActiveCharacter(minecraftProfile) if (character != null) { return if (input && conversable.hasPermission("rpkit.characters.command.character.set.dead.yes") || !input && conversable.hasPermission("rpkit.characters.command.character.set.dead.no")) { character.isDead = input characterProvider.updateCharacter(character) DeadSetPrompt() } else { DeadNotSetNoPermissionPrompt(input) } } } } return DeadSetPrompt() } override fun getFailedValidationText(context: ConversationContext, invalidInput: String): String { return plugin.messages["character-set-dead-invalid-boolean"] } override fun getPromptText(context: ConversationContext): String { return plugin.messages["character-set-dead-prompt"] } } private inner class DeadSetPrompt: MessagePrompt() { override fun getNextPrompt(context: ConversationContext): Prompt? { val conversable = context.forWhom if (conversable is Player) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(context.forWhom as Player) if (minecraftProfile != null) { characterProvider.getActiveCharacter(minecraftProfile)?.showCharacterCard(minecraftProfile) } } return Prompt.END_OF_CONVERSATION } override fun getPromptText(context: ConversationContext): String { return plugin.messages["character-set-dead-valid"] } } private inner class DeadNotSetNoPermissionPrompt(private val dead: Boolean): MessagePrompt() { override fun getNextPrompt(context: ConversationContext): Prompt? { val conversable = context.forWhom if (conversable is Player) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(context.forWhom as Player) if (minecraftProfile != null) { characterProvider.getActiveCharacter(minecraftProfile)?.showCharacterCard(minecraftProfile) } } return Prompt.END_OF_CONVERSATION } override fun getPromptText(context: ConversationContext): String { return plugin.messages["no-permission-character-set-dead-" + if (dead) "yes" else "no"] } } }
apache-2.0
b36741a79ca7fb212347539ea5321a11
46.812121
212
0.628343
5.716667
false
false
false
false
drmaas/ratpack-kotlin
ratpack-kotlin-test/src/test/kotlin/ratpack/kotlin/test/RatpackKotlinApplicationUnderTestTest.kt
1
2353
package ratpack.kotlin.test import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import ratpack.guice.BindingsImposition import ratpack.impose.ImpositionsSpec import ratpack.kotlin.test.embed.ratpack import ratpack.server.RatpackServer class RatpackKotlinApplicationUnderTestTest: StringSpec() { init { "test an app via main class" { val aut = kotlinApplicationUnderTest(SampleApp::class) val client = testHttpClient(aut) val response = client.get() response.statusCode shouldBe 200 response.body.text shouldBe "foo" aut.close() } "test an app via url" { val app = sampleApp() app.start() val aut = kotlinApplicationUnderTest("${app.scheme}://${app.bindHost}:${app.bindPort}") val client = testHttpClient(aut) val response = client.get() response.statusCode shouldBe 200 response.body.text shouldBe "foo" app.stop() } "test an app via RatpackServer" { val aut = kotlinApplicationUnderTest(sampleApp()) val client = testHttpClient(aut) val response = client.get() response.statusCode shouldBe 200 response.body.text shouldBe "foo" aut.getRegistry() shouldNotBe null aut.close() } "test an app via main class with impositions" { val aut = object : KMainClassApplicationUnderTest(SampleApp::class) { override fun addImpositions(impositions: ImpositionsSpec?) { impositions?.add(BindingsImposition.of { it.bindInstance(String::class.java, "bar") }) } } aut.test {client -> val response = client.get() response.statusCode shouldBe 200 response.body.text shouldBe "bar" aut.getRegistry() shouldNotBe null } } } } class SampleApp { companion object { @JvmStatic fun main(args: Array<String>) { ratpack { serverConfig { port(8089) } bindings { bindInstance(String::class.java, "foo") } handlers { get { render(get(String::class.java)) } } } } } } fun sampleApp(): RatpackServer { return ratpack { serverConfig { port(8089) } handlers { get { render("foo") } } }.server }
apache-2.0
7df255c87dd0d225eea417345fc04af4
24.576087
96
0.628984
4.216846
false
true
false
false
oversecio/oversec_crypto
crypto/src/main/java/io/oversec/one/crypto/encoding/XCoderAndPadder.kt
1
811
package io.oversec.one.crypto.encoding import io.oversec.one.crypto.encoding.pad.AbstractPadder import io.oversec.one.crypto.proto.Outer class XCoderAndPadder(val xcoder: IXCoder, val padder: AbstractPadder?) { val label: String get() = xcoder.getLabel(padder) val example: String get() = xcoder.getExample(padder) val id: String get() = xcoder.id + (padder?.let{ "__" + it.id} ?: "") val coderId: String? get() = xcoder.id val padderId: String? get() = padder?.id @Synchronized @Throws(Exception::class) fun encode( msg: Outer.Msg, srcText: String, appendNewLines: Boolean, packagename: String ): String { return xcoder.encode(msg, padder, srcText, appendNewLines, packagename) } }
gpl-3.0
584f5bfdfed2571add66f836ace61b26
23.575758
79
0.630086
3.686364
false
false
false
false
Litote/kmongo
kmongo-rxjava2-core-tests/src/main/kotlin/org/litote/kmongo/rxjava2/AggregateTest.kt
1
3858
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo.rxjava2 import com.mongodb.MongoCommandException import com.mongodb.reactivestreams.client.MongoCollection import kotlinx.serialization.Serializable import org.junit.After import org.junit.Before import org.junit.Test import org.litote.kmongo.MongoOperator.* import org.litote.kmongo.model.Friend import kotlin.reflect.KClass import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertTrue class AggregateTest : KMongoRxBaseTest<AggregateTest.Article>() { @Serializable data class Article(val title: String, val author: String, val tags: List<String>) { constructor(title: String, author: String, vararg tags: String) : this(title, author, tags.asList()) } lateinit var friendCol: MongoCollection<Friend> @Before fun setup() { col.insertOne(Article("Zombie Panic", "Kirsty Mckay", "horror", "virus")).blockingAwait() col.insertOne(Article("Apocalypse Zombie", "Maberry Jonathan", "horror", "dead")).blockingAwait() col.insertOne(Article("World War Z", "Max Brooks", "horror", "virus", "pandemic")).blockingAwait() friendCol = getCollection<Friend>() friendCol.insertOne(Friend("William")).blockingAwait() friendCol.insertOne(Friend("John")).blockingAwait() friendCol.insertOne(Friend("Richard")).blockingAwait() } @After fun tearDown() { rule.dropCollection<Friend>().blockingAwait() } override fun getDefaultCollectionClass(): KClass<Article> = Article::class @Test fun canAggregate() { col.aggregate<Article>("{$match:{}}").toObservable().blockingIterable().toList() } @Test fun canAggregateWithMultipleDocuments() { val data = col.aggregate<Article>("{$match:{tags:'virus'}}").toObservable().blockingIterable().toList() assertEquals(2, data.size) assertTrue(data.all { it.tags.contains("virus") }) } @Test fun canAggregateParameters() { val tag = "pandemic" val data = col.aggregate<Article>("{$match:{tags:'$tag'}}").toObservable().blockingIterable().toList() assertEquals(1, data.size) assertEquals("World War Z", data.first().title) } @Test fun canAggregateWithManyMatch() { val data = col.aggregate<Article>("{$match:{$and:[{tags:'virus'}, {tags:'pandemic'}]}}").toObservable().blockingIterable().toList() assertEquals(1, data.size) assertEquals("World War Z", data.first().title) } @Test fun canAggregateWithManyOperators() { val data = col.aggregate<Article>("[{$match:{tags:'virus'}},{$limit:1}]").toObservable().blockingIterable().toList() assertEquals(1, data.size) } @Test fun shouldCheckIfCommandHasErrors() { assertFailsWith(MongoCommandException::class) { col.aggregate<Article>("{\$invalid:{}}") .toObservable().blockingIterable().toList() } } @Test fun shouldPopulateIds() { val data = friendCol.aggregate<Friend>("{$project: {_id: '\$_id', name: '\$name'}}") .toObservable().blockingIterable().toList() assertEquals(3, data.size) assertTrue(data.all { it._id != null }) } }
apache-2.0
2296ffe1ab00a588d00a5e301c41b2de
33.756757
139
0.671073
4.170811
false
true
false
false
Litote/kmongo
kmongo-shared/src/main/kotlin/org/litote/kmongo/service/ClassMappingType.kt
1
2147
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo.service import java.util.ServiceLoader private val mappingTypeProvider by lazy { ServiceLoader.load(ClassMappingTypeService::class.java) } private val defaultService by lazy { var priority = Integer.MIN_VALUE var current: ClassMappingTypeService? = null mappingTypeProvider.iterator().apply { while (hasNext()) { val n = next() if (n.priority() > priority) { current = n priority = n.priority() } } } current ?: error("Service ClassMappingTypeService not found") } @Volatile private var selectedService: ClassMappingTypeService? = (System.getProperty("org.litote.mongo.mapping.service") ?: System.getProperty("org.litote.mongo.test.mapping.service")) ?.let { Class.forName(it).getConstructor().newInstance() as ClassMappingTypeService } private var currentService: ClassMappingTypeService get() = selectedService ?: defaultService set(value) { selectedService = value } /** * [ClassMappingTypeService] currently used retrieved via [java.util.ServiceLoader]. */ object ClassMappingType : ClassMappingTypeService by currentService { /** * Do not use the [ClassMappingTypeService.priority] method do define the service used, * and force the use of the specified service. * Use this method at startup only. */ fun forceService(service: ClassMappingTypeService) { selectedService = service } }
apache-2.0
c10402ca483414f9f2f7447a25b7758d
30.588235
91
0.685142
4.587607
false
false
false
false
TGITS/programming-workouts
kotlin/basic/dice/kobalt/src/Build.kt
1
536
import com.beust.kobalt.* import com.beust.kobalt.plugin.packaging.* import com.beust.kobalt.plugin.application.* import com.beust.kobalt.plugin.kotlin.* val p = project { name = "dice" group = "tgits.workouts.basic" artifactId = name version = "0.1" dependencies { // compile("com.beust:jcommander:1.68") } dependenciesTest { compile("org.testng:testng:6.11") } assemble { jar { } } application { mainClass = "tgits.workouts.basic.MainKt" } }
mit
da39649972f8acf2b41a5b4e32b19a38
18.142857
49
0.606343
3.480519
false
true
false
false
star3136/DemoCollection
app/src/main/java/com/lee/democollection/view/itemdecoration/GridDividerItemDecoration.kt
1
4322
package com.lee.democollection.view.itemdecoration import android.graphics.Canvas import android.graphics.Color import android.graphics.Rect import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import android.view.View /** * Created by Allen on 2017/6/1. */ class GridDividerItemDecoration : RecyclerView.ItemDecoration { var mDivider : Drawable ?= null var mDividerSize = -1 var mClose = true var mEnableRow = true //允许行线 var mEnableCol = true //允许列线 constructor(close : Boolean){ mClose = close mDivider = ColorDrawable(Color.BLACK) mDividerSize = 1 } fun setEnableRow(enableRow : Boolean){ mEnableRow = enableRow } fun setEnableCol(enableCol : Boolean){ mEnableCol = enableCol } fun setDividerSize(dividerSize : Int){ mDividerSize = dividerSize } fun setDivider(divider : Drawable){ mDivider = divider } override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) { if(mClose){ // var pos = parent?.getChildAdapterPosition(view) // var layout = parent.layoutManager as GridLayoutManager // val spanCount = layout.spanCount with(parent!!){ var pos = getChildAdapterPosition(view) var layout = layoutManager as GridLayoutManager val spanCount = layout.spanCount var fisrtRow = pos < spanCount //第一行 // var lastRow = childCount - pos <= spanCount //最后一行 var firstCol = pos % spanCount == 0 //第一列 // var lastCol = pos % spanCount == spanCount - 1 || pos == childCount - 1 //最后一列 var left = 0 var top = 0 if(firstCol){ left = mDividerSize } if(fisrtRow){ top = mDividerSize } outRect?.set(left, top, mDividerSize, mDividerSize) } }else{ outRect?.set(0, 0, mDividerSize, mDividerSize) } } override fun onDraw(c: Canvas?, parent: RecyclerView?, state: RecyclerView.State?) { val childCount = parent!!.childCount var layout = parent.layoutManager as GridLayoutManager val spanCount = layout.spanCount for (i in 0 until childCount){ var fisrtRow = i < spanCount //第一行 var lastRow = childCount - i <= spanCount //最后一行 var firstCol = i % spanCount == 0 //第一列 var lastCol = i % spanCount == spanCount - 1 || i == childCount - 1 //最后一列 var child = parent.getChildAt(i) if(mEnableCol){ /** * 横向绘制竖线 */ drawHorizontal(c, child, firstCol, lastCol) } if(mEnableRow){ /** * 竖向绘制横线 */ drawVertical(c, child, fisrtRow, lastRow) } } } fun drawHorizontal(c : Canvas ?, child : View?, firstCol : Boolean, lastCol : Boolean){ if(firstCol && mClose){ mDivider!!.setBounds(child!!.left - mDividerSize, child.top, child.left, child.bottom + mDividerSize) mDivider!!.draw(c) } if(mClose || !lastCol){ mDivider!!.setBounds(child!!.right, child.top, child.right + mDividerSize, child.bottom + mDividerSize) mDivider!!.draw(c) } } fun drawVertical(c : Canvas ?, child : View?, fistRow : Boolean, lastRow : Boolean){ if(fistRow && mClose){ var left = if(mEnableRow && mEnableCol) child!!.left - mDividerSize else child!!.left mDivider!!.setBounds(left, child.top - mDividerSize, child.right + mDividerSize, child.top) mDivider!!.draw(c) } if(mClose || !lastRow){ mDivider!!.setBounds(child!!.left, child.bottom, child.right + mDividerSize, child.bottom + mDividerSize) mDivider!!.draw(c) } } }
apache-2.0
c0afff2f44e5daabfcab4dd0999143a6
32.283465
117
0.570752
4.4862
false
false
false
false
BenoitDuffez/AndroidCupsPrint
app/src/main/java/ch/ethz/vppserver/schema/ippclient/Tag.kt
1
1565
package ch.ethz.vppserver.schema.ippclient /** * Copyright (C) 2008 ITS of ETH Zurich, Switzerland, Sarah Windler Burri * * 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, see <http:></http:>//www.gnu.org/licenses/>. */ /*Notice * This file has been modified. It is not the original. * XML parsing annotations, etc. have been removed Jon Freeman - 2013 */ class Tag { var value: String var name: String var description: String? = null var max: Short? = null constructor(value: String, name: String) { this.value = value this.name = name } constructor(value: String, name: String, description: String) { this.value = value this.name = name this.description = description } constructor(value: String, name: String, description: String, max: String) { this.value = value this.name = name this.description = description this.max = java.lang.Short.parseShort(max) } }
lgpl-3.0
3f2949129524519a849d13bdc282723b
32.297872
80
0.688179
4.023136
false
false
false
false
VerifAPS/verifaps-lib
lang/src/main/kotlin/edu/kit/iti/formal/automation/visitors/Utils.kt
1
2278
package edu.kit.iti.formal.automation.visitors /*- * #%L * iec61131lang * %% * Copyright (C) 2016 Alexander Weigl * %% * This program isType 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 isType 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 clone of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import edu.kit.iti.formal.automation.parser.IEC61131Lexer import edu.kit.iti.formal.automation.st.ast.PouElements import edu.kit.iti.formal.automation.st.ast.PouExecutable import edu.kit.iti.formal.automation.st.ast.ProgramDeclaration import org.antlr.v4.runtime.Lexer import org.antlr.v4.runtime.Token fun findProgram(tles: PouElements): ProgramDeclaration? = tles.findFirstProgram() fun PouElements.findFirstProgram(): ProgramDeclaration? = asSequence().filterIsInstance<ProgramDeclaration>().firstOrNull() fun selectByName(name: String) = { elements: PouElements -> elements.find { it.name == name } as? PouExecutable? } /** * Created by weigla on 09.06.2014.*/ object Utils { fun compareTokens(tokens: List<Token>, expected: Array<String>, lexer: Lexer) { try { for (i in expected.indices) { val expect = lexer.getTokenType(expected[i]) val tok = tokens[i] val tokName = IEC61131Lexer.tokenNames[tok.type] if (!expected[i].contentEquals(tokName)) { throw AssertionError( String.format("Token mismatch! Expected: %s but got %s", expected[i], tokName)) } } } catch (e: IndexOutOfBoundsException) { throw AssertionError("Not enough tokens found!") } if (expected.size < tokens.size) { throw AssertionError("Too much tokens found!") } } }
gpl-3.0
4dd2d4d860b46f54677e6317704c1dea
35.741935
123
0.675593
4.017637
false
false
false
false
googlecodelabs/android-compose-codelabs
AdaptiveUICodelab/app/src/main/java/com/example/reply/ui/ReplyApp.kt
1
9036
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.ui import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Article import androidx.compose.material.icons.filled.Chat import androidx.compose.material.icons.filled.Inbox import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.MenuOpen import androidx.compose.material.icons.outlined.Chat import androidx.compose.material.icons.outlined.People import androidx.compose.material.icons.outlined.Videocam import androidx.compose.material3.DrawerValue import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.NavigationBar import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.NavigationDrawerItem import androidx.compose.material3.NavigationDrawerItemDefaults import androidx.compose.material3.NavigationRail import androidx.compose.material3.NavigationRailItem import androidx.compose.material3.Text import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.reply.R @OptIn(ExperimentalMaterial3Api::class) @Composable fun ReplyApp(replyHomeUIState: ReplyHomeUIState) { // You will add navigation info here ReplyNavigationWrapperUI(replyHomeUIState) } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun ReplyNavigationWrapperUI( replyHomeUIState: ReplyHomeUIState ) { val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed) val scope = rememberCoroutineScope() val selectedDestination = ReplyDestinations.INBOX ReplyAppContent(replyHomeUIState) } @Composable fun ReplyAppContent( replyHomeUIState: ReplyHomeUIState, onDrawerClicked: () -> Unit = {} ) { Row(modifier = Modifier .fillMaxSize()) { Column(modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.inverseOnSurface) ) { ReplyListOnlyContent(replyHomeUIState = replyHomeUIState, modifier = Modifier.weight(1f)) ReplyBottomNavigationBar() } } } @Composable @Preview fun ReplyNavigationRail( onDrawerClicked: () -> Unit = {}, ) { NavigationRail(modifier = Modifier.fillMaxHeight()) { NavigationRailItem( selected = false, onClick = onDrawerClicked, icon = { Icon(imageVector = Icons.Default.Menu, contentDescription = stringResource(id = R.string.navigation_drawer)) } ) NavigationRailItem( selected = true, onClick = { /*TODO*/ }, icon = { Icon(imageVector = Icons.Default.Inbox, contentDescription = stringResource(id = R.string.tab_inbox)) } ) NavigationRailItem( selected = false, onClick = {/*TODO*/ }, icon = { Icon(imageVector = Icons.Default.Article, stringResource(id = R.string.tab_article)) } ) NavigationRailItem( selected = false, onClick = { /*TODO*/ }, icon = { Icon(imageVector = Icons.Outlined.Chat, stringResource(id = R.string.tab_dm)) } ) NavigationRailItem( selected = false, onClick = { /*TODO*/ }, icon = { Icon(imageVector = Icons.Outlined.People, stringResource(id = R.string.tab_groups)) } ) } } @Composable @Preview fun ReplyBottomNavigationBar() { NavigationBar(modifier = Modifier.fillMaxWidth()) { NavigationBarItem( selected = true, onClick = { /*TODO*/ }, icon = { Icon(imageVector = Icons.Default.Inbox, contentDescription = stringResource(id = R.string.tab_inbox)) } ) NavigationBarItem( selected = false, onClick = { /*TODO*/ }, icon = { Icon(imageVector = Icons.Default.Article, contentDescription = stringResource(id = R.string.tab_inbox)) } ) NavigationBarItem( selected = false, onClick = { /*TODO*/ }, icon = { Icon(imageVector = Icons.Outlined.Chat, contentDescription = stringResource(id = R.string.tab_inbox)) } ) NavigationBarItem( selected = false, onClick = { /*TODO*/ }, icon = { Icon(imageVector = Icons.Outlined.Videocam, contentDescription = stringResource(id = R.string.tab_inbox)) } ) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun NavigationDrawerContent( selectedDestination: String, modifier: Modifier = Modifier, onDrawerClicked: () -> Unit = {} ) { Column( modifier .wrapContentWidth() .fillMaxHeight() .background(MaterialTheme.colorScheme.inverseOnSurface) .padding(24.dp) ) { Row( modifier = modifier .fillMaxWidth() .padding(16.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( text = stringResource(id = R.string.app_name).uppercase(), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.primary ) IconButton(onClick = onDrawerClicked) { Icon( imageVector = Icons.Default.MenuOpen, contentDescription = stringResource(id = R.string.navigation_drawer) ) } } NavigationDrawerItem( selected = selectedDestination == ReplyDestinations.INBOX, label = { Text(text = stringResource(id = R.string.tab_inbox), modifier = Modifier.padding(horizontal = 16.dp)) }, icon = { Icon(imageVector = Icons.Default.Inbox, contentDescription = stringResource(id = R.string.tab_inbox)) }, colors = NavigationDrawerItemDefaults.colors(unselectedContainerColor = Color.Transparent), onClick = { /*TODO*/ } ) NavigationDrawerItem( selected = selectedDestination == ReplyDestinations.ARTICLES, label = { Text(text = stringResource(id = R.string.tab_article), modifier = Modifier.padding(horizontal = 16.dp)) }, icon = { Icon(imageVector = Icons.Default.Article, contentDescription = stringResource(id = R.string.tab_article)) }, colors = NavigationDrawerItemDefaults.colors(unselectedContainerColor = Color.Transparent), onClick = { /*TODO*/ } ) NavigationDrawerItem( selected = selectedDestination == ReplyDestinations.DM, label = { Text(text = stringResource(id = R.string.tab_dm), modifier = Modifier.padding(horizontal = 16.dp)) }, icon = { Icon(imageVector = Icons.Default.Chat, contentDescription = stringResource(id = R.string.tab_dm)) }, colors = NavigationDrawerItemDefaults.colors(unselectedContainerColor = Color.Transparent), onClick = { /*TODO*/ } ) NavigationDrawerItem( selected = selectedDestination == ReplyDestinations.GROUPS, label = { Text(text = stringResource(id = R.string.tab_groups), modifier = Modifier.padding(horizontal = 16.dp)) }, icon = { Icon(imageVector = Icons.Default.Article, contentDescription = stringResource(id = R.string.tab_groups)) }, colors = NavigationDrawerItemDefaults.colors(unselectedContainerColor = Color.Transparent), onClick = { /*TODO*/ } ) } }
apache-2.0
f43ae52b0753d550d5280bc51ba5f225
39.891403
132
0.679726
4.718538
false
false
false
false
Juuxel/ChatTime
api/src/main/kotlin/chattime/api/event/Events.kt
1
3378
/* 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 chattime.api.event import chattime.api.Server import chattime.api.User import chattime.api.plugin.Plugin /** * Represents a server event (a user joining, for example). * Events are fired and handled through the server [EventBus]. * * The [server] property is used in event handling to use server functions * and properties. * * @constructor The primary constructor. * * @property server the chat server */ abstract class Event( val server: Server) { /** * A property with the server event bus ([Server.eventBus]) * as its value. */ val eventBus get() = server.eventBus } /** * Represents an event that can be canceled. * * If an event is canceled, the final action after the event * should not be called. * * @constructor The primary constructor. * * @param server the chat server */ abstract class CancelableEvent(server: Server) : Event(server) { /** * If this is true, the event is canceled. */ var isCanceled: Boolean = false get private set /** * Cancels the event by setting [isCanceled] to true. * This cannot be reversed. */ fun cancel() { isCanceled = true } } /** * This event is fired when a user joins the server. * * @constructor The primary constructor. * * @param server the chat server * @property user the user */ class UserJoinEvent(server: Server, val user: User) : Event(server) /** * This event is fired when a plugin is loading. * * @constructor The primary constructor. * * @param server the chat server * @property plugin the plugin */ class PluginLoadEvent(server: Server, val plugin: Plugin) : Event(server) /** * This event represents a plugin-to-plugin message. * * @constructor The primary constructor. * * @param server the chat server * @property receiverId the message receiver's id * @property sender the message sender * @property msg the message */ class PluginMessageEvent(server: Server, val receiverId: String, val sender: Plugin, val msg: Any) : Event(server) /** * Represents an event type containing an event class. * Event type objects hold Java classes of the event types, * used when subscribing to events. * * @constructor The primary constructor. * @property eventClass the event class */ open class EventType<E : Event> protected constructor( val eventClass: Class<E>) { companion object { /** The event type of [UserJoinEvent]. */ @JvmField val userJoin = EventType(UserJoinEvent::class.java) /** The event type of [PluginMessageEvent]. */ @JvmField val pluginMessage = EventType(PluginMessageEvent::class.java) /** The event type of [PluginLoadEvent]. */ @JvmField val pluginLoad = EventType(PluginLoadEvent::class.java) /** The event type of [MessageEvent]. */ @JvmField val chatMessage = EventType(MessageEvent::class.java) /** The event type of [CommandEvent].*/ @JvmField val commandCall = EventType(CommandEvent::class.java) } }
mpl-2.0
0c49ef56a58343d399cc48042af7b9b8
25.809524
79
0.655121
4.233083
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/ide/intentions/AddElseIntention.kt
1
1544
package org.rust.ide.intentions import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RustIfExprElement import org.rust.lang.core.psi.RustPsiFactory import org.rust.lang.core.psi.util.parentOfType class AddElseIntention : PsiElementBaseIntentionAction() { override fun getText() = "Add else branch to is if statement" override fun getFamilyName(): String = text override fun startInWriteAction() = true private data class Context( val blockExpr: RustIfExprElement ) private fun findContext(element: PsiElement): Context? { if (!element.isWritable) return null val ifStmnt = element.parentOfType<RustIfExprElement>() as? RustIfExprElement ?: return null return if (ifStmnt.elseBranch == null) Context(ifStmnt) else null } override fun isAvailable(project: Project, editor: Editor?, element: PsiElement): Boolean = findContext(element) != null override fun invoke(project: Project, editor: Editor?, element: PsiElement) { val ifStmnt = findContext(element)?.blockExpr ?: return val ifExpr = RustPsiFactory(project).createExpression("${ifStmnt.text}\nelse {}") as RustIfExprElement val elseBlockOffset = (ifStmnt.replace(ifExpr) as RustIfExprElement).elseBranch?.block?.textOffset ?: return editor?.caretModel?.moveToOffset(elseBlockOffset + 1) ?: return } }
mit
f28e33bb2d42796706aedb4c3e3b295f
41.888889
116
0.742876
4.462428
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/minecraft/McMoletomCommand.kt
1
6949
package net.perfectdreams.loritta.morenitta.commands.vanilla.minecraft import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.utils.LorittaUtils import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.morenitta.utils.minecraft.MCUtils import net.perfectdreams.loritta.morenitta.messages.LorittaReply import net.perfectdreams.loritta.morenitta.utils.extensions.readImage import java.awt.Color import java.awt.Graphics2D import java.awt.image.BufferedImage import java.io.File class McMoletomCommand(loritta: LorittaBot) : AbstractCommand(loritta, "mcmoletom", listOf("mcsweater"), net.perfectdreams.loritta.common.commands.CommandCategory.MINECRAFT) { override fun getDescriptionKey() = LocaleKeyData("commands.command.mcsweater.description") override fun getExamplesKey() = LocaleKeyData("commands.category.minecraft.skinPlayerNameExamples") // TODO: Fix Usage override fun needsToUploadFiles(): Boolean { return true } override suspend fun run(context: CommandContext,locale: BaseLocale) { val attached = context.message.attachments.firstOrNull { it.isImage } var skin: BufferedImage? = null if (attached == null) { val nickname = context.args.getOrNull(0) if (nickname != null) { val profile = MCUtils.getUserProfileFromName(nickname) if (profile == null) { context.reply( LorittaReply( locale["commands.category.minecraft.unknownPlayer", context.args.getOrNull(0)], Constants.ERROR ) ) return } if (!profile.textures.containsKey("SKIN")) { context.reply( LorittaReply( "Player não possui skin!", Constants.ERROR ) ) return } skin = LorittaUtils.downloadImage(loritta, profile.textures["SKIN"]!!.url) } else { this.explain(context) return } } else { skin = LorittaUtils.downloadImage(loritta, attached.url) } if (skin != null) { val moletom = createSkin(skin) if (moletom == null) { context.reply( locale["commands.command.mcsweater.invalidSkin"], Constants.ERROR ) return } val str = "<:loritta:331179879582269451> **|** " + context.getAsMention(true) + locale["commands.command.mcsweater.done"] val message = context.sendFile(moletom, "moletom.png", str) val image = message.attachments.first() message.editMessage(str + " " + locale["commands.command.mcsweater.uploadToMojang"] + " <https://minecraft.net/pt-br/profile/skin/remote/?url=${image.url}>").queue() } else { context.reply( LorittaReply( locale["commands.category.minecraft.unknownPlayer", context.args.getOrNull(0)], Constants.ERROR ) ) } } companion object { suspend fun createSkin(originalSkin: BufferedImage?): BufferedImage? { if (originalSkin == null || (originalSkin.height != 64 && originalSkin.height != 32) || originalSkin.width != 64) return null var isPre18 = originalSkin.height == 32 val skin = BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB) // Corrige skins paletadas val graphics = skin.graphics as Graphics2D graphics.drawImage(originalSkin, 0, 0, null) if (isPre18) { fun flipAndPaste(bufferedImage: BufferedImage, x: Int, y: Int) { graphics.drawImage(bufferedImage, x + bufferedImage.width, y, -bufferedImage.width, bufferedImage.height, null) } // i have no idea what I'm doing var leg0 = deepCopy(skin.getSubimage(0, 16, 16, 4)) var leg1 = deepCopy(skin.getSubimage(4, 20, 8, 12)) var leg2 = deepCopy(skin.getSubimage(0, 20, 4, 12)) var leg3 = deepCopy(skin.getSubimage(12, 20, 4, 12)) var arm0 = deepCopy(skin.getSubimage(40, 16, 16, 4)) var arm1 = deepCopy(skin.getSubimage(4 + 40, 20, 8, 12)) var arm2 = deepCopy(skin.getSubimage(0 + 40, 20, 4, 12)) var arm3 = deepCopy(skin.getSubimage(12 + 40, 20, 4, 12)) graphics.drawImage(leg0, 16, 48, null) flipAndPaste(leg1, 16, 52) flipAndPaste(leg2, 24, 52) flipAndPaste(leg3, 28, 52) graphics.drawImage(arm0, 32, 48, null) flipAndPaste(arm1, 32, 52) flipAndPaste(arm2, 40, 52) flipAndPaste(arm3, 44, 52) } val alexTestColor = Color(skin.getRGB(50, 16), true) val isAlex = alexTestColor.alpha != 255 val template = if (isAlex) readImage(File(LorittaBot.ASSETS, "template_alex.png")) else readImage(File(LorittaBot.ASSETS, "template_steve.png")) val handColor = if (isAlex) { Color(skin.getRGB(48, 17), true) } else { Color(skin.getRGB(49, 17), true) } var wrong = 0 for (x in 40..43) { val color = Color(skin.getRGB(x, 31)) if (handColor.red in color.red - 40 until color.red + 40) { if (handColor.green in color.green - 40 until color.green + 40) { if (handColor.blue in color.blue - 40 until color.blue + 40) { continue } } } wrong++ } var lowerBarWrong = wrong > 2 for (x in 40..43) { val color = Color(skin.getRGB(x, 30)) if (handColor.red in color.red - 40 until color.red + 40) { if (handColor.green in color.green - 40 until color.green + 40) { if (handColor.blue in color.blue - 40 until color.blue + 40) { continue } } } wrong++ } if (wrong > 2) { graphics.color = handColor val arm1 = deepCopy(skin.getSubimage(40, 31, if (isAlex) 14 else 16, 1)) val arm2 = deepCopy(skin.getSubimage(32, 63, if (isAlex) 14 else 16, 1)) // ARMS graphics.fillRect(40, 30, if (isAlex) 14 else 16, if (!lowerBarWrong) 1 else 2) graphics.fillRect(32, 62, if (isAlex) 14 else 16, if (!lowerBarWrong) 1 else 2) // HANDS if (lowerBarWrong) { graphics.fillRect(if (isAlex) 47 else 48, 16, if (isAlex) 3 else 4, 4) graphics.fillRect(if (isAlex) 39 else 40, 48, if (isAlex) 3 else 4, 4) } else { // println("Fixing arm by copying lower pixels") graphics.drawImage(arm1, 40, 30, null) graphics.drawImage(arm2, 32, 62, null) } } graphics.background = Color(255, 255, 255, 0) graphics.clearRect(16, 32, 48, 16) graphics.clearRect(48, 48, 16, 16) graphics.drawImage(template, 0, 0, null) return skin } fun deepCopy(bi: BufferedImage): BufferedImage { val cm = bi.colorModel val isAlphaPremultiplied = cm.isAlphaPremultiplied val raster = bi.copyData(bi.raster.createCompatibleWritableRaster()) return BufferedImage(cm, raster, isAlphaPremultiplied, null) } } }
agpl-3.0
0284658ab90ea623dcc2101f2d02f840
32.73301
175
0.662349
3.405882
false
false
false
false
ericberman/MyFlightbookAndroid
app/src/main/java/com/myflightbook/android/DlgSignIn.kt
1
4785
/* MyFlightbook for Android - provides native access to MyFlightbook pilot's logbook Copyright (C) 2017-2022 MyFlightbook, LLC 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.myflightbook.android import android.app.Activity import android.app.Dialog import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.TextView import com.myflightbook.android.webservices.AircraftSvc import com.myflightbook.android.webservices.AuthToken import com.myflightbook.android.webservices.CustomPropertyTypesSvc import com.myflightbook.android.webservices.MFBSoap import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import model.AuthResult internal class DlgSignIn(private val mCallingActivity: Activity) : Dialog( mCallingActivity, R.style.MFBDialog ), View.OnClickListener { private fun postSignIn() { val act = mCallingActivity // should never be null val c = context GlobalScope.launch(Dispatchers.Main) { ActMFBForm.doAsync<MFBSoap, Any?>( act, MFBSoap(), c.getString(R.string.prgAircraft), { s -> AircraftSvc().getAircraftForUser(AuthToken.m_szAuthToken, c) s.mProgress?.notifyProgress(0, c.getString(R.string.prgCPT)) CustomPropertyTypesSvc().getCustomPropertyTypes(AuthToken.m_szAuthToken, false, c) }, { _, _ -> dismiss() } ) } } // Sign in - if successful will then download Aircraft and then download Properties private fun signIn(szUser : String, szPass : String, sz2FA : String?) { val act = mCallingActivity // should never be null val c = context val d = this val at = AuthToken() // make sure we don't use any existing credentials!! at.flushCache() // Also flush any cached aircraft when we change users AircraftSvc().flushCache() GlobalScope.launch(Dispatchers.Main) { ActMFBForm.doAsync<AuthToken, AuthResult?>( act, at, c.getString(R.string.prgSigningIn), { s -> s.authorizeUser(szUser, szPass, sz2FA, c) }, { _, result -> if (result!!.authStatus === AuthResult.AuthStatus.TwoFactorCodeRequired) { findViewById<View>(R.id.layout2FA).visibility = View.VISIBLE findViewById<View>(R.id.layoutCredentials).visibility = View.GONE findViewById<View>(R.id.txtWarning).visibility = View.GONE } else { if (result!!.authStatus === AuthResult.AuthStatus.Success) { MFBMain.invalidateAll() postSignIn() } else if (d.findViewById<View>(R.id.layout2FA).visibility != View.VISIBLE) d.findViewById<TextView>(R.id.editPass).text = "" // clear out password for another try on failure } } ) } } public override fun onCreate(savedInstanceState: Bundle?) { findViewById<View>(R.id.btnSubmit).setOnClickListener(this) findViewById<View>(R.id.btnCancel).setOnClickListener(this) } override fun onClick(v: View) { val id = v.id if (id == R.id.btnCancel) { dismiss() return } val txtUser = findViewById<EditText>(R.id.editEmail) val txtPass = findViewById<EditText>(R.id.editPass) val txt2FA = findViewById<EditText>(R.id.txt2FA) signIn(txtUser.text.toString(), txtPass.text.toString(), txt2FA.text.toString()) } init { setContentView(R.layout.dlgsignin) setTitle("Please sign in to MyFlightbook") val txtUser = findViewById<EditText>(R.id.editEmail) val txtPass = findViewById<EditText>(R.id.editPass) txtUser.setText(AuthToken.m_szEmail) txtPass.setText(AuthToken.m_szPass) } }
gpl-3.0
4d8cc2c7b6100ec2796b603c951f9d37
38.553719
128
0.628422
4.587728
false
false
false
false
VladRassokhin/intellij-hcl
src/kotlin/org/intellij/plugins/hcl/psi/impl/HCLHeredocContentMixin.kt
1
2468
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.hcl.psi.impl import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import com.intellij.psi.LiteralTextEscaper import com.intellij.psi.PsiLanguageInjectionHost import org.intellij.plugins.hcl.psi.HCLHeredocContent import org.intellij.plugins.hcl.psi.HCLHeredocContentManipulator abstract class HCLHeredocContentMixin(node: ASTNode) : HCLLiteralImpl(node), PsiLanguageInjectionHost, HCLHeredocContent { override fun isValidHost() = true override fun updateText(text: String): PsiLanguageInjectionHost { return HCLHeredocContentManipulator().handleContentChange(this, text) as PsiLanguageInjectionHost } override fun createLiteralTextEscaper(): LiteralTextEscaper<out PsiLanguageInjectionHost> { return object : LiteralTextEscaper<HCLHeredocContentMixin>(this) { override fun isOneLine(): Boolean { return false } override fun decode(rangeInsideHost: TextRange, outChars: StringBuilder): Boolean { outChars.append(rangeInsideHost.subSequence(myHost.text)) return true } override fun getOffsetInHost(offsetInDecoded: Int, rangeInsideHost: TextRange): Int { val offset = offsetInDecoded + rangeInsideHost.startOffset if (offset < rangeInsideHost.startOffset) { return -1 } if (offset > rangeInsideHost.endOffset) { return -1 } return offset } override fun getRelevantTextRange(): TextRange { return myHost.getInnerRange() } } } fun getInnerRange(): TextRange { if (this.textLength == 0) return TextRange.EMPTY_RANGE // Everything except last EOL val lastChild = this.lastChild if (lastChild != null) { return TextRange.create(0, lastChild.startOffsetInParent) } return TextRange.from(0, this.textLength) } }
apache-2.0
2c42ec0a62c91ea331a2204fc522dfd9
34.257143
122
0.729335
4.587361
false
false
false
false
gatheringhallstudios/MHGenDatabase
app/src/main/java/com/ghstudios/android/data/database/ItemDao.kt
1
15529
package com.ghstudios.android.data.database import android.database.sqlite.SQLiteOpenHelper import com.ghstudios.android.AppSettings import com.ghstudios.android.data.classes.* import com.ghstudios.android.data.cursors.* import com.ghstudios.android.data.util.* import com.ghstudios.android.util.firstOrNull import com.ghstudios.android.util.forEach import com.ghstudios.android.util.toList import com.ghstudios.android.util.useCursor class ItemDao(val dbMainHelper: SQLiteOpenHelper) { val db get() = dbMainHelper.writableDatabase private val column_name get() = localizeColumn("name") private val column_description get() = localizeColumn("description") private val item_columns get() = "_id, $column_name name, name_ja, $column_description description, " + "type, sub_type, rarity, carry_capacity, buy, sell, icon_name, icon_color, account " // todo: add family, remove "item only" fields like carry cap /** * Returns columns for armor, prefixed using an armor prefix and item prefix * to avoid ambiguity */ private fun armor_columns(a : String, i: String) = "$a._id, $i.$column_name name, $i.name_ja, $column_description description, " + "$a.family, rarity, slot, gender, hunter_type, num_slots, " + "defense, max_defense, fire_res, thunder_res, dragon_res, water_res, ice_res, " + "type, sub_type, carry_capacity, buy, sell, icon_name, icon_color " /** * ****************************** ITEM QUERIES ***************************************** */ /** * Get all items, including equipment like armor and weapons */ fun queryItems(): ItemCursor { return ItemCursor(db.rawQuery(""" SELECT $item_columns FROM items ORDER BY _id """, emptyArray())) } /** * Queries all normal items, controllable via an optional search filter */ fun queryBasicItems(searchTerm: String = ""): ItemCursor { val typeItem = ItemTypeConverter.serialize(ItemType.ITEM) // return all basic items, filtered val filter = SqlFilter(column_name, searchTerm) return ItemCursor(db.rawQuery(""" SELECT $item_columns FROM items WHERE type in (?) AND ${filter.predicate} ORDER BY _id """, arrayOf(typeItem, *filter.parameters))) } /** * Get a specific item */ fun queryItem(id: Long): Item? { return ItemCursor(db.rawQuery(""" SELECT $item_columns FROM items WHERE _id = ? """, arrayOf(id.toString()))).toList { it.item }.firstOrNull() } /** * Get items based on search text. Gets all items, including armor and equipment. */ fun queryItemSearch(searchTerm: String?, includeTypes: List<ItemType> = emptyList()): ItemCursor { if (searchTerm == null || searchTerm.isBlank()) { return queryItems() } val filter = SqlFilter(column_name, searchTerm) val typePredicate = when { includeTypes.isEmpty() -> "TRUE" else -> "(" + includeTypes.joinToString(" OR ") { "type = '${ItemTypeConverter.serialize(it)}'" } + ")" } return ItemCursor(db.rawQuery(""" SELECT $item_columns FROM items WHERE ${filter.predicate} AND $typePredicate ORDER BY _id """, arrayOf(*filter.parameters))) } /** * ****************************** COMBINING QUERIES ***************************************** */ /** * Internal helper that returns the column names for a sub-item in a combine recipe. */ private fun combiningItemColumns(table: String, prefix: String): String { val p = prefix val columns = arrayOf( "_id", "name_ja", "type", "sub_type", "rarity", "carry_capacity", "buy", "sell", "icon_name", "icon_color") val colName = localizeColumn("$table.name") val colDescription = localizeColumn("$table.description") return "$colName ${p}name, $colDescription ${p}description, " + columns.joinToString(", ") { "$table.$it AS $prefix$it" } } /* * Get all combinings */ fun queryCombinings(): CombiningCursor { return CombiningCursor(db.rawQuery(""" SELECT c._id, c.amount_made_min, c.amount_made_max, c.percentage, ${combiningItemColumns("crt", "crt")}, ${combiningItemColumns("mat1", "mat1")}, ${combiningItemColumns("mat2", "mat2")} FROM combining c LEFT OUTER JOIN items crt ON c.created_item_id = crt._id LEFT OUTER JOIN items mat1 ON c.item_1_id = mat1._id LEFT OUTER JOIN items mat2 ON c.item_2_id = mat2._id """, emptyArray())) } /** * Get a specific combining */ fun queryCombining(id: Long): Combining? { return CombiningCursor(db.rawQuery(""" SELECT c._id, c.amount_made_min, c.amount_made_max, c.percentage, ${combiningItemColumns("crt", "crt")}, ${combiningItemColumns("mat1", "mat1")}, ${combiningItemColumns("mat2", "mat2")} FROM combining c LEFT OUTER JOIN items crt ON c.created_item_id = crt._id LEFT OUTER JOIN items mat1 ON c.item_1_id = mat1._id LEFT OUTER JOIN items mat2 ON c.item_2_id = mat2._id WHERE c._id = ? """, arrayOf(id.toString()))).firstOrNull { it.combining } } fun queryCombinationsOnItemID(id: Long): CombiningCursor { return CombiningCursor(db.rawQuery(""" SELECT c._id, c.amount_made_min, c.amount_made_max, c.percentage, ${combiningItemColumns("crt", "crt")}, ${combiningItemColumns("mat1", "mat1")}, ${combiningItemColumns("mat2", "mat2")} FROM combining c LEFT OUTER JOIN items crt ON c.created_item_id = crt._id LEFT OUTER JOIN items mat1 ON c.item_1_id = mat1._id LEFT OUTER JOIN items mat2 ON c.item_2_id = mat2._id WHERE crt._id = @id OR mat1._id = @id OR mat2._id = @id """, arrayOf(id.toString()))) } /** * ****************************** ARMOR QUERIES ***************************************** */ /** * Get all armor */ fun queryArmor(): ArmorCursor { return ArmorCursor(db.rawQuery(""" SELECT ${armor_columns("a", "i")} FROM armor a JOIN items i USING (_id) """, emptyArray())) } fun queryArmorSearch(searchTerm: String): ArmorCursor { val filter = SqlFilter(column_name, searchTerm) return ArmorCursor(db.rawQuery(""" SELECT ${armor_columns("a", "i")} FROM armor a JOIN items i USING (_id) WHERE ${filter.predicate} """, filter.parameters)) } /** * Get a specific armor */ fun queryArmor(id: Long): Armor? { return ArmorCursor(db.rawQuery(""" SELECT ${armor_columns("a", "i")} FROM armor a JOIN items i USING (_id) WHERE a._id = ? """, arrayOf(id.toString()))).firstOrNull { it.armor } } /** * Get armor for family */ fun queryArmorByFamily(id: Long): List<Armor> { return ArmorCursor(db.rawQuery(""" SELECT ${armor_columns("a", "i")} FROM armor a JOIN items i USING (_id) WHERE a.family = ? """, arrayOf(id.toString()))).toList { it.armor } } /** * Get a list of armor based on hunter type. * If "BOTH" is passed, then its equivalent to querying all armor */ fun queryArmorType(type: Int): ArmorCursor { return ArmorCursor(db.rawQuery(""" SELECT ${armor_columns("a", "i")} FROM armor a JOIN items i USING (_id) WHERE a.hunter_type = @type OR a.hunter_type = 2 OR @type = '2' """, arrayOf(type.toString()))) } /** * Get a list of armor based on hunter type with a list of all awarded skill points. * If "BOTH" is passed, then its equivalent to querying all armor. * If NULL is passed for armorSlot, then it queries all armor types. */ fun queryArmorSkillPointsByType(armorSlot: String, hunterType: Int): List<ArmorSkillPoints> { // note we use armor cursor as its basically armor + a few columns val cursor = ArmorCursor(db.rawQuery(""" SELECT ${armor_columns("a", "i")}, st._id as st_id, st.$column_name AS st_name, st.name_ja as st_name_ja, its.point_value FROM armor a JOIN items i USING (_id) LEFT JOIN item_to_skill_tree its on its.item_id = a._id LEFT JOIN skill_trees st on st._id = its.skill_tree_id WHERE (a.hunter_type = @type OR a.hunter_type = 2 OR @type = '2') AND (a.slot = @slot OR @slot IS NULL) ORDER BY i.rarity, i.$column_name ASC """, arrayOf(hunterType.toString(), armorSlot))) // stores armor and skills as its processed val armorMap = LinkedHashMap<Long, Armor>() val armorToSkills = LinkedHashMap<Long, MutableList<SkillTreePoints>>() // Iterate cursor cursor.useCursor { while (cursor.moveToNext()) { val id = cursor.getLong("_id") armorMap.getOrPut(id) { cursor.armor } // Ensure there is a skills entry for this armor piece val skills = armorToSkills.getOrPut(id) { mutableListOf() } // Add skill (if non-null) if (!cursor.isNull("st_id")) { val skillPoints = SkillTreePoints(SkillTree( cursor.getLong("st_id"), cursor.getString("st_name"), cursor.getString("st_name_ja") ), cursor.getInt("point_value")) skills.add(skillPoints) } } } // assemble results return armorToSkills.map { ArmorSkillPoints(armorMap[it.key]!!, it.value) } } /** * Returns an armor families cursor * @param searchFilter the search predicate to filter on * @param skipSolos true to skip armor families with a single child, otherwise returns all. */ @JvmOverloads fun queryArmorFamilyBaseSearch(searchFilter: String, skipSolos: Boolean = false): List<ArmorFamilyBase> { val sqlFilter = SqlFilter("name", searchFilter) val soloPredicate = when (skipSolos) { false -> "TRUE" true -> "(SELECT count(*) FROM armor a WHERE a.family = af._id) > 1" } // todo: localize return db.rawQuery(""" SELECT af._id, COALESCE(af.$column_name, af.name) name, af.rarity, af.hunter_type FROM armor_families af WHERE ${sqlFilter.predicate} AND $soloPredicate ORDER BY af.rarity, af._id """, sqlFilter.parameters).toList { ArmorFamilyBase().apply { id = it.getLong("_id") name = it.getString("name") rarity = it.getInt("rarity") hunterType = it.getInt("hunter_type") } } } fun queryArmorFamilies(type: Int): List<ArmorFamily> { // todo: localize // todo: clean up. Should be 3 queries, not 2. This mechanism is harder to understand val slotsByFamilyId = linkedMapOf<Long, MutableList<Int>>() db.rawQuery(""" SELECT af._id, a.num_slots FROM armor a JOIN armor_families af ON af._id = a.family WHERE a.hunter_type=@type OR a.hunter_type=2 ORDER BY a._id ASC""", arrayOf(type.toString()) ).forEach { val id = it.getLong("_id") val slots = it.getInt("num_slots") slotsByFamilyId.getOrPut(id) { mutableListOf() }.add(slots) } val cursor = ArmorFamilyCursor(db.rawQuery(""" SELECT af._id, COALESCE(af.$column_name, af.name) name, af.rarity, af.hunter_type, st.$column_name AS st_name,SUM(its.point_value) AS point_value,SUM(a.defense) AS min,SUM(a.max_defense) AS max FROM armor_families af JOIN armor a on a.family=af._id JOIN item_to_skill_tree its on a._id=its.item_id JOIN skill_trees st on st._id=its.skill_tree_id WHERE a.hunter_type=@type OR a.hunter_type=2 GROUP BY af._id,its.skill_tree_id; """, arrayOf(type.toString()))) val results = linkedMapOf<Long, ArmorFamily>() cursor.forEach { val newFamily = cursor.armor if (newFamily.id in results) { results[newFamily.id]?.skills?.add(newFamily.skills[0]) } else { newFamily.slots.addAll(slotsByFamilyId[newFamily.id] ?: emptyList()) results[newFamily.id] = newFamily } } return results.values.toList() } fun queryComponentsByArmorFamily(family: Long): ComponentCursor { return ComponentCursor(db.rawQuery(""" SELECT c._id,SUM(c.quantity) AS quantity,c.type,MAX(c.key) AS key, c.created_item_id,cr.$column_name AS crname,cr.type AS crtype, cr.rarity AS crrarity,cr.icon_name AS cricon_name,cr.sub_type AS crsub_type, cr.icon_color AS cricon_color, c.component_item_id,co.$column_name AS coname,co.type AS cotype, co.rarity AS corarity,co.icon_name AS coicon_name,co.sub_type AS cosub_type, co.icon_color AS coicon_color FROM armor a JOIN components c ON c.created_item_id = a._id JOIN items cr ON cr._id=a._id JOIN items co ON co._id=c.component_item_id WHERE a.family=? GROUP BY c.component_item_id ORDER BY quantity DESC """,arrayOf(family.toString()))) } /** * Returns a list of ItemToSkillTree, where each item is of type */ fun queryArmorSkillTreePointsBySkillTree(skillTreeId: Long): List<ItemToSkillTree> { val cursor = db.rawQuery(""" SELECT ${armor_columns("a", "i")}, st._id as st_id, st.$column_name AS st_name, st.name_ja as st_name_ja, its.point_value FROM armor a JOIN items i USING (_id) LEFT JOIN item_to_skill_tree its on its.item_id = a._id LEFT JOIN skill_trees st on st._id = its.skill_tree_id WHERE st._id = ? ORDER BY i.rarity DESC, its.point_value DESC """, arrayOf(skillTreeId.toString())) return ArmorCursor(cursor).toList { val armor = it.armor val skillTree = SkillTree( id=it.getLong("st_id"), name=it.getString("st_name"), jpnName= it.getString("st_name_ja")) val points = it.getInt("point_value") ItemToSkillTree(skillTree, points).apply { this.item = armor } } } }
mit
c51584a1be658d8ab6ac6a638925ce93
37.440594
133
0.552772
4.197027
false
false
false
false
NuclearCoder/nuclear-bot
src/nuclearbot/gui/components/StatusPanel.kt
1
3105
package nuclearbot.gui.components import nuclearbot.gui.NuclearBotGUI import nuclearbot.gui.utils.VerticalLayout import nuclearbot.util.JavaWrapper import java.awt.FlowLayout import java.awt.Font import javax.swing.JButton import javax.swing.JLabel import javax.swing.JPanel import javax.swing.SwingConstants import javax.swing.border.EmptyBorder /* * Copyright (C) 2017 NuclearCoder * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * The GUI panel for the status tab.<br></br> * <br></br> * NuclearBot (https://github.com/NuclearCoder/nuclear-bot/)<br></br> * @author NuclearCoder (contact on the GitHub repo) */ class StatusPanel(gui: NuclearBotGUI) : JPanel(VerticalLayout()) { private val statusLabel = JLabel("Not running").apply { border = EmptyBorder(0, 0, 0, 3) font = font.deriveFont(Font.ITALIC) } private val startButton = JButton("Start").apply { isEnabled = true addActionListener { gui.startClient() } } private val stopButton = JButton("Stop").apply { isEnabled = false addActionListener { gui.doRestartClient = false gui.stopClient() } } private val restartButton = JButton("Restart").apply { isEnabled = false addActionListener { gui.doRestartClient = true gui.stopClient() } } private val pluginLabel = JLabel().apply { font = font.deriveFont(Font.PLAIN) horizontalAlignment = SwingConstants.CENTER componentPopupMenu = gui.popupMenu } init { val controls = JPanel(FlowLayout()).apply { add(statusLabel) add(startButton) add(stopButton) add(restartButton) } val currentPlugin = JPanel(FlowLayout()).apply { add(JLabel("<html><u>Current plugin:</u></html>")) add(pluginLabel) } add(controls) add(currentPlugin) } fun setStatusText(text: String) { statusLabel.text = text } fun setPluginText(text: String, tooltipText: String) { pluginLabel.text = text pluginLabel.toolTipText = tooltipText } var isStartEnabled by JavaWrapper(startButton::isEnabled, startButton::setEnabled) var isStopEnabled by JavaWrapper(stopButton::isEnabled, stopButton::setEnabled) var isRestartEnabled by JavaWrapper(restartButton::isEnabled, restartButton::setEnabled) }
agpl-3.0
45f4780973a430984705debdf3893a84
29.145631
92
0.669243
4.435714
false
false
false
false
zyyoona7/KExtensions
lib/src/main/java/com/zyyoona7/extensions/systemService.kt
1
7508
package com.zyyoona7.extensions import android.accounts.AccountManager import android.annotation.SuppressLint import android.annotation.TargetApi import android.app.* import android.app.admin.DevicePolicyManager import android.app.job.JobScheduler import android.appwidget.AppWidgetManager import android.bluetooth.BluetoothManager import android.content.ClipboardManager import android.content.Context import android.content.RestrictionsManager import android.content.pm.LauncherApps import android.hardware.ConsumerIrManager import android.hardware.SensorManager import android.hardware.camera2.CameraManager import android.hardware.display.DisplayManager import android.hardware.input.InputManager import android.hardware.usb.UsbManager import android.location.LocationManager import android.media.AudioManager import android.media.MediaRouter import android.media.projection.MediaProjectionManager import android.media.session.MediaSessionManager import android.media.tv.TvInputManager import android.net.ConnectivityManager import android.net.nsd.NsdManager import android.net.wifi.WifiManager import android.net.wifi.p2p.WifiP2pManager import android.nfc.NfcManager import android.os.* import android.os.storage.StorageManager import android.print.PrintManager import android.telecom.TelecomManager import android.telephony.TelephonyManager import android.view.LayoutInflater import android.view.WindowManager import android.view.accessibility.AccessibilityManager import android.view.accessibility.CaptioningManager import android.view.inputmethod.InputMethodManager import android.view.textservice.TextServicesManager /** * Created by zyyoona7 on 2017/8/26. * SystemService 各种manager */ val Context.accessibilityManager get() = getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager? val Context.accountManager get() = getSystemService(Context.ACCOUNT_SERVICE) as AccountManager? val Context.activityManager get() = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager? val Context.alarmManager get() = getSystemService(Context.ALARM_SERVICE) as AlarmManager? val Context.appWidgetManager get() = getSystemService(Context.APPWIDGET_SERVICE) as AppWidgetManager? val Context.appOpsManager @TargetApi(Build.VERSION_CODES.KITKAT) get() = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager? val Context.audioManager get() = getSystemService(Context.AUDIO_SERVICE) as AudioManager? val Context.batteryManager get() = getSystemService(Context.BATTERY_SERVICE) as BatteryManager? val Context.bluetoothManager @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) get() = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager? val Context.cameraManager @TargetApi(Build.VERSION_CODES.LOLLIPOP) get() = getSystemService(Context.CAMERA_SERVICE) as CameraManager? val Context.captioningManager @TargetApi(Build.VERSION_CODES.KITKAT) get() = getSystemService(Context.CAPTIONING_SERVICE) as CaptioningManager? val Context.clipboardManager get() = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager? val Context.connectivityManager get() = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager? val Context.consumerIrManager @TargetApi(Build.VERSION_CODES.KITKAT) get() = getSystemService(Context.CONSUMER_IR_SERVICE) as ConsumerIrManager? val Context.devicePolicyManager get() = getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager? val Context.displayManager @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) get() = getSystemService(Context.DISPLAY_SERVICE) as DisplayManager? val Context.downloadManager get() = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager? val Context.dropBoxManager get() = getSystemService(Context.DROPBOX_SERVICE) as DropBoxManager? val Context.inputMethodManager get() = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager? val Context.inputManager get() = getSystemService(Context.INPUT_SERVICE) as InputManager? val Context.jobScheduler @TargetApi(Build.VERSION_CODES.LOLLIPOP) get() = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler? val Context.keyguardManager get() = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager? val Context.launcherApps @TargetApi(Build.VERSION_CODES.LOLLIPOP) get() = getSystemService(Context.LAUNCHER_APPS_SERVICE) as LauncherApps? val Context.layoutInflater get() = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater? val Context.locationManager get() = getSystemService(Context.LOCATION_SERVICE) as LocationManager? val Context.mediaProjectionManager @TargetApi(Build.VERSION_CODES.LOLLIPOP) get() = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager? val Context.mediaRouter get() = getSystemService(Context.MEDIA_ROUTER_SERVICE) as MediaRouter? val Context.mediaSessionManager @TargetApi(Build.VERSION_CODES.LOLLIPOP) get() = getSystemService(Context.MEDIA_SESSION_SERVICE) as MediaSessionManager? val Context.nfcManager get() = getSystemService(Context.NFC_SERVICE) as NfcManager? val Context.notificationManager get() = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager? val Context.nsdManager get() = getSystemService(Context.NSD_SERVICE) as NsdManager? val Context.powerManager get() = getSystemService(Context.POWER_SERVICE) as PowerManager? val Context.printManager @TargetApi(Build.VERSION_CODES.KITKAT) get() = getSystemService(Context.PRINT_SERVICE) as PrintManager? val Context.restrictionsManager @TargetApi(Build.VERSION_CODES.LOLLIPOP) get() = getSystemService(Context.RESTRICTIONS_SERVICE) as RestrictionsManager? val Context.searchManager get() = getSystemService(Context.SEARCH_SERVICE) as SearchManager? val Context.sensorManager get() = getSystemService(Context.SENSOR_SERVICE) as SensorManager? val Context.storageManager get() = getSystemService(Context.STORAGE_SERVICE) as StorageManager? val Context.telecomManager @TargetApi(Build.VERSION_CODES.LOLLIPOP) get() = getSystemService(Context.TELECOM_SERVICE) as TelecomManager? val Context.telephonyManager get() = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager? val Context.textServicesManager get() = getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE) as TextServicesManager? val Context.tvInputManager @TargetApi(Build.VERSION_CODES.LOLLIPOP) get() = getSystemService(Context.TV_INPUT_SERVICE) as TvInputManager? val Context.uiModeManager get() = getSystemService(Context.UI_MODE_SERVICE) as UiModeManager? val Context.usbManager get() = getSystemService(Context.USB_SERVICE) as UsbManager? val Context.userManager @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) get() = getSystemService(Context.USER_SERVICE) as UserManager? val Context.vibrator get() = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator? val Context.wallpaperManager @SuppressLint("ServiceCast") get() = getSystemService(Context.WALLPAPER_SERVICE) as WallpaperManager? val Context.wifiP2pManager get() = getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager? val Context.wifiManager get() = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager? val Context.windowManager get() = getSystemService(Context.WINDOW_SERVICE) as WindowManager?
apache-2.0
c0ad7c6245cea8b2841bfe3cb992f46e
34.909091
91
0.808769
4.523207
false
false
false
false
luoyuan800/NeverEnd
dataModel/src/cn/luo/yuan/maze/model/skill/hero/Dodge.kt
1
2465
package cn.luo.yuan.maze.model.skill.hero import cn.luo.yuan.maze.model.Data import cn.luo.yuan.maze.model.Hero import cn.luo.yuan.maze.model.NameObject import cn.luo.yuan.maze.model.skill.DefSkill import cn.luo.yuan.maze.model.skill.SkillParameter import cn.luo.yuan.maze.model.skill.UpgradeAble import cn.luo.yuan.maze.model.skill.result.SkillResult import cn.luo.yuan.maze.model.skill.result.SkipThisTurn import cn.luo.yuan.maze.service.BattleMessageInterface import cn.luo.yuan.maze.utils.Field import cn.luo.yuan.maze.utils.StringUtils /** * Created by luoyuan on 2017/7/16. */ class Dodge():DefSkill(), UpgradeAble { companion object { private const val serialVersionUID = Field.SERVER_VERSION } private var level = 1L private val model = HeroModel(this) override fun upgrade(parameter: SkillParameter?): Boolean { if(rate + 0.3 > Data.RATE_MAX/10){ return false } val hero = parameter!!.owner if (hero is Hero) { rate += 0.3f level++ return true } return false } override fun getLevel(): Long { return level } override fun getName(): String { return "闪避 X $level" } override fun getDisplayName(): String { val builder = StringBuilder() builder.append("防御技能<br>") builder.append(StringUtils.formatPercentage(rate)).append("概率闪避攻击") builder.append("<br>已经使用:${StringUtils.formatNumber(useTime)}次") return builder.toString() } override fun canMount(parameter: SkillParameter?): Boolean { return model.canMount(parameter) } override fun invoke(parameter: SkillParameter): SkillResult { val skipThisTurn = SkipThisTurn() val massger : BattleMessageInterface = parameter[SkillParameter.MESSAGE] massger.dodge(parameter.owner as NameObject, parameter[SkillParameter.ATKER]) return skipThisTurn } override fun enable(parameter: SkillParameter?) { isEnable = true } override fun canEnable(parameter: SkillParameter): Boolean { return model.canEnable(parameter) ; } override fun getSkillName(): String { return model.skillName } override fun canUpgrade(parameter: SkillParameter): Boolean { return isEnable && parameter.owner is Hero && rate < Data.RATE_MAX && model.canUpgrade(parameter) } }
bsd-3-clause
e4451025c2190397107032dd25c48183
30.153846
105
0.673117
3.943182
false
false
false
false
jsargent7089/android
src/main/java/com/nextcloud/client/jobs/ContactsImportWork.kt
1
5100
/* * Nextcloud Android client application * * @author Tobias Kaminsky * Copyright (C) 2017 Tobias Kaminsky * Copyright (C) 2017 Nextcloud GmbH. * Copyright (C) 2020 Chris Narkiewicz <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.jobs import android.content.ContentResolver import android.content.Context import android.database.Cursor import android.net.Uri import android.provider.ContactsContract import androidx.work.Worker import androidx.work.WorkerParameters import com.nextcloud.client.logger.Logger import com.owncloud.android.ui.fragment.contactsbackup.ContactListFragment import com.owncloud.android.ui.fragment.contactsbackup.ContactListFragment.VCardComparator import ezvcard.Ezvcard import ezvcard.VCard import third_parties.ezvcard_android.ContactOperations import java.io.File import java.io.IOException import java.util.ArrayList import java.util.Collections import java.util.TreeMap class ContactsImportWork( appContext: Context, params: WorkerParameters, private val logger: Logger, private val contentResolver: ContentResolver ) : Worker(appContext, params) { companion object { const val TAG = "ContactsImportWork" const val ACCOUNT_TYPE = "account_type" const val ACCOUNT_NAME = "account_name" const val VCARD_FILE_PATH = "vcard_file_path" const val SELECTED_CONTACTS_INDICES = "selected_contacts_indices" } @Suppress("ComplexMethod", "NestedBlockDepth") // legacy code override fun doWork(): Result { val vCardFilePath = inputData.getString(VCARD_FILE_PATH) ?: "" val contactsAccountName = inputData.getString(ACCOUNT_NAME) val contactsAccountType = inputData.getString(ACCOUNT_TYPE) val selectedContactsIndices = inputData.getIntArray(SELECTED_CONTACTS_INDICES) ?: IntArray(0) val file = File(vCardFilePath) val vCards = ArrayList<VCard>() var cursor: Cursor? = null @Suppress("TooGenericExceptionCaught") // legacy code try { val operations = ContactOperations(applicationContext, contactsAccountName, contactsAccountType) vCards.addAll(Ezvcard.parse(file).all()) Collections.sort(vCards, VCardComparator()) cursor = contentResolver.query( ContactsContract.Contacts.CONTENT_URI, null, null, null, null ) val ownContactMap = TreeMap<VCard, Long?>(VCardComparator()) if (cursor != null && cursor.count > 0) { cursor.moveToFirst() for (i in 0 until cursor.count) { val vCard = getContactFromCursor(cursor) if (vCard != null) { ownContactMap[vCard] = cursor.getLong(cursor.getColumnIndex("NAME_RAW_CONTACT_ID")) } cursor.moveToNext() } } for (contactIndex in selectedContactsIndices) { val vCard = vCards[contactIndex] if (ContactListFragment.getDisplayName(vCard).isEmpty()) { if (!ownContactMap.containsKey(vCard)) { operations.insertContact(vCard) } else { operations.updateContact(vCard, ownContactMap[vCard]) } } else { operations.insertContact(vCard) // Insert All the contacts without name } } } catch (e: Exception) { logger.e(TAG, "${e.message}", e) } finally { cursor?.close() } return Result.success() } private fun getContactFromCursor(cursor: Cursor): VCard? { val lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)) val uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey) var vCard: VCard? = null try { contentResolver.openInputStream(uri).use { inputStream -> val vCardList = ArrayList<VCard>() vCardList.addAll(Ezvcard.parse(inputStream).all()) if (vCardList.size > 0) { vCard = vCardList[0] } } } catch (e: IOException) { logger.d(TAG, "${e.message}") } return vCard } }
gpl-2.0
05667bde68817a2b6caa6092d3abb256
38.230769
108
0.637647
4.722222
false
false
false
false