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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Yubico/yubioath-desktop | android/flutter_plugins/qrscanner_zxing/android/src/main/kotlin/com/yubico/authenticator/flutter_plugins/qrscanner_zxing/QRScannerZxingPlugin.kt | 1 | 3354 | /*
* Copyright (C) 2022 Yubico.
*
* 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.yubico.authenticator.flutter_plugins.qrscanner_zxing
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry
class PermissionsResultRegistrar {
private var permissionsResultListener: PluginRegistry.RequestPermissionsResultListener? = null
fun setListener(listener: PluginRegistry.RequestPermissionsResultListener?) {
permissionsResultListener = listener
}
fun onResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
): Boolean {
return permissionsResultListener?.onRequestPermissionsResult(
requestCode,
permissions,
grantResults
) ?: false
}
}
/** QRScannerZxingPlugin */
class QRScannerZxingPlugin : FlutterPlugin, MethodCallHandler, ActivityAware,
PluginRegistry.RequestPermissionsResultListener {
private val registrar = PermissionsResultRegistrar()
private lateinit var channel: MethodChannel
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(binding.binaryMessenger, "qrscanner_zxing")
channel.setMethodCallHandler(this)
binding.platformViewRegistry
.registerViewFactory(
"qrScannerNativeView",
QRScannerViewFactory(binding.binaryMessenger, registrar)
)
}
override fun onMethodCall(call: MethodCall, result: Result) {
if (call.method == "getPlatformVersion") {
result.success("Android ${android.os.Build.VERSION.RELEASE}")
} else {
result.notImplemented()
}
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
binding.addRequestPermissionsResultListener(this)
}
override fun onDetachedFromActivityForConfigChanges() {
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
}
override fun onDetachedFromActivity() {
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
): Boolean {
return registrar.onResult(requestCode, permissions, grantResults)
}
}
| apache-2.0 | ae92c51c47233c5a88d72a368bac1bf0 | 32.54 | 98 | 0.728682 | 4.991071 | false | false | false | false |
MER-GROUP/intellij-community | platform/script-debugger/backend/src/org/jetbrains/debugger/BreakpointManagerBase.kt | 4 | 4991 | /*
* Copyright 2000-2015 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.debugger
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.EventDispatcher
import com.intellij.util.SmartList
import com.intellij.util.containers.ContainerUtil
import gnu.trove.TObjectHashingStrategy
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.rejectedPromise
import org.jetbrains.concurrency.resolvedPromise
import java.util.concurrent.ConcurrentMap
abstract class BreakpointManagerBase<T : BreakpointBase<*>> : BreakpointManager {
override val breakpoints = ContainerUtil.newConcurrentSet<T>()
protected val breakpointDuplicationByTarget: ConcurrentMap<T, T> = ContainerUtil.newConcurrentMap<T, T>(object : TObjectHashingStrategy<T> {
override fun computeHashCode(b: T): Int {
var result = b.line
result *= 31 + b.column
if (b.condition != null) {
result *= 31 + b.condition!!.hashCode()
}
result *= 31 + b.target.hashCode()
return result
}
override fun equals(b1: T, b2: T) = b1.target.javaClass == b2.target.javaClass && b1.target == b2.target && b1.line == b2.line && b1.column == b2.column && StringUtil.equals(b1.condition, b2.condition)
})
protected val dispatcher: EventDispatcher<BreakpointListener> = EventDispatcher.create(BreakpointListener::class.java)
protected abstract fun createBreakpoint(target: BreakpointTarget, line: Int, column: Int, condition: String?, ignoreCount: Int, enabled: Boolean): T
protected abstract fun doSetBreakpoint(target: BreakpointTarget, breakpoint: T): Promise<out Breakpoint>
override final fun setBreakpoint(target: BreakpointTarget, line: Int, column: Int, condition: String?, ignoreCount: Int, enabled: Boolean, promiseRef: Ref<Promise<out Breakpoint>>?): Breakpoint {
val breakpoint = createBreakpoint(target, line, column, condition, ignoreCount, enabled)
val existingBreakpoint = breakpointDuplicationByTarget.putIfAbsent(breakpoint, breakpoint)
if (existingBreakpoint != null) {
promiseRef?.set(resolvedPromise(breakpoint))
return existingBreakpoint
}
breakpoints.add(breakpoint)
if (enabled) {
val promise = doSetBreakpoint(target, breakpoint)
.rejected { dispatcher.multicaster.errorOccurred(breakpoint, it.message ?: it.toString()) }
promiseRef?.set(promise)
}
else {
promiseRef?.set(resolvedPromise(breakpoint))
}
return breakpoint
}
override final fun remove(breakpoint: Breakpoint): Promise<*> {
@Suppress("UNCHECKED_CAST")
val b = breakpoint as T
val existed = breakpoints.remove(b)
if (existed) {
breakpointDuplicationByTarget.remove(b)
}
return if (!existed || !b.isVmRegistered()) resolvedPromise() else doClearBreakpoint(b)
}
override final fun removeAll(): Promise<*> {
val list = breakpoints.toList()
breakpoints.clear()
breakpointDuplicationByTarget.clear()
val promises = SmartList<Promise<*>>()
for (b in list) {
if (b.isVmRegistered()) {
promises.add(doClearBreakpoint(b))
}
}
return Promise.all(promises)
}
protected abstract fun doClearBreakpoint(breakpoint: T): Promise<*>
override final fun addBreakpointListener(listener: BreakpointListener) {
dispatcher.addListener(listener)
}
protected fun notifyBreakpointResolvedListener(breakpoint: T) {
if (breakpoint.isResolved) {
dispatcher.multicaster.resolved(breakpoint)
}
}
@Suppress("UNCHECKED_CAST")
override fun flush(breakpoint: Breakpoint) = (breakpoint as T).flush(this)
override fun enableBreakpoints(enabled: Boolean): Promise<*> = rejectedPromise<Any?>("Unsupported")
}
class DummyBreakpointManager : BreakpointManager {
override val breakpoints: Iterable<Breakpoint>
get() = emptyList()
override fun setBreakpoint(target: BreakpointTarget, line: Int, column: Int, condition: String?, ignoreCount: Int, enabled: Boolean, promiseRef: Ref<Promise<out Breakpoint>>?): Breakpoint {
throw UnsupportedOperationException()
}
override fun remove(breakpoint: Breakpoint) = resolvedPromise()
override fun addBreakpointListener(listener: BreakpointListener) {
}
override fun removeAll() = resolvedPromise()
override fun flush(breakpoint: Breakpoint) = resolvedPromise()
override fun enableBreakpoints(enabled: Boolean) = resolvedPromise()
} | apache-2.0 | 560bac2653fe6263d3593d1a51645915 | 37.10687 | 205 | 0.736726 | 4.452275 | false | false | false | false |
mdaniel/intellij-community | platform/lang-impl/testSources/com/intellij/toolWindow/ToolWindowManagerTestCase.kt | 1 | 1894 | // 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.toolWindow
import com.intellij.openapi.application.EDT
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerListener.ToolWindowManagerEventType
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.openapi.wm.impl.ProjectFrameHelper
import com.intellij.openapi.wm.impl.ToolWindowManagerImpl
import com.intellij.testFramework.LightPlatformTestCase
import com.intellij.testFramework.SkipInHeadlessEnvironment
import com.intellij.testFramework.replaceService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
@SkipInHeadlessEnvironment
abstract class ToolWindowManagerTestCase : LightPlatformTestCase() {
@JvmField
protected var manager: ToolWindowManagerImpl? = null
final override fun runInDispatchThread() = false
public override fun setUp() {
super.setUp()
runBlocking {
val project = project
manager = object : ToolWindowManagerImpl(project) {
override fun fireStateChanged(changeType: ToolWindowManagerEventType) {}
}
project.replaceService(ToolWindowManager::class.java, manager!!, testRootDisposable)
val frame = withContext(Dispatchers.EDT) {
val frame = ProjectFrameHelper(IdeFrameImpl(), null)
frame.init()
frame
}
manager!!.doInit(frame, project.messageBus.connect(testRootDisposable), FileEditorManagerEx.getInstanceEx(project))
}
}
public override fun tearDown() {
try {
manager!!.projectClosed()
manager = null
}
catch (e: Throwable) {
addSuppressedException(e)
}
finally {
super.tearDown()
}
}
} | apache-2.0 | cc6affe3215b17042d3e9759a44bea13 | 32.245614 | 121 | 0.763464 | 5.064171 | false | true | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/gradle/hmppImportAndHighlighting/multiModulesHmpp/bottom-mpp/src/commonMain/kotlin/transitiveStory/midActual/commonSource/SomethinInTheCommon.kt | 2 | 1349 | package transitiveStory.midActual.commonSource
val moduleName = "bottom-mpp"
expect val <!LINE_MARKER("descr='Has actuals in [multimod-hmpp.bottom-mpp.iosSimLibMain, multimod-hmpp.bottom-mpp.jvm16Main, multimod-hmpp.bottom-mpp.jvmWithJavaMain] module'")!>sourceSetName<!>: String
expect open class <!LINE_MARKER("descr='Has actuals in [multimod-hmpp.bottom-mpp.iosSimLibMain, multimod-hmpp.bottom-mpp.jvm16Main, multimod-hmpp.bottom-mpp.jvmWithJavaMain] module'")!>SomeMPPInTheCommon<!>() {
val <!LINE_MARKER("descr='Has actuals in [multimod-hmpp.bottom-mpp.iosSimLibMain, multimod-hmpp.bottom-mpp.jvm16Main, multimod-hmpp.bottom-mpp.jvmWithJavaMain] module'")!>simpleVal<!>: Int
companion object <!LINE_MARKER("descr='Has actuals in [multimod-hmpp.bottom-mpp.iosSimLibMain, multimod-hmpp.bottom-mpp.jvm16Main, multimod-hmpp.bottom-mpp.jvmWithJavaMain] module'")!>Compainon<!> {
val <!LINE_MARKER("descr='Has actuals in [multimod-hmpp.bottom-mpp.iosSimLibMain, multimod-hmpp.bottom-mpp.jvm16Main, multimod-hmpp.bottom-mpp.jvmWithJavaMain] module'")!>inTheCompanionOfBottomActualDeclarations<!>: String
}
}
fun regularTLfunInTheMidActualCommmon(s: String): String {
return "I'm a function at the top level of a file in `commonMain` source set of module $moduleName." +
"This is the message I've got: \n`$s`"
}
| apache-2.0 | bab91ebb0da6f3c7f24868977bc60f01 | 78.352941 | 230 | 0.762046 | 3.330864 | false | false | false | false |
ingokegel/intellij-community | platform/remote-core/src/remote/SshConnectionConfigPatch.kt | 9 | 3629 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.remote
import org.jetbrains.annotations.ApiStatus
import java.time.Duration
/**
* Additional options overridable in SSH Connections settings. This config must have the highest priority across all other configuration
* ways. Every field is nullable. Null means that the value should keep its default value.
*
* @param serverAliveInterval How often to send keep-alive messages in OpenSSH format. Overrides `ServerAliveInterval` section of
* OpenSSH configs. If the duration is zero or negative, keep-alive messages are forcibly disabled.
*/
@ApiStatus.Experimental
data class SshConnectionConfigPatch(
var hostKeyVerifier: HostKeyVerifier?,
var serverAliveInterval: Duration?,
var proxyParams: ProxyParams?,
) {
data class ProxyParams(
var proxyHost: String,
var proxyPort: Int,
var proxyType: Type,
var authData: ProxyAuthData?,
) {
constructor() : this("", -1, Type.NO_PROXY, null)
fun withProxyHost(value: String): ProxyParams = apply { proxyHost = value }
fun withProxyPort(value: Int): ProxyParams = apply { proxyPort = value }
fun withProxyType(value: Type): ProxyParams = apply { proxyType = value }
fun withProxyAuthData(value: ProxyAuthData) = apply { authData = value }
enum class Type {
NO_PROXY,
HTTP,
SOCKS,
IDE_WIDE_PROXY
}
data class ProxyAuthData(
var username: String,
var password: String,
var authType: ProxyAuthType,
) {
constructor() : this("", "", ProxyAuthType.NO_AUTHORIZATION)
enum class ProxyAuthType {
NO_AUTHORIZATION,
USER_AND_PASSWORD,
}
}
}
/**
* @param hashKnownHosts Indicates that host names and addresses should be hashed while being added to the known hosts file.
* @param strictHostKeyChecking How the SSH client should react on a host key which's not mentioned in the known hosts file.
*/
data class HostKeyVerifier(
var hashKnownHosts: Boolean?,
var strictHostKeyChecking: StrictHostKeyChecking?,
) {
constructor() : this(null, null)
fun withHashKnownHosts(value: Boolean): HostKeyVerifier = apply { hashKnownHosts = value }
fun withStrictHostKeyChecking(value: StrictHostKeyChecking): HostKeyVerifier = apply { strictHostKeyChecking = value }
}
constructor() : this(
hostKeyVerifier = null,
serverAliveInterval = null,
proxyParams = null,
)
fun withHostKeyVerifier(value: HostKeyVerifier): SshConnectionConfigPatch = apply { hostKeyVerifier = value }
fun withServerAliveInterval(value: Duration): SshConnectionConfigPatch = apply { serverAliveInterval = value }
fun withProxyParameters(value: ProxyParams): SshConnectionConfigPatch = apply { proxyParams = value }
fun deepCopy(): SshConnectionConfigPatch = copy(
hostKeyVerifier = hostKeyVerifier?.copy(),
proxyParams = proxyParams?.copy(),
)
}
@ApiStatus.Experimental
enum class StrictHostKeyChecking {
/** Never automatically add host keys to the known hosts file. */
YES,
/** Automatically add new host keys to the user known hosts files, but not permit connections to hosts with changed host keys. */
ACCEPT_NEW,
/** Automatically add new host keys to the user known hosts files and allow connections to hosts with changed host keys to proceed. */
NO,
/** New host keys will be added to the user known host files only after the user has confirmed that is what they really want to do. */
ASK,
}
| apache-2.0 | f29ab42b3a02451e5046269c26ecc8d2 | 32.915888 | 158 | 0.724442 | 4.356543 | false | true | false | false |
squanchy-dev/squanchy-android | app/src/main/java/net/squanchy/support/graphics/CircularRevealDrawable.kt | 1 | 4171 | package net.squanchy.support.graphics
import android.animation.Animator
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import androidx.annotation.ColorInt
import androidx.annotation.IntRange
import androidx.core.animation.doOnEnd
import androidx.interpolator.view.animation.FastOutLinearInInterpolator
import me.eugeniomarletti.renderthread.CanvasProperty
import me.eugeniomarletti.renderthread.RenderThread
import kotlin.math.max
import kotlin.math.sqrt
class CircularRevealDrawable : ColorDrawable() {
private val animationPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val interpolator = FastOutLinearInInterpolator()
private lateinit var radiusAnimator: Animator
private lateinit var centerXProperty: CanvasProperty<Float>
private lateinit var centerYProperty: CanvasProperty<Float>
private lateinit var radiusProperty: CanvasProperty<Float>
private lateinit var paintProperty: CanvasProperty<Paint>
private var startAnimationOnNextDraw: Boolean = false
private var revealDuration: Int = 0
private var hotspotX: Float = 0f
private var hotspotY: Float = 0f
private var width: Int = 0
private var height: Int = 0
@ColorInt
private var pendingTargetColor: Int = 0
@ColorInt
private var targetColor: Int = 0
fun animateToColor(@ColorInt newColor: Int, @IntRange(from = 0) durationMillis: Int) {
revealDuration = durationMillis
pendingTargetColor = newColor
startAnimationOnNextDraw = true
color = targetColor
}
override fun draw(canvas: Canvas) {
// 1. Draw the "current" color
canvas.drawColor(color)
// 2. If we just got a reveal start request, go with it
if (startAnimationOnNextDraw) {
initializeAnimation(canvas, pendingTargetColor)
radiusAnimator.start()
startAnimationOnNextDraw = false
}
// 3. This draws the reveal, if one is needed
if (::radiusAnimator.isInitialized && radiusAnimator.isRunning) {
RenderThread.drawCircle(canvas, centerXProperty, centerYProperty, radiusProperty, paintProperty)
}
}
private fun initializeAnimation(canvas: Canvas, pendingTargetColor: Int) {
val initialRadius = 0f
val targetRadius = calculateTargetRadius()
animationPaint.color = pendingTargetColor
centerXProperty = RenderThread.createCanvasProperty(canvas, hotspotX)
centerYProperty = RenderThread.createCanvasProperty(canvas, hotspotY)
radiusProperty = RenderThread.createCanvasProperty(canvas, initialRadius)
paintProperty = RenderThread.createCanvasProperty(canvas, animationPaint)
cancelTransitions()
radiusAnimator = RenderThread.createFloatAnimator(this, canvas, radiusProperty, targetRadius)
radiusAnimator.interpolator = interpolator
radiusAnimator.duration = revealDuration.toLong()
radiusAnimator.doOnEnd {
color = targetColor
}
targetColor = pendingTargetColor
}
private fun calculateTargetRadius(): Float {
val maxXDistance = max(hotspotX, width - hotspotX)
val maxYDistance = max(hotspotY, height - hotspotY)
return sqrt(maxXDistance * maxXDistance + maxYDistance * maxYDistance)
}
override fun setHotspot(x: Float, y: Float) {
super.setHotspot(x, y)
hotspotX = x
hotspotY = y
}
override fun onBoundsChange(bounds: Rect) {
super.onBoundsChange(bounds)
width = bounds.width()
height = bounds.height()
}
override fun setColor(color: Int) {
targetColor = color
super.setColor(color)
}
fun cancelTransitions() {
if (!::radiusAnimator.isInitialized || !radiusAnimator.isRunning) {
return
}
radiusAnimator.cancel()
color = targetColor
}
companion object {
fun from(initialColor: Int) = CircularRevealDrawable().apply {
color = initialColor
targetColor = initialColor
}
}
}
| apache-2.0 | ae4c6f87b959638a2e1fda855280fa9d | 31.084615 | 108 | 0.699592 | 4.83314 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/magnacarta/MagnaCartaTransitData.kt | 1 | 2576 | /*
* MagnaCartaTransitData.kt
*
* Copyright 2019 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.magnacarta
import au.id.micolous.metrodroid.card.CardType
import au.id.micolous.metrodroid.card.desfire.DesfireCard
import au.id.micolous.metrodroid.card.desfire.DesfireCardTransitFactory
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.transit.*
@Parcelize
class MagnaCartaTransitData (
private val mBalance: Int? // cents
): TransitData() {
override val serialNumber: String?
get() = null
override val cardName: String
get() = NAME
override val balance
get() = mBalance?.let { TransitCurrency.EUR(it) }
companion object {
const val NAME = "MagnaCarta"
const val APP_ID_BALANCE = 0xf080f3
private val CARD_INFO = CardInfo(
name = NAME,
locationId = R.string.location_germany,
region = TransitRegion.GERMANY,
imageId = R.drawable.ximedes,
cardType = CardType.MifareDesfire)
val FACTORY: DesfireCardTransitFactory = object : DesfireCardTransitFactory {
override val allCards: List<CardInfo>
get() = listOf(CARD_INFO)
override fun earlyCheck(appIds: IntArray) = APP_ID_BALANCE in appIds
override fun parseTransitData(card: DesfireCard): MagnaCartaTransitData? {
val file2 = card.getApplication(APP_ID_BALANCE)?.getFile(2)
val balance = file2?.data?.byteArrayToInt(6, 2)
return MagnaCartaTransitData(mBalance = balance)
}
override fun parseTransitIdentity(card: DesfireCard): TransitIdentity =
TransitIdentity(NAME, null)
override val hiddenAppIds: List<Int>
get() = listOf(APP_ID_BALANCE)
}
}
}
| gpl-3.0 | aa5bd32b4fe6e3f1836b6993ab9c3c1e | 35.28169 | 86 | 0.671584 | 4.388416 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/friends/feed/FeedViewController.kt | 1 | 9598 | package io.ipoli.android.friends.feed
import android.animation.Animator
import android.animation.AnimatorInflater
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.view.*
import android.view.animation.OvershootInterpolator
import com.google.firebase.auth.FirebaseAuth
import io.ipoli.android.R
import io.ipoli.android.common.redux.android.ReduxViewController
import io.ipoli.android.common.view.*
import io.ipoli.android.friends.feed.FeedViewState.StateType.*
import io.ipoli.android.friends.feed.data.AndroidReactionType
import io.ipoli.android.friends.feed.data.Post
import kotlinx.android.synthetic.main.controller_feed.view.*
import kotlinx.android.synthetic.main.item_popup_reaction.view.*
import kotlinx.android.synthetic.main.view_empty_list.view.*
import kotlinx.android.synthetic.main.view_loader.view.*
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 7/10/18.
*/
class FeedViewController(args: Bundle? = null) :
ReduxViewController<FeedAction, FeedViewState, FeedReducer>(args), ReactionPopupHandler {
override val reducer = FeedReducer
private var isGuest = true
init {
helpConfig = HelpConfig(
R.string.help_dialog_heroes_feed_title,
R.string.help_dialog_heroes_feed_message
)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup,
savedViewState: Bundle?
): View {
setHasOptionsMenu(true)
val view = container.inflate(R.layout.controller_feed)
view.shareItem.onDebounceClick {
navigateFromRoot().toPostItemPicker()
}
view.reactionPopup.layoutManager = GridLayoutManager(view.context, 3)
view.reactionPopup.adapter = ReactionPopupAdapter(this)
(view.reactionPopup.adapter as ReactionPopupAdapter).updateAll(
AndroidReactionType.values().map { it ->
val title = stringRes(it.title)
ReactionPopupViewModel(
title,
it.animation,
title,
Post.ReactionType.valueOf(it.name)
) {
if (FirebaseAuth.getInstance().currentUser == null) {
showShortToast(R.string.error_need_registration)
} else {
dispatch(FeedAction.React(it))
}
}
}
)
view.feedList.setOnTouchListener { _, _ ->
if (isPopupShown()) {
hideReactionPopup()
true
} else {
false
}
}
view.feedList.layoutManager = LinearLayoutManager(view.context)
view.feedList.adapter = PostAdapter(this, activity!!)
view.emptyAnimation.setAnimation("empty_posts.json")
return view
}
override fun isPopupShown() = view?.let { it.reactionPopup.alpha > 0 } ?: false
override fun onCreateLoadAction() = FeedAction.Load
override fun onAttach(view: View) {
super.onAttach(view)
enableToolbarTitle()
toolbarTitle = stringRes(R.string.drawer_feed)
}
override fun onDetach(view: View) {
dispatch(FeedAction.Unload)
super.onDetach(view)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.feed_menu, menu)
}
override fun onPrepareOptionsMenu(menu: Menu) {
menu.findItem(R.id.actionAddFriend).isVisible = !isGuest
super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home ->
return router.handleBack()
R.id.actionAddFriend -> {
dispatch(FeedAction.InviteFriend)
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun handleBack() =
if (view != null && view!!.reactionPopup.visible) {
hideReactionPopup()
true
} else false
override fun render(state: FeedViewState, view: View) {
when (state.type) {
LOADING -> {
view.loader.visible()
view.emptyAnimation.pauseAnimation()
view.emptyContainer.gone()
view.feedList.gone()
view.reactionPopup.gone()
}
POSTS_CHANGED -> {
state.isPlayerSignedIn?.let {
isGuest = !it
activity?.invalidateOptionsMenu()
}
val posts = state.posts!!
if (posts.isNotEmpty()) {
renderPosts(view, state)
} else {
renderEmptyPosts(view)
}
if (isGuest) {
view.shareItem.gone()
} else {
view.shareItem.visible()
}
}
NO_INTERNET_CONNECTION -> {
view.loader.gone()
view.emptyContainer.visible()
view.feedList.gone()
view.shareItem.gone()
view.reactionPopup.gone()
view.emptyAnimation.pauseAnimation()
view.emptyAnimation.gone()
view.emptyTitle.text = stringRes(R.string.error_no_internet_title)
view.emptyText.text = stringRes(R.string.feed_no_internet_text)
}
NO_INVITES_LEFT ->
showLongToast(R.string.no_invites_left)
SHOW_INVITE_FRIEND ->
navigate().toInviteFriends()
else -> {
}
}
}
private fun renderEmptyPosts(view: View) {
view.loader.gone()
view.emptyContainer.visible()
view.feedList.gone()
view.reactionPopup.gone()
view.shareItem.visible()
view.emptyAnimation.playAnimation()
view.emptyAnimation.visible()
view.emptyTitle.text = stringRes(R.string.feed_empty_title)
view.emptyText.text = stringRes(R.string.feed_empty_text)
}
private fun renderPosts(
view: View,
state: FeedViewState
) {
view.loader.gone()
view.emptyContainer.gone()
view.emptyAnimation.pauseAnimation()
view.feedList.visible()
view.shareItem.visible()
val postVMs = state.posts!!.map { p ->
toPostViewModel(context = activity!!, post = p,
reactListener = { postId, _ ->
dispatch(FeedAction.ShowReactionPopupForPost(postId))
},
reactListListener = {
if (FirebaseAuth.getInstance().currentUser == null) {
showShortToast(R.string.error_need_registration)
} else {
navigate().toReactionHistory(it)
}
},
commentsListener = {
if (FirebaseAuth.getInstance().currentUser == null) {
showShortToast(R.string.error_need_registration)
} else {
navigateFromRoot().toPost(it)
}
},
shareListener = { m ->
navigate().toSharePost(m)
},
postClickListener = { postId ->
if (FirebaseAuth.getInstance().currentUser == null) {
showShortToast(R.string.error_need_registration)
} else {
navigateFromRoot().toPost(postId)
}
},
avatarClickListener = { postPlayerId ->
navigateFromRoot().toProfile(postPlayerId)
}
)
}
(view.feedList.adapter as PostAdapter).updateAll(postVMs)
}
override fun containerCoordinates() =
view?.let {
val parentLoc = IntArray(2)
view!!.container.getLocationInWindow(parentLoc)
parentLoc
} ?: intArrayOf(0, 0)
override fun hideReactionPopup() {
view?.reactionPopup?.children?.forEach {
it.reactionAnimation.cancelAnimation()
}
view?.let {
playAnimation(
createPopupAnimator(
it.reactionPopup, true
),
onEnd = { it.reactionPopup.gone() }
)
}
}
override fun showReactionPopup(x: Int, y: Float) {
view?.let {
val reactionPopup = it.reactionPopup
reactionPopup.x = x.toFloat()
reactionPopup.y = y
playAnimation(
createPopupAnimator(reactionPopup),
onStart = { reactionPopup.visible() },
onEnd = {
it.reactionPopup.children.forEach { v ->
v.reactionAnimation.playAnimation()
}
})
}
}
private fun createPopupAnimator(view: View, reverse: Boolean = false): Animator {
val anim = if (reverse) R.animator.popout else R.animator.popup
val animator = AnimatorInflater.loadAnimator(view.context, anim)
animator.setTarget(view)
animator.interpolator = OvershootInterpolator()
animator.duration = shortAnimTime
return animator
}
} | gpl-3.0 | 3ffcb55edf7bbf82e0e544e869b49644 | 30.890365 | 93 | 0.554282 | 4.967909 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/challenge/preset/picker/PhysicalCharacteristicsPickerViewState.kt | 1 | 5022 | package io.ipoli.android.challenge.preset.picker
import io.ipoli.android.challenge.preset.picker.PhysicalCharacteristicsPickerViewState.StateType.*
import io.ipoli.android.challenge.preset.picker.PhysicalCharacteristicsPickerViewState.ValidationError
import io.ipoli.android.challenge.usecase.CreateChallengeFromPresetUseCase.PhysicalCharacteristics
import io.ipoli.android.challenge.usecase.CreateChallengeFromPresetUseCase.PhysicalCharacteristics.Gender
import io.ipoli.android.challenge.usecase.CreateChallengeFromPresetUseCase.PhysicalCharacteristics.Units
import io.ipoli.android.common.AppState
import io.ipoli.android.common.BaseViewStateReducer
import io.ipoli.android.common.DataLoadedAction
import io.ipoli.android.common.Validator
import io.ipoli.android.common.redux.Action
import io.ipoli.android.common.redux.BaseViewState
import io.ipoli.android.pet.PetAvatar
sealed class PhysicalCharacteristicsPickerAction : Action {
object Load : PhysicalCharacteristicsPickerAction()
object ToggleUnits : PhysicalCharacteristicsPickerAction()
data class Done(
val currentWeight: String,
val targetWeight: String,
val heightCm: Int,
val heightFeet: Int,
val heightInches: Int
) : PhysicalCharacteristicsPickerAction()
data class ChangeGender(val gender: PhysicalCharacteristics.Gender) :
PhysicalCharacteristicsPickerAction()
}
object PhysicalCharacteristicsPickerReducer :
BaseViewStateReducer<PhysicalCharacteristicsPickerViewState>() {
override val stateKey = key<PhysicalCharacteristicsPickerViewState>()
override fun reduce(
state: AppState,
subState: PhysicalCharacteristicsPickerViewState,
action: Action
) =
when (action) {
is PhysicalCharacteristicsPickerAction.Load ->
state.dataState.player?.let {
subState.copy(
type = DATA_LOADED,
petAvatar = it.pet.avatar
)
} ?: subState.copy(type = LOADING)
is DataLoadedAction.PlayerChanged ->
subState.copy(
type = DATA_LOADED,
petAvatar = action.player.pet.avatar
)
is PhysicalCharacteristicsPickerAction.ToggleUnits ->
subState.copy(
type = UNITS_CHANGED,
units = if (subState.units == Units.IMPERIAL) Units.METRIC else Units.IMPERIAL
)
is PhysicalCharacteristicsPickerAction.Done -> {
val errors = Validator.validate(action).check<ValidationError> {
"gender" {
given { subState.gender == null } addError ValidationError.NO_GENDER_SELECTED
}
"currentWeight" {
given {
action.currentWeight.isBlank() || action.currentWeight.toIntOrNull() == null
} addError ValidationError.EMPTY_CURRENT_WEIGHT
}
"targetWeight" {
given {
action.targetWeight.isBlank() || action.targetWeight.toIntOrNull() == null
} addError ValidationError.EMPTY_TARGET_WEIGHT
}
}
if (errors.isEmpty()) {
subState.copy(
type = PhysicalCharacteristicsPickerViewState.StateType.CHARACTERISTICS_PICKED,
weight = action.currentWeight.toInt(),
targetWeight = action.targetWeight.toInt()
)
} else {
subState.copy(
type = VALIDATION_ERROR,
errors = errors.toSet()
)
}
}
is PhysicalCharacteristicsPickerAction.ChangeGender ->
subState.copy(
type = GENDER_CHANGED,
gender = action.gender
)
else -> subState
}
override fun defaultState() =
PhysicalCharacteristicsPickerViewState(
type = LOADING,
petAvatar = PetAvatar.BEAR,
units = Units.IMPERIAL,
gender = null,
weight = null,
targetWeight = null,
errors = emptySet()
)
}
data class PhysicalCharacteristicsPickerViewState(
val type: StateType,
val petAvatar: PetAvatar,
val units: Units,
val gender: Gender?,
val weight: Int?,
val targetWeight: Int?,
val errors: Set<ValidationError>
) : BaseViewState() {
enum class StateType {
LOADING,
DATA_LOADED,
GENDER_CHANGED,
UNITS_CHANGED,
VALIDATION_ERROR,
CHARACTERISTICS_PICKED
}
enum class ValidationError {
EMPTY_CURRENT_WEIGHT, EMPTY_TARGET_WEIGHT, NO_GENDER_SELECTED
}
} | gpl-3.0 | c8250f3a2f06499cd1a493b2349cadaf | 35.398551 | 105 | 0.599164 | 5.713311 | false | false | false | false |
GunoH/intellij-community | jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/junit/HamcrestAssertionsConverterInspection.kt | 2 | 10729 | // 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.codeInspection.test.junit
import com.intellij.analysis.JvmAnalysisBundle
import com.intellij.codeInspection.*
import com.intellij.codeInspection.test.junit.HamcrestCommonClassNames.*
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.CommonClassNames.*
import com.intellij.uast.UastHintedVisitorAdapter
import com.intellij.util.asSafely
import com.siyeh.ig.junit.JUnitCommonClassNames.*
import com.siyeh.ig.psiutils.TypeUtils
import org.jetbrains.uast.*
import org.jetbrains.uast.generate.UastElementFactory
import org.jetbrains.uast.generate.getUastElementFactory
import org.jetbrains.uast.generate.importMemberOnDemand
import org.jetbrains.uast.generate.replace
import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor
import javax.swing.JComponent
class HamcrestAssertionsConverterInspection : AbstractBaseUastLocalInspectionTool() {
@JvmField
var importMemberOnDemand = true
override fun createOptionsPanel(): JComponent = SingleCheckboxOptionsPanel(
JvmAnalysisBundle.message("jvm.inspections.migrate.assert.to.matcher.option"), this, "importMemberOnDemand"
)
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
val matcherFqn =
JavaPsiFacade.getInstance(holder.project).findClass(ORG_HAMCREST_MATCHERS, holder.file.resolveScope)?.qualifiedName
?: JavaPsiFacade.getInstance(holder.project).findClass(ORG_HAMCREST_CORE_MATCHERS, holder.file.resolveScope)?.qualifiedName
?: return PsiElementVisitor.EMPTY_VISITOR
return UastHintedVisitorAdapter.create(
holder.file.language,
HamcrestAssertionsConverterVisitor(holder, matcherFqn, importMemberOnDemand),
arrayOf(UCallExpression::class.java),
directOnly = true
)
}
}
private class HamcrestAssertionsConverterVisitor(
private val holder: ProblemsHolder,
private val matcherFqn: String,
private val importMemberOnDemand: Boolean,
) : AbstractUastNonRecursiveVisitor() {
private fun isBooleanAssert(methodName: String) = methodName == "assertTrue" || methodName == "assertFalse"
override fun visitCallExpression(node: UCallExpression): Boolean {
val methodName = node.methodName ?: return true
if (!JUNIT_ASSERT_METHODS.contains(methodName)) return true
val method = node.resolveToUElement() ?: return true
val methodClass = method.getContainingUClass() ?: return true
if (methodClass.qualifiedName != ORG_JUNIT_ASSERT && methodClass.qualifiedName != JUNIT_FRAMEWORK_ASSERT) return true
if (isBooleanAssert(methodName)) {
val args = node.valueArguments
val resolveScope = node.sourcePsi?.resolveScope ?: return true
val psiFacade = JavaPsiFacade.getInstance(holder.project)
if (args.last() is UBinaryExpression && psiFacade.findClass(ORG_HAMCREST_NUMBER_ORDERING_COMPARISON, resolveScope) == null) return true
}
val message = JvmAnalysisBundle.message("jvm.inspections.migrate.assert.to.matcher.description", "assertThat()")
holder.registerUProblem(node, message, MigrateToAssertThatQuickFix(matcherFqn, importMemberOnDemand))
return true
}
companion object {
private val JUNIT_ASSERT_METHODS = listOf(
"assertArrayEquals",
"assertEquals", "assertNotEquals",
"assertSame", "assertNotSame",
"assertNotNull", "assertNull",
"assertTrue", "assertFalse"
)
}
}
private class MigrateToAssertThatQuickFix(private val matcherClassFqn: String, private val importMemberOnDemand: Boolean) : LocalQuickFix {
override fun getFamilyName(): String = CommonQuickFixBundle.message("fix.replace.with.x", "assertThat()")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement ?: return
val call = element.getUastParentOfType<UCallExpression>() ?: return
val factory = call.getUastElementFactory(project) ?: return
val methodName = call.methodName ?: return
val arguments = call.valueArguments.toMutableList()
val method = call.resolveToUElement()?.asSafely<UMethod>() ?: return
val message = if (TypeUtils.typeEquals(JAVA_LANG_STRING, method.uastParameters.first().type)) {
arguments.removeFirst()
} else null
val (left, right) = when (methodName) {
"assertTrue", "assertFalse" -> {
val conditionArgument = arguments.lastOrNull() ?: return
when (conditionArgument) {
is UBinaryExpression -> {
val operator = conditionArgument.operator.normalize(methodName)
val matchExpression = factory.buildMatchExpression(operator, conditionArgument.rightOperand) ?: return
conditionArgument.leftOperand to matchExpression
}
is UQualifiedReferenceExpression -> {
val conditionCall = conditionArgument.selector.asSafely<UCallExpression>() ?: return
val conditionMethodName = conditionCall.methodName ?: return
val matchExpression = if (methodName.contains("False")) {
factory.createMatchExpression(
"not", factory.buildMatchExpression(conditionMethodName, conditionArgument.receiver, conditionCall.valueArguments.first())
)
} else {
factory.buildMatchExpression(conditionMethodName, conditionArgument.receiver, conditionCall.valueArguments.first())
} ?: return
conditionArgument.receiver to matchExpression
}
else -> return
}
}
"assertEquals", "assertArrayEquals" -> {
val matchExpression = factory.createMatchExpression("is", arguments.first()) ?: return
arguments.last() to matchExpression
}
"assertNotEquals" -> {
val matchExpression = factory.createMatchExpression(
"not", factory.createMatchExpression("is", arguments.first())
) ?: return
arguments.last() to matchExpression
}
"assertSame" -> {
val matchExpression = factory.createMatchExpression("sameInstance", arguments.first()) ?: return
arguments.last() to matchExpression
}
"assertNotSame" -> {
val matchExpression = factory.createMatchExpression(
"not", factory.createMatchExpression("sameInstance", arguments.first())
) ?: return
arguments.last() to matchExpression
}
"assertNull" -> {
val matchExpression = factory.createMatchExpression("nullValue") ?: return
arguments.first() to matchExpression
}
"assertNotNull" -> {
val matchExpression = factory.createMatchExpression("notNullValue") ?: return
arguments.first() to matchExpression
}
else -> return
}
if (importMemberOnDemand) {
val assertThatCall = factory.createAssertThat(listOfNotNull(message, left, right)) ?: return
val replaced = call.getQualifiedParentOrThis().replace(assertThatCall)?.asSafely<UQualifiedReferenceExpression>() ?: return
var toImport = replaced
while (true) {
val imported = toImport.importMemberOnDemand()?.asSafely<UCallExpression>() ?: return
toImport = imported.valueArguments.lastOrNull()?.asSafely<UQualifiedReferenceExpression>() ?: return
}
}
}
private fun UastElementFactory.createAssertThat(params: List<UExpression>): UExpression? {
val matchAssert = createQualifiedReference(ORG_HAMCREST_MATCHER_ASSERT, null) ?: return null
return createCallExpression(matchAssert, "assertThat", params, null, UastCallKind.METHOD_CALL)
?.getQualifiedParentOrThis()
}
private fun UastElementFactory.createMatchExpression(name: String, parameter: UExpression? = null): UExpression? {
val paramList = if (parameter == null) emptyList() else listOf(parameter)
val matcher = createQualifiedReference(matcherClassFqn, null) ?: return null
return createCallExpression(matcher, name, paramList, null, UastCallKind.METHOD_CALL)?.getQualifiedParentOrThis()
}
private fun UExpression.isPrimitiveType() = getExpressionType() is PsiPrimitiveType
private fun UastElementFactory.createIdEqualsExpression(param: UExpression) =
if (param.isPrimitiveType()) createMatchExpression("is", param) else createMatchExpression("sameInstance", param)
private fun UastBinaryOperator.inverse(): UastBinaryOperator = when (this) {
UastBinaryOperator.EQUALS -> UastBinaryOperator.NOT_EQUALS
UastBinaryOperator.NOT_EQUALS -> UastBinaryOperator.EQUALS
UastBinaryOperator.IDENTITY_EQUALS -> UastBinaryOperator.IDENTITY_NOT_EQUALS
UastBinaryOperator.IDENTITY_NOT_EQUALS -> UastBinaryOperator.IDENTITY_EQUALS
UastBinaryOperator.GREATER -> UastBinaryOperator.LESS_OR_EQUALS
UastBinaryOperator.LESS -> UastBinaryOperator.GREATER_OR_EQUALS
UastBinaryOperator.GREATER_OR_EQUALS -> UastBinaryOperator.LESS
UastBinaryOperator.LESS_OR_EQUALS -> UastBinaryOperator.GREATER
else -> this
}
fun UastBinaryOperator.normalize(methodName: String): UastBinaryOperator = if (methodName.contains("False")) inverse() else this
private fun UastElementFactory.buildMatchExpression(operator: UastBinaryOperator, param: UExpression): UExpression? = when (operator) {
UastBinaryOperator.EQUALS -> createMatchExpression("is", param)
UastBinaryOperator.NOT_EQUALS -> createMatchExpression("not", createMatchExpression("is", param))
UastBinaryOperator.IDENTITY_EQUALS -> createIdEqualsExpression(param)
UastBinaryOperator.IDENTITY_NOT_EQUALS -> createMatchExpression("not", createIdEqualsExpression(param))
UastBinaryOperator.GREATER -> createMatchExpression("greaterThan", param)
UastBinaryOperator.LESS -> createMatchExpression("lessThan", param)
UastBinaryOperator.GREATER_OR_EQUALS -> createMatchExpression("greaterThanOrEqualTo", param)
UastBinaryOperator.LESS_OR_EQUALS -> createMatchExpression("lessThanOrEqualTo", param)
else -> null
}
private fun UastElementFactory.buildMatchExpression(methodName: String, receiver: UExpression, param: UExpression): UExpression? {
return when (methodName) {
"contains" -> {
if (receiver.getExpressionType()?.isInheritorOf(JAVA_UTIL_COLLECTION) == true) {
return createMatchExpression("hasItem", param)
}
if (TypeUtils.typeEquals(JAVA_LANG_STRING, param.getExpressionType())) {
return createMatchExpression("containsString", param)
}
return createMatchExpression("contains", param)
}
"equals" -> createMatchExpression("is", param)
else -> null
}
}
} | apache-2.0 | 4593989fae955b7715f30b423c41429b | 48.447005 | 141 | 0.738093 | 5.096912 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/DestructuringWrongNameInspection.kt | 2 | 2464 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInsight.daemon.impl.quickfix.RenameElementFix
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.psi.destructuringDeclarationVisitor
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class DestructuringWrongNameInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return destructuringDeclarationVisitor(fun(destructuringDeclaration) {
val initializer = destructuringDeclaration.initializer ?: return
val type = initializer.analyze().getType(initializer) ?: return
val classDescriptor = type.constructor.declarationDescriptor as? ClassDescriptor ?: return
if (!classDescriptor.isData) return
val primaryParameterNames = classDescriptor.constructors
.firstOrNull { it.isPrimary }
?.valueParameters
?.map { it.name.asString() } ?: return
destructuringDeclaration.entries.forEachIndexed { entryIndex, entry ->
val variableName = entry.name
if (variableName != primaryParameterNames.getOrNull(entryIndex)) {
for ((parameterIndex, parameterName) in primaryParameterNames.withIndex()) {
if (parameterIndex == entryIndex) continue
if (variableName == parameterName) {
val fix = primaryParameterNames.getOrNull(entryIndex)?.let { RenameElementFix(entry, it) }
holder.registerProblem(
entry,
KotlinBundle.message("variable.name.0.matches.the.name.of.a.different.component", variableName),
*listOfNotNull(fix).toTypedArray()
)
break
}
}
}
}
})
}
}
| apache-2.0 | 95d7b1e3fc6c7eff5909eabe71274409 | 50.333333 | 158 | 0.646916 | 5.908873 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinWhenEntryHandler.kt | 5 | 2193 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.joinLines
import com.intellij.codeInsight.editorActions.JoinLinesHandlerDelegate.CANNOT_JOIN
import com.intellij.codeInsight.editorActions.JoinRawLinesHandlerDelegate
import com.intellij.openapi.editor.Document
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtWhenEntry
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.kotlin.psi.psiUtil.*
class JoinWhenEntryHandler : JoinRawLinesHandlerDelegate {
override fun tryJoinRawLines(document: Document, file: PsiFile, start: Int, end: Int): Int {
if (file !is KtFile) return CANNOT_JOIN
val element = file.findElementAt(start) ?: return CANNOT_JOIN
val entry = element.getPrevSiblingIgnoringWhitespaceAndComments() as? KtWhenEntry ?: return CANNOT_JOIN
if (entry.hasComments()) return CANNOT_JOIN
val entryLastCondition = entry.conditions.lastOrNull() ?: return CANNOT_JOIN
val whenExpression = entry.parent as? KtWhenExpression ?: return CANNOT_JOIN
val nextEntry = entry.getNextSiblingIgnoringWhitespaceAndComments() as? KtWhenEntry ?: return CANNOT_JOIN
if (nextEntry.isElse || nextEntry.hasComments() || !nextEntry.hasSameExpression(entry)) return CANNOT_JOIN
val nextEntryFirstCondition = nextEntry.conditions.firstOrNull() ?: return CANNOT_JOIN
val separator = if (whenExpression.subjectExpression != null) ", " else " || "
document.replaceString(entryLastCondition.endOffset, nextEntryFirstCondition.startOffset, separator)
return entry.startOffset
}
override fun tryJoinLines(document: Document, file: PsiFile, start: Int, end: Int): Int = CANNOT_JOIN
private fun KtWhenEntry.hasComments(): Boolean =
allChildren.any { it is PsiComment } || siblings(withItself = false).takeWhile { !it.textContains('\n') }.any { it is PsiComment }
private fun KtWhenEntry.hasSameExpression(other: KtWhenEntry) = expression?.text == other.expression?.text
}
| apache-2.0 | 9bbe30bb88de1e6ce84c91bb0d6e5009 | 55.230769 | 138 | 0.760602 | 4.75705 | false | false | false | false |
GunoH/intellij-community | plugins/filePrediction/src/com/intellij/filePrediction/logger/FilePredictionEncodedEventFields.kt | 12 | 1387 | // 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.filePrediction.logger
import com.intellij.filePrediction.FilePredictionEventFieldEncoder.encodeBool
import com.intellij.filePrediction.FilePredictionEventFieldEncoder.encodeDouble
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.eventLog.events.*
internal class EncodedBooleanEventField(name: String) {
val field: IntEventField = EventFields.Int(name)
infix fun with(data: Boolean): EventPair<Int> {
return field.with(encodeBool(data))
}
}
internal class EncodedDoubleEventField(name: String) {
val field: DoubleEventField = EventFields.Double(name)
infix fun with(data: Double): EventPair<Double> {
return field.with(encodeDouble(data))
}
}
internal class EncodedEnumEventField<T : Enum<*>>(name: String) {
val field: IntEventField = EventFields.Int(name)
infix fun with(data: T): EventPair<Int> {
return field.with(data.ordinal)
}
}
internal class CandidateAnonymizedPath : PrimitiveEventField<String?>() {
override val validationRule: List<String>
get() = listOf("{regexp#hash}")
override val name = "file_path"
override fun addData(fuData: FeatureUsageData, value: String?) {
fuData.addAnonymizedPath(value)
}
} | apache-2.0 | 00e394bcaf8c1aecd1fe1fddca40e9d4 | 32.853659 | 140 | 0.769286 | 4.140299 | false | false | false | false |
jk1/intellij-community | plugins/github/src/org/jetbrains/plugins/github/util/GithubAccountsMigrationHelper.kt | 1 | 5466 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.util
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ThrowableComputable
import git4idea.DialogManager
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.plugins.github.api.GithubApiTaskExecutor
import org.jetbrains.plugins.github.api.GithubApiUtil
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.api.GithubTask
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.accounts.GithubAccountManager
import org.jetbrains.plugins.github.authentication.ui.GithubLoginDialog
import java.io.IOException
internal const val GITHUB_SETTINGS_PASSWORD_KEY = "GITHUB_SETTINGS_PASSWORD_KEY"
/**
* Temporary helper
* Will move single-account authorization data to accounts list if it was a token-based auth and clear old settings
*/
@Suppress("DEPRECATION")
class GithubAccountsMigrationHelper internal constructor(private val settings: GithubSettings,
private val passwordSafe: PasswordSafe,
private val accountManager: GithubAccountManager) {
private val LOG = logger<GithubAccountsMigrationHelper>()
internal fun getOldServer(): GithubServerPath? {
try {
if (hasOldAccount()) {
return GithubServerPath.from(settings.host ?: GithubApiUtil.DEFAULT_GITHUB_HOST)
}
}
catch (ignore: Exception) {
// it could be called from AnAction.update()
}
return null
}
private fun hasOldAccount(): Boolean {
// either password-based with specified login or token based
return ((settings.authType == GithubAuthData.AuthType.BASIC && settings.login != null) ||
(settings.authType == GithubAuthData.AuthType.TOKEN))
}
/**
* @return false if process was cancelled by user, true otherwise
*/
@CalledInAwt
fun migrate(project: Project): Boolean {
LOG.debug("Migrating old auth")
val login = settings.login
val host = settings.host
val password = passwordSafe.getPassword(GithubSettings::class.java, GITHUB_SETTINGS_PASSWORD_KEY)
val authType = settings.authType
LOG.debug("Old auth data: { login: $login, host: $host, authType: $authType, password null: ${password == null} }")
val hasAnyInfo = login != null || host != null || authType != null || password != null
if (!hasAnyInfo) return true
var dialogCancelled = false
if (accountManager.accounts.isEmpty()) {
val hostToUse = host ?: GithubApiUtil.DEFAULT_GITHUB_HOST
when (authType) {
GithubAuthData.AuthType.TOKEN -> {
LOG.debug("Migrating token auth")
if (password != null) {
try {
val server = GithubServerPath.from(hostToUse)
val progressManager = ProgressManager.getInstance()
val accountName = progressManager.runProcessWithProgressSynchronously(ThrowableComputable<String, IOException> {
GithubApiTaskExecutor.execute(progressManager.progressIndicator, server, password,
GithubTask { GithubApiUtil.getCurrentUser(it).login })
}, "Accessing Github", true, project)
val account = GithubAccountManager.createAccount(accountName, server)
registerAccount(account, password)
}
catch (e: Exception) {
LOG.debug("Failed to migrate old token-based auth. Showing dialog.", e)
val dialog = GithubLoginDialog(project).withServer(hostToUse, false).withToken(password).withError(e)
dialogCancelled = !registerFromDialog(dialog)
}
}
}
GithubAuthData.AuthType.BASIC -> {
LOG.debug("Migrating basic auth")
val dialog = GithubLoginDialog(project, message = "Password authentication is no longer supported for Github.\n" +
"Personal access token can be acquired instead.")
.withServer(hostToUse, false).withCredentials(login, password)
dialogCancelled = !registerFromDialog(dialog)
}
else -> {
}
}
}
if (!dialogCancelled) clearOldAuth()
return !dialogCancelled
}
private fun registerFromDialog(dialog: GithubLoginDialog): Boolean {
DialogManager.show(dialog)
return if (dialog.isOK) {
registerAccount(GithubAccountManager.createAccount(dialog.getLogin(), dialog.getServer()), dialog.getToken())
true
}
else false
}
private fun registerAccount(account: GithubAccount, token: String) {
accountManager.accounts += account
accountManager.updateAccountToken(account, token)
LOG.debug("Registered account $account")
}
private fun clearOldAuth() {
settings.clearAuth()
passwordSafe.setPassword(GithubSettings::class.java, GITHUB_SETTINGS_PASSWORD_KEY, null)
}
companion object {
@JvmStatic
fun getInstance(): GithubAccountsMigrationHelper = service()
}
}
| apache-2.0 | 4f292d10a4cf5b4a61e08534746c3255 | 41.046154 | 140 | 0.687706 | 4.850044 | false | false | false | false |
jk1/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/util/scenarios/WelcomePageModel.kt | 2 | 1498 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testGuiFramework.util.scenarios
import com.intellij.testGuiFramework.fixtures.JDialogFixture
import com.intellij.testGuiFramework.fixtures.WelcomeFrameFixture
import com.intellij.testGuiFramework.impl.GuiTestCase
import com.intellij.testGuiFramework.util.logTestStep
import com.intellij.testGuiFramework.utils.TestUtilsClass
import com.intellij.testGuiFramework.utils.TestUtilsClassCompanion
class WelcomePageDialogModel(val testCase: GuiTestCase) : TestUtilsClass(testCase) {
companion object : TestUtilsClassCompanion<WelcomePageDialogModel>(
{ WelcomePageDialogModel(it) }
)
object Constants {
const val actionCreateNewProject = "Create New Project"
const val actionImportProject = "Create Import Project"
const val actionOpen = "Open"
const val actionCheckout = "Check out from Version Control"
const val menuConfigure = "Configure"
}
}
val GuiTestCase.welcomePageDialogModel by WelcomePageDialogModel
fun WelcomePageDialogModel.createNewProject() {
WelcomeFrameFixture.findSimple().createNewProject()
testCase.newProjectDialogModel.waitLoadingTemplates()
}
fun WelcomePageDialogModel.openPluginsDialog():JDialogFixture{
with(testCase) {
logTestStep("Open `Plugins` dialog")
WelcomeFrameFixture.findSimple().openPluginsDialog()
return pluginsDialogModel.connectDialog()
}
} | apache-2.0 | 852f1d749ecd8d033d380e7faba2c21e | 37.435897 | 140 | 0.811081 | 4.755556 | false | true | false | false |
helloworld1/FreeOTPPlus | token-data/src/main/java/org/fedorahosted/freeotp/data/util/TokenCodeUtil.kt | 1 | 3274 | package org.fedorahosted.freeotp.data.util
import com.google.android.apps.authenticator.Base32String
import org.fedorahosted.freeotp.data.OtpToken
import org.fedorahosted.freeotp.data.OtpTokenType
import org.fedorahosted.freeotp.data.legacy.TokenCode
import java.nio.ByteBuffer
import java.security.InvalidKeyException
import java.security.NoSuchAlgorithmException
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import javax.inject.Inject
class TokenCodeUtil @Inject constructor() {
fun generateTokenCode(otpToken: OtpToken): TokenCode {
val cur = System.currentTimeMillis()
when (otpToken.tokenType) {
OtpTokenType.HOTP ->
return TokenCode(getHOTP(otpToken, otpToken.counter), cur, cur + otpToken.period * 1000)
OtpTokenType.TOTP -> {
val counter: Long = cur / 1000 / otpToken.period
return TokenCode(
getHOTP(otpToken, counter + 0),
(counter + 0) * otpToken.period * 1000,
(counter + 1) * otpToken.period * 1000,
TokenCode(
getHOTP(otpToken, counter + 1),
(counter + 1) * otpToken.period * 1000,
(counter + 2) * otpToken.period * 1000
)
)
}
}
}
private fun getHOTP(otpToken: OtpToken, counter: Long): String {
// Encode counter in network byte order
val bb = ByteBuffer.allocate(8)
bb.putLong(counter)
// Create digits divisor
var div = 1
for (i in otpToken.digits downTo 1) div *= 10
// Create the HMAC
try {
val mac = Mac.getInstance("Hmac${otpToken.algorithm}")
mac.init(SecretKeySpec(Base32String.decode(otpToken.secret), "Hmac${otpToken.algorithm}"))
// Do the hashing
val digest = mac.doFinal(bb.array())
// Truncate
var binary: Int
val off = digest[digest.size - 1].toInt() and 0xf
binary = digest[off].toInt() and 0x7f shl 0x18
binary = binary or (digest[off + 1].toInt() and 0xff shl 0x10)
binary = binary or (digest[off + 2].toInt() and 0xff shl 0x08)
binary = binary or (digest[off + 3].toInt() and 0xff)
var hotp = ""
if (otpToken.issuer == "Steam") {
for (i in 0 until otpToken.digits) {
hotp += STEAMCHARS[binary % STEAMCHARS.size]
binary /= STEAMCHARS.size
}
} else {
binary %= div
// Zero pad
hotp = binary.toString()
while (hotp.length != otpToken.digits) hotp = "0$hotp"
}
return hotp
} catch (e: InvalidKeyException) {
e.printStackTrace()
} catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
}
return ""
}
companion object {
private val STEAMCHARS = charArrayOf(
'2', '3', '4', '5', '6', '7', '8', '9', 'B', 'C',
'D', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q',
'R', 'T', 'V', 'W', 'X', 'Y'
)
}
} | apache-2.0 | 31474bd32840368d1500c5aa5877bcb5 | 34.215054 | 104 | 0.535736 | 4.097622 | false | false | false | false |
evanchooly/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/dependency/FileDependency.kt | 1 | 1263 | package com.beust.kobalt.maven.dependency
import com.beust.kobalt.api.IClasspathDependency
import com.beust.kobalt.maven.CompletedFuture
import org.apache.maven.model.Dependency
import java.io.File
open class FileDependency(open val fileName: String) : IClasspathDependency, Comparable<FileDependency> {
companion object {
val PREFIX_FILE: String = "file://"
}
override val id = PREFIX_FILE + fileName
override val version = "0.0"
override val isMaven = false
override val jarFile = CompletedFuture(File(fileName))
override fun toMavenDependencies(): Dependency {
with(Dependency()) {
systemPath = jarFile.get().absolutePath
return this
}
}
override val shortId = fileName
override fun directDependencies() = arrayListOf<IClasspathDependency>()
override fun compareTo(other: FileDependency) = fileName.compareTo(other.fileName)
override fun toString() = fileName
override fun equals(other: Any?): Boolean{
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as FileDependency
if (id != other.id) return false
return true
}
override fun hashCode() = id.hashCode()
}
| apache-2.0 | 0243e03a21038e920489bd5cee2b9444 | 25.3125 | 105 | 0.684086 | 4.677778 | false | false | false | false |
voxelcarrot/Warren | src/test/kotlin/engineer/carrot/warren/warren/handler/rpl/Rpl474HandlerTests.kt | 2 | 1440 | package engineer.carrot.warren.warren.handler.rpl
import engineer.carrot.warren.kale.irc.message.rfc1459.rpl.Rpl474Message
import engineer.carrot.warren.kale.irc.message.utility.CaseMapping
import engineer.carrot.warren.warren.state.*
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
class Rpl474HandlerTests {
lateinit var handler: Rpl474Handler
lateinit var channelsState: ChannelsState
val caseMappingState = CaseMappingState(mapping = CaseMapping.RFC1459)
@Before fun setUp() {
channelsState = emptyChannelsState(caseMappingState)
handler = Rpl474Handler(channelsState.joining, caseMappingState)
}
@Test fun test_handle_NonexistentChannel_DoesNothing() {
handler.handle(Rpl474Message(source = "", target = "", channel = "#somewhere", contents = ""), mapOf())
assertEquals(emptyChannelsState(caseMappingState), channelsState)
}
@Test fun test_handle_ValidChannel_SetsStatusToFailed() {
channelsState.joining += JoiningChannelState("#channel", status = JoiningChannelLifecycle.JOINING)
handler.handle(Rpl474Message(source = "", target = "", channel = "#channel", contents = ""), mapOf())
val expectedChannelState = JoiningChannelState("#channel", status = JoiningChannelLifecycle.FAILED)
assertEquals(joiningChannelsStateWith(listOf(expectedChannelState), caseMappingState), channelsState)
}
} | isc | d3a2c46f17ac72781d6d55e567310016 | 37.945946 | 111 | 0.75 | 4.705882 | false | true | false | false |
cmzy/okhttp | okhttp/src/main/kotlin/okhttp3/internal/tls/OkHostnameVerifier.kt | 4 | 7799 | /*
* 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 okhttp3.internal.tls
import okhttp3.internal.canParseAsIpAddress
import okhttp3.internal.toCanonicalHost
import okio.utf8Size
import java.security.cert.CertificateParsingException
import java.security.cert.X509Certificate
import java.util.Locale
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLException
import javax.net.ssl.SSLSession
/**
* A HostnameVerifier consistent with [RFC 2818][rfc_2818].
*
* [rfc_2818]: http://www.ietf.org/rfc/rfc2818.txt
*/
@Suppress("NAME_SHADOWING")
object OkHostnameVerifier : HostnameVerifier {
private const val ALT_DNS_NAME = 2
private const val ALT_IPA_NAME = 7
override fun verify(host: String, session: SSLSession): Boolean {
return if (!host.isAscii()) {
false
} else {
try {
verify(host, session.peerCertificates[0] as X509Certificate)
} catch (_: SSLException) {
false
}
}
}
fun verify(host: String, certificate: X509Certificate): Boolean {
return when {
host.canParseAsIpAddress() -> verifyIpAddress(host, certificate)
else -> verifyHostname(host, certificate)
}
}
/** Returns true if [certificate] matches [ipAddress]. */
private fun verifyIpAddress(ipAddress: String, certificate: X509Certificate): Boolean {
val canonicalIpAddress = ipAddress.toCanonicalHost()
return getSubjectAltNames(certificate, ALT_IPA_NAME).any {
canonicalIpAddress == it.toCanonicalHost()
}
}
/** Returns true if [certificate] matches [hostname]. */
private fun verifyHostname(hostname: String, certificate: X509Certificate): Boolean {
val hostname = hostname.asciiToLowercase()
return getSubjectAltNames(certificate, ALT_DNS_NAME).any {
verifyHostname(hostname, it)
}
}
/**
* This is like [toLowerCase] except that it does nothing if this contains any non-ASCII
* characters. We want to avoid lower casing special chars like U+212A (Kelvin symbol) because
* they can return ASCII characters that match real hostnames.
*/
private fun String.asciiToLowercase(): String {
return when {
isAscii() -> lowercase(Locale.US) // This is an ASCII string.
else -> this
}
}
/** Returns true if the [String] is ASCII encoded (0-127). */
private fun String.isAscii() = length == utf8Size().toInt()
/**
* Returns true if [hostname] matches the domain name [pattern].
*
* @param hostname lower-case host name.
* @param pattern domain name pattern from certificate. May be a wildcard pattern such as
* `*.android.com`.
*/
private fun verifyHostname(hostname: String?, pattern: String?): Boolean {
var hostname = hostname
var pattern = pattern
// Basic sanity checks
if (hostname.isNullOrEmpty() ||
hostname.startsWith(".") ||
hostname.endsWith("..")) {
// Invalid domain name
return false
}
if (pattern.isNullOrEmpty() ||
pattern.startsWith(".") ||
pattern.endsWith("..")) {
// Invalid pattern/domain name
return false
}
// Normalize hostname and pattern by turning them into absolute domain names if they are not
// yet absolute. This is needed because server certificates do not normally contain absolute
// names or patterns, but they should be treated as absolute. At the same time, any hostname
// presented to this method should also be treated as absolute for the purposes of matching
// to the server certificate.
// www.android.com matches www.android.com
// www.android.com matches www.android.com.
// www.android.com. matches www.android.com.
// www.android.com. matches www.android.com
if (!hostname.endsWith(".")) {
hostname += "."
}
if (!pattern.endsWith(".")) {
pattern += "."
}
// Hostname and pattern are now absolute domain names.
pattern = pattern.asciiToLowercase()
// Hostname and pattern are now in lower case -- domain names are case-insensitive.
if ("*" !in pattern) {
// Not a wildcard pattern -- hostname and pattern must match exactly.
return hostname == pattern
}
// Wildcard pattern
// WILDCARD PATTERN RULES:
// 1. Asterisk (*) is only permitted in the left-most domain name label and must be the
// only character in that label (i.e., must match the whole left-most label).
// For example, *.example.com is permitted, while *a.example.com, a*.example.com,
// a*b.example.com, a.*.example.com are not permitted.
// 2. Asterisk (*) cannot match across domain name labels.
// For example, *.example.com matches test.example.com but does not match
// sub.test.example.com.
// 3. Wildcard patterns for single-label domain names are not permitted.
if (!pattern.startsWith("*.") || pattern.indexOf('*', 1) != -1) {
// Asterisk (*) is only permitted in the left-most domain name label and must be the only
// character in that label
return false
}
// Optimization: check whether hostname is too short to match the pattern. hostName must be at
// least as long as the pattern because asterisk must match the whole left-most label and
// hostname starts with a non-empty label. Thus, asterisk has to match one or more characters.
if (hostname.length < pattern.length) {
return false // Hostname too short to match the pattern.
}
if ("*." == pattern) {
return false // Wildcard pattern for single-label domain name -- not permitted.
}
// Hostname must end with the region of pattern following the asterisk.
val suffix = pattern.substring(1)
if (!hostname.endsWith(suffix)) {
return false // Hostname does not end with the suffix.
}
// Check that asterisk did not match across domain name labels.
val suffixStartIndexInHostname = hostname.length - suffix.length
if (suffixStartIndexInHostname > 0 &&
hostname.lastIndexOf('.', suffixStartIndexInHostname - 1) != -1) {
return false // Asterisk is matching across domain name labels -- not permitted.
}
// Hostname matches pattern.
return true
}
fun allSubjectAltNames(certificate: X509Certificate): List<String> {
val altIpaNames = getSubjectAltNames(certificate, ALT_IPA_NAME)
val altDnsNames = getSubjectAltNames(certificate, ALT_DNS_NAME)
return altIpaNames + altDnsNames
}
private fun getSubjectAltNames(certificate: X509Certificate, type: Int): List<String> {
try {
val subjectAltNames = certificate.subjectAlternativeNames ?: return emptyList()
val result = mutableListOf<String>()
for (subjectAltName in subjectAltNames) {
if (subjectAltName == null || subjectAltName.size < 2) continue
if (subjectAltName[0] != type) continue
val altName = subjectAltName[1] ?: continue
result.add(altName as String)
}
return result
} catch (_: CertificateParsingException) {
return emptyList()
}
}
}
| apache-2.0 | 71fd938c74c4eaf7f0e513bc33da8f24 | 36.676329 | 98 | 0.685216 | 4.29697 | false | false | false | false |
mdanielwork/intellij-community | platform/projectModel-impl/src/com/intellij/openapi/options/SchemeManager.kt | 6 | 2572 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.options
import com.intellij.openapi.util.Condition
import java.io.File
abstract class SchemeManager<T> {
companion object {
const val EDITABLE_COPY_PREFIX: String = "_@user_"
@JvmStatic
fun getDisplayName(scheme: Scheme): String {
val schemeName = scheme.name
return if (schemeName.startsWith(EDITABLE_COPY_PREFIX))
schemeName.substring(EDITABLE_COPY_PREFIX.length)
else
schemeName
}
}
abstract val allSchemes: List<T>
open val isEmpty: Boolean
get() = allSchemes.isEmpty()
abstract val activeScheme: T?
@Deprecated(replaceWith = ReplaceWith("activeScheme"), message = "Use activeScheme")
open fun getCurrentScheme(): Scheme = activeScheme as Scheme
/**
* If schemes are lazy loaded, you can use this method to postpone scheme selection (scheme will be found by name on first use)
*/
abstract var currentSchemeName: String?
abstract val allSchemeNames: Collection<String>
abstract val rootDirectory: File
abstract fun loadSchemes(): Collection<T>
open fun reload() {}
@Deprecated("Use addScheme", ReplaceWith("addScheme(scheme, replaceExisting)"))
fun addNewScheme(scheme: Scheme, replaceExisting: Boolean) {
@Suppress("UNCHECKED_CAST")
addScheme(scheme as T, replaceExisting)
}
fun addScheme(scheme: T): Unit = addScheme(scheme, true)
abstract fun addScheme(scheme: T, replaceExisting: Boolean)
abstract fun findSchemeByName(schemeName: String): T?
abstract fun setCurrentSchemeName(schemeName: String?, notify: Boolean)
@JvmOverloads
open fun setCurrent(scheme: T?, notify: Boolean = true) {
}
abstract fun removeScheme(scheme: T): Boolean
open fun removeScheme(name: String): T? {
val scheme = findSchemeByName(name)
if (scheme != null) {
removeScheme(scheme)
return scheme
}
return null
}
/**
* Must be called before [.loadSchemes].
*
* Scheme manager processor must be LazySchemeProcessor
*/
open fun loadBundledScheme(resourceName: String, requestor: Any) {}
@JvmOverloads
open fun setSchemes(newSchemes: List<T>, newCurrentScheme: T? = null, removeCondition: Condition<T>? = null) {
}
/**
* Bundled / read-only (or overriding) scheme cannot be renamed or deleted.
*/
open fun isMetadataEditable(scheme: T): Boolean {
return true
}
open fun save(errors: MutableList<Throwable>) {}
}
| apache-2.0 | 5660c38eadde5d71c3cd02dcaacd880e | 26.655914 | 140 | 0.709176 | 4.37415 | false | false | false | false |
Tickaroo/tikxml | processor-common/src/main/java/com/tickaroo/tikxml/processor/converter/ConverterChecker.kt | 1 | 5115 | /*
* Copyright (C) 2015 Hannes Dorfmann
* Copyright (C) 2015 Tickaroo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tickaroo.tikxml.processor.converter
import com.tickaroo.tikxml.TypeConverter
import com.tickaroo.tikxml.processor.ProcessingException
import java.lang.reflect.Modifier
import javax.lang.model.element.Element
import javax.lang.model.element.ElementKind
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.TypeElement
import javax.lang.model.type.DeclaredType
import javax.lang.model.type.MirroredTypeException
import javax.lang.model.type.TypeKind
import kotlin.reflect.KClass
/**
* Class that checks if the given converter class matches the required criterias
* @author Hannes Dorfmann
*/
abstract class ConverterChecker<in T : Annotation> {
// TODO add check if TypeConverter is applyable for the given annotated field type
/**
* Checks if the given class is valid
* @return null if no TypeConverter should be used, otherwise the full qualified name of the type converter
*/
fun getQualifiedConverterName(element: Element, annotation: T): String? {
try {
// Already compiled class
val converterClass = getConverterFromAnnotation(annotation).java
// No type converter
if (converterClass == TypeConverter.NoneTypeConverter::class.java) {
return null
}
// Class must be public
if (!Modifier.isPublic(converterClass.modifiers)) {
throw ProcessingException(element, "TypeConverter class ${converterClass.canonicalName} must be a public class!")
}
if (Modifier.isAbstract(converterClass.modifiers)) {
throw ProcessingException(element, "TypeConverter class ${converterClass.canonicalName} cannot be a abstract")
}
if (Modifier.isInterface(converterClass.modifiers)) {
throw ProcessingException(element, "TypeConverter class ${converterClass.canonicalName} cannot be an interface. Only classes are allowed!")
}
// Must have default constructor
val constructors = converterClass.constructors
for (c in constructors) {
val isPublicConstructor = Modifier.isPublic(c.modifiers);
val paramTypes = c.parameterTypes;
if (paramTypes.isEmpty() && isPublicConstructor) {
return converterClass.canonicalName
}
}
// No public constructor found
throw ProcessingException(element, "TypeConverter class ${converterClass.canonicalName} must provide an empty (parameter-less) public constructor")
} catch(mte: MirroredTypeException) {
// Not compiled class
val typeMirror = mte.typeMirror
if (typeMirror.toString() == TypeConverter.NoneTypeConverter::class.qualifiedName) {
return null
}
if (typeMirror.kind != TypeKind.DECLARED) {
throw ProcessingException(element, "TypeConverter must be a class")
}
val typeConverterType = typeMirror as DeclaredType
val typeConverterElement = typeConverterType.asElement()
if (typeConverterElement.kind != ElementKind.CLASS) {
throw ProcessingException(element, "TypeConverter ${typeConverterElement} must be a public class!")
}
if (!typeConverterElement.modifiers.contains(javax.lang.model.element.Modifier.PUBLIC)) {
throw ProcessingException(element, "TypeConverter ${typeConverterElement} class is not public!")
}
// Check empty constructor
for (e in (typeConverterElement as TypeElement).enclosedElements) {
if (e.kind == ElementKind.CONSTRUCTOR) {
val constructor = e as ExecutableElement
if (constructor.modifiers.contains(javax.lang.model.element.Modifier.PUBLIC)
&& constructor.parameters.isEmpty()) {
return typeMirror.toString()
}
}
}
throw ProcessingException(element, "TypeConverter class ${typeMirror} must provide an empty (parameter-less) public constructor")
}
}
/**
* Extracts the type Converter class from a given annotation
*/
abstract protected fun getConverterFromAnnotation(annotation: T): KClass<out TypeConverter<Any>>
} | apache-2.0 | 8684ac4ea63210a6321a19b1cafb0366 | 38.053435 | 159 | 0.660215 | 5.311526 | false | false | false | false |
mdanielwork/intellij-community | platform/credential-store/src/PasswordSafeImpl.kt | 1 | 8771 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("PackageDirectoryMismatch")
package com.intellij.ide.passwordSafe.impl
import com.intellij.credentialStore.*
import com.intellij.credentialStore.kdbx.IncorrectMasterPasswordException
import com.intellij.credentialStore.keePass.*
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.ide.passwordSafe.PasswordStorage
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.SettingsSavingComponent
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.util.ShutDownTracker
import com.intellij.util.Alarm
import com.intellij.util.SingleAlarm
import com.intellij.util.concurrency.SynchronizedClearableLazy
import org.jetbrains.annotations.TestOnly
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.runAsync
import java.nio.file.Path
import java.nio.file.Paths
open class BasePasswordSafe @JvmOverloads constructor(val settings: PasswordSafeSettings /* public - backward compatibility */,
provider: CredentialStore? = null /* TestOnly */) : PasswordSafe() {
override var isRememberPasswordByDefault: Boolean
get() = settings.state.isRememberPasswordByDefault
set(value) {
settings.state.isRememberPasswordByDefault = value
}
private val _currentProvider = SynchronizedClearableLazy { computeProvider(settings) }
protected val currentProviderIfComputed: CredentialStore?
get() = if (_currentProvider.isInitialized()) _currentProvider.value else null
internal var currentProvider: CredentialStore
get() = _currentProvider.value
set(value) {
_currentProvider.value = value
}
internal fun closeCurrentStore(isSave: Boolean, isEvenMemoryOnly: Boolean) {
val store = currentProviderIfComputed ?: return
if (isEvenMemoryOnly || store !is InMemoryCredentialStore) {
_currentProvider.drop()
if (isSave && store is KeePassCredentialStore) {
try {
store.save(createMasterKeyEncryptionSpec())
}
catch (e: Exception) {
LOG.warn(e)
}
}
}
}
internal fun createMasterKeyEncryptionSpec(): EncryptionSpec {
val pgpKey = settings.state.pgpKeyId
return when (pgpKey) {
null -> EncryptionSpec(type = getDefaultEncryptionType(), pgpKeyId = null)
else -> EncryptionSpec(type = EncryptionType.PGP_KEY, pgpKeyId = pgpKey)
}
}
// it is helper storage to support set password as memory-only (see setPassword memoryOnly flag)
protected val memoryHelperProvider: Lazy<CredentialStore> = lazy { InMemoryCredentialStore() }
override val isMemoryOnly: Boolean
get() = settings.providerType == ProviderType.MEMORY_ONLY
init {
provider?.let {
currentProvider = it
}
}
override fun get(attributes: CredentialAttributes): Credentials? {
val value = currentProvider.get(attributes)
if ((value == null || value.password.isNullOrEmpty()) && memoryHelperProvider.isInitialized()) {
// if password was set as `memoryOnly`
memoryHelperProvider.value.get(attributes)?.let {
if (!it.isEmpty()) {
return it
}
}
}
return value
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
currentProvider.set(attributes, credentials)
if (attributes.isPasswordMemoryOnly && !credentials?.password.isNullOrEmpty()) {
// we must store because otherwise on get will be no password
memoryHelperProvider.value.set(attributes.toPasswordStoreable(), credentials)
}
else if (memoryHelperProvider.isInitialized()) {
memoryHelperProvider.value.set(attributes, null)
}
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?, memoryOnly: Boolean) {
if (memoryOnly) {
memoryHelperProvider.value.set(attributes.toPasswordStoreable(), credentials)
// remove to ensure that on getPassword we will not return some value from default provider
currentProvider.set(attributes, null)
}
else {
set(attributes, credentials)
}
}
// maybe in the future we will use native async, so, this method added here instead "if need, just use runAsync in your code"
override fun getAsync(attributes: CredentialAttributes): Promise<Credentials?> = runAsync { get(attributes) }
open fun save() {
val keePassCredentialStore = currentProviderIfComputed as? KeePassCredentialStore ?: return
keePassCredentialStore.save(createMasterKeyEncryptionSpec())
}
override fun isPasswordStoredOnlyInMemory(attributes: CredentialAttributes, credentials: Credentials): Boolean {
if (isMemoryOnly || credentials.password.isNullOrEmpty()) {
return true
}
if (!memoryHelperProvider.isInitialized()) {
return false
}
return memoryHelperProvider.value.get(attributes)?.let {
!it.password.isNullOrEmpty()
} ?: false
}
}
class PasswordSafeImpl(settings: PasswordSafeSettings /* public - backward compatibility */) : BasePasswordSafe(settings), SettingsSavingComponent {
// SecureRandom (used to generate master password on first save) can be blocking on Linux
private val saveAlarm = SingleAlarm(Runnable {
val currentThread = Thread.currentThread()
ShutDownTracker.getInstance().registerStopperThread(currentThread)
try {
(currentProviderIfComputed as? KeePassCredentialStore)?.save(createMasterKeyEncryptionSpec())
}
finally {
ShutDownTracker.getInstance().unregisterStopperThread(currentThread)
}
}, 0, Alarm.ThreadToUse.POOLED_THREAD, ApplicationManager.getApplication())
override fun save() {
val keePassCredentialStore = currentProviderIfComputed as? KeePassCredentialStore ?: return
if (keePassCredentialStore.isNeedToSave()) {
saveAlarm.request()
}
}
@Suppress("unused", "DeprecatedCallableAddReplaceWith")
@Deprecated("Do not use it")
// public - backward compatibility
val memoryProvider: PasswordStorage
get() = memoryHelperProvider.value as PasswordStorage
}
internal fun getDefaultKeePassDbFile() = getDefaultKeePassBaseDirectory().resolve(DB_FILE_NAME)
private fun computeProvider(settings: PasswordSafeSettings): CredentialStore {
if (settings.providerType == ProviderType.MEMORY_ONLY || (ApplicationManager.getApplication()?.isUnitTestMode == true)) {
return InMemoryCredentialStore()
}
fun showError(title: String) {
NOTIFICATION_MANAGER.notify(title = title, content = "In-memory password storage will be used.", action = object: NotificationAction("Passwords Settings") {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
// to hide before Settings open, otherwise dialog and notification are shown at the same time
notification.expire()
ShowSettingsUtil.getInstance().showSettingsDialog(e.project, PasswordSafeConfigurable::class.java)
}
})
}
if (settings.providerType == ProviderType.KEEPASS) {
try {
val dbFile = settings.keepassDb?.let { Paths.get(it) } ?: getDefaultKeePassDbFile()
return KeePassCredentialStore(dbFile, getDefaultMasterPasswordFile())
}
catch (e: IncorrectMasterPasswordException) {
LOG.warn(e)
showError("KeePass master password is ${if (e.isFileMissed) "missing" else "incorrect"}")
}
catch (e: Throwable) {
LOG.error(e)
showError("Failed opening KeePass database")
}
}
else {
try {
val store = createPersistentCredentialStore()
if (store == null) {
showError("Native keychain is not available")
}
else {
return store
}
}
catch (e: Throwable) {
LOG.error(e)
showError("Cannot use native keychain")
}
}
settings.providerType = ProviderType.MEMORY_ONLY
return InMemoryCredentialStore()
}
internal fun createPersistentCredentialStore(): CredentialStore? {
for (factory in CredentialStoreFactory.CREDENTIAL_STORE_FACTORY.extensionList) {
return factory.create() ?: continue
}
return null
}
@TestOnly
fun createKeePassStore(dbFile: Path, masterPasswordFile: Path): PasswordSafe {
val store = KeePassCredentialStore(dbFile, masterPasswordFile)
val settings = PasswordSafeSettings()
settings.loadState(PasswordSafeSettings.PasswordSafeOptions().apply {
provider = ProviderType.KEEPASS
keepassDb = store.dbFile.toString()
})
return BasePasswordSafe(settings, store)
} | apache-2.0 | 492e5270f465a4fd7991b7b413186e1a | 36.648069 | 160 | 0.733782 | 4.772035 | false | false | false | false |
iSoron/uhabits | uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/ui/views/HistoryChart.kt | 1 | 8845 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.core.ui.views
import org.isoron.platform.gui.Canvas
import org.isoron.platform.gui.Color
import org.isoron.platform.gui.DataView
import org.isoron.platform.gui.TextAlign
import org.isoron.platform.time.DayOfWeek
import org.isoron.platform.time.LocalDate
import org.isoron.platform.time.LocalDateFormatter
import org.isoron.uhabits.core.models.PaletteColor
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.min
import kotlin.math.round
interface OnDateClickedListener {
fun onDateShortPress(date: LocalDate) {}
fun onDateLongPress(date: LocalDate) {}
}
class HistoryChart(
var dateFormatter: LocalDateFormatter,
var firstWeekday: DayOfWeek,
var paletteColor: PaletteColor,
var series: List<Square>,
var defaultSquare: Square,
var notesIndicators: List<Boolean>,
var theme: Theme,
var today: LocalDate,
var onDateClickedListener: OnDateClickedListener = object : OnDateClickedListener {},
var padding: Double = 0.0,
) : DataView {
enum class Square {
ON,
OFF,
GREY,
DIMMED,
HATCHED,
}
var squareSpacing = 1.0
override var dataOffset = 0
private var squareSize = 0.0
private var width = 0.0
private var height = 0.0
private var nColumns = 0
private var topLeftOffset = 0
private var topLeftDate = LocalDate(2020, 1, 1)
private var lastPrintedMonth = ""
private var lastPrintedYear = ""
private var headerOverflow = 0.0
override val dataColumnWidth: Double
get() = squareSpacing + squareSize
override fun onClick(x: Double, y: Double) {
onDateClicked(x, y, false)
}
override fun onLongClick(x: Double, y: Double) {
onDateClicked(x, y, true)
}
private fun onDateClicked(x: Double, y: Double, isLongClick: Boolean) {
if (width <= 0.0) throw IllegalStateException("onClick must be called after draw(canvas)")
val col = ((x - padding) / squareSize).toInt()
val row = ((y - padding) / squareSize).toInt()
val offset = col * 7 + (row - 1)
if (x - padding < 0 || row == 0 || row > 7 || col == nColumns) return
val clickedDate = topLeftDate.plus(offset)
if (clickedDate.isNewerThan(today)) return
if (isLongClick) {
onDateClickedListener.onDateLongPress(clickedDate)
} else {
onDateClickedListener.onDateShortPress(clickedDate)
}
}
override fun draw(canvas: Canvas) {
width = canvas.getWidth()
height = canvas.getHeight()
canvas.setColor(theme.cardBackgroundColor)
canvas.fill()
squareSize = round((height - 2 * padding) / 8.0)
canvas.setFontSize(min(14.0, height * 0.06))
val weekdayColumnWidth = DayOfWeek.values().map { weekday ->
canvas.measureText(dateFormatter.shortWeekdayName(weekday)) + squareSize * 0.15
}.maxOrNull() ?: 0.0
nColumns = floor((width - 2 * padding - weekdayColumnWidth) / squareSize).toInt()
val firstWeekdayOffset = (
today.dayOfWeek.daysSinceSunday -
firstWeekday.daysSinceSunday + 7
) % 7
topLeftOffset = (nColumns - 1 + dataOffset) * 7 + firstWeekdayOffset
topLeftDate = today.minus(topLeftOffset)
lastPrintedYear = ""
lastPrintedMonth = ""
headerOverflow = 0.0
// Draw main columns
repeat(nColumns) { column ->
val topOffset = topLeftOffset - 7 * column
val topDate = topLeftDate.plus(7 * column)
drawColumn(canvas, column, topDate, topOffset)
}
// Draw week day names
canvas.setColor(theme.mediumContrastTextColor)
repeat(7) { row ->
val date = topLeftDate.plus(row)
canvas.setTextAlign(TextAlign.LEFT)
canvas.drawText(
dateFormatter.shortWeekdayName(date),
padding + nColumns * squareSize + squareSize * 0.15,
padding + squareSize * (row + 1) + squareSize / 2
)
}
}
private fun drawColumn(
canvas: Canvas,
column: Int,
topDate: LocalDate,
topOffset: Int,
) {
drawHeader(canvas, column, topDate)
repeat(7) { row ->
val offset = topOffset - row
val date = topDate.plus(row)
if (offset < 0) return
drawSquare(
canvas,
padding + column * squareSize,
padding + (row + 1) * squareSize,
squareSize - squareSpacing,
squareSize - squareSpacing,
date,
offset
)
}
}
private fun drawHeader(canvas: Canvas, column: Int, date: LocalDate) {
canvas.setColor(theme.mediumContrastTextColor)
val monthText = dateFormatter.shortMonthName(date)
val yearText = date.year.toString()
val headerText: String
when {
monthText != lastPrintedMonth -> {
headerText = monthText
lastPrintedMonth = monthText
}
yearText != lastPrintedYear -> {
headerText = yearText
lastPrintedYear = headerText
}
else -> {
headerText = ""
}
}
canvas.setTextAlign(TextAlign.LEFT)
canvas.drawText(
headerText,
headerOverflow + padding + column * squareSize,
padding + squareSize / 2
)
headerOverflow += canvas.measureText(headerText) + 0.1 * squareSize
headerOverflow = max(0.0, headerOverflow - squareSize)
}
private fun drawSquare(
canvas: Canvas,
x: Double,
y: Double,
width: Double,
height: Double,
date: LocalDate,
offset: Int,
) {
val value = if (offset >= series.size) defaultSquare else series[offset]
val hasNotes = if (offset >= notesIndicators.size) false else notesIndicators[offset]
val squareColor: Color
val circleColor: Color
val color = theme.color(paletteColor.paletteIndex)
squareColor = when (value) {
Square.ON -> {
color
}
Square.OFF -> {
theme.lowContrastTextColor
}
Square.GREY -> {
theme.mediumContrastTextColor
}
Square.DIMMED, Square.HATCHED -> {
color.blendWith(theme.cardBackgroundColor, 0.5)
}
}
canvas.setColor(squareColor)
canvas.fillRoundRect(x, y, width, height, width * 0.15)
if (value == Square.HATCHED) {
canvas.setStrokeWidth(0.75)
canvas.setColor(theme.cardBackgroundColor)
var k = width / 10
repeat(5) {
canvas.drawLine(x + k, y, x, y + k)
canvas.drawLine(
x + width - k,
y + height,
x + width,
y + height - k
)
k += width / 5
}
}
val textColor = if (theme.cardBackgroundColor == Color.TRANSPARENT) {
theme.highContrastTextColor
} else {
val c1 = squareColor.contrast(theme.cardBackgroundColor)
val c2 = squareColor.contrast(theme.mediumContrastTextColor)
if (c1 > c2) theme.cardBackgroundColor else theme.mediumContrastTextColor
}
canvas.setColor(textColor)
canvas.setTextAlign(TextAlign.CENTER)
canvas.drawText(date.day.toString(), x + width / 2, y + width / 2)
if (hasNotes) {
circleColor = when (value) {
Square.ON, Square.GREY -> theme.lowContrastTextColor
else -> color
}
canvas.setColor(circleColor)
canvas.fillCircle(x + width - width / 5, y + width / 5, width / 12)
}
}
}
| gpl-3.0 | 74b92962bb1e77fd435c2fc5969f013c | 32 | 98 | 0.589665 | 4.466667 | false | false | false | false |
android/project-replicator | plugin/src/functionalTest/kotlin/com/android/gradle/replicator/AndroidPluginTests.kt | 1 | 5229 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.gradle.replicator
import com.google.common.truth.Truth
import kotlin.test.Test
class AndroidPluginTests {
@Test
fun `android-app in groovy`() {
val setup = setupProject(type = BuildFileType.GROOVY) {
"""
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:$AGP_VERSION"
}
"""
}
setup.buildFile.appendText("""
apply plugin: "com.android.application"
//apply plugin: "kotlin-kapt"
android {
compileSdkVersion = 30
defaultConfig {
minSdkVersion = 24
targetSdkVersion = 30
}
}
""".trimIndent())
setup.runner.build()
// Verify the result
Truth.assertThat(setup.projectDir.resolve("build/project-structure.json").readText()).isEqualTo("""
{
"gradle": "$GRADLE_VERSION",
"agp": "$AGP_VERSION",
"kotlin": "n/a",
"properties": [],
"rootModule": {
"path": ":",
"plugins": [
"com.android.application"
],
"javaSources": {
"fileCount": 0
},
"androidResources": {
"animator": [],
"anim": [],
"color": [],
"drawable": [],
"font": [],
"layout": [],
"menu": [],
"mipmap": [],
"navigation": [],
"raw": [],
"transition": [],
"values": [],
"xml": []
},
"javaResources": {},
"assets": {},
"dependencies": [],
"android": {
"compileSdkVersion": "android-30",
"minSdkVersion": 24,
"targetSdkVersion": 30,
"buildFeatures": {}
}
},
"modules": []
}
""".trimIndent())
}
@Test
fun `android-app plus kotlin in groovy`() {
val setup = setupProject(type = BuildFileType.GROOVY) {
"""
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:$AGP_VERSION"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$KOTLIN_VERSION"
}
"""
}
setup.buildFile.appendText("""
apply plugin: "com.android.application"
apply plugin: "kotlin-android"
android {
compileSdkVersion = 30
defaultConfig {
minSdkVersion = 24
targetSdkVersion = 30
}
}
""".trimIndent())
setup.runner.build()
// Verify the result
Truth.assertThat(setup.projectDir.resolve("build/project-structure.json").readText()).isEqualTo("""
{
"gradle": "$GRADLE_VERSION",
"agp": "$AGP_VERSION",
"kotlin": "$KOTLIN_VERSION",
"properties": [],
"rootModule": {
"path": ":",
"plugins": [
"org.jetbrains.kotlin.android",
"com.android.application"
],
"javaSources": {
"fileCount": 0
},
"kotlinSources": {
"fileCount": 0
},
"androidResources": {
"animator": [],
"anim": [],
"color": [],
"drawable": [],
"font": [],
"layout": [],
"menu": [],
"mipmap": [],
"navigation": [],
"raw": [],
"transition": [],
"values": [],
"xml": []
},
"javaResources": {},
"assets": {},
"dependencies": [],
"android": {
"compileSdkVersion": "android-30",
"minSdkVersion": 24,
"targetSdkVersion": 30,
"buildFeatures": {}
}
},
"modules": []
}
""".trimIndent())
}
} | apache-2.0 | 3928d910ee15619d8bbf985a77ebc613 | 28.548023 | 107 | 0.420348 | 5.424274 | false | false | false | false |
cdietze/klay | tripleklay/src/main/kotlin/tripleklay/util/Bag.kt | 1 | 5079 | package tripleklay.util
import euklid.platform.arrayCopy
/**
* An unordered collection of elements which may contain duplicates. Elements must not be null. The
* elements will be reordered during normal operation of the bag. This is optimized for fast
* additions, removals and iteration. It is not optimized for programmer ass coverage; see the
* warnings below.
*
* *Note:* extra bounds checking is *not performed* which means that some invalid
* operations will succeeed and return null rather than throwing `IndexOutOfBoundsException`.
* Be careful.
*
* *Note:* the iterator returned by [.iterator] does not make concurrent
* modification checks, so concurrent modifications will cause unspecified behavior. Don't do
* that.
*/
class Bag<E>
/** Creates a bag with the specified initial capacity.
* The default initial capacity is 16.*/
constructor(initialCapacity: Int = 16) : Iterable<E> {
private var _elems: Array<Any?> = arrayOfNulls(initialCapacity)
private var _size: Int = 0
/** Returns the number of elements in this bag. */
fun size(): Int {
return _size
}
/** Returns whether this bag is empty. */
val isEmpty: Boolean
get() = _size == 0
/** Returns the element at `index`. */
operator fun get(index: Int): E {
val elem = _elems[index] as E
return elem
}
/** Returns whether this bag contains `elem`. Equality is by reference. */
operator fun contains(elem: E): Boolean {
val elems = _elems
var ii = 0
val ll = _size
while (ii < ll) {
if (elem === elems[ii]) return true
ii++
}
return false
}
/** Returns whether this bag contains at least one element matching `pred`. */
operator fun contains(pred: (E) -> Boolean): Boolean {
val elems = _elems
var ii = 0
val ll = _size
while (ii < ll) {
if (pred.invoke(get(ii))) return true
ii++
}
return false
}
/** Adds `elem` to this bag. The element will always be added to the end of the bag.
* @return the index at which the element was added.
*/
fun add(elem: E): Int {
if (_size == _elems.size) expand(_elems.size * 3 / 2 + 1)
_elems[_size++] = elem
return _size
}
/** Removes the element at the specified index.
* @return the removed element.
*/
fun removeAt(index: Int): E {
val elem = _elems[index] as E
_elems[index] = _elems[--_size]
_elems[_size] = null
return elem
}
/** Removes the first occurrance of `elem` from the bag. Equality is by reference.
* @return true if `elem` was found and removed, false if not.
*/
fun remove(elem: E): Boolean {
val elems = _elems
var ii = 0
val ll = _size
while (ii < ll) {
val ee = elems[ii]
if (ee === elem) {
elems[ii] = elems[--_size]
elems[_size] = null
return true
}
ii++
}
return false
}
/** Removes all elements that match `pred`.
* @return true if at least one element was found and removed, false otherwise.
*/
fun removeWhere(pred: (E) -> Boolean): Boolean {
val elems = _elems
var removed = 0
var ii = 0
val ll = _size
while (ii < ll) {
if (pred.invoke(get(ii))) {
// back ii up so that we recheck the element we're swapping into place here
elems[ii--] = elems[--_size]
elems[_size] = null
removed += 1
}
ii++
}
return removed > 0
}
/** Removes and returns the last element of the bag.
* @throws ArrayIndexOutOfBoundsException if the bag is empty.
*/
fun removeLast(): E {
val elem = _elems[--_size] as E
_elems[_size] = null
return elem
}
/** Removes all elements from this bag. */
fun removeAll() {
val elems = _elems
for (ii in 0.._size - 1) elems[ii] = null
_size = 0
}
override fun iterator(): MutableIterator<E> {
return object : MutableIterator<E> {
override fun hasNext(): Boolean {
return _pos < _size
}
override fun next(): E {
return get(_pos++)
}
override fun remove() {
[email protected](--_pos)
}
private var _pos: Int = 0
}
}
override fun toString(): String {
val buf = StringBuilder("{")
var ii = 0
val ll = _size
while (ii < ll) {
if (ii > 0) buf.append(",")
buf.append(_elems[ii])
ii++
}
return buf.append("}").toString()
}
private fun expand(capacity: Int) {
val elems = arrayOfNulls<Any>(capacity)
arrayCopy(_elems, 0, elems, 0, _elems.size)
_elems = elems
}
}
| apache-2.0 | 3a818e39760c08f2673f455fbc719a98 | 28.022857 | 99 | 0.54302 | 4.163115 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/base/gallery/adapters/HorizontalListAdapters.kt | 1 | 2764 | /*
* 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.base.gallery.adapters
import android.app.Activity
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.squareup.picasso.Picasso
import de.dreier.mytargets.R
import de.dreier.mytargets.base.gallery.HorizontalImageViewHolder
import de.dreier.mytargets.utils.ImageList
import java.io.File
typealias OnItemClickListener = (Int) -> Unit
class HorizontalListAdapters(
private val activity: Activity,
private val images: ImageList,
private val clickListener: OnItemClickListener
) : RecyclerView.Adapter<HorizontalImageViewHolder>() {
private var selectedItem = -1
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HorizontalImageViewHolder {
return HorizontalImageViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.item_image_horizontal, parent, false)
)
}
override fun onBindViewHolder(holder: HorizontalImageViewHolder, position: Int) {
if (position == images.size()) {
holder.image.visibility = View.GONE
holder.camera.visibility = View.VISIBLE
} else {
holder.camera.visibility = View.GONE
holder.image.visibility = View.VISIBLE
Picasso.with(activity)
.load(File(activity.filesDir, images[position].fileName))
.fit()
.into(holder.image)
val matrix = ColorMatrix()
if (selectedItem != position) {
matrix.setSaturation(0f)
holder.image.alpha = 0.5f
} else {
matrix.setSaturation(1f)
holder.image.alpha = 1f
}
val filter = ColorMatrixColorFilter(matrix)
holder.image.colorFilter = filter
}
holder.itemView.setOnClickListener { clickListener.invoke(position) }
}
override fun getItemCount(): Int {
return images.size() + 1
}
fun setSelectedItem(position: Int) {
selectedItem = position
notifyDataSetChanged()
}
}
| gpl-2.0 | f892a691e5e0d6b73d998d069f96a978 | 32.707317 | 98 | 0.681621 | 4.724786 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/mfm/MatcherCache.kt | 1 | 1863 | package jp.juggler.subwaytooter.mfm
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern
// 正規表現パターンごとにMatcherをキャッシュする
// 対象テキストが変わったらキャッシュを捨てて更新する
// Matcher#region(start,text.length) を設定してから返す
// (同一テキストに対してMatcher.usePatternで正規表現パターンを切り替えるのも検討したが、usePatternの方が多分遅くなる)
internal object MatcherCache {
private class MatcherCacheItem(
var matcher: Matcher,
var text: String,
var textHashCode: Int,
)
// スレッドごとにキャッシュ用のマップを持つ
private val matcherCacheMap =
object : ThreadLocal<HashMap<Pattern, MatcherCacheItem>>() {
override fun initialValue(): HashMap<Pattern, MatcherCacheItem> = HashMap()
}
internal fun matcher(
pattern: Pattern,
text: String,
start: Int = 0,
end: Int = text.length,
): Matcher {
val m: Matcher
val textHashCode = text.hashCode()
val map = matcherCacheMap.get()!!
val item = map[pattern]
if (item != null) {
if (item.textHashCode != textHashCode || item.text != text) {
item.matcher = pattern.matcher(text).apply {
useAnchoringBounds(true)
}
item.text = text
item.textHashCode = textHashCode
}
m = item.matcher
} else {
m = pattern.matcher(text).apply {
useAnchoringBounds(true)
}
map[pattern] = MatcherCacheItem(m, text, textHashCode)
}
m.region(start, end)
return m
}
}
| apache-2.0 | 7cd560d406fdb653935ea2c7f2cf8c4d | 28.811321 | 87 | 0.572566 | 3.728311 | false | false | false | false |
gituser9/InvoiceManagement | app/src/main/java/com/user/invoicemanagement/view/fragment/dialog/SetWeightDialogFragment.kt | 1 | 2902 | package com.user.invoicemanagement.view.fragment.dialog
import android.app.Dialog
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.app.AlertDialog
import android.widget.Button
import android.widget.EditText
import com.user.invoicemanagement.R
import com.user.invoicemanagement.model.data.WeightEnum
import com.user.invoicemanagement.model.dto.Product
import com.user.invoicemanagement.other.Constant
import com.user.invoicemanagement.view.interfaces.Saver
class SetWeightDialogFragment : DialogFragment() {
lateinit var edtNewWeight: EditText
lateinit var button: Button
lateinit var product: Product
lateinit var weightEnum: WeightEnum
var fragment: Saver? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(activity)
val inflater = activity.layoutInflater
val view = inflater.inflate(R.layout.dialog_set_weight, null)
edtNewWeight = view.findViewById(R.id.edtNewWeight)
view.findViewById<Button>(R.id.btnWeightMinus).setOnClickListener {
dismiss()
val oldValue = prepareString(button.text.toString()).toFloatOrNull() ?: 0f
val value = prepareString(edtNewWeight.text.toString()).toFloatOrNull() ?: 0f
setProductWeight(product, oldValue - value)
button.text = Constant.priceFormat.format(oldValue - value)
fragment?.saveAll()
}
view.findViewById<Button>(R.id.btnWeightReset).setOnClickListener {
dismiss()
setProductWeight(product, 0f)
button.text = "0.0"
fragment?.saveAll()
}
view.findViewById<Button>(R.id.btnWeightPlus).setOnClickListener {
val oldValue = prepareString(button.text.toString()).toFloatOrNull() ?: 0f
val value = prepareString(edtNewWeight.text.toString()).toFloatOrNull() ?: 0f
setProductWeight(product, oldValue + value)
button.text = Constant.priceFormat.format(oldValue + value).replace(',', '.')
fragment?.saveAll()
dismiss()
}
return builder.setView(view).setCancelable(true).create()
}
private fun setProductWeight(product: Product, weightValue: Float) {
when(weightEnum) {
WeightEnum.WEIGHT_1 -> { product.weightOnStore = weightValue }
WeightEnum.WEIGHT_2 -> { product.weightInFridge = weightValue }
WeightEnum.WEIGHT_3 -> { product.weightInStorage = weightValue }
WeightEnum.WEIGHT_4 -> { product.weight4 = weightValue }
WeightEnum.WEIGHT_5 -> { product.weight5 = weightValue }
}
}
private fun prepareString(string: String): String {
return string.trim()
.replace(',', '.')
.replace(Constant.whiteSpaceRegex, "")
}
} | mit | b389b13668d26990a6c846ad6816ebc9 | 37.706667 | 89 | 0.670917 | 4.688207 | false | false | false | false |
sachil/Essence | app/src/main/java/xyz/sachil/essence/widget/ScalableImageView.kt | 1 | 10615 | package xyz.sachil.essence.widget
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.View
import android.widget.OverScroller
import kotlin.math.max
import kotlin.math.min
class ScalableImageView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
View(context, attrs, defStyleAttr) {
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context) : this(context, null)
companion object {
private const val TAG = "ScalableImageView"
private const val ZOOM_IN_FRACTION = 2.5F
private const val EQUAL_FACTOR = 0.00001F
private const val SCALE_ANIMATION_DURATION = 300L
}
private var imageWidth = 0
private var imageHeight = 0
private var smallestScale = 0F
private var largestScale = 0F
private var largestImageWidth = 0
private var largestImageHeight = 0
private var translateY = 0F
private var translateX = 0F
private lateinit var image: Bitmap
private var isPlaceHolder = false
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
//用于辅助执行fling动画
private val overScroller = OverScroller(context)
//用于执行缩放动画
private lateinit var scaleAnimator: ObjectAnimator
//用于检测双击、滑动和fling手势
private val gestureDetector = GestureDetector(context, GestureListener())
//用于检测缩放手势
private val scaleGestureDetector = ScaleGestureDetector(context, ScaleGestureListener())
private val filingAnimationRunner = FlingAnimationRunner()
var currentScale = 0.0F
set(value) {
field = value
invalidate()
}
fun setImage(image: Bitmap, isPlaceHolder: Boolean) {
this.image = image
this.isPlaceHolder = isPlaceHolder
imageWidth = image.width
imageHeight = image.height
initializeScale()
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
var result = scaleGestureDetector.onTouchEvent(event)
if (!scaleGestureDetector.isInProgress) {
result = gestureDetector.onTouchEvent(event)
}
return result
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (::image.isInitialized) {
val scaleFraction = (currentScale - smallestScale) / (largestScale - smallestScale)
canvas.translate(translateX * scaleFraction, translateY * scaleFraction)
canvas.scale(currentScale, currentScale, width / 2.0f, height / 2.0f)
canvas.drawBitmap(
image,
(width - imageWidth) / 2.0f,
(height - imageHeight) / 2.0f,
paint
)
}
}
private fun initializeScale() {
val imageAspectRatio = imageWidth.toFloat() / imageHeight
val viewAspectRatio = width.toFloat() / height
if (imageAspectRatio > viewAspectRatio) {
smallestScale = width.toFloat() / imageWidth
largestScale = height.toFloat() / imageHeight
} else {
smallestScale = height.toFloat() / imageHeight
largestScale = width.toFloat() / imageWidth
}
//为了可以上下左右拖动,最大缩放比例再大一些
largestScale *= ZOOM_IN_FRACTION
//初始化当前缩放比例
currentScale = smallestScale
largestImageWidth = (imageWidth * largestScale).toInt()
largestImageHeight = (imageHeight * largestScale).toInt()
//初始化缩放动画
scaleAnimator = ObjectAnimator.ofFloat(
this@ScalableImageView,
"currentScale",
smallestScale,
largestScale
).setDuration(SCALE_ANIMATION_DURATION)
}
private fun fixTranslate() {
//这儿使用最大缩放比例的图片大小,是因为在onDraw()方法中,移动偏移量是乘了缩放系数的。
translateX = min((largestImageWidth - width) / 2F, translateX)
translateX = max(-(largestImageWidth - width) / 2F, translateX)
translateY = min((largestImageHeight - height) / 2F, translateY)
translateY = max(-(largestImageHeight - height) / 2F, translateY)
}
private inner class GestureListener : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent?): Boolean = true
override fun onSingleTapConfirmed(e: MotionEvent?): Boolean {
return [email protected]()
}
override fun onDoubleTap(e: MotionEvent): Boolean {
if (!::scaleAnimator.isInitialized) {
return false
}
scaleAnimator.setFloatValues(smallestScale, largestScale)
//如果当前已经缩放到最大
if (largestScale - currentScale <= EQUAL_FACTOR) {
scaleAnimator.reverse()
} else {
if (currentScale - smallestScale <= EQUAL_FACTOR) {
//从手指焦点处开始缩放
val offsetX = e.x - width / 2F
val offsetY = e.y - height / 2F
translateX = offsetX - offsetX * largestScale / smallestScale
translateY = offsetY - offsetY * largestScale / smallestScale
fixTranslate()
} else {
scaleAnimator.setFloatValues(currentScale, largestScale)
}
scaleAnimator.start()
}
return false
}
override fun onScroll(
e1: MotionEvent?,
e2: MotionEvent?,
distanceX: Float,
distanceY: Float
): Boolean {
val currentImageWidth = imageWidth * currentScale
val currentImageHeight = imageHeight * currentScale
//当image的尺寸大于view的尺寸时,才支持scroll
if (currentImageWidth <= width && currentImageHeight <= height) {
return false
}
if (currentImageWidth > width) {
translateX -= distanceX
//当image的高度未超过view的高度时,不支持上下scroll
if (currentImageHeight <= height) {
translateY = 0f
}
}
if (currentImageHeight > height) {
translateY -= distanceY
//当image的宽度未超过view的高度时,不支持左右scroll
if (currentImageWidth <= width) {
translateX = 0f
}
}
fixTranslate()
invalidate()
return false
}
override fun onFling(
e1: MotionEvent?,
e2: MotionEvent?,
velocityX: Float,
velocityY: Float
): Boolean {
val currentImageWidth: Float = imageWidth * currentScale
val currentImageHeight: Float = imageHeight * currentScale
//只有当image的尺寸大于view的尺寸时才能fling
if (currentImageWidth <= width && currentImageHeight <= height) {
return false
}
var minX = 0
var maxX = 0
var minY = 0
var maxY = 0
//计算
if (currentImageWidth > width) {
minX = (-(largestImageWidth - width) / 2F).toInt()
maxX = ((largestImageWidth - width) / 2F).toInt()
}
if (currentImageHeight > height) {
minY = (-(largestImageHeight - height) / 2F).toInt()
maxY = ((largestImageHeight - height) / 2F).toInt()
}
overScroller.fling(
translateX.toInt(),
translateY.toInt(),
velocityX.toInt(),
velocityY.toInt(),
minX,
maxX,
minY,
maxY
)
//启动fling动画
postOnAnimation(filingAnimationRunner)
return false
}
}
private inner class ScaleGestureListener : ScaleGestureDetector.OnScaleGestureListener {
private var beginScale = 0F
override fun onScaleBegin(detector: ScaleGestureDetector?): Boolean {
beginScale = currentScale
return true
}
override fun onScale(detector: ScaleGestureDetector): Boolean {
currentScale = beginScale * detector.scaleFactor
if (currentScale * 2 <= smallestScale && ::scaleAnimator.isInitialized) {
scaleAnimator.setFloatValues(currentScale, smallestScale)
scaleAnimator.start()
} else {
//从手指焦点处开始缩放
val offsetX = detector.focusX - width / 2F
val offsetY = detector.focusY - height / 2F
translateX = offsetX - offsetX * currentScale / smallestScale
translateY = offsetY - offsetY * currentScale / smallestScale
fixTranslate()
invalidate()
}
return false
}
override fun onScaleEnd(detector: ScaleGestureDetector?) {
if (::scaleAnimator.isInitialized) {
//当缩放比例大于最大缩放比例时,恢复到最大缩放比例
if (currentScale > largestScale) {
scaleAnimator.setFloatValues(currentScale, largestScale)
scaleAnimator.start()
} else if (currentScale < smallestScale) {
//当缩放比例小于最小缩放比例时,恢复到最小缩放比例
scaleAnimator.setFloatValues(currentScale, smallestScale)
scaleAnimator.start()
}
}
}
}
private inner class FlingAnimationRunner : Runnable {
override fun run() {
//递归调用不断的执行fling动画
if (overScroller.computeScrollOffset()) {
translateX = overScroller.currX.toFloat()
translateY = overScroller.currY.toFloat()
invalidate()
postOnAnimation(this)
}
}
}
} | apache-2.0 | d4f226879a8a46ef12bc3357cbf60b95 | 34.114983 | 95 | 0.580431 | 5.061276 | false | false | false | false |
paplorinc/intellij-community | plugins/changeReminder/src/com/jetbrains/changeReminder/util.kt | 1 | 2864 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.changeReminder
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Consumer
import com.intellij.vcsUtil.VcsUtil
import com.jetbrains.changeReminder.predict.PredictedChange
import com.jetbrains.changeReminder.predict.PredictedFilePath
import git4idea.GitCommit
import git4idea.GitVcs
import git4idea.checkin.GitCheckinEnvironment
import git4idea.history.GitLogUtil
fun CheckinProjectPanel.isAmend(): Boolean {
if (this !is CommitChangeListDialog) return false
val gitCheckinOptions = this.additionalComponents
.filterIsInstance(GitCheckinEnvironment.GitCheckinOptions::class.java)
.firstOrNull()
?: return false
return gitCheckinOptions.isAmend
}
fun CheckinProjectPanel.getGitRootFiles(project: Project): Map<VirtualFile, Collection<FilePath>> {
val rootFiles = HashMap<VirtualFile, HashSet<FilePath>>()
this.files.forEach { file ->
val filePath = VcsUtil.getFilePath(file.absolutePath)
val fileVcs = ProjectLevelVcsManager.getInstance(project).getVcsRootObjectFor(filePath)
if (fileVcs != null && fileVcs.vcs is GitVcs) {
val fileRoot = fileVcs.path
if (fileRoot != null) {
rootFiles.getOrPut(fileRoot) { HashSet() }.add(filePath)
}
}
}
return rootFiles
}
fun processCommitsFromHashes(project: Project, root: VirtualFile, hashes: List<String>, commitConsumer: (GitCommit) -> Unit): Unit =
GitLogUtil.readFullDetailsForHashes(
project,
root,
GitVcs.getInstance(project),
Consumer<GitCommit> {
commitConsumer(it)
},
hashes.toList(),
true,
false,
false,
false,
GitLogUtil.DiffRenameLimit.NO_RENAMES
)
fun GitCommit.changedFilePaths(): List<FilePath> = this.changes.mapNotNull { it.afterRevision?.file ?: it.beforeRevision?.file }
fun Collection<FilePath>.toPredictedFiles(changeListManager: ChangeListManager) = this.mapNotNull {
val currentChange = changeListManager.getChange(it)
when {
currentChange != null -> PredictedChange(currentChange)
it.virtualFile != null -> PredictedFilePath(it)
else -> null
}
}
fun <T> measureSupplierTimeMillis(supplier: () -> T): Pair<Long, T> {
val startTime = System.currentTimeMillis()
val result = supplier()
val executionTime = System.currentTimeMillis() - startTime
return Pair(executionTime, result)
} | apache-2.0 | cb3f9830aa04c3a12514bf32c82a487b | 35.265823 | 140 | 0.747556 | 4.345979 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/MainEntityListImpl.kt | 1 | 5883 | package com.intellij.workspaceModel.storage.entities.test.api
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
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class MainEntityListImpl(val dataSource: MainEntityListData) : MainEntityList, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val x: String
get() = dataSource.x
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: MainEntityListData?) : ModifiableWorkspaceEntityBase<MainEntityList>(), MainEntityList.Builder {
constructor() : this(MainEntityListData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity MainEntityList 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().isXInitialized()) {
error("Field MainEntityList#x 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 MainEntityList
this.entitySource = dataSource.entitySource
this.x = dataSource.x
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var x: String
get() = getEntityData().x
set(value) {
checkModificationAllowed()
getEntityData().x = value
changedProperty.add("x")
}
override fun getEntityData(): MainEntityListData = result ?: super.getEntityData() as MainEntityListData
override fun getEntityClass(): Class<MainEntityList> = MainEntityList::class.java
}
}
class MainEntityListData : WorkspaceEntityData<MainEntityList>() {
lateinit var x: String
fun isXInitialized(): Boolean = ::x.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<MainEntityList> {
val modifiable = MainEntityListImpl.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): MainEntityList {
return getCached(snapshot) {
val entity = MainEntityListImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return MainEntityList::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return MainEntityList(x, entitySource) {
}
}
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 MainEntityListData
if (this.entitySource != other.entitySource) return false
if (this.x != other.x) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as MainEntityListData
if (this.x != other.x) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + x.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + x.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | cd50dd3cc6a7e3283e5eb055ffb54b18 | 29.640625 | 124 | 0.72276 | 5.319168 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/screen/NewRemixScreen.kt | 2 | 6017 | package io.github.chrislo27.rhre3.screen
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.utils.Align
import io.github.chrislo27.rhre3.RHRE3Application
import io.github.chrislo27.rhre3.RemixRecovery
import io.github.chrislo27.rhre3.editor.Editor
import io.github.chrislo27.rhre3.entity.model.ISoundDependent
import io.github.chrislo27.rhre3.entity.model.ModelEntity
import io.github.chrislo27.rhre3.soundsystem.SoundCache
import io.github.chrislo27.rhre3.stage.GenericStage
import io.github.chrislo27.toolboks.ToolboksScreen
import io.github.chrislo27.toolboks.registry.AssetRegistry
import io.github.chrislo27.toolboks.registry.ScreenRegistry
import io.github.chrislo27.toolboks.ui.Button
import io.github.chrislo27.toolboks.ui.ImageLabel
import io.github.chrislo27.toolboks.ui.Stage
import io.github.chrislo27.toolboks.ui.TextLabel
import io.github.chrislo27.toolboks.util.gdxutils.maxX
class NewRemixScreen(main: RHRE3Application)
: ToolboksScreen<RHRE3Application, NewRemixScreen>(main) {
private val editorScreen: EditorScreen by lazy { ScreenRegistry.getNonNullAsType<EditorScreen>("editor") }
private val editor: Editor
get() = editorScreen.editor
override val stage: Stage<NewRemixScreen> = GenericStage(main.uiPalette, null, main.defaultCamera)
private val mainLabel: TextLabel<NewRemixScreen>
init {
stage as GenericStage
stage.titleIcon.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_newremix"))
stage.titleLabel.text = "screen.new.title"
stage.backButton.visible = true
stage.onBackButtonClick = {
main.screen = ScreenRegistry.getNonNull("editor")
}
val palette = main.uiPalette
stage.bottomStage.elements += Button(palette.copy(highlightedBackColor = Color(1f, 0f, 0f, 0.5f),
clickedBackColor = Color(1f, 0.5f, 0.5f, 0.5f)), stage.bottomStage, stage.bottomStage).apply {
this.location.set(screenX = 0.25f, screenWidth = 0.5f)
this.addLabel(TextLabel(palette, this, this.stage).apply {
this.textAlign = Align.center
this.text = "screen.new.button"
this.isLocalizationKey = true
})
this.leftClickAction = { _, _ ->
editor.remix.entities.forEach {
if (it is ISoundDependent) {
it.unloadSounds()
}
}
SoundCache.unloadAll()
val oldRemix = editor.remix
val newRemix = editor.createRemix()
editor.remix = newRemix
oldRemix.entities.filter { it.bounds.x <= editor.camera.position.x + editor.camera.viewportWidth * 1.5f && it.bounds.maxX >= editor.camera.position.x - editor.camera.viewportWidth * 1.5f }
.filterIsInstance<ModelEntity<*>>()
.forEach { editor.explodeEntity(it, doExplode = true) }
val tmpRect = Rectangle(0f, 0f, 0f, 0.75f)
oldRemix.trackersReverseView.forEach { container ->
tmpRect.y = -0.75f * (container.renderLayer + 1)
container.map.values
.filter { it.beat <= editor.camera.position.x + editor.camera.viewportWidth * 1.5f && it.endBeat >= editor.camera.position.x - editor.camera.viewportWidth * 1.5f }
.forEach { tracker ->
if (tracker.isZeroWidth) {
tmpRect.width = 0.15f
tmpRect.x = tracker.beat - tmpRect.width / 2
} else {
tmpRect.width = tracker.width
tmpRect.x = tracker.beat
}
editor.explodeRegion(tmpRect, tracker.getColour(editor.theme))
}
}
val timeSigColor = editor.theme.trackLine.cpy().apply { a *= 0.25f }
oldRemix.timeSignatures.map.values.forEach { ts ->
editor.explodeRegion(tmpRect.set(ts.beat + 0.125f, 0f, 0.25f, oldRemix.trackCount.toFloat()), timeSigColor)
}
[email protected]()
RemixRecovery.cacheRemixChecksum(newRemix)
Gdx.app.postRunnable {
System.gc()
}
}
}
mainLabel = TextLabel(palette, stage.centreStage, stage.centreStage).apply {
this.location.set(screenX = 0.5f, screenWidth = 0.5f - 0.125f)
this.textAlign = Align.left
this.isLocalizationKey = true
this.text = "screen.new.warning"
}
stage.centreStage.elements += mainLabel
val warn = ImageLabel(palette, stage.centreStage, stage.centreStage).apply {
this.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_warn"))
this.renderType = ImageLabel.ImageRendering.ASPECT_RATIO
this.location.set(screenY = 0.125f, screenHeight = 0.75f)
}
stage.centreStage.elements += warn
warn.apply {
stage.updatePositions()
this.location.set(screenWidth = stage.percentageOfWidth(this.location.realHeight))
this.location.set(screenX = 0.5f - this.location.screenWidth)
}
stage.updatePositions()
}
override fun renderUpdate() {
super.renderUpdate()
if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE)) {
(stage as GenericStage).onBackButtonClick()
}
}
override fun dispose() {
}
override fun tickUpdate() {
}
} | gpl-3.0 | 5d98f9402c4da2fe21cf3fd0f694f784 | 44.938931 | 204 | 0.609108 | 4.376 | false | false | false | false |
JetBrains/teamcity-dnx-plugin | plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/agent/CommandLine.kt | 1 | 719 | package jetbrains.buildServer.agent
import jetbrains.buildServer.agent.runner.StdOutText
data class CommandLine(
val baseCommandLine: CommandLine?,
val target: TargetType,
val executableFile: Path,
val workingDirectory: Path,
val arguments: List<CommandLineArgument> = emptyList(),
val environmentVariables: List<CommandLineEnvironmentVariable> = emptyList(),
val title: String = "",
val description: List<StdOutText> = emptyList())
val CommandLine.chain: Sequence<CommandLine> get() {
var cur: CommandLine? = this
return sequence {
while (cur != null) {
yield(cur!!)
cur = cur?.baseCommandLine
}
}
} | apache-2.0 | d2b32d7389cec5451551d021d43904a4 | 30.304348 | 85 | 0.652295 | 4.958621 | false | false | false | false |
udevbe/westford | compositor/src/main/kotlin/org/westford/compositor/drm/DrmEventBusFactory.kt | 3 | 1793 | /*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* 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 org.westford.compositor.drm
import org.freedesktop.jaccall.Pointer
import org.westford.nativ.libdrm.*
import javax.inject.Inject
class DrmEventBusFactory @Inject internal constructor(private val privateDrmEventBusFactory: PrivateDrmEventBusFactory) {
fun create(drmFd: Int): DrmEventBus {
val drmEventContextP = Pointer.malloc<DrmEventContext>(Struct_DrmEventContext.SIZE,
DrmEventContext::class.java)
val drmEventBus = this.privateDrmEventBusFactory.create(drmFd,
drmEventContextP.address)
val drmEventContext = drmEventContextP.get()
drmEventContext.version = Libdrm.DRM_EVENT_CONTEXT_VERSION
drmEventContext.page_flip_handler = Pointerpage_flip_handler.nref(drmEventBus::pageFlipHandler as page_flip_handler)
drmEventContext.vblank_handler = Pointervblank_handler.nref(drmEventBus::vblankHandler as vblank_handler)
return drmEventBus
}
}
| agpl-3.0 | 1060377cfb1d6adaa8809263a1a3ff8e | 43.825 | 124 | 0.710541 | 4.505025 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/checks/Patterns.kt | 1 | 1764 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.common.checks
/**
* Named pattern as a value class
* @param pattern
*/
data class Pattern(val pattern: String)
/**
* Named regex pattern
*/
object Patterns {
@JvmField val email = Pattern("""([\w\.\-\_]+)@([\w\.\-\_]+)""")
@JvmField val alpha = Pattern("""^[a-zA-Z]*$""")
@JvmField val alphaUpperCase = Pattern("""^[A-Z]*$""")
@JvmField val alphaLowerCase = Pattern("""^[a-z]*$""")
@JvmField val alphaNumeric = Pattern("""^[a-zA-Z0-9]*$""")
@JvmField val alphaNumericSpace = Pattern("""^[a-zA-Z0-9 ]*$""")
@JvmField val alphaNumericSpaceDash = Pattern("""^[a-zA-Z0-9 \-]*$""")
@JvmField val alphaNumericSpaceDashUnderscore = Pattern("""^[a-zA-Z0-9 \-_]*$""")
@JvmField val alphaNumericSpaceDashUnderscorePeriod = Pattern("""^[a-zA-Z0-9\. \-_]*$""")
@JvmField val numeric = Pattern("""^\-?[0-9]*\.?[0-9]*$""")
@JvmField val digits = Pattern("""^\-?[0-9]*$""")
@JvmField val socialSecurity = Pattern("""\d{3}[-]?\d{2}[-]?\d{4}""")
@JvmField val url = Pattern("""^^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_=]*)?$""")
@JvmField val zipCodeUS = Pattern("""^\d{5}$""")
@JvmField val zipCodeUSWithFour = Pattern("""\d{5}[-]\d{4}""")
@JvmField val zipCodeUSWithFourOptional = Pattern("""\d{5}([-]\d{4})?""")
@JvmField val phoneUS = Pattern("""\d{3}[-]?\d{3}[-]?\d{4}""")
}
| apache-2.0 | 07a8d06172412255f5e1c2f82feac006 | 40.023256 | 145 | 0.575397 | 3.0625 | false | false | false | false |
grover-ws-1/http4k | http4k-core/src/main/kotlin/org/http4k/filter/ServerFilters.kt | 1 | 5417 | package org.http4k.filter
import org.http4k.base64Decoded
import org.http4k.core.Credentials
import org.http4k.core.Filter
import org.http4k.core.HttpHandler
import org.http4k.core.Method
import org.http4k.core.Method.OPTIONS
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status
import org.http4k.core.Status.Companion.INTERNAL_SERVER_ERROR
import org.http4k.core.Status.Companion.OK
import org.http4k.core.Status.Companion.UNAUTHORIZED
import org.http4k.core.then
import org.http4k.core.with
import org.http4k.lens.Header
import org.http4k.lens.LensFailure
import java.io.PrintWriter
import java.io.StringWriter
data class CorsPolicy(val origins: List<String>,
val headers: List<String>,
val methods: List<Method>) {
companion object {
val UnsafeGlobalPermissive = CorsPolicy(listOf("*"), listOf("content-type"), Method.values().toList())
}
}
object ServerFilters {
object Cors {
private fun List<String>.joined() = this.joinToString(", ")
operator fun invoke(policy: CorsPolicy) = Filter { next ->
{
val response = if (it.method == OPTIONS) Response(OK) else next(it)
response.with(
Header.required("access-control-allow-origin") of policy.origins.joined(),
Header.required("access-control-allow-headers") of policy.headers.joined(),
Header.required("access-control-allow-methods") of policy.methods.map { it.name }.joined()
)
}
}
}
/**
* Adds Zipkin request tracing headers to the incoming request and outbound response. (traceid, spanid, parentspanid)
*/
object RequestTracing {
operator fun invoke(
startReportFn: (Request, ZipkinTraces) -> Unit = { _, _ -> },
endReportFn: (Request, Response, ZipkinTraces) -> Unit = { _, _, _ -> }): Filter = Filter { next ->
{
val fromRequest = ZipkinTraces(it)
startReportFn(it, fromRequest)
ZipkinTraces.THREAD_LOCAL.set(fromRequest.copy(parentSpanId = fromRequest.spanId, spanId = TraceId.new()))
try {
val response = ZipkinTraces(fromRequest, next(ZipkinTraces(fromRequest, it)))
endReportFn(it, response, fromRequest)
response
} finally {
ZipkinTraces.THREAD_LOCAL.remove()
}
}
}
}
/**
* Simple Basic Auth credential checking.
*/
object BasicAuth {
operator fun invoke(realm: String, authorize: (Credentials) -> Boolean): Filter = Filter { next ->
{
val credentials = it.basicAuthenticationCredentials()
if (credentials == null || !authorize(credentials)) {
Response(UNAUTHORIZED).header("WWW-Authenticate", "Basic Realm=\"$realm\"")
} else next(it)
}
}
operator fun invoke(realm: String, user: String, password: String): Filter = this(realm, Credentials(user, password))
operator fun invoke(realm: String, credentials: Credentials): Filter = this(realm, { it == credentials })
private fun Request.basicAuthenticationCredentials(): Credentials? = header("Authorization")?.replace("Basic ", "")?.toCredentials()
private fun String.toCredentials(): Credentials? = base64Decoded().split(":").let { Credentials(it.getOrElse(0, { "" }), it.getOrElse(1, { "" })) }
}
/**
* Converts Lens extraction failures into Http 400 (Bad Requests). This is required when using lenses to
* automatically respond to bad requests.
*/
object CatchLensFailure : Filter {
override fun invoke(next: HttpHandler): HttpHandler = {
try {
next(it)
} catch (lensFailure: LensFailure) {
Response(lensFailure.status)
}
}
}
/**
* Last gasp filter which catches all exceptions and returns a formatted Internal Server Error.
*/
object CatchAll {
operator fun invoke(errorStatus: Status = INTERNAL_SERVER_ERROR): Filter = Filter { next ->
{
try {
next(it)
} catch (e: Exception) {
val sw = StringWriter()
e.printStackTrace(PrintWriter(sw))
Response(errorStatus).body(sw.toString())
}
}
}
}
/**
* Copy headers from the incoming request to the outbound response.
*/
object CopyHeaders {
operator fun invoke(vararg headers: String): Filter = Filter { next ->
{ request ->
headers.fold(next(request),
{ memo, name -> request.header(name)?.let { memo.header(name, it) } ?: memo })
}
}
}
/**
* Basic GZip and Gunzip support of Request/Response. Does not currently support GZipping streams.
* Only Gunzips requests which contain "transfer-encoding" header containing 'gzip'
* Only Gzips responses when request contains "accept-encoding" header containing 'gzip'.
*/
object GZip {
operator fun invoke(): Filter = RequestFilters.GunZip().then(ResponseFilters.GZip())
}
} | apache-2.0 | 74b8ec6f365b6fe853504754e0433c9d | 36.109589 | 155 | 0.596825 | 4.563606 | false | false | false | false |
leafclick/intellij-community | plugins/stats-collector/src/com/intellij/completion/sorting/FeatureUtils.kt | 1 | 907 | /*
* Copyright 2000-2018 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.completion.sorting
object FeatureUtils {
const val UNDEFINED: String = "UNDEFINED"
const val INVALID_CACHE: String = "INVALID_CACHE"
const val NONE: String = "NONE"
const val ML_RANK: String = "ml_rank"
const val BEFORE_ORDER: String = "before_rerank_order"
}
| apache-2.0 | 995c29f0734e928140b865cb8e29a625 | 31.392857 | 75 | 0.725469 | 3.943478 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/DataClassOperatorsLowering.kt | 1 | 4282 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.lower
import org.jetbrains.kotlin.backend.common.FunctionLoweringPass
import org.jetbrains.kotlin.backend.common.lower.createIrBuilder
import org.jetbrains.kotlin.backend.common.lower.irBlock
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.expressions.IrCall
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
internal class DataClassOperatorsLowering(val context: Context): FunctionLoweringPass {
private val irBuiltins = context.irModule!!.irBuiltins
override fun lower(irFunction: IrFunction) {
irFunction.transformChildrenVoid(object: IrElementTransformerVoid() {
override fun visitCall(expression: IrCall): IrExpression {
expression.transformChildrenVoid(this)
if (expression.symbol != irBuiltins.dataClassArrayMemberToStringSymbol
&& expression.symbol != irBuiltins.dataClassArrayMemberHashCodeSymbol)
return expression
val argument = expression.getValueArgument(0)!!
val argumentType = argument.type.makeNotNullable()
val genericType =
if (argumentType.arguments.isEmpty())
argumentType
else
(argumentType.constructor.declarationDescriptor as ClassDescriptor).defaultType
val isToString = expression.symbol == irBuiltins.dataClassArrayMemberToStringSymbol
val newSymbol = if (isToString)
context.ir.symbols.arrayContentToString[genericType]!!
else
context.ir.symbols.arrayContentHashCode[genericType]!!
val startOffset = expression.startOffset
val endOffset = expression.endOffset
val irBuilder = context.createIrBuilder(irFunction.symbol, startOffset, endOffset)
return irBuilder.run {
val typeArguments =
if (argumentType.arguments.isEmpty())
emptyList<KotlinType>()
else argumentType.arguments.map { it.type }
if (!argument.type.isMarkedNullable) {
irCall(newSymbol, typeArguments).apply {
extensionReceiver = argument
}
} else {
val tmp = scope.createTemporaryVariable(argument)
val call = irCall(newSymbol, typeArguments).apply {
extensionReceiver = irGet(tmp.symbol)
}
irBlock(argument) {
+tmp
+irIfThenElse(call.type,
irEqeqeq(irGet(tmp.symbol), irNull()),
if (isToString)
irString("null")
else
irInt(0),
call)
}
}
}
}
})
}
} | apache-2.0 | 35e3b029133de0cdefdd6e41a55c0d9c | 45.554348 | 107 | 0.590612 | 5.778677 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/coroutines/controlFlow/throwInTryWithHandleResult.kt | 2 | 1192 | // WITH_RUNTIME
// WITH_COROUTINES
import helpers.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
class Controller {
var result = ""
suspend fun <T> suspendAndLog(value: T): T = suspendCoroutineOrReturn { c ->
result += "suspend($value);"
c.resume(value)
COROUTINE_SUSPENDED
}
}
fun builder(c: suspend Controller.() -> Unit): String {
val controller = Controller()
c.startCoroutine(controller, object : Continuation<Unit> {
override val context = EmptyCoroutineContext
override fun resume(data: Unit) {}
override fun resumeWithException(exception: Throwable) {
controller.result += "ignoreCaught(${exception.message});"
}
})
return controller.result
}
fun box(): String {
val value = builder {
try {
suspendAndLog("before")
throw RuntimeException("foo")
} catch (e: RuntimeException) {
result += "caught(${e.message});"
}
suspendAndLog("after")
}
if (value != "suspend(before);caught(foo);suspend(after);") {
return "fail: $value"
}
return "OK"
}
| apache-2.0 | f475ef9b52db97a951aae251cf809f5a | 24.361702 | 80 | 0.609899 | 4.549618 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/activities/SearchActivity.kt | 1 | 3492 | package com.kickstarter.ui.activities
import android.content.Intent
import android.os.Bundle
import android.util.Pair
import androidx.recyclerview.widget.LinearLayoutManager
import com.jakewharton.rxbinding.support.v7.widget.RecyclerViewScrollEvent
import com.jakewharton.rxbinding.support.v7.widget.RxRecyclerView
import com.kickstarter.R
import com.kickstarter.databinding.SearchLayoutBinding
import com.kickstarter.libs.BaseActivity
import com.kickstarter.libs.RecyclerViewPaginator
import com.kickstarter.libs.RefTag
import com.kickstarter.libs.qualifiers.RequiresActivityViewModel
import com.kickstarter.libs.utils.InputUtils
import com.kickstarter.libs.utils.extensions.getProjectIntent
import com.kickstarter.models.Project
import com.kickstarter.ui.IntentKey
import com.kickstarter.ui.adapters.SearchAdapter
import com.kickstarter.ui.viewholders.KSViewHolder
import com.kickstarter.viewmodels.SearchViewModel
import rx.android.schedulers.AndroidSchedulers
@RequiresActivityViewModel(SearchViewModel.ViewModel::class)
class SearchActivity : BaseActivity<SearchViewModel.ViewModel>(), SearchAdapter.Delegate {
private lateinit var adapter: SearchAdapter
private lateinit var paginator: RecyclerViewPaginator
lateinit var binding: SearchLayoutBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = SearchLayoutBinding.inflate(layoutInflater)
setContentView(binding.root)
adapter = SearchAdapter(this)
binding.searchRecyclerView.layoutManager = LinearLayoutManager(this)
binding.searchRecyclerView.adapter = adapter
paginator = RecyclerViewPaginator(binding.searchRecyclerView, { viewModel.inputs.nextPage() }, viewModel.outputs.isFetchingProjects())
RxRecyclerView.scrollEvents(binding.searchRecyclerView)
.compose(bindToLifecycle())
.filter { scrollEvent: RecyclerViewScrollEvent -> scrollEvent.dy() != 0 } // Skip scroll events when y is 0, usually indicates new data
.observeOn(AndroidSchedulers.mainThread())
.subscribe { InputUtils.hideKeyboard(this, currentFocus) }
viewModel.outputs.popularProjects()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { adapter.loadPopularProjects(it) }
viewModel.outputs.searchProjects()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { adapter.loadSearchProjects(it) }
viewModel.outputs.startProjectActivity()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { startProjectActivity(it) }
}
private fun startProjectActivity(projectAndRefTagAndIsFfEnabled: Pair<Project, RefTag>) {
val intent = Intent().getProjectIntent(this)
.putExtra(IntentKey.PROJECT, projectAndRefTagAndIsFfEnabled.first)
.putExtra(IntentKey.REF_TAG, projectAndRefTagAndIsFfEnabled.second)
startActivity(intent)
overridePendingTransition(R.anim.slide_in_right, R.anim.fade_out_slide_out_left)
}
override fun onDestroy() {
super.onDestroy()
paginator.stop()
binding.searchRecyclerView.adapter = null
}
override fun projectSearchResultClick(viewHolder: KSViewHolder?, project: Project?) {
project?.let { viewModel.inputs.projectClicked(it) }
}
}
| apache-2.0 | ef813b733b5665628d7f301b737088aa | 42.65 | 147 | 0.752577 | 5.105263 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/profile/microblog/comments/MicroblogCommentsPresenter.kt | 1 | 2922 | package io.github.feelfreelinux.wykopmobilny.ui.modules.profile.microblog.comments
import io.github.feelfreelinux.wykopmobilny.api.entries.EntriesApi
import io.github.feelfreelinux.wykopmobilny.api.profile.ProfileApi
import io.github.feelfreelinux.wykopmobilny.base.BasePresenter
import io.github.feelfreelinux.wykopmobilny.base.Schedulers
import io.github.feelfreelinux.wykopmobilny.models.dataclass.EntryComment
import io.github.feelfreelinux.wykopmobilny.ui.fragments.entrycomments.EntryCommentActionListener
import io.github.feelfreelinux.wykopmobilny.ui.fragments.entrycomments.EntryCommentInteractor
import io.github.feelfreelinux.wykopmobilny.utils.intoComposite
import io.reactivex.Single
class MicroblogCommentsPresenter(
val schedulers: Schedulers,
val profileApi: ProfileApi,
val entriesApi: EntriesApi,
private val entryCommentInteractor: EntryCommentInteractor
) : BasePresenter<MicroblogCommentsView>(), EntryCommentActionListener {
var page = 1
lateinit var username: String
fun loadData(shouldRefresh: Boolean) {
if (shouldRefresh) page = 1
profileApi.getEntriesComments(username, page)
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe(
{
if (it.isNotEmpty()) {
page++
view?.addItems(it, shouldRefresh)
} else view?.disableLoading()
},
{ view?.showErrorDialog(it) }
)
.intoComposite(compositeObservable)
}
override fun voteComment(comment: EntryComment) =
entryCommentInteractor.voteComment(comment).processEntryCommentSingle(comment)
override fun unvoteComment(comment: EntryComment) =
entryCommentInteractor.unvoteComment(comment).processEntryCommentSingle(comment)
override fun deleteComment(comment: EntryComment) =
entryCommentInteractor.deleteComment(comment).processEntryCommentSingle(comment)
override fun getVoters(comment: EntryComment) {
view?.openVotersMenu()
entriesApi.getEntryCommentVoters(comment.id)
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe({
view?.showVoters(it)
}, {
view?.showErrorDialog(it)
})
.intoComposite(compositeObservable)
}
private fun Single<EntryComment>.processEntryCommentSingle(comment: EntryComment) {
this
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe({ view?.updateComment(it) },
{
view?.showErrorDialog(it)
view?.updateComment(comment)
})
.intoComposite(compositeObservable)
}
} | mit | 4f966e4ee3bb172e7386f3151b1c9878 | 39.041096 | 97 | 0.680356 | 5.264865 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/base/plugin/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinJpsPluginSettings.kt | 1 | 11557 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.compiler.configuration
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.service
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.util.JDOMUtil
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.util.io.exists
import com.intellij.util.xmlb.XmlSerializer
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.config.JpsPluginSettings
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.config.SettingConstants
import org.jetbrains.kotlin.config.SettingConstants.KOTLIN_JPS_PLUGIN_SETTINGS_SECTION
import org.jetbrains.kotlin.config.toKotlinVersion
import org.jetbrains.kotlin.idea.base.plugin.KotlinBasePluginBundle
import java.nio.file.Path
import kotlin.io.path.bufferedReader
@State(name = KOTLIN_JPS_PLUGIN_SETTINGS_SECTION, storages = [(Storage(SettingConstants.KOTLIN_COMPILER_SETTINGS_FILE))])
class KotlinJpsPluginSettings(project: Project) : BaseKotlinCompilerSettings<JpsPluginSettings>(project) {
override fun createSettings() = JpsPluginSettings()
fun setVersion(jpsVersion: String) {
if (jpsVersion == settings.version) return
update { version = jpsVersion }
}
fun dropExplicitVersion(): Unit = setVersion("")
companion object {
// Use bundled by default because this will work even without internet connection
@JvmStatic
val rawBundledVersion: String get() = bundledVersion.rawVersion
// Use stable 1.6.21 for outdated compiler versions in order to work with old LV settings
@JvmStatic
val fallbackVersionForOutdatedCompiler: String get() = "1.6.21"
@JvmStatic
val bundledVersion: IdeKotlinVersion get() = KotlinPluginLayout.standaloneCompilerVersion
@JvmStatic
val jpsMinimumSupportedVersion: KotlinVersion = IdeKotlinVersion.get("1.6.0").kotlinVersion
@JvmStatic
val jpsMaximumSupportedVersion: KotlinVersion = LanguageVersion.values().last().toKotlinVersion()
fun validateSettings(project: Project) {
val jpsPluginSettings = project.service<KotlinJpsPluginSettings>()
if (jpsPluginSettings.settings.version.isEmpty() && bundledVersion.buildNumber == null) {
// Encourage user to specify desired Kotlin compiler version in project settings for sake of reproducible builds
// it's important to trigger `.idea/kotlinc.xml` file creation
jpsPluginSettings.setVersion(rawBundledVersion)
}
}
fun jpsVersion(project: Project): String = getInstance(project).settings.versionWithFallback
/**
* @see readFromKotlincXmlOrIpr
*/
@JvmStatic
fun getInstance(project: Project): KotlinJpsPluginSettings = project.service()
/**
* @param jpsVersion version to parse
* @param fromFile true if [jpsVersion] come from kotlin.xml
* @return error message if [jpsVersion] is not valid
*/
@Nls
fun checkJpsVersion(jpsVersion: String, fromFile: Boolean = false): UnsupportedJpsVersionError? {
val parsedKotlinVersion = IdeKotlinVersion.opt(jpsVersion)?.kotlinVersion
if (parsedKotlinVersion == null) {
return ParsingError(
if (fromFile) {
KotlinBasePluginBundle.message(
"failed.to.parse.kotlin.version.0.from.1",
jpsVersion,
SettingConstants.KOTLIN_COMPILER_SETTINGS_FILE,
)
} else {
KotlinBasePluginBundle.message("failed.to.parse.kotlin.version.0", jpsVersion)
}
)
}
if (parsedKotlinVersion < jpsMinimumSupportedVersion) {
return OutdatedCompilerVersion(KotlinBasePluginBundle.message(
"kotlin.jps.compiler.minimum.supported.version.not.satisfied",
jpsMinimumSupportedVersion,
jpsVersion,
))
}
if (parsedKotlinVersion > jpsMaximumSupportedVersion) {
return NewCompilerVersion(KotlinBasePluginBundle.message(
"kotlin.jps.compiler.maximum.supported.version.not.satisfied",
jpsMaximumSupportedVersion,
jpsVersion,
))
}
return null
}
/**
* Replacement for [getInstance] for cases when it's not possible to use [getInstance] (e.g. project isn't yet initialized).
*
* Please, prefer [getInstance] if possible.
*/
fun readFromKotlincXmlOrIpr(path: Path): JpsPluginSettings? {
return path.takeIf { it.fileIsNotEmpty() }
?.let { JDOMUtil.load(path) }
?.children
?.singleOrNull { it.getAttributeValue("name") == KotlinJpsPluginSettings::class.java.simpleName }
?.let { xmlElement ->
JpsPluginSettings().apply {
XmlSerializer.deserializeInto(this, xmlElement)
}
}
}
fun supportedJpsVersion(project: Project, onUnsupportedVersion: (String) -> Unit): String? {
val version = jpsVersion(project)
return when (val error = checkJpsVersion(version, fromFile = true)) {
is OutdatedCompilerVersion -> fallbackVersionForOutdatedCompiler
is NewCompilerVersion, is ParsingError -> {
onUnsupportedVersion(error.message)
null
}
null -> version
}
}
/**
* @param isDelegatedToExtBuild `true` if compiled with Gradle/Maven. `false` if compiled with JPS
*/
fun importKotlinJpsVersionFromExternalBuildSystem(project: Project, rawVersion: String, isDelegatedToExtBuild: Boolean) {
val instance = getInstance(project)
if (rawVersion == rawBundledVersion) {
instance.setVersion(rawVersion)
return
}
val error = checkJpsVersion(rawVersion)
val version = when (error) {
is OutdatedCompilerVersion -> fallbackVersionForOutdatedCompiler
is NewCompilerVersion, is ParsingError -> rawBundledVersion
null -> rawVersion
}
if (error != null && !isDelegatedToExtBuild) {
showNotificationUnsupportedJpsPluginVersion(
project,
KotlinBasePluginBundle.message("notification.title.unsupported.kotlin.jps.plugin.version"),
KotlinBasePluginBundle.message(
"notification.content.bundled.version.0.will.be.used.reason.1",
version,
error.message
),
)
}
when (error) {
is ParsingError, is NewCompilerVersion -> {
instance.dropExplicitVersion()
return
}
null, is OutdatedCompilerVersion -> Unit
}
if (!shouldImportKotlinJpsPluginVersionFromExternalBuildSystem(IdeKotlinVersion.get(version))) {
instance.dropExplicitVersion()
return
}
if (!isDelegatedToExtBuild) {
downloadKotlinJpsInBackground(project, version)
}
runInEdt {
runWriteAction {
instance.setVersion(version)
}
}
}
private fun downloadKotlinJpsInBackground(project: Project, version: String) {
ProgressManager.getInstance().run(
object : Task.Backgroundable(project, KotlinBasePluginBundle.getMessage("progress.text.downloading.kotlinc.dist"), true) {
override fun isHeadless(): Boolean {
return false
}
override fun run(indicator: ProgressIndicator) {
KotlinArtifactsDownloader.lazyDownloadMissingJpsPluginDependencies(
project,
version,
indicator,
onError = {
showNotificationUnsupportedJpsPluginVersion(
project,
KotlinBasePluginBundle.message("kotlin.dist.downloading.failed"),
it,
)
}
)
}
}
)
}
internal fun shouldImportKotlinJpsPluginVersionFromExternalBuildSystem(version: IdeKotlinVersion): Boolean {
check(jpsMinimumSupportedVersion < IdeKotlinVersion.get("1.7.10").kotlinVersion) {
"${::shouldImportKotlinJpsPluginVersionFromExternalBuildSystem.name} makes sense when minimum supported version is lower " +
"than 1.7.20. If minimum supported version is already 1.7.20 then you can drop this function."
}
require(version.kotlinVersion >= jpsMinimumSupportedVersion) {
"${version.kotlinVersion} is lower than $jpsMinimumSupportedVersion"
}
val kt160 = IdeKotlinVersion.get("1.6.0")
val kt170 = IdeKotlinVersion.get("1.7.0")
// Until 1.6.0 none of unbundled Kotlin JPS artifacts was published to the Maven Central.
// In range [1.6.0, 1.7.0] unbundled Kotlin JPS artifacts were published only for release Kotlin versions.
return version > kt170 || version >= kt160 && version.isRelease && version.buildNumber == null
}
}
}
sealed class UnsupportedJpsVersionError(val message: String)
class ParsingError(message: String) : UnsupportedJpsVersionError(message)
class OutdatedCompilerVersion(message: String) : UnsupportedJpsVersionError(message)
class NewCompilerVersion(message: String) : UnsupportedJpsVersionError(message)
@get:NlsSafe
val JpsPluginSettings.versionWithFallback: String get() = version.ifEmpty { KotlinJpsPluginSettings.rawBundledVersion }
private fun showNotificationUnsupportedJpsPluginVersion(
project: Project,
@NlsContexts.NotificationTitle title: String,
@NlsContexts.NotificationContent content: String,
) {
NotificationGroupManager.getInstance()
.getNotificationGroup("Kotlin JPS plugin")
.createNotification(title, content, NotificationType.WARNING)
.setImportant(true)
.notify(project)
}
fun Path.fileIsNotEmpty() = exists() && bufferedReader().use { it.readLine() != null }
| apache-2.0 | 0419a5f5f62a5ca9b7d60f3f89a46486 | 42.942966 | 140 | 0.621095 | 5.529665 | false | false | false | false |
MoonlightOwl/Yui | src/main/kotlin/totoro/yui/util/api/CryptoCompare.kt | 1 | 2797 | package totoro.yui.util.api
import com.beust.klaxon.JsonObject
import com.beust.klaxon.Parser
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.result.Result
import totoro.yui.util.api.data.Currency
import java.time.Duration
object CryptoCompare {
fun get(from: String, to: String?, duration: Duration?, success: (Currency) -> Unit, failure: () -> Unit) {
"https://min-api.cryptocompare.com/data/price?fsym=$from&tsyms=USD${ if (to != null) "," + to else "" }"
.httpGet().responseString { _, _, result ->
when (result) {
is Result.Failure -> failure()
is Result.Success -> {
val json = Parser().parse(StringBuilder(result.value)) as JsonObject
val currency = to ?: "USD"
val price = json.double(currency)
if (price == null) failure()
else {
if (duration != null) {
val (param, amount) = when {
duration.toDays() > 0 -> Pair("day", duration.toDays())
duration.toHours() > 0 -> Pair("hour", duration.toHours())
else -> Pair("minute", duration.toMinutes())
}
"https://min-api.cryptocompare.com/data/histo$param?fsym=$from&tsym=$currency&limit=$amount"
.httpGet().responseString { _, _, histoResult ->
when (histoResult) {
is Result.Failure -> failure()
is Result.Success -> {
val histoJson = Parser().parse(StringBuilder(histoResult.value)) as JsonObject
val dataArray = histoJson.array<JsonObject>("Data")
if (dataArray != null && dataArray.size > 0) {
val item = dataArray.first()
val openPrice = item.double("open")
if (openPrice != null) {
val percentage = (price - openPrice) / openPrice * 100.0
success(Currency(currency, price, delta = percentage))
} else failure()
} else failure()
}
}
}
} else success(Currency(currency, price))
}
}
}
}
}
}
| mit | a5f0fa507393fa036c69b694305f619e | 52.788462 | 120 | 0.421523 | 5.462891 | false | false | false | false |
androidx/androidx | room/room-runtime/src/main/java/androidx/room/MultiInstanceInvalidationClient.kt | 3 | 4546 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room
import android.content.Intent
import android.content.ServiceConnection
import android.content.ComponentName
import android.content.Context
import android.os.IBinder
import android.os.RemoteException
import android.util.Log
import androidx.room.Room.LOG_TAG
import java.util.concurrent.Executor
import java.util.concurrent.atomic.AtomicBoolean
/**
* Handles all the communication from [RoomDatabase] and [InvalidationTracker] to
* [MultiInstanceInvalidationService].
*
* @param context The Context to be used for binding
* [IMultiInstanceInvalidationService].
* @param name The name of the database file.
* @param serviceIntent The [Intent] used for binding
* [IMultiInstanceInvalidationService].
* @param invalidationTracker The [InvalidationTracker]
* @param executor The background executor.
*/
internal class MultiInstanceInvalidationClient(
context: Context,
val name: String,
serviceIntent: Intent,
val invalidationTracker: InvalidationTracker,
val executor: Executor
) {
private val appContext = context.applicationContext
/**
* The client ID assigned by [MultiInstanceInvalidationService].
*/
var clientId = 0
lateinit var observer: InvalidationTracker.Observer
var service: IMultiInstanceInvalidationService? = null
val callback: IMultiInstanceInvalidationCallback =
object : IMultiInstanceInvalidationCallback.Stub() {
override fun onInvalidation(tables: Array<out String>) {
executor.execute { invalidationTracker.notifyObserversByTableNames(*tables) }
}
}
val stopped = AtomicBoolean(false)
val serviceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
[email protected] =
IMultiInstanceInvalidationService.Stub.asInterface(service)
executor.execute(setUpRunnable)
}
override fun onServiceDisconnected(name: ComponentName) {
executor.execute(removeObserverRunnable)
service = null
}
}
val setUpRunnable = Runnable {
try {
service?.let {
clientId = it.registerCallback(callback, name)
invalidationTracker.addObserver(observer)
}
} catch (e: RemoteException) {
Log.w(LOG_TAG, "Cannot register multi-instance invalidation callback", e)
}
}
val removeObserverRunnable = Runnable { invalidationTracker.removeObserver(observer) }
init {
// Use all tables names for observer.
val tableNames: Set<String> = invalidationTracker.tableIdLookup.keys
observer = object : InvalidationTracker.Observer(tableNames.toTypedArray()) {
override fun onInvalidated(tables: Set<String>) {
if (stopped.get()) {
return
}
try {
service?.broadcastInvalidation(clientId, tables.toTypedArray())
} catch (e: RemoteException) {
Log.w(LOG_TAG, "Cannot broadcast invalidation", e)
}
}
override val isRemote: Boolean
get() = true
}
appContext.bindService(
serviceIntent,
serviceConnection,
Context.BIND_AUTO_CREATE
)
}
fun stop() {
if (stopped.compareAndSet(false, true)) {
invalidationTracker.removeObserver(observer)
try {
service?.unregisterCallback(callback, clientId)
} catch (e: RemoteException) {
Log.w(LOG_TAG, "Cannot unregister multi-instance invalidation callback", e)
}
appContext.unbindService(serviceConnection)
}
}
} | apache-2.0 | d1511af4379dcd7c63936ea043c3603a | 34.248062 | 93 | 0.659041 | 5.125141 | false | false | false | false |
androidx/androidx | compose/foundation/foundation-layout/samples/src/main/java/androidx/compose/foundation/layout/samples/ColumnSample.kt | 3 | 5883 | /*
* 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.foundation.layout.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.VerticalAlignmentLine
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import kotlin.math.max
import kotlin.math.min
@Sampled
@Composable
fun SimpleColumn() {
Column {
// The child with no weight will have the specified size.
Box(Modifier.size(40.dp, 80.dp).background(Color.Magenta))
// Has weight, the child will occupy half of the remaining height.
Box(Modifier.width(40.dp).weight(1f).background(Color.Yellow))
// Has weight and does not fill, the child will occupy at most half of the remaining height.
// Therefore it will occupy 80.dp (its preferred height) if the assigned height is larger.
Box(
Modifier.size(40.dp, 80.dp)
.weight(1f, fill = false)
.background(Color.Green)
)
}
}
@Sampled
@Composable
fun SimpleAlignInColumn() {
Column(Modifier.fillMaxWidth()) {
// The child with no align modifier is positioned by default so that its start edge
// aligned with the start edge of the horizontal axis.
Box(Modifier.size(80.dp, 40.dp).background(Color.Magenta))
// Alignment.Start, the child will be positioned so that its start edge is aligned with
// the start edge of the horizontal axis.
Box(
Modifier.size(80.dp, 40.dp)
.align(Alignment.Start)
.background(Color.Red)
)
// Alignment.Center, the child will be positioned so that its center is in the middle of
// the horizontal axis.
Box(
Modifier.size(80.dp, 40.dp)
.align(Alignment.CenterHorizontally)
.background(Color.Yellow)
)
// Alignment.End, the child will be positioned so that its end edge aligned to the end of
// the horizontal axis.
Box(
Modifier.size(80.dp, 40.dp)
.align(Alignment.End)
.background(Color.Green)
)
}
}
@Sampled
@Composable
fun SimpleRelativeToSiblings() {
Column {
// Center of the first rectangle is aligned to the right edge of the second rectangle and
// left edge of the third one.
Box(
Modifier.size(80.dp, 40.dp)
.alignBy { it.measuredWidth / 2 }
.background(Color.Blue)
)
Box(
Modifier.size(80.dp, 40.dp)
.alignBy { it.measuredWidth }
.background(Color.Magenta)
)
Box(
Modifier.size(80.dp, 40.dp)
.alignBy { 0 }
.background(Color.Red)
)
}
}
@Sampled
@Composable
fun SimpleRelativeToSiblingsInColumn() {
// Alignment lines provided by the RectangleWithStartEnd layout. We need to create these
// local alignment lines because Compose is currently not providing any top-level out of
// the box vertical alignment lines. Two horizontal alignment lines are provided though:
// FirstBaseline and LastBaseline, but these can only be used to align vertically children
// of Row because the baselines are horizontal. Therefore, we create these vertical alignment
// lines, that refer to the start and end of the RectangleWithStartEnd layout which knows
// how to provide them. Then Column will know how to align horizontally children such
// that the positions of the alignment lines coincide, as asked by alignBy.
val start = VerticalAlignmentLine(::min)
val end = VerticalAlignmentLine(::min)
@Composable
fun RectangleWithStartEnd(modifier: Modifier = Modifier, color: Color, width: Dp, height: Dp) {
Layout(
content = { },
modifier = modifier.background(color = color)
) { _, constraints ->
val widthPx = max(width.roundToPx(), constraints.minWidth)
val heightPx = max(height.roundToPx(), constraints.minHeight)
layout(widthPx, heightPx, mapOf(start to 0, end to widthPx)) {}
}
}
Column {
// Center of the first rectangle is aligned to the right edge of the second rectangle and
// left edge of the third one.
Box(
Modifier.size(80.dp, 40.dp)
.alignBy { it.measuredWidth / 2 }
.background(Color.Blue)
)
RectangleWithStartEnd(
Modifier.alignBy(end),
color = Color.Magenta,
width = 80.dp,
height = 40.dp
)
RectangleWithStartEnd(
Modifier.alignBy(start),
color = Color.Red,
width = 80.dp,
height = 40.dp
)
}
} | apache-2.0 | 0c79d3ea9d5fcecf217a88b805306d35 | 36.240506 | 100 | 0.648989 | 4.44 | false | false | false | false |
GunoH/intellij-community | plugins/gradle/java/src/service/completion/GradleCompletionCustomizer.kt | 4 | 1919 | // 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.plugins.gradle.service.completion
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.completion.CompletionSorter
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.gradle.config.GradleFileType
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.jetbrains.plugins.groovy.GroovyFileType
import org.jetbrains.plugins.groovy.lang.completion.api.GroovyCompletionConsumer
import org.jetbrains.plugins.groovy.lang.completion.api.GroovyCompletionCustomizer
import org.jetbrains.plugins.groovy.lang.completion.impl.AccumulatingGroovyCompletionConsumer
class GradleCompletionCustomizer : GroovyCompletionCustomizer {
override fun customizeCompletionConsumer(completionParameters: CompletionParameters,
resultSet: CompletionResultSet): CompletionResultSet {
if (completionParameters.originalFile.fileType == GradleFileType || completionParameters.originalFile.fileType == GroovyFileType.GROOVY_FILE_TYPE && completionParameters.originalFile.virtualFile.extension == GradleConstants.EXTENSION) {
val sorter = CompletionSorter.defaultSorter(completionParameters, resultSet.prefixMatcher)
return resultSet.withRelevanceSorter(sorter.weighBefore("priority", GradleLookupWeigher()))
} else {
return resultSet
}
}
override fun generateCompletionConsumer(element: PsiElement, resultSet: CompletionResultSet): GroovyCompletionConsumer? {
val file = element.containingFile
if (file.name.endsWith(GradleConstants.EXTENSION)) {
return GradleCompletionConsumer(element, AccumulatingGroovyCompletionConsumer(resultSet))
}
else {
return null
}
}
} | apache-2.0 | cdc568bb37ff206f1b6b4d240822b79f | 52.333333 | 240 | 0.807191 | 5.301105 | false | false | false | false |
jwren/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/ModuleModelProxyImpl.kt | 2 | 6718 | // 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.idea.maven.importing
import com.intellij.openapi.module.ModifiableModuleModel
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleWithNameAlreadyExists
import com.intellij.openapi.module.impl.ModulePath
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ExternalProjectSystemRegistry
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.PathUtil
import com.intellij.util.containers.map2Array
import com.intellij.workspaceModel.ide.impl.JpsEntitySourceFactory
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleByEntity
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleEntity
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.getInstance
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.storage.VersionedEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.*
import com.intellij.workspaceModel.storage.impl.VersionedEntityStorageOnBuilder
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
interface ModuleModelProxy {
fun disposeModule(module: Module)
fun findModuleByName(name: String): Module?
fun newModule(path: String, moduleTypeId: String): Module
fun setModuleGroupPath(module: Module, groupPath: Array<String>?)
@Throws(ModuleWithNameAlreadyExists::class)
fun renameModule(module: Module, moduleName: String)
val modules: Array<Module>
}
class ModuleModelProxyWrapper(val delegate: ModifiableModuleModel) : ModuleModelProxy {
override fun disposeModule(module: Module) {
delegate.disposeModule(module)
}
override fun findModuleByName(name: String): Module? {
return delegate.findModuleByName(name)
}
override fun newModule(path: String, moduleTypeId: String): Module {
return delegate.newModule(path, moduleTypeId)
}
override fun setModuleGroupPath(module: Module, groupPath: Array<String>?) {
delegate.setModuleGroupPath(module, groupPath)
}
override fun renameModule(module: Module, moduleName: String) {
delegate.renameModule(module, moduleName)
}
override val modules: Array<Module>
get() = delegate.modules
}
class ModuleModelProxyImpl(private val diff: WorkspaceEntityStorageBuilder,
private val project: Project) : ModuleModelProxy {
private val virtualFileManager: VirtualFileUrlManager = project.getService(VirtualFileUrlManager::class.java)
private val versionedStorage: VersionedEntityStorage
override fun disposeModule(module: Module) {
if (module.project.isDisposed) {
//if the project is being disposed now, removing module won't work because WorkspaceModelImpl won't fire events and the module won't be disposed
//it looks like this may happen in tests only so it's ok to skip removal of the module since the project will be disposed anyway
return
}
if (module !is ModuleBridge) return
val moduleEntity: ModuleEntity = diff.findModuleEntity(module) ?: return //MavenProjectImporterImpl.LOG.error("Could not find module entity to remove by $module");
moduleEntity.dependencies
.asSequence()
.filterIsInstance<ModuleDependencyItem.Exportable.LibraryDependency>()
.filter { (it.library.tableId as? LibraryTableId.ModuleLibraryTableId)?.moduleId == module.moduleEntityId }
.mapNotNull { it.library.resolve(diff) }
.forEach {
diff.removeEntity(it)
}
diff.removeEntity(moduleEntity)
}
override val modules: Array<Module>
get() = diff.entities(ModuleEntity::class.java)
.map { diff.findModuleByEntity(it) }
.filterNotNull()
.toList()
.map2Array { it }
override fun findModuleByName(name: String): Module? {
val entity = diff.resolve(ModuleId(name)) ?: return null
return diff.findModuleByEntity(entity)
}
override fun newModule(path: String, moduleTypeId: String): Module {
val systemIndependentPath = FileUtil.toSystemIndependentName(path)
val modulePath = ModulePath(systemIndependentPath, null)
val name = modulePath.moduleName
val source = JpsEntitySourceFactory.createEntitySourceForModule(project,
virtualFileManager.fromPath(
PathUtil.getParentPath(
systemIndependentPath)), ExternalProjectSystemRegistry.getInstance().getSourceById(
ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID))
val moduleEntity = diff.addEntity(ModifiableModuleEntity::class.java, source) {
this.name = name
type = moduleTypeId
dependencies = listOf(ModuleDependencyItem.ModuleSourceDependency)
}
val moduleManager = getInstance(project)
val module = moduleManager.createModuleInstance(moduleEntity, versionedStorage, diff, true, null)
diff.getMutableExternalMapping<Module>("intellij.modules.bridge").addMapping(moduleEntity, module)
return module
}
override fun setModuleGroupPath(module: Module, groupPath: Array<String>?) {
if (module !is ModuleBridge) return
val moduleEntity = diff.findModuleEntity(module) ?: error("Could not resolve module entity for $module")
val moduleGroupEntity = moduleEntity.groupPath
val groupPathList = groupPath?.toList()
if (moduleGroupEntity?.path != groupPathList) {
when {
moduleGroupEntity == null && groupPathList != null -> diff.addModuleGroupPathEntity(
module = moduleEntity,
path = groupPathList,
source = moduleEntity.entitySource
)
moduleGroupEntity == null && groupPathList == null -> Unit
moduleGroupEntity != null && groupPathList == null -> diff.removeEntity(moduleGroupEntity)
moduleGroupEntity != null && groupPathList != null -> diff.modifyEntity(ModifiableModuleGroupPathEntity::class.java,
moduleGroupEntity) {
path = groupPathList
}
else -> error("Should not be reached")
}
}
}
override fun renameModule(module: Module, moduleName: String) {
TODO("Not yet implemented")
}
init {
versionedStorage = VersionedEntityStorageOnBuilder(diff)
}
} | apache-2.0 | 0c13a04f6c7d2d8cf378aba0c8078ab8 | 42.915033 | 167 | 0.73117 | 5.19969 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/checker/QualifiedExpressions.kt | 4 | 651 | package qualified_expressions
fun test(s: IntRange?) {
val <warning descr="[UNUSED_VARIABLE] Variable 'a' is never used">a</warning>: Int = <error descr="[TYPE_MISMATCH] Type mismatch: inferred type is Int? but Int was expected">s?.start</error>
val b: Int? = s?.start
val <warning>c</warning>: Int = s?.start ?: -11
val <warning>d</warning>: Int = <error>s?.start ?: "empty"</error>
val e: String = <error>s?.start ?: "empty"</error>
val <warning>f</warning>: Int = s?.endInclusive ?: b ?: 1
val <warning>g</warning>: Boolean? = e.startsWith("s")//?.length
}
fun String.startsWith(<warning>s</warning>: String): Boolean = true
| apache-2.0 | 46fac127a865ca5e0e91143571169802 | 49.076923 | 193 | 0.655914 | 3.390625 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/hierarchy/calls/callees/kotlinFunction/main0.kt | 13 | 482 | class KA {
val name = "A"
fun foo(s: String): String = "A: $s"
}
fun packageFun(s: String): String = s
val packageVal = ""
class KClient() {
fun <caret>bar() {
fun localFun(s: String): String = packageFun(s)
val localVal = localFun("")
KA().foo(KA().name)
JA().foo(JA().name)
localFun(packageVal)
run {
KA().foo(KA().name)
JA().foo(JA().name)
packageFun(localVal)
}
}
} | apache-2.0 | 4471e3ea93c231ca82ea9dd037cbfe59 | 18.32 | 55 | 0.489627 | 3.256757 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/expandBooleanExpression/parenthesized.kt | 13 | 76 | fun test(i: Int): Boolean {
return (i == 1 || i == 2<caret> || i == 3)
} | apache-2.0 | c5d29ee4a3387812bbfd86d3764c21ed | 24.666667 | 46 | 0.460526 | 2.62069 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ExperimentalFixesFactory.kt | 1 | 7327 | // 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.quickfix
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.module.Module
import com.intellij.psi.SmartPsiElementPointer
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget
import org.jetbrains.kotlin.descriptors.resolveClassByFqName
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors.*
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.toDescriptor
import org.jetbrains.kotlin.idea.util.findAnnotation
import org.jetbrains.kotlin.idea.util.projectStructure.module
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypesAndPredicate
import org.jetbrains.kotlin.resolve.AnnotationChecker
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.checkers.ExperimentalUsageChecker
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
object ExperimentalFixesFactory : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val element = diagnostic.psiElement
val containingDeclaration: KtDeclaration = element.getParentOfTypesAndPredicate(
true,
KtDeclarationWithBody::class.java,
KtClassOrObject::class.java,
KtProperty::class.java,
KtTypeAlias::class.java
) {
!KtPsiUtil.isLocal(it)
} ?: return emptyList()
val annotationFqName = when (diagnostic.factory) {
EXPERIMENTAL_API_USAGE -> EXPERIMENTAL_API_USAGE.cast(diagnostic).a
EXPERIMENTAL_API_USAGE_ERROR -> EXPERIMENTAL_API_USAGE_ERROR.cast(diagnostic).a
EXPERIMENTAL_OVERRIDE -> EXPERIMENTAL_OVERRIDE.cast(diagnostic).a
EXPERIMENTAL_OVERRIDE_ERROR -> EXPERIMENTAL_OVERRIDE_ERROR.cast(diagnostic).a
else -> null
} ?: return emptyList()
val moduleDescriptor = containingDeclaration.resolveToDescriptorIfAny()?.module ?: return emptyList()
val annotationClassDescriptor = moduleDescriptor.resolveClassByFqName(
annotationFqName, NoLookupLocation.FROM_IDE
) ?: return emptyList()
val applicableTargets = AnnotationChecker.applicableTargetSet(annotationClassDescriptor) ?: KotlinTarget.DEFAULT_TARGET_SET
val context = when (element) {
is KtElement -> element.analyze()
else -> containingDeclaration.analyze()
}
fun isApplicableTo(declaration: KtDeclaration, applicableTargets: Set<KotlinTarget>): Boolean {
val actualTargetList = AnnotationChecker.getDeclarationSiteActualTargetList(
declaration, declaration.toDescriptor() as? ClassDescriptor, context
)
return actualTargetList.any { it in applicableTargets }
}
val result = mutableListOf<IntentionAction>()
run {
val kind = AddAnnotationFix.Kind.Declaration(containingDeclaration.name)
if (isApplicableTo(containingDeclaration, applicableTargets)) {
result.add(AddAnnotationFix(containingDeclaration, annotationFqName, kind))
}
result.add(
HighPriorityAddAnnotationFix(
containingDeclaration, moduleDescriptor.OPT_IN_FQ_NAME, kind, annotationFqName,
containingDeclaration.findAnnotation(moduleDescriptor.OPT_IN_FQ_NAME)?.createSmartPointer()
)
)
}
if (containingDeclaration is KtCallableDeclaration) {
val containingClassOrObject = containingDeclaration.containingClassOrObject
if (containingClassOrObject != null) {
val kind = AddAnnotationFix.Kind.ContainingClass(containingClassOrObject.name)
if (isApplicableTo(containingClassOrObject, applicableTargets)) {
result.add(AddAnnotationFix(containingClassOrObject, annotationFqName, kind))
} else {
result.add(
HighPriorityAddAnnotationFix(
containingClassOrObject, moduleDescriptor.OPT_IN_FQ_NAME, kind, annotationFqName,
containingDeclaration.findAnnotation(moduleDescriptor.OPT_IN_FQ_NAME)?.createSmartPointer()
)
)
}
}
}
val containingFile = containingDeclaration.containingKtFile
val module = containingFile.module
if (module != null) {
result.add(
LowPriorityMakeModuleExperimentalFix(containingFile, module, annotationFqName)
)
}
// Add the file-level annotation `@file:OptIn(...)` fix
result.add(
AddFileAnnotationFix(
containingFile,
moduleDescriptor.OPT_IN_FQ_NAME,
annotationFqName,
findFileAnnotation(containingFile, moduleDescriptor.OPT_IN_FQ_NAME)?.createSmartPointer()
)
)
return result
}
private val ModuleDescriptor.OPT_IN_FQ_NAME: FqName
get() = ExperimentalUsageChecker.OPT_IN_FQ_NAME.takeIf { fqNameIsExisting(it) }
?: ExperimentalUsageChecker.OLD_USE_EXPERIMENTAL_FQ_NAME
// Find the existing file-level annotation of the specified class if it exists
private fun findFileAnnotation(file: KtFile, annotationFqName: FqName): KtAnnotationEntry? {
val context = file.analyze(BodyResolveMode.PARTIAL)
return file.fileAnnotationList?.annotationEntries?.firstOrNull { entry ->
context.get(BindingContext.ANNOTATION, entry)?.fqName == annotationFqName
}
}
fun ModuleDescriptor.fqNameIsExisting(fqName: FqName): Boolean = resolveClassByFqName(fqName, NoLookupLocation.FROM_IDE) != null
private class HighPriorityAddAnnotationFix(
element: KtDeclaration,
annotationFqName: FqName,
kind: Kind = Kind.Self,
argumentClassFqName: FqName? = null,
existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null
) : AddAnnotationFix(element, annotationFqName, kind, argumentClassFqName, existingAnnotationEntry), HighPriorityAction
private class LowPriorityMakeModuleExperimentalFix(
file: KtFile,
module: Module,
annotationFqName: FqName
) : MakeModuleExperimentalFix(file, module, annotationFqName), LowPriorityAction
}
| apache-2.0 | 15d361a2e8d24ce9b9a0357e5dd74307 | 48.506757 | 158 | 0.703562 | 5.584604 | false | false | false | false |
TachiWeb/TachiWeb-Server | TachiServer/src/main/java/xyz/nulldev/ts/api/v2/java/impl/extensions/ExtensionsControllerImpl.kt | 1 | 2123 | package xyz.nulldev.ts.api.v2.java.impl.extensions
import com.github.salomonbrys.kodein.Kodein
import com.github.salomonbrys.kodein.conf.global
import com.github.salomonbrys.kodein.instance
import com.github.salomonbrys.kodein.lazy
import eu.kanade.tachiyomi.extension.ExtensionManager
import eu.kanade.tachiyomi.extension.model.Extension
import xyz.nulldev.androidcompat.pm.PackageController
import xyz.nulldev.ts.api.v2.java.model.extensions.ExtensionsController
import xyz.nulldev.ts.ext.kInstance
import xyz.nulldev.ts.ext.kInstanceLazy
import java.io.File
class ExtensionsControllerImpl : ExtensionsController {
private val controller by kInstanceLazy<PackageController>()
override fun get(vararg packageNames: String)
= ExtensionCollectionImpl(packageNames.toList()) // TODO Check these extensions exist
override fun getAll()
= ExtensionCollectionImpl(getAllExtensions().map { it.pkgName })
override fun trust(hash: String) {
manager.trustSignature(hash)
}
override fun reloadAvailable() {
manager.findAvailableExtensions()
manager.getAvailableExtensionsObservable().take(2).toBlocking().subscribe()
}
override fun reloadLocal() {
manager.init(kInstance())
}
override fun installExternal(apk: File) {
controller.installPackage(apk, true)
reloadLocal()
}
companion object {
private val manager by Kodein.global.lazy.instance<ExtensionManager>()
internal fun getAllExtensions(): List<Extension> {
var localExtensions = manager.installedExtensions +
manager.untrustedExtensions
// Get available extensions excluding ones that have already been installed
localExtensions += manager.availableExtensions.filter { avail ->
localExtensions.none { it.pkgName == avail.pkgName }
}
return localExtensions
}
init {
// Forcibly fill this initially to allow the reloadAvailable endpoint to function
manager.findAvailableExtensions()
}
}
} | apache-2.0 | 703fdb1b0d21ece5699bd7325763a809 | 33.258065 | 97 | 0.710316 | 4.903002 | false | false | false | false |
StoneIoT/establishment-api | src/com/iot/ClassFinder.kt | 1 | 1624 | package com.iot
import java.io.File
import java.net.URL
import java.util.ArrayList
/**
* Created by JGabrielFreitas on 22/03/17.
*/
object ClassFinder {
val PKG_SEPARATOR = '.'
val DIR_SEPARATOR = '/'
val CLASS_FILE_SUFFIX = ".class"
val BAD_PACKAGE_ERROR = "Unable to get resources from path '%s'. Are you sure the package '%s' exists?"
fun find(scannedPackage: String): List<Class<*>> {
val scannedPath = scannedPackage.replace(PKG_SEPARATOR, DIR_SEPARATOR)
val scannedUrl = Thread.currentThread().contextClassLoader.getResource(scannedPath) ?: throw IllegalArgumentException(String.format(BAD_PACKAGE_ERROR, scannedPath, scannedPackage))
val scannedDir = File(scannedUrl.file)
val classes = ArrayList<Class<*>>()
for (file in scannedDir.listFiles()!!) {
classes.addAll(find(file, scannedPackage))
}
return classes
}
private fun find(file: File, scannedPackage: String): List<Class<*>> {
val classes = ArrayList<Class<*>>()
val resource = scannedPackage + PKG_SEPARATOR + file.name
if (file.isDirectory) {
for (child in file.listFiles()!!) {
classes.addAll(find(child, resource))
}
} else if (resource.endsWith(CLASS_FILE_SUFFIX)) {
val endIndex = resource.length - CLASS_FILE_SUFFIX.length
val className = resource.substring(0, endIndex)
try {
classes.add(Class.forName(className))
} catch (ignore: ClassNotFoundException) {
}
}
return classes
}
} | mit | bedae7bb5c9ca1650aa72b16b315b159 | 33.574468 | 188 | 0.624384 | 4.319149 | false | false | false | false |
Husterknupp/jubilant-todo-tribble | src/main/kotlin/de/husterknupp/todoapp/health/ApplicationHealth.kt | 1 | 1683 | package de.husterknupp.todoapp.health
import de.husterknupp.todoapp.gateway.GitlabGateway
import org.springframework.boot.actuate.health.HealthIndicator
import org.springframework.boot.actuate.health.Status
import org.springframework.context.ApplicationContext
import org.springframework.http.HttpStatus
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service
private const val TIME_TO_LIVE = 30000L
@Service
open class JubilantTodoTribbleHealth constructor(
private val applicationContext: ApplicationContext
): ServiceHealth("Jubilant Todo Tribble") {
init { }
private val IGNORED_HEALTH_CHECKS: Array<String> = arrayOf(
"ldapHealthIndicator"
)
@Scheduled(fixedDelay = TIME_TO_LIVE)
fun update() {
var isHealthy: Boolean = true
try {
val healthIndicators = applicationContext.getBeansOfType(HealthIndicator::class.java)
healthIndicators.forEach {
if (!IGNORED_HEALTH_CHECKS.contains(it.key) && it.value.health().status != Status.UP) {
isHealthy = false
}
}
} catch (e: Exception) {
isHealthy = false
}
status = if (isHealthy) HttpStatus.OK else HttpStatus.SERVICE_UNAVAILABLE
}
}
@Service
open class GitlabHealth constructor(
private val gitlabGateway: GitlabGateway
): ServiceHealth("Gitlab") {
@Scheduled(fixedDelay = TIME_TO_LIVE)
fun update() {
status = gitlabGateway.getStatus()
}
}
sealed class ServiceHealth constructor(
val name: String
) {
var status = HttpStatus.OK
protected set
}
| apache-2.0 | 45f563378c2ec49090070f54f0be4278 | 29.053571 | 103 | 0.690434 | 4.623626 | false | false | false | false |
wonderkiln/CameraKit-Android | camerakit/src/main/java/com/camerakit/preview/CameraSurfaceView.kt | 2 | 3058 | package com.camerakit.preview
import android.content.Context
import android.opengl.GLES20.glGenTextures
import android.opengl.GLSurfaceView
import android.os.Build
import androidx.annotation.Keep
import android.util.AttributeSet
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
class CameraSurfaceView : GLSurfaceView, GLSurfaceView.Renderer {
var cameraSurfaceTextureListener: CameraSurfaceTextureListener? = null
private var cameraSurfaceTexture: CameraSurfaceTexture? = null
constructor(context: Context)
: super(context)
constructor(context: Context, attributeSet: AttributeSet)
: super(context, attributeSet)
init {
setEGLContextClientVersion(2)
setRenderer(this)
renderMode = RENDERMODE_WHEN_DIRTY
nativeInit()
}
override fun onResume() {
super.onResume()
}
override fun onPause() {
super.onPause()
}
// GLSurfaceView.Renderer:
override fun onSurfaceCreated(gl: GL10, config: EGLConfig) {
genTextures { inputTexture, outputTexture ->
cameraSurfaceTexture = CameraSurfaceTexture(inputTexture, outputTexture).apply {
setOnFrameAvailableListener { requestRender() }
cameraSurfaceTextureListener?.onSurfaceReady(this)
}
}
nativeOnSurfaceCreated()
}
override fun onSurfaceChanged(gl: GL10, width: Int, height: Int) {
nativeOnSurfaceChanged(width, height)
}
override fun onDrawFrame(gl: GL10) {
val cameraSurfaceTexture = cameraSurfaceTexture
if (cameraSurfaceTexture != null) {
nativeOnDrawFrame()
cameraSurfaceTexture.updateTexImage()
nativeDrawTexture(cameraSurfaceTexture.outputTexture,
cameraSurfaceTexture.size.width,
cameraSurfaceTexture.size.height)
}
}
// Other:
private fun genTextures(textureCallback: (inputTexture: Int, outputTexture: Int) -> Unit) {
val textures = IntArray(2)
glGenTextures(2, textures, 0)
textureCallback(textures[0], textures[1])
}
// ---
@Keep
override fun finalize() {
super.finalize()
try {
nativeFinalize()
} catch (e: Exception) {
// ignore
}
}
// ---
@Keep
private var nativeHandle: Long = 0L
private external fun nativeInit()
private external fun nativeOnSurfaceCreated()
private external fun nativeOnSurfaceChanged(width: Int, height: Int)
private external fun nativeOnDrawFrame()
private external fun nativeDrawTexture(texture: Int, textureWidth: Int, textureHeight: Int)
private external fun nativeFinalize()
private external fun nativeRelease()
companion object {
init {
if (Build.VERSION.SDK_INT <= 17) {
System.loadLibrary("camerakit-core")
}
System.loadLibrary("camerakit")
}
}
}
| mit | ea63e686369aa3628ee40db83894405a | 24.915254 | 95 | 0.651079 | 4.95624 | false | false | false | false |
kamgurgul/cpu-info | app/src/main/java/com/kgurgul/cpuinfo/features/HostActivity.kt | 1 | 3095 | /*
* Copyright 2017 KG Soft
*
* 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.kgurgul.cpuinfo.features
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.kgurgul.cpuinfo.R
import com.kgurgul.cpuinfo.databinding.ActivityHostLayoutBinding
import com.kgurgul.cpuinfo.utils.runOnApiAbove
import com.kgurgul.cpuinfo.utils.setupEdgeToEdge
import dagger.hilt.android.AndroidEntryPoint
/**
* Base activity which is a host for whole application.
*
* @author kgurgul
*/
@AndroidEntryPoint
class HostActivity : AppCompatActivity() {
private lateinit var navController: NavController
private lateinit var binding: ActivityHostLayoutBinding
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppThemeBase)
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_host_layout)
setupEdgeToEdge()
setupNavigation()
setSupportActionBar(binding.toolbar)
runOnApiAbove(Build.VERSION_CODES.M) {
// Processes cannot be listed above M
val menu = binding.bottomNavigation.menu
menu.findItem(R.id.processes).isVisible = false
}
}
override fun onSupportNavigateUp() = navController.navigateUp()
private fun setupNavigation() {
navController =
(supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment)
.navController
navController.addOnDestinationChangedListener { _, destination, _ ->
setToolbarTitleAndElevation(destination.label.toString())
}
binding.bottomNavigation.apply {
setupWithNavController(navController)
setOnItemReselectedListener {
// Do nothing - TODO: scroll to top
}
}
}
/**
* Set toolbar title and manage elevation in case of L+ devices and TabLayout
*/
@SuppressLint("NewApi")
private fun setToolbarTitleAndElevation(title: String) {
binding.toolbar.title = title
if (navController.currentDestination?.id == R.id.hardware) {
binding.toolbar.elevation = 0f
} else {
binding.toolbar.elevation = resources.getDimension(R.dimen.elevation_height)
}
}
} | apache-2.0 | ec41fc5075f951d38401c8827389145f | 34.586207 | 96 | 0.715347 | 4.874016 | false | false | false | false |
nsnikhil/Notes | app/src/main/java/com/nrs/nsnik/notes/view/adapters/NotesAdapter.kt | 1 | 14001 | /*
* Notes Copyright (C) 2018 Nikhil Soni
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.nrs.nsnik.notes.view.adapters
import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.bumptech.glide.RequestManager
import com.jakewharton.rxbinding2.view.RxView
import com.nrs.nsnik.notes.MyApplication
import com.nrs.nsnik.notes.R
import com.nrs.nsnik.notes.data.FolderEntity
import com.nrs.nsnik.notes.data.NoteEntity
import com.nrs.nsnik.notes.util.AppUtil
import com.nrs.nsnik.notes.util.FileUtil
import com.nrs.nsnik.notes.view.MainActivity
import com.nrs.nsnik.notes.view.fragments.ListFragment
import com.nrs.nsnik.notes.view.listeners.ItemTouchListener
import com.nrs.nsnik.notes.view.listeners.ListHeaderClickListener
import com.nrs.nsnik.notes.view.listeners.NoteItemClickListener
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.item_indicator.view.*
import kotlinx.android.synthetic.main.single_folder_layout.view.*
import kotlinx.android.synthetic.main.single_list_header.view.*
import kotlinx.android.synthetic.main.single_note_layout.view.*
import timber.log.Timber
import java.io.File
/**
* This adapter takes in a uri queries the uri and
* registers for change in uri i.e. if any items in
* that uri changes the adapter is notified and then
* adapters clear the old list re draws the entire list
* with the new data set
*/
class NotesAdapter(private val mContext: Context,
private var mNotesList: List<NoteEntity>,
private var mFolderList: List<FolderEntity>,
private val mNoteItemClickListener: NoteItemClickListener,
private val listHeaderClickListener: ListHeaderClickListener) : RecyclerView.Adapter<RecyclerView.ViewHolder>(), ItemTouchListener {
companion object {
private const val NOTES = 0
private const val FOLDER = 1
private const val HEADER = 2
}
private val mLayoutInflater: LayoutInflater
private val mRequestManager: RequestManager?
private val mFileUtil: FileUtil?
private val mCompositeDisposable: CompositeDisposable
private val mRootFolder: File
init {
mRequestManager = (mContext.applicationContext as MyApplication).requestManager
mFileUtil = (mContext.applicationContext as MyApplication).fileUtil
mRootFolder = mFileUtil.rootFolder
mLayoutInflater = LayoutInflater.from(mContext)
mCompositeDisposable = CompositeDisposable()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
FOLDER -> FolderViewHolder(mLayoutInflater.inflate(R.layout.single_folder_layout, parent, false))
NOTES -> NoteViewHolder(mLayoutInflater.inflate(R.layout.single_note_layout, parent, false))
HEADER -> HeaderViewHolder(mLayoutInflater.inflate(R.layout.single_list_header, parent, false))
else -> NoteViewHolder(mLayoutInflater.inflate(R.layout.single_note_layout, parent, false))
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
var pos = mFolderList.size + 2
val tempPOS = position - 1
when (holder.itemViewType) {
FOLDER -> bindFolderData(holder, tempPOS)
NOTES -> {
pos = position - pos
bindNotesData(holder, pos)
}
HEADER -> {
try {
val layoutParams = holder.itemView.layoutParams as StaggeredGridLayoutManager.LayoutParams
layoutParams.isFullSpan = true
} catch (e: ClassCastException) {
e.printStackTrace()
}
bindHeaderData(holder, position)
}
}
}
override fun getItemCount(): Int {
return mNotesList.size + mFolderList.size + 2
}
private fun bindHeaderData(holder: RecyclerView.ViewHolder, position: Int) {
val headerViewHolder = holder as HeaderViewHolder
if (position == 0) {
headerViewHolder.itemHeaderContainer.visibility = if (mFolderList.isNotEmpty()) View.VISIBLE else View.GONE
if (headerViewHolder.itemHeader.isVisible) headerViewHolder.itemHeader.text = mContext.resources.getString(R.string.headingFolder)
} else {
headerViewHolder.itemHeaderContainer.visibility = if (mNotesList.isNotEmpty()) View.VISIBLE else View.GONE
if (headerViewHolder.itemHeader.isVisible) headerViewHolder.itemHeader.text = mContext.resources.getString(R.string.headingNotes)
}
}
private fun bindFolderData(holder: RecyclerView.ViewHolder, position: Int) {
val folderViewHolder = holder as FolderViewHolder
val folderEntity: FolderEntity = mFolderList[position]
folderViewHolder.folderName.text = folderEntity.folderName
folderViewHolder.folderName.compoundDrawableTintList = AppUtil.stateList(folderEntity.color)
changeVisibility(folderViewHolder.isPinned, folderEntity.pinned)
changeVisibility(folderViewHolder.isLocked, folderEntity.locked)
}
private fun bindNotesData(holder: RecyclerView.ViewHolder, position: Int) {
val noteViewHolder = holder as NoteViewHolder
mFileUtil?.getLiveNote(mNotesList[position].fileName!!)?.observe(mContext as MainActivity, Observer {
if (it.title != null && !it.title!!.isEmpty()) {
noteViewHolder.noteTitle.visibility = View.VISIBLE
noteViewHolder.noteTitle.text = it.title
noteViewHolder.noteTitle.setTextColor(Color.parseColor(it.color))
} else {
noteViewHolder.noteTitle.visibility = View.GONE
}
if (it.locked == 0) {
if (it.noteContent != null && !it.noteContent!!.isEmpty()) {
noteViewHolder.noteContent.visibility = View.VISIBLE
noteViewHolder.noteContent.text = it.noteContent
noteViewHolder.noteContent.setTextColor(ContextCompat.getColor(mContext, R.color.colorAccent))
noteViewHolder.noteContent.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, 0, 0)
noteViewHolder.noteContent.compoundDrawablePadding = 0
//noteViewHolder.noteContent.setTextColor(ContextCompat.getColor(mContext, R.color.contentColor))
} else {
noteViewHolder.noteContent.visibility = View.GONE
}
if (it.imageList != null && it.imageList!!.isNotEmpty()) {
noteViewHolder.noteImage.visibility = View.VISIBLE
mRequestManager?.load(File(mRootFolder, it.imageList!![0]))?.into(noteViewHolder.noteImage)
} else {
noteViewHolder.noteImage.visibility = View.GONE
}
} else {
noteViewHolder.noteContent.text = mContext.resources?.getString(R.string.hidden)
noteViewHolder.noteImage.visibility = View.GONE
noteViewHolder.noteContent.setTextColor(ContextCompat.getColor(mContext, R.color.grey))
noteViewHolder.noteContent.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_lock_48px, 0, 0, 0)
noteViewHolder.noteContent.compoundDrawablePadding = 4
}
changeVisibility(noteViewHolder.isPinned, it.pinned)
})
}
private fun changeVisibility(imageView: ImageView, value: Int) {
imageView.visibility = if (value == 1) View.VISIBLE else View.GONE
}
//TODO CHANGE NOTIFY-DATA-SET-CHANGE WITH DIFF UTIL
fun updateNotesList(noteList: List<NoteEntity>) {
mNotesList = noteList
notifyDataSetChanged()
}
//TODO CHANGE NOTIFY-DATA-SET-CHANGE WITH DIFF UTIL
fun updateFolderList(folderList: List<FolderEntity>) {
mFolderList = folderList
notifyDataSetChanged()
}
override fun getItemViewType(position: Int): Int {
return if (position == 0 || position == mFolderList.size + 1) HEADER
else if (position > 0 && position <= mFolderList.size) FOLDER
else if (position > mFolderList.size + 1 && position < mNotesList.size) NOTES
else super.getItemViewType(position)
}
override fun onItemMove(fromPosition: Int, toPosition: Int, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder) {
if (viewHolder.itemViewType == target.itemViewType) {
notifyItemMoved(fromPosition, toPosition)
}
}
//TODO
override fun onItemMoved(fromPosition: Int, toPosition: Int, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
var startPos = -100
if (viewHolder.itemViewType == NOTES) {
startPos = mFolderList.size + 2
}
if (viewHolder.itemViewType == FOLDER) {
startPos = 1
}
val fromPos = fromPosition - startPos
val toPos = toPosition - startPos
}
//TODO
override fun onItemDismiss(position: Int) {
//notifyItemRemoved(position);
}
private fun cleanUp() {
mCompositeDisposable.dispose()
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
cleanUp()
super.onDetachedFromRecyclerView(recyclerView)
}
internal inner class NoteViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val noteTitle: TextView = itemView.singleNoteTitle
val noteContent: TextView = itemView.singleNoteContent
val noteImage: ImageView = itemView.singleNoteImage
val isPinned: ImageView = itemView.itemIndicatorPin
val isLocked: ImageView = itemView.itemIndicatorLock
init {
mCompositeDisposable.addAll(
RxView.clicks(itemView).subscribe({
if (adapterPosition != RecyclerView.NO_POSITION) {
mNoteItemClickListener.onClick(adapterPosition, itemViewType)
}
}, { throwable -> Timber.d(throwable.message) }),
RxView.longClicks(itemView).subscribe({
if (adapterPosition != RecyclerView.NO_POSITION) {
mNoteItemClickListener.onLongClick(adapterPosition, itemViewType, itemView)
}
}, { throwable -> Timber.d(throwable.message) })
)
}
}
internal inner class FolderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val folderName: TextView = itemView.singleFolderName
val isPinned: ImageView = itemView.itemIndicatorPin
val isLocked: ImageView = itemView.itemIndicatorLock
init {
mCompositeDisposable.addAll(
RxView.clicks(itemView).subscribe {
if (adapterPosition != RecyclerView.NO_POSITION) {
mNoteItemClickListener.onClick(adapterPosition, itemViewType)
}
},
RxView.longClicks(itemView).subscribe({
if (adapterPosition != RecyclerView.NO_POSITION) {
mNoteItemClickListener.onLongClick(adapterPosition, itemViewType, itemView)
}
}, { throwable -> Timber.d(throwable.message) })
)
}
}
internal inner class HeaderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val itemHeader: TextView = itemView.itemHeader
private val itemHeaderMore: ImageView = itemView.itemHeaderMore
val itemHeaderContainer: ConstraintLayout = itemView.itemHeaderContainer
init {
mCompositeDisposable.addAll(
RxView.clicks(itemHeaderMore).subscribe {
if (adapterPosition != RecyclerView.NO_POSITION) {
listHeaderClickListener.headerClick(
if (itemHeader.text.toString() == mContext.resources.getString(R.string.headingFolder)) ListFragment.ItemType.FOLDER
else ListFragment.ItemType.NOTES, itemHeaderMore)
}
}
)
}
}
} | gpl-3.0 | 70523c426b297c0c6c9afd3a0b49346e | 42.619938 | 152 | 0.664381 | 5.045405 | false | false | false | false |
AndroidX/constraintlayout | demoProjects/ComposeDemos/app/src/main/java/androidx/demo/composedemos/ui/theme/Type.kt | 2 | 803 | package androidx.demo.composedemos.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
) | apache-2.0 | 550220c235bae07017c188e6014fef60 | 27.714286 | 50 | 0.693649 | 4.436464 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/series/HighSeriesOf9Statistic.kt | 1 | 951 | package ca.josephroque.bowlingcompanion.statistics.impl.series
import android.os.Parcel
import android.os.Parcelable
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator
/**
* Copyright (C) 2018 Joseph Roque
*
* Highest series of 9 games.
*/
class HighSeriesOf9Statistic(value: Int = 0) : HighSeriesStatistic(value) {
// MARK: Overrides
override val seriesSize = 9
override val titleId = Id
override val id = Id.toLong()
// MARK: Parcelable
companion object {
/** Creator, required by [Parcelable]. */
@Suppress("unused")
@JvmField val CREATOR = parcelableCreator(::HighSeriesOf9Statistic)
/** Unique ID for the statistic. */
const val Id = R.string.statistic_high_series_of_9
}
/**
* Construct this statistic from a [Parcel].
*/
private constructor(p: Parcel): this(value = p.readInt())
}
| mit | 2432b8b710198125023fadf57d9269eb | 25.416667 | 75 | 0.685594 | 4.245536 | false | false | false | false |
lena0204/Plattenspieler | musicServiceLibrary/src/main/java/com/lk/musicservicelibrary/playback/PlaybackCallback.kt | 1 | 3459 | package com.lk.musicservicelibrary.playback
import android.content.Context
import android.media.session.MediaSession
import android.media.session.PlaybackState
import android.os.Bundle
import android.os.ResultReceiver
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.lk.musicservicelibrary.database.PlaylistRepository
import com.lk.musicservicelibrary.main.*
import com.lk.musicservicelibrary.models.*
import com.lk.musicservicelibrary.playback.state.*
import com.lk.musicservicelibrary.system.MusicDataRepository
import com.lk.musicservicelibrary.utils.PlaybackStateFactory
/**
* Erstellt von Lena am 05/04/2019.
*/
class PlaybackCallback(private val dataRepository: MusicDataRepository,
private val playlistRepository: PlaylistRepository,
val context: Context):
MediaSession.Callback(),
MusicPlayer.PlaybackFinished {
private val TAG = "PlaybackCallback"
private var playerState: BasicState = StoppedState(this)
private var commandResolver = CommandResolver(this)
private var playingList = MutableLiveData<MusicList>()
private var playbackState = MutableLiveData<PlaybackState>()
private var player: MusicPlayer = SimpleMusicPlayer(this)
private var queriedMediaList = MusicList()
// TODO check audiofocus, update code etc. !!!
init {
playingList.value = MusicList()
playbackState.value = PlaybackStateFactory.createState(States.STOPPED)
}
fun getPlayingList(): LiveData<MusicList> = playingList
fun setPlayingList(updatedList: MusicList) {
playingList.value = updatedList
}
fun getQueriedMediaList(): MusicList = queriedMediaList
fun setQueriedMediaList(updatedList: MusicList) {
queriedMediaList = updatedList
Log.v(TAG, "Neue QueriedMediaList: $queriedMediaList")
}
fun getPlaybackState(): LiveData<PlaybackState> = playbackState
fun setPlaybackState(updatedState: PlaybackState) {
playbackState.value = updatedState
}
fun getShuffleFromPlaybackState(): Boolean {
val extras = playbackState.value!!.extras
return extras?.getBoolean(MusicService.SHUFFLE_KEY) ?: false
}
fun getPlayerState(): BasicState = playerState
fun setPlayerState(state: BasicState) {
playerState = state
}
fun getDataRepository(): MusicDataRepository = dataRepository
fun getPlaylistRepository(): PlaylistRepository = playlistRepository
fun getPlayer(): MusicPlayer = player
fun setPlayer(player: MusicPlayer) { this.player = player }
fun preparePlayback() {
playerState.prepareFromMediaList()
}
override fun playbackFinished() {
playerState.skipToNext()
}
override fun onPlay() {
playerState.play()
}
override fun onPlayFromMediaId(mediaId: String?, extras: Bundle?) {
playerState.playFromId(mediaId)
}
override fun onPause() {
playerState.pause()
}
override fun onSkipToNext() {
playerState.skipToNext()
}
override fun onSkipToPrevious() {
playerState.skipToPrevious()
}
override fun onStop() {
if(playerState.type != States.STOPPED) {
playerState.stop()
}
}
override fun onCommand(command: String, args: Bundle?, cb: ResultReceiver?) {
commandResolver.resolveCommand(command, args, cb)
}
} | gpl-3.0 | 94c8068a681f6a4924cc5f09b439367b | 29.619469 | 81 | 0.714079 | 4.790859 | false | false | false | false |
lvtanxi/TanxiNote | app/src/main/java/com/lv/note/ui/MainAct.kt | 1 | 6117 | package com.lv.note.ui
import android.app.Activity
import android.content.Intent
import android.support.design.widget.AppBarLayout
import android.support.design.widget.FloatingActionButton
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.text.Html
import android.text.TextUtils
import android.text.format.DateFormat
import android.view.View
import android.widget.PopupMenu
import cn.bmob.v3.BmobQuery
import com.lv.note.App
import com.lv.note.R
import com.lv.note.adapter.BaseHolder
import com.lv.note.adapter.LBaseAdapter
import com.lv.note.base.BaseRecyclerActivity
import com.lv.note.entity.Note
import com.lv.note.helper.FindListenerSub
import com.lv.note.helper.UpdateListenerSub
import com.orhanobut.hawk.Hawk
import com.xiaomi.market.sdk.XiaomiUpdateAgent
/**
* User: 吕勇
* Date: 2016-06-13
* Time: 13:31
* Description:主界面
*/
class MainAct : BaseRecyclerActivity<Note>(), AppBarLayout.OnOffsetChangedListener {
private var mDrawerLayout: DrawerLayout? = null
private var mActionBarDrawerToggle: ActionBarDrawerToggle? = null;
private var mAppBar: AppBarLayout? = null
private var mAddBtn: FloatingActionButton? = null
var mFrag: NavigationFra? = null
private var year = ""
companion object {
val CHANGE_NOTE = "CHANGE_NOTE"
fun startMainAct(actvity: Activity) {
actvity.startActivity(Intent(actvity, MainAct::class.java))
}
}
override fun loadLayoutId(): Int {
column = 2
return R.layout.act_main
}
override fun processLogic() {
super.processLogic()
XiaomiUpdateAgent.update(this)
}
override fun initViews() {
super.initViews()
mDrawerLayout = fdb(R.id.mian_drawer_layout);
mAppBar = fdb(R.id.main_appbar);
mAddBtn = fdb(R.id.main_float_button);
}
override fun initData() {
mActionBarDrawerToggle = ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.open, R.string.close);
mActionBarDrawerToggle?.syncState()
super.initData()
year = DateFormat.format("yyyy年", System.currentTimeMillis()) as String
}
override fun bindListener() {
super.bindListener()
mDrawerLayout?.addDrawerListener(mActionBarDrawerToggle!!)
mAppBar?.addOnOffsetChangedListener(this)
mAddBtn?.setOnClickListener { AddNoteAct.startAddNoteAct(this, null) }
mBaseAdapter?.setOnRecyclerItemChildClickListener(object : LBaseAdapter
.OnRecyclerItemChildClickListener {
override fun onItemChildClick(view: View, position: Int) {
if (view.id == R.id.item_knife) {
AddNoteAct.startAddNoteAct(this@MainAct, mBaseAdapter!!.getItem(position))
return
}
val mPopupMenu = PopupMenu(this@MainAct, view)
mPopupMenu.menu.add("分享")
mPopupMenu.menu.add("删除")
mPopupMenu.setOnMenuItemClickListener { item ->
val note = mBaseAdapter?.getItem(position)
note?.let {
if (TextUtils.equals("分享", item.title))
shareText(note.note)
else
updateNote(note)
}
true
}
mPopupMenu.show()
}
})
}
private fun shareText(message: String) {
val shareIntent = Intent()
shareIntent.action = Intent.ACTION_SEND
shareIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(message).toString())
shareIntent.type = "text/plain"
startActivity(Intent.createChooser(shareIntent, "分享到"))
}
private fun updateNote(note: Note) {
note.status = "0"
note.update(this, note.objectId, object : UpdateListenerSub(this) {
override fun onSuccess() {
processLogic()
}
})
}
override val lBaseAdapter: LBaseAdapter<Note>
get() = object : LBaseAdapter<Note>(R.layout.item_note) {
override fun onBindItem(baseHolder: BaseHolder, realPosition: Int, item: Note) {
baseHolder.setKnifeTextHtml(R.id.item_knife, item.note)
.setText(R.id.item_date, item.year.replace(year, ""))
.setText(R.id.item_time, item.time)
.setOnItemChildClickListener(OnItemChildClickListener(), R.id.item_more, R.id.item_knife)
}
override fun onItemClick(item: Note) {
AddNoteAct.startAddNoteAct(this@MainAct, item)
}
}
override fun onBGARefresh(): Boolean {
val query = BmobQuery<Note>()
query.addWhereEqualTo("userId", App.getInstance().getPerson()?.objectId)
query.addWhereEqualTo("status", "1")
query.order("createdAt")
query.findObjects(this, object : FindListenerSub<Note>(this, false) {
override fun onSuccess(p0: MutableList<Note>?) {
addItems(p0!!)
}
override fun onFinish() {
stopRefreshing()
}
})
return false
}
override fun onResume() {
super.onResume()
mAppBar?.addOnOffsetChangedListener(this)
if (Hawk.get(CHANGE_NOTE, false)) {
Hawk.remove(CHANGE_NOTE)
commonRefresh?.setDelegate(mDelegate)
processLogic()
}
}
override fun onPause() {
super.onPause()
mAppBar?.removeOnOffsetChangedListener(this)
}
override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
commonRefresh?.setDelegate(if (verticalOffset == 0) mDelegate else null)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
mFrag?.let {
mFrag!!.onActivityResult(requestCode, resultCode, data)
}
super.onActivityResult(requestCode, resultCode, data)
}
} | apache-2.0 | 1c86cb184bec1343935497fc73098082 | 32.822222 | 117 | 0.62461 | 4.452816 | false | false | false | false |
cketti/k-9 | app/ui/legacy/src/main/java/com/fsck/k9/ui/messagesource/MessageSourceActivity.kt | 2 | 1908 | package com.fsck.k9.ui.messagesource
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.fragment.app.commit
import com.fsck.k9.controller.MessageReference
import com.fsck.k9.ui.R
import com.fsck.k9.ui.base.K9Activity
/**
* Temporary Activity used until the fragment can be displayed in the main activity.
*/
class MessageSourceActivity : K9Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setLayout(R.layout.message_view_headers_activity)
setTitle(R.string.show_headers_action)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
if (savedInstanceState == null) {
addMessageHeadersFragment()
}
}
private fun addMessageHeadersFragment() {
val messageReferenceString = intent.getStringExtra(ARG_REFERENCE) ?: error("Missing argument $ARG_REFERENCE")
val messageReference = MessageReference.parse(messageReferenceString)
?: error("Invalid message reference: $messageReferenceString")
val fragment = MessageHeadersFragment.newInstance(messageReference)
supportFragmentManager.commit {
add(R.id.message_headers_fragment, fragment)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return if (item.itemId == android.R.id.home) {
finish()
true
} else {
super.onOptionsItemSelected(item)
}
}
companion object {
private const val ARG_REFERENCE = "reference"
fun createLaunchIntent(context: Context, messageReference: MessageReference): Intent {
return Intent(context, MessageSourceActivity::class.java).apply {
putExtra(ARG_REFERENCE, messageReference.toIdentityString())
}
}
}
}
| apache-2.0 | 4f1d7b5821b816adb2b41ce083ec52c2 | 33.071429 | 117 | 0.688679 | 4.699507 | false | false | false | false |
FWDekker/intellij-randomness | src/main/kotlin/com/fwdekker/randomness/ui/ListenerHelper.kt | 1 | 6171 | package com.fwdekker.randomness.ui
import com.fwdekker.randomness.Bundle
import com.fwdekker.randomness.StateEditor
import java.awt.event.FocusEvent
import java.awt.event.FocusListener
import java.beans.PropertyChangeEvent
import javax.swing.ButtonGroup
import javax.swing.JCheckBox
import javax.swing.JRadioButton
import javax.swing.JSpinner
import javax.swing.JTextArea
import javax.swing.JTextField
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import javax.swing.event.TreeModelEvent
import javax.swing.event.TreeModelListener
import javax.swing.text.Document
import com.intellij.openapi.editor.Document as JBDocument
import com.intellij.openapi.editor.event.DocumentEvent as JBDocumentEvent
import com.intellij.openapi.editor.event.DocumentListener as JBDocumentListener
/**
* Adds [listener] to each of [components].
*
* @param components the components to add the listener to
* @param listener the listener to invoke whenever any of the given components changes state
*/
@Suppress("SpreadOperator") // Acceptable because this method is called rarely
fun addChangeListenerTo(vararg components: Any, listener: () -> Unit) {
components.forEach { component ->
when (component) {
is ButtonGroup -> addChangeListenerTo(*component.buttons(), listener = listener)
is JBDocument -> component.addDocumentListener(SimpleJBDocumentListener { listener() })
is JCheckBox -> component.addItemListener { listener() }
is JRadioButton -> component.addItemListener { listener() }
is JSpinner -> component.addChangeListener { listener() }
is JTextArea -> component.document.addDocumentListener(SimpleDocumentListener { listener() })
is JTextField -> component.addChangeListener { listener() }
is StateEditor<*> -> component.addChangeListener { listener() }
is VariableLabelRadioButton -> component.addChangeListener { listener() }
else -> throw IllegalArgumentException(
Bundle("helpers.error.unknown_component_type", component.javaClass.canonicalName)
)
}
}
}
/**
* Adds [listener] to a text field.
*
* Code taken from https://stackoverflow.com/a/27190162/3307872, but without the `invokeLater`.
*
* @param listener the change listener that responds to changes in the text field
*/
fun JTextField.addChangeListener(listener: (JTextField) -> Unit) {
val dl = object : DocumentListener {
private var lastChange = 0
private var lastNotifiedChange = 0
override fun changedUpdate(e: DocumentEvent?) {
lastChange++
if (lastNotifiedChange == lastChange) return
lastNotifiedChange = lastChange
listener(this@addChangeListener)
}
override fun insertUpdate(e: DocumentEvent?) = changedUpdate(e)
override fun removeUpdate(e: DocumentEvent?) = changedUpdate(e)
}
this.addPropertyChangeListener("document") { e: PropertyChangeEvent ->
(e.oldValue as? Document)?.removeDocumentListener(dl)
(e.newValue as? Document)?.addDocumentListener(dl)
dl.changedUpdate(null)
}
this.document.addDocumentListener(dl)
}
/**
* A [JBDocumentListener] that invokes [listener] on each event.
*
* @property listener The listener to invoke on any event.
*/
class SimpleJBDocumentListener(private val listener: (JBDocumentEvent) -> Unit) : JBDocumentListener {
/**
* Invoked after contents have been changed.
*
* @param event the event that triggered the listener
*/
override fun documentChanged(event: JBDocumentEvent) {
listener(event)
}
}
/**
* A [DocumentListener] that invokes [listener] on each event.
*
* @property listener The listener to invoke on any event.
*/
class SimpleDocumentListener(private val listener: (DocumentEvent) -> Unit) : DocumentListener {
/**
* Invoked after text has been inserted.
*
* @param event the event that triggered the listener
*/
override fun insertUpdate(event: DocumentEvent) = listener(event)
/**
* Invoked after text has been removed.
*
* @param event the event that triggered the listener
*/
override fun removeUpdate(event: DocumentEvent) = listener(event)
/**
* Invoked after attributes have been changed.
*
* @param event the event that triggered the listener
*/
override fun changedUpdate(event: DocumentEvent) = listener(event)
}
/**
* A [TreeModelListener] that invokes [listener] on each event.
*
* @property listener The listener to invoke on any event.
*/
class SimpleTreeModelListener(private val listener: (TreeModelEvent) -> Unit) : TreeModelListener {
/**
* Invoked after a node has changed.
*
* @param event the event that triggered the listener
*/
override fun treeNodesChanged(event: TreeModelEvent) = listener(event)
/**
* Invoked after a node has been inserted.
*
* @param event the event that triggered the listener
*/
override fun treeNodesInserted(event: TreeModelEvent) = listener(event)
/**
* Invoked after a node has been removed.
*
* @param event the event that triggered the listener
*/
override fun treeNodesRemoved(event: TreeModelEvent) = listener(event)
/**
* Invoked after the structure of the tree has changed.
*
* @param event the event that triggered the listener
*/
override fun treeStructureChanged(event: TreeModelEvent) = listener(event)
}
/**
* A [FocusListener] that invokes [listener] when focus is gained only.
*
* @property listener The listener to invoke when focus is gained.
*/
class FocusGainListener(private val listener: (FocusEvent) -> Unit) : FocusListener {
/**
* Invokes [listener].
*
* @param event the event passed to [listener]
*/
override fun focusGained(event: FocusEvent) {
listener(event)
}
/**
* Does nothing.
*
* @param event ignored
*/
override fun focusLost(event: FocusEvent) {
// Do nothing
}
}
| mit | 2b6d8f921f6db840e1c11d30078607d1 | 31.824468 | 105 | 0.69227 | 4.699924 | false | false | false | false |
android/user-interface-samples | Text/app/src/main/java/com/example/android/text/demo/linebreak/EditTextDialogFragment.kt | 1 | 2730 | /*
* Copyright (C) 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 com.example.android.text.demo.linebreak
import android.app.Dialog
import android.os.Bundle
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.setFragmentResult
import com.example.android.text.databinding.EditTextDialogFragmentBinding
import com.google.android.material.dialog.MaterialAlertDialogBuilder
class EditTextDialogFragment private constructor() : DialogFragment() {
companion object {
const val REQUEST_EDIT_TEXT =
"com.example.android.text.demo.linebreak.EditTextDialogFragment:edit_text"
const val RESULT_ARG_TEXT = "text"
private const val ARG_INITIAL_TEXT = "initial_text"
fun newInstance(initialText: String): EditTextDialogFragment {
return EditTextDialogFragment().apply {
arguments = Bundle().apply {
putString(ARG_INITIAL_TEXT, initialText)
}
}
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val binding = EditTextDialogFragmentBinding.inflate(layoutInflater)
binding.input.setText(requireArguments().getString(ARG_INITIAL_TEXT))
if (binding.input.requestFocus()) {
binding.input.selectAll()
}
return MaterialAlertDialogBuilder(requireContext())
.setView(binding.root)
.setPositiveButton(android.R.string.ok) { _, _ ->
setFragmentResult(REQUEST_EDIT_TEXT, Bundle().apply {
putString(RESULT_ARG_TEXT, binding.input.text.toString())
})
}
.create()
.also { dialog ->
// Show the software keyboard.
dialog.window?.run {
clearFlags(
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
)
setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
}
}
}
}
| apache-2.0 | 357c4ff5d34f4784487d615aaa20eb58 | 38 | 96 | 0.648718 | 4.963636 | false | false | false | false |
proxer/ProxerAndroid | src/main/kotlin/me/proxer/app/chat/prv/create/CreateConferenceFragment.kt | 1 | 15977 | package me.proxer.app.chat.prv.create
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import androidx.core.os.bundleOf
import androidx.core.view.isGone
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.textfield.TextInputLayout
import com.jakewharton.rxbinding3.view.clicks
import com.jakewharton.rxbinding3.widget.editorActions
import com.jakewharton.rxbinding3.widget.textChanges
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.IIcon
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial
import com.mikepenz.iconics.utils.colorInt
import com.mikepenz.iconics.utils.paddingDp
import com.mikepenz.iconics.utils.sizeDp
import com.rubengees.easyheaderfooteradapter.EasyHeaderFooterAdapter
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import com.vanniktech.emoji.EmojiEditText
import com.vanniktech.emoji.EmojiPopup
import io.reactivex.android.schedulers.AndroidSchedulers
import kotterknife.bindView
import me.proxer.app.GlideApp
import me.proxer.app.R
import me.proxer.app.base.BaseAdapter.ContainerPositionResolver
import me.proxer.app.base.BaseFragment
import me.proxer.app.chat.prv.Participant
import me.proxer.app.chat.prv.PrvMessengerActivity
import me.proxer.app.exception.InvalidInputException
import me.proxer.app.exception.TopicEmptyException
import me.proxer.app.util.ErrorUtils
import me.proxer.app.util.Validators
import me.proxer.app.util.extension.multilineSnackbar
import me.proxer.app.util.extension.resolveColor
import me.proxer.app.util.extension.safeInject
import me.proxer.app.util.extension.setIconicsImage
import me.proxer.app.util.extension.subscribeAndLogErrors
import me.proxer.app.util.extension.unsafeLazy
import org.koin.androidx.viewmodel.ext.android.viewModel
import kotlin.properties.Delegates
/**
* @author Ruben Gees
*/
class CreateConferenceFragment : BaseFragment(R.layout.fragment_create_conference) {
companion object {
fun newInstance() = CreateConferenceFragment().apply {
arguments = bundleOf()
}
}
override val hostingActivity: CreateConferenceActivity
get() = activity as CreateConferenceActivity
private val viewModel by viewModel<CreateConferenceViewModel>()
private val validators by safeInject<Validators>()
private val isGroup: Boolean
get() = hostingActivity.isGroup
private val initialParticipant: Participant?
get() = hostingActivity.initialParticipant
private val emojiPopup by unsafeLazy {
val popup = EmojiPopup.Builder.fromRootView(root)
.setOnEmojiPopupShownListener { updateIcons() }
.setOnEmojiPopupDismissListener { updateIcons() }
.build(messageInput)
popup
}
private var innerAdapter by Delegates.notNull<CreateConferenceParticipantAdapter>()
private var adapter by Delegates.notNull<EasyHeaderFooterAdapter>()
private var addParticipantFooter by Delegates.notNull<ViewGroup>()
private var addParticipantInputFooter by Delegates.notNull<ViewGroup>()
private val root: ViewGroup by bindView(R.id.root)
private val progress: SwipeRefreshLayout by bindView(R.id.progress)
private val topicContainer: ViewGroup by bindView(R.id.topicContainer)
private val topicInputContainer: TextInputLayout by bindView(R.id.topicInputContainer)
private val topicInput: EditText by bindView(R.id.topicInput)
private val participants: RecyclerView by bindView(R.id.participants)
private val emojiButton: ImageButton by bindView(R.id.emojiButton)
private val messageInput: EmojiEditText by bindView(R.id.messageInput)
private val sendButton: ImageView by bindView(R.id.sendButton)
private val addParticipantImage by lazy {
addParticipantFooter.findViewById<ImageView>(R.id.image)
}
private val participantInputContainer by lazy {
addParticipantInputFooter.findViewById<TextInputLayout>(R.id.participantInputContainer)
}
private val participantInput by lazy {
addParticipantInputFooter.findViewById<EditText>(R.id.participantInput)
}
private val acceptParticipant by lazy {
addParticipantInputFooter.findViewById<ImageButton>(R.id.accept)
}
private val cancelParticipant by lazy {
addParticipantInputFooter.findViewById<ImageButton>(R.id.cancel)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
innerAdapter = CreateConferenceParticipantAdapter(savedInstanceState)
adapter = EasyHeaderFooterAdapter(innerAdapter)
innerAdapter.positionResolver = ContainerPositionResolver(adapter)
if (savedInstanceState == null) {
initialParticipant?.let {
innerAdapter.add(it)
if (!isGroup) {
adapter.footer = null
}
}
}
innerAdapter.removalSubject
.autoDisposable(this.scope())
.subscribe {
if (adapter.footer == null) {
adapter.footer = addParticipantFooter
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
addParticipantFooter = inflater.inflate(
R.layout.item_create_conference_add_participant,
container,
false
) as ViewGroup
addParticipantInputFooter = inflater.inflate(
R.layout.item_create_conference_add_participant_input,
container,
false
) as ViewGroup
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Call getter as soon as possible to make keyboard detection work properly.
emojiPopup
updateIcons()
initFooter()
innerAdapter.glide = GlideApp.with(this)
participants.isNestedScrollingEnabled = false
participants.layoutManager = LinearLayoutManager(context)
participants.adapter = adapter
val schemeColors = requireContext().let { context ->
intArrayOf(context.resolveColor(R.attr.colorPrimary), context.resolveColor(R.attr.colorSecondary))
}
progress.setColorSchemeColors(*schemeColors)
progress.isEnabled = false
emojiButton.clicks()
.autoDisposable(viewLifecycleOwner.scope())
.subscribe { emojiPopup.toggle() }
initSendButton()
initTopicInput()
viewModel.isLoading.observe(
viewLifecycleOwner,
Observer {
progress.isEnabled = it == true
progress.isRefreshing = it == true
}
)
viewModel.result.observe(
viewLifecycleOwner,
Observer {
it?.let {
requireActivity().finish()
PrvMessengerActivity.navigateTo(requireActivity(), it)
}
}
)
viewModel.error.observe(
viewLifecycleOwner,
Observer {
it?.let {
hostingActivity.multilineSnackbar(
it.message,
Snackbar.LENGTH_LONG,
it.buttonMessage,
it.toClickListener(hostingActivity)
)
}
}
)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
innerAdapter.saveInstanceState(outState)
}
override fun onDestroyView() {
participants.layoutManager = null
participants.adapter = null
emojiPopup.dismiss()
super.onDestroyView()
}
private fun initFooter() {
addParticipantImage.setIconicsImage(
when (isGroup) {
true -> CommunityMaterial.Icon.cmd_account_plus
false -> CommunityMaterial.Icon.cmd_account_multiple_plus
},
96,
16
)
acceptParticipant.setIconicsImage(CommunityMaterial.Icon.cmd_check, 48, 16)
cancelParticipant.setIconicsImage(CommunityMaterial.Icon.cmd_close, 48, 16)
addParticipantFooter.clicks()
.autoDisposable(viewLifecycleOwner.scope())
.subscribe {
adapter.footer = addParticipantInputFooter
addParticipantFooter.post {
if (this.view != null) addParticipantInputFooter.requestFocus()
}
}
cancelParticipant.clicks()
.autoDisposable(viewLifecycleOwner.scope())
.subscribe {
participantInput.text.clear()
adapter.footer = addParticipantFooter
messageInput.requestFocus()
}
acceptParticipant.clicks()
.autoDisposable(viewLifecycleOwner.scope())
.subscribe {
if (validateAndAddUser()) {
messageInput.requestFocus()
}
}
participantInput.textChanges()
.skipInitialValue()
.autoDisposable(viewLifecycleOwner.scope())
.subscribe {
participantInputContainer.error = null
participantInputContainer.isErrorEnabled = false
}
participantInput.editorActions { it == EditorInfo.IME_ACTION_NEXT }
.autoDisposable(viewLifecycleOwner.scope())
.subscribe {
if (it == EditorInfo.IME_ACTION_NEXT && validateAndAddUser()) {
messageInput.requestFocus()
}
}
if (innerAdapter.itemCount <= 0) {
adapter.footer = addParticipantInputFooter
}
}
@Suppress("ThrowsCount")
private fun initSendButton() {
sendButton.clicks()
.map {
validators.validateLogin()
val topic = topicInput.text.toString().trim()
val firstMessage = messageInput.text.toString().trim()
val participants = innerAdapter.participants
when {
isGroup && topic.isBlank() -> throw TopicEmptyException()
firstMessage.isBlank() -> throw InvalidInputException(
requireContext().getString(R.string.error_missing_message)
)
participants.isEmpty() -> throw InvalidInputException(
requireContext().getString(R.string.error_missing_participants)
)
}
Triple(topic, firstMessage, participants)
}
.doOnError {
when (it) {
is InvalidInputException -> it.message?.let { message ->
hostingActivity.multilineSnackbar(message)
}
is TopicEmptyException -> {
topicInputContainer.isErrorEnabled = true
topicInputContainer.error = requireContext().getString(R.string.error_input_empty)
}
else -> ErrorUtils.handle(it).let { action ->
hostingActivity.multilineSnackbar(
action.message,
Snackbar.LENGTH_LONG,
action.buttonMessage,
action.toClickListener(hostingActivity)
)
}
}
}
.retry()
.filter { viewModel.isLoading.value != true }
.observeOn(AndroidSchedulers.mainThread())
.autoDisposable(viewLifecycleOwner.scope())
.subscribeAndLogErrors { (topic, firstMessage, participants) ->
when (isGroup) {
true -> viewModel.createGroup(topic, firstMessage, participants)
false -> viewModel.createChat(firstMessage, participants.first())
}
}
}
private fun initTopicInput() {
if (isGroup) {
topicInput.textChanges()
.skipInitialValue()
.autoDisposable(viewLifecycleOwner.scope())
.subscribe {
topicInputContainer.isErrorEnabled = false
topicInputContainer.error = null
}
topicInput.editorActions { it == EditorInfo.IME_ACTION_NEXT }
.autoDisposable(viewLifecycleOwner.scope())
.subscribe {
if (it == EditorInfo.IME_ACTION_NEXT) {
if (innerAdapter.isEmpty()) {
adapter.footer = addParticipantInputFooter
participantInput.requestFocus()
} else {
messageInput.requestFocus()
}
}
}
topicInput.requestFocus()
} else {
topicContainer.isGone = true
if (innerAdapter.itemCount <= 0) {
addParticipantInputFooter.requestFocus()
} else {
messageInput.requestFocus()
}
}
}
private fun validateAndAddUser(): Boolean = participantInput.text.toString().trim().let {
when {
it.isBlank() -> {
participantInputContainer.isErrorEnabled = true
participantInputContainer.error = requireContext().getString(R.string.error_input_empty)
false
}
innerAdapter.contains(it) -> {
participantInputContainer.isErrorEnabled = true
participantInputContainer.error = requireContext().getString(R.string.error_duplicate_participant)
false
}
it.equals(storageHelper.user?.name, ignoreCase = true) -> {
participantInputContainer.isErrorEnabled = true
participantInputContainer.error = requireContext().getString(R.string.error_self_participant)
false
}
else -> {
innerAdapter.add(Participant(it, ""))
participantInput.text.clear()
if (!isGroup && innerAdapter.itemCount >= 1) {
adapter.footer = null
true
} else {
false
}
}
}
}
private fun updateIcons() {
val emojiButtonIcon: IIcon = when (emojiPopup.isShowing) {
true -> CommunityMaterial.Icon2.cmd_keyboard
false -> CommunityMaterial.Icon.cmd_emoticon
}
emojiButton.setImageDrawable(
IconicsDrawable(requireContext(), emojiButtonIcon).apply {
colorInt = requireContext().resolveColor(R.attr.colorIcon)
paddingDp = 6
sizeDp = 32
}
)
sendButton.setImageDrawable(
IconicsDrawable(requireContext(), CommunityMaterial.Icon3.cmd_send).apply {
colorInt = requireContext().resolveColor(R.attr.colorSecondary)
paddingDp = 4
sizeDp = 32
}
)
}
}
| gpl-3.0 | 6ec273451e3dacf669cbe14de4ddf57f | 34.425721 | 116 | 0.614696 | 5.58051 | false | false | false | false |
Lennoard/HEBF | app/src/main/java/com/androidvip/hebf/ui/main/tools/apps/AutoStartDisablerActivity.kt | 1 | 6412 | package com.androidvip.hebf.ui.main.tools.apps
import android.app.SearchManager
import android.content.Context
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.widget.SearchView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.androidvip.hebf.R
import com.androidvip.hebf.ui.base.BaseActivity
import com.androidvip.hebf.adapters.AutoStartAdapter
import com.androidvip.hebf.models.App
import com.androidvip.hebf.models.OpApp
import com.androidvip.hebf.toast
import com.androidvip.hebf.utils.*
import kotlinx.android.synthetic.main.activity_app_ops.*
import kotlinx.coroutines.launch
import java.util.*
import kotlin.Comparator
class AutoStartDisablerActivity : BaseActivity() {
private lateinit var rv: RecyclerView
private lateinit var adapter: AutoStartAdapter
private val opApps: MutableList<OpApp> = mutableListOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_app_ops)
setUpToolbar(toolbar)
appOpsInfoCard.visibility = View.VISIBLE
appOpsInfoCardButton.setOnClickListener { appOpsInfoCard.visibility = View.GONE }
appOpsAppProgress.visibility = View.VISIBLE
setupRecyclerView()
Logger.logDebug("Retrieving BOOT_COMPLETED ops", this)
lifecycleScope.launch(workerContext) {
val opStatus = RootUtils
.executeSync("appops query-op BOOT_COMPLETED allow")
.toLowerCase(Locale.US)
val supported = opStatus.isNotEmpty()
&& !opStatus.contains("unknown")
&& !opStatus.contains("error")
if (supported) {
val appsList = PackagesManager(this@AutoStartDisablerActivity).getThirdPartyApps()
appsList.sortWith(Comparator { one: App, other: App -> one.label.compareTo(other.label) })
appsList.forEach { app ->
val opApp = OpApp("BOOT_COMPLETED", app).apply {
isOpEnabled = RootUtils.executeWithOutput(
"appops get ${this.packageName} ${this.op}", "allow",
this@AutoStartDisablerActivity
).contains("allow")
}
opApps.add(opApp)
}
}
runSafeOnUiThread {
if (supported) {
adapter = AutoStartAdapter(this@AutoStartDisablerActivity, opApps)
rv.adapter = adapter
appOpsAppProgress.visibility = View.GONE
} else {
toast("Not supported: Operation not found")
finish()
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.apps_manager, menu)
val searchMenuItem = menu.findItem(R.id.action_search)
menu.findItem(R.id.action_filter).isVisible = false
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager?
val searchView = searchMenuItem.actionView as SearchView
searchView.queryHint = getString(R.string.search)
if (searchManager != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName))
searchMenuItem.setOnActionExpandListener(object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem): Boolean {
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
adapter = AutoStartAdapter(this@AutoStartDisablerActivity, filterListByMatch(query))
rv.adapter = adapter
return true
}
override fun onQueryTextChange(newText: String): Boolean {
if (newText.length > 2) {
adapter = AutoStartAdapter(this@AutoStartDisablerActivity, filterListByMatch(newText))
rv.adapter = adapter
return true
} else if (newText.isEmpty()) {
adapter = AutoStartAdapter(this@AutoStartDisablerActivity, opApps)
rv.adapter = adapter
return true
}
return false
}
})
return true
}
override fun onMenuItemActionCollapse(item: MenuItem): Boolean {
adapter = AutoStartAdapter(this@AutoStartDisablerActivity, opApps)
rv.adapter = adapter
return true
}
})
}
return true
}
override fun finish() {
super.finish()
overridePendingTransition(R.anim.fragment_close_enter, R.anim.slide_out_right)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
return true
}
return super.onOptionsItemSelected(item)
}
private fun setupRecyclerView() {
rv = findViewById(R.id.app_ops_rv)
val layoutManager = GridLayoutManager(applicationContext, defineRecyclerViewColumns())
rv.setHasFixedSize(true)
rv.layoutManager = layoutManager
}
private fun defineRecyclerViewColumns(): Int {
val isTablet = resources.getBoolean(R.bool.is_tablet)
val isLandscape = resources.getBoolean(R.bool.is_landscape)
return if (isTablet || isLandscape) 2 else 1
}
private fun filterListByMatch(query: String): List<OpApp> {
val filteredList = ArrayList<OpApp>()
for (app in opApps)
if (app.label.toLowerCase(Locale.getDefault()).contains(query.toLowerCase(Locale.getDefault())))
filteredList.add(app)
return filteredList
}
} | apache-2.0 | bcd5cc4ccbbaec7171094e6f2394ed2d | 38.832298 | 118 | 0.600281 | 5.415541 | false | false | false | false |
usommerl/kotlin-koans | src/i_introduction/_1_Java_To_Kotlin_Converter/JavaToKotlinConverter.kt | 1 | 502 | package i_introduction._1_Java_To_Kotlin_Converter
import util.TODO
fun todoTask1(collection: Collection<Int>): Nothing = TODO(
"""
Task 1.
Rewrite JavaCode1.task1 in Kotlin.
In IntelliJ IDEA, you can just copy-paste the code and agree to automatically convert it to Kotlin,
but only for this task!
""",
references = { JavaCode1().task1(collection) })
fun task1(collection: Collection<Int>): String = collection.joinToString(prefix = "{", postfix = "}")
| mit | 592fc94c6a3ef52df93aa79c863b3f65 | 32.466667 | 107 | 0.677291 | 4.14876 | false | false | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/record.kt | 1 | 1689 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.taskdefs.Recorder
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
fun Ant.record(
name: String? = null,
action: ActionChoices? = null,
append: Boolean? = null,
emacsmode: Boolean? = null,
loglevel: VerbosityLevelChoices? = null)
{
Recorder().execute("record") { task ->
if (name != null)
task.setName(name)
if (action != null)
task.setAction(Recorder.ActionChoices().apply { this.value = action.value })
if (append != null)
task.setAppend(append)
if (emacsmode != null)
task.setEmacsMode(emacsmode)
if (loglevel != null)
task.setLoglevel(Recorder.VerbosityLevelChoices().apply { this.value = loglevel.value })
}
}
enum class ActionChoices(val value: String) { START("start"), STOP("stop") }
enum class VerbosityLevelChoices(val value: String) { ERROR("error"), WARN("warn"), WARNING("warning"), INFO("info"), VERBOSE("verbose"), DEBUG("debug") }
| apache-2.0 | 1b38dd4defc800316a32ab2db86c776d | 34.93617 | 154 | 0.647128 | 3.84738 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/newsfeed/UserListAdapter.kt | 1 | 8021 | package mil.nga.giat.mage.newsfeed
import android.content.Context
import android.database.Cursor
import android.graphics.PorterDuff
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.recyclerview.widget.RecyclerView
import com.google.android.gms.maps.model.LatLng
import com.google.common.collect.Collections2
import com.j256.ormlite.android.AndroidDatabaseResults
import com.j256.ormlite.stmt.PreparedQuery
import mil.nga.giat.mage.R
import mil.nga.giat.mage.coordinate.CoordinateFormatter
import mil.nga.giat.mage.glide.GlideApp
import mil.nga.giat.mage.glide.model.Avatar.Companion.forUser
import mil.nga.giat.mage.sdk.datastore.location.Location
import mil.nga.giat.mage.sdk.datastore.location.LocationHelper
import mil.nga.giat.mage.sdk.datastore.user.EventHelper
import mil.nga.giat.mage.sdk.datastore.user.Team
import mil.nga.giat.mage.sdk.datastore.user.TeamHelper
import mil.nga.giat.mage.sdk.datastore.user.User
import mil.nga.giat.mage.utils.DateFormatFactory
import mil.nga.sf.util.GeometryUtils
import org.apache.commons.lang3.StringUtils
import java.sql.SQLException
import java.text.DateFormat
import java.util.*
sealed class UserAction {
class Coordinates(val location: String): UserAction()
class Email(val email: String): UserAction()
class Phone(val phone: String): UserAction()
class Directions(val user: User, val location: Location): UserAction()
}
class UserListAdapter(
private val context: Context,
userFeedState: UserFeedState,
private val userAction: (UserAction) -> Unit,
private val userClickListener: (User) -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val dateFormat: DateFormat = DateFormatFactory.format("yyyy-MM-dd HH:mm zz", Locale.getDefault(), context)
private var cursor: Cursor = userFeedState.cursor
private val query: PreparedQuery<Location> = userFeedState.query
private val filterText: String = userFeedState.filterText
private val teamHelper = TeamHelper.getInstance(context)
private val eventHelper = EventHelper.getInstance(context)
private class PersonViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val cardView: View = view.findViewById(R.id.card)
val avatarView: ImageView = view.findViewById(R.id.avatarImageView)
val nameView: TextView = view.findViewById(R.id.name)
val dateView: TextView = view.findViewById(R.id.date)
val teamsView: TextView = view.findViewById(R.id.teams)
val location: TextView = view.findViewById(R.id.location)
val locationIcon: ImageView = view.findViewById(R.id.location_icon)
val email: ImageButton = view.findViewById(R.id.email_button)
val phone: ImageButton = view.findViewById(R.id.phone_button)
val directions: ImageButton = view.findViewById(R.id.directions_button)
fun bind(user: User, listener: (User) -> Unit) {
cardView.setOnClickListener { listener.invoke(user) }
}
}
private class FooterViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val footerText: TextView = view.findViewById(R.id.footer_text)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == TYPE_USER) {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.people_list_item, parent, false)
PersonViewHolder(itemView)
} else {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.feed_footer, parent, false)
FooterViewHolder(itemView)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is PersonViewHolder -> bindUser(holder, position)
else -> bindFooter(holder)
}
}
private fun bindUser(holder: RecyclerView.ViewHolder, position: Int) {
cursor.moveToPosition(position)
val vh = holder as PersonViewHolder
try {
val location = query.mapRow(AndroidDatabaseResults(cursor, null, false))
val user = location.user ?: return
vh.bind(user, userClickListener)
val defaultPersonIcon = DrawableCompat.wrap(ContextCompat.getDrawable(context, R.drawable.ic_person_white_48dp)!!)
DrawableCompat.setTint(defaultPersonIcon, ContextCompat.getColor(context, R.color.icon))
DrawableCompat.setTintMode(defaultPersonIcon, PorterDuff.Mode.SRC_ATOP)
vh.avatarView.setImageDrawable(defaultPersonIcon)
GlideApp.with(context)
.load(forUser(user))
.fallback(defaultPersonIcon)
.error(defaultPersonIcon)
.circleCrop()
.into(vh.avatarView)
vh.nameView.text = user.displayName
val timeText = dateFormat.format(location.timestamp)
vh.dateView.text = timeText
val userTeams: MutableCollection<Team> = teamHelper.getTeamsByUser(user)
val event = eventHelper.currentEvent
val eventTeams = teamHelper.getTeamsByEvent(event)
userTeams.retainAll(eventTeams.toSet())
val teamNames = Collections2.transform(userTeams) { team: Team -> team.name }
vh.teamsView.text = StringUtils.join(teamNames, ", ")
var locationIconColor = ContextCompat.getColor(context, R.color.primary_icon)
val locations = LocationHelper.getInstance(context).getUserLocations(user.id, event.id, 1, true)
locations?.first()?.let { location: Location ->
if (location.propertiesMap["accuracy_type"]?.value == "COARSE") {
locationIconColor = ContextCompat.getColor(context, R.color.md_amber_700)
}
val point = GeometryUtils.getCentroid(location.geometry)
val coordinates = CoordinateFormatter(context).format(LatLng(point.y, point.x))
vh.location.text = coordinates
vh.location.setTextColor(locationIconColor)
vh.location.setOnClickListener { userAction(UserAction.Coordinates(coordinates)) }
vh.directions.setOnClickListener { userAction(UserAction.Directions(user, location)) }
}
val locationIcon = DrawableCompat.wrap(ContextCompat.getDrawable(context, R.drawable.ic_my_location_white_24dp)!!)
DrawableCompat.setTint(locationIcon, locationIconColor)
DrawableCompat.setTintMode(locationIcon, PorterDuff.Mode.SRC_ATOP)
vh.locationIcon.setImageDrawable(locationIcon)
if (user.email?.isNotEmpty() == true) {
vh.email.visibility = View.VISIBLE
vh.email.setOnClickListener { userAction(UserAction.Email(user.email)) }
} else {
vh.email.visibility = View.GONE
}
if (user.primaryPhone?.isNotEmpty() == true) {
vh.phone.visibility = View.VISIBLE
vh.phone.setOnClickListener { userAction(UserAction.Phone(user.primaryPhone)) }
} else {
vh.phone.visibility = View.GONE
}
} catch (e: SQLException) {
Log.e(LOG_NAME, "Could not set location view information.", e)
}
}
private fun bindFooter(holder: RecyclerView.ViewHolder) {
val vh = holder as FooterViewHolder
var footerText = "End of results"
if (filterText.isNotEmpty()) {
footerText = "End of results for $filterText"
}
vh.footerText.text = footerText
}
override fun getItemViewType(position: Int): Int {
return if (position == cursor.count) {
TYPE_FOOTER
} else {
TYPE_USER
}
}
override fun getItemCount(): Int {
return cursor.count + 1
}
companion object {
private val LOG_NAME = UserListAdapter::class.java.name
private const val TYPE_USER = 1
private const val TYPE_FOOTER = 2
}
} | apache-2.0 | 445bc2ae1a07ce8e80c1002d64e89b17 | 40.564767 | 123 | 0.708016 | 4.259692 | false | false | false | false |
samuelclay/NewsBlur | clients/android/NewsBlur/test/com/newsblur/SessionDataSourceTest.kt | 1 | 5485 | package com.newsblur
import com.newsblur.domain.Feed
import com.newsblur.util.FeedSet
import com.newsblur.util.Session
import com.newsblur.util.SessionDataSource
import org.junit.Assert
import org.junit.Test
class SessionDataSourceTest {
private val folders = listOf(
"F1",
"F2",
"F3",
"F4",
"F5",
)
private val folderChildren = listOf(
emptyList(),
listOf(
createFeed("20"),
createFeed("21"),
createFeed("22"),
),
listOf(
createFeed("30"),
),
emptyList(),
listOf(
createFeed("50"),
createFeed("51"),
)
)
@Test
fun `session constructor test`() {
val feedSet = FeedSet.singleFeed("1")
val session = Session(feedSet)
Assert.assertEquals(feedSet, session.feedSet)
Assert.assertNull(session.feed)
Assert.assertNull(session.folderName)
}
@Test
fun `session full constructor test`() {
val feedSet = FeedSet.singleFeed("10")
val feed = createFeed("10")
val session = Session(feedSet, "folderName", feed)
Assert.assertEquals(feedSet, session.feedSet)
Assert.assertEquals("folderName", session.folderName)
Assert.assertEquals(feed, session.feed)
}
@Test
fun `next session for unknown feedId`() {
val session = Session(FeedSet.singleFeed("123"))
val sessionDs = SessionDataSource(session, folders, folderChildren)
Assert.assertNull(sessionDs.getNextSession())
}
@Test
fun `next session for empty folder`() {
val feedSet = FeedSet.singleFeed("123")
val feed = createFeed("123")
val session = Session(feedSet, "F1", feed)
val sessionDs = SessionDataSource(session, folders, folderChildren)
Assert.assertNull(sessionDs.getNextSession())
}
/**
* Expected to return the next [Session] containing feed id 11
* as the second feed in folder F2 after feed id 10
*/
@Test
fun `next session for F2 feedSet`() {
val feedSet = FeedSet.singleFeed("20")
val feed = createFeed("20")
val session = Session(feedSet, "F2", feed)
val sessionDs = SessionDataSource(session, folders, folderChildren)
sessionDs.getNextSession()?.let {
Assert.assertEquals("F2", it.folderName)
Assert.assertEquals("21", it.feed?.feedId)
with(it.feedSet) {
Assert.assertNotNull(this)
Assert.assertTrue(it.feedSet.flatFeedIds.size == 1)
Assert.assertEquals("21", it.feedSet.flatFeedIds.first())
}
} ?: Assert.fail("Next session was null")
}
/**
* Expected to return a null [Session] because feed id 12
* is the last feed id in folder F2
*/
@Test
fun `next session for end of F2 feedSet`() {
val feedSet = FeedSet.singleFeed("22")
val feed = createFeed("22")
val session = Session(feedSet, "F2", feed)
val sessionDs = SessionDataSource(session, folders, folderChildren)
Assert.assertNull(sessionDs.getNextSession())
}
@Test
fun `next session for F2 feedSetFolder`() {
val feedSet = FeedSet.folder("F2", setOf("21"))
val feed = createFeed("21")
val session = Session(feedSet, "F2", feed)
val sessionDs = SessionDataSource(session, folders, folderChildren)
sessionDs.getNextSession()?.let {
Assert.assertNull(it.feed)
Assert.assertEquals("F3", it.folderName)
Assert.assertEquals("F3", it.feedSet.folderName)
Assert.assertEquals("30", it.feedSet.flatFeedIds.firstOrNull())
} ?: Assert.fail("Next session is null for F2 feedSetFolder")
}
/**
* Expected to return folder "F5" because folder "F3"
* doesn't have any feeds
*/
@Test
fun `next session for F3 feedSetFolder`() {
val feedSet = FeedSet.folder("F3", setOf("30"))
val feed = createFeed("30")
val session = Session(feedSet, "F3", feed)
val sessionDs = SessionDataSource(session, folders, folderChildren)
sessionDs.getNextSession()?.let {
Assert.assertNull(it.feed)
Assert.assertEquals("F5", it.folderName)
Assert.assertEquals("F5", it.feedSet.folderName)
Assert.assertEquals("50", it.feedSet.flatFeedIds.firstOrNull())
} ?: Assert.fail("Next session is null for F5 feedSetFolder")
}
/**
* Expected to return session for F1 feedSetFolder
*/
@Test
fun `next session for F5 feedSetFolder`() {
val feedSet = FeedSet.folder("F5", setOf("50"))
val feed = createFeed("50")
val session = Session(feedSet, "F5", feed)
val sessionDs = SessionDataSource(session, folders, folderChildren)
sessionDs.getNextSession()?.let {
Assert.assertNull(it.feed)
Assert.assertEquals("F2", it.folderName)
Assert.assertEquals("F2", it.feedSet.folderName)
Assert.assertEquals(setOf("20", "21", "22"), it.feedSet.flatFeedIds)
} ?: Assert.fail("Next session is null for F5 feedSetFolder")
}
private fun createFeed(id: String) = Feed().apply {
feedId = id
title = "Feed #$id"
}
} | mit | a62fc836380650db8bdccbfc15b2952e | 32.248485 | 80 | 0.59289 | 4.199847 | false | true | false | false |
Shynixn/PetBlocks | petblocks-bukkit-plugin/petblocks-bukkit-nms-113R2/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_13_R2/NMSPetRabbit.kt | 1 | 4717 | package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_13_R2
import com.github.shynixn.petblocks.api.PetBlocksApi
import com.github.shynixn.petblocks.api.business.proxy.PathfinderProxy
import com.github.shynixn.petblocks.api.business.service.ConcurrencyService
import com.github.shynixn.petblocks.api.persistence.entity.AIMovement
import net.minecraft.server.v1_13_R2.*
import org.bukkit.Location
import org.bukkit.craftbukkit.v1_13_R2.CraftWorld
import org.bukkit.event.entity.CreatureSpawnEvent
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
class NMSPetRabbit(petDesign: NMSPetArmorstand, location: Location) : EntityRabbit((location.world as CraftWorld).handle) {
private var petDesign: NMSPetArmorstand? = null
private var pathfinderCounter = 0
init {
this.petDesign = petDesign
this.isSilent = true
clearAIGoals()
this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).value = 0.30000001192092896 * 0.75
this.Q = 1.0F
val mcWorld = (location.world as CraftWorld).handle
this.setPosition(location.x, location.y - 200, location.z)
mcWorld.addEntity(this, CreatureSpawnEvent.SpawnReason.CUSTOM)
val targetLocation = location.clone()
PetBlocksApi.resolve(ConcurrencyService::class.java).runTaskSync(20L) {
// Only fix location if it is not already fixed.
if (this.bukkitEntity.location.distance(targetLocation) > 20) {
this.setPosition(targetLocation.x, targetLocation.y + 1.0, targetLocation.z)
}
}
}
/**
* Applies pathfinders to the entity.
*/
fun applyPathfinders(pathfinders: List<Any>) {
clearAIGoals()
for (pathfinder in pathfinders) {
if (pathfinder is PathfinderProxy) {
this.goalSelector.a(pathfinderCounter++, Pathfinder(pathfinder))
val aiBase = pathfinder.aiBase
if (aiBase is AIMovement) {
this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).value = 0.30000001192092896 * aiBase.movementSpeed
this.Q = aiBase.climbingHeight.toFloat()
}
} else {
this.goalSelector.a(pathfinderCounter++, pathfinder as PathfinderGoal)
}
}
}
/**
* Gets called on move to play sounds.
*/
override fun a(blockposition: BlockPosition, iblockdata: IBlockData) {
if (petDesign == null) {
return
}
if (!this.isInWater) {
petDesign!!.proxy.playMovementEffects()
}
}
/**
* Disable health.
*/
override fun setHealth(f: Float) {
}
/**
* Gets the bukkit entity.
*/
override fun getBukkitEntity(): CraftPet {
if (this.bukkitEntity == null) {
this.bukkitEntity = CraftPet(this.world.server, this)
}
return this.bukkitEntity as CraftPet
}
/**
* Clears all entity aiGoals.
*/
private fun clearAIGoals() {
val bField = PathfinderGoalSelector::class.java.getDeclaredField("b")
bField.isAccessible = true
(bField.get(this.goalSelector) as MutableSet<*>).clear()
(bField.get(this.targetSelector) as MutableSet<*>).clear()
val cField = PathfinderGoalSelector::class.java.getDeclaredField("c")
cField.isAccessible = true
(cField.get(this.goalSelector) as MutableSet<*>).clear()
(cField.get(this.targetSelector) as MutableSet<*>).clear()
}
} | apache-2.0 | 0a480447b29b278244670d8deac4d2d7 | 35.292308 | 130 | 0.669917 | 4.319597 | false | false | false | false |
macrat/RuuMusic | app/src/main/java/jp/blanktar/ruumusic/service/MediaSessionEndpoint.kt | 1 | 8967 | package jp.blanktar.ruumusic.service
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.session.PlaybackState
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.view.KeyEvent
import jp.blanktar.ruumusic.R
import jp.blanktar.ruumusic.client.main.MainActivity
import jp.blanktar.ruumusic.util.EqualizerInfo
import jp.blanktar.ruumusic.util.PlayingStatus
import jp.blanktar.ruumusic.util.Preference
import jp.blanktar.ruumusic.util.RepeatModeType
import jp.blanktar.ruumusic.util.RuuFileBase
class MediaSessionEndpoint(val context: Context, controller: RuuService.Controller, initialStatus: PlayingStatus, initialPlaylist: Playlist?) : Endpoint {
override val supported = true
val preference
get() = Preference(context)
val mediaSession: MediaSessionCompat
val sessionToken: MediaSessionCompat.Token
get() = mediaSession.sessionToken
private var queueIndex: Long = 0
init {
val componentName = ComponentName(context.packageName, MediaButtonReceiver::class.java.name)
val mediaButtonIntent = Intent(Intent.ACTION_MEDIA_BUTTON)
mediaButtonIntent.component = componentName
val openPlayerIntent = Intent(context, MainActivity::class.java)
openPlayerIntent.action = MainActivity.ACTION_OPEN_PLAYER
onStatusUpdated(initialStatus)
if (initialPlaylist != null) {
updateQueue(initialPlaylist)
}
mediaSession = MediaSessionCompat(context, "RuuMusicService", componentName, PendingIntent.getBroadcast(context, 0, mediaButtonIntent, 0)).apply {
setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS or MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS)
setSessionActivity(PendingIntent.getActivity(context, 0, openPlayerIntent, 0))
isActive = true
setCallback(callbacks)
}
}
override fun close() = mediaSession.release()
override fun onStatusUpdated(status: PlayingStatus) {
updateMetadata(status)
updatePlaybackState(status)
}
override fun onEqualizerInfo(info: EqualizerInfo) {}
override fun onFailedPlay(status: PlayingStatus) {
onError(context.getString(R.string.failed_play, status.currentMusic?.realPath), status)
}
override fun onError(message: String, status: PlayingStatus) {
updateMetadata(status)
updatePlaybackState(status, message)
}
override fun onEndOfList(isFirst: Boolean, status: PlayingStatus) {
onError(context.getString(if (isFirst) R.string.first_of_directory else R.string.last_of_directory, status.currentMusic?.realPath), status)
}
private val displayIcon = BitmapFactory.decodeResource(context.resources, R.drawable.display_icon)
private fun updateMetadata(status: PlayingStatus) {
val parentPath = try {
status.currentMusic?.parent?.ruuPath ?: ""
} catch (e: RuuFileBase.OutOfRootDirectory) {
""
}
val metadata = MediaMetadataCompat.Builder().apply {
putString(MediaMetadataCompat.METADATA_KEY_ALBUM, parentPath)
putString(MediaMetadataCompat.METADATA_KEY_TITLE, status.currentMusic?.name)
putBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON, displayIcon)
putLong(MediaMetadataCompat.METADATA_KEY_DURATION, status.duration)
}.build()
mediaSession.setMetadata(metadata)
}
private fun updatePlaybackState(status: PlayingStatus, error: String? = null) {
val state = PlaybackStateCompat.Builder().apply {
setState(
if (status.playing) PlaybackStateCompat.STATE_PLAYING else PlaybackStateCompat.STATE_PAUSED,
if (status.currentMusic != null) status.receivedCurrentTime else PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN,
1.0f
)
setActiveQueueItemId(queueIndex)
setActions(
PlaybackStateCompat.ACTION_PLAY
or PlaybackStateCompat.ACTION_PAUSE
or PlaybackStateCompat.ACTION_PLAY_PAUSE
or PlaybackStateCompat.ACTION_STOP
or PlaybackStateCompat.ACTION_SKIP_TO_NEXT
or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
or PlaybackStateCompat.ACTION_SET_REPEAT_MODE
or PlaybackStateCompat.ACTION_SET_SHUFFLE_MODE
or PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID
or PlaybackStateCompat.ACTION_PLAY_FROM_URI
or PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH
)
if (error != null && error != "") {
setErrorMessage(PlaybackStateCompat.ERROR_CODE_UNKNOWN_ERROR, error)
setState(
PlaybackStateCompat.STATE_ERROR,
if (status.currentMusic != null) status.receivedCurrentTime else PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN,
1.0f
)
}
}.build()
mediaSession.setPlaybackState(state)
mediaSession.setShuffleMode(if (status.shuffleMode) PlaybackStateCompat.SHUFFLE_MODE_ALL else PlaybackStateCompat.SHUFFLE_MODE_NONE)
mediaSession.setRepeatMode(when (status.repeatMode) {
RepeatModeType.OFF -> PlaybackStateCompat.REPEAT_MODE_NONE
RepeatModeType.SINGLE -> PlaybackStateCompat.REPEAT_MODE_ONE
RepeatModeType.LOOP -> PlaybackStateCompat.REPEAT_MODE_ALL
})
}
fun updateQueue(playlist: Playlist) {
queueIndex = playlist.queueIndex.toLong()
mediaSession.setQueue(playlist.mediaSessionQueue)
mediaSession.setQueueTitle(playlist.title)
}
private val callbacks = object : MediaSessionCompat.Callback() {
override fun onPlay() = controller.play()
override fun onPlayFromMediaId(mediaId: String?, extras: Bundle?) {
mediaId?.let { controller.play(it) }
}
override fun onPlayFromUri(uri: Uri, extras: Bundle) = controller.play(uri.path)
override fun onPlayFromSearch(query: String?, extras: Bundle?) {
val defaultPath = preference.RootDirectory.get()?.fullPath
extras?.getCharSequence("path", defaultPath)?.toString()?.let {
controller.playSearch(it, query)
}
}
override fun onSkipToQueueItem(id: Long) = controller.play(id)
override fun onPause() = controller.pause()
override fun onStop() = controller.pause()
override fun onSkipToNext() = controller.next()
override fun onSkipToPrevious() = controller.prev()
override fun onSeekTo(pos: Long) = controller.seek(pos)
override fun onSetRepeatMode(repeatMode: Int) {
controller.setRepeatMode(when (repeatMode) {
PlaybackStateCompat.REPEAT_MODE_ONE -> RepeatModeType.SINGLE
PlaybackStateCompat.REPEAT_MODE_ALL -> RepeatModeType.LOOP
else -> RepeatModeType.OFF
})
}
override fun onSetShuffleMode(shuffleMode: Int) {
controller.setShuffleMode(shuffleMode != PlaybackStateCompat.SHUFFLE_MODE_NONE)
}
}
class MediaButtonReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Intent.ACTION_MEDIA_BUTTON) {
val keyEvent = intent.getParcelableExtra<KeyEvent>(Intent.EXTRA_KEY_EVENT)
if (keyEvent?.action != KeyEvent.ACTION_UP) {
return
}
when (keyEvent.keyCode) {
KeyEvent.KEYCODE_MEDIA_PLAY -> sendIntent(context, RuuService.ACTION_PLAY)
KeyEvent.KEYCODE_MEDIA_PAUSE -> sendIntent(context, RuuService.ACTION_PAUSE)
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, KeyEvent.KEYCODE_HEADSETHOOK -> sendIntent(context, RuuService.ACTION_PLAY_PAUSE)
KeyEvent.KEYCODE_MEDIA_NEXT -> sendIntent(context, RuuService.ACTION_NEXT)
KeyEvent.KEYCODE_MEDIA_PREVIOUS -> sendIntent(context, RuuService.ACTION_PREV)
}
}
}
private fun sendIntent(context: Context, event: String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(Intent(context, RuuService::class.java).setAction(event))
} else {
context.startService(Intent(context, RuuService::class.java).setAction(event))
}
}
}
}
| mit | 67eda5b25b9bbd0b4a91fa792ea3148c | 40.706977 | 154 | 0.671462 | 4.844408 | false | false | false | false |
shaeberling/euler | kotlin/src/com/s13g/aoc/aoc2020/Day1.kt | 1 | 688 | package com.s13g.aoc.aoc2020
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
/**
* --- Day 1: Report Repair ---
* https://adventofcode.com/2020/day/1
*/
class Day1 : Solver {
override fun solve(lines: List<String>): Result {
val (resultA, resultB) = run(lines.map { it.toLong() }.toHashSet())
return Result("$resultA", "$resultB")
}
private fun run(input: Set<Long>, year: Int = 2020): Array<Long> {
val result = arrayOf(0L, 0L)
for (i in input) {
if (input.contains(year - i)) result[0] = i * (year - i)
for (j in input) {
if (input.contains(year - (i + j))) result[1] = i * j * (year - (i + j))
}
}
return result
}
} | apache-2.0 | d881e5a9607708f5fa81c09f92c26bfe | 25.5 | 80 | 0.585756 | 3.004367 | false | false | false | false |
wasabeef/recyclerview-animators | animators/src/main/java/jp/wasabeef/recyclerview/animators/LandingAnimator.kt | 1 | 1747 | package jp.wasabeef.recyclerview.animators
import android.view.animation.Interpolator
import androidx.recyclerview.widget.RecyclerView
/**
* Copyright (C) 2021 Daichi Furiya / Wasabeef
*
* 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.
*/
open class LandingAnimator : BaseItemAnimator {
constructor()
constructor(interpolator: Interpolator) {
this.interpolator = interpolator
}
override fun animateRemoveImpl(holder: RecyclerView.ViewHolder) {
holder.itemView.animate().apply {
alpha(0f)
.scaleX(1.5f)
.scaleY(1.5f)
duration = removeDuration
interpolator = interpolator
setListener(DefaultRemoveAnimatorListener(holder))
startDelay = getRemoveDelay(holder)
}.start()
}
override fun preAnimateAddImpl(holder: RecyclerView.ViewHolder) {
holder.itemView.alpha = 0f
holder.itemView.scaleX = 1.5f
holder.itemView.scaleY = 1.5f
}
override fun animateAddImpl(holder: RecyclerView.ViewHolder) {
holder.itemView.animate().apply {
alpha(1f)
scaleX(1f)
scaleY(1f)
duration = addDuration
interpolator = interpolator
setListener(DefaultAddAnimatorListener(holder))
startDelay = getAddDelay(holder)
}.start()
}
}
| apache-2.0 | 1d1620b8d785023ef15356c9e7cdd46c | 30.196429 | 75 | 0.721809 | 4.271394 | false | false | false | false |
vyo/strakh | src/main/kotlin/io/github/vyo/strakh/model/game/Resources.kt | 1 | 3015 | package io.github.vyo.strakh.model.game
import bwapi.Unit
import bwapi.UnitType
/**
* Created by Manuel Weidmann on 23.11.2015.
*/
object Resources : State() {
var minerals: MutableList<Unit> = arrayListOf()
var geysers: MutableList<Unit> = arrayListOf()
var refineries: MutableList<Unit> = arrayListOf()
data class ResourceSpot(var resource: Unit?, var nearby: Boolean = false, var
saturated: Boolean = false, var hasRefinery: Boolean = false)
fun nearestMineralPatch(worker: Unit): ResourceSpot {
//find the closest mineral
var closestPatch: bwapi.Unit? = null
for (mineralPatch in minerals) {
if (closestPatch == null || worker.getDistance(mineralPatch) < worker.getDistance(closestPatch)) {
closestPatch = mineralPatch
}
}
val nearby = true
val saturated = false
return ResourceSpot(closestPatch, nearby, saturated)
// if (closestMineral is Unit) return closestMineral
// else throw UnsupportedOperationException()
}
fun nearestGeyser(worker: bwapi.Unit): ResourceSpot {
//find the closest geyser
var closestGeyser: bwapi.Unit? = null
for (geyser in geysers) {
if (closestGeyser == null || worker.getDistance(geyser) < worker.getDistance(closestGeyser)) {
closestGeyser = geyser
}
}
val nearby = true
val saturated = true
return ResourceSpot(closestGeyser, nearby, saturated)
// return false
}
fun nearestRefinery(worker: Unit): ResourceSpot {
//find the closest refinery
var closestRefinery: bwapi.Unit? = null
for (refinery in refineries) {
if (closestRefinery == null || worker.getDistance(refinery) < worker.getDistance(closestRefinery)) {
closestRefinery = refinery
}
}
val nearby = true
val saturated = true
return ResourceSpot(closestRefinery, nearby, saturated)
// return false
}
override fun update() {
//TODO: update re-actively instead of looping each frame
//update mineral patches
minerals.clear()
for (patch in World.units.neutral) {
if (patch.type == UnitType.Resource_Mineral_Field
|| patch.type == UnitType.Resource_Mineral_Field_Type_2
|| patch.type == UnitType.Resource_Mineral_Field_Type_3) {
minerals.add(patch)
}
}
//update vespene geysers
geysers.clear()
for (geyser in World.units.neutral) {
if (geyser.type == UnitType.Resource_Vespene_Geyser) {
geysers.add(geyser)
}
}
//update refineries
refineries.clear()
for (refinery in World.units.own) {
if (refinery.type.isRefinery) {
refineries.add(refinery)
}
}
}
} | mit | 1bd96ecd84e9064903c2fd68a978b5a3 | 32.511111 | 112 | 0.591708 | 4.135802 | false | false | false | false |
Ekito/koin | koin-projects/examples/androidx-samples/src/main/java/org/koin/sample/androidx/components/Constants.kt | 2 | 291 | package org.koin.sample.androidx.components
const val APP_TITLE = "Android Samples Demo"
const val ID = "42"
const val SCOPE_ID = "SCOPE_ID"
const val SCOPE_SESSION = "SCOPE_SESSION"
const val SESSION_1 = "session1"
const val SESSION_2 = "session2"
object Counter {
var released = 0
} | apache-2.0 | f866cb786d67ad7df2596d875b1c260b | 21.461538 | 44 | 0.725086 | 3.233333 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/addons/mappers/RemoteAddonOptionDtoMapper.kt | 2 | 1312 | package org.wordpress.android.fluxc.network.rest.wpcom.wc.addons.mappers
import org.wordpress.android.fluxc.domain.Addon
import org.wordpress.android.fluxc.model.addons.RemoteAddonDto.RemotePriceType.FlatFee
import org.wordpress.android.fluxc.model.addons.RemoteAddonDto.RemotePriceType.PercentageBased
import org.wordpress.android.fluxc.model.addons.RemoteAddonDto.RemotePriceType.QuantityBased
import org.wordpress.android.fluxc.model.addons.RemoteAddonDto.RemoteOption
object RemoteAddonOptionDtoMapper {
fun toDomainModel(dto: RemoteOption): Addon.HasOptions.Option {
return Addon.HasOptions.Option(
label = dto.label,
image = dto.image,
price = dto.mapPrice()
)
}
private fun RemoteOption.mapPrice(): Addon.HasAdjustablePrice.Price.Adjusted {
return Addon.HasAdjustablePrice.Price.Adjusted(
priceType = when (this.priceType) {
FlatFee -> Addon.HasAdjustablePrice.Price.Adjusted.PriceType.FlatFee
QuantityBased -> Addon.HasAdjustablePrice.Price.Adjusted.PriceType.QuantityBased
PercentageBased -> Addon.HasAdjustablePrice.Price.Adjusted.PriceType.PercentageBased
},
value = this.price.orEmpty()
)
}
}
| gpl-2.0 | 9abbbf86b63232ff08ed680263b16a00 | 45.857143 | 104 | 0.707317 | 4.25974 | false | false | false | false |
google/chromeosnavigationdemo | app/src/main/java/com/emilieroberts/chromeosnavigationdemo/FilesAdapter.kt | 1 | 4299 | /*
* 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.emilieroberts.chromeosnavigationdemo
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import java.text.SimpleDateFormat
import java.util.*
class FilesAdapter (private val actionsListener: RecyclerViewFileActionsListener) :
ListAdapter<PhotoFile, FilesAdapter.PhotoFileViewHolder> (DIFF_CALLBACK) {
override fun getItemViewType(position: Int): Int {
return if (0 == position) {
LIST_HEADER
} else {
LIST_ITEM
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotoFileViewHolder {
val layoutResource = when(viewType) {
LIST_HEADER -> R.layout.recycler_item_list_header
else -> R.layout.recycler_item_list
}
val view = LayoutInflater.from(parent.context).inflate(layoutResource, parent, false) as LinearLayout
if (viewType == LIST_HEADER) view.setFocusable(false)
return PhotoFileViewHolder(view, actionsListener)
}
override fun onBindViewHolder(holder: PhotoFileViewHolder, position: Int) {
holder.bind(getItem(position))
}
override fun onViewDetachedFromWindow(holder: PhotoFileViewHolder) {
if (holder.itemViewType != LIST_HEADER) holder.clearAllViews()
}
class PhotoFileViewHolder (private val view: View, private val actionsListener: RecyclerViewFileActionsListener) :
RecyclerView.ViewHolder (view), View.OnClickListener, View.OnFocusChangeListener {
private val fileTitle: TextView = view.findViewById(R.id.file_title)
private val fileSize: TextView = view.findViewById(R.id.file_filesize)
private val fileDate: TextView? = view.findViewById(R.id.file_date)
lateinit var file: PhotoFile
fun bind(fileToShow: PhotoFile) {
view.onFocusChangeListener = this
view.setOnClickListener(this)
file = fileToShow
if (file.imageId != 0) {
fileTitle.text = file.title
fileSize.text = file.filesize
fileDate?.text = dateFormat(file.date)
}
}
fun clearAllViews() {
fileTitle.text = EMPTY_STRING
fileDate?.text = EMPTY_STRING
fileSize.text = EMPTY_STRING
}
override fun onClick(v: View?) {
actionsListener.onListItemClick(this.adapterPosition, file.imageId)
}
override fun onFocusChange(v: View?, hasFocus: Boolean) {
if (hasFocus) actionsListener.onListItemFocus(file.imageId)
}
private fun dateFormat(date: Date) : String {
return DATE_FORMATTER.format(date)
}
}
companion object {
private const val LIST_HEADER = 0
private const val LIST_ITEM = 1
private const val EMPTY_STRING = ""
private val DATE_FORMATTER = SimpleDateFormat("dd MMM YYYY")
private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<PhotoFile> () {
override fun areItemsTheSame(oldItem: PhotoFile, newItem: PhotoFile): Boolean {
return oldItem.imageId == newItem.imageId
}
override fun areContentsTheSame(oldItem: PhotoFile, newItem: PhotoFile): Boolean {
return false
}
}
}
interface RecyclerViewFileActionsListener {
fun onListItemClick(position: Int, fileId: Int)
fun onListItemFocus(imageId: Int)
}
}
| apache-2.0 | e219decb32b3c060807e1c68f9072ada | 34.237705 | 118 | 0.672017 | 4.771365 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/command/executors/fun/CommandSelfroles.kt | 1 | 6433 | package me.mrkirby153.KirBot.command.executors.`fun`
import me.mrkirby153.KirBot.command.CommandCategory
import me.mrkirby153.KirBot.command.CommandException
import me.mrkirby153.KirBot.command.annotations.Command
import me.mrkirby153.KirBot.command.annotations.CommandDescription
import me.mrkirby153.KirBot.command.annotations.IgnoreWhitelist
import me.mrkirby153.KirBot.command.args.CommandContext
import me.mrkirby153.KirBot.user.CLEARANCE_ADMIN
import me.mrkirby153.KirBot.utils.Context
import me.mrkirby153.KirBot.utils.FuzzyMatchException
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.Role
class CommandSelfroles {
@Command(name = "selfrole", category = CommandCategory.UTILITY)
@CommandDescription("Displays a list of self-assignable roles")
fun execute(context: Context, cmdContext: CommandContext) {
var msg = "Self-assignable roles are:\n```\n"
val selfroles = context.kirbotGuild.getSelfroles()
selfroles.mapNotNull {
context.guild.getRoleById(it)
}.forEach {
msg += "\n${it.id} - ${it.name}"
if (msg.length > 1900) {
msg += "```"
context.channel.sendMessage(msg).queue()
msg = "```"
}
}
msg += "```"
context.channel.sendMessage(msg).queue()
}
@Command(name = "join", arguments = ["<role:string...>"], parent = "selfrole", category = CommandCategory.UTILITY, permissions = [Permission.MANAGE_ROLES])
@CommandDescription("Join a self-assignable role")
fun join(context: Context, cmdContext: CommandContext) {
val role = cmdContext.get<String>("role")!!
val foundRole = findSelfassignRole(context, role)
if (foundRole.id in context.member!!.roles.map { it.id })
throw CommandException("You are already in `${foundRole.name}`")
if (foundRole.position >= context.guild.selfMember.roles.sortedByDescending { it.position }.first().position)
throw CommandException(
"That role is above my highest role. I can't assign that to you!")
context.guild.addRoleToMember(context.member!!, foundRole).queue()
context.send().success("Joined role `${foundRole.name}`", true).queue()
}
@Command(name = "leave", arguments = ["<role:string...>"], parent = "selfrole", category = CommandCategory.UTILITY, permissions = [Permission.MANAGE_PERMISSIONS])
@CommandDescription("Leave a self-assignable role")
fun leave(context: Context, cmdContext: CommandContext) {
val role = cmdContext.get<String>("role")!!
val foundRole = findSelfassignRole(context, role)
if (foundRole.id !in context.member!!.roles.map { it.id })
throw CommandException("You are not in `${foundRole.name}`")
if (foundRole.position >= context.guild.selfMember.roles.sortedByDescending { it.position }.first().position)
throw CommandException(
"That role is above my highest role. I can't remove that from you!")
context.guild.addRoleToMember(context.member!!, foundRole).queue()
context.send().success("Left role `${foundRole.name}`", true).queue()
}
@Command(name = "add", arguments = ["<role:string...>"], clearance = CLEARANCE_ADMIN,
parent = "selfrole", category = CommandCategory.UTILITY)
@CommandDescription("Add a role to the list of self-assignable roles")
@IgnoreWhitelist
fun add(context: Context, cmdContext: CommandContext) {
try {
val role = cmdContext.get<String>("role")!!
val foundRole = context.kirbotGuild.matchRole(role) ?: throw CommandException(
"No role was found for that query")
if (foundRole.id in context.kirbotGuild.getSelfroles())
throw CommandException("`${foundRole.name}` already is a selfrole!")
context.kirbotGuild.createSelfrole(foundRole.id)
context.send().success(
"Added `${foundRole.name}` to the list of self assignable roles!").queue()
} catch (e: FuzzyMatchException.TooManyMatchesException) {
throw CommandException(
"Too many matches for that query. Try a more specific query or the role's id instead")
} catch (e: FuzzyMatchException.NoMatchesException) {
throw CommandException("No role was found for that query")
}
}
@Command(name = "remove", arguments = ["<role:string...>"], clearance = CLEARANCE_ADMIN,
parent = "selfrole", category = CommandCategory.UTILITY)
@CommandDescription("Removes a role from the list of self-assignable roles")
@IgnoreWhitelist
fun remove(context: Context, cmdContext: CommandContext) {
val role = cmdContext.get<String>("role")!!
try {
val foundRole = context.kirbotGuild.matchRole(role) ?: throw CommandException(
"No role was found for that query")
if (foundRole.id !in context.kirbotGuild.getSelfroles())
throw CommandException("`${foundRole.name}` isn't a selfrole!")
context.kirbotGuild.removeSelfrole(foundRole.id)
context.send().success(
"Removed `${foundRole.name}` from the list of self assignable roles!").queue()
} catch (e: FuzzyMatchException.TooManyMatchesException) {
throw CommandException(
"Too many matches for that query. Try a more specific query or the role's id instead")
} catch (e: FuzzyMatchException.NoMatchesException) {
throw CommandException("No role was found for that query")
}
}
private fun findSelfassignRole(context: Context, query: String): Role {
try {
val foundRole = context.kirbotGuild.matchRole(query)
if (foundRole == null || foundRole.id !in context.kirbotGuild.getSelfroles())
throw CommandException("No self-assignable role was found with that query")
return foundRole
} catch (e: FuzzyMatchException.TooManyMatchesException) {
throw CommandException(
"Too many roles were found for the query. Try a more specific query or the role id")
} catch (e: FuzzyMatchException.NoMatchesException) {
throw CommandException("No role was found for that query")
}
}
} | mit | ef4e709187d676cd44d10745a8d6bdbd | 51.737705 | 166 | 0.652728 | 4.52391 | false | false | false | false |
OurFriendIrony/MediaNotifier | app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/AbstractClient.kt | 1 | 1895 | package uk.co.ourfriendirony.medianotifier.clients
import android.util.Log
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
abstract class AbstractClient {
@Throws(IOException::class)
protected fun httpGetRequest(url: String): String {
val client = OkHttpClient()
val req: Request = Request.Builder()
.url(url)
.addHeader("User-Agent", "MediaNotifier/1.0.0 ( [email protected] )")
.build()
while (true) {
client.newCall(req).execute().use { res ->
val payload = res.body!!.string()
val statusCode = res.code
val headers = parseHeaders(res)
logResponse(url, payload, headers, statusCode)
if (statusCode == 200) {
return payload
} else {
// TODO: This is 100% unacceptable implementation for a production release product
sleep()
}
}
}
}
private fun logResponse(url: String, payload: String, headers: String, statusCode: Int) {
Log.d("[REQUEST URL]", url)
Log.d("[RESPONSE PAYLOAD]", payload)
Log.d("[RESPONSE HEADERS]", headers)
Log.d("[RESPONSE STATUSC]", statusCode.toString())
}
private fun sleep(time: Int = SLEEP) {
try {
Thread.sleep((time * 1000).toLong())
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
private fun parseHeaders(res: Response): String {
val builder = StringBuilder()
for (name in res.headers.names()) {
builder.append(name).append(":").append(res.headers[name]).append("|")
}
return builder.toString()
}
companion object {
private const val SLEEP = 1
}
} | apache-2.0 | e9c7c1f38280a7a5fbb9cedfb07a0ac9 | 31.135593 | 102 | 0.565172 | 4.65602 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/formatter/RsAlignmentStrategy.kt | 5 | 2967 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.formatter
import com.intellij.formatting.Alignment
import com.intellij.lang.ASTNode
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
interface RsAlignmentStrategy {
/**
* Requests current strategy for alignment to use for given child.
*/
fun getAlignment(child: ASTNode, parent: ASTNode?, childCtx: RsFmtContext): Alignment?
/**
* Always returns `null`.
*/
object NullStrategy : RsAlignmentStrategy {
override fun getAlignment(child: ASTNode, parent: ASTNode?, childCtx: RsFmtContext): Alignment? = null
}
/**
* Apply this strategy only when child element is in [tt].
*/
fun alignIf(vararg tt: IElementType): RsAlignmentStrategy = alignIf(TokenSet.create(*tt))
/**
* Apply this strategy only when child element type matches [filterSet].
*/
fun alignIf(filterSet: TokenSet): RsAlignmentStrategy =
object : RsAlignmentStrategy {
override fun getAlignment(child: ASTNode, parent: ASTNode?, childCtx: RsFmtContext): Alignment? =
if (child.elementType in filterSet) {
[email protected](child, parent, childCtx)
} else {
null
}
}
/**
* Apply this strategy only when [predicate] passes.
*/
fun alignIf(predicate: (child: ASTNode, parent: ASTNode?, ctx: RsFmtContext) -> Boolean): RsAlignmentStrategy =
object : RsAlignmentStrategy {
override fun getAlignment(child: ASTNode, parent: ASTNode?, childCtx: RsFmtContext): Alignment? =
if (predicate(child, parent, childCtx)) {
[email protected](child, parent, childCtx)
} else {
null
}
}
/**
* Returns [NullStrategy] if [condition] is `false`. Useful for making strategies configurable.
*/
fun alignIf(condition: Boolean): RsAlignmentStrategy =
if (condition) {
this
} else {
NullStrategy
}
companion object {
/**
* Always returns [alignment].
*/
fun wrap(alignment: Alignment = Alignment.createAlignment()): RsAlignmentStrategy =
object : RsAlignmentStrategy {
override fun getAlignment(child: ASTNode, parent: ASTNode?, childCtx: RsFmtContext): Alignment? =
alignment
}
/**
* Always returns [RsFmtContext.sharedAlignment]
*/
fun shared(): RsAlignmentStrategy =
object : RsAlignmentStrategy {
override fun getAlignment(child: ASTNode, parent: ASTNode?, childCtx: RsFmtContext): Alignment? =
childCtx.sharedAlignment
}
}
}
| mit | 8ba0f11c9b8b2e7cc1c9c7198b95d1df | 33.5 | 115 | 0.608696 | 5.17801 | false | false | false | false |
wuseal/JsonToKotlinClass | src/main/kotlin/wu/seal/jsontokotlin/feedback/PersistCache.kt | 1 | 1997 | package wu.seal.jsontokotlin.feedback
import java.io.File
import java.util.Date
/**
*
* Created by Seal.Wu on 2017/9/25.
*/
interface IPersistCache {
fun saveExceptionInfo(exceptionInfo: String)
fun readAllCachedExceptionInfo(): String
fun deleteAllExceptionInfoCache()
fun saveActionInfo(actionInfo: String)
fun readAllCachedActionInfo(): String
fun deleteAllActionInfo()
}
object PersistCache : IPersistCache {
private val rootDir = "${DefaultCacheDirProvider().get()}/.jsontokotlin"
private val exceptionDirPath = "$rootDir/exceptionLog"
private val actionInfoPath = "$rootDir/actionInfo"
private val exceptionDir = File(exceptionDirPath)
private val actionDir = File(actionInfoPath)
init {
if (!exceptionDir.exists()) {
exceptionDir.mkdirs()
}
if (!actionDir.exists()) {
actionDir.mkdirs()
}
}
override fun saveExceptionInfo(exceptionInfo: String) {
File(exceptionDir, Date().time.toString()).writeText(exceptionInfo)
}
override fun readAllCachedExceptionInfo(): String {
val builder = StringBuilder()
exceptionDir.listFiles()?.forEach {
if (it.exists()) {
builder.append(it.readText()).append("#")
}
}
return builder.toString()
}
override fun deleteAllExceptionInfoCache() {
exceptionDir.listFiles()?.forEach { it.delete() }
}
override fun saveActionInfo(actionInfo: String) {
File(actionDir, Date().time.toString()).writeText(actionInfo)
}
override fun readAllCachedActionInfo(): String {
val builder = StringBuilder()
actionDir.listFiles()?.forEach {
if (it.exists()) {
builder.append(it.readText()).append("#")
}
}
return builder.toString()
}
override fun deleteAllActionInfo() {
actionDir.listFiles()?.forEach { it.delete() }
}
}
| gpl-3.0 | 1a75da6346a692bde9775234def9f986 | 23.060241 | 76 | 0.629945 | 4.633411 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/intentions/ToggleIgnoreTestIntention.kt | 1 | 1355 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.ext.findOuterAttr
import org.rust.lang.core.psi.ext.isTest
class ToggleIgnoreTestIntention: RsElementBaseIntentionAction<ToggleIgnoreTestIntention.Context>() {
data class Context(
val element: RsFunction
)
override fun getText() = "Toggle ignore for tests"
override fun getFamilyName() = text
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
val function = element.parent as? RsFunction ?: return null
if (!function.isTest) return null
return Context(function)
}
override fun invoke(project: Project, editor: Editor, ctx: Context) {
val ignore = ctx.element.findOuterAttr("ignore")
if (ignore == null) {
val ignore = RsPsiFactory(project).createOuterAttr("ignore")
val test = ctx.element.findOuterAttr("test")
ctx.element.addBefore(ignore, test)
} else {
ignore.delete()
}
}
}
| mit | 5953094a59fb7701b2cfd3a015c340b3 | 32.04878 | 105 | 0.698155 | 4.221184 | false | true | false | false |
vitalybe/radio-stream | app/android/app/src/main/java/com/radiostream/ui/BluetoothUI.kt | 1 | 4816 | package com.radiostream.ui
import android.content.Intent
import android.media.MediaMetadata
import android.media.session.MediaSession
import android.media.session.PlaybackState
import android.view.KeyEvent
import com.radiostream.javascript.bridge.PlayerEventsEmitter
import com.radiostream.player.Player
import com.radiostream.player.PlayerService
import com.radiostream.player.Song
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.async
import javax.inject.Inject
import timber.log.Timber
class BluetoothUI @Inject
constructor(playerEventsEmitter: PlayerEventsEmitter, private val mPlayerService: PlayerService) {
private val mNotificationId = 1
internal var mMediaSession: MediaSession? = null
private val mMediaSessionCallback = object : MediaSession.Callback() {
override fun onMediaButtonEvent(mediaButtonIntent: Intent): Boolean {
Timber.i("function start")
val ke = mediaButtonIntent.getParcelableExtra<KeyEvent>(Intent.EXTRA_KEY_EVENT)
if (ke != null && ke.action == KeyEvent.ACTION_DOWN) {
when (ke.keyCode) {
KeyEvent.KEYCODE_MEDIA_PLAY -> {
Timber.i("play media button")
async(CommonPool) {
try {
mPlayerService.play()
} catch (e: Exception) {
Timber.e(e, "Error: ${e}")
}
}
return true
}
KeyEvent.KEYCODE_MEDIA_PAUSE -> {
Timber.i("pause media button")
async(CommonPool) {
try {
mPlayerService.pause()
} catch (e: Exception) {
Timber.e(e, "Error: ${e}")
}
}
return true
}
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> {
Timber.i("play/pause media button")
async(CommonPool) {
try {
mPlayerService.playPause()
} catch (e: Exception) {
Timber.e(e, "Error: ${e}")
}
}
return true
}
}
}
return false
}
}
init {
Timber.i("function start")
playerEventsEmitter.subscribePlayerChanges { player -> onPlayerChanged(player) }
}
fun create() {
mMediaSession = MediaSession(mPlayerService, "PlayerService")
mMediaSession!!.setCallback(mMediaSessionCallback)
mMediaSession!!.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS or MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS)
}
fun destroy() {
mMediaSession!!.release()
}
private fun onPlayerChanged(player: Player) {
Timber.i("function start")
val isLoading = player.isLoading
if(isLoading) {
Timber.i("song loading")
updateDisplayText("Loading...")
} else if(player.currentSong != null) {
Timber.i("updating song information")
updateDisplaySong(player.currentSong!!, player.isPlaying)
} else {
Timber.i("no playlist")
updateDisplayText("No playlist")
}
}
private fun updateDisplaySong(song: Song, isPlaying: Boolean) {
updateMediaSesssion(isPlaying, song.title, song.artist, song.album)
}
private fun updateDisplayText(text: String) {
updateMediaSesssion(true, text, text, text)
}
private fun updateMediaSesssion(isPlaying: Boolean, title: String, artist: String, album: String) {
Timber.i("updating media session")
mMediaSession!!.isActive = true
val actions = PlaybackState.ACTION_PLAY_PAUSE or PlaybackState.ACTION_PLAY or PlaybackState.ACTION_PAUSE
val playingState = if (isPlaying) PlaybackState.STATE_PLAYING else PlaybackState.STATE_PAUSED
val state = PlaybackState.Builder().setActions(actions).setState(playingState, 0, 1f).build()
mMediaSession!!.setPlaybackState(state)
val metadata = MediaMetadata.Builder()
.putString(MediaMetadata.METADATA_KEY_TITLE, title)
.putString(MediaMetadata.METADATA_KEY_ARTIST, artist)
.putString(MediaMetadata.METADATA_KEY_ALBUM, album)
.build();
mMediaSession!!.setMetadata(metadata);
Timber.i("setting media metadata")
}
}
| mit | efd531f1838f61f5aea9eb4bfb684a30 | 36.046154 | 121 | 0.5625 | 5.263388 | false | false | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/hazelcast/serializers/OrganizationExternalDatabaseColumnStreamSerializer.kt | 1 | 2623 | package com.openlattice.hazelcast.serializers
import com.hazelcast.nio.ObjectDataInput
import com.hazelcast.nio.ObjectDataOutput
import com.kryptnostic.rhizome.hazelcast.serializers.UUIDStreamSerializerUtils
import com.kryptnostic.rhizome.pods.hazelcast.SelfRegisteringStreamSerializer
import com.openlattice.hazelcast.StreamSerializerTypeIds
import com.openlattice.organization.OrganizationExternalDatabaseColumn
import com.openlattice.postgres.PostgresDatatype
import org.springframework.stereotype.Component
import java.util.*
@Component
class OrganizationExternalDatabaseColumnStreamSerializer : SelfRegisteringStreamSerializer<OrganizationExternalDatabaseColumn> {
companion object {
private val postgresDatatypes = PostgresDatatype.values()
fun serialize(output: ObjectDataOutput, obj: OrganizationExternalDatabaseColumn) {
UUIDStreamSerializerUtils.serialize(output, obj.id)
output.writeUTF(obj.name)
output.writeUTF(obj.title)
output.writeUTF(obj.description)
UUIDStreamSerializerUtils.serialize(output, obj.tableId)
UUIDStreamSerializerUtils.serialize(output, obj.organizationId)
output.writeInt(obj.dataType.ordinal)
output.writeBoolean(obj.primaryKey)
output.writeInt(obj.ordinalPosition)
}
fun deserialize(input: ObjectDataInput): OrganizationExternalDatabaseColumn {
val id = UUIDStreamSerializerUtils.deserialize(input)
val name = input.readUTF()
val title = input.readUTF()
val description = input.readUTF()
val tableId = UUIDStreamSerializerUtils.deserialize(input)
val orgId = UUIDStreamSerializerUtils.deserialize(input)
val dataType = postgresDatatypes[input.readInt()]
val isPrimaryKey = input.readBoolean()
val ordinalPosition = input.readInt()
return OrganizationExternalDatabaseColumn(id, name, title, Optional.of(description), tableId, orgId, dataType, isPrimaryKey, ordinalPosition)
}
}
override fun write(output: ObjectDataOutput, obj: OrganizationExternalDatabaseColumn) {
serialize(output, obj)
}
override fun read(input: ObjectDataInput): OrganizationExternalDatabaseColumn {
return deserialize(input)
}
override fun getClazz(): Class<out OrganizationExternalDatabaseColumn> {
return OrganizationExternalDatabaseColumn::class.java
}
override fun getTypeId(): Int {
return StreamSerializerTypeIds.ORGANIZATION_EXTERNAL_DATABASE_COLUMN.ordinal
}
} | gpl-3.0 | f0a39325363b991bb7abe010139b732b | 42.733333 | 153 | 0.741136 | 5.498952 | false | false | false | false |
TimePath/java-xplaf | src/test/kotlin/com/timepath/plaf/x/filechooser/test/FileChooserTest.kt | 1 | 10629 | package com.timepath.plaf.x.filechooser.test
import com.timepath.plaf.win.JnaFileChooser
import com.timepath.plaf.x.filechooser.*
import com.timepath.plaf.x.filechooser.BaseFileChooser.ExtensionFilter
import com.timepath.plaf.x.filechooser.BaseFileChooser.FileMode
import java.awt.Dimension
import java.awt.EventQueue
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.io.IOException
import java.util.Arrays
import java.util.logging.Level
import java.util.logging.Logger
import javax.swing.*
import javax.swing.GroupLayout.Alignment
import javax.swing.LayoutStyle.ComponentPlacement
import javax.swing.table.DefaultTableModel
import kotlin.platform.platformStatic
/**
* @author TimePath
*/
public class FileChooserTest : JFrame() {
private val checkDirectories = JCheckBox()
private val checkFiles = JCheckBox()
private val checkMulti = JCheckBox()
private val checkSave = JCheckBox()
private val jButton1 = JButton()
private val jLabel1 = JLabel()
private val jList1 = JList<Any>()
private val jPanel1 = JPanel()
private val jPanel2 = JPanel()
private val jPanel3 = JPanel()
private val jPanel4 = JPanel()
private val jScrollPane1 = JScrollPane()
private val jScrollPane2 = JScrollPane()
private val jTable1 = JTable()
private val textTitle = JTextField()
init {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
setTitle("File dialog tester")
jList1.setModel(getFileChoosers())
jScrollPane1.setViewportView(jList1)
jTable1.setAutoCreateRowSorter(true)
jTable1.setModel(object : DefaultTableModel(array("Path", "Name"), 0) {
var types = array<Class<*>>(javaClass<String>(), javaClass<String>())
var canEdit = booleanArray(true, false)
override fun getColumnClass(columnIndex: Int): Class<out Any?> {
return types[columnIndex]
}
override fun isCellEditable(row: Int, column: Int): Boolean {
return canEdit[column]
}
})
jScrollPane2.setViewportView(jTable1)
jButton1.setText("Test")
jButton1.addActionListener(object : ActionListener {
override fun actionPerformed(e: ActionEvent) = jButton1ActionPerformed()
})
jLabel1.setText("Title:")
textTitle.setMinimumSize(Dimension(78, 27))
textTitle.setPreferredSize(Dimension(78, 27))
val jPanel2Layout = GroupLayout(jPanel2)
jPanel2.setLayout(jPanel2Layout)
jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING).addGroup(jPanel2Layout.createSequentialGroup().addContainerGap().addComponent(jLabel1).addPreferredGap(ComponentPlacement.RELATED).addComponent(textTitle, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addContainerGap()))
jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING).addGroup(jPanel2Layout.createSequentialGroup().addContainerGap().addGroup(jPanel2Layout.createParallelGroup(Alignment.BASELINE).addComponent(textTitle, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent(jLabel1)).addContainerGap()))
checkFiles.setSelected(true)
checkFiles.setText("Files")
checkDirectories.setText("Directories")
val jPanel3Layout = GroupLayout(jPanel3)
jPanel3.setLayout(jPanel3Layout)
jPanel3Layout.setHorizontalGroup(jPanel3Layout.createParallelGroup(Alignment.LEADING).addGroup(jPanel3Layout.createSequentialGroup().addContainerGap().addGroup(jPanel3Layout.createParallelGroup(Alignment.LEADING).addComponent(checkFiles).addComponent(checkDirectories)).addContainerGap()))
jPanel3Layout.setVerticalGroup(jPanel3Layout.createParallelGroup(Alignment.LEADING).addGroup(jPanel3Layout.createSequentialGroup().addContainerGap().addComponent(checkFiles).addPreferredGap(ComponentPlacement.RELATED).addComponent(checkDirectories).addContainerGap()))
checkSave.setText("Save")
checkMulti.setText("Multi")
val jPanel4Layout = GroupLayout(jPanel4)
jPanel4.setLayout(jPanel4Layout)
jPanel4Layout.setHorizontalGroup(jPanel4Layout.createParallelGroup(Alignment.LEADING).addGroup(jPanel4Layout.createSequentialGroup().addContainerGap().addGroup(jPanel4Layout.createParallelGroup(Alignment.LEADING).addComponent(checkSave).addComponent(checkMulti)).addContainerGap()))
jPanel4Layout.setVerticalGroup(jPanel4Layout.createParallelGroup(Alignment.LEADING).addGroup(jPanel4Layout.createSequentialGroup().addContainerGap().addComponent(checkSave).addPreferredGap(ComponentPlacement.RELATED).addComponent(checkMulti).addContainerGap()))
val jPanel1Layout = GroupLayout(jPanel1)
jPanel1.setLayout(jPanel1Layout)
jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addContainerGap().addGroup(jPanel1Layout.createParallelGroup(Alignment.LEADING, false).addGroup(jPanel1Layout.createSequentialGroup().addComponent(jPanel3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addPreferredGap(ComponentPlacement.RELATED).addComponent(jPanel2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)).addGroup(jPanel1Layout.createSequentialGroup().addComponent(jPanel4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, java.lang.Short.MAX_VALUE.toInt()).addComponent(jButton1, GroupLayout.PREFERRED_SIZE, 105, GroupLayout.PREFERRED_SIZE))).addContainerGap(43, java.lang.Short.MAX_VALUE.toInt())))
jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addContainerGap().addGroup(jPanel1Layout.createParallelGroup(Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addComponent(jPanel2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, java.lang.Short.MAX_VALUE.toInt()).addComponent(jButton1, GroupLayout.PREFERRED_SIZE, 42, GroupLayout.PREFERRED_SIZE)).addGroup(jPanel1Layout.createSequentialGroup().addComponent(jPanel3, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, java.lang.Short.MAX_VALUE.toInt()).addPreferredGap(ComponentPlacement.RELATED).addComponent(jPanel4, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, java.lang.Short.MAX_VALUE.toInt()))).addContainerGap()))
val layout = GroupLayout(getContentPane())
getContentPane().setLayout(layout)
layout.setHorizontalGroup(layout.createParallelGroup(Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, java.lang.Short.MAX_VALUE.toInt()).addComponent(jScrollPane2, GroupLayout.PREFERRED_SIZE, 0, java.lang.Short.MAX_VALUE.toInt()).addComponent(jScrollPane1)).addContainerGap()))
layout.setVerticalGroup(layout.createParallelGroup(Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addPreferredGap(ComponentPlacement.RELATED).addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, java.lang.Short.MAX_VALUE.toInt()).addComponent(jScrollPane2, GroupLayout.PREFERRED_SIZE, 197, GroupLayout.PREFERRED_SIZE).addContainerGap()))
pack()
this.jList1.setSelectedIndex(0)
}
private fun jButton1ActionPerformed() {
try {
val clazz = this.jList1.getSelectedValue() as Class<*>
val bfc = clazz.newInstance()
if (bfc !is BaseFileChooser) {
return
}
bfc.setParent(this)
bfc.setFileMode(if (this.checkDirectories.isSelected())
FileMode.DIRECTORIES_ONLY
else
(if (this.checkFiles.isSelected())
FileMode.FILES_ONLY
else
FileMode.FILES_AND_DIRECTORIES))
bfc.setDialogType(if (this.checkSave.isSelected())
BaseFileChooser.DialogType.SAVE_DIALOG
else
BaseFileChooser.DialogType.OPEN_DIALOG).setMultiSelectionEnabled(this.checkMulti.isSelected()).setTitle(this.textTitle.getText())
bfc.addFilter(ExtensionFilter("All files", ".*"))
val f = bfc.choose()
if (f == null) {
return
}
val table = jTable1.getModel() as DefaultTableModel
table.setRowCount(0)
for (aF in f) {
val row = array<Any>(aF.getParentFile().getPath(), aF.getName())
table.addRow(row)
LOG.log(Level.INFO, "{0}: {1}", array<Any>(aF, Arrays.toString(row)))
}
} catch (ex: IOException) {
LOG.log(Level.SEVERE, null, ex)
} catch (ex: InstantiationException) {
LOG.log(Level.SEVERE, null, ex)
} catch (ex: IllegalAccessException) {
LOG.log(Level.SEVERE, null, ex)
}
}
companion object {
private val serialVersionUID = 1
private val LOG = Logger.getLogger(javaClass<FileChooserTest>().getName())
private fun getFileChoosers() = object : AbstractListModel<Any>() {
SuppressWarnings("unchecked")
private val strings = array(
javaClass<NativeFileChooser>(),
javaClass<AWTFileChooser>(),
javaClass<SwingFileChooser>(),
javaClass<ZenityFileChooser>(),
javaClass<KDialogFileChooser>(),
javaClass<JnaFileChooser>()
)
override fun getElementAt(index: Int): Any? {
return strings[index]
}
override fun getSize(): Int {
return strings.size()
}
}
/**
* @param args the command line arguments
*/
public platformStatic fun main(args: Array<String>) {
EventQueue.invokeLater {
FileChooserTest().setVisible(true)
}
}
}
}
| artistic-2.0 | 73dd61a9dcadc9bbf858e0cae071cc0f | 61.157895 | 926 | 0.720105 | 4.575549 | false | false | false | false |
yamamotoj/workshop-jb | src/i_introduction/_2_Default_And_Named_Params/DefaultAndNamedParams.kt | 1 | 972 | package i_introduction._2_Default_And_Named_Params
import util.TODO
import i_introduction._1_Functions.task1
fun bar(i: Int, s: String = "", b: Boolean = true) {}
fun usage() {
bar(1, b = false)
}
fun todoTask2_1() = TODO(
"""
Task 2(1).
Rewrite all overloaded functions 'JavaCode2.foo()' to one function 'foo()' in Kotlin using default parameters.
The function 'foo()' is declared below, you have to add parameters and replace 'todoTask2_1()' with a body.
Uncomment the commented code and make it compile.
""",
references = { name: String -> JavaCode2().foo(name); foo(name) })
fun foo(name: String, number : Int = 42, toUpperCase : Boolean = false): String {
return (if(toUpperCase) name.toUpperCase() else name) + number
}
fun task2_1(): String {
return (foo("a") +
foo("b", number = 1) +
foo("c", toUpperCase = true) +
foo(name = "d", number = 2, toUpperCase = true))
}
| mit | 348e6d7b5c54c44e7f8bf76c6792da21 | 31.4 | 118 | 0.617284 | 3.613383 | false | false | false | false |
valich/intellij-markdown | src/commonMain/kotlin/org/intellij/markdown/parser/markerblocks/providers/SetextHeaderProvider.kt | 1 | 2192 | package org.intellij.markdown.parser.markerblocks.providers
import org.intellij.markdown.parser.LookaheadText
import org.intellij.markdown.parser.MarkerProcessor
import org.intellij.markdown.parser.ProductionHolder
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.constraints.eatItselfFromString
import org.intellij.markdown.parser.constraints.extendsPrev
import org.intellij.markdown.parser.markerblocks.MarkerBlock
import org.intellij.markdown.parser.markerblocks.MarkerBlockProvider
import org.intellij.markdown.parser.markerblocks.impl.SetextHeaderMarkerBlock
class SetextHeaderProvider : MarkerBlockProvider<MarkerProcessor.StateInfo> {
override fun createMarkerBlocks(pos: LookaheadText.Position,
productionHolder: ProductionHolder,
stateInfo: MarkerProcessor.StateInfo): List<MarkerBlock> {
if (stateInfo.paragraphBlock != null) {
return emptyList()
}
val currentConstaints = stateInfo.currentConstraints
if (stateInfo.nextConstraints != currentConstaints) {
return emptyList()
}
if (MarkerBlockProvider.isStartOfLineWithConstraints(pos, currentConstaints)
&& getNextLineFromConstraints(pos, currentConstaints)?.let { REGEX.matches(it) } == true) {
return listOf(SetextHeaderMarkerBlock(currentConstaints, productionHolder))
} else {
return emptyList()
}
}
override fun interruptsParagraph(pos: LookaheadText.Position, constraints: MarkdownConstraints): Boolean {
return false
}
private fun getNextLineFromConstraints(pos: LookaheadText.Position, constraints: MarkdownConstraints): CharSequence? {
val line = pos.nextLine ?: return null
val nextLineConstraints = constraints.applyToNextLine(pos.nextLinePosition())
if (nextLineConstraints.extendsPrev(constraints)) {
return nextLineConstraints.eatItselfFromString(line)
} else {
return null
}
}
companion object {
val REGEX: Regex = Regex("^ {0,3}(\\-+|=+) *$")
}
} | apache-2.0 | a519f76a265d273524bbc633be2aefeb | 43.755102 | 122 | 0.713047 | 5.169811 | false | false | false | false |
ntemplon/ygo-combo-calculator | src/com/croffgrin/ygocalc/Tester.kt | 1 | 1553 | package com.croffgrin.ygocalc
import java.util.*
/**
* Copyright (c) 2016 Nathan S. Templon
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
fun main(args: Array<String>) {
val rand = Random()
println(
(1..100000).map {
val i1 = rand.nextInt(6) + 1
val i2 = rand.nextInt(6) + 1
val i3 = rand.nextInt(6) + 1
val i4 = rand.nextInt(6) + 1
i1 + i2 + i3 + i4 - Math.min(i1, Math.min(i2, Math.min(i3, i4)))
}.average()
)
} | mit | f7f42348050731f1aa2e9e7b0997cf0d | 46.090909 | 118 | 0.683838 | 4.076115 | false | false | false | false |
Reduks/Reduks | src/test/java/com/reduks/reduks/repository/FakeData.kt | 1 | 790 | package com.reduks.reduks.repository
import com.reduks.reduks.Action
import com.reduks.reduks.Store
import com.reduks.reduks.reduksStore
class FakeData {
companion object Provider {
var store = Store(
FakeState(0, ""),
{ state, action -> action.action(state) }
)
val storeWithDslBuilder = reduksStore<FakeState> {}
}
}
data class FakeState(val id: Int = 0, val name: String = "")
data class MyStateWithDefaultValue(val state: FakeState? = null)
data class StateWithNoDefaultValue(val state: FakeState)
sealed class FakeActions : Action<FakeState> {
class SetValidState : FakeActions() {
override fun action(state: FakeState): FakeState = FakeState(1, "Bloder")
}
class EmptyAction : FakeActions()
} | mit | 660b9b46dfb8151d7049a6036272bea4 | 25.366667 | 81 | 0.679747 | 3.969849 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/pages/DeckOptions.kt | 1 | 2756 | /*
* Copyright (c) 2022 Brayan Oliveira <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.pages
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.webkit.WebView
import anki.collection.OpChanges
import com.ichi2.anki.CollectionManager
import com.ichi2.anki.R
import com.ichi2.libanki.CollectionV16
import com.ichi2.libanki.undoableOp
import com.ichi2.libanki.updateDeckConfigsRaw
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class DeckOptions : PageFragment() {
override val title = R.string.menu__deck_options
override val pageName = "deck-options"
override lateinit var webViewClient: PageWebViewClient
override var webChromeClient = PageChromeClient()
override fun onCreate(savedInstanceState: Bundle?) {
val deckId = arguments?.getLong(ARG_DECK_ID)
?: throw Exception("missing deck ID")
webViewClient = DeckOptionsWebClient(deckId)
super.onCreate(savedInstanceState)
}
class DeckOptionsWebClient(val deckId: Long) : PageWebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
// from upstream: https://github.com/ankitects/anki/blob/678c354fed4d98c0a8ef84fb7981ee085bd744a7/qt/aqt/deckoptions.py#L55
view!!.evaluateJavascript("const \$deckOptions = anki.setupDeckOptions($deckId);") {
super.onPageFinished(view, url)
}
}
}
companion object {
const val ARG_DECK_ID = "deckId"
fun getIntent(context: Context, deckId: Long): Intent {
val arguments = Bundle().apply {
putLong(ARG_DECK_ID, deckId)
}
return PagesActivity.getIntent(context, DeckOptions::class, arguments)
}
}
}
suspend fun PagesActivity.updateDeckConfigsRaw(input: ByteArray): ByteArray {
val output = CollectionManager.withCol { (this as CollectionV16).updateDeckConfigsRaw(input) }
undoableOp { OpChanges.parseFrom(output) }
withContext(Dispatchers.Main) { finish() }
return output
}
| gpl-3.0 | 550b5a789d26e316ba95c5661732606a | 38.371429 | 135 | 0.716981 | 4.113433 | false | false | false | false |
EvidentSolutions/apina | apina-core/src/main/kotlin/fi/evident/apina/java/reader/MethodSignatureVisitor.kt | 1 | 1663 | package fi.evident.apina.java.reader
import fi.evident.apina.java.model.MethodSignature
import fi.evident.apina.java.model.type.JavaType
import org.objectweb.asm.Opcodes
import org.objectweb.asm.signature.SignatureVisitor
import java.util.*
import java.util.function.Supplier
/**
* [SignatureVisitor] that builds method signature for generic methods.
*/
internal class MethodSignatureVisitor : SignatureVisitor(Opcodes.ASM9), Supplier<MethodSignature> {
private lateinit var returnTypeBuilder: Supplier<JavaType>
private val parameterTypeBuilders = ArrayList<Supplier<JavaType>>()
private val typeSchemaBuilder = TypeSchemaBuilder()
override fun visitFormalTypeParameter(name: String) {
typeSchemaBuilder.addTypeParameter(name)
}
override fun visitClassBound() = visitBound()
override fun visitInterfaceBound() = visitBound()
private fun visitBound(): SignatureVisitor {
return TypeBuildingSignatureVisitor().also {
typeSchemaBuilder.addBoundBuilderForLastTypeParameter(it)
}
}
override fun visitParameterType(): SignatureVisitor {
typeSchemaBuilder.finishFormalTypes()
return TypeBuildingSignatureVisitor().also {
parameterTypeBuilders += it
}
}
override fun visitReturnType(): SignatureVisitor {
typeSchemaBuilder.finishFormalTypes()
return TypeBuildingSignatureVisitor().also {
returnTypeBuilder = it
}
}
override fun get(): MethodSignature = MethodSignature(
returnTypeBuilder.get(),
parameterTypeBuilders.map { it.get() },
typeSchemaBuilder.schema
)
}
| mit | b059b18bab5300a449e001050151e027 | 29.796296 | 99 | 0.723391 | 4.891176 | false | false | false | false |
Kotlin/kotlinx.serialization | core/commonMain/src/kotlinx/serialization/internal/ElementMarker.kt | 1 | 4281 | /*
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.internal
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.CompositeDecoder
@OptIn(ExperimentalSerializationApi::class)
@PublishedApi
internal class ElementMarker(
private val descriptor: SerialDescriptor,
// Instead of inheritance and virtual function in order to keep cross-module internal modifier via suppresses
// Can be reworked via public + internal api if necessary
private val readIfAbsent: (SerialDescriptor, Int) -> Boolean
) {
/*
* Element decoding marks from given bytes.
* The element index is the same as the set bit position.
* Marks for the lowest 64 elements are always stored in a single Long value, higher elements stores in long array.
*/
private var lowerMarks: Long
private val highMarksArray: LongArray
private companion object {
private val EMPTY_HIGH_MARKS = LongArray(0)
}
init {
val elementsCount = descriptor.elementsCount
if (elementsCount <= Long.SIZE_BITS) {
lowerMarks = if (elementsCount == Long.SIZE_BITS) {
// number of bits in the mark is equal to the number of fields
0L
} else {
// (1 - elementsCount) bits are always 1 since there are no fields for them
-1L shl elementsCount
}
highMarksArray = EMPTY_HIGH_MARKS
} else {
lowerMarks = 0L
highMarksArray = prepareHighMarksArray(elementsCount)
}
}
fun mark(index: Int) {
if (index < Long.SIZE_BITS) {
lowerMarks = lowerMarks or (1L shl index)
} else {
markHigh(index)
}
}
fun nextUnmarkedIndex(): Int {
val elementsCount = descriptor.elementsCount
while (lowerMarks != -1L) {
val index = lowerMarks.inv().countTrailingZeroBits()
lowerMarks = lowerMarks or (1L shl index)
if (readIfAbsent(descriptor, index)) {
return index
}
}
if (elementsCount > Long.SIZE_BITS) {
return nextUnmarkedHighIndex()
}
return CompositeDecoder.DECODE_DONE
}
private fun prepareHighMarksArray(elementsCount: Int): LongArray {
// (elementsCount - 1) / Long.SIZE_BITS
// (elementsCount - 1) because only one Long value is needed to store 64 fields etc
val slotsCount = (elementsCount - 1) ushr 6
// elementsCount % Long.SIZE_BITS
val elementsInLastSlot = elementsCount and (Long.SIZE_BITS - 1)
val highMarks = LongArray(slotsCount)
// if (elementsCount % Long.SIZE_BITS) == 0 means that the fields occupy all bits in mark
if (elementsInLastSlot != 0) {
// all marks except the higher are always 0
highMarks[highMarks.lastIndex] = -1L shl elementsCount
}
return highMarks
}
private fun markHigh(index: Int) {
// (index / Long.SIZE_BITS) - 1
val slot = (index ushr 6) - 1
// index % Long.SIZE_BITS
val offsetInSlot = index and (Long.SIZE_BITS - 1)
highMarksArray[slot] = highMarksArray[slot] or (1L shl offsetInSlot)
}
private fun nextUnmarkedHighIndex(): Int {
for (slot in highMarksArray.indices) {
// (slot + 1) because first element in high marks has index 64
val slotOffset = (slot + 1) * Long.SIZE_BITS
// store in a variable so as not to frequently use the array
var slotMarks = highMarksArray[slot]
while (slotMarks != -1L) {
val indexInSlot = slotMarks.inv().countTrailingZeroBits()
slotMarks = slotMarks or (1L shl indexInSlot)
val index = slotOffset + indexInSlot
if (readIfAbsent(descriptor, index)) {
highMarksArray[slot] = slotMarks
return index
}
}
highMarksArray[slot] = slotMarks
}
return CompositeDecoder.DECODE_DONE
}
}
| apache-2.0 | 61377e85b3444cd2ef33d3856a98450f | 35.589744 | 119 | 0.61551 | 4.633117 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/service/permission/LanternPermissionDescription.kt | 1 | 3951 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.service.permission
import org.lanternpowered.api.text.Text
import org.lanternpowered.api.util.ToStringHelper
import org.lanternpowered.api.util.optional.asOptional
import org.spongepowered.api.service.permission.PermissionDescription
import org.spongepowered.api.service.permission.PermissionService
import org.spongepowered.api.service.permission.Subject
import org.spongepowered.api.service.permission.SubjectData
import org.spongepowered.api.service.permission.SubjectReference
import org.spongepowered.api.util.Tristate
import org.spongepowered.plugin.PluginContainer
import java.util.Optional
import java.util.concurrent.CompletableFuture
/**
* Basic implementation of [PermissionDescription]. Can only be used in
* conjunction with [LanternPermissionService].
*/
internal class LanternPermissionDescription private constructor(
private val permissionService: LanternPermissionService,
private val id: String,
private val owner: PluginContainer,
private val description: Text?
) : PermissionDescription {
override fun getId(): String = this.id
override fun getDescription(): Optional<Text> = this.description.asOptional()
override fun getAssignedSubjects(identifier: String): Map<Subject, Boolean> {
val subjects = this.permissionService[identifier]
return subjects.getLoadedWithPermission(this.id)
}
override fun findAssignedSubjects(type: String): CompletableFuture<Map<SubjectReference, Boolean>> {
val subjects = this.permissionService[type]
return subjects.getAllWithPermission(this.id)
}
override fun getOwner(): Optional<PluginContainer> = this.owner.asOptional()
override fun hashCode(): Int = this.id.hashCode()
override fun equals(other: Any?): Boolean {
if (this === other)
return true
if (other == null)
return false
if (this.javaClass != other.javaClass) {
return false
}
other as LanternPermissionDescription
return id == other.id && owner == other.owner && description == other.description
}
override fun toString(): String = ToStringHelper(this)
.add("owner", this.owner)
.add("id", this.id)
.toString()
internal class Builder(
private val permissionService: LanternPermissionService,
private val owner: PluginContainer
) : PermissionDescription.Builder {
private val roleAssignments = linkedMapOf<String, Tristate>()
private var description: Text? = null
private var id: String? = null
override fun id(id: String): Builder = apply { this.id = id }
override fun description(description: Text?): Builder = apply { this.description = description }
override fun assign(role: String, value: Boolean): Builder {
this.roleAssignments[role] = Tristate.fromBoolean(value)
return this
}
override fun register(): LanternPermissionDescription {
val id = checkNotNull(this.id) { "No id set" }
val description = LanternPermissionDescription(this.permissionService, id, this.owner, this.description)
this.permissionService.addDescription(description)
// Set role-templates
val subjects = this.permissionService[PermissionService.SUBJECTS_ROLE_TEMPLATE]
for ((key, value) in this.roleAssignments)
subjects[key].transientSubjectData.setPermission(SubjectData.GLOBAL_CONTEXT, id, value)
return description
}
}
}
| mit | ebe8a1e3055ff52163acb8b91a8e02dd | 38.909091 | 116 | 0.702354 | 4.760241 | false | false | false | false |
RoverPlatform/rover-android | experiences/src/main/kotlin/io/rover/sdk/experiences/ui/blocks/poll/text/ViewTextPoll.kt | 1 | 7958 | package io.rover.sdk.experiences.ui.blocks.poll.text
import android.graphics.Typeface
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import io.rover.sdk.core.data.domain.TextPoll
import io.rover.sdk.experiences.data.mapToFont
import io.rover.sdk.experiences.logging.log
import io.rover.sdk.experiences.platform.addView
import io.rover.sdk.experiences.platform.optionView
import io.rover.sdk.experiences.platform.setupLayoutParams
import io.rover.sdk.experiences.platform.textView
import io.rover.sdk.core.streams.androidLifecycleDispose
import io.rover.sdk.core.streams.subscribe
import io.rover.sdk.experiences.ui.asAndroidColor
import io.rover.sdk.experiences.ui.blocks.concerns.background.BackgroundViewModelInterface
import io.rover.sdk.experiences.ui.blocks.concerns.background.createBackgroundDrawable
import io.rover.sdk.experiences.ui.blocks.poll.VotingState
import io.rover.sdk.experiences.ui.concerns.MeasuredBindableView
import io.rover.sdk.experiences.ui.concerns.MeasuredSize
import io.rover.sdk.experiences.ui.concerns.ViewModelBinding
internal class ViewTextPoll(override val view: LinearLayout) : ViewTextPollInterface {
private val questionView = view.textView {
setupLayoutParams(
width = ViewGroup.LayoutParams.MATCH_PARENT,
height = ViewGroup.LayoutParams.WRAP_CONTENT
)
}
private var optionViews = mapOf<String, TextOptionView>()
init {
view.addView {
questionView
}
view.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
}
override var viewModelBinding: MeasuredBindableView.Binding<TextPollViewModelInterface>? by ViewModelBinding(view, cancellationBlock = { viewModelBinding?.viewModel?.cancel() }) { binding, subscriptionCallback ->
binding?.viewModel?.let { viewModel ->
bindQuestion(viewModel.textPoll, viewModel.textPoll.options.size)
if (optionViews.isNotEmpty()) {
optionViews.forEach { view.removeView(it.value) }
}
setupOptionViews(viewModel)
log.d("poll view bound")
viewModel.votingState.subscribe({ votingState : VotingState ->
when (votingState) {
is VotingState.InitialState -> {
setPollNotWaiting()
}
is VotingState.ResultsSeeded -> {
setPollNotWaiting()
}
is VotingState.SubmittingAnswer -> {
setVoteResultsReceived(votingState)
setPollNotWaiting()
}
is VotingState.RefreshingResults -> {
if (votingState.shouldTransition) setVoteResultUpdate(votingState)
setPollNotWaiting()
}
is VotingState.PollAnswered -> setPollAnsweredWaiting()
}
}, { e -> log.e("${e.message}") }, { subscriptionCallback(it) })
viewModel.bindInteractor(viewModel.id, optionViews.keys.toList())
}
}
private fun setPollAnsweredWaiting() {
view.alpha = 0.5f
optionViews.forEach { it.value.setOnClickListener(null) }
}
private fun setPollNotWaiting() {
view.alpha = 1f
}
private fun setupOptionViews(viewModel: TextPollViewModelInterface) {
var indexForAccessibility = 1
optionViews = createOptionViews(viewModel.textPoll)
startListeningForOptionImageUpdates(viewModel.optionBackgroundViewModel, optionViews)
optionViews.forEach { (optionId, optionView) ->
view.addView(optionView)
optionView.setContentDescription(indexForAccessibility)
optionView.setOnClickListener {
viewModelBinding?.viewModel?.castVote(optionId, viewModel.textPoll.options.map { it.id }) }
indexForAccessibility++
}
informOptionBackgroundAboutSize(viewModel)
}
private fun bindQuestion(textPoll: TextPoll, numberOfOptions: Int) {
questionView.run {
text = textPoll.question.rawValue
contentDescription = "Poll with $numberOfOptions options: ${textPoll.question.rawValue}"
gravity = textPoll.question.alignment.convertToGravity()
textSize = textPoll.question.font.size.toFloat()
setTextColor(textPoll.question.color.asAndroidColor())
val font = textPoll.question.font.weight.mapToFont()
typeface = Typeface.create(font.fontFamily, font.fontStyle)
}
}
private fun createOptionViews(textPoll: TextPoll): Map<String, TextOptionView> {
return textPoll.options.associate { option ->
option.id to view.optionView {
initializeOptionViewLayout(option)
bindOptionView(option)
}
}
}
private fun informOptionBackgroundAboutSize(viewModel: TextPollViewModelInterface) {
viewModelBinding?.measuredSize?.width?.let { measuredWidth ->
val optionStyleHeight = viewModel.textPoll.options.first().height.toFloat()
val measuredSize = MeasuredSize(
measuredWidth,
optionStyleHeight,
view.resources.displayMetrics.density
)
viewModel.optionBackgroundViewModel.informDimensions(measuredSize)
}
}
private fun setVoteResultUpdate(votingUpdate: VotingState.RefreshingResults) {
val maxVotingValue = votingUpdate.optionResults.results.map { it.value }.max() ?: 0
votingUpdate.optionResults.results.forEach { (id, votingShare) ->
val option = optionViews[id]
option?.setOnClickListener(null)
val isSelectedOption = id == votingUpdate.selectedOption
viewModelBinding?.viewModel?.let {
if (votingUpdate.shouldTransition) {
if (votingUpdate.shouldAnimate) {
option?.updateResults(votingShare)
} else {
option?.goToResultsState(votingShare, isSelectedOption, it.textPoll.options.find { it.id == id }!!,
false, viewModelBinding?.measuredSize?.width, maxVotingValue)
}
}
}
}
}
private fun setVoteResultsReceived(votingResults: VotingState.SubmittingAnswer) {
val maxVotingValue = votingResults.optionResults.results.map { it.value }.max() ?: 0
votingResults.optionResults.results.forEach { (id, votingShare) ->
val option = optionViews[id]
option?.setOnClickListener(null)
val isSelectedOption = id == votingResults.selectedOption
viewModelBinding?.viewModel?.let {
option?.goToResultsState(votingShare, isSelectedOption, it.textPoll.options.find { it.id == id }!!,
votingResults.shouldAnimate, viewModelBinding?.measuredSize?.width, maxVotingValue)
}
}
}
private fun startListeningForOptionImageUpdates(
viewModel: BackgroundViewModelInterface,
textOptionViews: Map<String, TextOptionView>
) {
viewModel.backgroundUpdates.androidLifecycleDispose(view)
.subscribe { (bitmap, fadeIn, backgroundImageConfiguration) ->
textOptionViews.forEach {
val backgroundDrawable = bitmap.createBackgroundDrawable(
view,
viewModel.backgroundColor,
fadeIn,
backgroundImageConfiguration
)
it.value.backgroundImage = backgroundDrawable
}
}
}
}
internal interface ViewTextPollInterface : MeasuredBindableView<TextPollViewModelInterface>
| apache-2.0 | a6e3c5759bec59da7d6bb9ee9c9df3c4 | 40.233161 | 216 | 0.642372 | 4.936725 | false | false | false | false |
gumil/basamto | data/src/main/kotlin/io/github/gumil/data/rest/RedditMoshiFactory.kt | 1 | 3510 | /*
* The MIT License (MIT)
*
* Copyright 2017 Miguel Panelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.gumil.data.rest
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonDataException
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import io.github.gumil.data.model.Link
import io.github.gumil.data.model.RedditType
import io.github.gumil.data.model.Thing
import java.io.IOException
import java.lang.ref.WeakReference
import java.lang.reflect.Type
internal class RedditMoshiFactory : JsonAdapter.Factory {
override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi): JsonAdapter<*>? {
val clazz = Types.getRawType(type)
if (Thing::class.java != clazz) {
return null
}
return object : JsonAdapter<Any>() {
@Suppress("UNCHECKED_CAST")
@Throws(IOException::class)
override fun fromJson(reader: JsonReader): Any? {
val jsonValue = reader.readJsonValue()
return (jsonValue as? String)?.let {
/**
* replies return [String] instead of a [Thing] when there are no replies
* return null to handle this state
*/
null
} ?:(jsonValue as? Map<String, Any>)?.let { map ->
map["kind"]?.let {
moshi.adapter(RedditType.valueOf((it as String).toUpperCase()).derivedClass)
?.fromJsonValue(map["data"]) ?: throw JsonDataException()
}
}
}
@Throws(IOException::class)
override fun toJson(writer: JsonWriter, value: Any?) {
when (value) {
is Link -> {
writer.name("kind")
moshi.adapter(RedditType::class.java).toJson(writer, RedditType.T3)
writer.name("data")
moshi.adapter(Link::class.java).toJson(writer, value)
}
}
}
}
}
companion object {
private var instance: WeakReference<RedditMoshiFactory>? = null
fun getInstance(): RedditMoshiFactory =
instance?.get() ?: RedditMoshiFactory().also { instance = WeakReference(it) }
}
}
| mit | 822757174e8aae09f86b5da5d642c950 | 38.886364 | 100 | 0.625356 | 4.730458 | false | false | false | false |
soniccat/android-taskmanager | service/src/main/java/com/example/alexeyglushkov/service/SimpleService.kt | 1 | 3392 | package com.example.alexeyglushkov.service
import android.os.HandlerThread
import com.example.alexeyglushkov.authorization.Auth.*
import com.example.alexeyglushkov.authorization.Auth.Authorizer.AuthError
import io.reactivex.Single
import io.reactivex.SingleSource
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Function
import tools.RxTools
import java.lang.Exception
/**
* Created by alexeyglushkov on 26.11.15.
*/
open class SimpleService : Service {
override var account: Account? = null
protected var commandProvider: ServiceCommandProvider? = null
protected var commandRunner: ServiceCommandRunner? = null
// to run authorization
private var authThread: HandlerThread? = null
override fun setServiceCommandProvider(provider: ServiceCommandProvider) {
commandProvider = provider
}
override fun setServiceCommandRunner(runner: ServiceCommandRunner) {
commandRunner = runner
}
override suspend fun <T> runCommand(command: ServiceCommand<T>, canSignIn: Boolean): T {
return runCommandInternal(command, canSignIn)
}
private suspend fun <R, T : ServiceCommand<R>> runCommandInternal(command: T, canSignIn: Boolean): R {
val account = account
checkNotNull(account)
return if (!account.isAuthorized) {
if (canSignIn) {
authorizeAndRun(command)
} else {
throw AuthError(AuthError.Reason.NotAuthorized, null)
}
} else {
account.signCommand(command)
runCommandInternal(command)
}
}
override suspend fun <T> runCommand(command: ServiceCommand<T>): T {
return runCommandInternal(command)
}
private suspend fun <R, T : ServiceCommand<R>> runCommandInternal(command: T): R {
val commandRunner = commandRunner
checkNotNull(commandRunner)
return try {
commandRunner.run(command)
} catch (ex: Exception) {
if (command.responseCode == 401) {
command.clear()
authorizeAndRun(command)
} else {
throw ex
}
}
}
suspend fun <R, T : ServiceCommand<R>> authorizeAndRun(command: T): R {
val response = authorize()
return runCommandInternal(command, false)
}
suspend fun authorizeIfNeeded(): AuthCredentials {
val account = account
val credentials = account?.credentials
checkNotNull(account)
return if (!account.isAuthorized) {
authorize()
} else if (credentials != null) {
credentials
} else {
throw Error("Empty credentials")
}
}
suspend fun authorize(): AuthCredentials {
val account = account
val authThread = authThread
checkNotNull(account)
checkNotNull(authThread)
startAuthThreadIfNeeded()
return account.authorize()
}
private fun startAuthThreadIfNeeded() {
if (authThread == null) {
authThread = HandlerThread("SimpleService Auth Thread").apply {
start()
}
}
}
override fun cancel(cmd: ServiceCommand<*>) {
val commandRunner = commandRunner
checkNotNull(commandRunner)
commandRunner.cancel(cmd)
}
} | mit | d339becb7da80b821fdf2902219e9eef | 28.25 | 106 | 0.637087 | 5.047619 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge3d/Light3D.kt | 1 | 1123 | package com.soywiz.korge3d
import com.soywiz.korim.color.*
import com.soywiz.korma.geom.*
@Korge3DExperimental
fun Container3D.light(
color: RGBA = Colors.WHITE,
constantAttenuation: Double = 1.0,
linearAttenuation: Double = 0.0,
quadraticAttenuation: Double = 0.00111109,
callback: Light3D.() -> Unit = {}
) = Light3D(color, constantAttenuation, linearAttenuation, quadraticAttenuation).addTo(this, callback)
@Korge3DExperimental
open class Light3D(
var color: RGBA = Colors.WHITE,
var constantAttenuation: Double = 1.0,
var linearAttenuation: Double = 0.0,
var quadraticAttenuation: Double = 0.00111109
) : View3D() {
internal val colorVec = Vector3D()
internal val attenuationVec = Vector3D()
fun setTo(
color: RGBA = Colors.WHITE,
constantAttenuation: Double = 1.0,
linearAttenuation: Double = 0.0,
quadraticAttenuation: Double = 0.00111109
): Light3D {
this.color = color
this.constantAttenuation = constantAttenuation
this.linearAttenuation = linearAttenuation
this.quadraticAttenuation = quadraticAttenuation
return this
}
override fun render(ctx: RenderContext3D) {
}
}
| apache-2.0 | 14bba2681f90bce6db22907f3642e13d | 27.075 | 102 | 0.753339 | 3.302941 | false | false | false | false |
cashapp/sqldelight | sqldelight-compiler/src/main/kotlin/app/cash/sqldelight/core/compiler/QueryInterfaceGenerator.kt | 1 | 1660 | /*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.sqldelight.core.compiler
import app.cash.sqldelight.core.capitalize
import app.cash.sqldelight.core.compiler.model.NamedQuery
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier.DATA
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeSpec
class QueryInterfaceGenerator(val query: NamedQuery) {
fun kotlinImplementationSpec(): TypeSpec {
val typeSpec = TypeSpec.classBuilder(query.name.capitalize())
.addModifiers(DATA)
val constructor = FunSpec.constructorBuilder()
query.resultColumns.forEach {
val javaType = it.javaType
val typeWithoutAnnotations = javaType.copy(annotations = emptyList())
typeSpec.addProperty(
PropertySpec.builder(it.name, typeWithoutAnnotations)
.initializer(it.name)
.addAnnotations(javaType.annotations)
.build(),
)
constructor.addParameter(it.name, typeWithoutAnnotations)
}
return typeSpec
.primaryConstructor(constructor.build())
.build()
}
}
| apache-2.0 | d4c704824ed6f5a962bfa9bb05a65734 | 33.583333 | 75 | 0.737349 | 4.426667 | false | false | false | false |
niranjan94/show-java | app/src/main/kotlin/com/njlabs/showjava/activities/explorer/navigator/NavigatorHandler.kt | 1 | 3428 | /*
* Show Java - A java/apk decompiler for android
* Copyright (c) 2018 Niranjan Rajendran
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.njlabs.showjava.activities.explorer.navigator
import android.content.Context
import com.crashlytics.android.Crashlytics
import com.njlabs.showjava.data.FileItem
import com.njlabs.showjava.utils.ZipUtils
import io.reactivex.Observable
import org.apache.commons.io.FileUtils
import java.io.File
import java.io.IOException
import java.text.DateFormat
import java.util.Date
import kotlin.collections.ArrayList
import kotlin.collections.forEach
import kotlin.collections.sortBy
class NavigatorHandler(private var context: Context) {
/**
* Load all files in the given directory
*/
fun loadFiles(currentDirectory: File): Observable<ArrayList<FileItem>> {
return Observable.fromCallable {
val directories = ArrayList<FileItem>()
val files = ArrayList<FileItem>()
val items = currentDirectory.listFiles()
if (items.isNullOrEmpty()) {
return@fromCallable directories
}
items.forEach { file ->
val lastModDate = DateFormat.getDateTimeInstance()
.format(
Date(
file.lastModified()
)
)
if (file.isDirectory) {
val children = file.listFiles()
val noOfChildren = children?.size ?: 0
val fileSize = "$noOfChildren ${if (noOfChildren == 1) "item" else "items"}"
directories.add(FileItem(file, fileSize, lastModDate))
} else {
val fileSize = FileUtils.byteCountToDisplaySize(file.length())
files.add(FileItem(file, fileSize, lastModDate))
}
}
directories.sortBy { it.name?.toLowerCase() }
files.sortBy { it.name?.toLowerCase() }
directories.addAll(files)
directories
}
}
/**
* Package an entire directory containing the source code into a .zip archive.
*/
fun archiveDirectory(sourceDirectory: File, packageName: String): Observable<File> {
return Observable.fromCallable {
ZipUtils.zipDir(sourceDirectory, packageName)
}
}
/**
* Delete the source directory
*/
fun deleteDirectory(sourceDirectory: File): Observable<Unit> {
return Observable.fromCallable {
try {
if (sourceDirectory.exists()) {
FileUtils.deleteDirectory(sourceDirectory)
}
} catch (e: IOException) {
Crashlytics.logException(e)
}
}
}
}
| gpl-3.0 | fedfe81c4d26aa765a81d191e7da81aa | 35.084211 | 96 | 0.61902 | 4.960926 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.