repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Gh0u1L5/WechatMagician
app/src/main/kotlin/com/gh0u1l5/wechatmagician/backend/plugins/Developer.kt
1
12487
package com.gh0u1l5.wechatmagician.backend.plugins import android.app.Activity import android.content.ContentValues import android.content.Intent import android.os.Bundle import android.widget.ListAdapter import com.gh0u1l5.wechatmagician.Global.DEVELOPER_DATABASE_DELETE import com.gh0u1l5.wechatmagician.Global.DEVELOPER_DATABASE_EXECUTE import com.gh0u1l5.wechatmagician.Global.DEVELOPER_DATABASE_INSERT import com.gh0u1l5.wechatmagician.Global.DEVELOPER_DATABASE_QUERY import com.gh0u1l5.wechatmagician.Global.DEVELOPER_DATABASE_UPDATE import com.gh0u1l5.wechatmagician.Global.DEVELOPER_TRACE_FILES import com.gh0u1l5.wechatmagician.Global.DEVELOPER_TRACE_LOGCAT import com.gh0u1l5.wechatmagician.Global.DEVELOPER_UI_DUMP_POPUP_MENU import com.gh0u1l5.wechatmagician.Global.DEVELOPER_UI_TOUCH_EVENT import com.gh0u1l5.wechatmagician.Global.DEVELOPER_UI_TRACE_ACTIVITIES import com.gh0u1l5.wechatmagician.Global.DEVELOPER_XML_PARSER import com.gh0u1l5.wechatmagician.backend.WechatHook import com.gh0u1l5.wechatmagician.spellbook.C import com.gh0u1l5.wechatmagician.spellbook.base.Hooker import com.gh0u1l5.wechatmagician.spellbook.base.HookerProvider import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.mm.sdk.platformtools.Classes.Logcat import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.mm.sdk.platformtools.Methods.XmlParser_parse import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.mm.ui.base.Classes.MMListPopupWindow import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.wcdb.database.Classes.SQLiteCursorFactory import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.wcdb.database.Classes.SQLiteDatabase import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.wcdb.support.Classes.SQLiteCancellationSignal import com.gh0u1l5.wechatmagician.util.MessageUtil.argsToString import com.gh0u1l5.wechatmagician.util.MessageUtil.bundleToString import de.robv.android.xposed.XC_MethodHook import de.robv.android.xposed.XposedBridge.* import de.robv.android.xposed.XposedHelpers.findAndHookConstructor import de.robv.android.xposed.XposedHelpers.findAndHookMethod import java.io.File object Developer : HookerProvider { private val pref = WechatHook.developer override fun provideStaticHookers(): List<Hooker>? { return listOf ( traceTouchEventsHooker, traceActivitiesHooker, dumpPopupMenuHooker, traceDatabaseHooker, traceLogcatHooker, traceFilesHooker, traceXMLParseHooker ) } // Hook View.onTouchEvent to trace touch events. private val traceTouchEventsHooker = Hooker { if (pref.getBoolean(DEVELOPER_UI_TOUCH_EVENT, false)) { findAndHookMethod(C.View, "onTouchEvent", C.MotionEvent, object : XC_MethodHook() { @Throws(Throwable::class) override fun beforeHookedMethod(param: MethodHookParam) { log("View.onTouchEvent => obj.class = ${param.thisObject::class.java}") } }) } } // Hook Activity.startActivity and Activity.onCreate to trace activities. private val traceActivitiesHooker = Hooker { if (pref.getBoolean(DEVELOPER_UI_TRACE_ACTIVITIES, false)) { findAndHookMethod(C.Activity, "startActivity", C.Intent, object : XC_MethodHook() { @Throws(Throwable::class) override fun beforeHookedMethod(param: MethodHookParam) { val intent = param.args[0] as Intent? log("Activity.startActivity => " + "${param.thisObject::class.java}, " + "intent => ${bundleToString(intent?.extras)}") } }) findAndHookMethod(C.Activity, "onCreate", C.Bundle, object : XC_MethodHook() { @Throws(Throwable::class) override fun afterHookedMethod(param: MethodHookParam) { val bundle = param.args[0] as Bundle? val intent = (param.thisObject as Activity).intent log("Activity.onCreate => " + "${param.thisObject::class.java}, " + "intent => ${bundleToString(intent?.extras)}, " + "bundle => ${bundleToString(bundle)}") } }) } } // Hook MMListPopupWindow to trace every popup menu. private val dumpPopupMenuHooker = Hooker { if (pref.getBoolean(DEVELOPER_UI_DUMP_POPUP_MENU, false)) { hookAllConstructors(MMListPopupWindow, object : XC_MethodHook() { @Throws(Throwable::class) override fun afterHookedMethod(param: MethodHookParam) { val menu = param.thisObject val context = param.args[0] log("POPUP => menu.class = ${menu::class.java}") log("POPUP => context.class = ${context::class.java}") } }) findAndHookMethod(MMListPopupWindow, "setAdapter", C.ListAdapter, object : XC_MethodHook() { @Throws(Throwable::class) override fun beforeHookedMethod(param: MethodHookParam) { val adapter = param.args[0] as ListAdapter? ?: return log("POPUP => adapter.count = ${adapter.count}") (0 until adapter.count).forEach { index -> log("POPUP => adapter.item[$index] = ${adapter.getItem(index)}") log("POPUP => adapter.item[$index].class = ${adapter.getItem(index)::class.java}") } } }) } } // Hook SQLiteDatabase to trace all the database operations. private val traceDatabaseHooker = Hooker { if (pref.getBoolean(DEVELOPER_DATABASE_QUERY, false)) { findAndHookMethod( SQLiteDatabase, "rawQueryWithFactory", SQLiteCursorFactory, C.String, C.StringArray, C.String, SQLiteCancellationSignal, object : XC_MethodHook() { @Throws(Throwable::class) override fun beforeHookedMethod(param: MethodHookParam) { val sql = param.args[1] as String? val selectionArgs = param.args[2] as Array<*>? log("DB => query sql = $sql, selectionArgs = ${argsToString(selectionArgs)}, db = ${param.thisObject}") } }) } if (pref.getBoolean(DEVELOPER_DATABASE_INSERT, false)) { findAndHookMethod( SQLiteDatabase, "insertWithOnConflict", C.String, C.String, C.ContentValues, C.Int, object : XC_MethodHook() { @Throws(Throwable::class) override fun beforeHookedMethod(param: MethodHookParam) { val table = param.args[0] as String? val values = param.args[2] as ContentValues? log("DB => insert table = $table, values = $values, db = ${param.thisObject}") } }) } if (pref.getBoolean(DEVELOPER_DATABASE_UPDATE, false)) { findAndHookMethod( SQLiteDatabase, "updateWithOnConflict", C.String, C.ContentValues, C.String, C.StringArray, C.Int, object : XC_MethodHook() { @Throws(Throwable::class) override fun beforeHookedMethod(param: MethodHookParam) { val table = param.args[0] as String? val values = param.args[1] as ContentValues? val whereClause = param.args[2] as String? val whereArgs = param.args[3] as Array<*>? log("DB => update " + "table = $table, " + "values = $values, " + "whereClause = $whereClause, " + "whereArgs = ${argsToString(whereArgs)}, " + "db = ${param.thisObject}") } }) } if (pref.getBoolean(DEVELOPER_DATABASE_DELETE, false)) { findAndHookMethod( SQLiteDatabase, "delete", C.String, C.String, C.StringArray, object : XC_MethodHook() { @Throws(Throwable::class) override fun beforeHookedMethod(param: MethodHookParam) { val table = param.args[0] as String? val whereClause = param.args[1] as String? val whereArgs = param.args[2] as Array<*>? log("DB => delete " + "table = $table, " + "whereClause = $whereClause, " + "whereArgs = ${argsToString(whereArgs)}, " + "db = ${param.thisObject}") } }) } if (pref.getBoolean(DEVELOPER_DATABASE_EXECUTE, false)) { findAndHookMethod( SQLiteDatabase, "executeSql", C.String, C.ObjectArray, SQLiteCancellationSignal, object : XC_MethodHook() { @Throws(Throwable::class) override fun beforeHookedMethod(param: MethodHookParam) { val sql = param.args[0] as String? val bindArgs = param.args[1] as Array<*>? log("DB => executeSql sql = $sql, bindArgs = ${argsToString(bindArgs)}, db = ${param.thisObject}") } }) } } // Hook Log to trace hidden logcat output. private val traceLogcatHooker = Hooker { if (pref.getBoolean(DEVELOPER_TRACE_LOGCAT, false)) { val functions = listOf("d", "e", "f", "i", "v", "w") functions.forEach { func -> findAndHookMethod(Logcat, func, C.String, C.String, C.ObjectArray, object : XC_MethodHook() { override fun afterHookedMethod(param: MethodHookParam) { val tag = param.args[0] as String? val msg = param.args[1] as String? val args = param.args[2] as Array<*>? if (args == null) { log("LOG.${func.toUpperCase()} => [$tag] $msg") } else { log("LOG.${func.toUpperCase()} => [$tag] ${msg?.format(*args)}") } } }) } } } // Hook FileInputStream / FileOutputStream to trace file operations. private val traceFilesHooker = Hooker { if (pref.getBoolean(DEVELOPER_TRACE_FILES, false)) { findAndHookConstructor(C.FileInputStream, C.File, object : XC_MethodHook() { @Throws(Throwable::class) override fun beforeHookedMethod(param: MethodHookParam) { val path = (param.args[0] as File?)?.absolutePath ?: return log("FILE => Read $path") } }) findAndHookConstructor(C.FileOutputStream, C.File, C.Boolean, object : XC_MethodHook() { @Throws(Throwable::class) override fun beforeHookedMethod(param: MethodHookParam) { val path = (param.args[0] as File?)?.absolutePath ?: return log("FILE => Write $path") } }) findAndHookMethod(C.File, "delete", object : XC_MethodHook() { override fun beforeHookedMethod(param: MethodHookParam) { val file = param.thisObject as File log("FILE => Delete ${file.absolutePath}") } }) } } // Hook XML Parser to trace the XML files used in Wechat. private val traceXMLParseHooker = Hooker { if (pref.getBoolean(DEVELOPER_XML_PARSER, false)) { hookMethod(XmlParser_parse, object : XC_MethodHook() { @Throws(Throwable::class) override fun afterHookedMethod(param: MethodHookParam) { val xml = param.args[0] as String? val root = param.args[1] as String? log("XML => root = $root, xml = $xml") } }) } } }
gpl-3.0
dc7c491d6b14b17528a5d316cc1f8d3e
46.846743
128
0.570113
4.786125
false
false
false
false
kunalsheth/units-of-measure
plugin/src/main/kotlin/info/kunalsheth/units/data/Relation.kt
1
3536
/* * Copyright 2019 Kunal Sheth * * 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 info.kunalsheth.units.data import info.kunalsheth.units.data.RelationType.Divide import info.kunalsheth.units.data.RelationType.Multiply import java.io.Serializable /** * Created by kunal on 8/5/17. */ data class Relation(val a: Dimension, val f: RelationType, val b: Dimension) : Serializable { val result = f(a, b) companion object { private fun Set<Dimension>.permuteRelations() = flatMap { x -> flatMap { y -> listOf( Relation(x, Divide, x), Relation(x, Divide, y), Relation(x, Multiply, x), Relation(x, Multiply, y), Relation(y, Divide, x), Relation(y, Divide, y), Relation(y, Multiply, x), Relation(y, Multiply, y) ) } } fun closedPermute(inputDimensions: Set<Dimension>) = inputDimensions.permuteRelations() .filter { arrayOf(it.a, it.b, it.result).all { it in inputDimensions } } .toSet() fun openPermute(inputDimensions: Set<Dimension>): Set<Relation> { val newDimensions = inputDimensions + inputDimensions.permuteRelations().map(Relation::result) return newDimensions .permuteRelations() .filter { arrayOf(it.a, it.b, it.result).all { it in newDimensions } } .toSet() } } } enum class RelationType : (Dimension, Dimension) -> Dimension { Divide { override fun invoke(a: Dimension, b: Dimension) = Dimension( L = a.L - b.L, A = a.A - b.A, M = a.M - b.M, T = a.T - b.T, I = a.I - b.I, Theta = a.Theta - b.Theta, N = a.N - b.N, J = a.J - b.J ) }, Multiply { override fun invoke(a: Dimension, b: Dimension) = Dimension( L = a.L + b.L, A = a.A + b.A, M = a.M + b.M, T = a.T + b.T, I = a.I + b.I, Theta = a.Theta + b.Theta, N = a.N + b.N, J = a.J + b.J ) } }
mit
fc0ca07762a912fac76cd319cfae8837
39.193182
129
0.542138
4.442211
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/types/infer/Unify.kt
3
4211
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.types.infer import org.rust.lang.utils.snapshot.Snapshot import org.rust.lang.utils.snapshot.UndoLog import org.rust.lang.utils.snapshot.Undoable interface NodeOrValue interface Node: NodeOrValue { var parent: NodeOrValue } data class VarValue<out V>(val value: V?, val rank: Int): NodeOrValue /** * [UnificationTable] is map from [K] to [V] with additional ability * to redirect certain K's to a single V en-masse with the help of * disjoint set union. * * We implement Tarjan's union-find * algorithm: when two keys are unified, one of them is converted * into a "redirect" pointing at the other. These redirects form a * DAG: the roots of the DAG (nodes that are not redirected) are each * associated with a value of type `V` and a rank. The rank is used * to keep the DAG relatively balanced, which helps keep the running * time of the algorithm under control. For more information, see * [Disjoint-set data structure](https://en.wikipedia.org/wiki/Disjoint-set_data_structure). */ @Suppress("UNCHECKED_CAST") class UnificationTable<K : Node, V> { private val undoLog: UndoLog = UndoLog() @Suppress("UNCHECKED_CAST") private data class Root<out K: Node, out V>(val key: K) { private val varValue: VarValue<V> = key.parent as VarValue<V> val rank: Int get() = varValue.rank val value: V? get() = varValue.value } private fun get(key: Node): Root<K, V> { val parent = key.parent return if (parent is Node) { val root = get(parent) if (key.parent != root.key) { logNodeState(key) key.parent = root.key // Path compression } root } else { Root(key as K) } } private fun setValue(root: Root<K, V>, value: V) { logNodeState(root.key) root.key.parent = VarValue(value, root.rank) } private fun unify(rootA: Root<K, V>, rootB: Root<K, V>, newValue: V?): K { return when { // a has greater rank, so a should become b's parent, // i.e., b should redirect to a. rootA.rank > rootB.rank -> redirectRoot(rootA.rank, rootB, rootA, newValue) // b has greater rank, so a should redirect to b. rootA.rank < rootB.rank -> redirectRoot(rootB.rank, rootA, rootB, newValue) // If equal, redirect one to the other and increment the // other's rank. else -> redirectRoot(rootA.rank + 1, rootA, rootB, newValue) } } private fun redirectRoot(newRank: Int, oldRoot: Root<K, V>, newRoot: Root<K, V>, newValue: V?): K { val oldRootKey = oldRoot.key val newRootKey = newRoot.key logNodeState(newRootKey) logNodeState(oldRootKey) oldRootKey.parent = newRootKey newRootKey.parent = VarValue(newValue, newRank) return newRootKey } fun findRoot(key: K): K = get(key).key fun findValue(key: K): V? = get(key).value fun unifyVarVar(key1: K, key2: K): K { val node1 = get(key1) val node2 = get(key2) if (node1.key == node2.key) return node1.key // already unified val val1 = node1.value val val2 = node2.value val newVal = if (val1 != null && val2 != null) { if (val1 != val2) error("unification error") // must be solved on the upper level val1 } else { val1 ?: val2 } return unify(node1, node2, newVal) } fun unifyVarValue(key: K, value: V) { val node = get(key) if (node.value != null && node.value != value) error("unification error") // must be solved on the upper level setValue(node, value) } private fun logNodeState(node: Node) { undoLog.logChange(SetParent(node, node.parent)) } fun startSnapshot(): Snapshot = undoLog.startSnapshot() private data class SetParent(private val node: Node, private val oldParent: NodeOrValue) : Undoable { override fun undo() { node.parent = oldParent } } }
mit
2ecc5615fb9500991c76883c81cd9b8d
32.420635
118
0.620518
3.821234
false
false
false
false
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt
1
523
package com.baeldung.constructor open class Person( val name: String, val age: Int? = null ) { val upperCaseName: String = name.toUpperCase() init { println("Hello, I'm $name") if (age != null && age < 0) { throw IllegalArgumentException("Age cannot be less than zero!") } } init { println("upperCaseName is $upperCaseName") } } fun main(args: Array<String>) { val person = Person("John") val personWithAge = Person("John", 22) }
gpl-3.0
399bb18e5bd03bd4cad160a96a5b9cf2
19.153846
75
0.577438
3.962121
false
false
false
false
pyamsoft/power-manager
powermanager-base/src/main/java/com/pyamsoft/powermanager/base/states/DataSaverStateObserver.kt
1
1299
/* * Copyright 2017 Peter Kenji Yamanaka * * 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.pyamsoft.powermanager.base.states import com.pyamsoft.powermanager.model.StateObserver import com.pyamsoft.powermanager.model.States import timber.log.Timber import javax.inject.Inject internal class DataSaverStateObserver @Inject internal constructor( private val wrapper: DeviceFunctionWrapper) : StateObserver { init { Timber.d("New StateObserver for Data Saver") } override fun enabled(): Boolean { val enabled = wrapper.state === States.ENABLED Timber.d("Enabled: %s", enabled) return enabled } override fun unknown(): Boolean { val unknown = wrapper.state === States.UNKNOWN Timber.d("Unknown: %s", unknown) return unknown } }
apache-2.0
c92b312a0e2ae399c2c396cccc10704d
29.928571
75
0.73749
4.33
false
false
false
false
MakinGiants/caty
app/src/main/java/com/makingiants/caty/screens/settings/SettingsPresenter.kt
2
1331
package com.makingiants.caty.screens.settings import com.makingiants.caty.model.cache.Settings import com.makingiants.caty.model.notifications.Notifier open class SettingsPresenter(val settings: Settings, val notifier: Notifier) { private var view: SettingsView? = null fun attach(view: SettingsView) { this.view = view if (settings.notificationPermissionGranted) { view.setupViews() view.setHeadphonesToggleCheck(settings.playJustWithHeadphones) view.setReadNotificationsCheck(settings.readNotificationEnabled) view.setReadOnlyMessageNotificationsCheck(settings.readJustMessages) setOtherViewsEnabled(settings.readNotificationEnabled) } else { view.startWelcomeView() view.close() } } fun unAttach() { view = null } fun onSwitchPlayJustWithHeadphonesClick(checked: Boolean) { settings.playJustWithHeadphones = checked } fun onButtonTryClick(text: String) { notifier.notify("Test", text) } fun onSwitchReadNotificationEnabledClick(checked: Boolean) { settings.readNotificationEnabled = checked setOtherViewsEnabled(checked) } open fun setOtherViewsEnabled(enabled: Boolean) { view?.apply { setEnabledSwitchPlayJustWithHeadphones(enabled) setEnabledSwitchPlayJustMessageNotifications(enabled) } } }
mit
d139cfe5ebcab22545e215f8ee01b17c
26.75
78
0.755071
4.496622
false
false
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/cabal/psi/Benchmark.kt
1
1257
package org.jetbrains.cabal.psi import com.intellij.lang.ASTNode import org.jetbrains.cabal.parser.* import org.jetbrains.cabal.psi.Name import java.util.ArrayList import org.jetbrains.cabal.highlight.ErrorMessage import java.lang.IllegalStateException public class Benchmark(node: ASTNode) : BuildSection(node) { public override fun getAvailableFieldNames(): List<String> { var res = ArrayList<String>() res.addAll(BENCHMARK_FIELDS.keySet()) res.addAll(IF_ELSE) return res } public override fun check(): List<ErrorMessage> { val res = ArrayList<ErrorMessage>() val typeField = getField(javaClass<TypeField>()) val mainIsField = getField(javaClass<MainFileField>()) if (typeField == null) { res.add(ErrorMessage(getSectTypeNode(), "type field is required", "error")) } if ((typeField?.getValue()?.getText() == "exitcode-stdio-1.0") && (mainIsField == null)) { res.add(ErrorMessage(getSectTypeNode(), "main-is field is required", "error")) } return res } public fun getBenchmarkName(): String { val res = getSectName() if (res == null) throw IllegalStateException() return res } }
apache-2.0
5ee0c78d7c337a2c5410a25f603ac24a
31.230769
98
0.653938
4.246622
false
false
false
false
felipebz/sonar-plsql
zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/SelectAllColumnsCheck.kt
1
3216
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plsqlopen.checks import com.felipebz.flr.api.AstNode import org.sonar.plsqlopen.typeIs import org.sonar.plugins.plsqlopen.api.DmlGrammar import org.sonar.plugins.plsqlopen.api.PlSqlGrammar import org.sonar.plugins.plsqlopen.api.PlSqlPunctuator import org.sonar.plugins.plsqlopen.api.annotations.* import org.sonar.plugins.plsqlopen.api.symbols.PlSqlType @Rule(priority = Priority.MAJOR, tags = [Tags.PERFORMANCE]) @ConstantRemediation("30min") @RuleInfo(scope = RuleInfo.Scope.ALL) @ActivatedByDefault class SelectAllColumnsCheck : AbstractBaseCheck() { override fun init() { subscribeTo(DmlGrammar.SELECT_COLUMN) } override fun visitNode(node: AstNode) { val topParent = node.parent.parent.parent if (topParent.typeIs(PlSqlGrammar.EXISTS_EXPRESSION)) { return } if (topParent.typeIs(PlSqlGrammar.CURSOR_DECLARATION)) { // TODO this is very complex and it probably can be simplified in the future val fetchDestination = semantic(topParent.getFirstChild(PlSqlGrammar.IDENTIFIER_NAME)) .symbol?.usages().orEmpty() .map { it.parent.parent } .filter { it.typeIs(PlSqlGrammar.FETCH_STATEMENT) } .map { it.getFirstChild(DmlGrammar.INTO_CLAUSE).getFirstChildOrNull(PlSqlGrammar.VARIABLE_NAME) } .firstOrNull() if (fetchDestination != null && semantic(fetchDestination).plSqlType == PlSqlType.ROWTYPE) { return } } var candidate = node.firstChild if (candidate.typeIs(PlSqlGrammar.OBJECT_REFERENCE)) { candidate = candidate.lastChild } if (candidate.typeIs(PlSqlPunctuator.MULTIPLICATION)) { val intoClause = node.parent.getFirstChildOrNull(DmlGrammar.INTO_CLAUSE) if (intoClause != null) { val variablesInInto = intoClause.getChildren(PlSqlGrammar.VARIABLE_NAME, PlSqlGrammar.MEMBER_EXPRESSION, PlSqlGrammar.METHOD_CALL) val type = semantic(variablesInInto[0]).plSqlType if (variablesInInto.size == 1 && (type == PlSqlType.ROWTYPE || type == PlSqlType.ASSOCIATIVE_ARRAY)) { return } } addIssue(node, getLocalizedMessage()) } } }
lgpl-3.0
73521e09f3136a594fbcf0bf87c403e1
38.219512
146
0.680348
4.466667
false
false
false
false
jguerinet/form-generator
library/src/main/java/base/BaseTextInputItem.kt
1
2817
/* * Copyright 2015-2019 Julien Guerinet * * 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.guerinet.morf.base import android.view.View import android.widget.EditText import android.widget.LinearLayout import androidx.annotation.StringRes import com.google.android.material.textfield.TextInputLayout import com.guerinet.morf.Morf import com.guerinet.morf.util.Layout /** * Based form item for a [TextInputLayout] * @author Julien Guerinet * @since 3.0.0 * * @param morf [Morf] instance * @param view Item [View] */ open class BaseTextInputItem<T : BaseTextInputItem<T, V>, V : EditText>(morf: Morf, view: V) : BaseEditTextItem<T, V>(morf, view, false) { private val inputLayout = TextInputLayout(morf.context) init { inputLayout.layoutParams = LinearLayout.LayoutParams(Layout.MATCH_PARENT, Layout.WRAP_CONTENT) // Add the view to the input layout inputLayout.addView(view) } var isPasswordVisibilityToggleEnabled: Boolean get() = error("Setter only") set(value) { inputLayout.isPasswordVisibilityToggleEnabled = value } /** * @return Item with the password visibility toggle shown or not depending on [isEnabled] */ fun showPasswordVisibilityToggle(isEnabled: Boolean): T = setAndReturn { this.isPasswordVisibilityToggleEnabled = isEnabled } override var hint: String? get() = super.hint set(value) { inputLayout.hint = value } override fun hint(hint: String?): T = setAndReturn { this.hint = hint } override var hintId: Int get() = super.hintId set(@StringRes value) { hint(view.resources.getString(value)) } override fun hint(stringId: Int): T = setAndReturn { this.hintId = stringId } override var backgroundId: Int get() = super.backgroundId set(value) = inputLayout.setBackgroundResource(value) override fun backgroundId(backgroundId: Int): T = setAndReturn { this.backgroundId = backgroundId } override fun build(): T { // Add the input layout to the container, not the view if (inputLayout.parent == null) { morf.addView(inputLayout) } return super.build() } }
apache-2.0
1d1ee634d36982bc6cf81b71916adea0
29.956044
93
0.676606
4.347222
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/osm/elementgeometry/NodeWayMap.kt
1
1187
package de.westnordost.streetcomplete.data.osm.elementgeometry /** Knows which vertices connect which ways. T is the identifier of a vertex */ class NodeWayMap<T>(ways: List<List<T>>) { private val wayEndpoints = LinkedHashMap<T, MutableList<List<T>>>() init { for (way in ways) { val firstNode = way.first() val lastNode = way.last() wayEndpoints.getOrPut(firstNode, { ArrayList() }).add(way) wayEndpoints.getOrPut(lastNode, { ArrayList() }).add(way) } } fun hasNextNode(): Boolean = wayEndpoints.isNotEmpty() fun getNextNode(): T = wayEndpoints.keys.iterator().next() fun getWaysAtNode(node: T): List<List<T>>? = wayEndpoints[node] fun removeWay(way: List<T>) { val it = wayEndpoints.values.iterator() while (it.hasNext()) { val waysPerNode = it.next() val waysIt = waysPerNode.iterator() while (waysIt.hasNext()) { if (waysIt.next() === way) { waysIt.remove() } } if (waysPerNode.isEmpty()) { it.remove() } } } }
gpl-3.0
9f1702077fc634d69b2992b10353c17c
27.95122
80
0.551811
4.20922
false
false
false
false
schneppd/lab.schneppd.android2017.opengl2
MyApplication/app/src/main/java/com/schneppd/myopenglapp/MainActivity.kt
1
3991
package com.schneppd.myopenglapp import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import android.os.Environment import android.provider.MediaStore import android.support.design.widget.FloatingActionButton import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.View import android.view.Menu import android.view.MenuItem import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.content_main.* import org.jetbrains.anko.imageBitmap import java.io.File import android.os.Environment.DIRECTORY_PICTURES import android.support.v4.content.FileProvider import java.text.SimpleDateFormat import java.util.* class MainActivity : AppCompatActivity() { companion object Static { val REQUEST_IMAGE_CAPTURE = 1 val REQUEST_TAKE_PHOTO = 1 } var currentPhotoPath = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) /* val fab = findViewById(R.id.fab) as FloatingActionButton fab.setOnClickListener { view -> onClickTestButton(view) } */ } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. when(item.itemId){ R.id.action_photo -> onTakePhoto() R.id.action_import_model -> onChangeModel() } return super.onOptionsItemSelected(item) } fun onChangeModel() { //Snackbar.make(v, "Change model", Snackbar.LENGTH_LONG).setAction("Action", null).show() if(svUserModel.visibility == View.VISIBLE) svUserModel.visibility = View.INVISIBLE else svUserModel.visibility = View.VISIBLE } fun onTakePhoto() { //Snackbar.make(v, "Taking photo for background", Snackbar.LENGTH_LONG).setAction("Action", null).show() val takePictureIntent: Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) val serviceProvider = takePictureIntent.resolveActivity(packageManager) serviceProvider?.let { var photoFile:File? = createImageSaveFile() photoFile?: return val photoURI = FileProvider.getUriForFile(this, "com.schneppd.myopenglapp.fileprovider", photoFile) takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI) //startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE) startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO) }?: Snackbar.make(ivUserPicture, "No photo app installed", Snackbar.LENGTH_LONG).setAction("Action", null).show() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { /* val extras = data!!.extras val rawImageBitmap = extras.get("data") as Bitmap val imageBitmap = Bitmap.createScaledBitmap(rawImageBitmap, ivUserPicture.width, ivUserPicture.height, true) ivUserPicture.imageBitmap = imageBitmap */ val fileUri = "file://" + currentPhotoPath Picasso.with(this).load(fileUri).resize(ivUserPicture.width, ivUserPicture.height).centerCrop().into(ivUserPicture) } super.onActivityResult(requestCode, resultCode, data) } private fun createImageSaveFile() : File{ val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date()) val imageFileName = "JPEG_" + timeStamp + "_" val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES) val image = File.createTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ) currentPhotoPath = image.absolutePath return image } }
gpl-3.0
fdfbfc4ca14e9b512214de9671da7e60
31.983471
118
0.761964
3.963257
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/profile/ui/activity/ProfileActivity.kt
1
2593
package org.stepik.android.view.profile.ui.activity import android.content.Context import android.content.Intent import android.content.pm.ShortcutManager import android.net.Uri import android.os.Bundle import android.view.MenuItem import androidx.appcompat.app.AppCompatDelegate import androidx.fragment.app.Fragment import org.stepic.droid.R import org.stepic.droid.analytic.Analytic import org.stepic.droid.base.SingleFragmentActivity import org.stepic.droid.ui.activities.contracts.CloseButtonInToolbar import org.stepic.droid.util.AppConstants import org.stepik.android.view.profile.ui.fragment.ProfileFragment class ProfileActivity : SingleFragmentActivity(), CloseButtonInToolbar { companion object { private const val EXTRA_USER_ID = "user_id" init { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) } fun createIntent(context: Context, userId: Long): Intent = Intent(context, ProfileActivity::class.java) .putExtra(EXTRA_USER_ID, userId) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null && intent.action == AppConstants.OPEN_SHORTCUT_PROFILE) { analytic.reportEvent(Analytic.Shortcut.OPEN_PROFILE) if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N_MR1) { getSystemService(ShortcutManager::class.java)?.reportShortcutUsed(AppConstants.PROFILE_SHORTCUT_ID) } } } override fun createFragment(): Fragment { val userId = intent .getLongExtra(EXTRA_USER_ID, 0) .takeIf { it > 0 } ?: getUserId(intent.data) return ProfileFragment.newInstance(userId) } private fun getUserId(dataUri: Uri?): Long { if (dataUri == null) return 0 analytic.reportEvent(Analytic.Profile.OPEN_BY_LINK) return try { dataUri.pathSegments[1].toLong() } catch (exception: NumberFormatException) { -1 } } override fun onOptionsItemSelected(item: MenuItem?): Boolean = when (item?.itemId) { android.R.id.home -> { onBackPressed() true } else -> super.onOptionsItemSelected(item) } override fun onBackPressed() { super.onBackPressed() finish() } override fun finish() { super.finish() overridePendingTransition(R.anim.no_transition, R.anim.push_down) } }
apache-2.0
0966d01da00745bfc85c9a882908f66a
31.4125
115
0.659082
4.622103
false
false
false
false
jiaminglu/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/util/util.kt
1
1427
/* * 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.util import kotlin.system.measureTimeMillis fun printMillisec(message: String, body: () -> Unit) { val msec = measureTimeMillis{ body() } println("$message: $msec msec") } fun profile(message: String, body: () -> Unit) = profileIf( System.getProperty("konan.profile")?.equals("true") ?: false, message, body) fun profileIf(condition: Boolean, message: String, body: () -> Unit) = if (condition) printMillisec(message, body) else body() fun nTabs(amount: Int): String { return String.format("%1$-${(amount+1)*4}s", "") } fun String.suffixIfNot(suffix: String) = if (this.endsWith(suffix)) this else "$this$suffix" fun String.removeSuffixIfPresent(suffix: String) = if (this.endsWith(suffix)) this.dropLast(suffix.length) else this
apache-2.0
48d7feca49156e4f55c676b674e2e19c
32.186047
75
0.707779
3.735602
false
false
false
false
Lucas-Lu/KotlinWorld
anko-example-master/app/src/main/java/org/example/ankodemo/MainActivity.kt
1
2192
package org.example.ankodemo import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.text.InputType.TYPE_CLASS_TEXT import android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD import android.view.Gravity import android.widget.Button import android.widget.EditText import org.jetbrains.anko.* import org.jetbrains.anko.sdk25.coroutines.onClick class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) MainActivityUi().setContentView(this) } fun tryLogin(ui: AnkoContext<MainActivity>, name: CharSequence?, password: CharSequence?) { ui.doAsync { Thread.sleep(500) activityUiThreadWithContext { if (checkCredentials(name.toString(), password.toString())) { toast("Logged in! :)") startActivity<CountriesActivity>() } else { toast("Wrong password :( Enter user:password") } } } } private fun checkCredentials(name: String, password: String) = name == "user" && password == "password" } class MainActivityUi : AnkoComponent<MainActivity> { private val customStyle = { v: Any -> when (v) { is Button -> v.textSize = 26f is EditText -> v.textSize = 24f } } override fun createView(ui: AnkoContext<MainActivity>) = with(ui) { verticalLayout { padding = dip(32) imageView(android.R.drawable.ic_menu_manage).lparams { margin = dip(16) gravity = Gravity.CENTER } val name = editText { hintResource = R.string.name } val password = editText { hintResource = R.string.password inputType = TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_PASSWORD } button("Log in") { onClick { ui.owner.tryLogin(ui, name.text, password.text) } } myRichView() }.applyRecursively(customStyle) } }
mit
78ea6234e0d64e8522a9f40a253ad1a5
29.887324
107
0.583029
4.765217
false
false
false
false
agrawalsuneet/DotsLoader
dotsloader/src/main/java/com/agrawalsuneet/dotsloader/loaders/BounceLoader.kt
1
8832
package com.agrawalsuneet.dotsloader.loaders import android.content.Context import android.util.AttributeSet import android.view.View import android.view.ViewGroup import android.view.ViewTreeObserver import android.view.animation.* import android.widget.LinearLayout import android.widget.RelativeLayout import com.agrawalsuneet.dotsloader.R import com.agrawalsuneet.dotsloader.basicviews.CircleView import com.agrawalsuneet.dotsloader.contracts.LoaderContract /** * Created by agrawalsuneet on 4/13/19. */ class BounceLoader : LinearLayout, LoaderContract { var ballRadius: Int = 60 var ballColor: Int = resources.getColor(android.R.color.holo_red_dark) var showShadow: Boolean = true var shadowColor: Int = resources.getColor(android.R.color.black) var animDuration: Int = 1500 set(value) { field = if (value <= 0) 1000 else value } private var relativeLayout: RelativeLayout? = null private var ballCircleView: CircleView? = null private var ballShadowView: CircleView? = null private var calWidth: Int = 0 private var calHeight: Int = 0 private val STATE_GOINGDOWN: Int = 0 private val STATE_SQUEEZING: Int = 1 private val STATE_RESIZING: Int = 2 private val STATE_COMINGUP: Int = 3 private var state: Int = STATE_GOINGDOWN constructor(context: Context?) : super(context) { initView() } constructor(context: Context?, attrs: AttributeSet) : super(context, attrs) { initAttributes(attrs) initView() } constructor(context: Context?, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { initAttributes(attrs) initView() } constructor(context: Context?, ballRadius: Int, ballColor: Int, showShadow: Boolean, shadowColor: Int = 0) : super(context) { this.ballRadius = ballRadius this.ballColor = ballColor this.shadowColor = shadowColor initView() } override fun initAttributes(attrs: AttributeSet) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.BounceLoader, 0, 0) this.ballRadius = typedArray.getDimensionPixelSize(R.styleable.BounceLoader_bounce_ballRadius, 60) this.ballColor = typedArray.getColor(R.styleable.BounceLoader_bounce_ballColor, resources.getColor(android.R.color.holo_red_dark)) this.shadowColor = typedArray.getColor(R.styleable.BounceLoader_bounce_shadowColor, resources.getColor(android.R.color.black)) this.showShadow = typedArray.getBoolean(R.styleable.BounceLoader_bounce_showShadow, true) this.animDuration = typedArray.getInt(R.styleable.BounceLoader_bounce_animDuration, 1500) typedArray.recycle() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) if (calWidth == 0 || calHeight == 0) { calWidth = 5 * ballRadius calHeight = 8 * ballRadius } setMeasuredDimension(calWidth, calHeight) } private fun initView() { removeAllViews() removeAllViewsInLayout() if (calWidth == 0 || calHeight == 0) { calWidth = 5 * ballRadius calHeight = 8 * ballRadius } relativeLayout = RelativeLayout(context) if (showShadow) { ballShadowView = CircleView(context = context, circleRadius = ballRadius, circleColor = shadowColor, isAntiAlias = false) val shadowParam = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) shadowParam.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE) shadowParam.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE) relativeLayout?.addView(ballShadowView, shadowParam) } ballCircleView = CircleView(context = context, circleRadius = ballRadius, circleColor = ballColor) val ballParam = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) ballParam.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE) ballParam.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE) relativeLayout?.addView(ballCircleView, ballParam) val relParam = RelativeLayout.LayoutParams(calWidth, calHeight) this.addView(relativeLayout, relParam) viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { startLoading() [email protected](this) } }) } private fun startLoading() { val ballAnim = getBallAnimation() ballAnim.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationEnd(anim: Animation?) { state = (state + 1) % 4 startLoading() } override fun onAnimationRepeat(p0: Animation?) { } override fun onAnimationStart(p0: Animation?) { } }) if (showShadow) { if (state == STATE_SQUEEZING || state == STATE_RESIZING) { ballShadowView?.clearAnimation() ballShadowView?.visibility = View.GONE } else { ballShadowView?.visibility = View.VISIBLE val shadowAnim = getShadowAnimation() ballShadowView?.startAnimation(shadowAnim) } } ballCircleView?.startAnimation(ballAnim) } private fun getBallAnimation(): Animation { return when (state) { STATE_GOINGDOWN -> { TranslateAnimation(0.0f, 0.0f, (-6 * ballRadius).toFloat(), 0.0f) .apply { duration = animDuration.toLong() interpolator = AccelerateInterpolator() } } STATE_SQUEEZING -> { ScaleAnimation(1.0f, 1.0f, 1.0f, 0.85f , ballRadius.toFloat(), (2 * ballRadius).toFloat()) .apply { duration = (animDuration / 20).toLong() interpolator = AccelerateInterpolator() } } STATE_RESIZING -> { ScaleAnimation(1.0f, 1.0f, 0.85f, 1.0f , ballRadius.toFloat(), (2 * ballRadius).toFloat()) .apply { duration = (animDuration / 20).toLong() interpolator = DecelerateInterpolator() } } else -> { TranslateAnimation(0.0f, 0.0f, 0.0f, (-6 * ballRadius).toFloat()) .apply { duration = animDuration.toLong() interpolator = DecelerateInterpolator() } } }.apply { fillAfter = true repeatCount = 0 } } private fun getShadowAnimation(): AnimationSet { val transAnim: Animation val scaleAnim: Animation val alphaAnim: AlphaAnimation val set = AnimationSet(true) when (state) { STATE_COMINGUP -> { transAnim = TranslateAnimation(0.0f, (-4 * ballRadius).toFloat(), 0.0f, (-3 * ballRadius).toFloat()) scaleAnim = ScaleAnimation(0.9f, 0.5f, 0.9f, 0.5f, ballRadius.toFloat(), ballRadius.toFloat()) alphaAnim = AlphaAnimation(0.6f, 0.2f) set.interpolator = DecelerateInterpolator() } else -> { transAnim = TranslateAnimation((-4 * ballRadius).toFloat(), 0.0f, (-3 * ballRadius).toFloat(), 0.0f) scaleAnim = ScaleAnimation(0.5f, 0.9f, 0.5f, 0.9f, ballRadius.toFloat(), ballRadius.toFloat()) alphaAnim = AlphaAnimation(0.2f, 0.6f) set.interpolator = AccelerateInterpolator() } } set.addAnimation(transAnim) set.addAnimation(scaleAnim) set.addAnimation(alphaAnim) set.apply { duration = animDuration.toLong() fillAfter = true repeatCount = 0 } return set } }
apache-2.0
ab1e33fd75aa76d07520e4097be5ee79
32.71374
129
0.585711
5.189189
false
false
false
false
MrSugarCaney/DirtyArrows
src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/ShearBow.kt
1
6626
package nl.sugcube.dirtyarrows.bow.ability import nl.sugcube.dirtyarrows.DirtyArrows import nl.sugcube.dirtyarrows.bow.BowAbility import nl.sugcube.dirtyarrows.bow.DefaultBow import nl.sugcube.dirtyarrows.util.* import org.bukkit.Location import org.bukkit.Material import org.bukkit.block.Block import org.bukkit.enchantments.Enchantment import org.bukkit.entity.* import org.bukkit.event.entity.ProjectileHitEvent import org.bukkit.inventory.ItemStack import kotlin.random.Random /** * Breaks and drops all shearable blocks. * Shears sheep in range on impact. * Shears mooshrooms in range on impact. * Shears snow golems in range on impact. * * @author SugarCaney */ open class ShearBow(plugin: DirtyArrows) : BowAbility( plugin = plugin, type = DefaultBow.SHEAR, handleEveryNTicks = 1, canShootInProtectedRegions = false, removeArrow = true, description = "Breaks all shearable blocks." ) { /** * The range around the location of impact where special blocks/entities (sheep, pumpkins, ...), in blocks. */ val impactRange = config.getDouble("$node.impact-range") /** * How much the range increases per power level on the bow, in blocks. */ val rangeIncrease = config.getDouble("$node.range-increase") init { require(impactRange >= 0) { "$node.impact-range must not be negative, got <$impactRange>" } } override fun land(arrow: Arrow, player: Player, event: ProjectileHitEvent) { // When an entity is hit, don't bounce. if (event.hitEntity != null) { arrow.location.impactEffects(player) arrow.remove() return } val hitBlockType = event.hitBlock?.type ?: return if (hitBlockType != Material.AIR && hitBlockType.isShearable.not()) { arrow.location.impactEffects(player) return } event.hitBlock?.shearBlocks() registerArrow(arrow.respawnArrow()) } override fun effect() { arrows.forEach { if (it.location.isInProtectedRegion(it.shooter as? LivingEntity, showError = false).not()) { it.location.block.shearBlocks() } } } /** * Shears all blocks around this block. */ @Suppress("DEPRECATION") private fun Block.shearBlocks() { forXYZ(-1..1, -1..1, -1..1) { dx, dy, dz -> val block = getRelative(dx, dy, dz) val originalType = block.type if (originalType.isShearable) { val itemDrop = ItemStack(originalType, 1, block.itemDataValue().toShort()) block.centreLocation.dropItem(itemDrop) block.type = Material.AIR } } } /** * Get the data value for the item that is dropped by this block. */ @Suppress("DEPRECATION") private fun Block.itemDataValue(): Byte = when (type) { // TODO: Shear Bow Leave block data // Material.LEAVES -> (state.data as Leaves).species.data // Material.LEAVES_2 -> ((state.data as Leaves).species.data - 4).toByte() // Material.LONG_GRASS -> (state.data as LongGrass).species.data // Material.DOUBLE_PLANT -> state.data.data else -> 0 } /** * Processes all effects that happen when the arrow lands. */ private fun Location.impactEffects(player: Player) { val bowItem = player.bowItem() ?: return val lootingLevel = bowItem.getEnchantmentLevel(Enchantment.LOOT_BONUS_MOBS) val powerLevel = bowItem.getEnchantmentLevel(Enchantment.ARROW_DAMAGE) val range = impactRange + powerLevel * rangeIncrease shearSheep(range, lootingLevel) shearMooshrooms(range, lootingLevel) shearSnowGolems(range) } /** * Shears all sheep around this location. * * @param range * How far from this location to check for sheep. * @param lootingLevel * The level of the looting enchantment (0 if not applicable). */ @Suppress("DEPRECATION") private fun Location.shearSheep(range: Double, lootingLevel: Int = 0) = nearbyLivingEntities(range).asSequence() .mapNotNull { it as? Sheep } .filter { it.isSheared.not() } .forEach { // val woolBlocks = Random.nextInt(1, 4) + lootingLevel // val itemDrops = ItemStack(Material.WOOL, woolBlocks, it.color.woolData.toShort()) // it.world.dropItem(it.location, itemDrops) // it.isSheared = true // TODO: Shear Bow Sheep wool drop } /** * Shears all mooshrooms around this location. * * @param range * How far from this location to check for mooshrooms. * @param lootingLevel * The level of the looting enchantment (0 if not applicable). */ private fun Location.shearMooshrooms(range: Double, lootingLevel: Int = 0) = nearbyLivingEntities(range).asSequence() .mapNotNull { it as? MushroomCow } .forEach { val mushrooms = 5 + lootingLevel val mushroomType = if (Random.nextBoolean()) Material.RED_MUSHROOM else Material.BROWN_MUSHROOM val itemDrops = ItemStack(mushroomType, mushrooms) it.world.dropItem(it.location, itemDrops) it.location.spawn(Cow::class) it.remove() } /** * Shears all mooshrooms around this location. * * @param range * How far from this location to check for snow golems. */ private fun Location.shearSnowGolems(range: Double) = nearbyLivingEntities(range).asSequence() .mapNotNull { it as? Snowman } .filter { it.isDerp } .forEach { val itemDrops = ItemStack(Material.PUMPKIN, 1) it.world.dropItem(it.location, itemDrops) it.isDerp = false } /** * Shears all pumpkins around this location. * * @param range * How far from this location to check for pumpkins. * @param lootingLevel * The level of the looting enchantment (0 if not applicable). */ @Suppress("UNUSED_PARAMETER") private fun Location.carvePumpkins(range: Double, lootingLevel: Int = 0) { // TODO: carving pumpkins has been introduced in 1.13 } companion object { /** * The shears item used to break blocks. */ private val SHEARS = ItemStack(Material.SHEARS, 1) } }
gpl-3.0
70ea6a154e5d61f5f2871167020d2fb6
33.696335
121
0.611832
4.316612
false
false
false
false
MarkNKamau/JustJava-Android
app/src/main/java/com/marknkamau/justjava/ui/productDetails/OptionsAdapter.kt
1
1916
package com.marknkamau.justjava.ui.productDetails import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.marknkamau.justjava.R import com.marknkamau.justjava.data.models.AppProductChoiceOption import com.marknkamau.justjava.databinding.ItemProductChoiceOptionBinding import com.marknkamau.justjava.utils.CurrencyFormatter class OptionsAdapter(private val context: Context) : RecyclerView.Adapter<OptionsAdapter.ViewHolder>() { private val items by lazy { mutableListOf<AppProductChoiceOption>() } var onSelected: ((option: AppProductChoiceOption, checked: Boolean) -> Unit)? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = ItemProductChoiceOptionBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(binding) } override fun getItemCount() = items.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(items[position], context) } fun setItems(newItems: List<AppProductChoiceOption>) { items.clear() items.addAll(newItems) notifyDataSetChanged() } inner class ViewHolder( private val binding: ItemProductChoiceOptionBinding ) : RecyclerView.ViewHolder(binding.root) { fun bind(option: AppProductChoiceOption, context: Context) { val formattedPrice = CurrencyFormatter.format(option.price) binding.tvOptionPrice.text = context.getString(R.string.price_listing_w_add, formattedPrice) binding.cbOptionTitle.text = option.name binding.cbOptionTitle.isChecked = option.isChecked binding.cbOptionTitle.setOnClickListener { onSelected?.invoke(option, binding.cbOptionTitle.isChecked) } } } }
apache-2.0
aa9fe8669bf2b0fe23e2d924417f144d
38.916667
112
0.736952
4.875318
false
false
false
false
GabrielCastro/open_otp
app/src/main/kotlin/ca/gabrielcastro/openotp/ui/list/ListPresenterImpl.kt
1
1958
package ca.gabrielcastro.openotp.ui.list import ca.gabrielcastro.openotp.R import ca.gabrielcastro.openotp.db.Database import ca.gabrielcastro.openotp.rx.ioAndMain import rx.Subscription import timber.log.Timber import javax.inject.Inject internal class ListPresenterImpl @Inject constructor( val database: Database ) : ListContract.Presenter { lateinit var view: ListContract.View var listSub: Subscription? = null override fun init(view: ListContract.View) { this.view = view this.view.showEmptyView(false) } override fun pause() { listSub?.unsubscribe() } override fun resume() { listSub = database.list() .ioAndMain() .map { it.map { val iconRes = iconForIssuer(it.userIssuer) ?: iconForIssuer(it.issuer) ?: R.drawable.issuer_default_36 ListContract.ListItem(it.uuid, it.userIssuer, it.userAccountName, iconRes) } } .subscribe { view.showItems(it) this.view.showEmptyView(it.size == 0) } } override fun itemSelected(item: ListContract.ListItem) { Timber.i("selected totp: $item") view.showDetailForId(item.id) } override fun addNewTotp() { Timber.i("add new totp clicked") view.startScanning() } override fun invalidCodeScanned() { Timber.i("invalid code scanned") view.showTemporaryMessage("Invalid Code Scanned") } } val iconMap = listOf( Regex(".*Google.*", RegexOption.IGNORE_CASE) to R.drawable.issuer_google_36, Regex(".*Slack.*", RegexOption.IGNORE_CASE) to R.drawable.issuer_slack_36 ) fun iconForIssuer(issuerName: String) : Int? { return iconMap.find { it.first.matches(issuerName) }?.second }
mit
740357ee7bd9ea83e9dd99533f494a8f
27.376812
98
0.595506
4.45
false
false
false
false
slak44/gitforandroid
app/src/main/java/slak/gitforandroid/MainActivity.kt
1
2805
package slak.gitforandroid import android.app.AlertDialog import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.ArrayAdapter import android.widget.TextView import kotlinx.android.synthetic.main.activity_main.* import java.util.* class MainActivity : AppCompatActivity() { companion object { const val INTENT_REPO_NAME = "slak.gitforandroid.REPO_NAME" } private var repoNames: ArrayList<String> = ArrayList() private var listElements: ArrayAdapter<String>? = null private fun addRepoNames() { repoNames.clear() repoNames.addAll(Arrays.asList(*Repository.getRootDirectory(this).list())) repoNames.sort() } override fun onResume() { addRepoNames() listElements!!.notifyDataSetChanged() super.onResume() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) Thread.setDefaultUncaughtExceptionHandler { thread, throwable -> Log.e("UNCAUGHT DEFAULT", thread.toString(), throwable) } // Force the user to quit if there isn't access to the filesystem if (!Repository.isFilesystemAvailable) { val fatalError = AlertDialog.Builder(this@MainActivity) fatalError .setTitle(R.string.error_storage_unavailable) .setNegativeButton(R.string.app_quit) { _, _ -> // It is impossible to have more than one Activity on the stack at this point // This means the following call terminates the app System.exit(1) } .create() .show() return } addRepoNames() listElements = ArrayAdapter(this, R.layout.list_element_main, repoNames) repoList.adapter = listElements repoList.setOnItemClickListener { _, view: View, _, _ -> val repoViewIntent = Intent(this@MainActivity, RepoViewActivity::class.java) repoViewIntent.putExtra(INTENT_REPO_NAME, (view as TextView).text.toString()) startActivity(repoViewIntent) } fab.setOnClickListener { createRepoDialog(this, fab, { newRepoName -> repoNames.add(newRepoName) listElements!!.notifyDataSetChanged() }) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.settings) { val settingsIntent = Intent(this@MainActivity, SettingsActivity::class.java) startActivity(settingsIntent) return true } return super.onOptionsItemSelected(item) } }
mit
7e71e664eee759dfe30048e5cc196ee6
29.824176
89
0.706239
4.546191
false
false
false
false
qoncept/kaja
src/jp/co/qoncept/kaja/Result.kt
1
2053
package jp.co.qoncept.kaja import jp.co.qoncept.kotres.Result import jp.co.qoncept.kotres.flatMap operator fun Result<Json, JsonException>.get(index: Int): Result<Json, JsonException> { return flatMap { it[index] } } operator fun Result<Json, JsonException>.get(key: String): Result<Json, JsonException> { return flatMap { it[key] } } val Result<Json, JsonException>.boolean: Result<Boolean, JsonException> get() = flatMap { it.boolean } val Result<Json, JsonException>.int: Result<Int, JsonException> get() = flatMap { it.int } val Result<Json, JsonException>.long: Result<Long, JsonException> get() = flatMap { it.long } val Result<Json, JsonException>.double: Result<Double, JsonException> get() = flatMap { it. double} val Result<Json, JsonException>.string: Result<String, JsonException> get() = flatMap { it. string} val Result<Json, JsonException>.list: Result<List<Json>, JsonException> get() = flatMap { it.list } val Result<Json, JsonException>.map: Result<Map<String, Json>, JsonException> get() = flatMap { it.map } fun <T> Result<Json, JsonException>.list(decode: (Json) -> Result<T, JsonException>): Result<List<T>, JsonException> { return flatMap { it.list(decode) } } fun <T> Result<Json, JsonException>.map(decode: (Json) -> Result<T, JsonException>): Result<Map<kotlin.String, T>, JsonException> { return flatMap { it.map(decode) } } fun <T> Result<T, JsonException>.optional(defaultValue: T): Result<T, JsonException> { return when (this) { is Result.Success -> this is Result.Failure -> when (exception) { is MissingKeyException -> Result.Success(defaultValue) else -> this } } } val <T> Result<T, JsonException>.optional: Result<T?, JsonException> get() = when (this) { is Result.Success -> Result.Success(value) is Result.Failure -> when (exception) { is MissingKeyException -> Result.Success(null) else -> Result.Failure(exception) } }
mit
d0bb8e11a53e0502546ec97a6bc1aee6
33.216667
131
0.664881
3.766972
false
false
false
false
k9mail/k-9
app/storage/src/main/java/com/fsck/k9/preferences/migrations/StorageMigrationTo8.kt
2
663
package com.fsck.k9.preferences.migrations import android.database.sqlite.SQLiteDatabase /** * Rewrite theme setting to use `FOLLOW_SYSTEM` when it's currently set to `LIGHT`. */ class StorageMigrationTo8( private val db: SQLiteDatabase, private val migrationsHelper: StorageMigrationsHelper ) { fun rewriteTheme() { val theme = migrationsHelper.readValue(db, "theme") if (theme == THEME_LIGHT) { migrationsHelper.writeValue(db, "theme", THEME_FOLLOW_SYSTEM) } } companion object { private const val THEME_LIGHT = "LIGHT" private const val THEME_FOLLOW_SYSTEM = "FOLLOW_SYSTEM" } }
apache-2.0
496fbe3512ff2da7834b1ed0a44ff88c
27.826087
83
0.678733
4.25
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/test-framework/test/org/jetbrains/kotlin/idea/test/KotlinLightPlatformCodeInsightFixtureTestCase.kt
2
1574
// 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.test import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase import com.intellij.util.ThrowableRunnable import org.jetbrains.kotlin.test.KotlinRoot import java.io.File abstract class KotlinLightPlatformCodeInsightFixtureTestCase : LightPlatformCodeInsightFixtureTestCase() { protected open fun isFirPlugin(): Boolean = false override fun setUp() { super.setUp() enableKotlinOfficialCodeStyle(project) VfsRootAccess.allowRootAccess(myFixture.testRootDisposable, KotlinRoot.DIR.path) if (!isFirPlugin()) { invalidateLibraryCache(project) } } override fun tearDown() { runAll( ThrowableRunnable { disableKotlinOfficialCodeStyle(project) }, ThrowableRunnable { super.tearDown() }, ) } protected fun dataFile(fileName: String): File = File(testDataPath, fileName) protected fun dataFile(): File = dataFile(fileName()) protected fun dataPath(fileName: String = fileName()): String = dataFile(fileName).toString() protected fun dataPath(): String = dataPath(fileName()) protected open fun fileName(): String = KotlinTestUtils.getTestDataFileName(this::class.java, this.name) ?: (getTestName(false) + ".kt") override fun getTestDataPath() = TestMetadataUtil.getTestDataPath(this::class.java) }
apache-2.0
265d28e73c975799dd2a67520e9ce89d
36.47619
140
0.733799
5.160656
false
true
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddEqEqTrueFix.kt
1
1071
// 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.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern class AddEqEqTrueFix(expression: KtExpression) : KotlinQuickFixAction<KtExpression>(expression) { override fun getText() = KotlinBundle.message("fix.add.eq.eq.true") override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val expression = element ?: return expression.replace(KtPsiFactory(expression).createExpressionByPattern("$0 == true", expression)) } }
apache-2.0
026e3f4fdd3ba4e01dc29f0b7a2691ab
45.565217
158
0.792717
4.353659
false
false
false
false
mdaniel/intellij-community
platform/platform-api/src/com/intellij/openapi/progress/tasks.kt
2
3661
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Experimental package com.intellij.openapi.progress import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts.ProgressTitle import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import org.jetbrains.annotations.ApiStatus.Experimental suspend fun <T> withBackgroundProgressIndicator( project: Project, title: @ProgressTitle String, action: suspend CoroutineScope.() -> T ): T { return withBackgroundProgressIndicator(project, title, cancellable = true, action) } suspend fun <T> withBackgroundProgressIndicator( project: Project, title: @ProgressTitle String, cancellable: Boolean, action: suspend CoroutineScope.() -> T ): T { val cancellation = if (cancellable) TaskCancellation.cancellable() else TaskCancellation.nonCancellable() return withBackgroundProgressIndicator(project, title, cancellation, action) } /** * Shows a background progress indicator, and runs the specified [action]. * The action receives [ProgressSink] in the coroutine context, progress sink updates are reflected in the UI during the action. * The indicator is not shown immediately to avoid flickering, * i.e. the user won't see anything if the [action] completes within the given timeout. * * @param project in which frame the progress should be shown * @param cancellation controls the UI appearance, e.g. [TaskCancellation.nonCancellable] or [TaskCancellation.cancellable] * @throws CancellationException if the calling coroutine was cancelled, * or if the indicator was cancelled by the user in the UI */ suspend fun <T> withBackgroundProgressIndicator( project: Project, title: @ProgressTitle String, cancellation: TaskCancellation, action: suspend CoroutineScope.() -> T ): T { val service = ApplicationManager.getApplication().getService(TaskSupport::class.java) return service.withBackgroundProgressIndicatorInternal( project, title, cancellation, action ) } suspend fun <T> withModalProgressIndicator( project: Project, title: @ProgressTitle String, action: suspend CoroutineScope.() -> T, ): T { return withModalProgressIndicator(owner = ModalTaskOwner.project(project), title = title, action = action) } /** * Shows a modal progress indicator, and runs the specified [action]. * The action receives [ProgressSink] in the coroutine context, progress sink updates are reflected in the UI during the action. * The indicator is not shown immediately to avoid flickering, * i.e. the user won't see anything if the [action] completes within the given timeout. * Switches to [com.intellij.openapi.application.EDT] are allowed inside the action, * as they are automatically scheduled with the correct modality, which is the newly entered one. * * @param owner in which frame the progress should be shown * @param cancellation controls the UI appearance, e.g. [TaskCancellation.nonCancellable] or [TaskCancellation.cancellable] * @throws CancellationException if the calling coroutine was cancelled, * or if the indicator was cancelled by the user in the UI */ suspend fun <T> withModalProgressIndicator( owner: ModalTaskOwner, title: @ProgressTitle String, cancellation: TaskCancellation = TaskCancellation.cancellable(), action: suspend CoroutineScope.() -> T, ): T { val service = ApplicationManager.getApplication().getService(TaskSupport::class.java) return service.withModalProgressIndicatorInternal(owner, title, cancellation, action) }
apache-2.0
869622bc4a71e7627444596270b8a8df
43.108434
128
0.783119
4.729974
false
false
false
false
android/nowinandroid
app-nia-catalog/src/main/java/com/google/samples/apps/niacatalog/ui/Catalog.kt
1
29172
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.niacatalog.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.add import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.systemBars import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.google.accompanist.flowlayout.FlowRow import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaDropdownMenuButton import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaFilledButton import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaFilterChip import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationBar import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationBarItem import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaOutlinedButton import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTab import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTabRow import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTextButton import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaToggleButton import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTopicTag import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaViewToggleButton import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme /** * Now in Android component catalog. */ @Composable fun NiaCatalog() { NiaTheme { Surface { val contentPadding = WindowInsets .systemBars .add(WindowInsets(left = 16.dp, top = 16.dp, right = 16.dp, bottom = 16.dp)) .asPaddingValues() LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = contentPadding, verticalArrangement = Arrangement.spacedBy(16.dp) ) { item { Text( text = "NiA Catalog", style = MaterialTheme.typography.headlineSmall, ) } item { Text("Buttons", Modifier.padding(top = 16.dp)) } item { FlowRow(mainAxisSpacing = 16.dp) { NiaFilledButton(onClick = {}) { Text(text = "Enabled") } NiaOutlinedButton(onClick = {}) { Text(text = "Enabled") } NiaTextButton(onClick = {}) { Text(text = "Enabled") } } } item { Text("Disabled buttons", Modifier.padding(top = 16.dp)) } item { FlowRow(mainAxisSpacing = 16.dp) { NiaFilledButton( onClick = {}, enabled = false ) { Text(text = "Disabled") } NiaOutlinedButton( onClick = {}, enabled = false ) { Text(text = "Disabled") } NiaTextButton( onClick = {}, enabled = false ) { Text(text = "Disabled") } } } item { Text("Buttons with leading icons", Modifier.padding(top = 16.dp)) } item { FlowRow(mainAxisSpacing = 16.dp) { NiaFilledButton( onClick = {}, text = { Text(text = "Enabled") }, leadingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) NiaOutlinedButton( onClick = {}, text = { Text(text = "Enabled") }, leadingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) NiaTextButton( onClick = {}, text = { Text(text = "Enabled") }, leadingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) } } item { Text("Disabled buttons with leading icons", Modifier.padding(top = 16.dp)) } item { FlowRow(mainAxisSpacing = 16.dp) { NiaFilledButton( onClick = {}, enabled = false, text = { Text(text = "Disabled") }, leadingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) NiaOutlinedButton( onClick = {}, enabled = false, text = { Text(text = "Disabled") }, leadingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) NiaTextButton( onClick = {}, enabled = false, text = { Text(text = "Disabled") }, leadingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) } } item { Text("Buttons with trailing icons", Modifier.padding(top = 16.dp)) } item { FlowRow(mainAxisSpacing = 16.dp) { NiaFilledButton( onClick = {}, text = { Text(text = "Enabled") }, trailingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) NiaOutlinedButton( onClick = {}, text = { Text(text = "Enabled") }, trailingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) NiaTextButton( onClick = {}, text = { Text(text = "Enabled") }, trailingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) } } item { Text("Disabled buttons with trailing icons", Modifier.padding(top = 16.dp)) } item { FlowRow(mainAxisSpacing = 16.dp) { NiaFilledButton( onClick = {}, enabled = false, text = { Text(text = "Disabled") }, trailingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) NiaOutlinedButton( onClick = {}, enabled = false, text = { Text(text = "Disabled") }, trailingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) NiaTextButton( onClick = {}, enabled = false, text = { Text(text = "Disabled") }, trailingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) } } item { Text("Small buttons", Modifier.padding(top = 16.dp)) } item { FlowRow(mainAxisSpacing = 16.dp) { NiaFilledButton( onClick = {}, small = true ) { Text(text = "Enabled") } NiaOutlinedButton( onClick = {}, small = true ) { Text(text = "Enabled") } NiaTextButton( onClick = {}, small = true ) { Text(text = "Enabled") } } } item { Text("Disabled small buttons", Modifier.padding(top = 16.dp)) } item { FlowRow(mainAxisSpacing = 16.dp) { NiaFilledButton( onClick = {}, enabled = false, small = true ) { Text(text = "Disabled") } NiaOutlinedButton( onClick = {}, enabled = false, small = true ) { Text(text = "Disabled") } NiaTextButton( onClick = {}, enabled = false, small = true ) { Text(text = "Disabled") } } } item { Text("Small buttons with leading icons", Modifier.padding(top = 16.dp)) } item { FlowRow(mainAxisSpacing = 16.dp) { NiaFilledButton( onClick = {}, small = true, text = { Text(text = "Enabled") }, leadingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) NiaOutlinedButton( onClick = {}, small = true, text = { Text(text = "Enabled") }, leadingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) NiaTextButton( onClick = {}, small = true, text = { Text(text = "Enabled") }, leadingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) } } item { Text( "Disabled small buttons with leading icons", Modifier.padding(top = 16.dp) ) } item { FlowRow(mainAxisSpacing = 16.dp) { NiaFilledButton( onClick = {}, enabled = false, small = true, text = { Text(text = "Disabled") }, leadingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) NiaOutlinedButton( onClick = {}, enabled = false, small = true, text = { Text(text = "Disabled") }, leadingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) NiaTextButton( onClick = {}, enabled = false, small = true, text = { Text(text = "Disabled") }, leadingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) } } item { Text("Small buttons with trailing icons", Modifier.padding(top = 16.dp)) } item { FlowRow(mainAxisSpacing = 16.dp) { NiaFilledButton( onClick = {}, small = true, text = { Text(text = "Enabled") }, trailingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) NiaOutlinedButton( onClick = {}, small = true, text = { Text(text = "Enabled") }, trailingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) NiaTextButton( onClick = {}, small = true, text = { Text(text = "Enabled") }, trailingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) } } item { Text( "Disabled small buttons with trailing icons", Modifier.padding(top = 16.dp) ) } item { FlowRow(mainAxisSpacing = 16.dp) { NiaFilledButton( onClick = {}, enabled = false, small = true, text = { Text(text = "Disabled") }, trailingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) NiaOutlinedButton( onClick = {}, enabled = false, small = true, text = { Text(text = "Disabled") }, trailingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) NiaTextButton( onClick = {}, enabled = false, small = true, text = { Text(text = "Disabled") }, trailingIcon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) } ) } } item { Text("Dropdown menu", Modifier.padding(top = 16.dp)) } item { NiaDropdownMenuButton( text = { Text("Newest first") }, items = listOf("Item 1", "Item 2", "Item 3"), onItemClick = {}, itemText = { item -> Text(item) } ) } item { Text("Chips", Modifier.padding(top = 16.dp)) } item { FlowRow(mainAxisSpacing = 16.dp) { var firstChecked by remember { mutableStateOf(false) } NiaFilterChip( selected = firstChecked, onSelectedChange = { checked -> firstChecked = checked }, label = { Text(text = "Enabled".uppercase()) } ) var secondChecked by remember { mutableStateOf(true) } NiaFilterChip( selected = secondChecked, onSelectedChange = { checked -> secondChecked = checked }, label = { Text(text = "Enabled".uppercase()) } ) var thirdChecked by remember { mutableStateOf(true) } NiaFilterChip( selected = thirdChecked, onSelectedChange = { checked -> thirdChecked = checked }, enabled = false, label = { Text(text = "Disabled".uppercase()) } ) } } item { Text("Toggle buttons", Modifier.padding(top = 16.dp)) } item { FlowRow(mainAxisSpacing = 16.dp) { var firstChecked by remember { mutableStateOf(false) } NiaToggleButton( checked = firstChecked, onCheckedChange = { checked -> firstChecked = checked }, icon = { Icon( painter = painterResource(id = NiaIcons.BookmarkBorder), contentDescription = null ) }, checkedIcon = { Icon( painter = painterResource(id = NiaIcons.Bookmark), contentDescription = null ) } ) var secondChecked by remember { mutableStateOf(true) } NiaToggleButton( checked = secondChecked, onCheckedChange = { checked -> secondChecked = checked }, icon = { Icon( painter = painterResource(id = NiaIcons.BookmarkBorder), contentDescription = null ) }, checkedIcon = { Icon( painter = painterResource(id = NiaIcons.Bookmark), contentDescription = null ) } ) var thirdChecked by remember { mutableStateOf(false) } NiaToggleButton( checked = thirdChecked, onCheckedChange = { checked -> thirdChecked = checked }, icon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) }, checkedIcon = { Icon(imageVector = NiaIcons.Check, contentDescription = null) } ) var fourthChecked by remember { mutableStateOf(true) } NiaToggleButton( checked = fourthChecked, onCheckedChange = { checked -> fourthChecked = checked }, icon = { Icon(imageVector = NiaIcons.Add, contentDescription = null) }, checkedIcon = { Icon(imageVector = NiaIcons.Check, contentDescription = null) } ) } } item { Text("View toggle", Modifier.padding(top = 16.dp)) } item { FlowRow(mainAxisSpacing = 16.dp) { var firstExpanded by remember { mutableStateOf(false) } NiaViewToggleButton( expanded = firstExpanded, onExpandedChange = { expanded -> firstExpanded = expanded }, compactText = { Text(text = "Compact view") }, expandedText = { Text(text = "Expanded view") } ) var secondExpanded by remember { mutableStateOf(true) } NiaViewToggleButton( expanded = secondExpanded, onExpandedChange = { expanded -> secondExpanded = expanded }, compactText = { Text(text = "Compact view") }, expandedText = { Text(text = "Expanded view") } ) } } item { Text("Tags", Modifier.padding(top = 16.dp)) } item { FlowRow(mainAxisSpacing = 16.dp) { var expandedTopicId by remember { mutableStateOf<String?>(null) } var firstFollowed by remember { mutableStateOf(false) } NiaTopicTag( expanded = expandedTopicId == "Topic 1", followed = firstFollowed, onDropMenuToggle = { show -> expandedTopicId = if (show) "Topic 1" else null }, onFollowClick = { firstFollowed = true }, onUnfollowClick = { firstFollowed = false }, onBrowseClick = {}, text = { Text(text = "Topic 1".uppercase()) }, followText = { Text(text = "Follow") }, unFollowText = { Text(text = "Unfollow") }, browseText = { Text(text = "Browse topic") } ) var secondFollowed by remember { mutableStateOf(true) } NiaTopicTag( expanded = expandedTopicId == "Topic 2", followed = secondFollowed, onDropMenuToggle = { show -> expandedTopicId = if (show) "Topic 2" else null }, onFollowClick = { secondFollowed = true }, onUnfollowClick = { secondFollowed = false }, onBrowseClick = {}, text = { Text(text = "Topic 2".uppercase()) }, followText = { Text(text = "Follow") }, unFollowText = { Text(text = "Unfollow") }, browseText = { Text(text = "Browse topic") } ) } } item { Text("Tabs", Modifier.padding(top = 16.dp)) } item { var selectedTabIndex by remember { mutableStateOf(0) } val titles = listOf("Topics", "People") NiaTabRow(selectedTabIndex = selectedTabIndex) { titles.forEachIndexed { index, title -> NiaTab( selected = selectedTabIndex == index, onClick = { selectedTabIndex = index }, text = { Text(text = title) } ) } } } item { Text("Navigation", Modifier.padding(top = 16.dp)) } item { var selectedItem by remember { mutableStateOf(0) } val items = listOf("For you", "Episodes", "Saved", "Interests") val icons = listOf( NiaIcons.UpcomingBorder, NiaIcons.MenuBookBorder, NiaIcons.BookmarksBorder ) val selectedIcons = listOf( NiaIcons.Upcoming, NiaIcons.MenuBook, NiaIcons.Bookmarks ) val tagIcon = NiaIcons.Tag NiaNavigationBar { items.forEachIndexed { index, item -> NiaNavigationBarItem( icon = { if (index == 3) { Icon(imageVector = tagIcon, contentDescription = null) } else { Icon( painter = painterResource(id = icons[index]), contentDescription = item ) } }, selectedIcon = { if (index == 3) { Icon(imageVector = tagIcon, contentDescription = null) } else { Icon( painter = painterResource(id = selectedIcons[index]), contentDescription = item ) } }, label = { Text(item) }, selected = selectedItem == index, onClick = { selectedItem = index } ) } } } } } } }
apache-2.0
deabf7d069d404afaced271c95cf9668
46.280389
100
0.376217
7.165807
false
false
false
false
square/picasso
picasso/src/main/java/com/squareup/picasso3/ContactsPhotoRequestHandler.kt
1
3618
/* * Copyright (C) 2013 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 com.squareup.picasso3 import android.content.ContentResolver import android.content.Context import android.content.UriMatcher import android.net.Uri import android.provider.ContactsContract import android.provider.ContactsContract.Contacts import com.squareup.picasso3.BitmapUtils.decodeStream import com.squareup.picasso3.Picasso.LoadedFrom.DISK import okio.Source import okio.source import java.io.FileNotFoundException import java.io.IOException internal class ContactsPhotoRequestHandler(private val context: Context) : RequestHandler() { companion object { /** A lookup uri (e.g. content://com.android.contacts/contacts/lookup/3570i61d948d30808e537) */ private const val ID_LOOKUP = 1 /** A contact thumbnail uri (e.g. content://com.android.contacts/contacts/38/photo) */ private const val ID_THUMBNAIL = 2 /** A contact uri (e.g. content://com.android.contacts/contacts/38) */ private const val ID_CONTACT = 3 /** * A contact display photo (high resolution) uri * (e.g. content://com.android.contacts/display_photo/5) */ private const val ID_DISPLAY_PHOTO = 4 private val matcher: UriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply { addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#", ID_LOOKUP) addURI(ContactsContract.AUTHORITY, "contacts/lookup/*", ID_LOOKUP) addURI(ContactsContract.AUTHORITY, "contacts/#/photo", ID_THUMBNAIL) addURI(ContactsContract.AUTHORITY, "contacts/#", ID_CONTACT) addURI(ContactsContract.AUTHORITY, "display_photo/#", ID_DISPLAY_PHOTO) } } override fun canHandleRequest(data: Request): Boolean { val uri = data.uri return uri != null && ContentResolver.SCHEME_CONTENT == uri.scheme && Contacts.CONTENT_URI.host == uri.host && matcher.match(data.uri) != UriMatcher.NO_MATCH } override fun load( picasso: Picasso, request: Request, callback: Callback ) { var signaledCallback = false try { val requestUri = checkNotNull(request.uri) val source = getSource(requestUri) val bitmap = decodeStream(source, request) signaledCallback = true callback.onSuccess(Result.Bitmap(bitmap, DISK)) } catch (e: Exception) { if (!signaledCallback) { callback.onError(e) } } } private fun getSource(uri: Uri): Source { val contentResolver = context.contentResolver val input = when (matcher.match(uri)) { ID_LOOKUP -> { val contactUri = Contacts.lookupContact(contentResolver, uri) ?: throw IOException("no contact found") Contacts.openContactPhotoInputStream(contentResolver, contactUri, true) } ID_CONTACT -> Contacts.openContactPhotoInputStream(contentResolver, uri, true) ID_THUMBNAIL, ID_DISPLAY_PHOTO -> contentResolver.openInputStream(uri) else -> throw IllegalStateException("Invalid uri: $uri") } ?: throw FileNotFoundException("can't open input stream, uri: $uri") return input.source() } }
apache-2.0
b6f99e8b93a592f021ad5b780c7f0852
36.6875
99
0.711443
4.202091
false
false
false
false
GunoH/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/column/VcsLogDefaultColumn.kt
2
9207
// 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.vcs.log.ui.table.column import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vcs.FilePath import com.intellij.util.containers.ContainerUtil import com.intellij.util.text.DateFormatUtil import com.intellij.util.text.DateTimeFormatManager import com.intellij.util.text.JBDateFormat import com.intellij.vcs.log.VcsCommitMetadata import com.intellij.vcs.log.VcsLogBundle import com.intellij.vcs.log.graph.DefaultColorGenerator import com.intellij.vcs.log.history.FileHistoryPaths.filePathOrDefault import com.intellij.vcs.log.history.FileHistoryPaths.hasPathsInformation import com.intellij.vcs.log.impl.CommonUiProperties import com.intellij.vcs.log.impl.VcsLogUiProperties import com.intellij.vcs.log.paint.GraphCellPainter import com.intellij.vcs.log.paint.SimpleGraphCellPainter import com.intellij.vcs.log.ui.frame.CommitPresentationUtil import com.intellij.vcs.log.ui.render.GraphCommitCell import com.intellij.vcs.log.ui.render.GraphCommitCellRenderer import com.intellij.vcs.log.ui.table.GraphTableModel import com.intellij.vcs.log.ui.table.RootCellRenderer import com.intellij.vcs.log.ui.table.VcsLogGraphTable import com.intellij.vcs.log.ui.table.VcsLogStringCellRenderer import com.intellij.vcs.log.util.VcsLogUtil import com.intellij.vcs.log.visible.VisiblePack import com.intellij.vcsUtil.VcsUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import java.util.* import javax.swing.table.TableCellRenderer internal fun getDefaultDynamicColumns() = listOf<VcsLogDefaultColumn<*>>(Author, Hash, Date) internal sealed class VcsLogDefaultColumn<T>( @NonNls override val id: String, override val localizedName: @Nls String, override val isDynamic: Boolean = true ) : VcsLogColumn<T> { /** * @return stable name (to identify column in statistics) */ val stableName: String get() = id.toLowerCase(Locale.ROOT) } internal object Root : VcsLogDefaultColumn<FilePath>("Default.Root", "", false) { override val isResizable = false override fun getValue(model: GraphTableModel, row: Int): FilePath { val visiblePack = model.visiblePack if (visiblePack.hasPathsInformation()) { val path = visiblePack.filePathOrDefault(visiblePack.visibleGraph.getRowInfo(row).commit) if (path != null) { return path } } return VcsUtil.getFilePath(visiblePack.getRoot(row)) } override fun createTableCellRenderer(table: VcsLogGraphTable): TableCellRenderer { doOnPropertyChange(table) { property -> if (CommonUiProperties.SHOW_ROOT_NAMES == property) { table.rootColumnUpdated() } } return RootCellRenderer(table.properties, table.colorManager) } override fun getStubValue(model: GraphTableModel): FilePath = VcsUtil.getFilePath(ContainerUtil.getFirstItem(model.logData.roots)) } internal object Commit : VcsLogDefaultColumn<GraphCommitCell>("Default.Subject", VcsLogBundle.message("vcs.log.column.subject"), false), VcsLogMetadataColumn { override fun getValue(model: GraphTableModel, row: Int): GraphCommitCell { val printElements = if (VisiblePack.NO_GRAPH_INFORMATION.get(model.visiblePack, false)) emptyList() else model.visiblePack.visibleGraph.getRowInfo(row).printElements return GraphCommitCell( getValue(model, model.getCommitMetadata(row, true)), model.getRefsAtRow(row), printElements ) } override fun getValue(model: GraphTableModel, commit: VcsCommitMetadata): String = commit.subject override fun createTableCellRenderer(table: VcsLogGraphTable): TableCellRenderer { val graphCellPainter: GraphCellPainter = object : SimpleGraphCellPainter(DefaultColorGenerator()) { override fun getRowHeight(): Int { return table.rowHeight } } val commitCellRenderer = GraphCommitCellRenderer(table.logData, graphCellPainter, table) commitCellRenderer.setCompactReferencesView(table.properties[CommonUiProperties.COMPACT_REFERENCES_VIEW]) commitCellRenderer.setShowTagsNames(table.properties[CommonUiProperties.SHOW_TAG_NAMES]) commitCellRenderer.setLeftAligned(table.properties[CommonUiProperties.LABELS_LEFT_ALIGNED]) doOnPropertyChange(table) { property -> if (CommonUiProperties.COMPACT_REFERENCES_VIEW == property) { commitCellRenderer.setCompactReferencesView(table.properties[CommonUiProperties.COMPACT_REFERENCES_VIEW]) table.repaint() } else if (CommonUiProperties.SHOW_TAG_NAMES == property) { commitCellRenderer.setShowTagsNames(table.properties[CommonUiProperties.SHOW_TAG_NAMES]) table.repaint() } else if (CommonUiProperties.LABELS_LEFT_ALIGNED == property) { commitCellRenderer.setLeftAligned(table.properties[CommonUiProperties.LABELS_LEFT_ALIGNED]) table.repaint() } } updateTableOnCommitDetailsLoaded(this, table) return commitCellRenderer } override fun getStubValue(model: GraphTableModel): GraphCommitCell = GraphCommitCell("", emptyList(), emptyList()) } internal object Author : VcsLogDefaultColumn<String>("Default.Author", VcsLogBundle.message("vcs.log.column.author")), VcsLogMetadataColumn { override fun getValue(model: GraphTableModel, row: Int) = getValue(model, model.getCommitMetadata(row, true)) override fun getValue(model: GraphTableModel, commit: VcsCommitMetadata) = CommitPresentationUtil.getAuthorPresentation(commit) override fun createTableCellRenderer(table: VcsLogGraphTable): TableCellRenderer { updateTableOnCommitDetailsLoaded(this, table) return VcsLogStringCellRenderer(true) } override fun getStubValue(model: GraphTableModel) = "" } internal object Date : VcsLogDefaultColumn<String>("Default.Date", VcsLogBundle.message("vcs.log.column.date")), VcsLogMetadataColumn { override fun getValue(model: GraphTableModel, row: Int): String { return getValue(model, model.getCommitMetadata(row, true)) } override fun getValue(model: GraphTableModel, commit: VcsCommitMetadata): String { val properties = model.properties val preferCommitDate = properties.exists(CommonUiProperties.PREFER_COMMIT_DATE) && properties.get(CommonUiProperties.PREFER_COMMIT_DATE) val timeStamp = if (preferCommitDate) commit.commitTime else commit.authorTime return if (timeStamp < 0) "" else JBDateFormat.getFormatter().formatPrettyDateTime(timeStamp) } override fun createTableCellRenderer(table: VcsLogGraphTable): TableCellRenderer { doOnPropertyChange(table) { property -> if (property == CommonUiProperties.PREFER_COMMIT_DATE && table.getTableColumn(this@Date) != null) { table.repaint() } } updateTableOnCommitDetailsLoaded(this, table) return VcsLogStringCellRenderer( withSpeedSearchHighlighting = true, contentSampleProvider = { if (DateTimeFormatManager.getInstance().isPrettyFormattingAllowed) { null } else { JBDateFormat.getFormatter().formatDateTime(DateFormatUtil.getSampleDateTime()) } } ) } override fun getStubValue(model: GraphTableModel): String = "" } internal object Hash : VcsLogDefaultColumn<String>("Default.Hash", VcsLogBundle.message("vcs.log.column.hash")), VcsLogMetadataColumn { override fun getValue(model: GraphTableModel, row: Int): String = getValue(model, model.getCommitMetadata(row, true)) override fun getValue(model: GraphTableModel, commit: VcsCommitMetadata) = commit.id.toShortString() override fun createTableCellRenderer(table: VcsLogGraphTable): TableCellRenderer { updateTableOnCommitDetailsLoaded(this, table) return VcsLogStringCellRenderer( withSpeedSearchHighlighting = true, contentSampleProvider = { "e".repeat(VcsLogUtil.SHORT_HASH_LENGTH) } ) } override fun getStubValue(model: GraphTableModel): String = "" } private fun updateTableOnCommitDetailsLoaded(column: VcsLogColumn<*>, graphTable: VcsLogGraphTable) { val miniDetailsLoadedListener = Runnable { graphTable.onColumnDataChanged(column) } graphTable.logData.miniDetailsGetter.addDetailsLoadedListener(miniDetailsLoadedListener) Disposer.register(graphTable) { graphTable.logData.miniDetailsGetter.removeDetailsLoadedListener(miniDetailsLoadedListener) } } private fun doOnPropertyChange(graphTable: VcsLogGraphTable, listener: (VcsLogUiProperties.VcsLogUiProperty<*>) -> Unit) { val propertiesChangeListener = object : VcsLogUiProperties.PropertiesChangeListener { override fun <T : Any?> onPropertyChanged(property: VcsLogUiProperties.VcsLogUiProperty<T>) { listener(property) } } graphTable.properties.addChangeListener(propertiesChangeListener) Disposer.register(graphTable) { graphTable.properties.removeChangeListener(propertiesChangeListener) } } @ApiStatus.Internal interface VcsLogMetadataColumn { @ApiStatus.Internal fun getValue(model: GraphTableModel, commit: VcsCommitMetadata): @NlsSafe String }
apache-2.0
b9cab7e5fe8087ee3b6da4c738f74ce2
42.230047
140
0.772564
4.800313
false
false
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/impl/PartialChangesUtil.kt
2
9714
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.impl import com.intellij.diff.util.Side import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.Computable import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.changes.conflicts.ChangelistConflictTracker import com.intellij.openapi.vcs.ex.ExclusionState import com.intellij.openapi.vcs.ex.PartialLocalLineStatusTracker import com.intellij.openapi.vcs.history.VcsRevisionNumber import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PairFunction import com.intellij.util.containers.MultiMap import com.intellij.util.ui.ThreeStateCheckBox object PartialChangesUtil { private val LOG = Logger.getInstance(PartialChangesUtil::class.java) @JvmStatic fun getPartialTracker(project: Project, change: Change): PartialLocalLineStatusTracker? { val file = getVirtualFile(change) ?: return null return getPartialTracker(project, file) } @JvmStatic fun getPartialTracker(project: Project, file: VirtualFile): PartialLocalLineStatusTracker? { val tracker = LineStatusTrackerManager.getInstance(project).getLineStatusTracker(file) return tracker as? PartialLocalLineStatusTracker } @JvmStatic fun getVirtualFile(change: Change): VirtualFile? { val revision = change.afterRevision as? CurrentContentRevision return revision?.virtualFile } @JvmStatic fun processPartialChanges(project: Project, changes: Collection<Change>, executeOnEDT: Boolean, partialProcessor: PairFunction<in List<ChangeListChange>, in PartialLocalLineStatusTracker, Boolean>): List<Change> { if (!LineStatusTrackerManager.getInstance(project).arePartialChangelistsEnabled() || changes.none { it is ChangeListChange }) { return changes.toMutableList() } val otherChanges = mutableListOf<Change>() val task = Runnable { val partialChangesMap = MultiMap<VirtualFile, ChangeListChange>() for (change in changes) { if (change is ChangeListChange) { val virtualFile = getVirtualFile(change) if (virtualFile != null) { partialChangesMap.putValue(virtualFile, change) } else { otherChanges.add(change.change) } } else { otherChanges.add(change) } } val lstManager = LineStatusTrackerManager.getInstance(project) for ((virtualFile, value) in partialChangesMap.entrySet()) { @Suppress("UNCHECKED_CAST") val partialChanges = value as List<ChangeListChange> val actualChange = partialChanges[0].change val tracker = lstManager.getLineStatusTracker(virtualFile) as? PartialLocalLineStatusTracker if (tracker == null || !partialProcessor.`fun`(partialChanges, tracker)) { otherChanges.add(actualChange) } } } if (executeOnEDT && !ApplicationManager.getApplication().isDispatchThread) { ApplicationManager.getApplication().invokeAndWait(task) } else { task.run() } return otherChanges } @JvmStatic fun runUnderChangeList(project: Project, targetChangeList: LocalChangeList?, task: Runnable) { computeUnderChangeList(project, targetChangeList) { task.run() null } } @JvmStatic fun <T> computeUnderChangeList(project: Project, targetChangeList: LocalChangeList?, task: Computable<T>): T { val changeListManager = ChangeListManagerEx.getInstanceEx(project) val oldDefaultList = changeListManager.defaultChangeList if (targetChangeList == null || targetChangeList == oldDefaultList || !changeListManager.areChangeListsEnabled()) { return task.compute() } switchChangeList(changeListManager, targetChangeList, oldDefaultList) val clmConflictTracker = ChangelistConflictTracker.getInstance(project) try { clmConflictTracker.setIgnoreModifications(true) return task.compute() } finally { clmConflictTracker.setIgnoreModifications(false) restoreChangeList(changeListManager, targetChangeList, oldDefaultList) } } suspend fun <T> underChangeList(project: Project, targetChangeList: LocalChangeList?, task: suspend () -> T): T { val changeListManager = ChangeListManagerEx.getInstanceEx(project) val oldDefaultList = changeListManager.defaultChangeList if (targetChangeList == null || targetChangeList == oldDefaultList || !changeListManager.areChangeListsEnabled()) { return task() } switchChangeList(changeListManager, targetChangeList, oldDefaultList) val clmConflictTracker = ChangelistConflictTracker.getInstance(project) try { clmConflictTracker.setIgnoreModifications(true) return task() } finally { clmConflictTracker.setIgnoreModifications(false) restoreChangeList(changeListManager, targetChangeList, oldDefaultList) } } @JvmStatic fun <T> computeUnderChangeListSync(project: Project, targetChangeList: LocalChangeList?, task: Computable<T>): T { val changeListManager = ChangeListManagerEx.getInstanceEx(project) val oldDefaultList = changeListManager.defaultChangeList if (targetChangeList == null || !changeListManager.areChangeListsEnabled()) { return task.compute() } switchChangeList(changeListManager, targetChangeList, oldDefaultList) val clmConflictTracker = ChangelistConflictTracker.getInstance(project) try { clmConflictTracker.setIgnoreModifications(true) return task.compute() } finally { clmConflictTracker.setIgnoreModifications(false) if (ApplicationManager.getApplication().isReadAccessAllowed) { LOG.warn("Can't wait till changes are applied while holding read lock", Throwable()) } else { ChangeListManagerEx.getInstanceEx(project).waitForUpdate() } restoreChangeList(changeListManager, targetChangeList, oldDefaultList) } } private fun switchChangeList(clm: ChangeListManagerEx, targetChangeList: LocalChangeList, oldDefaultList: LocalChangeList) { clm.setDefaultChangeList(targetChangeList, true) LOG.debug("Active changelist changed: ${oldDefaultList.name} -> ${targetChangeList.name}") } private fun restoreChangeList(clm: ChangeListManagerEx, targetChangeList: LocalChangeList, oldDefaultList: LocalChangeList) { val defaultChangeList = clm.defaultChangeList if (defaultChangeList.id == targetChangeList.id) { clm.setDefaultChangeList(oldDefaultList, true) LOG.debug("Active changelist restored: ${targetChangeList.name} -> ${oldDefaultList.name}") } else { LOG.warn(Throwable("Active changelist was changed during the operation. " + "Expected: ${targetChangeList.name} -> ${oldDefaultList.name}, " + "actual default: ${defaultChangeList.name}")) } } @JvmStatic fun convertExclusionState(exclusionState: ExclusionState): ThreeStateCheckBox.State { return when (exclusionState) { ExclusionState.ALL_INCLUDED -> ThreeStateCheckBox.State.SELECTED ExclusionState.ALL_EXCLUDED -> ThreeStateCheckBox.State.NOT_SELECTED else -> ThreeStateCheckBox.State.DONT_CARE } } @JvmStatic fun wrapPartialChanges(project: Project, changes: List<Change>): List<Change> { return changes.map { change -> wrapPartialChangeIfNeeded(project, change) ?: change } } private fun wrapPartialChangeIfNeeded(project: Project, change: Change): Change? { if (change !is ChangeListChange) return null val afterRevision = change.afterRevision if (afterRevision !is CurrentContentRevision) return null val tracker = getPartialTracker(project, change) if (tracker == null || !tracker.isOperational() || !tracker.hasPartialChangesToCommit()) return null val partialAfterRevision = PartialContentRevision(project, tracker.virtualFile, change.changeListId, afterRevision) return ChangeListChange.replaceChangeContents(change, change.beforeRevision, partialAfterRevision) } private class PartialContentRevision(val project: Project, val virtualFile: VirtualFile, val changeListId: String, val delegate: ContentRevision) : ContentRevision { override fun getFile(): FilePath = delegate.file override fun getRevisionNumber(): VcsRevisionNumber = delegate.revisionNumber override fun getContent(): String? { val tracker = getPartialTracker(project, virtualFile) if (tracker != null && tracker.isOperational() && tracker.hasPartialChangesToCommit()) { val partialContent = tracker.getChangesToBeCommitted(Side.LEFT, listOf(changeListId), true) if (partialContent != null) return partialContent LOG.warn("PartialContentRevision - missing partial content for $tracker") } return delegate.content } } }
apache-2.0
c7159f07898b249cbcc221b351023527
39.311203
145
0.691682
5.637841
false
false
false
false
GunoH/intellij-community
plugins/kotlin/features-trainer/src/org/jetbrains/kotlin/training/ifs/KotlinSuggesterSupport.kt
4
3682
// 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.training.ifs import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.util.descendantsOfType import com.intellij.psi.util.parentsOfType import org.jetbrains.kotlin.psi.* import training.featuresSuggester.SuggesterSupport import training.featuresSuggester.getParentByPredicate import training.featuresSuggester.getParentOfType class KotlinSuggesterSupport : SuggesterSupport { override fun isLoadedSourceFile(file: PsiFile): Boolean { return file is KtFile && !file.isCompiled && file.isContentsLoaded } override fun isIfStatement(element: PsiElement): Boolean { return element is KtIfExpression } override fun isForStatement(element: PsiElement): Boolean { return element is KtForExpression } override fun isWhileStatement(element: PsiElement): Boolean { return element is KtWhileExpression } override fun isCodeBlock(element: PsiElement): Boolean { return element is KtBlockExpression } override fun getCodeBlock(element: PsiElement): PsiElement? { return element.descendantsOfType<KtBlockExpression>().firstOrNull() } override fun getContainingCodeBlock(element: PsiElement): PsiElement? { return element.getParentOfType<KtBlockExpression>() } override fun getParentStatementOfBlock(element: PsiElement): PsiElement? { return element.parent?.parent } override fun getStatements(element: PsiElement): List<PsiElement> { return if (element is KtBlockExpression) { element.statements } else { emptyList() } } override fun getTopmostStatementWithText(psiElement: PsiElement, text: String): PsiElement? { val statement = psiElement.getParentByPredicate { isSupportedStatementToIntroduceVariable(it) && it.text.contains(text) && it.text != text } return if (statement is KtCallExpression) { return statement.parentsOfType<KtDotQualifiedExpression>().lastOrNull() ?: statement } else { statement } } override fun isSupportedStatementToIntroduceVariable(element: PsiElement): Boolean { return element is KtProperty || element is KtIfExpression || element is KtCallExpression || element is KtQualifiedExpression || element is KtReturnExpression } override fun isPartOfExpression(element: PsiElement): Boolean { return element.getParentOfType<KtExpression>() != null } override fun isExpressionStatement(element: PsiElement): Boolean { return element is KtExpression } override fun isVariableDeclaration(element: PsiElement): Boolean { return element is KtProperty } override fun getVariableName(element: PsiElement): String? { return if (element is KtProperty) { element.name } else { null } } override fun isFileStructureElement(element: PsiElement): Boolean { return (element is KtProperty && !element.isLocal) || element is KtNamedFunction || element is KtClass } override fun isIdentifier(element: PsiElement): Boolean { return element is LeafPsiElement && element.elementType.toString() == "IDENTIFIER" } override fun isLiteralExpression(element: PsiElement): Boolean { return element is KtStringTemplateExpression } }
apache-2.0
62f5ce078bb6c646ca44606ff45fe97d
34.747573
158
0.706953
5.511976
false
false
false
false
jk1/intellij-community
plugins/stats-collector/features/src/com/jetbrains/completion/feature/impl/CompletionFactors.kt
3
1291
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.completion.feature.impl class CompletionFactors(proximity: Set<String>, relevance: Set<String>) { private val knownFactors: Set<String> = HashSet<String>().apply { addAll(proximity.map { "prox_$it" }) addAll(relevance) } fun unknownFactors(factors: Set<String>): List<String> { var result: MutableList<String>? = null for (factor in factors) { val normalized = factor.substringBefore('@') if (normalized !in knownFactors) { result = (result ?: mutableListOf()).apply { add(normalized) } } } return if (result != null) result else emptyList() } }
apache-2.0
fa74d29ee221fdd1aede0f54419d6eda
32.973684
78
0.667699
4.274834
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/stories/StoryTextPostView.kt
1
6800
package org.thoughtcrime.securesms.stories import android.content.Context import android.graphics.Typeface import android.graphics.drawable.Drawable import android.util.AttributeSet import android.util.TypedValue import android.view.View import android.widget.ImageView import androidx.annotation.ColorInt import androidx.annotation.Px import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.graphics.ColorUtils import androidx.core.view.doOnNextLayout import androidx.core.view.isVisible import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.conversation.colors.ChatColors import org.thoughtcrime.securesms.database.model.databaseprotos.StoryTextPost import org.thoughtcrime.securesms.fonts.TextFont import org.thoughtcrime.securesms.linkpreview.LinkPreview import org.thoughtcrime.securesms.linkpreview.LinkPreviewViewModel import org.thoughtcrime.securesms.mediasend.v2.text.TextAlignment import org.thoughtcrime.securesms.mediasend.v2.text.TextStoryPostCreationState import org.thoughtcrime.securesms.mediasend.v2.text.TextStoryScale import org.thoughtcrime.securesms.mediasend.v2.text.TextStoryTextWatcher import org.thoughtcrime.securesms.util.concurrent.ListenableFuture import org.thoughtcrime.securesms.util.visible import java.util.Locale class StoryTextPostView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr) { init { inflate(context, R.layout.stories_text_post_view, this) } private var textAlignment: TextAlignment? = null private val backgroundView: ImageView = findViewById(R.id.text_story_post_background) private val textView: StoryTextView = findViewById(R.id.text_story_post_text) private val linkPreviewView: StoryLinkPreviewView = findViewById(R.id.text_story_post_link_preview) private var isPlaceholder: Boolean = true init { TextStoryTextWatcher.install(textView) } fun showCloseButton() { linkPreviewView.setCanClose(true) } fun hideCloseButton() { linkPreviewView.setCanClose(false) } fun setTypeface(typeface: Typeface) { textView.typeface = typeface } private fun setPostBackground(drawable: Drawable) { backgroundView.setImageDrawable(drawable) } private fun setTextColor(@ColorInt color: Int, isPlaceholder: Boolean) { if (isPlaceholder) { textView.setTextColor(ColorUtils.setAlphaComponent(color, 0x99)) } else { textView.setTextColor(color) } } private fun setText(text: CharSequence, isPlaceholder: Boolean) { this.isPlaceholder = isPlaceholder textView.text = text } private fun setTextSize(@Px textSize: Float) { textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize) } private fun setTextGravity(textAlignment: TextAlignment) { textView.gravity = textAlignment.gravity } private fun setTextScale(scalePercent: Int) { val scale = TextStoryScale.convertToScale(scalePercent) textView.scaleX = scale textView.scaleY = scale } private fun setTextVisible(visible: Boolean) { textView.visible = visible } private fun setTextBackgroundColor(@ColorInt color: Int) { textView.setWrappedBackgroundColor(color) } fun bindFromCreationState(state: TextStoryPostCreationState) { textAlignment = state.textAlignment setPostBackground(state.backgroundColor.chatBubbleMask) setText( state.body.ifEmpty { context.getString(R.string.TextStoryPostCreationFragment__tap_to_add_text) }.let { if (state.textFont.isAllCaps) { it.toString().uppercase(Locale.getDefault()) } else { it } }, state.body.isEmpty() ) setTextColor(state.textForegroundColor, state.body.isEmpty()) setTextBackgroundColor(state.textBackgroundColor) setTextGravity(state.textAlignment) setTextScale(state.textScale) postAdjustLinkPreviewTranslationY() } fun bindFromStoryTextPost(storyTextPost: StoryTextPost) { visible = true linkPreviewView.visible = false textAlignment = TextAlignment.CENTER val font = TextFont.fromStyle(storyTextPost.style) setPostBackground(ChatColors.forChatColor(ChatColors.Id.NotSet, storyTextPost.background).chatBubbleMask) if (font.isAllCaps) { setText(storyTextPost.body.uppercase(Locale.getDefault()), false) } else { setText(storyTextPost.body, false) } setTextColor(storyTextPost.textForegroundColor, false) setTextBackgroundColor(storyTextPost.textBackgroundColor) setTextGravity(TextAlignment.CENTER) hideCloseButton() postAdjustLinkPreviewTranslationY() } fun bindLinkPreview(linkPreview: LinkPreview?): ListenableFuture<Boolean> { return linkPreviewView.bind(linkPreview, View.GONE) } fun bindLinkPreviewState(linkPreviewState: LinkPreviewViewModel.LinkPreviewState, hiddenVisibility: Int) { linkPreviewView.bind(linkPreviewState, hiddenVisibility) } fun postAdjustLinkPreviewTranslationY() { setTextVisible(canDisplayText()) doOnNextLayout { adjustLinkPreviewTranslationY() } } fun setTextViewClickListener(onClickListener: OnClickListener) { setOnClickListener(onClickListener) } fun setLinkPreviewCloseListener(onClickListener: OnClickListener) { linkPreviewView.setOnCloseClickListener(onClickListener) } fun setLinkPreviewClickListener(onClickListener: OnClickListener?) { linkPreviewView.setOnClickListener(onClickListener) } fun showPostContent() { textView.alpha = 1f linkPreviewView.alpha = 1f } fun hidePostContent() { textView.alpha = 0f linkPreviewView.alpha = 0f } private fun canDisplayText(): Boolean { return !(linkPreviewView.isVisible && isPlaceholder) } private fun adjustLinkPreviewTranslationY() { val backgroundHeight = backgroundView.measuredHeight val textHeight = if (canDisplayText()) textView.measuredHeight * textView.scaleY else 0f val previewHeight = if (linkPreviewView.visible) linkPreviewView.measuredHeight else 0 val availableHeight = backgroundHeight - textHeight if (availableHeight >= previewHeight) { val totalContentHeight = textHeight + previewHeight val topAndBottomMargin = backgroundHeight - totalContentHeight val margin = topAndBottomMargin / 2f linkPreviewView.translationY = -margin val originPoint = textView.measuredHeight / 2f val desiredPoint = (textHeight / 2f) + margin textView.translationY = desiredPoint - originPoint } else { linkPreviewView.translationY = 0f val originPoint = textView.measuredHeight / 2f val desiredPoint = backgroundHeight / 2f textView.translationY = desiredPoint - originPoint } } }
gpl-3.0
5603be8dfde24b939c19a9bdaef15f6e
30.192661
109
0.765
4.809052
false
false
false
false
ktorio/ktor
ktor-client/ktor-client-java/jvm/src/io/ktor/client/engine/java/JavaHttpRequest.kt
1
2466
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.java import io.ktor.client.call.* import io.ktor.client.engine.* import io.ktor.client.plugins.* import io.ktor.client.request.* import io.ktor.http.* import io.ktor.http.HttpHeaders import io.ktor.http.content.* import io.ktor.util.* import io.ktor.utils.io.* import kotlinx.coroutines.* import java.net.http.HttpRequest import java.time.* import java.util.* import kotlin.coroutines.* internal val DISALLOWED_HEADERS = TreeSet(String.CASE_INSENSITIVE_ORDER).apply { addAll( setOf( HttpHeaders.Connection, HttpHeaders.ContentLength, HttpHeaders.Date, HttpHeaders.Expect, HttpHeaders.From, HttpHeaders.Host, HttpHeaders.Upgrade, HttpHeaders.Via, HttpHeaders.Warning ) ) } @OptIn(InternalAPI::class) internal fun HttpRequestData.convertToHttpRequest(callContext: CoroutineContext): HttpRequest { val builder = HttpRequest.newBuilder(url.toURI()) with(builder) { getCapabilityOrNull(HttpTimeout)?.let { timeoutAttributes -> timeoutAttributes.requestTimeoutMillis?.let { if (!isTimeoutInfinite(it)) timeout(Duration.ofMillis(it)) } } mergeHeaders(headers, body) { key, value -> if (!DISALLOWED_HEADERS.contains(key)) { header(key, value) } } method(method.value, body.convertToHttpRequestBody(callContext)) } return builder.build() } @OptIn(DelicateCoroutinesApi::class) internal fun OutgoingContent.convertToHttpRequestBody( callContext: CoroutineContext ): HttpRequest.BodyPublisher = when (this) { is OutgoingContent.ByteArrayContent -> HttpRequest.BodyPublishers.ofByteArray(bytes()) is OutgoingContent.ReadChannelContent -> JavaHttpRequestBodyPublisher( coroutineContext = callContext, contentLength = contentLength ?: -1 ) { readFrom() } is OutgoingContent.WriteChannelContent -> JavaHttpRequestBodyPublisher( coroutineContext = callContext, contentLength = contentLength ?: -1 ) { GlobalScope.writer(callContext) { writeTo(channel) }.channel } is OutgoingContent.NoContent -> HttpRequest.BodyPublishers.noBody() else -> throw UnsupportedContentTypeException(this) }
apache-2.0
35abffd1287a8a5b3b20d6bf398858be
31.447368
118
0.689781
4.644068
false
false
false
false
android/project-replicator
code/codegen/src/main/kotlin/com/android/gradle/replicator/codegen/ImportClassPicker.kt
1
8458
/* * 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.codegen import java.util.concurrent.atomic.AtomicBoolean import kotlin.random.Random import kotlin.reflect.KFunction import kotlin.reflect.KParameter import kotlin.reflect.KVisibility import kotlin.reflect.full.declaredFunctions import kotlin.reflect.jvm.jvmErasure /** * Utility class to randomly pick a class from a list of imported modules and a classloader. * * The class picker will use and environment which is defined by a class loader capable of loading classes and * a list of modules each with a list of class names that can be loaded by the previously mentioned class loader. * * The picked class is constrained by a few factors to be able to be used in code generation. In particular, the class * must have the following attributes : * <ul> * <li> must be public * <li> must be a class, non abstract * <li> must have a valid constructor that takes arguments that are themselves following the same constraints. * <li> must not be deprecated. * <li> must have at least one function that can be called from generated code (with parameters all following the * same constraints). * </ul> */ open class ImportClassPicker( private val classLoader: ClassLoader, private val modules: List<GeneratorDriver.ModuleImport>, private val verifyClasses: Boolean = true) { /** * set to true if we cannot pick any class in this environment, to avoid rescanning needlessly */ private val emptyPicker = AtomicBoolean(false) /** * pick a class using the [random] randomizer. * * @param random the randomizer to use to pick up the class. * @return a picked class that can be used to generate code with or null if none can be found. */ open fun pickClass(random: Random): ClassModel<*>? { if (emptyPicker.get() || modules.isEmpty()) return null var moduleIndex = random.nextInt(modules.size) val startModuleIndex = moduleIndex var selectedModule = modules[moduleIndex] var classIndex = random.nextInt(selectedModule.classes.size) var startClassIndexInModule = classIndex var className = selectedModule.classes[classIndex] var loadedClass= loadClass(className) var classModel = if (loadedClass != null) { if (verifyClasses) isClassEligible(loadedClass) else loadModel(loadedClass) } else null while (classModel == null) { classIndex = (classIndex + 1) % selectedModule.classes.size if (classIndex == startClassIndexInModule) { moduleIndex = (moduleIndex + 1) % modules.size if (moduleIndex == startModuleIndex) { emptyPicker.set(true) return null } selectedModule = modules[moduleIndex] classIndex = random.nextInt(selectedModule.classes.size) startClassIndexInModule = classIndex } className = selectedModule.classes[classIndex] loadedClass= loadClass(className) if (loadedClass != null) { classModel = isClassEligible(loadedClass) } } return classModel } /** * Loads a class from the classloader. * * @param name the class name to load. * @return the loaded class or null if the class cannot be loaded. */ private fun loadClass(name: String): Class<*>? = try { classLoader.loadClass(name) // some imported modules are not packaged correctly and have references to classes not present. // this is usually not a problem as those references are probably dead code but the randomizer can pick them // nonetheless so we should handle these class loading failures graciously. } catch (e: ClassNotFoundException) { null } catch (e: NoClassDefFoundError) { null } /** * creates a [ClassModel] without verify if the classes are suitable for use in code generation. */ private fun loadModel(kClass: Class<*>): ClassModel<*>? { val selectedType = kClass.kotlin try { return ClassModel<Any>(selectedType, selectedType.constructors.first(), selectedType.declaredFunctions) } catch (e: Exception) { println("Caught !") return null } catch (e: Error) { println("Caught !") return null } } /** * Returns true if the class is eligible to used for code generation. It must follows all the constraints * described in the class comments. */ private fun isClassEligible(kClass: Class<*>?): ClassModel<*>? { try { // if the class loader that actually loaded the class is a parent class loader like the boot // classpath, do not use the class as it is probably a base JDK class version rather than // android specific one. if (kClass?.classLoader != classLoader) return null // avoid picking up kotlin.* as it is problematic when using java code generation. if (kClass.packageName.startsWith("kotlin")) return null if (!kClass.isInterface && !kClass.isAnnotation) { val selectedType = kClass.kotlin val declaredFunctions = selectedType.declaredFunctions if (!selectedType.isAbstract && isClassHierarchySafe(selectedType.java) && selectedType.visibility == KVisibility.PUBLIC && declaredFunctions.isNotEmpty() && selectedType.isNotDeprecated() && selectedType.isNotOptInType()) { val constructor = selectedType.findSuitableConstructor(mutableListOf()) ?: return null val suitableMethodsToCall = findSuitableMethodsToCall(declaredFunctions) if (suitableMethodsToCall.isEmpty()) return null return ClassModel<Any>(selectedType, constructor, suitableMethodsToCall) } } return null // A number of exceptions can be thrown by kotlin reflection. // Some of these exceptions are warranted like ClassNotFoundException which is due to faulty packaging // of dependencies. However, some like the java.lang.reflect.* ones are linked to features not implemented // in the kotlin reflection part or bugs in its implementation. } catch (e: Exception) { return null } catch (e: Error) { return null } } private fun isClassHierarchySafe(type: Class<*>): Boolean { if (!type.interfaces.all { intf -> isClassHierarchySafe(intf)}) return false return isTypeSafe(type) && (type.superclass == null || isClassHierarchySafe(type.superclass)) } private fun findSuitableMethodsToCall(methods: Collection<KFunction<*>>): List<KFunction<*>> = methods.filter { (it.isNotDeprecated() && it.isPublic() && it.allParametersCanBeInstantiated(mutableListOf()) && it.parameters.all { parameter -> isTypeSafe(parameter.type.jvmErasure.java) } && isTypeSafe(it.returnType.jvmErasure.java) && !it.isSuspend && (it.parameters.any { parameter -> parameter.kind == KParameter.Kind.INSTANCE })) } private fun isTypeSafe(type: Class<*>): Boolean = type.classLoader == classLoader || type.isPrimitive || type.packageName == "java.lang" || type.packageName == "java.util" }
apache-2.0
76dd8e8eb01d9411e962cb2190ab21c8
43.994681
118
0.633601
5.144769
false
false
false
false
StPatrck/edac
app/src/main/java/com/phapps/elitedangerous/companion/ui/MainActivity.kt
1
5250
package com.phapps.elitedangerous.companion.ui import android.content.Intent import android.os.Bundle import android.support.design.widget.NavigationView import android.support.design.widget.Snackbar import android.support.v4.app.Fragment import android.support.v4.view.GravityCompat import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import com.phapps.elitedangerous.companion.R import com.phapps.elitedangerous.companion.ui.galnet.GalNetFeedFragment import com.phapps.elitedangerous.companion.ui.settings.SettingsActivity import com.phapps.elitedangerous.companion.util.SharedPrefsHelper import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.support.HasSupportFragmentInjector import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.content_main.* import javax.inject.Inject /** * An [AppCompatActivity] that contains a [NavigationView] and a content * [android.widget.FrameLayout] to hold different [android.app.Fragment]s. * * Provides a `Settings` [Menu] option that starts the [SettingsActivity] when selected. */ class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener, HasSupportFragmentInjector { @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment> @Inject lateinit var navigationController: NavigationController @Inject lateinit var sharedPrefsHelper: SharedPrefsHelper override fun supportFragmentInjector(): AndroidInjector<Fragment> { return dispatchingAndroidInjector } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) val toggle = ActionBarDrawerToggle(this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) toggle.isDrawerIndicatorEnabled = false toggle.setToolbarNavigationClickListener { drawer_layout.openDrawer(GravityCompat.START) toggle.syncState() } toggle.syncState() drawer_layout.addDrawerListener(toggle) nav_view.setNavigationItemSelectedListener(this) if (savedInstanceState == null) { nav_view.menu?.getItem(0)?.isChecked = true var fragment = supportFragmentManager.findFragmentByTag(GalNetFeedFragment.TAG) if (fragment == null) { fragment = GalNetFeedFragment.newInstance() } supportFragmentManager.beginTransaction().replace(R.id.frame_content, fragment, GalNetFeedFragment.TAG).commit() } } override fun onBackPressed() { if (drawer_layout.isDrawerOpen(GravityCompat.START)) { drawer_layout.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { super.onCreateOptionsMenu(menu) menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_settings -> { startActivity(Intent(this@MainActivity, SettingsActivity::class.java)) true } else -> super.onOptionsItemSelected(item) } } override fun onNavigationItemSelected(item: MenuItem): Boolean { var handled = false when (item.itemId) { R.id.nav_galnet -> { handled = true navigationController.navigateToGalNet() } R.id.nav_item_profile -> { handled = onProfileClicked() } R.id.nav_settings -> { handled = true onSettingsClicked() } R.id.nav_item_edsm_system_search -> { handled = true navigationController.navigateToSystemSearch() } R.id.nav_item_edsm_calculate_route -> { handled = true navigationController.navigateToRouteCalculation() } } drawer_layout.closeDrawer(GravityCompat.START) return handled } private fun onProfileClicked(): Boolean { var handled = false if (sharedPrefsHelper.isEdcEnabled()) { handled = true navigationController.navigateToProfile() } else { val snackbar: Snackbar = Snackbar.make(nav_view, R.string.snack_edsm_not_configured, Snackbar.LENGTH_LONG) snackbar.setAction(R.string.snack_action_settings, { startActivity(Intent(this@MainActivity, SettingsActivity::class.java)) }) snackbar.show() } return handled } private fun onSettingsClicked() { startActivity(Intent(this, SettingsActivity::class.java)) } }
gpl-3.0
603ee2cf1902f53cfbe98a308874b6ba
34.958904
96
0.656381
5.15211
false
false
false
false
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/util/Identity.kt
1
7789
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * 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. */ @file:JvmName("Identity") package com.github.jonathanxd.kores.util import com.github.jonathanxd.kores.Types import com.github.jonathanxd.kores.type.KoresType import com.github.jonathanxd.kores.type.GenericType import com.github.jonathanxd.kores.type.LoadedKoresType import com.github.jonathanxd.iutils.string.ToStringHelper import com.github.jonathanxd.kores.type.koresType import java.lang.reflect.Type import java.util.* /** * Non-strict generic equality check, only works for generic types. * * This method will not make strict bound checks, it means that `List<?>` is equal to `List`, * `List<? extends Person>` is equal to `List<Person>`, but `List<Number>` is not equal to `List<Integer>`. */ fun KoresType.nonStrictEq(other: KoresType): Boolean { if (this is GenericType) return this.nonStrictEq(other) if (other is GenericType) return other.nonStrictEq(this) return this.`is`(other) } /** * Non-strict generic bound equality check, only works for generic types. * * This method will not make strict bound checks, it means that `List<?>` is equal to `List`, * `List<? extends Person>` is equal to `List<Person>`, but `List<Number>` is not equal to `List<Integer>`. */ fun GenericType.nonStrictEq(other: KoresType): Boolean { if (other is GenericType) { return this.isWildcard == other.isWildcard && this.isType == other.isType && this.name == other.name && this.bounds.nonStrictEq(other.bounds) } else { if (this.bounds.all { it.type is GenericType && it.type.isWildcard }) return this.resolvedType.identification == other.identification return this.isType && this.bounds.isEmpty() && this.identification == other.identification } } /** * Non-strict bound comparison. */ private fun GenericType.Bound.nonStrictEq(other: GenericType.Bound): Boolean { val thisType = this.type val otherType = other.type val comparator = { it: KoresType, second: KoresType -> (it is GenericType && it.isWildcard) && (it.bounds.isEmpty() && ( second is GenericType && second.bounds.size == 1 && second.bounds.first().nonStrictEq(GenericType.GenericBound(Types.OBJECT)) || second.`is`(Types.OBJECT) ) || ( it.bounds.isNotEmpty() && it.bounds.any { it.type.`is`(second) } )) } return comparator(thisType, otherType) || comparator( otherType, thisType ) || thisType.`is`(other.type) } /** * Non-strict array bound comparison. */ private fun Array<out GenericType.Bound>.nonStrictEq(others: Array<out GenericType.Bound>): Boolean { if (this.size != others.size) return false this.forEachIndexed { index, bound -> if (!bound.nonStrictEq(others[index])) return@nonStrictEq false } return true } /** * Default equals algorithm for [GenericType] */ fun GenericType.eq(other: Any?): Boolean = this.identityEq(other) /** * Default hashCode algorithm for [GenericType] */ fun GenericType.hash(): Int { if (this.isType && this.bounds.isEmpty()) return (this as KoresType).hash() var result = Objects.hash(this.name, this.isType, this.isWildcard) result = 31 * result + Arrays.deepHashCode(this.bounds) return result } /** * Default to string conversion for [GenericType]. * * This method convert [GenericType] to a Java Source representation of the [GenericType], * see the algorithm of translation [here][toSourceString]. */ fun GenericType.toStr(): String { return this.toSourceString() } /** * * Creates string representation of components of [GenericType]. * * **This method is not recommended for object comparison.** */ fun GenericType.toComponentString(): String = ToStringHelper.defaultHelper(this::class.java.simpleName) .add("name", this.name) .add("isWildcard", this.isWildcard) .add(if (this.isType) "codeType" else "inferredType", this.resolvedType) .add("isType", this.isWildcard) .add("bounds", this.bounds.map { it.toComponentString() }) .toString() /** * Creates a string representation of components of [GenericType.Bound]. * * **This method is not recommended for object comparison.** */ fun GenericType.Bound.toComponentString(): String = ToStringHelper.defaultHelper(this::class.java.simpleName) .add("sign", this.sign) .add("type", this.type) .toString() /** * Default hash algorithm. * * @return Hash code. */ fun KoresType.identityHash(): Int = this.identification.hashCode() /** * Default equals method. * * @param obj Object to test. * @return True if this [KoresType] is equals to another [KoresType]. */ fun KoresType.identityEq(obj: Any?): Boolean = obj is KoresType && this.identification == obj.identification /** * Default hash algorithm. * * @return Hash code. */ fun KoresType.hash(): Int = this.identityHash() /** * Default equals method. * * @param obj Object to test. * @return True if this [KoresType] is equals to another [KoresType]. */ fun KoresType.eq(obj: Any?): Boolean = this.identityEq(obj) /** * Default to string conversion for [KoresType]. * * This methods generates a string with the simple name of current class and the [Type Identification][KoresType.identification]. */ fun KoresType.toStr(): String = "${this::class.java.simpleName}[${this.identification}]" /** * Default equality check for [LoadedKoresType], this method checks if the loaded types are equal. */ fun <T> LoadedKoresType<T>.eq(obj: Any?) = when (obj) { null -> false is LoadedKoresType<*> -> this.loadedType == obj.loadedType else -> (this as KoresType).eq(obj) } /** * Helper for checking equality of two types. Delegates to [KoresType.identityEq] */ operator fun Type.contains(other: Type) = this.koresType.`is`(other.koresType) /** * Helper for checking equality of two types. Delegates to [KoresType.identityEq] */ operator fun Type.contains(others: List<Type>) = others.any { it.koresType.`is`(this.koresType) }
mit
4d47444a8855a3fbf32915b06b17b820
31.057613
129
0.66427
4.1944
false
false
false
false
dahlstrom-g/intellij-community
plugins/git4idea/src/git4idea/index/ui/GitStageCommitPanel.kt
5
5420
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.index.ui import com.intellij.openapi.Disposable import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.containers.DisposableWrapperList import com.intellij.util.ui.JBUI.Borders.empty import com.intellij.vcs.commit.CommitProgressPanel import com.intellij.vcs.commit.EditedCommitDetails import com.intellij.vcs.commit.NonModalCommitPanel import git4idea.i18n.GitBundle import git4idea.index.ContentVersion import git4idea.index.GitFileStatus import git4idea.index.GitStageTracker import git4idea.index.createChange import kotlin.properties.Delegates.observable private fun GitStageTracker.State.getStaged(): Set<GitFileStatus> = rootStates.values.flatMapTo(mutableSetOf()) { it.getStaged() } private fun GitStageTracker.RootState.getStaged(): Set<GitFileStatus> = statuses.values.filterTo(mutableSetOf()) { it.getStagedStatus() != null } private fun GitStageTracker.RootState.getStagedChanges(project: Project): List<Change> = getStaged().mapNotNull { createChange(project, root, it, ContentVersion.HEAD, ContentVersion.STAGED) } class GitStageCommitPanel(project: Project) : NonModalCommitPanel(project) { private val progressPanel = GitStageCommitProgressPanel() override val commitProgressUi: GitStageCommitProgressPanel get() = progressPanel @Volatile private var state: InclusionState = InclusionState(emptySet(), GitStageTracker.State.EMPTY) val rootsToCommit get() = state.rootsToCommit val includedRoots get() = state.includedRoots val conflictedRoots get() = state.conflictedRoots private val editedCommitListeners = DisposableWrapperList<() -> Unit>() override var editedCommit: EditedCommitDetails? by observable(null) { _, _, _ -> editedCommitListeners.forEach { it() } } init { Disposer.register(this, commitMessage) commitMessage.setChangesSupplier { state.stagedChanges } progressPanel.setup(this, commitMessage.editorField) bottomPanel = { add(progressPanel.apply { border = empty(6) }) add(commitAuthorComponent.apply { border = empty(0, 5, 4, 0) }) add(commitActionsPanel) } buildLayout() } fun setIncludedRoots(includedRoots: Collection<VirtualFile>) { setState(includedRoots, state.trackerState) } fun setTrackerState(trackerState: GitStageTracker.State) { setState(state.includedRoots, trackerState) } private fun setState(includedRoots: Collection<VirtualFile>, trackerState: GitStageTracker.State) { val newState = InclusionState(includedRoots, trackerState) if (state != newState) { state = newState fireInclusionChanged() } } fun addEditedCommitListener(listener: () -> Unit, parent: Disposable) { editedCommitListeners.add(listener, parent) } override fun activate(): Boolean = true override fun refreshData() = Unit override fun getDisplayedChanges(): List<Change> = emptyList() override fun getIncludedChanges(): List<Change> = state.stagedChanges override fun getDisplayedUnversionedFiles(): List<FilePath> = emptyList() override fun getIncludedUnversionedFiles(): List<FilePath> = emptyList() override fun includeIntoCommit(items: Collection<*>) = Unit private inner class InclusionState(val includedRoots: Collection<VirtualFile>, val trackerState: GitStageTracker.State) { private val stagedStatuses: Set<GitFileStatus> = trackerState.getStaged() val conflictedRoots: Set<VirtualFile> = trackerState.rootStates.filter { it.value.hasConflictedFiles() }.keys val stagedChanges by lazy { trackerState.rootStates.filterKeys { includedRoots.contains(it) }.values.flatMap { it.getStagedChanges(project) } } val rootsToCommit get() = trackerState.stagedRoots.intersect(includedRoots) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as InclusionState if (includedRoots != other.includedRoots) return false if (stagedStatuses != other.stagedStatuses) return false if (conflictedRoots != other.conflictedRoots) return false return true } override fun hashCode(): Int { var result = includedRoots.hashCode() result = 31 * result + stagedStatuses.hashCode() result = 31 * result + conflictedRoots.hashCode() return result } } } class GitStageCommitProgressPanel : CommitProgressPanel() { var isEmptyRoots by stateFlag() var isUnmerged by stateFlag() override fun clearError() { super.clearError() isEmptyRoots = false isUnmerged = false } override fun buildErrorText(): String? = when { isEmptyRoots -> GitBundle.message("error.no.selected.roots.to.commit") isUnmerged -> GitBundle.message("error.unresolved.conflicts") isEmptyChanges && isEmptyMessage -> GitBundle.message("error.no.staged.changes.no.commit.message") isEmptyChanges -> GitBundle.message("error.no.staged.changes.to.commit") isEmptyMessage -> VcsBundle.message("error.no.commit.message") else -> null } }
apache-2.0
867a456e77cfab46ccb9194507022824
37.169014
140
0.75203
4.688581
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/usecases/first_android_app/src/main/kotlin/com/example/awsapp/Database.kt
1
1549
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.example.awsapp import aws.sdk.kotlin.services.dynamodb.DynamoDbClient import aws.sdk.kotlin.services.dynamodb.model.AttributeValue import aws.sdk.kotlin.services.dynamodb.model.PutItemRequest import aws.sdk.kotlin.services.dynamodb.model.DynamoDbException import kotlin.system.exitProcess class Database { suspend fun putItemInTable2( ddb: DynamoDbClient, tableNameVal: String, key: String, keyVal: String, moneyTotal: String, moneyTotalValue: String, name: String, nameValue: String, email: String, emailVal: String, date: String, dateVal: String, ) { val itemValues = mutableMapOf<String, AttributeValue>() // Add all content to the table. itemValues[key] = AttributeValue.S(keyVal) itemValues[moneyTotal] = AttributeValue.S(moneyTotalValue) itemValues[name] = AttributeValue.S(nameValue) itemValues[email] = AttributeValue.S(emailVal) itemValues[date] = AttributeValue.S(dateVal) val request = PutItemRequest { tableName=tableNameVal item = itemValues } try { ddb.putItem(request) println(" A new item was placed into $tableNameVal.") } catch (ex: DynamoDbException) { println(ex.message) ddb.close() exitProcess(0) } } }
apache-2.0
292d1d5d200e941386165fce850098d8
27.685185
69
0.639768
4.351124
false
false
false
false
airbnb/epoxy
epoxy-adapter/src/main/java/com/airbnb/epoxy/preload/EpoxyPreloader.kt
1
10878
package com.airbnb.epoxy.preload import android.content.Context import android.view.View import android.widget.ImageView import androidx.annotation.IdRes import androidx.annotation.Px import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.airbnb.epoxy.BaseEpoxyAdapter import com.airbnb.epoxy.EpoxyAdapter import com.airbnb.epoxy.EpoxyController import com.airbnb.epoxy.EpoxyModel import com.airbnb.epoxy.getModelForPositionInternal import kotlin.math.max import kotlin.math.min /** * A scroll listener that prefetches view content. * * To use this, create implementations of [EpoxyModelPreloader] for each EpoxyModel class that you want to preload. * Then, use the [EpoxyPreloader.with] methods to create an instance that preloads models of that type. * Finally, add the resulting scroll listener to your RecyclerView. * * If you are using [com.airbnb.epoxy.EpoxyRecyclerView] then use [com.airbnb.epoxy.EpoxyRecyclerView.addPreloader] * to setup the preloader as a listener. * * Otherwise there is a [RecyclerView.addEpoxyPreloader] extension for easy usage. */ class EpoxyPreloader<P : PreloadRequestHolder> private constructor( private val adapter: BaseEpoxyAdapter, preloadTargetFactory: () -> P, errorHandler: PreloadErrorHandler, private val maxItemsToPreload: Int, modelPreloaders: List<EpoxyModelPreloader<*, *, out P>> ) : RecyclerView.OnScrollListener() { private var lastVisibleRange: IntRange = IntRange.EMPTY private var lastPreloadRange: IntProgression = IntRange.EMPTY private var totalItemCount = -1 private var scrollState: Int = RecyclerView.SCROLL_STATE_IDLE private val modelPreloaders: Map<Class<out EpoxyModel<*>>, EpoxyModelPreloader<*, *, out P>> = modelPreloaders.associateBy { it.modelType } private val requestHolderFactory = PreloadTargetProvider(maxItemsToPreload, preloadTargetFactory) private val viewDataCache = PreloadableViewDataProvider(adapter, errorHandler) constructor( epoxyController: EpoxyController, requestHolderFactory: () -> P, errorHandler: PreloadErrorHandler, maxItemsToPreload: Int, modelPreloaders: List<EpoxyModelPreloader<*, *, out P>> ) : this( epoxyController.adapter, requestHolderFactory, errorHandler, maxItemsToPreload, modelPreloaders ) constructor( adapter: EpoxyAdapter, requestHolderFactory: () -> P, errorHandler: PreloadErrorHandler, maxItemsToPreload: Int, modelPreloaders: List<EpoxyModelPreloader<*, *, out P>> ) : this( adapter as BaseEpoxyAdapter, requestHolderFactory, errorHandler, maxItemsToPreload, modelPreloaders ) init { require(maxItemsToPreload > 0) { "maxItemsToPreload must be greater than 0. Was $maxItemsToPreload" } } override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { scrollState = newState } override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { if (dx == 0 && dy == 0) { // Sometimes flings register a bunch of 0 dx/dy scroll events. To avoid redundant prefetching we just skip these // Additionally, the first RecyclerView layout notifies a scroll of 0, since that can be an important time for // performance (eg page load) we avoid prefetching at the same time. return } if (dx.isFling() || dy.isFling()) { // We avoid preloading during flings for two reasons // 1. Image requests are expensive and we don't want to drop frames on fling // 2. We'll likely scroll past the preloading item anyway return } // Update item count before anything else because validations depend on it totalItemCount = recyclerView.adapter?.itemCount ?: 0 val layoutManager = recyclerView.layoutManager as LinearLayoutManager val firstVisiblePosition = layoutManager.findFirstVisibleItemPosition() val lastVisiblePosition = layoutManager.findLastVisibleItemPosition() if (firstVisiblePosition.isInvalid() || lastVisiblePosition.isInvalid()) { lastVisibleRange = IntRange.EMPTY lastPreloadRange = IntRange.EMPTY return } val visibleRange = IntRange(firstVisiblePosition, lastVisiblePosition) if (visibleRange == lastVisibleRange) { return } val isIncreasing = visibleRange.first > lastVisibleRange.first || visibleRange.last > lastVisibleRange.last val preloadRange = calculatePreloadRange(firstVisiblePosition, lastVisiblePosition, isIncreasing) // Start preload for any items that weren't already preloaded preloadRange .subtract(lastPreloadRange) .forEach { preloadAdapterPosition(it) } lastVisibleRange = visibleRange lastPreloadRange = preloadRange } /** * @receiver The number of pixels scrolled. * @return True if this distance is large enough to be considered a fast fling. */ private fun Int.isFling() = Math.abs(this) > FLING_THRESHOLD_PX private fun calculatePreloadRange( firstVisiblePosition: Int, lastVisiblePosition: Int, isIncreasing: Boolean ): IntProgression { val from = if (isIncreasing) lastVisiblePosition + 1 else firstVisiblePosition - 1 val to = from + if (isIncreasing) maxItemsToPreload - 1 else 1 - maxItemsToPreload return IntProgression.fromClosedRange( rangeStart = from.clampToAdapterRange(), rangeEnd = to.clampToAdapterRange(), step = if (isIncreasing) 1 else -1 ) } /** Check if an item index is valid. It may not be if the adapter is empty, or if adapter changes have been dispatched since the last layout pass. */ private fun Int.isInvalid() = this == RecyclerView.NO_POSITION || this >= totalItemCount private fun Int.clampToAdapterRange() = min(totalItemCount - 1, max(this, 0)) private fun preloadAdapterPosition(position: Int) { @Suppress("UNCHECKED_CAST") val epoxyModel = adapter.getModelForPositionInternal(position) as? EpoxyModel<Any> ?: return @Suppress("UNCHECKED_CAST") val preloader = modelPreloaders[epoxyModel::class.java] as? EpoxyModelPreloader<EpoxyModel<*>, ViewMetadata?, P> ?: return viewDataCache .dataForModel(preloader, epoxyModel, position) .forEach { viewData -> val preloadTarget = requestHolderFactory.next() preloader.startPreload(epoxyModel, preloadTarget, viewData) } } /** * Cancels all current preload requests in progress. */ fun cancelPreloadRequests() { requestHolderFactory.clearAll() } companion object { /** * * Represents a threshold for fast scrolling. * This is a bit arbitrary and was determined by looking at values while flinging vs slow scrolling. * Ideally it would be based on DP, but this is simpler. */ private const val FLING_THRESHOLD_PX = 75 /** * Helper to create a preload scroll listener. Add the result to your RecyclerView. * for different models or content types. * * @param maxItemsToPreload How many items to prefetch ahead of the last bound item * @param errorHandler Called when the preloader encounters an exception. By default this throws only * if the app is not in a debuggle model * @param modelPreloader Describes how view content for the EpoxyModel should be preloaded * @param requestHolderFactory Should create and return a new [PreloadRequestHolder] each time it is invoked */ fun <P : PreloadRequestHolder> with( epoxyController: EpoxyController, requestHolderFactory: () -> P, errorHandler: PreloadErrorHandler, maxItemsToPreload: Int, modelPreloader: EpoxyModelPreloader<out EpoxyModel<*>, out ViewMetadata?, out P> ): EpoxyPreloader<P> = with( epoxyController, requestHolderFactory, errorHandler, maxItemsToPreload, listOf(modelPreloader) ) fun <P : PreloadRequestHolder> with( epoxyController: EpoxyController, requestHolderFactory: () -> P, errorHandler: PreloadErrorHandler, maxItemsToPreload: Int, modelPreloaders: List<EpoxyModelPreloader<out EpoxyModel<*>, out ViewMetadata?, out P>> ): EpoxyPreloader<P> { return EpoxyPreloader( epoxyController, requestHolderFactory, errorHandler, maxItemsToPreload, modelPreloaders ) } /** Helper to create a preload scroll listener. Add the result to your RecyclerView. */ fun <P : PreloadRequestHolder> with( epoxyAdapter: EpoxyAdapter, requestHolderFactory: () -> P, errorHandler: PreloadErrorHandler, maxItemsToPreload: Int, modelPreloaders: List<EpoxyModelPreloader<out EpoxyModel<*>, out ViewMetadata?, out P>> ): EpoxyPreloader<P> { return EpoxyPreloader( epoxyAdapter, requestHolderFactory, errorHandler, maxItemsToPreload, modelPreloaders ) } } } class EpoxyPreloadException(errorMessage: String) : RuntimeException(errorMessage) typealias PreloadErrorHandler = (Context, RuntimeException) -> Unit /** * Data about an image view to be preloaded. This data is used to construct a Glide image request. * * @param metadata Any custom, additional data that the [EpoxyModelPreloader] chooses to provide that may be necessary to create the image request. */ class ViewData<out U : ViewMetadata?>( @IdRes val viewId: Int, @Px val width: Int, @Px val height: Int, val metadata: U ) interface ViewMetadata { companion object { fun getDefault(view: View): ViewMetadata? { return when (view) { is ImageView -> ImageViewMetadata(view.scaleType) else -> null } } } } /** * Default implementation of [ViewMetadata] for an ImageView. * This data can help the preload request know how to configure itself. */ open class ImageViewMetadata( val scaleType: ImageView.ScaleType ) : ViewMetadata
apache-2.0
2f223a877e218085dd4ffd0fa1563feb
36.12628
153
0.66014
5.474585
false
false
false
false
paplorinc/intellij-community
python/src/com/jetbrains/python/debugger/PySetNextStatementAction.kt
7
3670
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.debugger import com.intellij.codeInsight.hint.HintManager import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Pair import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.impl.DebuggerSupport import com.intellij.xdebugger.impl.XDebuggerUtilImpl import com.intellij.xdebugger.impl.actions.XDebuggerActionBase import com.intellij.xdebugger.impl.actions.XDebuggerSuspendedActionHandler import com.jetbrains.python.debugger.pydev.PyDebugCallback class PySetNextStatementAction : XDebuggerActionBase(true) { private val setNextStatementActionHandler: XDebuggerSuspendedActionHandler init { setNextStatementActionHandler = object : XDebuggerSuspendedActionHandler() { override fun perform(session: XDebugSession, dataContext: DataContext) { val debugProcess = session.debugProcess as? PyDebugProcess ?: return val position = XDebuggerUtilImpl.getCaretPosition(session.project, dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(dataContext) ?: FileEditorManager.getInstance(session.project).selectedTextEditor val suspendContext = debugProcess.session.suspendContext ApplicationManager.getApplication().executeOnPooledThread(Runnable { debugProcess.startSetNextStatement(suspendContext, position, object : PyDebugCallback<Pair<Boolean, String>> { override fun ok(response: Pair<Boolean, String>) { if (!response.first && editor != null) { ApplicationManager.getApplication().invokeLater(Runnable { if (!editor.isDisposed) { editor.caretModel.moveToOffset(position.offset) HintManager.getInstance().showErrorHint(editor, response.second) } }, ModalityState.defaultModalityState()) } } override fun error(e: PyDebuggerException) { LOG.error(e) } }) }) } override fun isEnabled(project: Project, event: AnActionEvent): Boolean { return super.isEnabled(project, event) && PyDebugSupportUtils.isCurrentPythonDebugProcess(project) } } } override fun getHandler(debuggerSupport: DebuggerSupport): XDebuggerSuspendedActionHandler = setNextStatementActionHandler override fun isHidden(event: AnActionEvent): Boolean { val project = event.getData(CommonDataKeys.PROJECT) return project == null || !PyDebugSupportUtils.isCurrentPythonDebugProcess(project) } companion object { private val LOG = Logger.getInstance("#com.jetbrains.python.debugger.PySetNextStatementAction") } }
apache-2.0
6518c4c3ec1fc4606b922a3b5bf2541b
44.308642
132
0.747684
5.027397
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/MovePropertyToClassBodyIntention.kt
1
4731
// 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.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.util.mustHaveOnlyPropertiesInPrimaryConstructor import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClass import org.jetbrains.kotlin.psi.psiUtil.isPropertyParameter import org.jetbrains.kotlin.resolve.AnnotationChecker import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class MovePropertyToClassBodyIntention : SelfTargetingIntention<KtParameter>( KtParameter::class.java, KotlinBundle.lazyMessage("move.to.class.body") ) { override fun isApplicableTo(element: KtParameter, caretOffset: Int): Boolean { if (!element.isPropertyParameter()) return false val containingClass = element.containingClass() ?: return false return !containingClass.mustHaveOnlyPropertiesInPrimaryConstructor() } override fun applyTo(element: KtParameter, editor: Editor?) { val parentClass = PsiTreeUtil.getParentOfType(element, KtClass::class.java) ?: return val propertyDeclaration = KtPsiFactory(element).createProperty("${element.valOrVarKeyword?.text} ${element.name} = ${element.name}") val firstProperty = parentClass.getProperties().firstOrNull() parentClass.addDeclarationBefore(propertyDeclaration, firstProperty).apply { val propertyModifierList = element.modifierList?.copy() as? KtModifierList propertyModifierList?.getModifier(KtTokens.VARARG_KEYWORD)?.delete() propertyModifierList?.let { modifierList?.replace(it) ?: addBefore(it, firstChild) } modifierList?.annotationEntries?.forEach { if (!it.isAppliedToProperty()) { it.delete() } else if (it.useSiteTarget?.getAnnotationUseSiteTarget() == AnnotationUseSiteTarget.PROPERTY) { it.useSiteTarget?.removeWithColon() } } } element.valOrVarKeyword?.delete() val parameterAnnotationsText = element.modifierList?.annotationEntries ?.filter { it.isAppliedToConstructorParameter() } ?.takeIf { it.isNotEmpty() } ?.joinToString(separator = " ") { it.textWithoutUseSite() } val hasVararg = element.hasModifier(KtTokens.VARARG_KEYWORD) if (parameterAnnotationsText != null) { element.modifierList?.replace(KtPsiFactory(element).createModifierList(parameterAnnotationsText)) } else { element.modifierList?.delete() } if (hasVararg) element.addModifier(KtTokens.VARARG_KEYWORD) } private fun KtAnnotationEntry.isAppliedToProperty(): Boolean { useSiteTarget?.getAnnotationUseSiteTarget()?.let { return it == AnnotationUseSiteTarget.FIELD || it == AnnotationUseSiteTarget.PROPERTY || it == AnnotationUseSiteTarget.PROPERTY_GETTER || it == AnnotationUseSiteTarget.PROPERTY_SETTER || it == AnnotationUseSiteTarget.SETTER_PARAMETER } return !isApplicableToConstructorParameter() } private fun KtAnnotationEntry.isAppliedToConstructorParameter(): Boolean { useSiteTarget?.getAnnotationUseSiteTarget()?.let { return it == AnnotationUseSiteTarget.CONSTRUCTOR_PARAMETER } return isApplicableToConstructorParameter() } private fun KtAnnotationEntry.isApplicableToConstructorParameter(): Boolean { val context = analyze(BodyResolveMode.PARTIAL) val descriptor = context[BindingContext.ANNOTATION, this] ?: return false val applicableTargets = AnnotationChecker.applicableTargetSet(descriptor) return applicableTargets.contains(KotlinTarget.VALUE_PARAMETER) } private fun KtAnnotationEntry.textWithoutUseSite() = "@" + typeReference?.text.orEmpty() + valueArgumentList?.text.orEmpty() private fun KtAnnotationUseSiteTarget.removeWithColon() { nextSibling?.delete() // ':' symbol after use site delete() } }
apache-2.0
cadc24931a3bde6c9a70766951229de5
46.787879
158
0.719087
5.552817
false
false
false
false
vhromada/Catalog
web/src/main/kotlin/com/github/vhromada/catalog/web/controller/RegistrationController.kt
1
2557
package com.github.vhromada.catalog.web.controller import com.github.vhromada.catalog.web.connector.AccountConnector import com.github.vhromada.catalog.web.fo.AccountFO import com.github.vhromada.catalog.web.mapper.AccountMapper import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.validation.Errors import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.ModelAttribute import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestMapping import javax.validation.Valid /** * A class represents controller for registration. * * @author Vladimir Hromada */ @Controller("registrationController") @RequestMapping("/registration") class RegistrationController( /** * Connector for accounts */ private val connector: AccountConnector, /** * Mapper for accounts */ private val mapper: AccountMapper ) { /** * Shows page for registration. * * @param model model * @return view for page for registration */ @GetMapping fun login(model: Model): String { return createFormView(model = model, account = AccountFO(username = null, password = null, copyPassword = null)) } /** * Process creating account. * * @param model model * @param account FO for account * @param errors errors * @return view for redirect to page with login (no errors) or view for page for creating user (errors) */ @PostMapping(params = ["create"]) fun processAdd(model: Model, @ModelAttribute("account") @Valid account: AccountFO, errors: Errors): String { if (errors.hasErrors()) { return createFormView(model = model, account = account) } connector.addCredentials(credentials = mapper.map(source = account)) return "redirect:/login" } /** * Cancel creating account. * * @return view for redirect to page with login */ @PostMapping(params = ["cancel"]) fun cancelAdd(): String { return "redirect:/login" } /** * Returns page's view with form. * * @param model model * @param account FO for account * @return page's view with form */ private fun createFormView(model: Model, account: AccountFO): String { model.addAttribute("account", account) model.addAttribute("title", "Registration") return "registration/registration" } }
mit
02939762ad8d83c65b259cce14facb91
28.732558
120
0.681658
4.493849
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinMethodSmartStepTarget.kt
1
3218
// 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.debugger.stepping.smartStepInto import com.intellij.debugger.engine.MethodFilter import com.intellij.openapi.application.runReadAction import com.intellij.psi.PsiElement import com.intellij.psi.SmartPsiElementPointer import com.intellij.util.Range import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.decompiler.navigation.SourceNavigationHelper import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.renderer.ParameterNameRenderingPolicy import org.jetbrains.kotlin.renderer.PropertyAccessorRenderingPolicy import javax.swing.Icon class KotlinMethodSmartStepTarget( lines: Range<Int>, highlightElement: PsiElement, label: String, declaration: KtDeclaration?, val ordinal: Int, val methodInfo: CallableMemberInfo ) : KotlinSmartStepTarget(label, highlightElement, false, lines) { companion object { private val renderer = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withOptions { parameterNameRenderingPolicy = ParameterNameRenderingPolicy.NONE withoutReturnType = true propertyAccessorRenderingPolicy = PropertyAccessorRenderingPolicy.PRETTY startFromName = true modifiers = emptySet() } fun calcLabel(descriptor: DeclarationDescriptor): String { return renderer.render(descriptor) } } private val declarationPtr = declaration?.let(SourceNavigationHelper::getNavigationElement)?.createSmartPointer() init { assert(declaration != null || methodInfo.isInvoke) } override fun getIcon(): Icon = if (methodInfo.isExtension) KotlinIcons.EXTENSION_FUNCTION else KotlinIcons.FUNCTION fun getDeclaration(): KtDeclaration? = declarationPtr.getElementInReadAction() override fun createMethodFilter(): MethodFilter { val declaration = declarationPtr.getElementInReadAction() return KotlinMethodFilter(declaration, callingExpressionLines, methodInfo) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other !is KotlinMethodSmartStepTarget) return false if (methodInfo.isInvoke && other.methodInfo.isInvoke) { // Don't allow to choose several invoke targets in smart step into as we can't distinguish them reliably during debug return true } return highlightElement === other.highlightElement } override fun hashCode(): Int { if (methodInfo.isInvoke) { // Predefined value to make all FunctionInvokeDescriptor targets equal return 42 } return highlightElement.hashCode() } } internal fun <T : PsiElement> SmartPsiElementPointer<T>?.getElementInReadAction(): T? = this?.let { runReadAction { element } }
apache-2.0
07d25d1ffc706251cce4faaf737f3116
39.225
158
0.740211
5.372287
false
false
false
false
Homes-MinecraftServerMod/Homes
src/main/kotlin/com/masahirosaito/spigot/homes/nms/v1_12_R1/NMSController_v1_12_R1.kt
1
1598
package com.masahirosaito.spigot.homes.nms.v1_12_R1 import com.masahirosaito.spigot.homes.nms.HomesEntity import com.masahirosaito.spigot.homes.nms.NMSController import com.masahirosaito.spigot.homes.nms.NMSEntityArmorStand import com.masahirosaito.spigot.homes.strings.HomeDisplayStrings.DEFAULT_HOME_DISPLAY_NAME import com.masahirosaito.spigot.homes.strings.HomeDisplayStrings.NAMED_HOME_DISPLAY_NAME import org.bukkit.craftbukkit.v1_12_R1.CraftWorld import org.bukkit.event.entity.CreatureSpawnEvent class NMSController_v1_12_R1 : NMSController { override fun setUp() { CustomEntities.registerEntities() } override fun spawn(homesEntity: HomesEntity): List<NMSEntityArmorStand> { val texts = if (homesEntity.homeName == null) { DEFAULT_HOME_DISPLAY_NAME(homesEntity.offlinePlayer.name).split("\n") } else { NAMED_HOME_DISPLAY_NAME(homesEntity.offlinePlayer.name, homesEntity.homeName!!).split("\n") } val list: MutableList<NMSEntityArmorStand> = mutableListOf() val location = homesEntity.location texts.forEachIndexed { index, text -> list.add(EntityNMSArmorStand((location.world as CraftWorld).handle).apply { setNMSName(text) setNameVisible(!homesEntity.isPrivate) setPosition(location.x, location.y + 0.8 - (index * 0.2), location.z) (homesEntity.location.world as CraftWorld).handle .addEntity(this, CreatureSpawnEvent.SpawnReason.CUSTOM) }) } return list } }
apache-2.0
25569ad7a9f9bf1a43825bbb314356ce
42.189189
103
0.696496
4.227513
false
false
false
false
glodanif/BluetoothChat
app/src/main/kotlin/com/glodanif/bluetoothchat/data/service/message/Contract.kt
1
2307
package com.glodanif.bluetoothchat.data.service.message import androidx.annotation.ColorInt import java.io.File class Contract { var partnerVersion: Int = MESSAGE_CONTRACT_VERSION infix fun setupWith(version: Int) { partnerVersion = version } fun reset() { partnerVersion = MESSAGE_CONTRACT_VERSION } fun createChatMessage(message: String) = Message(generateUniqueId(), message, MessageType.MESSAGE) fun createConnectMessage(name: String, @ColorInt color: Int) = Message(0, "$name$DIVIDER$color$DIVIDER$MESSAGE_CONTRACT_VERSION", true, MessageType.CONNECTION_REQUEST) fun createDisconnectMessage() = Message(false, MessageType.CONNECTION_REQUEST) fun createAcceptConnectionMessage(name: String, @ColorInt color: Int) = Message("$name$DIVIDER$color$DIVIDER$MESSAGE_CONTRACT_VERSION", true, MessageType.CONNECTION_RESPONSE) fun createRejectConnectionMessage(name: String, @ColorInt color: Int) = Message("$name$DIVIDER$color$DIVIDER$MESSAGE_CONTRACT_VERSION", false, MessageType.CONNECTION_RESPONSE) fun createSuccessfulDeliveryMessage(id: Long) = Message(id, true, MessageType.DELIVERY) fun createFileStartMessage(file: File, type: PayloadType): Message { val uid = if (partnerVersion >= 2) generateUniqueId() else 0L return Message(uid, "${file.name.replace(DIVIDER, "")}$DIVIDER${file.length()}$DIVIDER${type.value}", false, MessageType.FILE_START) } fun createFileEndMessage() = Message(false, MessageType.FILE_END) fun isFeatureAvailable(feature: Feature) = when (feature) { Feature.IMAGE_SHARING -> partnerVersion >= 1 } enum class MessageType(val value: Int) { UNEXPECTED(-1), MESSAGE(0), DELIVERY(1), CONNECTION_RESPONSE(2), CONNECTION_REQUEST(3), SEEING(4), EDITING(5), FILE_START(6), FILE_END(7), FILE_CANCELED(8); companion object { fun from(findValue: Int) = values().first { it.value == findValue } } } enum class Feature { IMAGE_SHARING; } companion object { const val DIVIDER = "#" const val MESSAGE_CONTRACT_VERSION = 2 fun generateUniqueId() = System.nanoTime() } }
apache-2.0
07008720785311d6483e4dc13ea5568b
30.175676
140
0.666667
4.272222
false
false
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/actions/ReaderModeActionProvider.kt
3
7007
// 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.codeInsight.actions import com.intellij.codeInsight.actions.ReaderModeSettings.Companion.matchMode import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.icons.AllIcons import com.intellij.ide.HelpTooltip import com.intellij.lang.LangBundle import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.actionSystem.impl.ActionButtonWithText import com.intellij.openapi.application.Experiments import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.ColorKey import com.intellij.openapi.editor.markup.InspectionWidgetActionProvider import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.DumbAwareToggleAction import com.intellij.openapi.project.Project import com.intellij.openapi.project.isNotificationSilentMode import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.registry.Registry import com.intellij.psi.PsiDocumentManager import com.intellij.ui.GotItTooltip import com.intellij.ui.JBColor import com.intellij.ui.scale.JBUIScale import com.intellij.util.NotNullProducer import com.intellij.util.ui.EmptyIcon import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.Insets import javax.swing.JComponent import javax.swing.plaf.FontUIResource private class ReaderModeActionProvider : InspectionWidgetActionProvider { override fun createAction(editor: Editor): AnAction? { val project: Project? = editor.project return if (project == null || project.isDefault) null else object : DefaultActionGroup(ReaderModeAction(editor), Separator.create()) { override fun update(e: AnActionEvent) { if (!Experiments.getInstance().isFeatureEnabled("editor.reader.mode")) { e.presentation.isEnabledAndVisible = false } else { if (project.isInitialized) { val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document)?.virtualFile e.presentation.isEnabledAndVisible = matchMode(project, file, editor) } else { e.presentation.isEnabledAndVisible = false } } } } } private class ReaderModeAction(private val editor: Editor) : DumbAwareToggleAction( LangBundle.messagePointer("action.ReaderModeProvider.text"), LangBundle.messagePointer("action.ReaderModeProvider.description"), null), CustomComponentAction { override fun createCustomComponent(presentation: Presentation, place: String): JComponent = object : ActionButtonWithText(this, presentation, place, JBUI.size(18)) { override fun iconTextSpace() = JBUI.scale(2) override fun updateToolTipText() { val project = editor.project if (Registry.`is`("ide.helptooltip.enabled") && project != null) { HelpTooltip.dispose(this) HelpTooltip() .setTitle(myPresentation.description) .setDescription(LangBundle.message("action.ReaderModeProvider.description")) .setLink(LangBundle.message("action.ReaderModeProvider.link.configure")) { ShowSettingsUtil.getInstance().showSettingsDialog(project, ReaderModeConfigurable::class.java) } .installOn(this) } else { toolTipText = myPresentation.description } } override fun getInsets(): Insets = JBUI.insets(2) override fun getMargins(): Insets = if (myPresentation.icon == AllIcons.General.ReaderMode) JBUI.emptyInsets() else JBUI.insetsRight(5) override fun updateUI() { super.updateUI() if (!SystemInfo.isWindows) { font = FontUIResource(font.deriveFont(font.style, font.size - JBUIScale.scale(2).toFloat())) } } }.also { it.foreground = JBColor(NotNullProducer { editor.colorsScheme.getColor(FOREGROUND) ?: FOREGROUND.defaultColor }) if (!SystemInfo.isWindows) { it.font = FontUIResource(it.font.deriveFont(it.font.style, it.font.size - JBUIScale.scale(2).toFloat())) } editor.project?.let { p -> if (!ReaderModeSettings.instance(p).enabled || isNotificationSilentMode(p)) return@let val connection = p.messageBus.connect(p) val gotItTooltip = GotItTooltip("reader.mode.got.it", LangBundle.message("text.reader.mode.got.it.popup"), p) .withHeader(LangBundle.message("title.reader.mode.got.it.popup")) if (gotItTooltip.canShow()) { connection.subscribe(DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC, object : DaemonCodeAnalyzer.DaemonListener { override fun daemonFinished(fileEditors: Collection<FileEditor>) { fileEditors.find { fe -> (fe is TextEditor) && editor == fe.editor }?.let { _ -> gotItTooltip.setOnBalloonCreated { balloon -> balloon.addListener(object: JBPopupListener { override fun onClosed(event: LightweightWindowEvent) { connection.disconnect() } })}. show(it, GotItTooltip.BOTTOM_MIDDLE) } } }) } } } override fun isSelected(e: AnActionEvent): Boolean { return true } override fun setSelected(e: AnActionEvent, state: Boolean) { val project = e.project ?: return ReaderModeSettings.instance(project).enabled = !ReaderModeSettings.instance(project).enabled project.messageBus.syncPublisher(ReaderModeSettingsListener.TOPIC).modeChanged(project) } override fun update(e: AnActionEvent) { val project = editor.project ?: return val presentation = e.presentation if (!ReaderModeSettings.instance(project).enabled) { presentation.text = null presentation.icon = AllIcons.General.ReaderMode presentation.hoveredIcon = null presentation.description = LangBundle.message("action.ReaderModeProvider.text.enter") } else { presentation.text = LangBundle.message("action.ReaderModeProvider.text") presentation.icon = EmptyIcon.ICON_16 presentation.hoveredIcon = AllIcons.Actions.CloseDarkGrey presentation.description = LangBundle.message("action.ReaderModeProvider.text.exit") } } } companion object { val FOREGROUND = ColorKey.createColorKey("ActionButton.iconTextForeground", UIUtil.getContextHelpForeground()) } }
apache-2.0
debb1eeda38569c5c7d7fb42e07f2c03
43.35443
140
0.696161
4.879526
false
false
false
false
zdary/intellij-community
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/HTMLFileEditor.kt
1
5605
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.fileEditor.impl import com.intellij.CommonBundle import com.intellij.ide.BrowserUtil import com.intellij.ide.IdeBundle import com.intellij.ide.plugins.MultiPanel import com.intellij.openapi.application.invokeLater import com.intellij.openapi.editor.EditorBundle import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorLocation import com.intellij.openapi.fileEditor.FileEditorState import com.intellij.openapi.project.Project import com.intellij.openapi.util.ActionCallback import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.UserDataHolderBase import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.StatusBar import com.intellij.testFramework.LightVirtualFile import com.intellij.ui.components.JBLoadingPanel import com.intellij.ui.jcef.JBCefBrowserBase.ErrorPage import com.intellij.ui.jcef.JCEFHtmlPanel import com.intellij.util.Alarm import com.intellij.util.AlarmFactory import com.intellij.util.ui.UIUtil import org.cef.browser.CefBrowser import org.cef.browser.CefFrame import org.cef.handler.* import org.cef.network.CefRequest import java.awt.BorderLayout import java.beans.PropertyChangeListener import java.util.concurrent.atomic.AtomicBoolean import javax.swing.JComponent internal class HTMLFileEditor(private val project: Project, private val file: LightVirtualFile, url: String) : UserDataHolderBase(), FileEditor { private val loadingPanel = JBLoadingPanel(BorderLayout(), this) private val contentPanel = JCEFHtmlPanel(null) private val alarm = AlarmFactory.getInstance().create(Alarm.ThreadToUse.SWING_THREAD, this) private val initial = AtomicBoolean(true) private val navigating = AtomicBoolean(false) private val multiPanel = object : MultiPanel() { override fun create(key: Int): JComponent = when (key) { LOADING_KEY -> loadingPanel CONTENT_KEY -> contentPanel.component else -> throw IllegalArgumentException("Unknown key: ${key}") } override fun select(key: Int, now: Boolean): ActionCallback { val callback = super.select(key, now) if (key == CONTENT_KEY) { UIUtil.invokeLaterIfNeeded { contentPanel.component.requestFocusInWindow() } } return callback } } init { loadingPanel.setLoadingText(CommonBundle.getLoadingTreeNodeText()) contentPanel.jbCefClient.addLoadHandler(object : CefLoadHandlerAdapter() { override fun onLoadingStateChange(browser: CefBrowser, isLoading: Boolean, canGoBack: Boolean, canGoForward: Boolean) { if (initial.get()) { if (isLoading) { invokeLater { loadingPanel.startLoading() multiPanel.select(LOADING_KEY, true) } } else { alarm.cancelAllRequests() initial.set(false) invokeLater { loadingPanel.stopLoading() multiPanel.select(CONTENT_KEY, true) } } } } }, contentPanel.cefBrowser) contentPanel.jbCefClient.addRequestHandler(object : CefRequestHandlerAdapter() { override fun onBeforeBrowse(browser: CefBrowser, frame: CefFrame, request: CefRequest, userGesture: Boolean, isRedirect: Boolean): Boolean = if (userGesture) { navigating.set(true); BrowserUtil.browse(request.url); true } else false }, contentPanel.cefBrowser) contentPanel.jbCefClient.addLifeSpanHandler(object : CefLifeSpanHandlerAdapter() { override fun onBeforePopup(browser: CefBrowser, frame: CefFrame, targetUrl: String, targetFrameName: String?): Boolean { BrowserUtil.browse(targetUrl) return true } }, contentPanel.cefBrowser) contentPanel.jbCefClient.addDisplayHandler(object : CefDisplayHandlerAdapter() { override fun onStatusMessage(browser: CefBrowser, text: @NlsSafe String) = StatusBar.Info.set(text, project) }, contentPanel.cefBrowser) contentPanel.setErrorPage { errorCode, errorText, failedUrl -> if (errorCode == CefLoadHandler.ErrorCode.ERR_ABORTED && navigating.getAndSet(false)) null else ErrorPage.DEFAULT.create(errorCode, errorText, failedUrl) } multiPanel.select(CONTENT_KEY, true) if (url.isNotEmpty()) { if (file.content.isEmpty()) { file.setContent(this, EditorBundle.message("message.html.editor.timeout"), false) } alarm.addRequest({ contentPanel.loadHTML(file.content.toString()) }, Registry.intValue("html.editor.timeout", 10000)) contentPanel.loadURL(url) } else { contentPanel.loadHTML(file.content.toString()) } } override fun getComponent(): JComponent = multiPanel override fun getPreferredFocusedComponent(): JComponent = multiPanel override fun getName(): String = IdeBundle.message("tab.title.html.preview") override fun setState(state: FileEditorState) { } override fun isModified(): Boolean = false override fun isValid(): Boolean = true override fun addPropertyChangeListener(listener: PropertyChangeListener) { } override fun removePropertyChangeListener(listener: PropertyChangeListener) { } override fun getCurrentLocation(): FileEditorLocation? = null override fun dispose() { } override fun getFile(): VirtualFile = file private companion object { private const val LOADING_KEY = 1 private const val CONTENT_KEY = 0 } }
apache-2.0
2976b4757cf1fdd1018b579881a50000
39.912409
146
0.738983
4.586743
false
false
false
false
leafclick/intellij-community
python/src/com/jetbrains/extenstions/QualifiedNameExt.kt
1
7590
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.extenstions import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiManager import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.QualifiedName import com.jetbrains.extensions.getSdk import com.jetbrains.python.PyNames import com.jetbrains.python.psi.PyClass import com.jetbrains.python.psi.PyFile import com.jetbrains.python.psi.resolve.* import com.jetbrains.python.psi.stubs.PyModuleNameIndex import com.jetbrains.python.psi.types.TypeEvalContext import com.jetbrains.python.sdk.PythonSdkType import org.jetbrains.annotations.ApiStatus //TODO: move to extensions /** * @deprecated use [com.jetbrains.extensions] */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated("Use com.jetbrains.extensions") interface ContextAnchor { val sdk: Sdk? val project: Project val qualifiedNameResolveContext: PyQualifiedNameResolveContext? val scope: GlobalSearchScope fun getRoots(): Array<VirtualFile> { return sdk?.rootProvider?.getFiles(OrderRootType.CLASSES) ?: emptyArray() } } /** * @deprecated use [com.jetbrains.extensions] */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated("Use com.jetbrains.extensions") class ModuleBasedContextAnchor(val module: Module) : ContextAnchor { override val sdk: Sdk? = module.getSdk() override val project: Project = module.project override val qualifiedNameResolveContext: PyQualifiedNameResolveContext = fromModule(module) override val scope: GlobalSearchScope = module.moduleContentScope override fun getRoots(): Array<VirtualFile> { val manager = ModuleRootManager.getInstance(module) return super.getRoots() + manager.contentRoots + manager.sourceRoots } } /** * @deprecated use [com.jetbrains.extensions] */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated("Use com.jetbrains.extensions") class ProjectSdkContextAnchor(override val project: Project, override val sdk: Sdk?) : ContextAnchor { override val qualifiedNameResolveContext: PyQualifiedNameResolveContext? = sdk?.let { fromSdk(project, it) } override val scope: GlobalSearchScope = GlobalSearchScope.projectScope(project) //TODO: Check if project scope includes SDK override fun getRoots(): Array<VirtualFile> { val manager = ProjectRootManager.getInstance(project) return super.getRoots() + manager.contentRoots + manager.contentSourceRoots } } /** * @deprecated use [com.jetbrains.extensions] */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated("Use com.jetbrains.extensions") data class QNameResolveContext( val contextAnchor: ContextAnchor, /** * Used for language level etc */ val sdk: Sdk? = contextAnchor.sdk, val evalContext: TypeEvalContext, /** * If not provided resolves against roots only. Resolved also against this folder otherwise */ val folderToStart: VirtualFile? = null, /** * Use index, plain dirs with Py2 and so on. May resolve names unresolvable in other cases, but may return false results. */ val allowInaccurateResult: Boolean = false ) /** * @deprecated use [com.jetbrains.extensions] */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated("Use com.jetbrains.extensions") fun QualifiedName.getRelativeNameTo(root: QualifiedName): QualifiedName? { if (!toString().startsWith(root.toString())) { return null } return subQualifiedName(root.componentCount, componentCount) } /** * @deprecated use [com.jetbrains.extensions] */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated("Use com.jetbrains.extensions") fun QualifiedName.resolveToElement(context: QNameResolveContext, stopOnFirstFail: Boolean = false): PsiElement? { return getElementAndResolvableName(context, stopOnFirstFail)?.element } /** * @deprecated use [com.jetbrains.extensions] */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated("Use com.jetbrains.extensions") data class NameAndElement(val name: QualifiedName, val element: PsiElement) /** * @deprecated use [com.jetbrains.extensions] */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated("Use com.jetbrains.extensions") fun QualifiedName.getElementAndResolvableName(context: QNameResolveContext, stopOnFirstFail: Boolean = false): NameAndElement? { var currentName = QualifiedName.fromComponents(this.components) var element: PsiElement? = null var lastElement: String? = null var psiDirectory: PsiDirectory? = null var resolveContext = context.contextAnchor.qualifiedNameResolveContext?.copyWithMembers() ?: return null if (PythonSdkType.getLanguageLevelForSdk(context.sdk).isPy3K || context.allowInaccurateResult) { resolveContext = resolveContext.copyWithPlainDirectories() } if (context.folderToStart != null) { psiDirectory = PsiManager.getInstance(context.contextAnchor.project).findDirectory(context.folderToStart) } // Drill as deep, as we can while (currentName.componentCount > 0 && element == null) { if (psiDirectory != null) { // Resolve against folder // There could be folder and module on the same level. Empty folder should be ignored in this case. element = resolveModuleAt(currentName, psiDirectory, resolveContext).filterNot { it is PsiDirectory && it.children.filterIsInstance<PyFile>().isEmpty() }.firstOrNull() } if (element == null) { // Resolve against roots element = resolveQualifiedName(currentName, resolveContext).firstOrNull() } if (element != null || stopOnFirstFail) { break } lastElement = currentName.lastComponent!! currentName = currentName.removeLastComponent() } if (lastElement != null && element is PyClass) { // Drill in class //TODO: Support nested classes val method = element.findMethodByName(lastElement, true, context.evalContext) if (method != null) { return NameAndElement(currentName.append(lastElement), method) } } if (element == null && this.firstComponent != null && context.allowInaccurateResult) { // If name starts with file which is not in root nor in folders -- use index. val nameToFind = this.firstComponent!! val pyFile = PyModuleNameIndex.find(nameToFind, context.contextAnchor.project, false).firstOrNull() ?: return element val folder = if (pyFile.name == PyNames.INIT_DOT_PY) { // We are in folder pyFile.virtualFile.parent.parent } else { pyFile.virtualFile.parent } return getElementAndResolvableName(context.copy(folderToStart = folder)) } return if (element != null) NameAndElement(currentName, element) else null }
apache-2.0
951443268d9eb1f3b0375738cf2c38f3
36.389163
128
0.757049
4.512485
false
false
false
false
nobuoka/vc-oauth-java
ktor-twitter-login/src/test/kotlin/info/vividcode/ktor/twitter/login/RoutingTest.kt
1
4093
package info.vividcode.ktor.twitter.login import info.vividcode.ktor.twitter.login.application.TemporaryCredentialNotFoundException import info.vividcode.ktor.twitter.login.application.TestServerTwitter import info.vividcode.ktor.twitter.login.application.TwitterCallFailedException import info.vividcode.ktor.twitter.login.application.responseBuilder import info.vividcode.ktor.twitter.login.test.TestCallFactory import info.vividcode.ktor.twitter.login.test.TestTemporaryCredentialStore import info.vividcode.oauth.OAuth import io.ktor.application.Application import io.ktor.application.call import io.ktor.http.HttpMethod import io.ktor.http.HttpStatusCode import io.ktor.response.respondText import io.ktor.routing.routing import io.ktor.server.testing.handleRequest import io.ktor.server.testing.withTestApplication import kotlinx.coroutines.newSingleThreadContext import okhttp3.Call import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.ResponseBody.Companion.toResponseBody import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import java.time.Clock import java.time.Instant import java.time.ZoneId import kotlin.coroutines.CoroutineContext internal class RoutingTest { private val testServer = TestServerTwitter() private val testTemporaryCredentialStore = TestTemporaryCredentialStore() private val testEnv = object : Env { override val oauth: OAuth = OAuth(object : OAuth.Env { override val clock: Clock = Clock.fixed(Instant.parse("2015-01-01T00:00:00Z"), ZoneId.systemDefault()) override val nextInt: (Int) -> Int = { (it - 1) / 2 } }) override val httpClient: Call.Factory = TestCallFactory(testServer) override val httpCallContext: CoroutineContext = newSingleThreadContext("TestHttpCall") override val temporaryCredentialStore: TemporaryCredentialStore = testTemporaryCredentialStore } private val outputPort = object : OutputPort { override val success: OutputInterceptor<TwitterToken> = { call.respondText("test success") } override val twitterCallFailed: OutputInterceptor<TwitterCallFailedException> = { call.respondText("test twitter call failed") } override val temporaryCredentialNotFound: OutputInterceptor<TemporaryCredentialNotFoundException> = { call.respondText("test temporary credential not found (identifier : ${it.temporaryCredentialIdentifier})") } } private val testableModule: Application.() -> Unit = { routing { setupTwitterLogin("/start", "/callback", "http://example.com", ClientCredential("test-identifier", "test-secret"), testEnv, outputPort) } } @Test fun testRequest() = withTestApplication(testableModule) { testServer.responseBuilders.add(responseBuilder { code(200).message("OK") body( "oauth_token=test-temporary-token&oauth_token_secret=test-token-secret" .toResponseBody("application/x-www-form-urlencoded".toMediaTypeOrNull()) ) }) handleRequest(HttpMethod.Post, "/start").run { assertEquals(HttpStatusCode.Found, response.status()) assertEquals( "https://api.twitter.com/oauth/authenticate?oauth_token=test-temporary-token", response.headers["Location"] ) } testServer.responseBuilders.add(responseBuilder { code(200).message("OK") body( "oauth_token=test-access-token&oauth_token_secret=test-token-secret&user_id=101&screen_name=foo" .toResponseBody("application/x-www-form-urlencoded".toMediaTypeOrNull()) ) }) handleRequest(HttpMethod.Get, "/callback?oauth_token=test-temporary-token&verifier=test-verifier").run { assertEquals(HttpStatusCode.OK, response.status()) assertEquals("test success", response.content) } } }
apache-2.0
a7c5b5ac5a3c9f9563c6374c104eea39
42.084211
118
0.705839
4.737269
false
true
false
false
leafclick/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/inference/driver/closure/ClosureDriver.kt
1
8540
// 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 org.jetbrains.plugins.groovy.intentions.style.inference.driver.closure import com.intellij.psi.* import com.intellij.psi.impl.source.resolve.graphInference.constraints.ConstraintFormula import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.parentOfType import org.jetbrains.plugins.groovy.intentions.style.inference.NameGenerator import org.jetbrains.plugins.groovy.intentions.style.inference.SignatureInferenceOptions import org.jetbrains.plugins.groovy.intentions.style.inference.driver.* import org.jetbrains.plugins.groovy.intentions.style.inference.driver.BoundConstraint.ContainMarker.INHABIT import org.jetbrains.plugins.groovy.intentions.style.inference.driver.BoundConstraint.ContainMarker.UPPER import org.jetbrains.plugins.groovy.intentions.style.inference.forceWildcardsAsTypeArguments import org.jetbrains.plugins.groovy.intentions.style.inference.isClosureTypeDeep import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import kotlin.LazyThreadSafetyMode.NONE class ClosureDriver private constructor(private val closureParameters: Map<GrParameter, ParameterizedClosure>, private val method: GrMethod, private val options: SignatureInferenceOptions) : InferenceDriver { companion object { fun createFromMethod(method: GrMethod, virtualMethod: GrMethod, generator: NameGenerator, options: SignatureInferenceOptions): InferenceDriver { val builder = ClosureParametersStorageBuilder(generator, virtualMethod) val visitedParameters = builder.extractClosuresFromOuterCalls(method, virtualMethod, options.calls.value) virtualMethod.forEachParameterUsage { parameter, instructions -> if (!parameter.type.isClosureTypeDeep() || parameter in visitedParameters) { return@forEachParameterUsage } val callUsages = instructions.mapNotNull { it.element?.parentOfType<GrCall>() } if (!builder.extractClosuresFromCallInvocation(callUsages, parameter)) { builder.extractClosuresFromOtherMethodInvocations(callUsages, parameter) } } val closureParameters = builder.build() return if (closureParameters.isEmpty()) EmptyDriver else ClosureDriver(closureParameters, virtualMethod, options) } } private fun produceParameterizedClosure(parameterMapping: Map<GrParameter, GrParameter>, closureParameter: ParameterizedClosure, substitutor: PsiSubstitutor, manager: ParameterizationManager): ParameterizedClosure { val newParameter = parameterMapping.getValue(closureParameter.parameter) val newTypes = mutableListOf<PsiType>() val newTypeParameters = mutableListOf<PsiTypeParameter>() for (directInnerParameter in closureParameter.typeParameters) { val substitutedType = substitutor.substitute(directInnerParameter)?.forceWildcardsAsTypeArguments() val generifiedType = substitutedType ?: getJavaLangObject(closureParameter.parameter) val (createdType, createdTypeParameters) = manager.createDeeplyParameterizedType(generifiedType) newTypes.add(createdType) newTypeParameters.addAll(createdTypeParameters) } return ParameterizedClosure(newParameter, newTypeParameters, closureParameter.closureArguments, newTypes) } override fun createParameterizedDriver(manager: ParameterizationManager, targetMethod: GrMethod, substitutor: PsiSubstitutor): InferenceDriver { val parameterMapping = setUpParameterMapping(method, targetMethod) val newClosureParameters = mutableMapOf<GrParameter, ParameterizedClosure>() val typeParameterList = targetMethod.typeParameterList ?: return EmptyDriver for ((_, closureParameter) in closureParameters) { val newClosureParameter = produceParameterizedClosure(parameterMapping, closureParameter, substitutor, manager) newClosureParameter.typeParameters.forEach { typeParameterList.add(it) } newClosureParameters[newClosureParameter.parameter] = newClosureParameter } return ClosureDriver(newClosureParameters, targetMethod, options) } override fun typeParameters(): Collection<PsiTypeParameter> { return closureParameters.flatMap { it.value.typeParameters } } override fun collectOuterConstraints(): Collection<ConstraintFormula> { val constraintCollector = mutableListOf<ConstraintFormula>() method.forEachParameterUsage { parameter, instructions -> if (parameter in closureParameters) { constraintCollector.addAll(extractConstraintsFromClosureInvocations(closureParameters.getValue(parameter), instructions)) } } return constraintCollector } private fun collectDeepClosureArgumentsConstraints(): List<TypeUsageInformation> { return closureParameters.values.flatMap { parameter -> parameter.closureArguments.map { closureBlock -> val newMethod = createMethodFromClosureBlock(closureBlock, parameter, method.typeParameterList!!) val emptyOptions = SignatureInferenceOptions(GlobalSearchScope.EMPTY_SCOPE, options.signatureInferenceContext, lazy(NONE) { emptyList<PsiReference>() }) val commonDriver = CommonDriver.createDirectlyFromMethod(newMethod, emptyOptions) val usageInformation = commonDriver.collectInnerConstraints() val typeParameterMapping = newMethod.typeParameters.zip(method.typeParameters).toMap() val shiftedRequiredTypes = usageInformation.requiredClassTypes.map { (param, list) -> typeParameterMapping.getValue(param) to list.map { if (it.marker == UPPER) BoundConstraint(it.type, INHABIT) else it } }.toMap() val newUsageInformation = usageInformation.run { TypeUsageInformation(shiftedRequiredTypes, constraints, dependentTypes.map { typeParameterMapping.getValue(it) }.toSet(), constrainingExpressions) } newUsageInformation } } } private fun collectClosureInvocationConstraints(): TypeUsageInformation { val builder = TypeUsageInformationBuilder(method, options.signatureInferenceContext) method.forEachParameterUsage { parameter, instructions -> if (parameter in closureParameters.keys) { analyzeClosureUsages(closureParameters.getValue(parameter), instructions, builder) } } return builder.build() } override fun collectInnerConstraints(): TypeUsageInformation { val closureBodyAnalysisResult = TypeUsageInformation.merge(collectDeepClosureArgumentsConstraints()) val closureInvocationConstraints = collectClosureInvocationConstraints() return closureInvocationConstraints + closureBodyAnalysisResult } override fun instantiate(resultMethod: GrMethod) { val mapping = setUpParameterMapping(method, resultMethod) for ((_, closureParameter) in closureParameters) { val createdAnnotations = closureParameter.renderTypes(method.parameterList) for ((parameter, anno) in createdAnnotations) { if (anno.isEmpty()) { continue } mapping.getValue(parameter).modifierList.addAnnotation(anno.substring(1)) } } } override fun acceptTypeVisitor(visitor: PsiTypeMapper, resultMethod: GrMethod): InferenceDriver { val mapping = setUpParameterMapping(method, resultMethod) val parameterizedClosureCollector = mutableListOf<Pair<GrParameter, ParameterizedClosure>>() for ((parameter, closure) in closureParameters) { val newTypes = closure.types.map { it.accept(visitor) } val newParameter = mapping.getValue(parameter) val newParameterizedClosure = ParameterizedClosure(newParameter, closure.typeParameters, closure.closureArguments, newTypes, closure.delegatesToCombiner) parameterizedClosureCollector.add(newParameter to newParameterizedClosure) } return ClosureDriver(parameterizedClosureCollector.toMap(), resultMethod, options) } }
apache-2.0
a61ebe0b34eaf016c4d824841db61e06
53.74359
159
0.746838
5.592665
false
false
false
false
kohesive/kohesive-iac
model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/cloudformation/resources/builders/Lambda.kt
1
4358
package uy.kohesive.iac.model.aws.cloudformation.resources.builders import com.amazonaws.AmazonWebServiceRequest import com.amazonaws.services.lambda.model.* import uy.kohesive.iac.model.aws.cloudformation.ResourcePropertiesBuilder import uy.kohesive.iac.model.aws.cloudformation.resources.Lambda class LambdaVersionResourcePropertiesBuilder : ResourcePropertiesBuilder<PublishVersionRequest> { override val requestClazz = PublishVersionRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as PublishVersionRequest).let { Lambda.Version( CodeSha256 = it.codeSha256, FunctionName = it.functionName, Description = it.description ) } } class LambdaPermissionResourcePropertiesBuilder : ResourcePropertiesBuilder<AddPermissionRequest> { override val requestClazz = AddPermissionRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as AddPermissionRequest).let { Lambda.Permission( Action = it.action, Principal = it.principal, FunctionName = it.functionName, SourceAccount = it.sourceAccount, SourceArn = it.sourceArn ) } } class LambdaAliasResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateAliasRequest> { override val requestClazz = CreateAliasRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as CreateAliasRequest).let { Lambda.Alias( Description = request.description, FunctionName = request.functionName, FunctionVersion = request.functionVersion, Name = request.name ) } } class LambdaEventSourceMappingResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateEventSourceMappingRequest> { override val requestClazz = CreateEventSourceMappingRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as CreateEventSourceMappingRequest).let { Lambda.EventSourceMapping( BatchSize = request.batchSize?.toString(), Enabled = request.enabled?.toString(), EventSourceArn = request.eventSourceArn, FunctionName = request.functionName, StartingPosition = request.startingPosition ) } } class LambdaFunctionResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateFunctionRequest> { override val requestClazz = CreateFunctionRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as CreateFunctionRequest).let { Lambda.Function( Code = request.code.let { Lambda.Function.CodeProperty( S3Key = it.s3Key, S3Bucket = it.s3Bucket, S3ObjectVersion = it.s3ObjectVersion, ZipFile = it.zipFile?.let { String(it.array()) } ) }, Description = request.description, Environment = request.environment?.let { Lambda.Function.EnvironmentProperty( Variables = it.variables ) }, FunctionName = request.functionName, Handler = request.handler, KmsKeyArn = request.kmsKeyArn, MemorySize = request.memorySize?.toString(), Role = request.role, Runtime = request.runtime, Timeout = request.timeout?.toString(), VpcConfig = request.vpcConfig?.let { Lambda.Function.VPCConfigProperty( SecurityGroupIds = it.securityGroupIds, SubnetIds = it.subnetIds ) } ) } }
mit
3c830e9de0d95bec31065329f0be69c1
37.910714
118
0.596374
5.953552
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/helpers/NotificationsManager.kt
1
4589
package com.habitrpg.android.habitica.helpers import android.content.Context import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.data.ApiClient import com.habitrpg.android.habitica.events.ShowAchievementDialog import com.habitrpg.android.habitica.events.ShowCheckinDialog import com.habitrpg.android.habitica.events.ShowSnackbarEvent import com.habitrpg.android.habitica.models.Notification import com.habitrpg.android.habitica.models.notifications.LoginIncentiveData import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.functions.Consumer import io.reactivex.subjects.BehaviorSubject import org.greenrobot.eventbus.EventBus import java.util.* class NotificationsManager (private val context: Context) { private val seenNotifications: MutableMap<String, Boolean> private var apiClient: ApiClient? = null private val notifications: BehaviorSubject<List<Notification>> private var lastNotificationHandling: Date? = null init { this.seenNotifications = HashMap() this.notifications = BehaviorSubject.create() } fun setNotifications(current: List<Notification>) { this.notifications.onNext(current) this.handlePopupNotifications(current) } fun getNotifications(): Flowable<List<Notification>> { return this.notifications .startWith(emptyList<Notification>()) .toFlowable(BackpressureStrategy.LATEST) } fun getNotification(id: String): Notification? { return this.notifications.value?.find { it.id == id } } fun setApiClient(apiClient: ApiClient?) { this.apiClient = apiClient } fun handlePopupNotifications(notifications: List<Notification>): Boolean? { val now = Date() if (now.time - (lastNotificationHandling?.time ?: 0) < 500) { return true } lastNotificationHandling = now notifications .filter { !this.seenNotifications.containsKey(it.id) } .map { val notificationDisplayed = when (it.type) { Notification.Type.LOGIN_INCENTIVE.type -> displayLoginIncentiveNotification(it) Notification.Type.ACHIEVEMENT_PARTY_UP.type -> displayAchievementNotification(it) Notification.Type.ACHIEVEMENT_PARTY_ON.type -> displayAchievementNotification(it) Notification.Type.ACHIEVEMENT_BEAST_MASTER.type -> displayAchievementNotification(it) Notification.Type.ACHIEVEMENT_MOUNT_MASTER.type -> displayAchievementNotification(it) Notification.Type.ACHIEVEMENT_TRIAD_BINGO.type -> displayAchievementNotification(it) Notification.Type.ACHIEVEMENT_GUILD_JOINED.type -> displayAchievementNotification(it) Notification.Type.ACHIEVEMENT_CHALLENGE_JOINED.type -> displayAchievementNotification(it) Notification.Type.ACHIEVEMENT_INVITED_FRIEND.type -> displayAchievementNotification(it) else -> false } if (notificationDisplayed == true) { this.seenNotifications[it.id] = true } } return true } fun displayLoginIncentiveNotification(notification: Notification): Boolean? { val notificationData = notification.data as? LoginIncentiveData val nextUnlockText = context.getString(R.string.nextPrizeUnlocks, notificationData?.nextRewardAt) if (notificationData?.rewardKey != null) { val event = ShowCheckinDialog(notification, nextUnlockText, notificationData.nextRewardAt ?: 0) EventBus.getDefault().post(event) } else { val event = ShowSnackbarEvent() event.title = notificationData?.message event.text = nextUnlockText event.type = HabiticaSnackbar.SnackbarDisplayType.BLUE EventBus.getDefault().post(event) if (apiClient != null) { apiClient?.readNotification(notification.id) ?.subscribe(Consumer {}, RxErrorHandler.handleEmptyError()) } } return true } private fun displayAchievementNotification(notification: Notification): Boolean { EventBus.getDefault().post(ShowAchievementDialog(notification.type ?: "", notification.id)) return true } }
gpl-3.0
8ad63c838e153980576c5d363b9daa11
41.88785
113
0.67226
5.329849
false
false
false
false
ReplayMod/ReplayMod
src/main/kotlin/com/replaymod/replay/gui/overlay/GuiReplayOverlayKt.kt
1
1287
package com.replaymod.replay.gui.overlay import com.replaymod.core.gui.utils.hiddenChildOf import com.replaymod.replay.gui.overlay.panels.UIHotkeyButtonsPanel import gg.essential.elementa.ElementaVersion import gg.essential.elementa.components.UIContainer import gg.essential.elementa.components.Window import gg.essential.elementa.constraints.ChildBasedMaxSizeConstraint import gg.essential.elementa.constraints.ChildBasedSizeConstraint import gg.essential.elementa.dsl.* class GuiReplayOverlayKt { val window = Window(ElementaVersion.V1, 60) val bottomLeftPanel by UIContainer().constrain { x = 6.pixels(alignOpposite = false) y = 6.pixels(alignOpposite = true) // Children will be next to each other width = ChildBasedSizeConstraint() height = ChildBasedMaxSizeConstraint() } childOf window val bottomRightPanel by UIContainer().constrain { x = 6.pixels(alignOpposite = true) y = 6.pixels(alignOpposite = true) // Children will be on top of each other width = ChildBasedMaxSizeConstraint() height = ChildBasedSizeConstraint() } childOf window val hotkeyButtonsPanel by UIHotkeyButtonsPanel().apply { toggleButton childOf bottomRightPanel } hiddenChildOf window }
gpl-3.0
d2cea5481992500b7eb915495b3084d6
36.852941
68
0.750583
4.5
false
false
false
false
siosio/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/KotlinShortNamesCache.kt
1
12928
// 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.caches import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiClass import com.intellij.psi.PsiField import com.intellij.psi.PsiMethod import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiShortNamesCache import com.intellij.psi.stubs.StubIndex import com.intellij.util.ArrayUtil import com.intellij.util.Processor import com.intellij.util.Processors import com.intellij.util.containers.ContainerUtil import com.intellij.util.indexing.IdFilter import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.asJava.defaultImplsChild import org.jetbrains.kotlin.asJava.finder.JavaElementFinder import org.jetbrains.kotlin.asJava.getAccessorLightMethods import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName import org.jetbrains.kotlin.idea.decompiler.builtIns.KotlinBuiltInFileType import org.jetbrains.kotlin.idea.stubindex.* import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.load.java.getPropertyNamesCandidatesByAccessorName import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtNamedFunction class KotlinShortNamesCache(private val project: Project) : PsiShortNamesCache() { companion object { private val LOG = Logger.getInstance(KotlinShortNamesCache::class.java) } //hacky way to avoid searches for Kotlin classes, when looking for Java (from Kotlin) val disableSearch: ThreadLocal<Boolean> = object : ThreadLocal<Boolean>() { override fun initialValue(): Boolean = false } //region Classes override fun processAllClassNames(processor: Processor<in String>): Boolean { if (disableSearch.get()) return true return KotlinClassShortNameIndex.getInstance().processAllKeys(project, processor) && KotlinFileFacadeShortNameIndex.INSTANCE.processAllKeys(project, processor) } override fun processAllClassNames(processor: Processor<in String>, scope: GlobalSearchScope, filter: IdFilter?): Boolean { if (disableSearch.get()) return true return processAllClassNames(processor) } /** * Return kotlin class names from project sources which should be visible from java. */ override fun getAllClassNames(): Array<String> { if (disableSearch.get()) return ArrayUtil.EMPTY_STRING_ARRAY return withArrayProcessor(ArrayUtil.EMPTY_STRING_ARRAY) { processor -> processAllClassNames(processor) } } override fun processClassesWithName( name: String, processor: Processor<in PsiClass>, scope: GlobalSearchScope, filter: IdFilter? ): Boolean { if (disableSearch.get()) return true val effectiveScope = kotlinDeclarationsVisibleFromJavaScope(scope) val fqNameProcessor = Processor<FqName> { fqName: FqName? -> if (fqName == null) return@Processor true val isInterfaceDefaultImpl = name == JvmAbi.DEFAULT_IMPLS_CLASS_NAME && fqName.shortName().asString() != name if (fqName.shortName().asString() != name && !isInterfaceDefaultImpl) { LOG.error( "A declaration obtained from index has non-matching name:" + "\nin index: $name" + "\ndeclared: ${fqName.shortName()}($fqName)" ) return@Processor true } val fqNameToSearch = if (isInterfaceDefaultImpl) fqName.defaultImplsChild() else fqName val psiClass = JavaElementFinder.getInstance(project).findClass(fqNameToSearch.asString(), effectiveScope) ?: return@Processor true return@Processor processor.process(psiClass) } val allKtClassOrObjectsProcessed = StubIndex.getInstance().processElements( KotlinClassShortNameIndex.getInstance().key, name, project, effectiveScope, filter, KtClassOrObject::class.java ) { ktClassOrObject -> fqNameProcessor.process(ktClassOrObject.fqName) } if (!allKtClassOrObjectsProcessed) { return false } return StubIndex.getInstance().processElements( KotlinFileFacadeShortNameIndex.getInstance().key, name, project, effectiveScope, filter, KtFile::class.java ) { ktFile -> fqNameProcessor.process(ktFile.javaFileFacadeFqName) } } /** * Return class names form kotlin sources in given scope which should be visible as Java classes. */ override fun getClassesByName(name: String, scope: GlobalSearchScope): Array<PsiClass> { if (disableSearch.get()) return PsiClass.EMPTY_ARRAY return withArrayProcessor(PsiClass.EMPTY_ARRAY) { processor -> processClassesWithName(name, processor, scope, null) } } private fun kotlinDeclarationsVisibleFromJavaScope(scope: GlobalSearchScope): GlobalSearchScope { val noBuiltInsScope: GlobalSearchScope = object : GlobalSearchScope(project) { override fun isSearchInModuleContent(aModule: Module) = true override fun compare(file1: VirtualFile, file2: VirtualFile) = 0 override fun isSearchInLibraries() = true override fun contains(file: VirtualFile) = file.fileType != KotlinBuiltInFileType } return KotlinSourceFilterScope.sourceAndClassFiles(scope, project).intersectWith(noBuiltInsScope) } //endregion //region Methods override fun processAllMethodNames( processor: Processor<in String>, scope: GlobalSearchScope, filter: IdFilter? ): Boolean { if (disableSearch.get()) return true return processAllMethodNames(processor) } override fun getAllMethodNames(): Array<String> { if (disableSearch.get()) ArrayUtil.EMPTY_STRING_ARRAY return withArrayProcessor(ArrayUtil.EMPTY_STRING_ARRAY) { processor -> processAllMethodNames(processor) } } private fun processAllMethodNames(processor: Processor<in String>): Boolean { if (disableSearch.get()) return true if (!KotlinFunctionShortNameIndex.getInstance().processAllKeys(project, processor)) { return false } return KotlinPropertyShortNameIndex.getInstance().processAllKeys(project) { name -> return@processAllKeys processor.process(JvmAbi.setterName(name)) && processor.process(JvmAbi.getterName(name)) } } override fun processMethodsWithName( name: String, processor: Processor<in PsiMethod>, scope: GlobalSearchScope, filter: IdFilter? ): Boolean { if (disableSearch.get()) return true val allFunctionsProcessed = StubIndex.getInstance().processElements( KotlinFunctionShortNameIndex.getInstance().key, name, project, scope, filter, KtNamedFunction::class.java ) { ktNamedFunction -> val methods = LightClassUtil.getLightClassMethodsByName(ktNamedFunction, name) return@processElements methods.all { method -> processor.process(method) } } if (!allFunctionsProcessed) { return false } for (propertyName in getPropertyNamesCandidatesByAccessorName(Name.identifier(name))) { val allProcessed = StubIndex.getInstance().processElements( KotlinPropertyShortNameIndex.getInstance().key, propertyName.asString(), project, scope, filter, KtNamedDeclaration::class.java ) { ktNamedDeclaration -> val methods: Sequence<PsiMethod> = ktNamedDeclaration.getAccessorLightMethods() .asSequence() .filter { it.name == name } return@processElements methods.all { method -> processor.process(method) } } if (!allProcessed) { return false } } return true } override fun getMethodsByName(name: String, scope: GlobalSearchScope): Array<PsiMethod> { if (disableSearch.get()) return PsiMethod.EMPTY_ARRAY return withArrayProcessor(PsiMethod.EMPTY_ARRAY) { processor -> processMethodsWithName(name, processor, scope, null) } } override fun getMethodsByNameIfNotMoreThan(name: String, scope: GlobalSearchScope, maxCount: Int): Array<PsiMethod> { if (disableSearch.get()) return PsiMethod.EMPTY_ARRAY require(maxCount >= 0) return withArrayProcessor(PsiMethod.EMPTY_ARRAY) { processor -> processMethodsWithName( name, { psiMethod -> processor.size != maxCount && processor.process(psiMethod) }, scope, null ) } } override fun processMethodsWithName( name: String, scope: GlobalSearchScope, processor: Processor<in PsiMethod> ): Boolean { if (disableSearch.get()) return true return ContainerUtil.process(getMethodsByName(name, scope), processor) } //endregion //region Fields override fun processAllFieldNames(processor: Processor<in String>, scope: GlobalSearchScope, filter: IdFilter?): Boolean { if (disableSearch.get()) return true return processAllFieldNames(processor) } override fun getAllFieldNames(): Array<String> { if (disableSearch.get()) return ArrayUtil.EMPTY_STRING_ARRAY return withArrayProcessor(ArrayUtil.EMPTY_STRING_ARRAY) { processor -> processAllFieldNames(processor) } } private fun processAllFieldNames(processor: Processor<in String>): Boolean { if (disableSearch.get()) return true return KotlinPropertyShortNameIndex.getInstance().processAllKeys(project, processor) } override fun processFieldsWithName( name: String, processor: Processor<in PsiField>, scope: GlobalSearchScope, filter: IdFilter? ): Boolean { if (disableSearch.get()) return true return StubIndex.getInstance().processElements( KotlinPropertyShortNameIndex.getInstance().key, name, project, scope, filter, KtNamedDeclaration::class.java ) { ktNamedDeclaration -> val field = LightClassUtil.getLightClassBackingField(ktNamedDeclaration) ?: return@processElements true return@processElements processor.process(field) } } override fun getFieldsByName(name: String, scope: GlobalSearchScope): Array<PsiField> { if (disableSearch.get()) return PsiField.EMPTY_ARRAY return withArrayProcessor(PsiField.EMPTY_ARRAY) { processor -> processFieldsWithName(name, processor, scope, null) } } override fun getFieldsByNameIfNotMoreThan(name: String, scope: GlobalSearchScope, maxCount: Int): Array<PsiField> { if (disableSearch.get()) return PsiField.EMPTY_ARRAY require(maxCount >= 0) return withArrayProcessor(PsiField.EMPTY_ARRAY) { processor -> processFieldsWithName( name, { psiField -> processor.size != maxCount && processor.process(psiField) }, scope, null ) } } //endregion private inline fun <T> withArrayProcessor( result: Array<T>, process: (CancelableArrayCollectProcessor<T>) -> Unit ): Array<T> { return CancelableArrayCollectProcessor<T>().also { processor -> process(processor) }.toArray(result) } private class CancelableArrayCollectProcessor<T> : Processor<T> { private val set = HashSet<T>() private val processor = Processors.cancelableCollectProcessor<T>(set) override fun process(value: T): Boolean { return processor.process(value) } val size: Int get() = set.size fun toArray(a: Array<T>): Array<T> = set.toArray(a) } }
apache-2.0
edd1ab542423c5414d0b8bdc7a93ee1e
36.581395
158
0.652305
5.346567
false
false
false
false
firebase/friendlyeats-android
app/src/main/java/com/google/firebase/example/fireeats/RatingDialogFragment.kt
1
2213
package com.google.firebase.example.fireeats import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import com.google.firebase.auth.ktx.auth import com.google.firebase.example.fireeats.databinding.DialogRatingBinding import com.google.firebase.example.fireeats.model.Rating import com.google.firebase.ktx.Firebase /** * Dialog Fragment containing rating form. */ class RatingDialogFragment : DialogFragment() { private var _binding: DialogRatingBinding? = null private val binding get() = _binding!! private var ratingListener: RatingListener? = null internal interface RatingListener { fun onRating(rating: Rating) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = DialogRatingBinding.inflate(inflater, container, false) binding.restaurantFormButton.setOnClickListener { onSubmitClicked() } binding.restaurantFormCancel.setOnClickListener { onCancelClicked() } return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onAttach(context: Context) { super.onAttach(context) if (parentFragment is RatingListener) { ratingListener = parentFragment as RatingListener } } override fun onResume() { super.onResume() dialog?.window?.setLayout( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } private fun onSubmitClicked() { val user = Firebase.auth.currentUser user?.let { val rating = Rating( it, binding.restaurantFormRating.rating.toDouble(), binding.restaurantFormText.text.toString()) ratingListener?.onRating(rating) } dismiss() } private fun onCancelClicked() { dismiss() } companion object { const val TAG = "RatingDialog" } }
apache-2.0
d8ca9ee7a7999cbac910662133d1d616
25.662651
77
0.663805
4.973034
false
false
false
false
yschimke/okhttp
okhttp/src/jvmMain/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinder.kt
1
5093
/* * Copyright (C) 2022 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 okhttp3.internal.connection import java.io.IOException import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.LinkedBlockingDeque import java.util.concurrent.TimeUnit import okhttp3.internal.concurrent.Task import okhttp3.internal.concurrent.TaskRunner import okhttp3.internal.connection.RoutePlanner.ConnectResult import okhttp3.internal.connection.RoutePlanner.Plan import okhttp3.internal.okHttpName /** * Speculatively connects to each IP address of a target address, returning as soon as one of them * connects successfully. This kicks off new attempts every 250 ms until a connect succeeds. */ internal class FastFallbackExchangeFinder( private val routePlanner: RoutePlanner, private val taskRunner: TaskRunner, ) { private val connectDelayMillis = 250L /** Plans currently being connected, and that will later be added to [connectResults]. */ private var connectsInFlight = CopyOnWriteArrayList<Plan>() /** * Results are posted here as they occur. The find job is done when either one plan completes * successfully or all plans fail. */ private val connectResults = taskRunner.backend.decorate(LinkedBlockingDeque<ConnectResult>()) /** Exceptions accumulate here. */ private var firstException: IOException? = null /** True until we've launched all the connects we'll ever launch. */ private var morePlansExist = true fun find(): RealConnection { try { while (morePlansExist || connectsInFlight.isNotEmpty()) { if (routePlanner.isCanceled()) throw IOException("Canceled") launchConnect() val connection = awaitConnection() if (connection != null) return connection morePlansExist = morePlansExist && routePlanner.hasMoreRoutes() } throw firstException!! } finally { for (plan in connectsInFlight) { plan.cancel() } } } private fun launchConnect() { if (!morePlansExist) return val plan = try { routePlanner.plan() } catch (e: IOException) { trackFailure(e) return } connectsInFlight += plan // Already connected? Enqueue the result immediately. if (plan.isConnected) { connectResults.put(ConnectResult(plan)) return } // Connect asynchronously. val taskName = "$okHttpName connect ${routePlanner.address.url.redact()}" taskRunner.newQueue().schedule(object : Task(taskName) { override fun runOnce(): Long { val connectResult = try { connectAndDoRetries() } catch (e: Throwable) { ConnectResult(plan, throwable = e) } connectResults.put(connectResult) return -1L } private fun connectAndDoRetries(): ConnectResult { var firstException: Throwable? = null var currentPlan = plan while (true) { val connectResult = currentPlan.connect() if (connectResult.throwable == null) { if (connectResult.nextPlan == null) return connectResult // Success. } else { if (firstException == null) { firstException = connectResult.throwable } else { firstException.addSuppressed(connectResult.throwable) } // Fail if there's no next plan, or if this failure exception is not recoverable. if (connectResult.nextPlan == null || connectResult.throwable !is IOException) break } // Replace the currently-running plan with its successor. connectsInFlight.add(connectResult.nextPlan) connectsInFlight.remove(currentPlan) currentPlan = connectResult.nextPlan } return ConnectResult(currentPlan, throwable = firstException) } }) } private fun awaitConnection(): RealConnection? { if (connectsInFlight.isEmpty()) return null val completed = connectResults.poll(connectDelayMillis, TimeUnit.MILLISECONDS) ?: return null connectsInFlight.remove(completed.plan) val exception = completed.throwable if (exception is IOException) { trackFailure(exception) return null } else if (exception != null) { throw exception } return completed.plan.handleSuccess() } private fun trackFailure(exception: IOException) { routePlanner.trackFailure(exception) if (firstException == null) { firstException = exception } else { firstException!!.addSuppressed(exception) } } }
apache-2.0
753472c7560b3c0acd59b79b39b0166f
30.438272
98
0.68604
4.873684
false
false
false
false
pokk/SSFM
app/src/main/kotlin/taiwan/no1/app/ssfm/features/search/RecyclerViewSearchArtistChartViewModel.kt
1
3820
package taiwan.no1.app.ssfm.features.search import android.databinding.ObservableField import android.graphics.Bitmap import android.view.View import com.devrapid.kotlinknifer.formatToMoneyKarma import com.devrapid.kotlinknifer.glideListener import com.devrapid.kotlinknifer.palette import com.hwangjr.rxbus.RxBus import taiwan.no1.app.ssfm.R import taiwan.no1.app.ssfm.features.base.BaseViewModel import taiwan.no1.app.ssfm.features.chart.ChartArtistDetailFragment import taiwan.no1.app.ssfm.misc.constants.Constant.RXBUS_PARAMETER_FRAGMENT import taiwan.no1.app.ssfm.misc.constants.Constant.RXBUS_PARAMETER_FRAGMENT_NEEDBACK import taiwan.no1.app.ssfm.misc.constants.Constant.VIEWMODEL_PARAMS_FOG_COLOR import taiwan.no1.app.ssfm.misc.constants.Constant.VIEWMODEL_PARAMS_IMAGE_URL import taiwan.no1.app.ssfm.misc.constants.Constant.VIEWMODEL_PARAMS_KEYWORD import taiwan.no1.app.ssfm.misc.constants.ImageSizes.EXTRA_LARGE import taiwan.no1.app.ssfm.misc.constants.RxBusTag import taiwan.no1.app.ssfm.misc.constants.RxBusTag.NAVIGATION_TO_FRAGMENT import taiwan.no1.app.ssfm.misc.extension.gAlphaIntColor import taiwan.no1.app.ssfm.misc.extension.gColor import taiwan.no1.app.ssfm.models.entities.lastfm.ArtistEntity import taiwan.no1.app.ssfm.models.entities.lastfm.BaseEntity import kotlin.properties.Delegates /** * * @author jieyi * @since 9/20/17 */ class RecyclerViewSearchArtistChartViewModel(private var artist: BaseEntity) : BaseViewModel() { val artistName by lazy { ObservableField<String>() } val playCount by lazy { ObservableField<String>() } val thumbnail by lazy { ObservableField<String>() } val imageCallback = glideListener<Bitmap> { onResourceReady = { resource, _, _, _, _ -> resource.palette(24).let { color = gAlphaIntColor(it.darkVibrantSwatch?.rgb ?: gColor(R.color.colorPrimaryDark), 0.65f) false } } } private var color by Delegates.notNull<Int>() init { refreshView() } fun setArtistItem(item: BaseEntity) { this.artist = item refreshView() } /** * A callback event for clicking a item to list track. * * @param view [android.widget.RelativeLayout] * * @event_to [taiwan.no1.app.ssfm.features.search.SearchViewModel.receiveClickHistoryEvent] * @event_to [taiwan.no1.app.ssfm.features.chart.ChartActivity.navigate] */ fun artistOnClick(view: View) { val (keyword, imageUrl) = (artist as ArtistEntity.Artist).let { val k = it.name.orEmpty() val u = it.images?.get(EXTRA_LARGE)?.text.orEmpty() k to u } // For `searching activity`. RxBus.get().post(RxBusTag.VIEWMODEL_CLICK_HISTORY, hashMapOf(VIEWMODEL_PARAMS_KEYWORD to keyword, VIEWMODEL_PARAMS_IMAGE_URL to imageUrl, VIEWMODEL_PARAMS_FOG_COLOR to color.toString())) // For `top chart activity`. (artist as ArtistEntity.Artist).let { RxBus.get().post(NAVIGATION_TO_FRAGMENT, hashMapOf(RXBUS_PARAMETER_FRAGMENT to ChartArtistDetailFragment.newInstance(it.mbid.orEmpty(), it.name.orEmpty()), RXBUS_PARAMETER_FRAGMENT_NEEDBACK to true)) } } private fun refreshView() { (artist as ArtistEntity.Artist).let { val count = (it.playCount?.toInt() ?: 0) / 1000 artistName.set(it.name) playCount.set("${count.toString().formatToMoneyKarma()}K") thumbnail.set(it.images?.get(EXTRA_LARGE)?.text.orEmpty()) } } }
apache-2.0
69bdca8689b3e4e3e5ab95ddbe6bfdea
40.075269
124
0.659162
4.12973
false
false
false
false
GunoH/intellij-community
platform/platform-api/src/com/intellij/openapi/observable/properties/AtomicBooleanProperty.kt
1
1684
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.observable.properties import com.intellij.openapi.Disposable import java.util.concurrent.atomic.AtomicReference /** * Atomic implementation of boolean property. */ @Suppress("DEPRECATION") class AtomicBooleanProperty( initial: Boolean ) : AbstractObservableBooleanProperty(), AtomicMutableBooleanProperty, BooleanProperty { private val value = AtomicReference(initial) override fun get(): Boolean = value.get() override fun set() = set(true) override fun reset() = set(false) override fun set(value: Boolean) { val oldValue = this.value.getAndSet(value) fireChangeEvents(oldValue, value) } override fun updateAndGet(update: (Boolean) -> Boolean): Boolean { var oldValue: Boolean? = null val newValue = value.updateAndGet { oldValue = it update(it) } fireChangeEvents(oldValue!!, newValue) return newValue } fun compareAndSet(expect: Boolean, update: Boolean): Boolean { val succeed = value.compareAndSet(expect, update) if (succeed) { fireChangeEvents(expect, update) } return succeed } //TODO: Remove with BooleanProperty override fun afterSet(listener: () -> Unit) = afterSet(null, listener) override fun afterSet(listener: () -> Unit, parentDisposable: Disposable) = afterSet(parentDisposable, listener) override fun afterReset(listener: () -> Unit) = afterReset(null, listener) override fun afterReset(listener: () -> Unit, parentDisposable: Disposable) = afterReset(parentDisposable, listener) }
apache-2.0
b5ea8b2163b7ad78d9680c26401f764d
30.792453
140
0.726841
4.514745
false
false
false
false
K0zka/kerub
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/share/nfs/ShareNfsFactoryTest.kt
2
3966
package com.github.kerubistan.kerub.planner.steps.storage.share.nfs import com.github.kerubistan.kerub.model.config.HostConfiguration import com.github.kerubistan.kerub.model.controller.config.ControllerConfig import com.github.kerubistan.kerub.model.controller.config.StorageTechnologiesConfig import com.github.kerubistan.kerub.model.dynamic.VirtualStorageDeviceDynamic import com.github.kerubistan.kerub.model.dynamic.VirtualStorageFsAllocation import com.github.kerubistan.kerub.model.io.VirtualDiskFormat import com.github.kerubistan.kerub.model.services.NfsDaemonService import com.github.kerubistan.kerub.model.services.NfsService import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.steps.AbstractFactoryVerifications import com.github.kerubistan.kerub.testDisk import com.github.kerubistan.kerub.testFsCapability import com.github.kerubistan.kerub.testHost import com.github.kerubistan.kerub.testHostCapabilities import io.github.kerubistan.kroki.size.MB import org.junit.Test import kotlin.test.assertTrue class ShareNfsFactoryTest : AbstractFactoryVerifications(ShareNfsFactory) { @Test fun produce() { assertTrue("when nfs disabled, no share steps") { ShareNfsFactory.produce( OperationalState.fromLists( hosts = listOf(testHost), hostCfgs = listOf( HostConfiguration( id = testHost.id, services = listOf(NfsDaemonService()) ) ), vStorage = listOf(), config = ControllerConfig( storageTechnologies = StorageTechnologiesConfig( nfsEnabled = false ) ) ) ).isEmpty() } assertTrue("when nfs enabled, produce steps") { ShareNfsFactory.produce( OperationalState.fromLists( hosts = listOf(testHost), hostCfgs = listOf( HostConfiguration( id = testHost.id, services = listOf(NfsDaemonService()) ) ), vStorage = listOf( testDisk ), vStorageDyns = listOf( VirtualStorageDeviceDynamic( id = testDisk.id, allocations = listOf( VirtualStorageFsAllocation( hostId = testHost.id, actualSize = 100.MB, mountPoint = "/kerub", fileName = "/kerub/${testDisk.id}.qcow2", type = VirtualDiskFormat.qcow2, capabilityId = testFsCapability.id ) ) ) ), config = ControllerConfig( storageTechnologies = StorageTechnologiesConfig( nfsEnabled = true ) ) ) ) == listOf(ShareNfs(host = testHost, directory = "/kerub")) } assertTrue("if it is already shared, do not share it again") { val host = testHost.copy( capabilities = testHostCapabilities.copy( storageCapabilities = listOf(testFsCapability) ) ) ShareNfsFactory.produce( OperationalState.fromLists( hosts = listOf(host), hostCfgs = listOf( HostConfiguration( id = host.id, services = listOf(NfsDaemonService(), NfsService("/kerub", write = true)) ) ), vStorage = listOf( testDisk ), vStorageDyns = listOf( VirtualStorageDeviceDynamic( id = testDisk.id, allocations = listOf( VirtualStorageFsAllocation( hostId = testHost.id, actualSize = 100.MB, mountPoint = testFsCapability.mountPoint, fileName = "${testFsCapability.mountPoint}/${testDisk.id}.qcow2", type = VirtualDiskFormat.qcow2, capabilityId = testFsCapability.id ) ) ) ), config = ControllerConfig( storageTechnologies = StorageTechnologiesConfig( nfsEnabled = true ) ) ) ).isEmpty() } } }
apache-2.0
6afc3639a323348a93a155010f093c7a
31.252033
84
0.635401
4.511945
false
true
false
false
vovagrechka/fucking-everything
phizdets/phizdetsc/src/com/google/gwt/dev/js/ScopeContext.kt
3
2483
/* * Copyright 2010-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 com.google.gwt.dev.js import org.jetbrains.kotlin.js.backend.ast.* import java.util.Stack class ScopeContext(scope: JsScope) { private val rootScope = generateSequence(scope) { it.parent }.first { it is JsRootScope } private val scopes = Stack<JsScope>() init { scopes.push(scope) } fun enterFunction(): JsFunction { val fn = JsFunction(currentScope, "<js function>") enterScope(fn.scope) return fn } fun exitFunction() { assert(currentScope is JsFunctionScope) exitScope() } fun enterCatch(ident: String): JsCatch { val jsCatch = JsCatch(currentScope, ident) enterScope(jsCatch.scope) return jsCatch } fun exitCatch() { assert(currentScope is JsCatchScope) exitScope() } fun enterLabel(ident: String): JsName = (currentScope as JsFunctionScope).enterLabel(ident) fun exitLabel() = (currentScope as JsFunctionScope).exitLabel() fun labelFor(ident: String): JsName? = (currentScope as JsFunctionScope).findLabel(ident) fun globalNameFor(ident: String): JsName = currentScope.findName(ident) ?: rootScope.declareName(ident) fun localNameFor(ident: String): JsName = currentScope.findOwnNameOrDeclare(ident) fun referenceFor(ident: String): JsNameRef = JsNameRef(ident) private fun enterScope(scope: JsScope) = scopes.push(scope) private fun exitScope() = scopes.pop() private val currentScope: JsScope get() = scopes.peek() } /** * Overrides JsFunctionScope declareName as it's mapped to declareFreshName */ private fun JsScope.findOwnNameOrDeclare(ident: String): JsName = when (this) { is JsFunctionScope -> declareNameUnsafe(ident) else -> declareName(ident) }
apache-2.0
5366d542d6474e97b2d01d9c57abb710
27.883721
93
0.670963
4.318261
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/tests/testData/compiler/asJava/ultraLightClasses/inheritance.kt
6
719
interface Intf { fun v(): Int } interface IntfWithProp : Intf { val x: Int } abstract class Base(p: Int) { open protected fun v(): Int? { } fun nv() { } abstract fun abs(): Int internal open val x: Int get() { } open var y = 1 open protected var z = 1 } class Derived(p: Int) : Base(p), IntfWithProp { override fun v() = unknown() override val x = 3 override fun abs() = 0 } abstract class AnotherDerived(override val x: Int, override val y: Int, override val z: Int) : Base(2) { final override fun v() { } abstract fun noReturn(s: String) abstract val abstractProp: Int } private class Private { override val overridesNothing: Boolean get() = false }
apache-2.0
3bc2f7859a66e93cde572e73cb77ddba
22.193548
104
0.62726
3.490291
false
false
false
false
GunoH/intellij-community
plugins/kotlin/injection/src/org/jetbrains/kotlin/idea/injection/KotlinLanguageInjectionPerformer.kt
2
1806
// 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.injection import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.lang.injection.MultiHostRegistrar import com.intellij.lang.injection.general.Injection import com.intellij.lang.injection.general.LanguageInjectionPerformer import com.intellij.psi.PsiElement import org.intellij.plugins.intelliLang.inject.InjectorUtils import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull class KotlinLanguageInjectionPerformer : LanguageInjectionPerformer { override fun isPrimary(): Boolean = true override fun performInjection(registrar: MultiHostRegistrar, injection: Injection, context: PsiElement): Boolean { if (context !is KtElement || !isSupportedElement(context)) return false val support = InjectorUtils.getActiveInjectionSupports() .firstIsInstanceOrNull<KotlinLanguageInjectionSupport>() ?: return false val language = InjectorUtils.getLanguageByString(injection.injectedLanguageId) ?: return false val file = context.containingKtFile val parts = transformToInjectionParts(injection, context) ?: return false if (parts.ranges.isEmpty()) return false InjectorUtils.registerInjection(language, file, parts.ranges, registrar) InjectorUtils.registerSupport(support, false, context, language) InjectorUtils.putInjectedFileUserData( context, language, InjectedLanguageManager.FRANKENSTEIN_INJECTION, if (parts.isUnparsable) java.lang.Boolean.TRUE else null ) return true } }
apache-2.0
6d2b12d1dae7171d100dcd4fd49aadb7
44.175
158
0.763566
5.130682
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/ui/KotlinSelectNestedClassRefactoringDialog.kt
3
5111
// 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.refactoring.move.moveDeclarations.ui import com.intellij.BundleBase import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.util.RadioUpDownListener import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtEnumEntry import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import java.awt.BorderLayout import javax.swing.* internal class KotlinSelectNestedClassRefactoringDialog private constructor( project: Project, private val nestedClass: KtClassOrObject, private val targetContainer: PsiElement? ) : DialogWrapper(project, true) { private val moveToUpperLevelButton = JRadioButton() private val moveMembersButton = JRadioButton() init { title = RefactoringBundle.message("select.refactoring.title") init() } override fun createNorthPanel() = JLabel(RefactoringBundle.message("what.would.you.like.to.do")) override fun getPreferredFocusedComponent() = moveToUpperLevelButton override fun getDimensionServiceKey(): String { return "#org.jetbrains.kotlin.idea.refactoring.move.moveTopLevelDeclarations.ui.KotlinSelectInnerOrMembersRefactoringDialog" } override fun createCenterPanel(): JComponent? { moveToUpperLevelButton.text = KotlinBundle.message("button.text.move.nested.class.0.to.upper.level", nestedClass.name.toString()) moveToUpperLevelButton.isSelected = true moveMembersButton.text = KotlinBundle.message("button.text.move.nested.class.0.to.another.class", nestedClass.name.toString()) ButtonGroup().apply { add(moveToUpperLevelButton) add(moveMembersButton) } RadioUpDownListener(moveToUpperLevelButton, moveMembersButton) return JPanel(BorderLayout()).apply { val box = Box.createVerticalBox().apply { add(Box.createVerticalStrut(5)) add(moveToUpperLevelButton) add(moveMembersButton) } add(box, BorderLayout.CENTER) } } fun getNextDialog(): DialogWrapper? { return when { moveToUpperLevelButton.isSelected -> MoveKotlinNestedClassesToUpperLevelDialog(nestedClass, targetContainer) moveMembersButton.isSelected -> MoveKotlinNestedClassesDialog(nestedClass, targetContainer) else -> null } } companion object { private fun MoveKotlinNestedClassesToUpperLevelDialog( nestedClass: KtClassOrObject, targetContainer: PsiElement? ): MoveKotlinNestedClassesToUpperLevelDialog? { val outerClass = nestedClass.containingClassOrObject ?: return null val newTarget = targetContainer ?: outerClass.containingClassOrObject ?: outerClass.containingFile.let { it.containingDirectory ?: it } return MoveKotlinNestedClassesToUpperLevelDialog(nestedClass.project, nestedClass, newTarget) } private fun MoveKotlinNestedClassesDialog( nestedClass: KtClassOrObject, targetContainer: PsiElement? ): MoveKotlinNestedClassesDialog { return MoveKotlinNestedClassesDialog( nestedClass.project, listOf(nestedClass), nestedClass.containingClassOrObject!!, targetContainer as? KtClassOrObject ?: nestedClass.containingClassOrObject!!, targetContainer as? PsiDirectory, null ) } fun chooseNestedClassRefactoring(nestedClass: KtClassOrObject, targetContainer: PsiElement?) { val project = nestedClass.project val dialog = when { targetContainer.isUpperLevelFor(nestedClass) -> MoveKotlinNestedClassesToUpperLevelDialog(nestedClass, targetContainer) nestedClass is KtEnumEntry -> return else -> { val selectionDialog = KotlinSelectNestedClassRefactoringDialog( project, nestedClass, targetContainer ) selectionDialog.show() if (selectionDialog.exitCode != OK_EXIT_CODE) return selectionDialog.getNextDialog() ?: return } } dialog?.show() } private fun PsiElement?.isUpperLevelFor(nestedClass: KtClassOrObject) = this != null && this !is KtClassOrObject && this !is PsiDirectory || nestedClass is KtClass && nestedClass.isInner() } }
apache-2.0
c6228752e9240db8df6bd1de1d77cb60
40.901639
158
0.671689
6.172705
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/openapi/keymap/impl/DefaultKeymapImpl.kt
10
1719
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.keymap.impl import com.intellij.configurationStore.SchemeDataHolder import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.actionSystem.MouseShortcut import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.options.SchemeState import com.intellij.openapi.util.SystemInfo import org.jdom.Element import java.awt.event.MouseEvent open class DefaultKeymapImpl(dataHolder: SchemeDataHolder<KeymapImpl>, private val defaultKeymapManager: DefaultKeymap, val plugin: PluginDescriptor) : KeymapImpl(dataHolder) { final override var canModify: Boolean get() = false set(_) { // ignore } override fun getSchemeState(): SchemeState = SchemeState.NON_PERSISTENT override fun getPresentableName() = DefaultKeymap.getInstance().getKeymapPresentableName(this) override fun readExternal(keymapElement: Element) { super.readExternal(keymapElement) if (KeymapManager.DEFAULT_IDEA_KEYMAP == name && !SystemInfo.isXWindow) { addShortcut(IdeActions.ACTION_GOTO_DECLARATION, MouseShortcut(MouseEvent.BUTTON2, 0, 1)) } } // default keymap can have parent only in the defaultKeymapManager // also, it allows us to avoid dependency on KeymapManager (maybe not initialized yet) override fun findParentScheme(parentSchemeName: String): Keymap? = defaultKeymapManager.findScheme(parentSchemeName) }
apache-2.0
cacf2b0c16cf947d30f0e396dd6282d4
43.076923
158
0.77196
4.968208
false
false
false
false
smmribeiro/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/EntityFamily.kt
3
5847
// 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.workspaceModel.storage.impl import com.intellij.openapi.diagnostic.thisLogger import com.intellij.workspaceModel.storage.WorkspaceEntity import it.unimi.dsi.fastutil.ints.IntOpenHashSet import it.unimi.dsi.fastutil.ints.IntSet internal class ImmutableEntityFamily<E : WorkspaceEntity>( override val entities: ArrayList<WorkspaceEntityData<E>?>, private val emptySlotsSize: Int ) : EntityFamily<E>() { constructor(): this(ArrayList(), 0) fun toMutable() = MutableEntityFamily(entities, true) override fun size(): Int = entities.size - emptySlotsSize override fun familyCheck() { val emptySlotsCounter = entities.count { it == null } assert(emptySlotsCounter == emptySlotsSize) { "EntityFamily has unregistered gaps" } } } internal class MutableEntityFamily<E : WorkspaceEntity>( override var entities: ArrayList<WorkspaceEntityData<E>?>, // if [freezed] is true, [entities] array MUST BE copied before modifying it. private var freezed: Boolean ) : EntityFamily<E>() { // This set contains empty slots at the moment of MutableEntityFamily creation // New empty slots MUST NOT be added this this set, otherwise it would be impossible to distinguish (remove + add) and (replace) events private val availableSlots: IntSet = IntOpenHashSet().also { entities.mapIndexed { index, pEntityData -> if (pEntityData == null) it.add(index) } } // Current amount of nulls in entities private var amountOfGapsInEntities = availableSlots.size // Indexes of entity data that are copied for modification. These entities can be safely modified. private val copiedToModify: IntSet = IntOpenHashSet() fun remove(id: Int) { if (availableSlots.contains(id)) { thisLogger().error("id $id is already removed") return } startWrite() copiedToModify.remove(id) entities[id] = null amountOfGapsInEntities++ } /** * This method adds entityData and changes it's id to the actual one */ fun add(other: WorkspaceEntityData<E>) { startWrite() if (availableSlots.isEmpty()) { other.id = entities.size entities.add(other) } else { val emptySlot = availableSlots.pop() other.id = emptySlot entities[emptySlot] = other amountOfGapsInEntities-- } copiedToModify.add(other.id) } fun book(): Int { startWrite() val bookedId = if (availableSlots.isEmpty()) { entities.add(null) amountOfGapsInEntities++ entities.lastIndex } else { val emptySlot = availableSlots.pop() entities[emptySlot] = null emptySlot } copiedToModify.add(bookedId) return bookedId } fun insertAtId(data: WorkspaceEntityData<E>) { startWrite() val prevValue = entities[data.id] entities[data.id] = data availableSlots.remove(data.id) if (prevValue == null) amountOfGapsInEntities-- copiedToModify.add(data.id) } fun replaceById(entity: WorkspaceEntityData<E>) { val id = entity.id if (entities[id] == null) { thisLogger().error("Nothing to replace. EntityData: $entity") return } startWrite() entities[id] = entity copiedToModify.add(id) } /** * Get entity data that can be modified in a save manne */ fun getEntityDataForModification(arrayId: Int): WorkspaceEntityData<E> { val entity = entities.getOrNull(arrayId) ?: error("Nothing to modify") if (arrayId in copiedToModify) return entity startWrite() val clonedEntity = entity.clone() entities[arrayId] = clonedEntity copiedToModify.add(arrayId) return clonedEntity } fun set(position: Int, value: WorkspaceEntityData<E>) { startWrite() entities[position] = value } fun toImmutable(): ImmutableEntityFamily<E> { freezed = true copiedToModify.clear() return ImmutableEntityFamily(entities, amountOfGapsInEntities) } override fun size(): Int = entities.size - amountOfGapsInEntities override fun familyCheck() {} internal fun isEmpty() = entities.size == amountOfGapsInEntities /** This method should always be called before any modification */ private fun startWrite() { if (!freezed) return entities = ArrayList(entities) freezed = false } private fun IntSet.pop(): Int { val iterator = this.iterator() if (!iterator.hasNext()) error("Set is empty") val res = iterator.nextInt() iterator.remove() return res } companion object { // Do not remove parameter. Kotlin fails with compilation without it @Suppress("RemoveExplicitTypeArguments") fun <T: WorkspaceEntity> createEmptyMutable() = MutableEntityFamily<T>(ArrayList(), false) } } internal sealed class EntityFamily<E : WorkspaceEntity> { internal abstract val entities: List<WorkspaceEntityData<E>?> operator fun get(idx: Int) = entities.getOrNull(idx) fun exists(id: Int) = get(id) != null fun all() = entities.asSequence().filterNotNull() abstract fun size(): Int override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is EntityFamily<*>) return false if (entities != other.entities) return false return true } override fun hashCode(): Int = entities.hashCode() override fun toString(): String { return "EntityFamily(entities=$entities)" } protected abstract fun familyCheck() inline fun assertConsistency(entityAssertion: (WorkspaceEntityData<E>) -> Unit = {}) { entities.forEachIndexed { idx, entity -> if (entity != null) { assert(idx == entity.id) { "Entity with id ${entity.id} is placed at index $idx" } entityAssertion(entity) } } familyCheck() } }
apache-2.0
d8491fcd9b7d2213dccc9b140d3d5e70
27.383495
140
0.693347
4.483896
false
false
false
false
seventhroot/elysium
bukkit/rpk-chat-lib-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/chatchannel/RPKChatChannel.kt
1
7926
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.chat.bukkit.chatchannel import com.rpkit.chat.bukkit.chatchannel.pipeline.DirectedChatChannelPipelineComponent import com.rpkit.chat.bukkit.chatchannel.pipeline.UndirectedChatChannelPipelineComponent import com.rpkit.core.database.Entity import com.rpkit.players.bukkit.player.RPKPlayer import com.rpkit.players.bukkit.profile.RPKMinecraftProfile import com.rpkit.players.bukkit.profile.RPKThinProfile import java.awt.Color /** * Represents a chat channel */ interface RPKChatChannel: Entity { /** * The name of the chat channel. */ val name: String /** * The colour used to represent the chat channel. * Associating a colour with each channel allows players to easily distinguish between channels. */ val color: Color /** * The radius up to which messages sent to the chat channel may be heard. * If the radius is less than or equal to zero, chat messages are global. * This is measured in metres, which is the size of one Minecraft block. */ val radius: Double /** * A list of all speakers in the channel. * If a speaker sends a message without indicating who it is directed to, it will be sent to this channel. * Players may only be speakers in a single channel. */ @Deprecated("Old players API. Please move to new profiles APIs.", ReplaceWith("speakerParticipants")) val speakers: List<RPKPlayer> /** * A list of all speakers in the channel. * If a speaker sends a message without indicating who it is directed to, it will be sent to this channel. * Chat participants may only be speakers in a single channel. */ val speakerMinecraftProfiles: List<RPKMinecraftProfile> /** * A list of all listeners in the channel. * If a message is sent to a channel, it will be heard by all listeners. * Players may listen to multiple channels. */ @Deprecated("Old players API. Please move to new profiles APIs.", ReplaceWith("listenerMinecraftProfiles")) val listeners: List<RPKPlayer> /** * A list of all listeners in the channel. * If a message is sent to a channel, it will be heard by all listeners. * Chat participants may listen to multiple channels. */ val listenerMinecraftProfiles: List<RPKMinecraftProfile> /** * The directed pipeline for the channel. * Messages to this channel will pass through this pipeline for each listener, so that formatting may be applied for * each recipient. */ val directedPipeline: List<DirectedChatChannelPipelineComponent> /** * The undirected pipeline for the channel. * Messages to this channel will pass through this pipeline once, so that messages may be logged or sent to IRC only * a single time. */ val undirectedPipeline: List<UndirectedChatChannelPipelineComponent> /** * The match pattern for this channel. * If a player's message matches the match pattern, it should be directed to this channel. * In the case of a chat channel not having a match pattern, this may be set to null. */ val matchPattern: String? /** * Whether this channel should be joined by default. * If a channel is joined by default, all new players are added as listeners to the channel upon joining for the * first time. If they are not, the channel is muted until they join it. */ val isJoinedByDefault: Boolean /** * Adds a speaker to the channel. * * @param speaker The player to add */ fun addSpeaker(speaker: RPKPlayer) /** * Removes a speaker from the channel. * * @param speaker The player to remove */ fun removeSpeaker(speaker: RPKPlayer) /** * Adds a speaker to the channel. * * @param speaker The chat participant to add */ fun addSpeaker(speaker: RPKMinecraftProfile) /** * Removes a speaker from the channel. * * @param speaker The chat participant to remove */ fun removeSpeaker(speaker: RPKMinecraftProfile) /** * Adds a listener to the channel. * * @param listener The player to add */ fun addListener(listener: RPKPlayer) /** * Removes a listener from the channel. * * @param listener The player to remove */ fun removeListener(listener: RPKPlayer) /** * Adds a listener to the channel. * * @param listener The Minecraft profile to add * @param isAsync Whether adding the listener is being done asynchronously */ fun addListener(listener: RPKMinecraftProfile, isAsync: Boolean = false) /** * Removes a listener from the channel. * * @param listener The Minecraft profile to remove */ fun removeListener(listener: RPKMinecraftProfile) /** * Sends a message to the channel, passing it through the directed pipeline once for each listener, and the * undirected pipeline once. * * @param sender The player sending the message * @param message The message * @param isAsync Whether the message is being sent asynchronously */ fun sendMessage(sender: RPKPlayer, message: String, isAsync: Boolean = false) /** * Sends the message to the channel, passing it through the specified directed pipeline once for each listener, and * the specified undirected pipeline once. * * @param sender The player sending the message * @param message The message * @param directedPipeline The directed pipeline * @param undirectedPipeline The undirected pipeline * @param isAsync Whether the message is being sent asynchronously */ fun sendMessage(sender: RPKPlayer, message: String, directedPipeline: List<DirectedChatChannelPipelineComponent>, undirectedPipeline: List<UndirectedChatChannelPipelineComponent>, isAsync: Boolean = false) /** * Sends a message to the channel, passing it through the directed pipeline once for each listener, and the * undirected pipeline once. * * @param sender The profile sending the message * @param senderMinecraftProfile The Minecraft profile used to send the message, or null if not sent from Minecraft * @param message The message * @param isAsync Whether the message is being sent asynchronously */ fun sendMessage(sender: RPKThinProfile, senderMinecraftProfile: RPKMinecraftProfile?, message: String, isAsync: Boolean = false) /** * Sends a message to the channel, passing it through the specified directed pipeline once for each listener, and * the specified undirected pipeline once. * * @param sender The profile sending the message * @param senderMinecraftProfile The Minecraft profile used to send the message, or null if not sent from Minecraft * @param message The message * @param directedPipeline The directed pipeline * @param undirectedPipeline The undirected pipeline * @param isAsync Whether the message is being sent asynchronously */ fun sendMessage(sender: RPKThinProfile, senderMinecraftProfile: RPKMinecraftProfile?, message: String, directedPipeline: List<DirectedChatChannelPipelineComponent>, undirectedPipeline: List<UndirectedChatChannelPipelineComponent>, isAsync: Boolean = false) }
apache-2.0
ab339de9d31d433a4e5a43b6bcc87822
36.56872
260
0.704517
4.981772
false
false
false
false
wuan/bo-android
app/src/main/java/org/blitzortung/android/map/MapFragment.kt
1
7130
package org.blitzortung.android.map import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.preference.PreferenceManager import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import org.blitzortung.android.app.Main import org.blitzortung.android.app.view.OnSharedPreferenceChangeListener import org.blitzortung.android.app.view.PreferenceKey import org.blitzortung.android.app.view.get import org.osmdroid.tileprovider.tilesource.TileSourceFactory import org.osmdroid.util.GeoPoint import org.osmdroid.views.CustomZoomButtonsController import org.osmdroid.views.overlay.CopyrightOverlay import org.osmdroid.views.overlay.ScaleBarOverlay import org.osmdroid.views.overlay.compass.CompassOverlay import org.osmdroid.views.overlay.compass.InternalCompassOrientationProvider import kotlin.math.min class MapFragment : Fragment(), OnSharedPreferenceChangeListener { private lateinit var mPrefs: SharedPreferences lateinit var mapView: OwnMapView private set private lateinit var mCopyrightOverlay: CopyrightOverlay private lateinit var mScaleBarOverlay: ScaleBarOverlay private lateinit var compassOverlay: CompassOverlay override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { mapView = OwnMapView(inflater.context) mapView.tileProvider.tileCache.apply { protectedTileComputers.clear(); setAutoEnsureCapacity(false) }; return mapView } @Deprecated("Deprecated in Java") override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val context = this.requireContext() val dm = context.resources.displayMetrics val preferences = PreferenceManager.getDefaultSharedPreferences(context) preferences.registerOnSharedPreferenceChangeListener(this) mPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) mCopyrightOverlay = CopyrightOverlay(context) mCopyrightOverlay.setTextSize(7) mapView.overlays.add(mCopyrightOverlay) mScaleBarOverlay = ScaleBarOverlay(mapView) mScaleBarOverlay.setScaleBarOffset(dm.widthPixels / 2, 15) mScaleBarOverlay.setCentred(true) mScaleBarOverlay.setAlignBottom(true) val centered = mScaleBarOverlay.javaClass.getDeclaredField("centred") centered.isAccessible = true centered.setBoolean(mScaleBarOverlay, true) mapView.overlays.add(this.mScaleBarOverlay) compassOverlay = CompassOverlay(context, InternalCompassOrientationProvider(context), mapView) compassOverlay.enableCompass() compassOverlay.setCompassCenter(mapView.width / 2.0f, mapView.height / 2.0f) mapView.overlays.add(this.compassOverlay) //built in zoom controls mapView.zoomController.setVisibility(CustomZoomButtonsController.Visibility.SHOW_AND_FADEOUT) //needed for pinch zooms mapView.setMultiTouchControls(true) //scales tiles to the current screen's DPI, helps with readability of labels mapView.isTilesScaledToDpi = true //the rest of this is restoring the last map location the user looked at val zoomLevel = mPrefs.getFloat(PREFS_ZOOM_LEVEL_DOUBLE, mPrefs.getInt(PREFS_ZOOM_LEVEL, 0).toFloat()) mapView.controller.setZoom(zoomLevel.toDouble()) mapView.setMapOrientation(0f, false) val latitudeString = mPrefs.getString(PREFS_LATITUDE_STRING, null) val longitudeString = mPrefs.getString(PREFS_LONGITUDE_STRING, null) if (latitudeString == null || longitudeString == null) { // case handled for historical reasons only val scrollX = mPrefs.getInt(PREFS_SCROLL_X, 0) val scrollY = mPrefs.getInt(PREFS_SCROLL_Y, 0) mapView.scrollTo(scrollX, scrollY) } else { val latitude = latitudeString.toDouble() val longitude = longitudeString.toDouble() mapView.setExpectedCenter(GeoPoint(latitude, longitude)) } setHasOptionsMenu(true) onSharedPreferenceChanged(preferences, PreferenceKey.MAP_TYPE, PreferenceKey.MAP_SCALE) } fun updateForgroundColor(fgcolor: Int) { mScaleBarOverlay.barPaint = mScaleBarOverlay.barPaint.apply { color = fgcolor } mScaleBarOverlay.textPaint = mScaleBarOverlay.textPaint.apply { color = fgcolor } mapView.postInvalidate() } override fun onPause() { //save the current location val edit = mPrefs.edit() edit.putString(PREFS_TILE_SOURCE, mapView.tileProvider.tileSource.name()) edit.putString(PREFS_LATITUDE_STRING, mapView.mapCenter.latitude.toString()) edit.putString(PREFS_LONGITUDE_STRING, mapView.mapCenter.longitude.toString()) edit.putFloat(PREFS_ZOOM_LEVEL_DOUBLE, mapView.zoomLevelDouble.toFloat()) edit.apply() mapView.onPause() super.onPause() } override fun onDestroyView() { super.onDestroyView() mapView.onDetach() } override fun onResume() { super.onResume() mapView.onResume() } fun calculateTargetZoomLevel(widthInMeters: Float): Double { val equatorLength = 40075004.0 // in meters val widthInPixels = min(mapView.height, mapView.width).toDouble() var metersPerPixel = equatorLength / 256 var zoomLevel = 0.0 while ((metersPerPixel * widthInPixels) > widthInMeters) { metersPerPixel /= 2.7 ++zoomLevel } return zoomLevel - 1.0 } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: PreferenceKey) { @Suppress("NON_EXHAUSTIVE_WHEN") when (key) { PreferenceKey.MAP_TYPE -> { val mapTypeString = sharedPreferences.get(key, "SATELLITE") mapView.setTileSource(if (mapTypeString == "SATELLITE") TileSourceFactory.DEFAULT_TILE_SOURCE else TileSourceFactory.MAPNIK) } PreferenceKey.MAP_SCALE -> { val scaleFactor = sharedPreferences.get(key, 100) / 100f Log.v(Main.LOG_TAG, "MapFragment scale $scaleFactor") mapView.tilesScaleFactor = scaleFactor } else -> {} } } companion object { // =========================================================== // Constants // =========================================================== const val PREFS_NAME = "org.andnav.osm.prefs" const val PREFS_TILE_SOURCE = "tilesource" const val PREFS_SCROLL_X = "scrollX" const val PREFS_SCROLL_Y = "scrollY" const val PREFS_LATITUDE_STRING = "latitudeString" const val PREFS_LONGITUDE_STRING = "longitudeString" const val PREFS_ZOOM_LEVEL = "zoomLevel" const val PREFS_ZOOM_LEVEL_DOUBLE = "zoomLevelDouble" } }
apache-2.0
d1a4961720080dc1d8d20e31aabd0ef8
39.742857
140
0.689762
4.934256
false
false
false
false
DR-YangLong/spring-boot-kotlin-demo
src/main/kotlin/site/yanglong/promotion/config/shiro/ShiroConfig.kt
1
9961
package site.yanglong.promotion.config.shiro import org.apache.commons.collections.MapUtils import org.apache.shiro.authc.credential.CredentialsMatcher import org.apache.shiro.cache.ehcache.EhCacheManager import org.apache.shiro.codec.Base64 import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor import org.apache.shiro.spring.web.ShiroFilterFactoryBean import org.apache.shiro.web.filter.authc.AnonymousFilter import org.apache.shiro.web.filter.authc.LogoutFilter import org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter import org.apache.shiro.web.filter.authc.UserFilter import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter import org.apache.shiro.web.mgt.CookieRememberMeManager import org.apache.shiro.web.mgt.DefaultWebSecurityManager import org.apache.shiro.web.servlet.AbstractShiroFilter import org.apache.shiro.web.servlet.SimpleCookie import org.apache.shiro.web.session.mgt.DefaultWebSessionManager import org.slf4j.LoggerFactory import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.AutoConfigureAfter import org.springframework.boot.autoconfigure.condition.ConditionalOnBean import org.springframework.cache.CacheManager import org.springframework.cache.ehcache.EhCacheCacheManager import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.DependsOn import site.yanglong.promotion.config.shiro.authentication.RealmService import site.yanglong.promotion.config.shiro.authentication.ShiroRealm import site.yanglong.promotion.config.shiro.dynamic.DynamicPermissionServiceImpl import site.yanglong.promotion.config.shiro.dynamic.JdbcPermissionDao import javax.servlet.Filter @Configuration @AutoConfigureAfter(ShiroLifeCycleConfig::class,CacheManager::class) class ShiroConfig { private val log = LoggerFactory.getLogger(ShiroConfig::class.java) @Autowired private var shiroProps: ShiroProperties?=null @Autowired private var cachemanager: EhCacheCacheManager? = null private var shiroFilter: ShiroFilterFactoryBean? = null @Bean(name = arrayOf("ehCacheManager")) fun ehCacheManager(): EhCacheManager { val ehCacheManager = EhCacheManager() val manager = cachemanager?.cacheManager ehCacheManager.cacheManager = manager return ehCacheManager } /** * 生成realm * * @return shiroRealm */ @Bean(name = arrayOf("shiroRealm")) @DependsOn("lifecycleBeanPostProcessor") fun shiroRealm(realmService: RealmService, credentialsMatcher: CredentialsMatcher): ShiroRealm { val shiroRealm = ShiroRealm() shiroRealm.name = "drRealm" shiroRealm.identity_in_map_key=shiroProps!!.identityInMapKey shiroRealm.password_in_map_key=shiroProps!!.passwordInMapKey shiroRealm.isEnablePerms=shiroProps!!.enablePerms shiroRealm.isEnableRoles=shiroProps!!.enableRoles shiroRealm.perms_in_map_key=shiroProps!!.permsInMapKey shiroRealm.roles_in_map_key=shiroProps!!.rolesInMapKey shiroRealm.user_status_in_map_key=shiroProps!!.userStatusInMapKey shiroRealm.user_status_forbidden=shiroProps!!.userStatusForbidden shiroRealm.user_status_locked=shiroProps!!.userStatusLocked shiroRealm.realmService = realmService shiroRealm.cacheManager = ehCacheManager() shiroRealm.credentialsMatcher = credentialsMatcher shiroRealm.isCachingEnabled = shiroProps!!.cachingEnabled shiroRealm.isAuthenticationCachingEnabled = shiroProps!!.authenticationCachingEnabled//认证缓存 shiroRealm.authenticationCacheName = shiroProps!!.authenticationCacheName shiroRealm.isAuthorizationCachingEnabled = shiroProps!!.authorizationCachingEnabled//授权缓存 shiroRealm.authorizationCacheName = shiroProps!!.authorizationCacheName return shiroRealm } /** * 代理 * * @return */ @Bean fun advisorAutoProxyCreator(): DefaultAdvisorAutoProxyCreator { val advisorAutoProxyCreator = DefaultAdvisorAutoProxyCreator() advisorAutoProxyCreator.isProxyTargetClass = true return advisorAutoProxyCreator } /** * 记住我cookie */ @Bean(name = arrayOf("rememberMeCookie")) fun rememberMeCookie(): SimpleCookie { val cookie = SimpleCookie(shiroProps!!.rmCookieName) cookie.isHttpOnly = shiroProps!!.cookieIsHttpOnly cookie.maxAge = shiroProps!!.rmCookieMaxAge//有效期,秒,7天 cookie.path = shiroProps!!.rmCookiePath return cookie } /** * 记住我cookie管理器 */ @Bean fun cookieRememberMeManager(): CookieRememberMeManager { val remember = CookieRememberMeManager() remember.cipherKey = Base64.decode(shiroProps!!.rmCipherKey)//用于cookie加密的key remember.cookie = rememberMeCookie()//cookie return remember } /** * 会话dao,如果要进行集群或者分布式应用,这里可以改造为自己的会话dao,也可以对DAO的缓存管理器进行改造 * {@link #ehCacheManager()} */ @Bean fun sessionDAO(): EnterpriseCacheSessionDAO { val sessionDAO = EnterpriseCacheSessionDAO() sessionDAO.activeSessionsCacheName = shiroProps!!.sessionCacheName//session缓存的名称 sessionDAO.cacheManager = ehCacheManager()//缓存管理器 return sessionDAO } /** * 会话cookie */ @Bean fun sessionIdCookie(): SimpleCookie { val sessionIdCookie = SimpleCookie(shiroProps!!.sessionCookieName) sessionIdCookie.domain = shiroProps!!.sessionCookieDomain//注意用域名时必须匹配或者设置跨域 sessionIdCookie.isHttpOnly = shiroProps!!.cookieIsHttpOnly sessionIdCookie.maxAge = shiroProps!!.sessionCookieMaxAge//cookie有效期,单位秒,-1为浏览器进度 sessionIdCookie.path = shiroProps!!.sessionCookiePath//cookie路径 return sessionIdCookie } /** * 会话管理器 */ @Bean fun sessionManager(): DefaultWebSessionManager { val sessionManager = DefaultWebSessionManager() sessionManager.sessionDAO = sessionDAO() sessionManager.isSessionIdCookieEnabled = true//使用cookie传递sessionId sessionManager.sessionIdCookie = sessionIdCookie() sessionManager.globalSessionTimeout = shiroProps!!.globalSessionTimeout//服务端session过期时间,单位毫秒 return sessionManager } /** * securityManager * * @return securityManager */ @Bean(name = arrayOf("securityManager")) fun webSecurityManager(shiroRealm: ShiroRealm): DefaultWebSecurityManager { val securityManager = DefaultWebSecurityManager() securityManager.setRealm(shiroRealm) securityManager.cacheManager = ehCacheManager() securityManager.rememberMeManager = cookieRememberMeManager() securityManager.sessionManager = sessionManager() return securityManager } /** * 授权验证代理设置 * @param securityManager * @return */ @Bean fun authorizationAttributeSourceAdvisor(securityManager: DefaultWebSecurityManager): AuthorizationAttributeSourceAdvisor { val authorizationAttributeSourceAdvisor = AuthorizationAttributeSourceAdvisor() authorizationAttributeSourceAdvisor.securityManager = securityManager return authorizationAttributeSourceAdvisor } /** * 凭证匹配器 * @return */ @Bean(name = arrayOf("credentialsMatcher")) fun credentialsMatcher(): CredentialsMatcher { return DrCredentialsMatcher() } /** * filter工厂 * @return */ @Bean(name = arrayOf("shiroFilter")) fun shiroFilter(webSecurityManager: DefaultWebSecurityManager): ShiroFilterFactoryBean { val shiroFilter = ShiroFilterFactoryBean() shiroFilter.loginUrl = shiroProps!!.loginUrl shiroFilter.successUrl = shiroProps!!.successUrl shiroFilter.unauthorizedUrl = shiroProps!!.unauthorizedUrl if (MapUtils.isNotEmpty(shiroProps!!.definitionMap)) { shiroFilter.filterChainDefinitionMap = shiroProps!!.definitionMap } shiroFilter.securityManager = webSecurityManager val filters = HashMap<String, Filter>() if (MapUtils.isNotEmpty(shiroProps!!.filtersMap)) { shiroProps!!.filtersMap?.forEach { t, u -> filters.put(t, (Class.forName(u).newInstance()) as Filter) } } else { filters.put("anon", AnonymousFilter()) filters.put("authc", PassThruAuthenticationFilter()) filters.put("logout", LogoutFilter()) filters.put("roles", RolesAuthorizationFilter()) filters.put("perms", PermissionsAuthorizationFilter()) filters.put("user", UserFilter()) } shiroFilter.filters = filters log.debug("shiro初始化完成,filter数量为:{}", shiroFilter.filters.size) this.shiroFilter = shiroFilter return shiroFilter } @Bean("dynamicPermissionService") @ConditionalOnBean(AbstractShiroFilter::class, ShiroFilterFactoryBean::class) fun filterChainDefinitionsFactory(jdbcPermissionDao: JdbcPermissionDao): DynamicPermissionServiceImpl { val service = DynamicPermissionServiceImpl() service.shiroFilter = shiroFilter?.`object` as? AbstractShiroFilter service.dynamicPermissionDao = jdbcPermissionDao service.definitions = shiroProps!!.definitions return service } }
apache-2.0
da7873e4c7ee43969629dc4307a7d04c
40.145299
126
0.737094
5.061514
false
true
false
false
Yorxxx/played-next-kotlin
app/src/androidTest/java/com/piticlistudio/playednext/util/RxIdlingResource.kt
1
1685
package com.piticlistudio.playednext.util import android.support.test.espresso.IdlingResource import timber.log.Timber import java.util.concurrent.atomic.AtomicInteger /** * Espresso Idling resource that handles waiting for RxJava Observables executions. * This class must be used with RxIdlingExecutionHook. * Before registering this idling resource you must: * 1. Create an instance of RxIdlingExecutionHook by passing an instance of this class. * 2. Register RxIdlingExecutionHook with the RxJavaPlugins using registerObservableExecutionHook() * 3. Register this idle resource with Espresso using Espresso.registerIdlingResources() */ class RxIdlingResource : IdlingResource { private val mActiveSubscriptionsCount = AtomicInteger(0) private var mResourceCallback: IdlingResource.ResourceCallback? = null override fun getName(): String { return javaClass.simpleName } override fun isIdleNow(): Boolean { return mActiveSubscriptionsCount.get() <= 0 } override fun registerIdleTransitionCallback(callback: IdlingResource.ResourceCallback) { mResourceCallback = callback } fun incrementActiveSubscriptionsCount() { val count = mActiveSubscriptionsCount.incrementAndGet() Timber.i("Active subscriptions count increased to %d", count) } fun decrementActiveSubscriptionsCount() { val count = mActiveSubscriptionsCount.decrementAndGet() Timber.i("Active subscriptions count decreased to %d", count) if (isIdleNow) { Timber.i("There is no active subscriptions, transitioning to Idle") mResourceCallback?.onTransitionToIdle() } } }
mit
aad6625ff2216a21aa553c10d5659478
35.652174
99
0.745401
5.400641
false
false
false
false
dmitryustimov/weather-kotlin
app/src/main/java/ru/ustimov/weather/util/Throwables.kt
1
737
package ru.ustimov.weather.util private const val CALLER_INDEX: Int = 1 fun Throwable?.println(logger: Logger) { val stackTraceThrowable = Throwable() val traces = stackTraceThrowable.stackTrace if (traces?.size ?: 0 > CALLER_INDEX + 1) { val trace = traces[CALLER_INDEX] val fileName: String? = trace.fileName val tag: String = if (fileName.isNullOrEmpty()) trace.className else fileName.orEmpty() val lineNumber = if (trace.lineNumber > 0) " at line ${trace.lineNumber}" else "" val message = "Exception in ${trace.className}.${trace.methodName}$lineNumber" logger.e(tag, message, this) } else { logger.e("Throwables", this?.message.orEmpty(), this); } }
apache-2.0
b9bedaba96fc6b73bb0b5d2e5200b6e1
34.142857
95
0.658073
4.117318
false
false
false
false
encodeering/conflate
modules/conflate-test/src/main/kotlin/com/encodeering/conflate/experimental/test/Spy.kt
1
494
package com.encodeering.conflate.experimental.test import org.mockito.Mockito /** * @author Michael Clausen - [email protected] */ fun <T> eq (value : T) : T = Mockito.eq (value) inline fun <reified T> any () : T = Mockito.any (T::class.java) inline fun <reified T> mock () : T = Mockito.mock (T::class.java) fun <T> whenever (element : T) = Mockito.`when` (element) fun spy () = mock<() -> Unit> () inline fun <reified T> spy () = mock<(T) -> Unit> ()
apache-2.0
81f46066a0d9ec428a3472559d3ecaca
26.5
65
0.605263
3.207792
false
true
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/games/lane/Deck.kt
1
4618
package ca.josephroque.bowlingcompanion.games.lane /** * Copyright (C) 2018 Joseph Roque * * Alias for an array of pins. */ typealias Deck = Array<Pin> // MARK: Pins val Deck.left2Pin: Pin get() = this[0] val Deck.left3Pin: Pin get() = this[1] val Deck.headPin: Pin get() = this[2] val Deck.right3Pin: Pin get() = this[3] val Deck.right2Pin: Pin get() = this[4] // MARK: First Ball fun Deck.isHeadPin(countH2asH: Boolean): Boolean { return this.isHeadPin || (countH2asH && this.value(false) == 7 && this.headPin.isDown) } val Deck.isHeadPin: Boolean get() = this.value(false) == 5 && this.headPin.isDown val Deck.isLeft: Boolean get() = this.value(false) == 13 && this.left2Pin.onDeck val Deck.isRight: Boolean get() = this.value(false) == 13 && this.right2Pin.onDeck val Deck.isAce: Boolean get() = this.value(false) == 11 val Deck.isLeftChopOff: Boolean get() = this.value(false) == 10 && this.left2Pin.isDown && this.left3Pin.isDown && this.headPin.isDown val Deck.isRightChopOff: Boolean get() = this.value(false) == 10 && this.right2Pin.isDown && this.right3Pin.isDown && this.headPin.isDown val Deck.isChopOff: Boolean get() = this.isLeftChopOff || this.isRightChopOff fun Deck.isLeftSplit(countS2asS: Boolean): Boolean { return this.isLeftSplit || (countS2asS && this.value(false) == 10 && this.headPin.isDown && this.left3Pin.isDown && this.right2Pin.isDown) } private val Deck.isLeftSplit: Boolean get() = this.value(false) == 8 && this.headPin.isDown && this.left3Pin.isDown fun Deck.isRightSplit(countS2asS: Boolean): Boolean { return this.isRightSplit || (countS2asS && this.value(false) == 10 && this.headPin.isDown && this.left2Pin.isDown && this.right3Pin.isDown) } private val Deck.isRightSplit: Boolean get() = this.value(false) == 8 && this.headPin.isDown && this.right3Pin.isDown fun Deck.isSplit(countS2asS: Boolean): Boolean { return isLeftSplit(countS2asS) || isRightSplit(countS2asS) } val Deck.isHitLeftOfMiddle: Boolean get() = this.headPin.onDeck && (this.left2Pin.isDown || this.left3Pin.isDown) val Deck.isHitRightOfMiddle: Boolean get() = this.headPin.onDeck && (this.right2Pin.isDown || this.right3Pin.isDown) val Deck.isMiddleHit: Boolean get() = this.headPin.isDown val Deck.isLeftTwelve: Boolean get() = this.value(false) == 12 && this.left3Pin.isDown val Deck.isRightTwelve: Boolean get() = this.value(false) == 12 && this.right3Pin.isDown val Deck.isTwelve: Boolean get() = this.isLeftTwelve || this.isRightTwelve val Deck.arePinsCleared: Boolean get() = this.all { it.isDown } // Functions fun Deck.toBooleanArray(): BooleanArray { return this.map { it.isDown }.toBooleanArray() } fun Deck.deepCopy(): Deck { return this.map { pin -> Pin(pin.type).apply { isDown = pin.isDown } }.toTypedArray() } fun Deck.toInt(): Int { var ball = 0 for (i in this.indices) { if (this[i].isDown) { ball += Math.pow(2.0, (-i + 4).toDouble()).toInt() } } return ball } fun Deck.reset() { this.forEach { it.isDown = false } } fun Deck.value(onDeck: Boolean): Int { return this.filter { it.onDeck == onDeck }.sumBy { it.value } } fun Deck.ballValue(ballIdx: Int, returnSymbol: Boolean, afterStrike: Boolean): String { val ball = when { isHeadPin(false) -> Ball.HeadPin isHeadPin(true) -> Ball.HeadPin2 isSplit(false) -> Ball.Split isSplit(true) -> Ball.Split2 isChopOff -> Ball.ChopOff isAce -> Ball.Ace isLeft -> Ball.Left isRight -> Ball.Right arePinsCleared -> { when { ballIdx == 0 -> Ball.Strike ballIdx == 1 && !afterStrike -> Ball.Spare else -> Ball.Cleared } } else -> Ball.None } return if (ball == Ball.None) { val value = this.value(false) return if (value == 0) { ball.toString() } else { value.toString() } } else { if (ballIdx == 0 || returnSymbol) ball.toString() else ball.numeral } } fun Deck.ballValueDifference(other: Deck, ballIdx: Int, returnSymbol: Boolean, afterStrike: Boolean): String { val deck = this.deepCopy() for (i in 0 until other.size) { if (other[i].isDown) { deck[i].isDown = false } } return deck.ballValue(ballIdx, returnSymbol, afterStrike) } fun Deck.valueDifference(other: Deck): Int { return this.filterIndexed { index, pin -> pin.isDown && !other[index].isDown }.sumBy { it.value } }
mit
2dd5730256734abb455b0b011606f9a4
26.987879
143
0.64162
3.390602
false
false
false
false
AlekseyZhelo/LBM
SimpleGUIApp/src/main/kotlin/com/alekseyzhelo/lbm/gui/simple/algs4/Algs4Util.kt
1
2587
package com.alekseyzhelo.lbm.gui.simple.algs4 import com.alekseyzhelo.lbm.core.lattice.LatticeD2 import com.alekseyzhelo.lbm.util.norm import com.alekseyzhelo.lbm.util.normalize import java.awt.Color import java.util.* /** * @author Aleks on 29-05-2016. */ internal val colorMemo = HashMap<Int, Color>() internal fun blueRedGradient(n: Int): Color { val corrected = when { n > 255 -> 255 n < 0 -> 0 else -> n } var color = colorMemo[corrected] if (color == null) { val b = 255 - corrected val r = 255 - b val g = 0 // var rgb = r; // rgb = (rgb shl 8) + g; // rgb = (rgb shl 8) + b; color = Color (r, g, b) colorMemo.put(corrected, color) } return color } internal fun cellColor(normalized: Double): Color { return blueRedGradient((normalized * 255).toInt()) } internal fun drawScalarValue(value: Double, i: Int, j: Int, minValue: Double, maxValue: Double): Unit { val color = cellColor(normalize(value, minValue, maxValue)) FasterStdDraw.setPenColor(color) // TODO: why is j + 1 necessary? j leaves an empty row at the top.. FasterStdDraw.deferredFilledSquareTest((i).toDouble(), (j + 1).toDouble(), 1.0) // double r } internal fun drawVectorValue(value: DoubleArray, i: Int, j: Int, minValue: Double, maxValue: Double): Unit { val color = cellColor(normalize(norm(value), minValue, maxValue)) val ort = normalize(value) FasterStdDraw.setPenColor(color) FasterStdDraw.drawArrowLineTest((i).toDouble(), (j).toDouble(), i + ort[0], j + ort[1], 0.3, 0.2) } fun LatticeD2<*>.drawDensityTable(minDensity: Double, maxDensity: Double): Unit { for (i in cells.indices) { for (j in cells[0].indices) { drawScalarValue(cells[i][j].computeRho(), i, j, minDensity, maxDensity) } } } fun LatticeD2<*>.drawVelocityNormTable(minVelocityNorm: Double, maxVelocityNorm: Double): Unit { for (i in cells.indices) { for (j in cells[0].indices) { drawScalarValue( norm(cells[i][j].computeRhoU()), i, j, minVelocityNorm, maxVelocityNorm ) } } } fun LatticeD2<*>.drawVelocityVectorTable(minVelocityNorm: Double, maxVelocityNorm: Double): Unit { for (i in cells.indices) { for (j in cells[0].indices) { drawVectorValue( cells[i][j].computeRhoU(), i, j, minVelocityNorm, maxVelocityNorm ) } } }
apache-2.0
ca32043a9f0180f75c70ac1c9ee773ee
29.093023
101
0.603402
3.633427
false
false
false
false
coil-kt/coil
coil-base/src/main/java/coil/util/Utils.kt
1
9515
@file:JvmName("-Utils") @file:Suppress("NOTHING_TO_INLINE") package coil.util import android.app.ActivityManager import android.content.ContentResolver.SCHEME_FILE import android.content.Context import android.content.pm.ApplicationInfo import android.content.res.Configuration import android.graphics.Bitmap import android.graphics.ColorSpace import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.graphics.drawable.VectorDrawable import android.net.Uri import android.os.Build.VERSION.SDK_INT import android.os.Looper import android.view.View import android.webkit.MimeTypeMap import android.widget.ImageView import android.widget.ImageView.ScaleType.CENTER_INSIDE import android.widget.ImageView.ScaleType.FIT_CENTER import android.widget.ImageView.ScaleType.FIT_END import android.widget.ImageView.ScaleType.FIT_START import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat import coil.ComponentRegistry import coil.EventListener import coil.ImageLoader import coil.base.R import coil.decode.DataSource import coil.decode.Decoder import coil.disk.DiskCache import coil.fetch.Fetcher import coil.intercept.Interceptor import coil.intercept.RealInterceptorChain import coil.memory.MemoryCache import coil.request.Parameters import coil.request.Tags import coil.request.ViewTargetRequestManager import coil.size.Dimension import coil.size.Scale import coil.size.Size import coil.size.isOriginal import coil.size.pxOrElse import coil.transform.Transformation import java.io.Closeable import java.io.File import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi import okhttp3.Headers internal val View.requestManager: ViewTargetRequestManager get() { var manager = getTag(R.id.coil_request_manager) as? ViewTargetRequestManager if (manager == null) { manager = synchronized(this) { // Check again in case coil_request_manager was just set. (getTag(R.id.coil_request_manager) as? ViewTargetRequestManager) ?.let { return@synchronized it } ViewTargetRequestManager(this).apply { addOnAttachStateChangeListener(this) setTag(R.id.coil_request_manager, this) } } } return manager } internal val DataSource.emoji: String get() = when (this) { DataSource.MEMORY_CACHE, DataSource.MEMORY -> Emoji.BRAIN DataSource.DISK -> Emoji.FLOPPY DataSource.NETWORK -> Emoji.CLOUD } internal val Drawable.width: Int get() = (this as? BitmapDrawable)?.bitmap?.width ?: intrinsicWidth internal val Drawable.height: Int get() = (this as? BitmapDrawable)?.bitmap?.height ?: intrinsicHeight internal val Drawable.isVector: Boolean get() = this is VectorDrawable || this is VectorDrawableCompat internal fun Closeable.closeQuietly() { try { close() } catch (e: RuntimeException) { throw e } catch (_: Exception) {} } internal val ImageView.scale: Scale get() = when (scaleType) { FIT_START, FIT_CENTER, FIT_END, CENTER_INSIDE -> Scale.FIT else -> Scale.FILL } /** * Modified from [MimeTypeMap.getFileExtensionFromUrl] to be more permissive * with special characters. */ internal fun MimeTypeMap.getMimeTypeFromUrl(url: String?): String? { if (url.isNullOrBlank()) { return null } val extension = url .substringBeforeLast('#') // Strip the fragment. .substringBeforeLast('?') // Strip the query. .substringAfterLast('/') // Get the last path segment. .substringAfterLast('.', missingDelimiterValue = "") // Get the file extension. return getMimeTypeFromExtension(extension) } internal val Uri.firstPathSegment: String? get() = pathSegments.firstOrNull() internal val Configuration.nightMode: Int get() = uiMode and Configuration.UI_MODE_NIGHT_MASK /** * An allowlist of valid bitmap configs for the input and output bitmaps of * [Transformation.transform]. */ internal val VALID_TRANSFORMATION_CONFIGS = if (SDK_INT >= 26) { arrayOf(Bitmap.Config.ARGB_8888, Bitmap.Config.RGBA_F16) } else { arrayOf(Bitmap.Config.ARGB_8888) } /** * Prefer hardware bitmaps on API 26 and above since they are optimized for drawing without * transformations. */ internal val DEFAULT_BITMAP_CONFIG = if (SDK_INT >= 26) { Bitmap.Config.HARDWARE } else { Bitmap.Config.ARGB_8888 } /** Required for compatibility with API 25 and below. */ internal val NULL_COLOR_SPACE: ColorSpace? = null internal val EMPTY_HEADERS = Headers.Builder().build() internal fun Headers?.orEmpty() = this ?: EMPTY_HEADERS internal fun Tags?.orEmpty() = this ?: Tags.EMPTY internal fun Parameters?.orEmpty() = this ?: Parameters.EMPTY internal fun isMainThread() = Looper.myLooper() == Looper.getMainLooper() internal inline val Any.identityHashCode: Int get() = System.identityHashCode(this) @OptIn(ExperimentalCoroutinesApi::class) internal fun <T> Deferred<T>.getCompletedOrNull(): T? { return try { getCompleted() } catch (_: Throwable) { null } } internal inline operator fun MemoryCache.get(key: MemoryCache.Key?) = key?.let(::get) /** https://github.com/coil-kt/coil/issues/675 */ internal val Context.safeCacheDir: File get() = cacheDir.apply { mkdirs() } internal inline fun ComponentRegistry.Builder.addFirst( pair: Pair<Fetcher.Factory<*>, Class<*>>? ) = apply { if (pair != null) fetcherFactories.add(0, pair) } internal inline fun ComponentRegistry.Builder.addFirst( factory: Decoder.Factory? ) = apply { if (factory != null) decoderFactories.add(0, factory) } internal fun String.toNonNegativeInt(defaultValue: Int): Int { val value = toLongOrNull() ?: return defaultValue return when { value > Int.MAX_VALUE -> Int.MAX_VALUE value < 0 -> 0 else -> value.toInt() } } internal fun DiskCache.Editor.abortQuietly() { try { abort() } catch (_: Exception) {} } internal const val MIME_TYPE_JPEG = "image/jpeg" internal const val MIME_TYPE_WEBP = "image/webp" internal const val MIME_TYPE_HEIC = "image/heic" internal const val MIME_TYPE_HEIF = "image/heif" internal val Interceptor.Chain.isPlaceholderCached: Boolean get() = this is RealInterceptorChain && isPlaceholderCached internal val Interceptor.Chain.eventListener: EventListener get() = if (this is RealInterceptorChain) eventListener else EventListener.NONE internal fun Int.isMinOrMax() = this == Int.MIN_VALUE || this == Int.MAX_VALUE internal inline fun Size.widthPx(scale: Scale, original: () -> Int): Int { return if (isOriginal) original() else width.toPx(scale) } internal inline fun Size.heightPx(scale: Scale, original: () -> Int): Int { return if (isOriginal) original() else height.toPx(scale) } internal fun Dimension.toPx(scale: Scale) = pxOrElse { when (scale) { Scale.FILL -> Int.MIN_VALUE Scale.FIT -> Int.MAX_VALUE } } internal fun unsupported(): Nothing = error("Unsupported") internal const val ASSET_FILE_PATH_ROOT = "android_asset" internal fun isAssetUri(uri: Uri): Boolean { return uri.scheme == SCHEME_FILE && uri.firstPathSegment == ASSET_FILE_PATH_ROOT } /** Modified from [Headers.Builder.add] */ internal fun Headers.Builder.addUnsafeNonAscii(line: String) = apply { val index = line.indexOf(':') require(index != -1) { "Unexpected header: $line" } addUnsafeNonAscii(line.substring(0, index).trim(), line.substring(index + 1)) } private const val STANDARD_MEMORY_MULTIPLIER = 0.2 private const val LOW_MEMORY_MULTIPLIER = 0.15 /** Return the default percent of the application's total memory to use for the memory cache. */ internal fun defaultMemoryCacheSizePercent(context: Context): Double { return try { val activityManager: ActivityManager = context.requireSystemService() if (activityManager.isLowRamDevice) LOW_MEMORY_MULTIPLIER else STANDARD_MEMORY_MULTIPLIER } catch (_: Exception) { STANDARD_MEMORY_MULTIPLIER } } private const val DEFAULT_MEMORY_CLASS_MEGABYTES = 256 /** Return a [percent] of the application's total memory in bytes. */ internal fun calculateMemoryCacheSize(context: Context, percent: Double): Int { val memoryClassMegabytes = try { val activityManager: ActivityManager = context.requireSystemService() val isLargeHeap = (context.applicationInfo.flags and ApplicationInfo.FLAG_LARGE_HEAP) != 0 if (isLargeHeap) activityManager.largeMemoryClass else activityManager.memoryClass } catch (_: Exception) { DEFAULT_MEMORY_CLASS_MEGABYTES } return (percent * memoryClassMegabytes * 1024 * 1024).toInt() } /** * Holds the singleton instance of the disk cache. We need to have a singleton disk cache * instance to support creating multiple [ImageLoader]s without specifying the disk cache * directory. * * @see DiskCache.Builder.directory */ internal object SingletonDiskCache { private const val FOLDER_NAME = "image_cache" private var instance: DiskCache? = null @Synchronized fun get(context: Context): DiskCache { return instance ?: run { // Create the singleton disk cache instance. DiskCache.Builder() .directory(context.safeCacheDir.resolve(FOLDER_NAME)) .build() .also { instance = it } } } }
apache-2.0
55277ff9081012df40e4ea706db05b64
31.697595
98
0.71403
4.262993
false
false
false
false
zhengjiong/ZJ_KotlinStudy
src/main/kotlin/com/zj/example/kotlin/basicsknowledge/1.ConstructorExample构造函数.kt
1
4542
package com.zj.example.kotlin.basicsknowledge /** * 构造函数example * CreateTime: 17/9/7 13:38 * @author 郑炯 */ fun main(args: Array<String>) { val a = Customer("jinjin"); println(a.name) } /** * 1.标准构造函数写法 */ private class Person constructor(val name: String) { fun sayHello() { println("hello $name") } } private data class Person2(val name:String?=null) /** * 2.构造函数简写 */ private class Animal(val name: String) { fun sayHello() { println("hello $name") } } /** * 3.在构造函数中声明的参数,它们默认属于类的公有字段,可以直接使用, * 如果你不希望别的类访问到这个变量,可以用private修饰。 */ private class Cat(private val name: String) { fun miao() { println("$name 喵") } } /** * 在主构造函数中不能有任何代码实现,如果有额外的代码需要在构造方法中执行, * 你需要放到init代码块中执行。同时,在本示例中由于需要更改 name 参数的值, * 我们将 val 改为 var,表明 name 参数是一个可改变的参数。 */ private class Dog(var name: String) { init { name = "金金" } } /** * 注意主构造函数的参数可以用在初始化块内,也可以用在类的属性初始化声明处: */ class Customer(val name: String) { val upperCaseName = name.toUpperCase() } /** * 类也可以有二级构造函数,需要加前缀 constructor: */ class SecondConstructorClass1 { constructor(parent: String) { println(parent) } } /** * 如果类有主构造函数,每个二级构造函数都要,或直接或间接通过另一个二级构造函数代理主构造函数。 * 在同一个类中代理另一个构造函数使用 this 关键字: */ class SecondConstructorClass2(val name: String) { constructor(name: String, age: Int) : this(name) { } } /** * 如果一个非抽象类没有声明构造函数(主构造函数或二级构造函数),它会产生一个没有参数的构造函数。该构造函数的可见 * 性是 public 。如果你不想你的类有公共的构造函数,你就得声明一个拥有非默认可见性的空主构造函数: */ class ConstructorClass { } class PrivateConstructorClass private constructor() { } /** * 注意:在 JVM 虚拟机中,如果主构造函数的所有参数都有默认值,编译器会生成一个附加的无参的构造函数, * 这个构造函数会直接使用默认值。这使得 Kotlin 可以更简单的使用像 Jackson 或者 JPA * 这样使用无参构造函数来创建类实例的库。 */ class DefaultValueConstructorClass(name: String = "ZhengJiong") { } fun main2(args: Array<String>) { val b = SecondaryConstructorClass2("zj") println(b.name) } fun main3(args: Array<String>) { var obj = SecondaryConstructorClass1("zhengjiong", 32) println("${obj.name} ${obj.age}") } /** * 如果声明了主构造函数, 二级构造函数必须通过this调用主构造函数 * 由于次级构造函数不能直接将参数转换为字段,所以需要手动声明一个 age 字段,并为 age 字段赋值。 */ class SecondaryConstructorClass1(val name: String) { var age: Int? = 0; constructor(name: String, age: Int) : this(name) { this.age = age } } /** * 由于次级构造函数不能直接将参数转换为字段,所以需要手动声明一个 name 字段,并为 name 字段赋值。 */ class SecondaryConstructorClass2 { var name: String? = null constructor(name: String) { this.name = name } } fun main4(args: Array<String>) { var obj = ConstructorPrivateClass("zj") } /** * 如果一个非抽象类没有声明构造函数(主构造函数或二级构造函数),它会产生一个没有参数的构造函数。该 * 构造函数的可见性是 public 。如果你不想你的类有公共的构造函数,你就得声明一个拥有非默认可见性的空主构造函数: */ class ConstructorPrivateClass private constructor() { var name: String? = null /** * 默认构造参数是private的不能通过其创建对象, 但是这个有参构造函数创建对象, * 如果声明了主构造函数, 二级构造函数必须通过this调用主构造函数 */ constructor(name: String) : this() { } /** * 可以通过这个构造函数调用上面那个构造函数 */ constructor(age: Int) : this("zhengjiong") { } }
mit
4b5c1cf6a1e4b0ee72724064b057d9a4
17.93125
65
0.668098
2.762774
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/ide/intentions/UnwrapSingleExprIntention.kt
1
1796
package org.rust.ide.intentions import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RustBlockExprElement import org.rust.lang.core.psi.RustExprElement import org.rust.lang.core.psi.util.getNextNonCommentSibling import org.rust.lang.core.psi.util.parentOfType class UnwrapSingleExprIntention : PsiElementBaseIntentionAction() { override fun getText() = "Remove braces from single expression" override fun getFamilyName() = text override fun startInWriteAction() = true private data class Context( val blockExpr: RustBlockExprElement ) private fun findContext(element: PsiElement): Context? { if (!element.isWritable) return null val blockExpr = element.parentOfType<RustBlockExprElement>() as? RustBlockExprElement ?: return null val block = blockExpr.block ?: return null if (block.expr != null && block.lbrace.getNextNonCommentSibling() == block.expr) { return Context(blockExpr) } return null } override fun invoke(project: Project, editor: Editor, element: PsiElement) { val ctx = findContext(element) ?: return val block = ctx.blockExpr val blockBody = ctx.blockExpr.block?.expr ?: return val relativeCaretPosition = editor.caretModel.offset - blockBody.textOffset val offset = (block.replace(blockBody) as RustExprElement).textOffset editor.caretModel.moveToOffset(offset + relativeCaretPosition) } override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean { return findContext(element) != null } }
mit
59a496c24633d39bb45bd8e9a6712b00
36.416667
108
0.725501
4.776596
false
false
false
false
android/user-interface-samples
CanonicalLayouts/feed-view/app/src/main/java/com/example/viewbasedfeedlayoutsample/ui/MySweetsRecyclerViewAdapter.kt
1
2482
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.viewbasedfeedlayoutsample.ui import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import coil.load import com.example.viewbasedfeedlayoutsample.data.Sweets import com.example.viewbasedfeedlayoutsample.databinding.FragmentSweetsFeedItemBinding /** * [RecyclerView.Adapter] that can display a [Sweets]. */ class MySweetsRecyclerViewAdapter( private val values: List<Sweets>, private val onSweetsSelected: (Sweets) -> Unit = {} ) : RecyclerView.Adapter<MySweetsRecyclerViewAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( FragmentSweetsFeedItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = values[position] holder.descriptionView.text = holder.descriptionView.context.getString(item.description) holder.thumbnailView.load(item.imageUrl) holder.setClickListener { onSweetsSelected(item) } } override fun getItemCount(): Int = values.size inner class ViewHolder(binding: FragmentSweetsFeedItemBinding) : RecyclerView.ViewHolder(binding.root) { val descriptionView: TextView = binding.description val thumbnailView: ImageView = binding.thumbnail private val root = binding.root fun setClickListener(listener: (View) -> Unit) { root.setOnClickListener(listener) } override fun toString(): String { return super.toString() + " '" + descriptionView.text + "'" } } }
apache-2.0
0c95c32e9e2c98b57cdcad173557e94d
34.457143
108
0.71112
4.791506
false
false
false
false
vanniktech/Emoji
emoji-material/src/androidMain/kotlin/com/vanniktech/emoji/material/EmojiMaterialRadioButton.kt
1
2659
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vanniktech.emoji.material import android.content.Context import android.text.SpannableStringBuilder import android.util.AttributeSet import androidx.annotation.AttrRes import androidx.annotation.CallSuper import androidx.annotation.DimenRes import androidx.annotation.Px import com.google.android.material.radiobutton.MaterialRadioButton import com.vanniktech.emoji.EmojiDisplayable import com.vanniktech.emoji.EmojiManager import com.vanniktech.emoji.init import com.vanniktech.emoji.replaceWithImages import kotlin.jvm.JvmOverloads open class EmojiMaterialRadioButton @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr: Int = com.google.android.material.R.attr.radioButtonStyle, ) : MaterialRadioButton(context, attrs, defStyleAttr), EmojiDisplayable { @Px private var emojiSize: Float init { emojiSize = init(attrs, R.styleable.EmojiMaterialRadioButton, R.styleable.EmojiMaterialRadioButton_emojiSize) } @CallSuper override fun setText(rawText: CharSequence?, type: BufferType) { if (isInEditMode) { super.setText(rawText, type) return } val spannableStringBuilder = SpannableStringBuilder(rawText ?: "") val fontMetrics = paint.fontMetrics val defaultEmojiSize = fontMetrics.descent - fontMetrics.ascent EmojiManager.replaceWithImages(context, spannableStringBuilder, if (emojiSize != 0f) emojiSize else defaultEmojiSize) super.setText(spannableStringBuilder, type) } override fun getEmojiSize() = emojiSize override fun setEmojiSize(@Px pixels: Int) = setEmojiSize(pixels, true) override fun setEmojiSize(@Px pixels: Int, shouldInvalidate: Boolean) { emojiSize = pixels.toFloat() if (shouldInvalidate) { text = text } } override fun setEmojiSizeRes(@DimenRes res: Int) = setEmojiSizeRes(res, true) override fun setEmojiSizeRes(@DimenRes res: Int, shouldInvalidate: Boolean) = setEmojiSize(resources.getDimensionPixelSize(res), shouldInvalidate) }
apache-2.0
e9fe97f0b0241b61952039721c38eeb5
36.422535
121
0.774181
4.596886
false
false
false
false
shantstepanian/obevo
obevo-core/src/main/java/com/gs/obevo/impl/reader/DbDirectoryChangesetReader.kt
1
15525
/** * Copyright 2017 Goldman Sachs. * 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.gs.obevo.impl.reader import com.gs.obevo.api.appdata.ChangeInput import com.gs.obevo.api.appdata.doc.TextMarkupDocumentSection import com.gs.obevo.api.platform.ChangeType import com.gs.obevo.api.platform.DeployMetrics import com.gs.obevo.api.platform.FileSourceContext import com.gs.obevo.api.platform.FileSourceParams import com.gs.obevo.impl.DeployMetricsCollector import com.gs.obevo.impl.DeployMetricsCollectorImpl import com.gs.obevo.impl.OnboardingStrategy import com.gs.obevo.util.VisibleForTesting import com.gs.obevo.util.hash.OldWhitespaceAgnosticDbChangeHashStrategy import com.gs.obevo.util.vfs.* import com.gs.obevo.util.vfs.FileFilterUtils.* import org.apache.commons.lang3.Validate import org.apache.commons.vfs2.FileFilter import org.eclipse.collections.api.block.function.Function import org.eclipse.collections.api.block.function.Function0 import org.eclipse.collections.api.list.ImmutableList import org.eclipse.collections.api.set.ImmutableSet import org.eclipse.collections.impl.factory.Lists import org.eclipse.collections.impl.factory.Sets import org.eclipse.collections.impl.map.mutable.ConcurrentHashMap import org.slf4j.LoggerFactory class DbDirectoryChangesetReader : FileSourceContext { private val convertDbObjectName: Function<String, String> private val packageMetadataReader: PackageMetadataReader private val packageMetadataCache = ConcurrentHashMap<FileObject, PackageMetadata>() private val tableChangeParser: DbChangeFileParser private val baselineTableChangeParser: DbChangeFileParser private val rerunnableChangeParser: DbChangeFileParser private val deployMetricsCollector: DeployMetricsCollector constructor(convertDbObjectName: Function<String, String>, deployMetricsCollector: DeployMetricsCollector, backwardsCompatibleMode: Boolean, textMarkupDocumentReader: TextMarkupDocumentReader, baselineTableChangeParser: DbChangeFileParser, getChangeType: GetChangeType) { this.packageMetadataReader = PackageMetadataReader(textMarkupDocumentReader) this.convertDbObjectName = convertDbObjectName this.tableChangeParser = TableChangeParser(OldWhitespaceAgnosticDbChangeHashStrategy(), backwardsCompatibleMode, deployMetricsCollector, textMarkupDocumentReader, getChangeType) this.baselineTableChangeParser = baselineTableChangeParser this.rerunnableChangeParser = RerunnableChangeParser(backwardsCompatibleMode, deployMetricsCollector, textMarkupDocumentReader) this.deployMetricsCollector = deployMetricsCollector } @VisibleForTesting constructor(convertDbObjectName: Function<String, String>, tableChangeParser: DbChangeFileParser, baselineTableChangeParser: DbChangeFileParser, rerunnableChangeParser: DbChangeFileParser) { this.packageMetadataReader = PackageMetadataReader(TextMarkupDocumentReader(false)) this.convertDbObjectName = convertDbObjectName this.tableChangeParser = tableChangeParser this.baselineTableChangeParser = baselineTableChangeParser this.rerunnableChangeParser = rerunnableChangeParser this.deployMetricsCollector = DeployMetricsCollectorImpl() } /* * (non-Javadoc) * * @see com.gs.obevo.db.newdb.DbChangeReader#readChanges(java.io.File) */ override fun readChanges(fileSourceParams: FileSourceParams): ImmutableList<ChangeInput> { if (fileSourceParams.isBaseline && baselineTableChangeParser == null) { throw IllegalArgumentException("Cannot invoke readChanges with useBaseline == true if baselineTableChangeParser hasn't been set; baseline reading may not be enabled in your Platform type") } val allChanges = mutableListOf<ChangeInput>() val envSchemas = fileSourceParams.schemaNames.collect(this.convertDbObjectName) Validate.notEmpty(envSchemas.castToSet(), "Environment must have schemas populated") for (sourceDir in fileSourceParams.files) { for (schemaDir in sourceDir.findFiles(BasicFileSelector(and(vcsAware(), directory()), false))) { val schema = schemaDir.name.baseName if (envSchemas.contains(this.convertDbObjectName.valueOf(schema))) { val schemaChanges = fileSourceParams.changeTypes.flatMap { changeType -> val changeTypeDir = this.findDirectoryForChangeType(schemaDir, changeType, fileSourceParams.isLegacyDirectoryStructureEnabled) if (changeTypeDir != null) { if (changeType.isRerunnable) { findChanges(changeType, changeTypeDir, this.rerunnableChangeParser, TrueFileFilter.INSTANCE, schema, fileSourceParams.acceptedExtensions, fileSourceParams.defaultSourceEncoding) } else { findTableChanges(changeType, changeTypeDir, schema, fileSourceParams.isBaseline, fileSourceParams.acceptedExtensions, fileSourceParams.defaultSourceEncoding) } } else { emptyList<ChangeInput>() } } val tableChangeMap = schemaChanges .filter { Sets.immutable.of(ChangeType.TABLE_STR, ChangeType.FOREIGN_KEY_STR).contains(it.changeTypeName) } .groupBy(ChangeInput::getDbObjectKey) val staticDataChanges = schemaChanges.filter { it.changeTypeName.equals(ChangeType.STATICDATA_STR)} // now enrich the staticData objects w/ the information from the tables to facilitate the // deployment order calculation. staticDataChanges.forEach { staticDataChange -> val relatedTableChanges = tableChangeMap.get(staticDataChange.getDbObjectKey()) ?: emptyList() val foreignKeys = relatedTableChanges.filter { it.changeTypeName == ChangeType.FOREIGN_KEY_STR } val fkContent = foreignKeys.map { it.content }.joinToString("\n\n") staticDataChange.setContentForDependencyCalculation(fkContent) } allChanges.addAll(schemaChanges) } else { LOG.info("Skipping schema directory [{}] as it was not defined among the schemas in your system-config.xml file: {}", schema, envSchemas) continue } } } return Lists.immutable.ofAll(allChanges); } /** * We have this here to look for directories in the various places we had specified it in the code before (i.e. * for backwards-compatibility). */ private fun findDirectoryForChangeType(schemaDir: FileObject, changeType: ChangeType, legacyDirectoryStructureEnabled: Boolean): FileObject? { var dir = schemaDir.getChild(changeType.directoryName) if (dir != null && dir.exists()) { return dir } dir = schemaDir.getChild(changeType.directoryName.toUpperCase()) if (dir != null && dir.exists()) { return dir } if (legacyDirectoryStructureEnabled && changeType.directoryNameOld != null) { // for backwards-compatibility dir = schemaDir.getChild(changeType.directoryNameOld) if (dir != null && dir.exists()) { deployMetricsCollector.addMetric("oldDirectoryNameUsed", true) return dir } } return null } private fun findTableChanges(changeType: ChangeType, tableDir: FileObject, schema: String, useBaseline: Boolean, acceptedExtensions: ImmutableSet<String>, sourceEncoding: String): List<ChangeInput> { val baselineFilter = WildcardFileFilter("*.baseline.*") val nonBaselineFiles = findFiles(tableDir, if (this.isUsingChangesConvention(tableDir)) CHANGES_WILDCARD_FILTER else NotFileFilter(baselineFilter), acceptedExtensions) var nonBaselineChanges = parseChanges(changeType, nonBaselineFiles, this.tableChangeParser, schema, sourceEncoding) val nonBaselineChangeMap = nonBaselineChanges.groupBy { it.dbObjectKey } if (useBaseline) { LOG.info("Using the 'useBaseline' mode to read in the db changes") val baselineFiles = findFiles(tableDir, if (this.isUsingChangesConvention(tableDir)) CHANGES_WILDCARD_FILTER else baselineFilter, acceptedExtensions) val baselineChanges = parseChanges(changeType, baselineFiles, this.baselineTableChangeParser, schema, sourceEncoding) for (baselineChange in baselineChanges) { val regularChanges = nonBaselineChangeMap.get(baselineChange.dbObjectKey)!! if (regularChanges.isEmpty()) { throw IllegalArgumentException("Invalid state - expecting a change here for this object key: " + baselineChange.dbObjectKey) } val regularChange = regularChanges.get(0) this.copyDbObjectMetadataOverToBaseline(regularChange, baselineChange) } val baselineDbObjectKeys = baselineChanges.map { it.dbObjectKey }.toSet() LOG.info("Found the following baseline changes: will try to deploy via baseline for these db objects: " + baselineDbObjectKeys.joinToString(",")) nonBaselineChanges = nonBaselineChanges .filterNot { baselineDbObjectKeys.contains(it.dbObjectKey) } .plus(baselineChanges) } return nonBaselineChanges } /** * This is for stuff in the METADATA tag that would be in the changes file but not the baseline file */ private fun copyDbObjectMetadataOverToBaseline(regularChange: ChangeInput, baselineChange: ChangeInput) { baselineChange.setRestrictions(regularChange.getRestrictions()) baselineChange.permissionScheme = regularChange.permissionScheme } private fun findFiles(dir: FileObject, fileFilter: FileFilter, acceptedExtensions: ImmutableSet<String>): List<FileObject> { val positiveSelector = BasicFileSelector( and( fileFilter, not(directory()), not( or( WildcardFileFilter("package-info*"), WildcardFileFilter("*." + OnboardingStrategy.exceptionExtension) ) ) ), vcsAware() ) val candidateFiles = listOf(*dir.findFiles(positiveSelector)) val extensionPartition = candidateFiles.partition { acceptedExtensions.contains(it.name.extension.toLowerCase()) } if (extensionPartition.second.isNotEmpty()) { val message = "Found unexpected file extensions (these will not be deployed!) in directory " + dir + "; expects extensions [" + acceptedExtensions + "], found: " + extensionPartition.second LOG.warn(message) deployMetricsCollector.addListMetric(DeployMetrics.UNEXPECTED_FILE_EXTENSIONS, message) } return extensionPartition.first } private fun parseChanges(changeType: ChangeType, files: List<FileObject>, changeParser: DbChangeFileParser, schema: String, sourceEncoding: String): List<ChangeInput> { return files.flatMap { file -> val packageMetadata = getPackageMetadata(file, sourceEncoding) var encoding: String? = null var metadataSection: TextMarkupDocumentSection? = null if (packageMetadata != null) { encoding = packageMetadata.fileToEncodingMap.get(file.name.baseName) metadataSection = packageMetadata.metadataSection } val charsetStrategy = CharsetStrategyFactory.getCharsetStrategy(encoding ?: sourceEncoding) val objectName = file.name.baseName.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0] try { LOG.debug("Attempting to read file {}", file) changeParser.value(changeType, file, file.getStringContent(charsetStrategy), objectName, schema, metadataSection).castToList() } catch (e: RuntimeException) { throw IllegalArgumentException("Error while parsing file " + file + " of change type " + changeType.name + "; please see the cause in the stack trace below: " + e.message, e) } } } private fun getPackageMetadata(file: FileObject, sourceEncoding: String): PackageMetadata? { return packageMetadataCache.getIfAbsentPut(file.parent, Function0<PackageMetadata> { val packageMetadataFile = file.parent!!.getChild("package-info.txt") // we check for containsKey, as we may end up persisting null as the value in the map if (packageMetadataFile == null || !packageMetadataFile.isReadable) { null } else { packageMetadataReader.getPackageMetadata(packageMetadataFile.getStringContent(CharsetStrategyFactory.getCharsetStrategy(sourceEncoding))) } }) } private fun findChanges(changeType: ChangeType, dir: FileObject, changeParser: DbChangeFileParser, fileFilter: FileFilter, schema: String, acceptedExtensions: ImmutableSet<String>, sourceEncoding: String): List<ChangeInput> { return parseChanges(changeType, findFiles(dir, fileFilter, acceptedExtensions), changeParser, schema, sourceEncoding) } /** * We have this check here for backwards-compatibility * Originally, we required the db files to end in .changes.*, but we now want to have the convention of the stard * file name being the * file that you edit, much like the other ones * * Originally, we wanted to regular name to be for the baseline, but given this is not yet implemented and won't * drive the changes, this was a wrong idea from the start. Eventually, we will have the baseline files in * .baseline.* */ private fun isUsingChangesConvention(dir: FileObject): Boolean { val files = dir.findFiles(BasicFileSelector(CHANGES_WILDCARD_FILTER, false)) val changesConventionUsed = files.size > 0 if (changesConventionUsed) { deployMetricsCollector.addMetric("changesConventionUsed", true) } return changesConventionUsed } companion object { private val LOG = LoggerFactory.getLogger(DbDirectoryChangesetReader::class.java) @VisibleForTesting @JvmStatic val CHANGES_WILDCARD_FILTER: FileFilter = WildcardFileFilter("*.changes.*") } }
apache-2.0
d0e29b55f88b08bbd80b40935a1275c6
51.272727
275
0.683092
5.480056
false
false
false
false
RyanAndroidTaylor/Rapido
rapidosqlite/src/androidTest/java/com/izeni/rapidosqlite/util/Person.kt
1
1674
package com.izeni.rapidosqlite.util import android.content.ContentValues import android.database.Cursor import com.izeni.rapidosqlite.DataConnection import com.izeni.rapidosqlite.addAll import com.izeni.rapidosqlite.get import com.izeni.rapidosqlite.item_builder.ItemBuilder import com.izeni.rapidosqlite.query.QueryBuilder import com.izeni.rapidosqlite.table.Column import com.izeni.rapidosqlite.table.ParentDataTable /** * Created by ner on 2/8/17. */ data class Person(val uuid: String, val name: String, val age: Int, val pets: List<Pet>) : ParentDataTable { companion object { val TABLE_NAME = "Person" val UUID = Column(String::class.java, "Uuid", notNull = true, unique = true) val NAME = Column(String::class.java, "Name", notNull = true) val AGE = Column(Int::class.java, "Age", notNull = true) val COLUMNS = arrayOf(UUID, NAME, AGE) val BUILDER = Builder() } override fun tableName() = TABLE_NAME override fun id() = uuid override fun idColumn() = UUID override fun contentValues() = ContentValues().addAll(COLUMNS, uuid, name, age) override fun getChildren() = pets class Builder : ItemBuilder<Person> { override fun buildItem(cursor: Cursor, dataConnection: DataConnection): Person { val uuid = cursor.get<String>(UUID) val petQuery = QueryBuilder .with(Pet.TABLE_NAME) .whereEquals(Pet.PERSON_UUID, uuid) .build() val pets = dataConnection.findAll(Pet.BUILDER, petQuery) return Person(uuid, cursor.get(NAME), cursor.get(AGE), pets) } } }
mit
fcefaac6b2109a4cd480869e40b15f38
30.603774
108
0.666069
4.174564
false
false
false
false
FurhatRobotics/example-skills
Quiz/src/main/kotlin/furhatos/app/quiz/questions/questionlist.kt
1
5478
package furhatos.app.quiz.questions /** * The questions are structured like * -The question * -The correct answer, followed by alternative pronounciations * -A list of other answers followed by their alternatives */ val questionsEnglish = mutableListOf( Question("How many wives did Henry VIII have?", answer = listOf("6"), alternatives = listOf(listOf("5"), listOf("8"), listOf("4"))), Question("Which country won the 2016 Eurovision Song competition?", answer = listOf("Ukraine"), alternatives = listOf(listOf("Sweden"), listOf("France"), listOf("Finland"))), Question("When was the first circumnavigation of the world completed?", answer = listOf("15 22", "1522"), alternatives = listOf(listOf("14 99", "1499"), listOf("16 32", "1632"), listOf("15 78", "1578"))), Question("Which language is Afrikaans derived from?", answer = listOf("Dutch", "touch"), alternatives = listOf(listOf("German"), listOf("Spanish"), listOf("English"))), Question("The Strip is a famous street in which American city?", answer = listOf("Las Vegas", "vegas"), alternatives = listOf(listOf("Washington DC", "washington"), listOf("Los Angeles", "hollywood", "angeles", "la"), listOf("New York", "York", "New"))), Question("During which decade did Elvis Presley die?", answer = listOf("70s", "seventies", "70"), alternatives = listOf(listOf("50s", "fifties", "50"), listOf("60s", "sixties", "60"), listOf("80s", "eighties", "hades", "80"))), Question("As of 2016, which athlete had won the most Olympic medals?", answer = listOf("Michael Phelps", "Phelps", "Michael"), alternatives = listOf(listOf("Usain Bolt", "Bolt", "Usain"))), Question("Who is the author of the Game of Thrones books?", answer = listOf("George RR Martin", "George Martin", "George", "martin"), alternatives = listOf(listOf("JK Rowling", "Rowling", "Rolling"), listOf("Suzanne Collins", "Collins", "Suzanne"), listOf("JRR Tolkien", "Tolkien", "Talking"))), Question("Which nation won the most gold medals at the 2014 Olympics in Brazil?", answer = listOf("USA", "America"), alternatives = listOf(listOf("Great Britain", "United Kingdom", "Britain"), listOf("China"), listOf("Russia"))), Question("What is the largest freshwater lake in the world?", answer = listOf("Lake Superior", "Superior"), alternatives = listOf(listOf("Lake Victoria", "Victoria"), listOf("Lake Michigan", "Michigan"), listOf("Great Bear Lake", "Great Bear"), listOf("Lake Ontario", "Ontario"))), Question("Where can you find the Sea of Tranquility?", answer = listOf("The moon", "moon"), alternatives = listOf(listOf("Turkey"), listOf("Germany"), listOf("The united states", "united states", "states"))), Question("What is the seventh planet from the Sun?", answer = listOf("Uranus", "anus"), alternatives = listOf(listOf("Pluto"), listOf("Neptune", "tune"), listOf("Saturn"))), Question("In what year did, ABBA, win the Eurovision songfestival?", answer = listOf("19 74", "1974", "74"), alternatives = listOf(listOf("19 78", "1978", "78"), listOf("19 76", "1976", "76"), listOf("19 72", "1972", "72"))), Question("What is the title of the famous novel by George Orwell?", answer = listOf("19 84", "1984"), alternatives = listOf(listOf("The lord of the rings", "lord of the rings", "the rings"), listOf("The Great Gatsby", "great gatsby", "the great", "gatsby"), listOf("Of mice and men", "mice and men"))), Question("Chardonnay. Malaga. and Merlot. are all types of which fruit?", answer = listOf("Grape", "grapes"), alternatives = listOf(listOf("Berry", "berries"), listOf("Melon", "Melons"), listOf("Stone fruit", "stone"))), Question("What did the Wright Brothers invent in 19 02?", answer = listOf("Airplane", "aeroplane", "plane"), alternatives = listOf(listOf("car", "cars", "automobile"), listOf("motorbike", "motor", "bike"), listOf("Fighter jet", "jet", "fighter"))), Question("Who was the first man on the moon?", answer = listOf("Neil Armstrong", "Armstrong", "Neil"), alternatives = listOf(listOf("Buzz Aldrin", "Buzz", "Aldrin"), listOf("Michael Collins", "Michael", "Collins"), listOf("Yuri Gagarin", "Yuri", "Gagarin"))), Question("Which country has more inhabitants?", answer = listOf("Sweden", "Swedish"), alternatives = listOf(listOf("Switzerland", "Swiss"))), Question("Which volcano erupted in 1906 and devastated Naples?", answer = listOf("Mount Vesuvius", "Vesuvius"), alternatives = listOf(listOf("Etna"), listOf("Fuji"), listOf("Krakatoa"))), Question("Which famous tennis player is from Sweden?", answer = listOf("Bjorn Borg", "Borg", "Bjorn"), alternatives = listOf(listOf("Roger Federer", "Federer", "Roger"), listOf("Novak Djokovic", "Novak", "Djokovic"), listOf("Andy Murray", "Andy", "Murray"))) )
mit
6538c866779688774ed0f7ca2a2e3384
60.561798
216
0.591639
4.054774
false
false
false
false
sampsonjoliver/Firestarter
app/src/main/java/com/sampsonjoliver/firestarter/views/dialogs/DatePickerDialogFragment.kt
1
1908
package com.sampsonjoliver.firestarter.views.dialogs import android.app.DatePickerDialog import android.app.Dialog import android.os.Build import android.os.Bundle import android.support.v4.app.DialogFragment import java.util.* class DatePickerDialogFragment : DialogFragment() { companion object { const val ARG_YEAR = "ARG_YEAR" const val ARG_MONTH = "ARG_MONTH" const val ARG_DAY = "ARG_DAY" const val ARG_MIN_DATE = "ARG_MIN_DATE" fun newInstance(year: Int, month: Int, day: Int): DatePickerDialogFragment { return DatePickerDialogFragment().apply { arguments = Bundle(3) arguments.putInt(ARG_YEAR, year) arguments.putInt(ARG_MONTH, month) arguments.putInt(ARG_DAY, day) } } fun newInstance(year: Int, month: Int, day: Int, minDate: Date): DatePickerDialogFragment { return DatePickerDialogFragment().apply { arguments = Bundle(4) arguments.putInt(ARG_YEAR, year) arguments.putInt(ARG_MONTH, month) arguments.putInt(ARG_DAY, day) arguments.putSerializable(ARG_MIN_DATE, minDate) } } } var listener: DatePickerDialog.OnDateSetListener? = null private val year by lazy { arguments.getInt(ARG_YEAR) } private val month by lazy { arguments.getInt(ARG_MONTH) } private val day by lazy { arguments.getInt(ARG_DAY) } private val minDate by lazy { arguments.getSerializable(ARG_MIN_DATE) as Date? } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val picker = DatePickerDialog(activity, listener, year, month, day) if (minDate != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) picker.datePicker.minDate = minDate?.time ?: 0L return picker } }
apache-2.0
241345a8c3c8b90de25efe27827a9486
37.959184
99
0.642034
4.489412
false
false
false
false
yschimke/oksocial
src/main/kotlin/com/baulsupp/okurl/util/HeaderUtil.kt
1
1362
package com.baulsupp.okurl.util import com.baulsupp.oksocial.output.UsageException import com.baulsupp.okurl.util.FileUtil.expectedFile import java.io.File import java.io.IOException // TODO handle duplicate header keys object HeaderUtil { fun headerMap(headers: List<String>?): Map<String, String> { val headerMap = mutableMapOf<String, String>() headers?.forEach { if (it.startsWith("@")) { headerMap.putAll(headerFileMap(it)) } else { val parts = it.split(":".toRegex(), 2).toTypedArray() // TODO: consider better strategy than simple trim val name = parts[0].trim { it <= ' ' } val value = stringValue(parts[1].trim { it <= ' ' }) headerMap[name] = value } } return headerMap.toMap() } private fun headerFileMap(input: String): Map<out String, String> { return try { headerMap(inputFile(input).readLines()) } catch (ioe: IOException) { throw UsageException("failed to read header file", ioe) } } fun stringValue(source: String): String { return if (source.startsWith("@")) { try { inputFile(source).readText() } catch (e: IOException) { throw UsageException(e.toString()) } } else { source } } fun inputFile(path: String): File { return expectedFile(path.substring(1)) } }
apache-2.0
5ba5dceb8bd38cb3fca4aef01a046a67
25.705882
69
0.629956
4.10241
false
false
false
false
yschimke/oksocial
src/main/kotlin/com/baulsupp/okurl/services/coinbase/CoinbaseAuthInterceptor.kt
1
5025
package com.baulsupp.okurl.services.coinbase import com.baulsupp.oksocial.output.OutputHandler import com.baulsupp.okurl.authenticator.Oauth2AuthInterceptor import com.baulsupp.okurl.authenticator.ValidatedCredentials import com.baulsupp.okurl.authenticator.oauth2.Oauth2ServiceDefinition import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token import com.baulsupp.okurl.completion.ApiCompleter import com.baulsupp.okurl.completion.BaseUrlCompleter import com.baulsupp.okurl.completion.CompletionVariableCache import com.baulsupp.okurl.completion.UrlList import com.baulsupp.okurl.credentials.CredentialsStore import com.baulsupp.okurl.credentials.Token import com.baulsupp.okurl.credentials.TokenValue import com.baulsupp.okurl.kotlin.query import com.baulsupp.okurl.kotlin.queryMap import com.baulsupp.okurl.kotlin.queryMapValue import com.baulsupp.okurl.kotlin.requestBuilder import com.baulsupp.okurl.secrets.Secrets import com.baulsupp.okurl.services.coinbase.model.AccountList import okhttp3.FormBody import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Response class CoinbaseAuthInterceptor : Oauth2AuthInterceptor() { override val serviceDefinition = Oauth2ServiceDefinition( "api.coinbase.com", "Coinbase API", "coinbase", "https://developers.coinbase.com/api/v2/", "https://www.coinbase.com/settings/api" ) override suspend fun intercept(chain: Interceptor.Chain, credentials: Oauth2Token): Response { var request = chain.request() request = request.newBuilder().header("Authorization", "Bearer ${credentials.accessToken}") .header("CB-VERSION", "2017-12-17").build() return chain.proceed(request) } override suspend fun authorize( client: OkHttpClient, outputHandler: OutputHandler<Response>, authArguments: List<String> ): Oauth2Token { val clientId = Secrets.prompt("Coinbase Client Id", "coinbase.clientId", "", false) val clientSecret = Secrets.prompt("Coinbase Client Secret", "coinbase.clientSecret", "", true) val scopes = Secrets.promptArray( "Scopes", "coinbase.scopes", listOf( "wallet:accounts:read", "wallet:addresses:read", "wallet:buys:read", "wallet:checkouts:read", "wallet:deposits:read", "wallet:notifications:read", "wallet:orders:read", "wallet:payment-methods:read", "wallet:payment-methods:limits", "wallet:sells:read", "wallet:transactions:read", "wallet:user:read", "wallet:withdrawals:read" // "wallet:accounts:update", // "wallet:accounts:create", // "wallet:accounts:delete", // "wallet:addresses:create", // "wallet:buys:create", // "wallet:checkouts:create", // "wallet:deposits:create", // "wallet:orders:create", // "wallet:orders:refund", // "wallet:payment-methods:delete", // "wallet:sells:create", // "wallet:transactions:send", // "wallet:transactions:request", // "wallet:transactions:transfer", // "wallet:user:update", // "wallet:user:email", // "wallet:withdrawals:create" ) ) return CoinbaseAuthFlow.login(client, outputHandler, clientId, clientSecret, scopes) } override suspend fun renew(client: OkHttpClient, credentials: Oauth2Token): Oauth2Token? { val body = FormBody.Builder() .add("client_id", credentials.clientId!!) .add("client_secret", credentials.clientSecret!!) .add("refresh_token", credentials.refreshToken!!) .add("grant_type", "refresh_token") .build() val request = requestBuilder( "https://api.coinbase.com/oauth/token", TokenValue(credentials) ) .post(body) .build() val responseMap = client.queryMap<Any>(request) // TODO check if refresh token in response? return Oauth2Token( responseMap["access_token"] as String, credentials.refreshToken, credentials.clientId, credentials.clientSecret ) } override suspend fun apiCompleter( prefix: String, client: OkHttpClient, credentialsStore: CredentialsStore, completionVariableCache: CompletionVariableCache, tokenSet: Token ): ApiCompleter { val urlList = UrlList.fromResource(name()) val completer = BaseUrlCompleter(urlList!!, hosts(credentialsStore), completionVariableCache) completer.withCachedVariable(name(), "account_id") { credentialsStore.get(serviceDefinition, tokenSet)?.let { client.query<AccountList>( "https://api.coinbase.com/v2/accounts", tokenSet ).data.map { it.id } } } return completer } override suspend fun validate( client: OkHttpClient, credentials: Oauth2Token ): ValidatedCredentials = ValidatedCredentials( client.queryMapValue<String>( "https://api.coinbase.com/v2/user", TokenValue(credentials), "data", "name" ) ) }
apache-2.0
db00c84a215c8f1723cbf2610fe4242e
33.655172
98
0.691343
4.302226
false
false
false
false
koesie10/AdventOfCode-Solutions-Kotlin
2015/src/main/kotlin/com/koenv/adventofcode/Day19.kt
1
3213
package com.koenv.adventofcode class Day19(input: CharSequence) { private val replacements: Map<String, List<String>> private val lexer: Lexer init { this.replacements = input.lines().map { val parts = it.split(" => ") parts[0] to parts[1] }.groupBy { it.first }.mapValues { it.value.map { it.second } } this.lexer = Lexer(replacements.keys.distinct().toList()) } public fun parse(input: String): List<Lexer.Token> { return lexer.parse(input) } public fun getPossibilities(input: String): List<String> { val tokens = parse(input) val possibilities = arrayListOf<String>() tokens.filter { it.type == Lexer.TokenType.REPLACEMENT }.forEach { token -> replacements[token.text]!!.forEach { replacement -> val text = StringBuilder() tokens.forEach { if (it == token) { text.append(replacement) } else { text.append(it.text) } } possibilities.add(text.toString()) } } return possibilities.distinct() } public fun fromElectronTo(input: String): Int { var target = input var steps = 0 while (target != "e") { replacements.forEach { entry -> entry.value.forEach { if (target.contains(it)) { target = target.substring(0, target.lastIndexOf(it)) + entry.key + target.substring(target.lastIndexOf(it) + it.length) steps++ } } } } return steps } class Lexer(private val replacementPossibilities: List<String>) { private var replacementMaxLength: Int init { this.replacementMaxLength = replacementPossibilities.map { it.length }.max()!! } public fun parse(input: String): List<Token> { val tokens = arrayListOf<Token>() var position = 0 while (position < input.length) { var nowPosition = position val it = StringBuilder() it.append(input[position]) nowPosition++ while (!replacementPossibilities.contains(it.toString()) && it.length < replacementMaxLength && nowPosition < input.length) { it.append(input[nowPosition]) nowPosition++ } if (replacementPossibilities.contains(it.toString())) { tokens.add(Token(position, TokenType.REPLACEMENT, it.toString())) position = nowPosition } else { tokens.add(Token(position, TokenType.TEXT, input[position].toString())) position++ } } return tokens } data class Token(val position: Int, val type: TokenType, val text: String) enum class TokenType { TEXT, REPLACEMENT } } }
mit
0fa8323fb631a02913cb8b28bc27fb0b
30.203883
143
0.50638
5.173913
false
false
false
false
looker-open-source/sdk-codegen
kotlin/src/main/com/looker/rtl/APIMethods.kt
1
3305
/* * The MIT License (MIT) * * Copyright (c) 2019 Looker Data Sciences, Inc. * * 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 com.looker.rtl import java.io.UnsupportedEncodingException import java.net.URLEncoder import java.nio.charset.StandardCharsets @Suppress("UNCHECKED_CAST") open class APIMethods(val authSession: AuthSession) { val authRequest = authSession::authenticate fun <T> ok(response: SDKResponse): T { when (response) { is SDKResponse.SDKErrorResponse<*> -> throw Error(response.value.toString()) is SDKResponse.SDKSuccessResponse<*> -> return response.value as T else -> throw Error("Fail!!") } } inline fun <reified T> get(path: String, queryParams: Values = mapOf(), body: Any? = null): SDKResponse { return authSession.transport.request<T>(HttpMethod.GET, path, queryParams, body, authRequest) } inline fun <reified T> head(path: String, queryParams: Values = mapOf(), body: Any? = null): SDKResponse { return authSession.transport.request<T>(HttpMethod.HEAD, path, queryParams, body, authRequest) } inline fun <reified T> delete(path: String, queryParams: Values = mapOf(), body: Any? = null): SDKResponse { return authSession.transport.request<T>(HttpMethod.DELETE, path, queryParams, body, authRequest) } inline fun <reified T> post(path: String, queryParams: Values = mapOf(), body: Any? = null): SDKResponse { return authSession.transport.request<T>(HttpMethod.POST, path, queryParams, body, authRequest) } inline fun <reified T> put(path: String, queryParams: Values = mapOf(), body: Any? = null): SDKResponse { return authSession.transport.request<T>(HttpMethod.PUT, path, queryParams, body, authRequest) } inline fun <reified T> patch(path: String, queryParams: Values = mapOf(), body: Any? = null): SDKResponse { return authSession.transport.request<T>(HttpMethod.PATCH, path, queryParams, body, authRequest) } fun encodeURI(value: String): String { try { return URLEncoder.encode(value, StandardCharsets.UTF_8.toString()) } catch (ex: UnsupportedEncodingException) { throw RuntimeException(ex.cause) } } }
mit
8c0c3d0571df1ab183b0e5cf609f030f
43.066667
112
0.706808
4.418449
false
false
false
false
mallowigi/a-file-icon-idea
common/src/main/java/com/mallowigi/icons/patchers/ExternalIconsPatcher.kt
1
1776
/* * The MIT License (MIT) * * Copyright (c) 2015-2022 Elior "Mallowigi" Boukhobza * * 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 com.mallowigi.icons.patchers import com.intellij.util.xmlb.annotations.Property import com.thoughtworks.xstream.annotations.XStreamAsAttribute /** External icons patcher. */ @Suppress("UnusedPrivateMember") open class ExternalIconsPatcher : AbstractIconPatcher() { @Property @XStreamAsAttribute private val append: String = "" @Property @XStreamAsAttribute private val name: String = "" @Property @XStreamAsAttribute private val remove: String = "" override val pathToAppend: String get() = append override val pathToRemove: String get() = remove }
mit
2da7d0988431ed2387528922c0d2a346
33.823529
82
0.748311
4.374384
false
false
false
false
wenhaiz/ListenAll
app/src/main/java/com/wenhaiz/himusic/data/MusicRepository.kt
1
3957
package com.wenhaiz.himusic.data import android.content.Context import com.wenhaiz.himusic.data.bean.Album import com.wenhaiz.himusic.data.bean.Artist import com.wenhaiz.himusic.data.bean.Collect import com.wenhaiz.himusic.data.bean.Song import com.wenhaiz.himusic.data.onlineprovider.Xiami import com.wenhaiz.himusic.http.data.RankList internal class MusicRepository(context: Context) : MusicSource { private var musicSource: MusicSource private var curProvider: MusicProvider companion object { @JvmStatic var INSTANCE: MusicRepository? = null @JvmStatic fun getInstance(context: Context): MusicRepository { if (INSTANCE == null) { synchronized(MusicRepository::class.java) { if (INSTANCE == null) { INSTANCE = MusicRepository(context) } } } return INSTANCE!! } } init { //default curProvider = MusicProvider.XIAMI musicSource = Xiami(context) } constructor(sourceProvider: MusicProvider, context: Context) : this(context) { curProvider = sourceProvider when (sourceProvider) { MusicProvider.XIAMI -> { musicSource = Xiami(context) } MusicProvider.QQMUSIC -> { // musicSource = QQ() } MusicProvider.NETEASE -> { // musicSource = NetEase() } } } fun changeMusicSource(provider: MusicProvider, context: Context) { if (provider != curProvider) { when (provider) { MusicProvider.XIAMI -> { musicSource = Xiami(context) } MusicProvider.QQMUSIC -> { // musicSource = QQ() } MusicProvider.NETEASE -> { // musicSource = NetEase() } } } } override fun loadSearchTips(keyword: String, callback: LoadSearchTipsCallback) { musicSource.loadSearchTips(keyword, callback) } override fun searchByKeyword(keyword: String, callback: LoadSearchResultCallback) { musicSource.searchByKeyword(keyword, callback) } override fun loadCollectDetail(collect: Collect, callback: LoadCollectDetailCallback) { musicSource.loadCollectDetail(collect, callback) } override fun loadAlbumDetail(album: Album, callback: LoadAlbumDetailCallback) { musicSource.loadAlbumDetail(album, callback) } override fun loadSongDetail(song: Song, callback: LoadSongDetailCallback) { musicSource.loadSongDetail(song, callback) } override fun loadHotCollect(page: Int, callback: LoadCollectCallback) { musicSource.loadHotCollect(page, callback) } override fun loadNewAlbum(page: Int, callback: LoadAlbumCallback) { musicSource.loadNewAlbum(page, callback) } override fun loadArtistDetail(artist: Artist, callback: LoadArtistDetailCallback) { musicSource.loadArtistDetail(artist, callback) } override fun loadArtistHotSongs(artist: Artist, page: Int, callback: LoadArtistHotSongsCallback) { musicSource.loadArtistHotSongs(artist, page, callback) } override fun loadArtistAlbums(artist: Artist, page: Int, callback: LoadArtistAlbumsCallback) { musicSource.loadArtistAlbums(artist, page, callback) } override fun loadCollectByCategory(category: String, page: Int, callback: LoadCollectByCategoryCallback) { musicSource.loadCollectByCategory(category, page, callback) } override fun loadRankingList(callback: LoadRankingCallback) { musicSource.loadRankingList(callback) } override fun loadRankingDetail(rank: RankList.Rank, callback: LoadRankingDetailCallback) { musicSource.loadRankingDetail(rank, callback) } }
apache-2.0
d5b2606d7483c4e241afa7c6d3da62d2
30.656
110
0.6419
4.879162
false
false
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/ide/inspections/RsSimplifyPrintInspection.kt
3
2018
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RsFormatMacroArgument import org.rust.lang.core.psi.RsMacroCall import org.rust.lang.core.psi.RsVisitor import org.rust.lang.core.psi.ext.macroName /** * Replace `println!("")` with `println!()` available since Rust 1.14.0 */ class RsSimplifyPrintInspection : RsLocalInspectionTool() { override fun getDisplayName() = "println!(\"\") usage" override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitMacroCall(o: RsMacroCall) { val macroName = o.macroName val formatMacroArg = o.formatMacroArgument ?: return if (!(macroName.endsWith("println"))) return if (emptyStringArg(formatMacroArg) == null) return holder.registerProblem( o, "println! macro invocation can be simplified", object : LocalQuickFix { override fun getName() = "Remove unnecessary argument" override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val macro = descriptor.psiElement as RsMacroCall val arg = emptyStringArg(macro.formatMacroArgument!!) ?: return arg.delete() } } ) } } private fun emptyStringArg(arg: RsFormatMacroArgument): PsiElement? { val singeArg = arg.formatMacroArgList.singleOrNull() ?: return null if (singeArg.text != "\"\"") return null return singeArg } }
mit
0389ebfe05795df82fa10f031a29ae88
35.690909
99
0.643707
4.933985
false
false
false
false
semonte/intellij-community
platform/configuration-store-impl/src/ProjectStoreImpl.kt
1
19316
/* * 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 com.intellij.configurationStore import com.intellij.ide.highlighter.ProjectFileType import com.intellij.ide.highlighter.WorkspaceFileType import com.intellij.notification.Notifications import com.intellij.notification.NotificationsManager import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeAndWaitIfNeed import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.* import com.intellij.openapi.components.StateStorage.SaveSession import com.intellij.openapi.components.impl.ServiceManagerImpl import com.intellij.openapi.components.impl.stores.IComponentStore import com.intellij.openapi.components.impl.stores.IProjectStore import com.intellij.openapi.components.impl.stores.StoreUtil import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.impl.ModuleManagerImpl import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectCoreUtil import com.intellij.openapi.project.ex.ProjectNameProvider import com.intellij.openapi.project.impl.ProjectImpl import com.intellij.openapi.project.impl.ProjectManagerImpl.UnableToSaveProjectNotification import com.intellij.openapi.project.impl.ProjectStoreClassProvider import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.Pair import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.ReadonlyStatusHandler import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PathUtilRt import com.intellij.util.SmartList import com.intellij.util.attribute import com.intellij.util.containers.computeIfAny import com.intellij.util.containers.forEachGuaranteed import com.intellij.util.containers.isNullOrEmpty import com.intellij.util.io.* import com.intellij.util.isEmpty import com.intellij.util.lang.CompoundRuntimeException import com.intellij.util.text.nullize import gnu.trove.THashSet import org.jdom.Element import java.io.File import java.io.IOException import java.nio.file.Path import java.nio.file.Paths const val PROJECT_FILE = "\$PROJECT_FILE$" const val PROJECT_CONFIG_DIR = "\$PROJECT_CONFIG_DIR$" val IProjectStore.nameFile: Path get() = Paths.get(directoryStorePath, ProjectImpl.NAME_FILE) internal val PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, false) internal val DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, true) abstract class ProjectStoreBase(override final val project: ProjectImpl) : ComponentStoreImpl(), IProjectStore { // protected setter used in upsource // Zelix KlassMaster - ERROR: Could not find method 'getScheme()' var scheme = StorageScheme.DEFAULT override final var loadPolicy = StateLoadPolicy.LOAD override final fun isOptimiseTestLoadSpeed() = loadPolicy != StateLoadPolicy.LOAD override final fun getStorageScheme() = scheme override abstract val storageManager: StateStorageManagerImpl protected val isDirectoryBased: Boolean get() = scheme == StorageScheme.DIRECTORY_BASED override final fun setOptimiseTestLoadSpeed(value: Boolean) { // we don't load default state in tests as app store does because // 1) we should not do it // 2) it was so before, so, we preserve old behavior (otherwise RunManager will load template run configurations) loadPolicy = if (value) StateLoadPolicy.NOT_LOAD else StateLoadPolicy.LOAD } override fun getProjectFilePath() = storageManager.expandMacro(PROJECT_FILE) override final fun getWorkspaceFilePath() = storageManager.expandMacro(StoragePathMacros.WORKSPACE_FILE) override final fun clearStorages() { storageManager.clearStorages() } override final fun loadProjectFromTemplate(defaultProject: Project) { defaultProject.save() val element = (defaultProject.stateStore as DefaultProjectStoreImpl).getStateCopy() ?: return LOG.runAndLogException { normalizeDefaultProjectElement(defaultProject, element, if (isDirectoryBased) Paths.get(storageManager.expandMacro(PROJECT_CONFIG_DIR)) else null) } (storageManager.getOrCreateStorage(PROJECT_FILE) as XmlElementStorage).setDefaultState(element) } override final fun getProjectBasePath(): String { if (isDirectoryBased) { val path = PathUtilRt.getParentPath(storageManager.expandMacro(PROJECT_CONFIG_DIR)) if (Registry.`is`("store.basedir.parent.detection", true) && PathUtilRt.getFileName(path).startsWith("${Project.DIRECTORY_STORE_FOLDER}.")) { return PathUtilRt.getParentPath(PathUtilRt.getParentPath(path)) } return path } else { return PathUtilRt.getParentPath(projectFilePath) } } // used in upsource protected fun setPath(filePath: String, refreshVfs: Boolean, useOldWorkspaceContentIfExists: Boolean) { val storageManager = storageManager val fs = LocalFileSystem.getInstance() if (filePath.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)) { scheme = StorageScheme.DEFAULT storageManager.addMacro(PROJECT_FILE, filePath) val workspacePath = composeWsPath(filePath) storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, workspacePath) if (refreshVfs) { invokeAndWaitIfNeed { VfsUtil.markDirtyAndRefresh(false, true, false, fs.refreshAndFindFileByPath(filePath), fs.refreshAndFindFileByPath(workspacePath)) } } if (ApplicationManager.getApplication().isUnitTestMode) { // load state only if there are existing files isOptimiseTestLoadSpeed = !File(filePath).exists() } } else { scheme = StorageScheme.DIRECTORY_BASED // if useOldWorkspaceContentIfExists false, so, file path is expected to be correct (we must avoid file io operations) val isDir = !useOldWorkspaceContentIfExists || Paths.get(filePath).isDirectory() val configDir = "${(if (isDir) filePath else PathUtilRt.getParentPath(filePath))}/${Project.DIRECTORY_STORE_FOLDER}" storageManager.addMacro(PROJECT_CONFIG_DIR, configDir) storageManager.addMacro(PROJECT_FILE, "$configDir/misc.xml") storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, "$configDir/workspace.xml") if (!isDir) { val workspace = File(workspaceFilePath) if (!workspace.exists()) { useOldWorkspaceContent(filePath, workspace) } } if (ApplicationManager.getApplication().isUnitTestMode) { // load state only if there are existing files isOptimiseTestLoadSpeed = !Paths.get(filePath).exists() } if (refreshVfs) { invokeAndWaitIfNeed { VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByPath(configDir)) } } } } override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): List<Storage> { val storages = stateSpec.storages if (storages.isEmpty()) { return listOf(PROJECT_FILE_STORAGE_ANNOTATION) } if (isDirectoryBased) { var result: MutableList<Storage>? = null for (storage in storages) { @Suppress("DEPRECATION") if (storage.path != PROJECT_FILE) { if (result == null) { result = SmartList() } result.add(storage) } } if (result.isNullOrEmpty()) { return listOf(PROJECT_FILE_STORAGE_ANNOTATION) } else { result!!.sortWith(deprecatedComparator) // if we create project from default, component state written not to own storage file, but to project file, // we don't have time to fix it properly, so, ancient hack restored result.add(DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION) return result } } else { var result: MutableList<Storage>? = null // FlexIdeProjectLevelCompilerOptionsHolder, FlexProjectLevelCompilerOptionsHolderImpl and CustomBeanRegistry var hasOnlyDeprecatedStorages = true for (storage in storages) { @Suppress("DEPRECATION") if (storage.path == PROJECT_FILE || storage.path == StoragePathMacros.WORKSPACE_FILE) { if (result == null) { result = SmartList() } result.add(storage) if (!storage.deprecated) { hasOnlyDeprecatedStorages = false } } } if (result.isNullOrEmpty()) { return listOf(PROJECT_FILE_STORAGE_ANNOTATION) } else { if (hasOnlyDeprecatedStorages) { result!!.add(PROJECT_FILE_STORAGE_ANNOTATION) } result!!.sortWith(deprecatedComparator) return result } } } override fun isProjectFile(file: VirtualFile): Boolean { if (!file.isInLocalFileSystem || !ProjectCoreUtil.isProjectOrWorkspaceFile(file, file.fileType)) { return false } val filePath = file.path if (!isDirectoryBased) { return filePath == projectFilePath || filePath == workspaceFilePath } return FileUtil.isAncestor(PathUtilRt.getParentPath(projectFilePath), filePath, false) } override fun getDirectoryStorePath(ignoreProjectStorageScheme: Boolean) = if (!ignoreProjectStorageScheme && !isDirectoryBased) null else PathUtilRt.getParentPath(projectFilePath).nullize() override fun getDirectoryStoreFile() = directoryStorePath?.let { LocalFileSystem.getInstance().findFileByPath(it) } override fun getDirectoryStorePathOrBase() = PathUtilRt.getParentPath(projectFilePath) } private open class ProjectStoreImpl(project: ProjectImpl, private val pathMacroManager: PathMacroManager) : ProjectStoreBase(project) { private var lastSavedProjectName: String? = null init { assert(!project.isDefault) } override final fun getPathMacroManagerForDefaults() = pathMacroManager override val storageManager = ProjectStateStorageManager(pathMacroManager.createTrackingSubstitutor(), project) override fun setPath(filePath: String) { setPath(filePath, true, true) } override fun getProjectName(): String { if (!isDirectoryBased) { return PathUtilRt.getFileName(projectFilePath).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION) } val baseDir = projectBasePath val nameFile = nameFile if (nameFile.exists()) { LOG.runAndLogException { nameFile.inputStream().reader().useLines { it.firstOrNull { !it.isEmpty() }?.trim() }?.let { lastSavedProjectName = it return it } } } return ProjectNameProvider.EP_NAME.extensions.computeIfAny { LOG.runAndLogException { it.getDefaultName(project) } } ?: PathUtilRt.getFileName(baseDir).replace(":", "") } private fun saveProjectName() { if (!isDirectoryBased) { return } val currentProjectName = project.name if (lastSavedProjectName == currentProjectName) { return } lastSavedProjectName = currentProjectName val basePath = projectBasePath if (currentProjectName == PathUtilRt.getFileName(basePath)) { // name equals to base path name - just remove name nameFile.delete() } else { if (Paths.get(basePath).isDirectory()) { nameFile.write(currentProjectName.toByteArray()) } } } override fun doSave(saveSessions: List<SaveSession>, readonlyFiles: MutableList<Pair<SaveSession, VirtualFile>>, prevErrors: MutableList<Throwable>?): MutableList<Throwable>? { try { saveProjectName() } catch (e: Throwable) { LOG.error("Unable to store project name", e) } var errors = prevErrors beforeSave(readonlyFiles) errors = super.doSave(saveSessions, readonlyFiles, errors) val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project) if (readonlyFiles.isEmpty()) { for (notification in notifications) { notification.expire() } return errors } if (!notifications.isEmpty()) { throw IComponentStore.SaveCancelledException() } val status = runReadAction { ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(*getFilesList(readonlyFiles)) } if (status.hasReadonlyFiles()) { dropUnableToSaveProjectNotification(project, status.readonlyFiles) throw IComponentStore.SaveCancelledException() } val oldList = readonlyFiles.toTypedArray() readonlyFiles.clear() for (entry in oldList) { errors = executeSave(entry.first, readonlyFiles, errors) } CompoundRuntimeException.throwIfNotEmpty(errors) if (!readonlyFiles.isEmpty()) { dropUnableToSaveProjectNotification(project, getFilesList(readonlyFiles)) throw IComponentStore.SaveCancelledException() } return errors } protected open fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) { } } private fun dropUnableToSaveProjectNotification(project: Project, readOnlyFiles: Array<VirtualFile>) { val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project) if (notifications.isEmpty()) { Notifications.Bus.notify(UnableToSaveProjectNotification(project, readOnlyFiles), project) } else { notifications[0].myFiles = readOnlyFiles } } private fun getFilesList(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) = Array(readonlyFiles.size) { readonlyFiles[it].second } private class ProjectWithModulesStoreImpl(project: ProjectImpl, pathMacroManager: PathMacroManager) : ProjectStoreImpl(project, pathMacroManager) { override fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) { super.beforeSave(readonlyFiles) for (module in (ModuleManager.getInstance(project)?.modules ?: Module.EMPTY_ARRAY)) { module.stateStore.save(readonlyFiles) } } } // used in upsource class PlatformLangProjectStoreClassProvider : ProjectStoreClassProvider { override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> { return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectWithModulesStoreImpl::class.java } } private class PlatformProjectStoreClassProvider : ProjectStoreClassProvider { override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> { return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectStoreImpl::class.java } } private fun composeWsPath(filePath: String) = "${FileUtilRt.getNameWithoutExtension(filePath)}${WorkspaceFileType.DOT_DEFAULT_EXTENSION}" private fun useOldWorkspaceContent(filePath: String, ws: File) { val oldWs = File(composeWsPath(filePath)) if (!oldWs.exists()) { return } try { FileUtil.copyContent(oldWs, ws) } catch (e: IOException) { LOG.error(e) } } private fun removeWorkspaceComponentConfiguration(defaultProject: Project, element: Element) { val componentElements = element.getChildren("component") if (componentElements.isEmpty()) { return } val workspaceComponentNames = THashSet(listOf("GradleLocalSettings")) @Suppress("DEPRECATION") val projectComponents = defaultProject.getComponents(PersistentStateComponent::class.java) projectComponents.forEachGuaranteed { getNameIfWorkspaceStorage(it.javaClass)?.let { workspaceComponentNames.add(it) } } ServiceManagerImpl.processAllImplementationClasses(defaultProject as ProjectImpl) { aClass, pluginDescriptor -> getNameIfWorkspaceStorage(aClass)?.let { workspaceComponentNames.add(it) } true } val iterator = componentElements.iterator() for (componentElement in iterator) { val name = componentElement.getAttributeValue("name") ?: continue if (workspaceComponentNames.contains(name)) { iterator.remove() } } return } // public only to test fun normalizeDefaultProjectElement(defaultProject: Project, element: Element, projectConfigDir: Path?) { LOG.runAndLogException { removeWorkspaceComponentConfiguration(defaultProject, element) } if (projectConfigDir == null) { return } LOG.runAndLogException { val iterator = element.getChildren("component").iterator() for (component in iterator) { val componentName = component.getAttributeValue("name") fun writeProfileSettings(schemeDir: Path) { component.removeAttribute("name") if (!component.isEmpty()) { val wrapper = Element("component").attribute("name", componentName) component.name = "settings" wrapper.addContent(component) JDOMUtil.write(wrapper, schemeDir.resolve("profiles_settings.xml").outputStream(), "\n") } } when (componentName) { "InspectionProjectProfileManager" -> { iterator.remove() val schemeDir = projectConfigDir.resolve("inspectionProfiles") convertProfiles(component.getChildren("profile").iterator(), componentName, schemeDir) component.removeChild("version") writeProfileSettings(schemeDir) } "CopyrightManager" -> { iterator.remove() val schemeDir = projectConfigDir.resolve("copyright") convertProfiles(component.getChildren("copyright").iterator(), componentName, schemeDir) writeProfileSettings(schemeDir) } ModuleManagerImpl.COMPONENT_NAME -> { iterator.remove() } } } } } private fun convertProfiles(profileIterator: MutableIterator<Element>, componentName: String, schemeDir: Path) { for (profile in profileIterator) { val schemeName = profile.getChildren("option").find { it.getAttributeValue("name") == "myName" }?.getAttributeValue("value") ?: continue profileIterator.remove() val wrapper = Element("component").attribute("name", componentName) wrapper.addContent(profile) val path = schemeDir.resolve("${FileUtil.sanitizeFileName(schemeName, true)}.xml") JDOMUtil.write(wrapper, path.outputStream(), "\n") } } private fun getNameIfWorkspaceStorage(aClass: Class<*>): String? { val stateAnnotation = StoreUtil.getStateSpec(aClass) if (stateAnnotation == null || stateAnnotation.name.isNullOrEmpty()) { return null } val storage = stateAnnotation.storages.sortByDeprecated().firstOrNull() ?: return null return if (storage.path == StoragePathMacros.WORKSPACE_FILE) stateAnnotation.name else null }
apache-2.0
6340ce2c7ee5ab817b740d7f1c11c299
36.076775
191
0.735608
5.185503
false
false
false
false
emufog/emufog
src/test/kotlin/emufog/graph/ASTest.kt
1
7495
/* * MIT License * * Copyright (c) 2019 emufog contributors * * 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 emufog.graph import emufog.container.DeviceContainer import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertNotEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows internal class ASTest { private val defaultSystem = AS(0) @Test fun `test the default init`() { assertEquals(0, defaultSystem.id) assertEquals(0, defaultSystem.backboneNodes.size) assertEquals(0, defaultSystem.edgeDeviceNodes.size) assertEquals(0, defaultSystem.edgeNodes.size) } @Test fun `getNode should return the respective node`() { val system = AS(0) assertNull(system.getNode(1)) val node = system.createBackboneNode(1) assertEquals(node, system.getNode(1)) } @Test fun `hashCode function should return id`() { assertEquals(0, defaultSystem.hashCode()) } @Test fun `toString function should include the id`() { assertEquals("AS: 0", defaultSystem.toString()) } @Test fun `equals with different system with same id`() { val system = AS(0) assertEquals(system, defaultSystem) assertFalse(system === defaultSystem) } @Test fun `equals with different system with different id`() { val system = AS(1) assertNotEquals(system, defaultSystem) assertFalse(system === defaultSystem) } @Test fun `equals with same object`() { assertEquals(defaultSystem, defaultSystem) } @Test fun `equals with null`() { assertNotEquals(defaultSystem, null) } @Test fun `create an edge node`() { val system = AS(1) val edgeNode = system.createEdgeNode(42) assertEquals(42, edgeNode.id) val actual = system.getEdgeNode(42) assertNotNull(actual) assertEquals(42, actual!!.id) assertTrue(system.containsNode(edgeNode)) assertTrue(system.edgeNodes.contains(edgeNode)) } @Test fun `create a backbone node`() { val system = AS(1) val backboneNode = system.createBackboneNode(42) assertEquals(42, backboneNode.id) val actual = system.getBackboneNode(42) assertNotNull(actual) assertEquals(42, actual!!.id) assertTrue(system.containsNode(backboneNode)) assertTrue(system.backboneNodes.contains(backboneNode)) } @Test fun `create an edge device node`() { val system = AS(1) val container = DeviceContainer("docker", "tag", 1, 1F, 1, 1F) val edgeDeviceNode = system.createEdgeDeviceNode(42, EdgeEmulationNode("1.2.3.4", container)) assertEquals(42, edgeDeviceNode.id) val actual = system.getEdgeDeviceNode(42) assertNotNull(actual) assertEquals(42, actual!!.id) assertTrue(system.containsNode(edgeDeviceNode)) assertTrue(system.edgeDeviceNodes.contains(edgeDeviceNode)) } @Test fun `containsNode on empty AS should return false`() { assertFalse(defaultSystem.containsNode(BackboneNode(1, defaultSystem))) } @Test fun `getBackboneNode that does not exist should return null`() { assertNull(defaultSystem.getBackboneNode(42)) } @Test fun `getEdgeNode that does not exist should return null`() { assertNull(defaultSystem.getEdgeNode(42)) } @Test fun `getEdgeDeviceNode that does not exist should return null`() { assertNull(defaultSystem.getEdgeDeviceNode(42)) } @Test fun `replace a backbone node with an edge node`() { val system = AS(1) val backboneNode = system.createBackboneNode(42) val edgeNode = system.replaceByEdgeNode(backboneNode) assertEquals(backboneNode, edgeNode) assertEquals(42, edgeNode.id) assertEquals(system, edgeNode.system) assertNull(system.getBackboneNode(42)) assertNull(system.backboneNodes.firstOrNull { it === backboneNode }) assertEquals(edgeNode, system.getEdgeNode(42)) assertTrue(system.edgeNodes.contains(edgeNode)) } @Test fun `replace a backbone node with an edge device node`() { val system = AS(1) val backboneNode = system.createBackboneNode(42) val container = DeviceContainer("abc", "tag", 1024, 1F, 1, 1.5F) val emulationNode = EdgeEmulationNode("1.2.3.4", container) val edgeDeviceNode = system.replaceByEdgeDeviceNode(backboneNode, emulationNode) assertEquals(backboneNode, edgeDeviceNode) assertEquals(42, edgeDeviceNode.id) assertEquals(system, edgeDeviceNode.system) assertEquals(emulationNode, edgeDeviceNode.emulationNode) assertNull(system.getBackboneNode(42)) assertNull(system.backboneNodes.firstOrNull { it === backboneNode }) assertEquals(edgeDeviceNode, system.getEdgeDeviceNode(42)) assertTrue(system.edgeDeviceNodes.contains(edgeDeviceNode)) } @Test fun `replace an edge node with a backbone node`() { val system = AS(1) val edgeNode = system.createEdgeNode(42) val backboneNode = system.replaceByBackboneNode(edgeNode) assertEquals(edgeNode, backboneNode) assertEquals(42, backboneNode.id) assertEquals(system, backboneNode.system) assertNull(system.getEdgeNode(42)) assertNull(system.edgeNodes.firstOrNull { it === edgeNode }) assertEquals(backboneNode, system.getBackboneNode(42)) assertTrue(system.backboneNodes.contains(backboneNode)) } @Test fun `replacement call should fail with an exception of node is not part of the AS`() { val node = AS(1024).createBackboneNode(1) assertThrows<IllegalArgumentException> { defaultSystem.replaceByEdgeNode(node) } } @Test fun `replacement call should fail with an exception if node cannot be removed from the AS`() { val system1 = AS(0) val system2 = AS(0) val node = system1.createBackboneNode(1) assertThrows<IllegalStateException> { system2.replaceByEdgeNode(node) } } }
mit
118db813cc1f62c6987bb679c8e3105c
35.038462
101
0.687925
4.66107
false
true
false
false
petrbalat/jlib
src/main/java/cz/softdeluxe/jlib/io/IOHelpers.kt
1
4460
package cz.softdeluxe.jlib.io import cz.petrbalat.utils.datetime.toLocalDateTime import cz.softdeluxe.jlib.GIGA import cz.softdeluxe.jlib.randomString import cz.softdeluxe.jlib.removeDiakritiku import org.imgscalr.Scalr import org.springframework.web.multipart.MultipartFile import java.awt.image.BufferedImage import java.io.* import java.net.URLConnection import java.nio.charset.Charset import java.nio.file.* import java.nio.file.attribute.BasicFileAttributes import java.time.LocalDateTime import java.util.* import java.util.zip.ZipEntry import java.util.zip.ZipInputStream import javax.imageio.ImageIO /** * zkopíruje do adresáře s path. * odstraní z názvu diakritiku, mezery apod a přidá do názvu random string */ fun MultipartFile.copyTo(path: String, pathPrepend: String = ""): String { return inputStream.use { it.copyTo(originalFilename, path, pathPrepend) } } /** * zkopíruje do adresáře s path. * odstraní z názvu diakritiku, mezery apod a přidá do názvu random string */ fun InputStream.copyTo(originalFilename:String, path: String, pathPrepend: String = ""): String { val origName = originalFilename.removeDiakritiku().replace(" ".toRegex(), "") val before = if (pathPrepend.isEmpty()) randomString(4) else pathPrepend val filename = "$before-${randomString(4).toLowerCase()}-$origName" val uploadFile = File(path, filename) assert(uploadFile.createNewFile()) FileOutputStream(uploadFile, false).use { this.use { inputStream -> inputStream.copyTo(it) } } return filename } fun File.createThumbnail(targetSize: Int, mode: Scalr.Mode = Scalr.Mode.FIT_TO_WIDTH, pathAppend: String = "thumb"): File { val image: BufferedImage = ImageIO.read(File(path)) val resizeImage: BufferedImage = Scalr.resize(image, Scalr.Method.QUALITY, mode, targetSize) val file = File("$directory/$nameWithoutExtension-$pathAppend.$extension") ImageIO.write(resizeImage, extension, file) return file } fun ZipInputStream.entrySequence(): Sequence<ZipEntry> { return generateSequence { nextEntry } } fun ZipInputStream.contentSequence(charsets: Charset = Charsets.UTF_8): Sequence<Pair<ZipEntry, String>> { return entrySequence().map { zipEntry -> val ous = ByteArrayOutputStream() this.writeTo(ous) val content = String(ous.toByteArray(), charsets) Pair(zipEntry, content) } } fun ZipInputStream.writeTo(outputStream: OutputStream): Unit { val buffer = ByteArray(DEFAULT_BUFFER_SIZE) outputStream.use { fos -> while (true) { val len = this.read(buffer) if (len <= 0) { break } fos.write(buffer, 0, len) } } } fun classPath(clazz: Class<Any>): Path { val classPath = Paths.get(clazz.protectionDomain.codeSource.location.toURI()) return Paths.get("$classPath").toRealPath() } val File.directory: File get() = if (isDirectory) this else parentFile!! val File.probeContentType: String? get() = Files.probeContentType(toPath()) ?: URLConnection.guessContentTypeFromName(name) fun File.lastModifiedTime(): LocalDateTime { val path = this.toPath() return Files.readAttributes(path, BasicFileAttributes::class.java).lastModifiedTime().toInstant().toLocalDateTime() } const val IMAGE_TYPE: String = "image" val File.typeByExtension: String get() = when (extension.toLowerCase()) { "pdf" -> "pdf" "avi", "mkv", "mp4", "vob", "wmv", "mpg", "mpeg", "3gp", "flv" -> "video" "jpg", "jpeg", "gif", "png" -> IMAGE_TYPE "doc", "docx", "odt" -> "doc" "mp3" -> "audio" else -> "unknown" } fun File.fileSystemSpace(unit: Double = GIGA): FileSystemSpaceDto { val dto = FileSystemSpaceDto() dto.freeSpace = freeSpace / unit dto.usableSpace = usableSpace / unit dto.totalSpace = totalSpace / unit return dto } fun File.loadAsProperties(): Properties { return inputStream().use { Properties().apply { this.load(it) } } } /** * zkopíruje do souboru */ fun InputStream.toFile(file:File): Long = this.use { ins -> file.outputStream().use { ins.copyTo(it) } } class FileSystemSpaceDto { var freeSpace: Double = 0.0 var usableSpace: Double = 0.0 var totalSpace: Double = 0.0 } fun File.asFileSystem(): FileSystem = FileSystems.newFileSystem(this.toPath(), null)
apache-2.0
601168dab05cd672eca766308bafc085
29.861111
123
0.684222
3.758883
false
false
false
false
herbeth1u/VNDB-Android
app/src/main/java/com/booboot/vndbandroid/model/vnstat/SimilarNovel.kt
1
916
package com.booboot.vndbandroid.model.vnstat data class SimilarNovel( var novelId: Int = 0, var similarity: Float = 0f, var title: String = "", var votecount: String? = null, var popularity: String? = null, var bayesianRating: String? = null, var meanRating: String? = null, var released: String? = null, var image: String? = null, var predictedRating: Float = 0f ) { fun imageLink(): String = IMAGE_LINK + image fun similarityPercentage(): Double = Math.floor(similarity * 1000 + 0.5) / 10 fun predictedRatingPercentage(): Double = Math.round(predictedRating * 10 * 100.0).toDouble() / 100.0 fun setNovelId(novelId: String) { this.novelId = novelId.toInt() } fun setSimilarity(similarity: String) { this.similarity = similarity.toFloat() } companion object { const val IMAGE_LINK = "http://i.vnstat.net/" } }
gpl-3.0
e59d966d3b31d4da07fbca650d52f70b
27.625
105
0.643013
3.785124
false
false
false
false
PSPDFKit-labs/QuickDemo
app/src/main/kotlin/com/pspdfkit/labs/quickdemo/service/DemoModeTileService.kt
1
1656
/* * Copyright (c) 2016-2019 PSPDFKit GmbH. All rights reserved. * * THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW * AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE PSPDFKIT LICENSE AGREEMENT. * UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES. * This notice may not be removed from this file */ package com.pspdfkit.labs.quickdemo.service import android.content.Intent import android.graphics.drawable.Icon import android.service.quicksettings.Tile import android.service.quicksettings.TileService import com.pspdfkit.labs.quickdemo.DemoMode import com.pspdfkit.labs.quickdemo.R import com.pspdfkit.labs.quickdemo.activity.SetupGuideActivity class DemoModeTileService : TileService() { private lateinit var demoMode: DemoMode override fun onCreate() { super.onCreate() demoMode = DemoMode.get(this) } override fun onStartListening() { qsTile.icon = Icon.createWithResource(this, R.drawable.ic_demo_mode) qsTile.label = "Demo mode" updateIcon() } override fun onClick() { if (!demoMode.requiredPermissionsGranted || !demoMode.demoModeAllowed) { startActivityAndCollapse(SetupGuideActivity.intent(this)) return } demoMode.enabled = !demoMode.enabled updateIcon() val it = Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS) sendBroadcast(it) } private fun updateIcon() { qsTile.state = if (demoMode.enabled) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE qsTile.updateTile() } }
mit
487dee265e3d5cc9e395b0da6e61fe31
30.865385
101
0.714976
4.268041
false
false
false
false
jcgay/gradle-notifier
src/main/kotlin/fr/jcgay/gradle/notifier/NotifierListener.kt
1
1986
package fr.jcgay.gradle.notifier import fr.jcgay.gradle.notifier.Status.FAILURE import fr.jcgay.gradle.notifier.Status.SUCCESS import fr.jcgay.gradle.notifier.extension.TimeThreshold import fr.jcgay.notification.Notification import fr.jcgay.notification.Notifier import fr.jcgay.notification.SendNotificationException import org.gradle.BuildAdapter import org.gradle.BuildResult import org.slf4j.LoggerFactory class NotifierListener(val notifier: Notifier, private val timer: Clock, private val threshold: TimeThreshold): BuildAdapter() { private val logger = LoggerFactory.getLogger(NotifierListener::class.java) init { logger.debug("Will send notification with: {} if execution last more than {}", notifier, threshold) } override fun buildFinished(result: BuildResult) { try { if (TimeThreshold(timer) >= threshold || notifier.isPersistent) { val status = status(result) val notification = Notification.builder() .title(result.gradle?.rootProject?.name) .message(message(result)) .icon(status.icon) .subtitle(status.message) .level(status.level) .build() logger.debug("Sending notification: {}", notification) notifier.send(notification) } } catch (e: SendNotificationException) { logger.warn("Error while sending notification.", e) } finally { notifier.close() } } private fun message(result: BuildResult): String? { return if (hasSucceeded(result)) { "Done in: ${timer.getTime()}." } else { result.failure?.message ?: "Build Failed." } } private fun status(result: BuildResult): Status = if (hasSucceeded(result)) SUCCESS else FAILURE private fun hasSucceeded(result: BuildResult): Boolean = result.failure == null }
mit
fddc40d5ae717c3e94da9c7867d8ce39
35.777778
128
0.641994
4.785542
false
false
false
false
rei-m/android_hyakuninisshu
state/src/main/java/me/rei_m/hyakuninisshu/state/question/action/StartAnswerQuestionAction.kt
1
1245
/* * Copyright (c) 2020. Rei Matsushita * * 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 me.rei_m.hyakuninisshu.state.question.action import me.rei_m.hyakuninisshu.state.core.Action import me.rei_m.hyakuninisshu.state.question.model.QuestionState /** * 問題の回答を開始するアクション. */ sealed class StartAnswerQuestionAction(override val error: Throwable? = null) : Action { class Success(val state: QuestionState.InAnswer) : StartAnswerQuestionAction() { override fun toString() = "$name(state=$state)" } class Failure(error: Throwable) : StartAnswerQuestionAction(error) { override fun toString() = "$name(error=$error)" } override val name = "StartAnswerQuestionAction" }
apache-2.0
e452121c54684ebbadf11d6afbb80f71
35.818182
112
0.739095
4.146758
false
false
false
false
sangcomz/FishBun
FishBun/src/main/java/com/sangcomz/fishbun/FishBunCreator.kt
1
8321
package com.sangcomz.fishbun import android.content.Context import android.content.Intent import android.graphics.drawable.Drawable import android.net.Uri import androidx.activity.result.ActivityResultLauncher import com.sangcomz.fishbun.ui.album.ui.AlbumActivity import com.sangcomz.fishbun.ui.picker.PickerActivity import kotlin.collections.ArrayList /** * Created by sangcomz on 17/05/2017. */ class FishBunCreator(private val fishBun: FishBun, private val fishton: Fishton) : BaseProperty, CustomizationProperty { private var requestCode = FishBun.FISHBUN_REQUEST_CODE override fun setSelectedImages(selectedImages: ArrayList<Uri>): FishBunCreator = this.apply { fishton.selectedImages.addAll(selectedImages) } override fun setAlbumThumbnailSize(size: Int): FishBunCreator = apply { fishton.albumThumbnailSize = size } override fun setPickerSpanCount(spanCount: Int): FishBunCreator = this.apply { fishton.photoSpanCount = if (spanCount <= 0) 3 else spanCount } @Deprecated("instead setMaxCount(count)", ReplaceWith("setMaxCount(count)")) override fun setPickerCount(count: Int): FishBunCreator = this.apply { setMaxCount(count) } override fun setMaxCount(count: Int): FishBunCreator = this.apply { fishton.maxCount = if (count <= 0) 1 else count } override fun setMinCount(count: Int): FishBunCreator = this.apply { fishton.minCount = if (count <= 0) 1 else count } override fun setActionBarTitleColor(actionbarTitleColor: Int): FishBunCreator = this.apply { fishton.colorActionBarTitle = actionbarTitleColor } override fun setActionBarColor(actionbarColor: Int): FishBunCreator = this.apply { fishton.colorActionBar = actionbarColor } override fun setActionBarColor(actionbarColor: Int, statusBarColor: Int): FishBunCreator = this.apply { fishton.colorActionBar = actionbarColor fishton.colorStatusBar = statusBarColor } override fun setActionBarColor( actionbarColor: Int, statusBarColor: Int, isStatusBarLight: Boolean ): FishBunCreator = this.apply { fishton.colorActionBar = actionbarColor fishton.colorStatusBar = statusBarColor fishton.isStatusBarLight = isStatusBarLight } @Deprecated("instead setCamera(count)", ReplaceWith("hasCameraInPickerPage(mimeType)")) override fun setCamera(isCamera: Boolean): FishBunCreator = this.apply { fishton.hasCameraInPickerPage = isCamera } override fun hasCameraInPickerPage(hasCamera: Boolean): FishBunCreator = this.apply { fishton.hasCameraInPickerPage = hasCamera } @Deprecated("To be deleted along with the startAlbum function") override fun setRequestCode(requestCode: Int): FishBunCreator = this.apply { this.requestCode = requestCode } override fun textOnNothingSelected(message: String): FishBunCreator = this.apply { fishton.messageNothingSelected = message } override fun textOnImagesSelectionLimitReached(message: String): FishBunCreator = this.apply { fishton.messageLimitReached = message } override fun setButtonInAlbumActivity(isButton: Boolean): FishBunCreator = this.apply { fishton.hasButtonInAlbumActivity = isButton } override fun setReachLimitAutomaticClose(isAutomaticClose: Boolean): FishBunCreator = this.apply { fishton.isAutomaticClose = isAutomaticClose } override fun setAlbumSpanCount( portraitSpanCount: Int, landscapeSpanCount: Int ): FishBunCreator = this.apply { fishton.albumPortraitSpanCount = portraitSpanCount fishton.albumLandscapeSpanCount = landscapeSpanCount } override fun setAlbumSpanCountOnlyLandscape(landscapeSpanCount: Int): FishBunCreator = this.apply { fishton.albumLandscapeSpanCount = landscapeSpanCount } override fun setAlbumSpanCountOnlPortrait(portraitSpanCount: Int): FishBunCreator = this.apply { fishton.albumPortraitSpanCount = portraitSpanCount } override fun setAllViewTitle(allViewTitle: String): FishBunCreator = this.apply { fishton.titleAlbumAllView = allViewTitle } override fun setActionBarTitle(actionBarTitle: String): FishBunCreator = this.apply { fishton.titleActionBar = actionBarTitle } override fun setHomeAsUpIndicatorDrawable(icon: Drawable?): FishBunCreator = this.apply { fishton.drawableHomeAsUpIndicator = icon } override fun setDoneButtonDrawable(icon: Drawable?): FishBunCreator = this.apply { fishton.drawableDoneButton = icon } override fun setAllDoneButtonDrawable(icon: Drawable?): FishBunCreator = this.apply { fishton.drawableAllDoneButton = icon } override fun setIsUseAllDoneButton(isUse: Boolean): FishBunCreator = this.apply { fishton.isUseAllDoneButton = isUse } @Deprecated("instead setMaxCount(count)", ReplaceWith("exceptMimeType(mimeType)")) override fun exceptGif(isExcept: Boolean): FishBunCreator = this.apply { fishton.exceptMimeTypeList = arrayListOf(MimeType.GIF) } override fun exceptMimeType(exceptMimeTypeList: List<MimeType>) = this.apply { fishton.exceptMimeTypeList = exceptMimeTypeList } override fun setMenuDoneText(text: String?): FishBunCreator = this.apply { fishton.strDoneMenu = text } override fun setMenuAllDoneText(text: String?): FishBunCreator = this.apply { fishton.strAllDoneMenu = text } override fun setMenuTextColor(color: Int): FishBunCreator = this.apply { fishton.colorTextMenu = color } override fun setIsUseDetailView(isUse: Boolean): FishBunCreator = this.apply { fishton.isUseDetailView = isUse } override fun setIsShowCount(isShow: Boolean): FishBunCreator = this.apply { fishton.isShowCount = isShow } override fun setSelectCircleStrokeColor(strokeColor: Int): FishBunCreator = this.apply { fishton.colorSelectCircleStroke = strokeColor } override fun isStartInAllView(isStartInAllView: Boolean): FishBunCreator = this.apply { fishton.isStartInAllView = isStartInAllView } override fun setSpecifyFolderList(specifyFolderList: List<String>) = this.apply { fishton.specifyFolderList = specifyFolderList } private fun prepareStartAlbum(context: Context) { checkNotNull(fishton.imageAdapter) exceptionHandling() setDefaultValue(context) } @Deprecated("instead startAlbumWithOnActivityResult(requestCode)", ReplaceWith("startAlbumWithOnActivityResult(requestCode)")) override fun startAlbum() { val fishBunContext = fishBun.fishBunContext val context = fishBunContext.getContext() prepareStartAlbum(context) fishBunContext.startActivityForResult(getIntent(context), requestCode) } override fun startAlbumWithOnActivityResult(requestCode: Int) { val fishBunContext = fishBun.fishBunContext val context = fishBunContext.getContext() prepareStartAlbum(context) fishBunContext.startActivityForResult(getIntent(context), requestCode) } override fun startAlbumWithActivityResultCallback(activityResultLauncher: ActivityResultLauncher<Intent>) { val fishBunContext = fishBun.fishBunContext val context = fishBunContext.getContext() prepareStartAlbum(context) fishBunContext.startWithRegisterForActivityResult(activityResultLauncher, getIntent(context)) } private fun getIntent(context: Context): Intent = if (fishton.isStartInAllView) { PickerActivity.getPickerActivityIntent(context, 0L, fishton.titleAlbumAllView, 0) } else { Intent(context, AlbumActivity::class.java) } private fun setDefaultValue(context: Context) { with(fishton) { setDefaultMessage(context) setMenuTextColor() setDefaultDimen(context) } } private fun exceptionHandling() { if (fishton.hasCameraInPickerPage) { fishton.hasCameraInPickerPage = fishton.specifyFolderList.isEmpty() } } }
apache-2.0
8fa1184621bf8724126ccbf62f35e32a
34.258475
130
0.71626
5.226759
false
false
false
false
JanYoStudio/WhatAnime
app/src/main/java/pw/janyo/whatanime/utils/FileUtil.kt
1
3028
package pw.janyo.whatanime.utils import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.os.Environment import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import pw.janyo.whatanime.context import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.nio.channels.FileChannel import java.security.MessageDigest import kotlin.math.max import kotlin.math.min private const val CACHE_IMAGE_FILE_NAME = "cacheImage" /** * 获取缓存文件 * @return 缓存文件(需要判断是否存在,如果返回为空说明目录权限有问题) */ fun File.getCacheFile(): File? { val saveParent = context.getExternalFilesDir(CACHE_IMAGE_FILE_NAME) ?: return null if (!saveParent.exists()) saveParent.mkdirs() if (saveParent.isDirectory || saveParent.delete() && saveParent.mkdirs()) { val md5Name = absolutePath.md5() return File(saveParent, md5Name) } return null } @Throws(IOException::class) private suspend fun <T : InputStream> T.copyToFile(outputFile: File) { withContext(Dispatchers.IO) { if (!outputFile.parentFile!!.exists()) outputFile.parentFile?.mkdirs() if (outputFile.exists()) outputFile.delete() FileOutputStream(outputFile).use { [email protected](it) } } } /** * 将Uri的内容克隆到临时文件,然后返回临时文件 * * @return 临时文件 */ suspend fun Uri.cloneUriToFile(): File? { val parent = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) ?: return null if (!parent.exists()) parent.mkdirs() if (parent.isDirectory || parent.delete() && parent.mkdirs()) { val file = File(parent, this.toString().sha1()) context.contentResolver.openInputStream(this)!!.use { it.copyToFile(file) } return file } return null } private fun File.zoomBitmap(): Bitmap { val maxHeight = 640 val maxWidth = 640 val options = BitmapFactory.Options() options.inJustDecodeBounds = true BitmapFactory.decodeFile(absolutePath, options) val scaleW = max(maxWidth, options.outWidth) / (min(maxWidth, options.outWidth) * 1.0) - 0.5 val scaleH = max(maxHeight, options.outHeight) / (min(maxHeight, options.outHeight) * 1.0) - 0.5 options.inSampleSize = max(scaleW, scaleH).toInt() options.inJustDecodeBounds = false return BitmapFactory.decodeFile(absolutePath, options) } @Throws(IOException::class) suspend fun File.md5(): String { return withContext(Dispatchers.IO) { val messageDigest = MessageDigest.getInstance("MD5") messageDigest.update( FileInputStream(this@md5).channel.map( FileChannel.MapMode.READ_ONLY, 0, length() ) ) val bytes = messageDigest.digest() toHex(bytes) } }
apache-2.0
a6f7786d3ec465bd5ca88dfa58fe42ad
28.989691
100
0.680536
4.027701
false
false
false
false
firebase/codelab-friendlychat-android
build-android/app/src/main/java/com/google/firebase/codelab/friendlychat/MainActivity.kt
1
9135
/** * Copyright Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.codelab.friendlychat import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.widget.ProgressBar import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import com.firebase.ui.auth.AuthUI import com.firebase.ui.database.FirebaseRecyclerOptions import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.codelab.friendlychat.databinding.ActivityMainBinding import com.google.firebase.codelab.friendlychat.model.FriendlyMessage import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ktx.database import com.google.firebase.ktx.Firebase import com.google.firebase.storage.StorageReference import com.google.firebase.storage.ktx.storage class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private lateinit var manager: LinearLayoutManager // Firebase instance variables private lateinit var auth: FirebaseAuth private lateinit var db: FirebaseDatabase private lateinit var adapter: FriendlyMessageAdapter private val openDocument = registerForActivityResult(MyOpenDocumentContract()) { uri -> uri?.let { onImageSelected(it) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // This codelab uses View Binding // See: https://developer.android.com/topic/libraries/view-binding binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // When running in debug mode, connect to the Firebase Emulator Suite // "10.0.2.2" is a special value which allows the Android emulator to // connect to "localhost" on the host computer. The port values are // defined in the firebase.json file. if (BuildConfig.DEBUG) { Firebase.database.useEmulator("10.0.2.2", 9000) Firebase.auth.useEmulator("10.0.2.2", 9099) Firebase.storage.useEmulator("10.0.2.2", 9199) } // Initialize Firebase Auth and check if the user is signed in auth = Firebase.auth if (auth.currentUser == null) { // Not signed in, launch the Sign In activity startActivity(Intent(this, SignInActivity::class.java)) finish() return } // Initialize Realtime Database db = Firebase.database val messagesRef = db.reference.child(MESSAGES_CHILD) // The FirebaseRecyclerAdapter class and options come from the FirebaseUI library // See: https://github.com/firebase/FirebaseUI-Android val options = FirebaseRecyclerOptions.Builder<FriendlyMessage>() .setQuery(messagesRef, FriendlyMessage::class.java) .build() adapter = FriendlyMessageAdapter(options, getUserName()) binding.progressBar.visibility = ProgressBar.INVISIBLE manager = LinearLayoutManager(this) manager.stackFromEnd = true binding.messageRecyclerView.layoutManager = manager binding.messageRecyclerView.adapter = adapter // Scroll down when a new message arrives // See MyScrollToBottomObserver for details adapter.registerAdapterDataObserver( MyScrollToBottomObserver(binding.messageRecyclerView, adapter, manager) ) // Disable the send button when there's no text in the input field // See MyButtonObserver for details binding.messageEditText.addTextChangedListener(MyButtonObserver(binding.sendButton)) // When the send button is clicked, send a text message binding.sendButton.setOnClickListener { val friendlyMessage = FriendlyMessage( binding.messageEditText.text.toString(), getUserName(), getPhotoUrl(), null ) db.reference.child(MESSAGES_CHILD).push().setValue(friendlyMessage) binding.messageEditText.setText("") } // When the image button is clicked, launch the image picker binding.addMessageImageView.setOnClickListener { openDocument.launch(arrayOf("image/*")) } } public override fun onStart() { super.onStart() // Check if user is signed in. if (auth.currentUser == null) { // Not signed in, launch the Sign In activity startActivity(Intent(this, SignInActivity::class.java)) finish() return } } public override fun onPause() { adapter.stopListening() super.onPause() } public override fun onResume() { super.onResume() adapter.startListening() } override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater = menuInflater inflater.inflate(R.menu.main_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.sign_out_menu -> { signOut() true } else -> super.onOptionsItemSelected(item) } } private fun onImageSelected(uri: Uri) { Log.d(TAG, "Uri: $uri") val user = auth.currentUser val tempMessage = FriendlyMessage(null, getUserName(), getPhotoUrl(), LOADING_IMAGE_URL) db.reference .child(MESSAGES_CHILD) .push() .setValue( tempMessage, DatabaseReference.CompletionListener { databaseError, databaseReference -> if (databaseError != null) { Log.w( TAG, "Unable to write message to database.", databaseError.toException() ) return@CompletionListener } // Build a StorageReference and then upload the file val key = databaseReference.key val storageReference = Firebase.storage .getReference(user!!.uid) .child(key!!) .child(uri.lastPathSegment!!) putImageInStorage(storageReference, uri, key) }) } private fun putImageInStorage(storageReference: StorageReference, uri: Uri, key: String?) { // First upload the image to Cloud Storage storageReference.putFile(uri) .addOnSuccessListener( this ) { taskSnapshot -> // After the image loads, get a public downloadUrl for the image // and add it to the message. taskSnapshot.metadata!!.reference!!.downloadUrl .addOnSuccessListener { uri -> val friendlyMessage = FriendlyMessage(null, getUserName(), getPhotoUrl(), uri.toString()) db.reference .child(MESSAGES_CHILD) .child(key!!) .setValue(friendlyMessage) } } .addOnFailureListener(this) { e -> Log.w( TAG, "Image upload task was unsuccessful.", e ) } } private fun signOut() { AuthUI.getInstance().signOut(this) startActivity(Intent(this, SignInActivity::class.java)) finish() } private fun getPhotoUrl(): String? { val user = auth.currentUser return user?.photoUrl?.toString() } private fun getUserName(): String? { val user = auth.currentUser return if (user != null) { user.displayName } else ANONYMOUS } companion object { private const val TAG = "MainActivity" const val MESSAGES_CHILD = "messages" const val ANONYMOUS = "anonymous" private const val LOADING_IMAGE_URL = "https://www.google.com/images/spin-32.gif" } }
apache-2.0
1d98b0ca3e34577b8352b0eb205f6c1c
37.0625
98
0.611932
5.326531
false
false
false
false
Aptoide/aptoide-client-v8
app/src/main/java/cm/aptoide/pt/home/bundles/promotional/NewAppVersionViewHolder.kt
1
5016
package cm.aptoide.pt.home.bundles.promotional import android.view.View import cm.aptoide.aptoideviews.skeleton.Skeleton import cm.aptoide.pt.R import cm.aptoide.pt.app.DownloadModel import cm.aptoide.pt.home.bundles.base.* import cm.aptoide.pt.networking.image.ImageLoader import kotlinx.android.synthetic.main.card_new_app_version.view.* import kotlinx.android.synthetic.main.card_new_package.view.action_button import kotlinx.android.synthetic.main.card_new_package.view.action_button_skeleton import kotlinx.android.synthetic.main.card_new_package.view.app_background_image import kotlinx.android.synthetic.main.card_new_package.view.app_icon import kotlinx.android.synthetic.main.card_new_package.view.app_icon_skeletonview import kotlinx.android.synthetic.main.card_new_package.view.app_name import kotlinx.android.synthetic.main.card_new_package.view.app_name_skeletonview import kotlinx.android.synthetic.main.card_new_package.view.card_title_label import kotlinx.android.synthetic.main.card_new_package.view.card_title_label_skeletonview import kotlinx.android.synthetic.main.card_new_package.view.card_title_label_text import rx.subjects.PublishSubject class NewAppVersionViewHolder(val view: View, val uiEventsListener: PublishSubject<HomeEvent>) : AppBundleViewHolder(view) { private var skeleton: Skeleton? = null override fun setBundle(homeBundle: HomeBundle?, position: Int) { if (homeBundle !is VersionPromotionalBundle) { throw IllegalStateException( this.javaClass.name + " is getting non PromotionalBundle instance!") } (homeBundle as? VersionPromotionalBundle)?.let { bundle -> if (homeBundle.content == null) { toggleSkeleton(true) } else { toggleSkeleton(false) ImageLoader.with(itemView.context) .loadWithRoundCorners(homeBundle.app.icon, 32, itemView.app_icon, R.attr.placeholder_square) itemView.card_title_label_text.text = homeBundle.title ImageLoader.with(itemView.context) .load(homeBundle.app.featureGraphic, itemView.app_background_image) itemView.app_name.text = homeBundle.app.name itemView.version_name.text = homeBundle.versionName itemView.action_button.setOnClickListener { fireAppClickEvent(homeBundle) } itemView.setOnClickListener { fireAppClickEvent(homeBundle) } setButtonText(homeBundle.downloadModel) } } } private fun setButtonText(model: DownloadModel) { when (model.action) { DownloadModel.Action.UPDATE -> itemView.action_button.text = itemView.resources.getString(R.string.appview_button_update) DownloadModel.Action.INSTALL -> itemView.action_button.text = itemView.resources.getString(R.string.appview_button_install) DownloadModel.Action.OPEN -> itemView.action_button.text = itemView.resources.getString(R.string.appview_button_open) DownloadModel.Action.DOWNGRADE -> itemView.action_button.text = itemView.resources.getString(R.string.appview_button_downgrade) DownloadModel.Action.MIGRATE -> itemView.action_button.text = itemView.resources.getString(R.string.promo_update2appc_appview_update_button) } } private fun fireAppClickEvent(homeBundle: PromotionalBundle) { uiEventsListener.onNext( AppHomeEvent(homeBundle.app, 0, homeBundle, adapterPosition, HomeEvent.Type.INSTALL_PROMOTIONAL)) } private fun toggleSkeleton(showSkeleton: Boolean) { if (showSkeleton) { skeleton?.showSkeleton() itemView.card_title_label_skeletonview.visibility = View.VISIBLE itemView.card_title_label.visibility = View.INVISIBLE itemView.app_icon_skeletonview.visibility = View.VISIBLE itemView.app_icon.visibility = View.INVISIBLE itemView.app_name_skeletonview.visibility = View.VISIBLE itemView.app_name.visibility = View.INVISIBLE itemView.version_text_skeleton.visibility = View.VISIBLE itemView.version_name_skeleton.visibility = View.VISIBLE itemView.version_name.visibility = View.INVISIBLE itemView.action_button_skeleton.visibility = View.VISIBLE itemView.action_button.visibility = View.INVISIBLE } else { skeleton?.showOriginal() itemView.card_title_label_skeletonview.visibility = View.INVISIBLE itemView.card_title_label.visibility = View.VISIBLE itemView.app_icon_skeletonview.visibility = View.INVISIBLE itemView.app_icon.visibility = View.VISIBLE itemView.app_name_skeletonview.visibility = View.INVISIBLE itemView.app_name.visibility = View.VISIBLE itemView.version_text_skeleton.visibility = View.INVISIBLE itemView.version_name_skeleton.visibility = View.INVISIBLE itemView.version_name.visibility = View.VISIBLE itemView.action_button_skeleton.visibility = View.INVISIBLE itemView.action_button.visibility = View.VISIBLE } } }
gpl-3.0
1a409324663d2174031278cb441dfd52
45.453704
89
0.74063
4.298201
false
false
false
false
TangHao1987/intellij-community
platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StreamProvider.kt
4
2148
/* * 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 com.intellij.openapi.components.impl.stores import com.intellij.openapi.components.RoamingType import java.io.IOException import java.io.InputStream public interface StreamProvider { public open val enabled: Boolean get() = true public open fun isApplicable(fileSpec: String, roamingType: RoamingType): Boolean = true /** * @param fileSpec * @param content bytes of content, size of array is not actual size of data, you must use `size` * @param size actual size of data */ public fun saveContent(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) public fun loadContent(fileSpec: String, roamingType: RoamingType): InputStream? public open fun listSubFiles(fileSpec: String, roamingType: RoamingType): Collection<String> = emptyList() /** * You must close passed input stream. */ public open fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean) { for (name in listSubFiles(path, roamingType)) { if (!filter(name)) { continue } val input: InputStream? try { input = loadContent("$path/$name", roamingType) } catch (e: IOException) { StorageUtil.LOG.error(e) continue } if (input != null && !processor(name, input, false)) { break } } } /** * Delete file or directory */ public fun delete(fileSpec: String, roamingType: RoamingType) }
apache-2.0
c209a3913be896792a011c7df71e56f5
30.602941
187
0.696462
4.330645
false
false
false
false