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
youdonghai/intellij-community
platform/script-debugger/debugger-ui/src/VariableView.kt
1
19818
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.icons.AllIcons import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.pom.Navigatable import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.util.SmartList import com.intellij.util.ThreeState import com.intellij.xdebugger.XSourcePositionWrapper import com.intellij.xdebugger.frame.* import com.intellij.xdebugger.frame.presentation.XKeywordValuePresentation import com.intellij.xdebugger.frame.presentation.XNumericValuePresentation import com.intellij.xdebugger.frame.presentation.XStringValuePresentation import com.intellij.xdebugger.frame.presentation.XValuePresentation import org.jetbrains.concurrency.* import org.jetbrains.debugger.values.* import java.util.* import java.util.concurrent.atomic.AtomicBoolean import java.util.regex.Pattern import javax.swing.Icon fun VariableView(variable: Variable, context: VariableContext) = VariableView(variable.name, variable, context) class VariableView(override val variableName: String, private val variable: Variable, private val context: VariableContext) : XNamedValue(variableName), VariableContext { @Volatile private var value: Value? = null // lazy computed private var _memberFilter: MemberFilter? = null @Volatile private var remainingChildren: List<Variable>? = null @Volatile private var remainingChildrenOffset: Int = 0 override fun watchableAsEvaluationExpression() = context.watchableAsEvaluationExpression() override val viewSupport: DebuggerViewSupport get() = context.viewSupport override val parent = context override val memberFilter: Promise<MemberFilter> get() = context.viewSupport.getMemberFilter(this) override val evaluateContext: EvaluateContext get() = context.evaluateContext override val scope: Scope? get() = context.scope override val vm: Vm? get() = context.vm override fun computePresentation(node: XValueNode, place: XValuePlace) { value = variable.value if (value != null) { computePresentation(value!!, node) return } if (variable !is ObjectProperty || variable.getter == null) { // it is "used" expression (WEB-6779 Debugger/Variables: Automatically show used variables) evaluateContext.evaluate(variable.name) .done(node) { if (it.wasThrown) { setEvaluatedValue(viewSupport.transformErrorOnGetUsedReferenceValue(it.value, null), null, node) } else { value = it.value computePresentation(it.value, node) } } .rejected(node) { setEvaluatedValue(viewSupport.transformErrorOnGetUsedReferenceValue(null, it.message), it.message, node) } return } node.setPresentation(null, object : XValuePresentation() { override fun renderValue(renderer: XValuePresentation.XValueTextRenderer) { renderer.renderValue("\u2026") } }, false) node.setFullValueEvaluator(object : XFullValueEvaluator(" (invoke getter)") { override fun startEvaluation(callback: XFullValueEvaluator.XFullValueEvaluationCallback) { var valueModifier = variable.valueModifier var nonProtoContext = context while (nonProtoContext is VariableView && nonProtoContext.variableName == PROTOTYPE_PROP) { valueModifier = nonProtoContext.variable.valueModifier nonProtoContext = nonProtoContext.parent } valueModifier!!.evaluateGet(variable, evaluateContext) .done(node) { callback.evaluated("") setEvaluatedValue(it, null, node) } } }.setShowValuePopup(false)) } private fun setEvaluatedValue(value: Value?, error: String?, node: XValueNode) { if (value == null) { node.setPresentation(AllIcons.Debugger.Db_primitive, null, error ?: "Internal Error", false) } else { this.value = value computePresentation(value, node) } } private fun computePresentation(value: Value, node: XValueNode) { when (value.type) { ValueType.OBJECT, ValueType.NODE -> context.viewSupport.computeObjectPresentation((value as ObjectValue), variable, context, node, icon) ValueType.FUNCTION -> node.setPresentation(icon, ObjectValuePresentation(trimFunctionDescription(value)), true) ValueType.ARRAY -> context.viewSupport.computeArrayPresentation(value, variable, context, node, icon) ValueType.BOOLEAN, ValueType.NULL, ValueType.UNDEFINED -> node.setPresentation(icon, XKeywordValuePresentation(value.valueString!!), false) ValueType.NUMBER -> node.setPresentation(icon, createNumberPresentation(value.valueString!!), false) ValueType.STRING -> { node.setPresentation(icon, XStringValuePresentation(value.valueString!!), false) // isTruncated in terms of debugger backend, not in our terms (i.e. sometimes we cannot control truncation), // so, even in case of StringValue, we check value string length if ((value is StringValue && value.isTruncated) || value.valueString!!.length > XValueNode.MAX_VALUE_LENGTH) { node.setFullValueEvaluator(MyFullValueEvaluator(value)) } } else -> node.setPresentation(icon, null, value.valueString!!, true) } } override fun computeChildren(node: XCompositeNode) { node.setAlreadySorted(true) if (value !is ObjectValue) { node.addChildren(XValueChildrenList.EMPTY, true) return } val list = remainingChildren if (list != null) { val to = Math.min(remainingChildrenOffset + XCompositeNode.MAX_CHILDREN_TO_SHOW, list.size) val isLast = to == list.size node.addChildren(createVariablesList(list, remainingChildrenOffset, to, this, _memberFilter), isLast) if (!isLast) { node.tooManyChildren(list.size - to) remainingChildrenOffset += XCompositeNode.MAX_CHILDREN_TO_SHOW } return } val objectValue = value as ObjectValue val hasNamedProperties = objectValue.hasProperties() != ThreeState.NO val hasIndexedProperties = objectValue.hasIndexedProperties() != ThreeState.NO val promises = SmartList<Promise<*>>() val additionalProperties = viewSupport.computeAdditionalObjectProperties(objectValue, variable, this, node) if (additionalProperties != null) { promises.add(additionalProperties) } // we don't support indexed properties if additional properties added - behavior is undefined if object has indexed properties and additional properties also specified if (hasIndexedProperties) { promises.add(computeIndexedProperties(objectValue as ArrayValue, node, !hasNamedProperties && additionalProperties == null)) } if (hasNamedProperties) { // named properties should be added after additional properties if (additionalProperties == null || additionalProperties.state != Promise.State.PENDING) { promises.add(computeNamedProperties(objectValue, node, !hasIndexedProperties && additionalProperties == null)) } else { promises.add(additionalProperties.thenAsync(node) { computeNamedProperties(objectValue, node, true) }) } } if (hasIndexedProperties == hasNamedProperties || additionalProperties != null) { all(promises).processed(node) { node.addChildren(XValueChildrenList.EMPTY, true) } } } abstract class ObsolescentIndexedVariablesConsumer(protected val node: XCompositeNode) : IndexedVariablesConsumer() { override val isObsolete: Boolean get() = node.isObsolete } private fun computeIndexedProperties(value: ArrayValue, node: XCompositeNode, isLastChildren: Boolean): Promise<*> { return value.getIndexedProperties(0, value.length, XCompositeNode.MAX_CHILDREN_TO_SHOW, object : ObsolescentIndexedVariablesConsumer(node) { override fun consumeRanges(ranges: IntArray?) { if (ranges == null) { val groupList = XValueChildrenList() addGroups(value, ::lazyVariablesGroup, groupList, 0, value.length, XCompositeNode.MAX_CHILDREN_TO_SHOW, this@VariableView) node.addChildren(groupList, isLastChildren) } else { addRanges(value, ranges, node, this@VariableView, isLastChildren) } } override fun consumeVariables(variables: List<Variable>) { node.addChildren(createVariablesList(variables, this@VariableView, null), isLastChildren) } }) } private fun computeNamedProperties(value: ObjectValue, node: XCompositeNode, isLastChildren: Boolean) = processVariables(this, value.properties, node) { memberFilter, variables -> _memberFilter = memberFilter if (value.type == ValueType.ARRAY && value !is ArrayValue) { computeArrayRanges(variables, node) return@processVariables } var functionValue = value as? FunctionValue if (functionValue != null && functionValue.hasScopes() == ThreeState.NO) { functionValue = null } remainingChildren = processNamedObjectProperties(variables, node, this@VariableView, memberFilter, XCompositeNode.MAX_CHILDREN_TO_SHOW, isLastChildren && functionValue == null) if (remainingChildren != null) { remainingChildrenOffset = XCompositeNode.MAX_CHILDREN_TO_SHOW } if (functionValue != null) { // we pass context as variable context instead of this variable value - we cannot watch function scopes variables, so, this variable name doesn't matter node.addChildren(XValueChildrenList.bottomGroup(FunctionScopesValueGroup(functionValue, context)), isLastChildren) } } private fun computeArrayRanges(properties: List<Variable>, node: XCompositeNode) { val variables = filterAndSort(properties, _memberFilter!!) var count = variables.size val bucketSize = XCompositeNode.MAX_CHILDREN_TO_SHOW if (count <= bucketSize) { node.addChildren(createVariablesList(variables, this, null), true) return } while (count > 0) { if (Character.isDigit(variables.get(count - 1).name[0])) { break } count-- } val groupList = XValueChildrenList() if (count > 0) { addGroups(variables, ::createArrayRangeGroup, groupList, 0, count, bucketSize, this) } var notGroupedVariablesOffset: Int if ((variables.size - count) > bucketSize) { notGroupedVariablesOffset = variables.size while (notGroupedVariablesOffset > 0) { if (!variables.get(notGroupedVariablesOffset - 1).name.startsWith("__")) { break } notGroupedVariablesOffset-- } if (notGroupedVariablesOffset > 0) { addGroups(variables, ::createArrayRangeGroup, groupList, count, notGroupedVariablesOffset, bucketSize, this) } } else { notGroupedVariablesOffset = count } for (i in notGroupedVariablesOffset..variables.size - 1) { val variable = variables.get(i) groupList.add(VariableView(_memberFilter!!.rawNameToSource(variable), variable, this)) } node.addChildren(groupList, true) } private val icon: Icon get() = getIcon(value!!) override fun getModifier(): XValueModifier? { if (!variable.isMutable) { return null } return object : XValueModifier() { override fun getInitialValueEditorText(): String? { if (value!!.type == ValueType.STRING) { val string = value!!.valueString!! val builder = StringBuilder(string.length) builder.append('"') StringUtil.escapeStringCharacters(string.length, string, builder) builder.append('"') return builder.toString() } else { return if (value!!.type.isObjectType) null else value!!.valueString } } override fun setValue(expression: String, callback: XValueModifier.XModificationCallback) { variable.valueModifier!!.setValue(variable, expression, evaluateContext) .doneRun { value = null callback.valueModified() } .rejected { callback.errorOccurred(it.message!!) } } } } fun getValue() = variable.value override fun canNavigateToSource() = value is FunctionValue || viewSupport.canNavigateToSource(variable, context) override fun computeSourcePosition(navigatable: XNavigatable) { if (value is FunctionValue) { (value as FunctionValue).resolve() .done { function -> vm!!.scriptManager.getScript(function) .done { navigatable.setSourcePosition(it?.let { viewSupport.getSourceInfo(null, it, function.openParenLine, function.openParenColumn) }?.let { object : XSourcePositionWrapper(it) { override fun createNavigatable(project: Project): Navigatable { return PsiVisitors.visit(myPosition, project) { position, element, positionOffset, document -> // element will be "open paren", but we should navigate to function name, // we cannot use specific PSI type here (like JSFunction), so, we try to find reference expression (i.e. name expression) var referenceCandidate: PsiElement? = element var psiReference: PsiElement? = null while (true) { referenceCandidate = referenceCandidate?.prevSibling ?: break if (referenceCandidate is PsiReference) { psiReference = referenceCandidate break } } if (psiReference == null) { referenceCandidate = element.parent while (true) { referenceCandidate = referenceCandidate?.prevSibling ?: break if (referenceCandidate is PsiReference) { psiReference = referenceCandidate break } } } (if (psiReference == null) element.navigationElement else psiReference.navigationElement) as? Navigatable } ?: super.createNavigatable(project) } } }) } } } else { viewSupport.computeSourcePosition(variableName, value!!, variable, context, navigatable) } } override fun computeInlineDebuggerData(callback: XInlineDebuggerDataCallback) = viewSupport.computeInlineDebuggerData(variableName, variable, context, callback) override fun getEvaluationExpression(): String? { if (!watchableAsEvaluationExpression()) { return null } if (context.variableName == null) return variable.name // top level watch expression, may be call etc. val list = SmartList<String>() addVarName(list, parent, variable.name) var parent: VariableContext? = context while (parent != null && parent.variableName != null) { addVarName(list, parent.parent, parent.variableName!!) parent = parent.parent } return context.viewSupport.propertyNamesToString(list, false) } private fun addVarName(list: SmartList<String>, parent: VariableContext?, name: String) { if (parent == null || parent.variableName != null) list.add(name) else list.addAll(name.split(".").reversed()) } private class MyFullValueEvaluator(private val value: Value) : XFullValueEvaluator(if (value is StringValue) value.length else value.valueString!!.length) { override fun startEvaluation(callback: XFullValueEvaluator.XFullValueEvaluationCallback) { if (value !is StringValue || !value.isTruncated) { callback.evaluated(value.valueString!!) return } val evaluated = AtomicBoolean() value.fullString .done { if (!callback.isObsolete && evaluated.compareAndSet(false, true)) { callback.evaluated(value.valueString!!) } } .rejected { callback.errorOccurred(it.message!!) } } } companion object { fun setObjectPresentation(value: ObjectValue, icon: Icon, node: XValueNode) { node.setPresentation(icon, ObjectValuePresentation(getObjectValueDescription(value)), value.hasProperties() != ThreeState.NO) } fun setArrayPresentation(value: Value, context: VariableContext, icon: Icon, node: XValueNode) { assert(value.type == ValueType.ARRAY) if (value is ArrayValue) { val length = value.length node.setPresentation(icon, ArrayPresentation(length, value.className), length > 0) return } val valueString = value.valueString // only WIP reports normal description if (valueString != null && valueString.endsWith("]") && ARRAY_DESCRIPTION_PATTERN.matcher(valueString).find()) { node.setPresentation(icon, null, valueString, true) } else { context.evaluateContext.evaluate("a.length", Collections.singletonMap<String, Any>("a", value), false) .done(node) { node.setPresentation(icon, null, "Array[${it.value.valueString}]", true) } .rejected(node) { node.setPresentation(icon, null, "Internal error: $it", false) } } } fun getIcon(value: Value): Icon { val type = value.type return when (type) { ValueType.FUNCTION -> AllIcons.Nodes.Function ValueType.ARRAY -> AllIcons.Debugger.Db_array else -> if (type.isObjectType) AllIcons.Debugger.Value else AllIcons.Debugger.Db_primitive } } } } fun getClassName(value: ObjectValue): String { val className = value.className return if (className.isNullOrEmpty()) "Object" else className!! } fun getObjectValueDescription(value: ObjectValue): String { val description = value.valueString return if (description.isNullOrEmpty()) getClassName(value) else description!! } internal fun trimFunctionDescription(value: Value): String { val presentableValue = value.valueString ?: return "" var endIndex = 0 while (endIndex < presentableValue.length && !StringUtil.isLineBreak(presentableValue[endIndex])) { endIndex++ } while (endIndex > 0 && Character.isWhitespace(presentableValue[endIndex - 1])) { endIndex-- } return presentableValue.substring(0, endIndex) } private fun createNumberPresentation(value: String): XValuePresentation { return if (value == PrimitiveValue.NA_N_VALUE || value == PrimitiveValue.INFINITY_VALUE) XKeywordValuePresentation(value) else XNumericValuePresentation(value) } private val ARRAY_DESCRIPTION_PATTERN = Pattern.compile("^[a-zA-Z\\d]+\\[\\d+\\]$") private class ArrayPresentation(length: Int, className: String?) : XValuePresentation() { private val length = Integer.toString(length) private val className = if (className.isNullOrEmpty()) "Array" else className!! override fun renderValue(renderer: XValuePresentation.XValueTextRenderer) { renderer.renderSpecialSymbol(className) renderer.renderSpecialSymbol("[") renderer.renderSpecialSymbol(length) renderer.renderSpecialSymbol("]") } } private val PROTOTYPE_PROP = "__proto__"
apache-2.0
8afc92ac5ba67ccd2c2ba0c5f6f7e53f
38.957661
181
0.686598
5.110366
false
false
false
false
jiro-aqua/vertical-text-viewer
vtextview/src/main/java/jp/gr/aqua/vtextviewer/PreferenceFragment.kt
1
3727
package jp.gr.aqua.vtextviewer import android.app.AlertDialog import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import androidx.preference.* class PreferenceFragment : PreferenceFragmentCompat() { private var mListener: OnFragmentInteractionListener? = null override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { // Load the vtext_preferences from an XML resource setPreferencesFromResource(R.xml.vtext_preferences, rootKey) val pm = preferenceManager val ps = pm.preferenceScreen // 原稿用紙モード val writingPaperModeEnabler : (value: Boolean)->Unit = { value-> ps.findPreference<Preference>(Preferences.KEY_FONT_SIZE)?.isEnabled = !value ps.findPreference<Preference>(Preferences.KEY_CHAR_MAX_PORT)?.isEnabled = !value ps.findPreference<Preference>(Preferences.KEY_CHAR_MAX_LAND)?.isEnabled = !value } writingPaperModeEnabler(Preferences(requireContext()).isWritingPaperMode()) ps.findPreference<Preference>(Preferences.KEY_WRITING_PAPER) ?.setOnPreferenceChangeListener { _, newValue -> if ( newValue is Boolean ) writingPaperModeEnabler(newValue) true } // ダークモードを使う ps.findPreference<Preference>(Preferences.KEY_USE_DARK_MODE)?.isEnabled= ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q ) // IPAフォントについて ps.findPreference<Preference>(Preferences.KEY_IPA) ?.setOnPreferenceClickListener { showMessage(R.string.vtext_about_ipa_font, "IPA_Font_License_Agreement_v1.0.txt") } // モリサワ BIZ UD明朝フォントについて ps.findPreference<Preference>(Preferences.KEY_ABOUT_MORISAWA_MINCHO) ?.setOnPreferenceClickListener { showMessage(R.string.vtext_about_morisawa_mincho, "OFL_bizmincho.txt") } // モリサワ BIZ UDゴシックフォントについて ps.findPreference<Preference>(Preferences.KEY_ABOUT_MORISAWA_GOTHIC) ?.setOnPreferenceClickListener { showMessage(R.string.vtext_about_morisawa_gothic, "OFL_bizgothic.txt") } // バージョン ps.findPreference<Preference>(Preferences.KEY_ABOUT) ?.setSummary("version: ${versionName} (c)Aquamarine Networks.") } private val versionName: String get() { val pm = requireActivity().packageManager var versionName = "" try { val packageInfo = pm.getPackageInfo(requireActivity().packageName, 0) versionName = packageInfo.versionName } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } return versionName } override fun onAttach(context: Context) { super.onAttach(context) if (context is OnFragmentInteractionListener) { mListener = context } else { throw RuntimeException(context.toString() + " must implement OnFragmentInteractionListener") } } override fun onDetach() { super.onDetach() mListener = null } interface OnFragmentInteractionListener private fun showMessage(titleResId: Int, assetText: String) : Boolean { val message = requireContext().assets.open(assetText).reader(charset = Charsets.UTF_8).use{it.readText()} AlertDialog.Builder(requireContext()) .setTitle(titleResId) .setMessage(message) .setPositiveButton(R.string.vtext_ok, null) .show() return false } }
apache-2.0
a40661d89dad110211d0944cb8a0301a
35.454545
128
0.661956
4.568354
false
false
false
false
zdary/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotatorPre30.kt
4
11075
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.annotator import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.util.InspectionMessage import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.HighlightSeverity import com.intellij.psi.PsiElement import com.intellij.psi.PsiErrorElement import com.intellij.psi.PsiModifier import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.ArrayUtil import org.jetbrains.plugins.groovy.GroovyBundle.message import org.jetbrains.plugins.groovy.annotator.intentions.ConvertLambdaToClosureAction import org.jetbrains.plugins.groovy.annotator.intentions.ReplaceDotFix import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.* import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor import org.jetbrains.plugins.groovy.lang.psi.api.* import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrBlockStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrAssertStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrThrowStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrTraditionalForClause import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.* import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil import org.jetbrains.plugins.groovy.lang.psi.util.isApplicationExpression internal class GroovyAnnotatorPre30(private val holder: AnnotationHolder) : GroovyElementVisitor() { private fun error(typeArgumentList: PsiElement, @InspectionMessage msg: String) { holder.newAnnotation(HighlightSeverity.ERROR, msg).range(typeArgumentList).create() } override fun visitModifierList(modifierList: GrModifierList) { val modifier = modifierList.getModifier(PsiModifier.DEFAULT) ?: return error(modifier, message("default.modifier.in.old.versions")) } override fun visitDoWhileStatement(statement: GrDoWhileStatement) { super.visitDoWhileStatement(statement) error(statement.doKeyword, message("unsupported.do.while.statement")) } override fun visitVariableDeclaration(variableDeclaration: GrVariableDeclaration) { super.visitVariableDeclaration(variableDeclaration) if (variableDeclaration.parent is GrTraditionalForClause) { if (variableDeclaration.isTuple) { holder.newAnnotation(HighlightSeverity.ERROR, message("unsupported.tuple.declaration.in.for")).create() } else if (variableDeclaration.variables.size > 1) { holder.newAnnotation(HighlightSeverity.ERROR, message("unsupported.multiple.variables.in.for")).create() } } else if (variableDeclaration.isTuple) { val initializer = variableDeclaration.tupleInitializer if (initializer != null && initializer.isApplicationExpression()) { error(initializer, message("unsupported.tuple.application.initializer")) } } } override fun visitExpressionList(expressionList: GrExpressionList) { super.visitExpressionList(expressionList) if (expressionList.expressions.size > 1) { holder.newAnnotation(HighlightSeverity.ERROR, message("unsupported.expression.list.in.for.update")).create() } } override fun visitTryResourceList(resourceList: GrTryResourceList) { super.visitTryResourceList(resourceList) error(resourceList.firstChild, message("unsupported.resource.list")) } override fun visitBinaryExpression(expression: GrBinaryExpression) { super.visitBinaryExpression(expression) val operator = expression.operationToken val tokenType = operator.node.elementType if (tokenType === T_ID || tokenType === T_NID) { error(operator, message("operator.is.not.supported.in", tokenType)) } } override fun visitInExpression(expression: GrInExpression) { super.visitInExpression(expression) if (GrInExpression.isNegated(expression)) { error(expression.operationToken, message("unsupported.negated.in")) } } override fun visitInstanceofExpression(expression: GrInstanceOfExpression) { super.visitInstanceofExpression(expression) if (GrInstanceOfExpression.isNegated(expression)) { error(expression.operationToken, message("unsupported.negated.instanceof")) } } override fun visitAssignmentExpression(expression: GrAssignmentExpression) { super.visitAssignmentExpression(expression) val operator = expression.operationToken if (operator.node.elementType === T_ELVIS_ASSIGN) { error(operator, message("unsupported.elvis.assignment")) } } override fun visitIndexProperty(expression: GrIndexProperty) { super.visitIndexProperty(expression) val safeAccessToken = expression.safeAccessToken if (safeAccessToken != null) { error(safeAccessToken, message("unsupported.safe.index.access")) } } override fun visitReferenceExpression(expression: GrReferenceExpression) { super.visitReferenceExpression(expression) val dot = expression.dotToken ?: return val tokenType = dot.node.elementType if (tokenType === T_METHOD_REFERENCE) { val fix = ReplaceDotFix(tokenType, T_METHOD_CLOSURE) val message = message("operator.is.not.supported.in", tokenType) val descriptor = InspectionManager.getInstance(expression.project).createProblemDescriptor( dot, dot, message, ProblemHighlightType.ERROR, true ) holder.newAnnotation(HighlightSeverity.ERROR, message).range(dot) .newLocalQuickFix(fix, descriptor).registerFix() .create() } } override fun visitArrayInitializer(arrayInitializer: GrArrayInitializer) { super.visitArrayInitializer(arrayInitializer) holder.newAnnotation(HighlightSeverity.ERROR, message("unsupported.array.initializers")).create() } override fun visitLambdaExpression(expression: GrLambdaExpression) { super.visitLambdaExpression(expression) holder.newAnnotation(HighlightSeverity.ERROR, message("unsupported.lambda")).range(expression.arrow) .withFix(ConvertLambdaToClosureAction(expression)) .create() } override fun visitTypeDefinitionBody(typeDefinitionBody: GrTypeDefinitionBody) { super.visitTypeDefinitionBody(typeDefinitionBody) checkAmbiguousCodeBlockInDefinition(typeDefinitionBody) } private fun checkAmbiguousCodeBlockInDefinition(typeDefinitionBody: GrTypeDefinitionBody) { val parent = typeDefinitionBody.parent as? GrAnonymousClassDefinition ?: return val prev = typeDefinitionBody.prevSibling if (!PsiUtil.isLineFeed(prev)) return val newExpression = parent.parent as? GrNewExpression ?: return val statementOwner = PsiTreeUtil.getParentOfType(newExpression, GrStatementOwner::class.java) val parenthesizedExpression = PsiTreeUtil.getParentOfType(newExpression, GrParenthesizedExpression::class.java) if (parenthesizedExpression != null && PsiTreeUtil.isAncestor(statementOwner, parenthesizedExpression, true)) return val argumentList = PsiTreeUtil.getParentOfType(newExpression, GrArgumentList::class.java) if (argumentList != null && argumentList !is GrCommandArgumentList) { if (PsiTreeUtil.isAncestor(statementOwner, argumentList, true)) return } holder.newAnnotation(HighlightSeverity.ERROR, message("ambiguous.code.block")).create() } override fun visitBlockStatement(blockStatement: GrBlockStatement) { super.visitBlockStatement(blockStatement) if (blockStatement.parent is GrStatementOwner) { holder.newAnnotation(HighlightSeverity.ERROR, message("ambiguous.code.block")).create() } } override fun visitClosure(closure: GrClosableBlock) { super.visitClosure(closure) if (!closure.hasParametersSection() && !followsError(closure) && isClosureAmbiguous(closure)) { holder.newAnnotation(HighlightSeverity.ERROR, message("ambiguous.code.block")).create() } } /** * for example if (!(a inst)) {} * ^ * we are here */ private fun followsError(closure: GrClosableBlock): Boolean { val prev = closure.prevSibling return prev is PsiErrorElement || prev is PsiWhiteSpace && prev.getPrevSibling() is PsiErrorElement } private fun isClosureAmbiguous(closure: GrClosableBlock): Boolean { if (mayBeAnonymousBody(closure)) return true var place: PsiElement = closure while (true) { val parent = place.parent if (parent == null || parent is GrUnAmbiguousClosureContainer) return false if (PsiUtil.isExpressionStatement(place)) return true if (parent.firstChild !== place) return false place = parent } } private fun mayBeAnonymousBody(closure: GrClosableBlock): Boolean { val parent = closure.parent as? GrMethodCallExpression ?: return false if (parent.invokedExpression !is GrNewExpression) { return false } if (!ArrayUtil.contains(closure, *parent.closureArguments)) { return false } var run: PsiElement? = parent.parent while (run != null) { if (run is GrParenthesizedExpression) return false if (run is GrReturnStatement || run is GrAssertStatement || run is GrThrowStatement || run is GrCommandArgumentList) return true run = run.parent } return false } override fun visitTypeElement(typeElement: GrTypeElement) { typeElement.annotations.forEach { error(it, message("unsupported.type.annotations")) } } override fun visitCodeReferenceElement(refElement: GrCodeReferenceElement) { refElement.annotations.forEach { error(it, message("unsupported.type.annotations")) } } override fun visitTupleAssignmentExpression(expression: GrTupleAssignmentExpression) { val rValue = expression.rValue if (rValue != null && rValue.isApplicationExpression()) { error(rValue, message("unsupported.tuple.application.initializer")) } } }
apache-2.0
a672a78c7c6110c120b390fe212d7b2e
42.774704
140
0.773995
4.767542
false
false
false
false
rodm/teamcity-gradle-init-scripts-plugin
server/src/main/kotlin/com/github/rodm/teamcity/gradle/scripts/server/DeleteScriptAction.kt
1
2053
/* * Copyright 2017 Rod MacKenzie. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.rodm.teamcity.gradle.scripts.server import jetbrains.buildServer.controllers.ActionMessages import jetbrains.buildServer.serverSide.ProjectManager import jetbrains.buildServer.web.openapi.ControllerAction import org.jdom.Element import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse class DeleteScriptAction(controller: InitScriptsActionsController, val projectManager: ProjectManager, val scriptsManager: GradleScriptsManager) : ControllerAction { private val NAME = "deleteScript" init { controller.registerAction(this) } override fun canProcess(request: HttpServletRequest): Boolean { return NAME == request.getParameter("action") } override fun process(request: HttpServletRequest, response: HttpServletResponse, ajaxResponse: Element?) { val name = request.getParameter("name") if (name != null) { val projectId = request.getParameter("projectId") val project = projectManager.findProjectById(projectId) if (project != null) { val deleted = scriptsManager.deleteScript(project, name) val message = "Gradle init script $name ${if (deleted) "was deleted" else "cannot be deleted"}" ActionMessages.getOrCreateMessages(request).addMessage("initScriptsMessage", message) } } } }
apache-2.0
bcb69fc301feac98563ec9c7afb96562
38.480769
111
0.707745
4.841981
false
false
false
false
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/main/kotlin/com/vrem/wifianalyzer/wifi/model/WiFiUtils.kt
1
1930
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.wifianalyzer.wifi.model import com.vrem.util.EMPTY import java.net.InetAddress import java.nio.ByteOrder import kotlin.math.abs import kotlin.math.log10 import kotlin.math.pow private const val DISTANCE_MHZ_M = 27.55 private const val MIN_RSSI = -100 private const val MAX_RSSI = -55 private const val QUOTE = "\"" fun calculateDistance(frequency: Int, level: Int): Double = 10.0.pow((DISTANCE_MHZ_M - 20 * log10(frequency.toDouble()) + abs(level)) / 20.0) fun calculateSignalLevel(rssi: Int, numLevels: Int): Int = when { rssi <= MIN_RSSI -> 0 rssi >= MAX_RSSI -> numLevels - 1 else -> (rssi - MIN_RSSI) * (numLevels - 1) / (MAX_RSSI - MIN_RSSI) } fun convertSSID(ssid: String): String = ssid.removePrefix(QUOTE).removeSuffix(QUOTE) fun convertIpAddress(ipAddress: Int): String { return try { val value: Long = when (ByteOrder.LITTLE_ENDIAN) { ByteOrder.nativeOrder() -> Integer.reverseBytes(ipAddress).toLong() else -> ipAddress.toLong() } InetAddress.getByAddress(value.toBigInteger().toByteArray()).hostAddress } catch (e: Exception) { String.EMPTY } }
gpl-3.0
882776d10b820e2b586135eb9aa4ccf9
35.415094
90
0.706736
3.891129
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-apis/src/main/kotlin/slatekit/apis/tools/code/builders/JavaBuilder.kt
1
3449
package slatekit.apis.tools.code.builders import kotlin.reflect.KClass import kotlin.reflect.KParameter import kotlin.reflect.KProperty import slatekit.apis.Verb import slatekit.apis.routes.Action import slatekit.apis.tools.code.CodeGenSettings import slatekit.apis.tools.code.TypeInfo import slatekit.common.newline import slatekit.meta.KTypes import slatekit.meta.Reflector class JavaBuilder(val settings: CodeGenSettings) : CodeBuilder { override val basicTypes = TypeInfo.basicTypes override val mapTypeDecl = "HashMap<String, Object> postData = new HashMap<>();" override fun buildModelInfo(cls: KClass<*>): String { val props = Reflector.getProperties(cls) val fields = props.foldIndexed("") { ndx: Int, acc: String, prop: KProperty<*> -> val type = prop.returnType val typeInfo = buildTypeName(type) val field = "public " + typeInfo.targetType + " " + prop.name + ";" + newline acc + (if (ndx > 0) "\t" else "") + field } return fields } override fun buildArg(parameter: KParameter): String { return buildTargetName(parameter.type.classifier as KClass<*>) + " " + parameter.name } /** * builds a string of parameters to put into the query string. * e.g. queryParams.put("id", id); */ override fun buildQueryParams(action: Action): String { return if (action.verb == Verb.Get) { action.paramsUser.foldIndexed("") { ndx: Int, acc: String, param: KParameter -> acc + (if (ndx > 0) "\t\t" else "") + "queryParams.put(\"" + param.name + "\", String.valueOf(" + param.name + "));" + newline } } else { "" } } /** * builds a string of the parameters to put into the entity/body of request * e..g dataParams.put('id", id); */ override fun buildDataParams(action: Action): String { return if (action.verb != Verb.Get) { action.paramsUser.foldIndexed("") { ndx: Int, acc: String, param: KParameter -> acc + (if (ndx > 0) "\t\t" else "") + "postData.put(\"" + param.name + "\", " + param.name + ");" + newline } } else { "" } } override fun buildTargetName(cls:KClass<*>): String { return when(cls) { KTypes.KStringClass -> KTypes.KStringClass .java.simpleName KTypes.KBoolClass -> KTypes.KBoolClass .java.simpleName KTypes.KShortClass -> KTypes.KShortClass .java.simpleName KTypes.KIntClass -> KTypes.KIntClass .java.simpleName KTypes.KLongClass -> KTypes.KLongClass .java.simpleName KTypes.KFloatClass -> KTypes.KFloatClass .java.simpleName KTypes.KDoubleClass -> KTypes.KDoubleClass .java.simpleName KTypes.KSmartValueClass -> KTypes.KSmartValueClass.java.simpleName KTypes.KDecStringClass -> KTypes.KStringClass .java.simpleName KTypes.KDecIntClass -> KTypes.KStringClass .java.simpleName KTypes.KDecLongClass -> KTypes.KStringClass .java.simpleName KTypes.KDecDoubleClass -> KTypes.KStringClass .java.simpleName else -> KTypes.KStringClass .java.simpleName } } override fun buildTypeLoader(): String = ".class" }
apache-2.0
c6e58fd69cad9ec1dc8780a01db6a561
41.060976
142
0.605103
4.279156
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/binaryOp/callAny.kt
5
682
fun box(): String { val a1: Any = 1.toByte().plus(1) val a2: Any = 1.toShort().plus(1) val a3: Any = 1.plus(1) val a4: Any = 1L.plus(1) val a5: Any = 1.0.plus(1) val a6: Any = 1f.plus(1) val a7: Any = 'A'.plus(1) val a8: Any = 'B'.minus('A') if (a1 !is Int || a1 != 2) return "fail 1" if (a2 !is Int || a2 != 2) return "fail 2" if (a3 !is Int || a3 != 2) return "fail 3" if (a4 !is Long || a4 != 2L) return "fail 4" if (a5 !is Double || a5 != 2.0) return "fail 5" if (a6 !is Float || a6 != 2f) return "fail 6" if (a7 !is Char || a7 != 'B') return "fail 7" if (a8 !is Int || a8 != 1) return "fail 8" return "OK" }
apache-2.0
a851434336542deb21c61aea47acd89a
31.52381
51
0.502933
2.409894
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/when/kt2466.kt
5
176
fun foo(b: Boolean) = when (b) { false -> 0 true -> 1 else -> 2 } fun box(): String = if (foo(false) == 0 && foo(true) == 1) "OK" else "Fail"
apache-2.0
987572ca8c4e91618fdce83373d50965
18.555556
75
0.431818
2.983051
false
false
false
false
AndroidX/androidx
wear/compose/compose-material/samples/src/main/java/androidx/wear/compose/material/samples/ChipSample.kt
3
5796
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.material.samples import androidx.annotation.Sampled import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.wear.compose.material.Chip import androidx.wear.compose.material.ChipDefaults import androidx.wear.compose.material.CompactChip import androidx.wear.compose.material.Icon import androidx.wear.compose.material.OutlinedChip import androidx.wear.compose.material.OutlinedCompactChip import androidx.wear.compose.material.Text @Sampled @Composable fun ChipWithIconAndLabel() { Chip( onClick = { /* Do something */ }, enabled = true, // When we have only primary label we can have up to 2 lines of text label = { Text( text = "Main label can span over 2 lines", maxLines = 2, overflow = TextOverflow.Ellipsis ) }, icon = { Icon( painter = painterResource(id = R.drawable.ic_airplanemode_active_24px), contentDescription = "airplane", modifier = Modifier.size(ChipDefaults.IconSize) .wrapContentSize(align = Alignment.Center), ) } ) } @Sampled @Composable fun OutlinedChipWithIconAndLabel() { OutlinedChip( onClick = { /* Do something */ }, enabled = true, // When we have only primary label we can have up to 2 lines of text label = { Text( text = "Main label can span over 2 lines", maxLines = 2, overflow = TextOverflow.Ellipsis ) }, icon = { Icon( painter = painterResource(id = R.drawable.ic_airplanemode_active_24px), contentDescription = "airplane", modifier = Modifier.size(ChipDefaults.IconSize) .wrapContentSize(align = Alignment.Center), ) } ) } @Sampled @Composable fun ChipWithIconAndLabels() { Chip( onClick = { /* Do something */ }, enabled = true, // When we have both label and secondary label present limit both to 1 line of text label = { Text(text = "Main label", maxLines = 1, overflow = TextOverflow.Ellipsis) }, secondaryLabel = { Text(text = "secondary label", maxLines = 1, overflow = TextOverflow.Ellipsis) }, icon = { Icon( painter = painterResource(id = R.drawable.ic_airplanemode_active_24px), contentDescription = "airplane", modifier = Modifier.size(ChipDefaults.IconSize) .wrapContentSize(align = Alignment.Center), ) } ) } @Sampled @Composable fun CompactChipWithIconAndLabel() { CompactChip( onClick = { /* Do something */ }, enabled = true, // CompactChip label should be no more than 1 line of text label = { Text("Single line label", maxLines = 1, overflow = TextOverflow.Ellipsis) }, icon = { Icon( painter = painterResource(id = R.drawable.ic_airplanemode_active_24px), contentDescription = "airplane", modifier = Modifier.size(ChipDefaults.SmallIconSize), ) }, ) } @Sampled @Composable fun CompactChipWithLabel() { CompactChip( onClick = { /* Do something */ }, enabled = true, // CompactChip label should be no more than 1 line of text label = { Text( text = "Single line label", maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth() ) }, ) } @Sampled @Composable fun CompactChipWithIcon() { CompactChip( onClick = { /* Do something */ }, enabled = true, icon = { Icon( painter = painterResource(id = R.drawable.ic_airplanemode_active_24px), contentDescription = "airplane", modifier = Modifier.size(ChipDefaults.IconSize) ) }, ) } @Sampled @Composable fun OutlinedCompactChipWithIconAndLabel() { OutlinedCompactChip( onClick = { /* Do something */ }, enabled = true, // CompactChip label should be no more than 1 line of text label = { Text("Single line label", maxLines = 1, overflow = TextOverflow.Ellipsis) }, icon = { Icon( painter = painterResource(id = R.drawable.ic_airplanemode_active_24px), contentDescription = "airplane", modifier = Modifier.size(ChipDefaults.SmallIconSize), ) }, ) }
apache-2.0
b707a4a8f9ca6c55187858b5fe31b314
31.2
94
0.604727
4.821963
false
false
false
false
Helabs/generator-he-kotlin-mvp
app/templates/app_mvp/src/main/kotlin/AppComponent.kt
1
494
package <%= appPackage %> import <%= appPackage %>.data.ApiModule import <%= appPackage %>.data.DataModule import <%= appPackage %>.ui.PresenterModule import <%= appPackage %>.ui.UiComponent import dagger.Component import javax.inject.Singleton @Singleton @Component(modules = arrayOf(ApplicationModule::class, ApiModule::class, DataModule::class)) interface AppComponent { fun inject(appApplication: AppApplication) operator fun plus(presenterModule: PresenterModule): UiComponent }
mit
9785aa9c285af70246127640e390a887
31.933333
92
0.773279
4.891089
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinMPPGradleModel.kt
1
2247
// 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. @file:Suppress("DeprecatedCallableAddReplaceWith") package org.jetbrains.kotlin.idea.gradleTooling import org.jetbrains.kotlin.idea.gradleTooling.arguments.AbstractCompilerArgumentsCacheAware import org.jetbrains.kotlin.idea.projectModel.* import org.jetbrains.plugins.gradle.model.ExternalDependency import org.jetbrains.plugins.gradle.model.ModelFactory import java.io.Serializable typealias KotlinDependency = ExternalDependency class KotlinDependencyMapper { private var currentIndex: KotlinDependencyId = 0 private val idToDependency = HashMap<KotlinDependencyId, KotlinDependency>() private val dependencyToId = HashMap<KotlinDependency, KotlinDependencyId>() fun getDependency(id: KotlinDependencyId) = idToDependency[id] fun getId(dependency: KotlinDependency): KotlinDependencyId { return dependencyToId[dependency] ?: let { currentIndex++ dependencyToId[dependency] = currentIndex idToDependency[currentIndex] = dependency return currentIndex } } fun toDependencyMap(): Map<KotlinDependencyId, KotlinDependency> = idToDependency } fun KotlinDependency.deepCopy(cache: MutableMap<Any, Any>): KotlinDependency { val cachedValue = cache[this] as? KotlinDependency return if (cachedValue != null) { cachedValue } else { val result = ModelFactory.createCopy(this) cache[this] = result result } } interface KotlinMPPGradleModel : KotlinSourceSetContainer, Serializable { val dependencyMap: Map<KotlinDependencyId, KotlinDependency> val targets: Collection<KotlinTarget> val extraFeatures: ExtraFeatures val kotlinNativeHome: String val partialCacheAware: CompilerArgumentsCacheAware @Deprecated("Use 'sourceSetsByName' instead", ReplaceWith("sourceSetsByName"), DeprecationLevel.ERROR) val sourceSets: Map<String, KotlinSourceSet> get() = sourceSetsByName override val sourceSetsByName: Map<String, KotlinSourceSet> companion object { const val NO_KOTLIN_NATIVE_HOME = "" } }
apache-2.0
d4d919e3731dafbc2d11e78ec46af6c3
35.852459
158
0.752559
5.467153
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/typealias/Basic.kt
10
227
//ALLOW_AST_ACCESS package test typealias S = String typealias SS = S typealias SSS = SS val x1: S = { "" }() val x2: SS = { "" }() val x3: SSS = { "" }() val x4: S? = { "" }() val x5: SS? = { "" }() val x6: SSS? = { "" }()
apache-2.0
0b408502021eb4f8f44a16f55d55a023
15.214286
23
0.480176
2.414894
false
true
false
false
chickenbane/workshop-jb
src/i_introduction/_4_Lambdas/Lambdas.kt
3
654
package i_introduction._4_Lambdas import util.* fun example() { val sum = { x: Int, y: Int -> x + y } val square: (Int) -> Int = { x -> x * x } sum(1, square(2)) == 5 } fun todoTask4(collection: Collection<Int>): Nothing = TODO( """ Task 4. Rewrite 'JavaCode4.task4()' in Kotlin using lambdas. You can find the appropriate function to call on 'collection' through IntelliJ's code completion feature. (Don't use the class 'Iterables'). """, documentation = doc4(), references = { JavaCode4().task4(collection) }) fun task4(collection: Collection<Int>): Boolean = todoTask4(collection)
mit
41503da2585ff73e3800fe80c853ee71
23.222222
113
0.619266
3.780347
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/preferences/EmailNotificationsPreferencesFragment.kt
1
4201
package com.habitrpg.android.habitica.ui.fragments.preferences import android.content.SharedPreferences import android.os.Bundle import androidx.preference.CheckBoxPreference import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.user.User import io.reactivex.functions.Consumer class EmailNotificationsPreferencesFragment : BasePreferencesFragment(), SharedPreferences.OnSharedPreferenceChangeListener { private var isInitialSet: Boolean = true private var isSettingUser: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { HabiticaBaseApplication.userComponent?.inject(this) super.onCreate(savedInstanceState) } override fun onResume() { super.onResume() preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this) } override fun onPause() { super.onPause() preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) } override fun setupPreferences() { /* no-on */ } override fun setUser(user: User?) { super.setUser(user) isSettingUser = !isInitialSet updatePreference("preference_email_you_won_challenge", user?.preferences?.emailNotifications?.wonChallenge) updatePreference("preference_email_received_a_private_message", user?.preferences?.emailNotifications?.newPM) updatePreference("preference_email_gifted_gems", user?.preferences?.emailNotifications?.giftedGems) updatePreference("preference_email_gifted_subscription", user?.preferences?.emailNotifications?.giftedSubscription) updatePreference("preference_email_invited_to_party", user?.preferences?.emailNotifications?.invitedParty) updatePreference("preference_email_invited_to_guild", user?.preferences?.emailNotifications?.invitedGuild) updatePreference("preference_email_your_quest_has_begun", user?.preferences?.emailNotifications?.questStarted) updatePreference("preference_email_invited_to_quest", user?.preferences?.emailNotifications?.invitedQuest) updatePreference("preference_email_important_announcements", user?.preferences?.emailNotifications?.majorUpdates) updatePreference("preference_email_kicked_group", user?.preferences?.emailNotifications?.kickedGroup) updatePreference("preference_email_onboarding", user?.preferences?.emailNotifications?.onboarding) updatePreference("preference_email_subscription_reminders", user?.preferences?.emailNotifications?.subscriptionReminders) isSettingUser = false isInitialSet = false } private fun updatePreference(key: String, isChecked: Boolean?) { val preference = (findPreference(key) as? CheckBoxPreference) preference?.isChecked = isChecked == true } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { if (isSettingUser) { return } val pathKey = when (key) { "preference_email_you_won_challenge" -> "wonChallenge" "preference_email_received_a_private_message" -> "newPM" "preference_email_gifted_gems" -> "giftedGems" "preference_email_gifted_subscription" -> "giftedSubscription" "preference_email_invited_to_party" -> "invitedParty" "preference_email_invited_to_guild" -> "invitedGuild" "preference_email_your_quest_has_begun" -> "questStarted" "preference_email_invited_to_quest" -> "invitedQuest" "preference_email_important_announcements" -> "majorUpdates" "preference_email_kicked_group" -> "kickedGroup" "preference_email_onboarding" -> "onboarding" "preference_email_subscription_reminders" -> "subscriptionReminders" else -> null } if (pathKey != null) { compositeSubscription.add(userRepository.updateUser(user, "preferences.emailNotifications.$pathKey", sharedPreferences.getBoolean(key, false)).subscribe(Consumer { }, RxErrorHandler.handleEmptyError())) } } }
gpl-3.0
115cd94aee34f4016936c755f67b1379
51.525
215
0.727684
5.173645
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/support/BugFixFragment.kt
1
4300
package com.habitrpg.android.habitica.ui.fragments.support import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.databinding.FragmentSupportBugFixBinding import com.habitrpg.android.habitica.helpers.AppConfigManager import com.habitrpg.android.habitica.helpers.AppTestingLevel import com.habitrpg.android.habitica.helpers.DeviceName import com.habitrpg.android.habitica.modules.AppModule import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment import io.reactivex.Completable import javax.inject.Inject import javax.inject.Named class BugFixFragment: BaseMainFragment() { private var deviceInfo: DeviceName.DeviceInfo? = null private lateinit var binding: FragmentSupportBugFixBinding @field:[Inject Named(AppModule.NAMED_USER_ID)] lateinit var userId: String @Inject lateinit var appConfigManager: AppConfigManager override fun injectFragment(component: UserComponent) { component.inject(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { hidesToolbar = true super.onCreateView(inflater, container, savedInstanceState) binding = FragmentSupportBugFixBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) compositeSubscription.add(Completable.fromAction { deviceInfo = DeviceName.getDeviceInfo(context) }.subscribe()) binding.reportBugButton.setOnClickListener { sendEmail("[Android] Bugreport") } } private val versionName: String by lazy { try { @Suppress("DEPRECATION") activity?.packageManager?.getPackageInfo(activity?.packageName, 0)?.versionName ?: "" } catch (e: PackageManager.NameNotFoundException) { "" } } private val versionCode: Int by lazy { try { @Suppress("DEPRECATION") activity?.packageManager?.getPackageInfo(activity?.packageName, 0)?.versionCode ?: 0 } catch (e: PackageManager.NameNotFoundException) { 0 } } private fun sendEmail(subject: String) { val version = Build.VERSION.SDK_INT val deviceName = deviceInfo?.name ?: DeviceName.getDeviceName() val manufacturer = deviceInfo?.manufacturer ?: Build.MANUFACTURER var bodyOfEmail = "Device: $manufacturer $deviceName" + " \nAndroid Version: $version"+ " \nAppVersion: " + getString(R.string.version_info, versionName, versionCode) if (appConfigManager.testingLevel().name != AppTestingLevel.PRODUCTION.name) { bodyOfEmail += " ${appConfigManager.testingLevel().name}" } bodyOfEmail += " \nUser ID: $userId" val user = this.user if (user != null) { bodyOfEmail += " \nLevel: " + (user.stats?.lvl ?: 0) + " \nClass: " + (if (user.preferences?.disableClasses == true) "Disabled" else (user.stats?.habitClass ?: "None")) + " \nIs in Inn: " + (user.preferences?.sleep ?: false) + " \nUses Costume: " + (user.preferences?.costume ?: false) + " \nCustom Day Start: " + (user.preferences?.dayStart ?: 0) + " \nTimezone Offset: " + (user.preferences?.timezoneOffset ?: 0) } bodyOfEmail += " \nDetails:\n" activity?.let { val emailIntent = Intent(Intent.ACTION_SENDTO) val mailto = "mailto:" + appConfigManager.supportEmail() + "&subject=" + Uri.encode(subject) + "&body=" + Uri.encode(bodyOfEmail) emailIntent.data = Uri.parse(mailto); startActivity(Intent.createChooser(emailIntent, "Choose an Email client :")) } } }
gpl-3.0
12eee883fe869307dcd0f9a79c02cbe2
38.1
135
0.657907
4.746137
false
true
false
false
NikAshanin/Design-Patterns-In-Swift-Compare-Kotlin
Structural/Facade/Facade.kt
1
971
// Implementation class ComplexSystemStore(val filePath: String) { init { println("Reading data from file: $filePath") } val store = HashMap<String, String>() fun store(key: String, payload: String) { store.put(key, payload) } fun read(key: String): String = store[key] ?: "" fun commit() = println("Storing cached data: $store to file: $filePath") } data class User(val login: String) class UserRepository { val systemPreferences = ComplexSystemStore("/data/default.prefs") fun save(user: User) { systemPreferences.store("USER_KEY", user.login) systemPreferences.commit() } fun findFirst(): User = User(systemPreferences.read("USER_KEY")) } // Usage fun main(args: Array<String>) { val userRepository = UserRepository() val user = User("dbacinski") userRepository.save(user) val resultUser = userRepository.findFirst() println("Found stored user: $resultUser") }
mit
539704812be9bff5fe3e513dd86c6d1a
22.707317
76
0.660144
3.979508
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/renderingKDoc/propertyRendering.kt
4
1528
/** * Hello darling * @author DarkWing Duck */ val prop = 2 /** * Hello darling var * @author Megavolt */ var prop = 2 class outherClass { /** * Hello darling instance * @author Morgana Macawber */ val instanceProp get() { /** * Hello darling local * @author Launchpad McQuack */ val localProp get() { if (true) { /** * Hello darling superLocal * @author Reginald Bushroot */ val superLocalProp = 4 } } } } // RENDER: <div class='content'><p>Hello darling</p></div><table class='sections'><tr><td valign='top' class='section'><p>Author:</td><td valign='top'>DarkWing Duck</td></table> // RENDER: <div class='content'><p>Hello darling var</p></div><table class='sections'><tr><td valign='top' class='section'><p>Author:</td><td valign='top'>Megavolt</td></table> // RENDER: <div class='content'><p>Hello darling instance</p></div><table class='sections'><tr><td valign='top' class='section'><p>Author:</td><td valign='top'>Morgana Macawber</td></table> // RENDER: <div class='content'><p>Hello darling local</p></div><table class='sections'><tr><td valign='top' class='section'><p>Author:</td><td valign='top'>Launchpad McQuack</td></table> // RENDER: <div class='content'><p>Hello darling superLocal</p></div><table class='sections'><tr><td valign='top' class='section'><p>Author:</td><td valign='top'>Reginald Bushroot</td></table>
apache-2.0
a97fbb7c32496e1e193b2c85220766ca
36.292683
192
0.592277
3.664269
false
false
false
false
JetBrains/kotlin-native
runtime/src/main/kotlin/generated/_StringUppercase.kt
1
2076
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package kotlin.text // // NOTE: THIS FILE IS AUTO-GENERATED by the GenerateUnicodeData.kt // See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib // internal fun String.codePointAt(index: Int): Int { val high = this[index] if (high.isHighSurrogate() && index + 1 < this.length) { val low = this[index + 1] if (low.isLowSurrogate()) { return Char.toCodePoint(high, low) } } return high.toInt() } internal fun Int.charCount(): Int = if (this >= Char.MIN_SUPPLEMENTARY_CODE_POINT) 2 else 1 internal fun StringBuilder.appendCodePoint(codePoint: Int) { if (codePoint < Char.MIN_SUPPLEMENTARY_CODE_POINT) { append(codePoint.toChar()) } else { append(Char.MIN_HIGH_SURROGATE + ((codePoint - 0x10000) shr 10)) append(Char.MIN_LOW_SURROGATE + (codePoint and 0x3ff)) } } internal fun String.uppercaseImpl(): String { var unchangedIndex = 0 while (unchangedIndex < this.length) { val codePoint = codePointAt(unchangedIndex) if (this[unchangedIndex].oneToManyUppercase() != null || codePoint.uppercaseCodePoint() != codePoint) { break } unchangedIndex += codePoint.charCount() } if (unchangedIndex == this.length) { return this } val sb = StringBuilder(this.length) sb.appendRange(this, 0, unchangedIndex) var index = unchangedIndex while (index < this.length) { val specialCasing = this[index].oneToManyUppercase() if (specialCasing != null) { sb.append(specialCasing) index++ continue } val codePoint = codePointAt(index) val uppercaseCodePoint = codePoint.uppercaseCodePoint() sb.appendCodePoint(uppercaseCodePoint) index += codePoint.charCount() } return sb.toString() }
apache-2.0
5d818d550548e0d7f21845bf9f20334d
29.985075
115
0.648362
4.062622
false
false
false
false
loxal/FreeEthereum
free-ethereum-core/src/test/java/org/ethereum/core/PruneTest.kt
1
23320
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * 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 org.ethereum.core import org.ethereum.config.SystemProperties import org.ethereum.crypto.ECKey import org.ethereum.crypto.HashUtil import org.ethereum.datasource.CountingBytesSource import org.ethereum.datasource.JournalSource import org.ethereum.datasource.Source import org.ethereum.datasource.inmem.HashMapDB import org.ethereum.db.ByteArrayWrapper import org.ethereum.trie.SecureTrie import org.ethereum.trie.TrieImpl import org.ethereum.util.ByteUtil.intToBytes import org.ethereum.util.FastByteComparisons import org.ethereum.util.blockchain.EtherUtil.Unit.ETHER import org.ethereum.util.blockchain.EtherUtil.convert import org.ethereum.util.blockchain.StandaloneBlockchain import org.junit.AfterClass import org.junit.Assert import org.junit.Assert.assertTrue import org.junit.Ignore import org.junit.Test import org.spongycastle.util.encoders.Hex import java.math.BigInteger import java.util.* class PruneTest { @Test @Throws(Exception::class) fun testJournal1() { val db = HashMapDB<ByteArray>() val countDB = CountingBytesSource(db) val journalDB = JournalSource(countDB) put(journalDB, "11") put(journalDB, "22") put(journalDB, "33") journalDB.commitUpdates(intToBytes(1)) checkKeys(db.storage, "11", "22", "33") put(journalDB, "22") delete(journalDB, "33") put(journalDB, "44") journalDB.commitUpdates(intToBytes(2)) checkKeys(db.storage, "11", "22", "33", "44") journalDB.persistUpdate(intToBytes(1)) checkKeys(db.storage, "11", "22", "33", "44") journalDB.revertUpdate(intToBytes(2)) checkKeys(db.storage, "11", "22", "33") put(journalDB, "22") delete(journalDB, "33") put(journalDB, "44") journalDB.commitUpdates(intToBytes(3)) checkKeys(db.storage, "11", "22", "33", "44") delete(journalDB, "22") put(journalDB, "33") delete(journalDB, "44") journalDB.commitUpdates(intToBytes(4)) checkKeys(db.storage, "11", "22", "33", "44") journalDB.persistUpdate(intToBytes(3)) checkKeys(db.storage, "11", "22", "33", "44") journalDB.persistUpdate(intToBytes(4)) checkKeys(db.storage, "11", "22", "33") delete(journalDB, "22") journalDB.commitUpdates(intToBytes(5)) checkKeys(db.storage, "11", "22", "33") journalDB.persistUpdate(intToBytes(5)) checkKeys(db.storage, "11", "33") } @Test @Throws(Exception::class) fun simpleTest() { val pruneCount = 3 SystemProperties.getDefault()!!.overrideParams( "database.prune.enabled", "true", "database.prune.maxDepth", "" + pruneCount, "mine.startNonce", "0") val bc = StandaloneBlockchain() val alice = ECKey.fromPrivate(BigInteger.ZERO) val bob = ECKey.fromPrivate(BigInteger.ONE) // System.out.println("Gen root: " + Hex.toHexString(bc.getBlockchain().getBestBlock().getStateRoot())); bc.createBlock() val b0 = bc.blockchain.bestBlock bc.sendEther(alice.address, convert(3, ETHER)) val b1_1 = bc.createBlock() bc.sendEther(alice.address, convert(3, ETHER)) val b1_2 = bc.createForkBlock(b0) bc.sendEther(alice.address, convert(3, ETHER)) val b1_3 = bc.createForkBlock(b0) bc.sendEther(alice.address, convert(3, ETHER)) val b1_4 = bc.createForkBlock(b0) bc.sendEther(bob.address, convert(5, ETHER)) bc.createBlock() bc.sendEther(alice.address, convert(3, ETHER)) bc.createForkBlock(b1_2) for (i in 0..8) { bc.sendEther(alice.address, convert(3, ETHER)) bc.sendEther(bob.address, convert(5, ETHER)) bc.createBlock() } val roots = arrayOfNulls<ByteArray>(pruneCount + 1) for (i in 0..pruneCount + 1 - 1) { val bNum = bc.blockchain.bestBlock.number - i val b = bc.blockchain.getBlockByNumber(bNum) roots[i] = b.stateRoot } checkPruning(bc.stateDS, bc.pruningStateDS, *roots) val bestBlockNum = bc.blockchain.bestBlock.number Assert.assertEquals(convert(30, ETHER), bc.blockchain.repository.getBalance(alice.address)) Assert.assertEquals(convert(50, ETHER), bc.blockchain.repository.getBalance(bob.address)) run { val b1 = bc.blockchain.getBlockByNumber(bestBlockNum - 1) val r1 = bc.blockchain.repository.getSnapshotTo(b1.stateRoot) Assert.assertEquals(convert((3 * 9).toLong(), ETHER), r1.getBalance(alice.address)) Assert.assertEquals(convert((5 * 9).toLong(), ETHER), r1.getBalance(bob.address)) } run { val b1 = bc.blockchain.getBlockByNumber(bestBlockNum - 2) val r1 = bc.blockchain.repository.getSnapshotTo(b1.stateRoot) Assert.assertEquals(convert((3 * 8).toLong(), ETHER), r1.getBalance(alice.address)) Assert.assertEquals(convert((5 * 8).toLong(), ETHER), r1.getBalance(bob.address)) } run { val b1 = bc.blockchain.getBlockByNumber(bestBlockNum - 3) val r1 = bc.blockchain.repository.getSnapshotTo(b1.stateRoot) Assert.assertEquals(convert((3 * 7).toLong(), ETHER), r1.getBalance(alice.address)) Assert.assertEquals(convert((5 * 7).toLong(), ETHER), r1.getBalance(bob.address)) } run { // this state should be pruned already val b1 = bc.blockchain.getBlockByNumber(bestBlockNum - 4) val r1 = bc.blockchain.repository.getSnapshotTo(b1.stateRoot) Assert.assertEquals(BigInteger.ZERO, r1.getBalance(alice.address)) Assert.assertEquals(BigInteger.ZERO, r1.getBalance(bob.address)) } } @Test @Throws(Exception::class) fun contractTest() { // checks that pruning doesn't delete the nodes which were 're-added' later // e.g. when a contract variable assigned value V1 the trie acquires node with key K1 // then if the variable reassigned value V2 the trie acquires new node with key K2 // and the node K1 is not needed anymore and added to the prune list // we should avoid situations when the value V1 is back, the node K1 is also back to the trie // but erroneously deleted later as was in the prune list val pruneCount = 3 SystemProperties.getDefault()!!.overrideParams( "database.prune.enabled", "true", "database.prune.maxDepth", "" + pruneCount) val bc = StandaloneBlockchain() val contr = bc.submitNewContract( "contract Simple {" + " uint public n;" + " function set(uint _n) { n = _n; } " + "}") bc.createBlock() // add/remove/add in the same block contr.callFunction("set", 0xaaaaaaaaaaaaL) contr.callFunction("set", 0xbbbbbbbbbbbbL) contr.callFunction("set", 0xaaaaaaaaaaaaL) bc.createBlock() Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr.callConstFunction("n")[0]) // force prune bc.createBlock() bc.createBlock() bc.createBlock() Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr.callConstFunction("n")[0]) for (i in 1..3) { for (j in 0..3) { contr.callFunction("set", 0xbbbbbbbbbbbbL) for (k in 0..j - 1) { bc.createBlock() } if (j > 0) Assert.assertEquals(BigInteger.valueOf(0xbbbbbbbbbbbbL), contr.callConstFunction("n")[0]) contr.callFunction("set", 0xaaaaaaaaaaaaL) for (k in 0..i - 1) { bc.createBlock() } Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr.callConstFunction("n")[0]) } } val roots = arrayOfNulls<ByteArray>(pruneCount + 1) for (i in 0..pruneCount + 1 - 1) { val bNum = bc.blockchain.bestBlock.number - i val b = bc.blockchain.getBlockByNumber(bNum) roots[i] = b.stateRoot } checkPruning(bc.stateDS, bc.pruningStateDS, *roots) } @Test @Throws(Exception::class) fun twoContractsTest() { val pruneCount = 3 SystemProperties.getDefault()!!.overrideParams( "database.prune.enabled", "true", "database.prune.maxDepth", "" + pruneCount) val src = "contract Simple {" + " uint public n;" + " function set(uint _n) { n = _n; } " + " function inc() { n++; } " + "}" val bc = StandaloneBlockchain() val b0 = bc.blockchain.bestBlock val contr1 = bc.submitNewContract(src) val contr2 = bc.submitNewContract(src) val b1 = bc.createBlock() checkPruning(bc.stateDS, bc.pruningStateDS, b1.stateRoot, b0.stateRoot) // add/remove/add in the same block contr1.callFunction("set", 0xaaaaaaaaaaaaL) contr2.callFunction("set", 0xaaaaaaaaaaaaL) val b2 = bc.createBlock() Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr1.callConstFunction("n")[0]) Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr2.callConstFunction("n")[0]) checkPruning(bc.stateDS, bc.pruningStateDS, b2.stateRoot, b1.stateRoot, b0.stateRoot) contr2.callFunction("set", 0xbbbbbbbbbbbbL) val b3 = bc.createBlock() Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr1.callConstFunction("n")[0]) Assert.assertEquals(BigInteger.valueOf(0xbbbbbbbbbbbbL), contr2.callConstFunction("n")[0]) checkPruning(bc.stateDS, bc.pruningStateDS, b3.stateRoot, b2.stateRoot, b1.stateRoot, b0.stateRoot) // force prune val b4 = bc.createBlock() checkPruning(bc.stateDS, bc.pruningStateDS, b4.stateRoot, b3.stateRoot, b2.stateRoot, b1.stateRoot) val b5 = bc.createBlock() checkPruning(bc.stateDS, bc.pruningStateDS, b5.stateRoot, b4.stateRoot, b3.stateRoot, b2.stateRoot) val b6 = bc.createBlock() Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr1.callConstFunction("n")[0]) Assert.assertEquals(BigInteger.valueOf(0xbbbbbbbbbbbbL), contr2.callConstFunction("n")[0]) checkPruning(bc.stateDS, bc.pruningStateDS, b6.stateRoot, b5.stateRoot, b4.stateRoot, b3.stateRoot) contr1.callFunction("set", 0xaaaaaaaaaaaaL) contr2.callFunction("set", 0xaaaaaaaaaaaaL) val b7 = bc.createBlock() Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr1.callConstFunction("n")[0]) Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr2.callConstFunction("n")[0]) checkPruning(bc.stateDS, bc.pruningStateDS, b7.stateRoot, b6.stateRoot, b5.stateRoot, b4.stateRoot) contr1.callFunction("set", 0xbbbbbbbbbbbbL) val b8 = bc.createBlock() Assert.assertEquals(BigInteger.valueOf(0xbbbbbbbbbbbbL), contr1.callConstFunction("n")[0]) Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr2.callConstFunction("n")[0]) checkPruning(bc.stateDS, bc.pruningStateDS, b8.stateRoot, b7.stateRoot, b6.stateRoot, b5.stateRoot) contr2.callFunction("set", 0xbbbbbbbbbbbbL) val b8_ = bc.createForkBlock(b7) checkPruning(bc.stateDS, bc.pruningStateDS, b8.stateRoot, b8_.stateRoot, b7.stateRoot, b6.stateRoot, b5.stateRoot) val b9_ = bc.createForkBlock(b8_) Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr1.callConstFunction("n")[0]) Assert.assertEquals(BigInteger.valueOf(0xbbbbbbbbbbbbL), contr2.callConstFunction("n")[0]) checkPruning(bc.stateDS, bc.pruningStateDS, b9_.stateRoot, b8.stateRoot, b8_.stateRoot, b7.stateRoot, b6.stateRoot) val b9 = bc.createForkBlock(b8) checkPruning(bc.stateDS, bc.pruningStateDS, b9.stateRoot, b9_.stateRoot, b8.stateRoot, b8_.stateRoot, b7.stateRoot, b6.stateRoot) val b10 = bc.createForkBlock(b9) Assert.assertEquals(BigInteger.valueOf(0xbbbbbbbbbbbbL), contr1.callConstFunction("n")[0]) Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr2.callConstFunction("n")[0]) checkPruning(bc.stateDS, bc.pruningStateDS, b10.stateRoot, b9.stateRoot, b9_.stateRoot, b8.stateRoot, b8_.stateRoot, b7.stateRoot) val b11 = bc.createForkBlock(b10) Assert.assertEquals(BigInteger.valueOf(0xbbbbbbbbbbbbL), contr1.callConstFunction("n")[0]) Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr2.callConstFunction("n")[0]) checkPruning(bc.stateDS, bc.pruningStateDS, b11.stateRoot, b10.stateRoot, b9.stateRoot, /*b9_.getStateRoot(),*/ b8.stateRoot) } @Test @Throws(Exception::class) fun branchTest() { val pruneCount = 3 SystemProperties.getDefault()!!.overrideParams( "database.prune.enabled", "true", "database.prune.maxDepth", "" + pruneCount) val bc = StandaloneBlockchain() val contr = bc.submitNewContract( "contract Simple {" + " uint public n;" + " function set(uint _n) { n = _n; } " + "}") val b1 = bc.createBlock() contr.callFunction("set", 0xaaaaaaaaaaaaL) val b2 = bc.createBlock() contr.callFunction("set", 0xbbbbbbbbbbbbL) val b2_ = bc.createForkBlock(b1) bc.createForkBlock(b2) bc.createBlock() bc.createBlock() bc.createBlock() Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr.callConstFunction("n")[0]) } @Test @Throws(Exception::class) fun storagePruneTest() { val pruneCount = 3 SystemProperties.getDefault()!!.overrideParams( "details.inmemory.storage.limit", "200", "database.prune.enabled", "true", "database.prune.maxDepth", "" + pruneCount) val bc = StandaloneBlockchain() val blockchain = bc.blockchain // RepositoryImpl repository = (RepositoryImpl) blockchain.getRepository(); // HashMapDB storageDS = new HashMapDB(); // repository.getDetailsDataStore().setStorageDS(storageDS); val contr = bc.submitNewContract( "contract Simple {" + " uint public n;" + " mapping(uint => uint) largeMap;" + " function set(uint _n) { n = _n; } " + " function put(uint k, uint v) { largeMap[k] = v; }" + "}") val b1 = bc.createBlock() val entriesForExtStorage = 100 for (i in 0..entriesForExtStorage - 1) { contr.callFunction("put", i, i) if (i % 100 == 0) bc.createBlock() } bc.createBlock() blockchain.flush() contr.callFunction("put", 1000000, 1) bc.createBlock() blockchain.flush() for (i in 0..99) { contr.callFunction("set", i) bc.createBlock() blockchain.flush() println(bc.stateDS.storage.size.toString() + ", " + bc.stateDS.storage.size) } println("Done") } @Ignore @Test @Throws(Exception::class) fun rewriteSameTrieNode() { val pruneCount = 3 SystemProperties.getDefault()!!.overrideParams( "database.prune.enabled", "true", "database.prune.maxDepth", "" + pruneCount) val bc = StandaloneBlockchain() val receiver = Hex.decode("0000000000000000000000000000000000000000") bc.sendEther(receiver, BigInteger.valueOf(0x77777777)) bc.createBlock() for (i in 0..99) { bc.sendEther(ECKey().address, BigInteger.valueOf(i.toLong())) } val contr = bc.submitNewContract( "contract Stupid {" + " function wrongAddress() { " + " address addr = 0x0000000000000000000000000000000000000000; " + " addr.call();" + " } " + "}") val b1 = bc.createBlock() contr.callFunction("wrongAddress") val b2 = bc.createBlock() contr.callFunction("wrongAddress") val b3 = bc.createBlock() Assert.assertEquals(BigInteger.valueOf(0xaaaaaaaaaaaaL), contr.callConstFunction("n")[0]) } private fun checkPruning(stateDS: HashMapDB<ByteArray>, stateJournalDS: Source<ByteArray, ByteArray>, vararg roots: ByteArray?) { println("Pruned storage size: " + stateDS.storage.size) val allRefs = HashSet<ByteArrayWrapper>() for (root in roots) { val bRefs = getReferencedTrieNodes(stateJournalDS, true, root) println("#" + Hex.toHexString(root).substring(0, 8) + " refs: ") for (bRef in bRefs) { println(" " + bRef.toString().substring(0, 8)) } allRefs.addAll(bRefs) } println("Trie nodes closure size: " + allRefs.size) if (allRefs.size != stateDS.storage.size) { stateDS.storage.keys .filterNot { allRefs.contains(ByteArrayWrapper(it)) } .forEach { println("Extra node: " + Hex.toHexString(it)) } // Assert.assertEquals(allRefs.size(), stateDS.getStorage().size()); } for (key in stateDS.storage.keys) { // Assert.assertTrue(allRefs.contains(new ByteArrayWrapper(key))); } } private fun getReferencedTrieNodes(stateDS: Source<ByteArray, ByteArray>, includeAccounts: Boolean, vararg roots: ByteArray?): Set<ByteArrayWrapper> { val ret = HashSet<ByteArrayWrapper>() roots .map { SecureTrie(stateDS, it) } .forEach { it.scanTree(object : TrieImpl.ScanAction { override fun doOnNode(hash: ByteArray, node: TrieImpl.Node) { ret.add(ByteArrayWrapper(hash)) } override fun doOnValue(nodeHash: ByteArray, node: TrieImpl.Node, key: ByteArray, value: ByteArray) { if (includeAccounts) { val accountState = AccountState(value) if (!FastByteComparisons.equal(accountState.codeHash, HashUtil.EMPTY_DATA_HASH)) { ret.add(ByteArrayWrapper(accountState.codeHash)) } if (!FastByteComparisons.equal(accountState.stateRoot, HashUtil.EMPTY_TRIE_HASH)) { ret.addAll(getReferencedTrieNodes(stateDS, false, accountState.stateRoot)) } } } }) } return ret } private fun dumpState(stateDS: Source<ByteArray, ByteArray>, includeAccounts: Boolean, root: ByteArray): String { val ret = StringBuilder() val trie = SecureTrie(stateDS, root) trie.scanTree(object : TrieImpl.ScanAction { override fun doOnNode(hash: ByteArray, node: TrieImpl.Node) {} override fun doOnValue(nodeHash: ByteArray, node: TrieImpl.Node, key: ByteArray, value: ByteArray) { if (includeAccounts) { val accountState = AccountState(value) ret.append(Hex.toHexString(nodeHash)).append(": Account: ").append(Hex.toHexString(key)).append(", Nonce: ").append(accountState.nonce).append(", Balance: ").append(accountState.balance).append("\n") if (!FastByteComparisons.equal(accountState.codeHash, HashUtil.EMPTY_DATA_HASH)) { ret.append(" CodeHash: ").append(Hex.toHexString(accountState.codeHash)).append("\n") } if (!FastByteComparisons.equal(accountState.stateRoot, HashUtil.EMPTY_TRIE_HASH)) { ret.append(dumpState(stateDS, false, accountState.stateRoot)) } } else { ret.append(" ").append(Hex.toHexString(nodeHash)).append(": ").append(Hex.toHexString(key)).append(" = ").append(Hex.toHexString(value)).append("\n") } } }) return ret.toString() } companion object { private val stateDS: HashMapDB<ByteArray>? = null @AfterClass fun cleanup() { SystemProperties.resetToDefault() } private fun put(db: Source<ByteArray, ByteArray>, key: String) { db.put(Hex.decode(key), Hex.decode(key)) } private fun delete(db: Source<ByteArray, ByteArray>, key: String) { db.delete(Hex.decode(key)) } private fun checkKeys(map: Map<ByteArray, ByteArray>, vararg keys: String) { Assert.assertEquals(keys.size.toLong(), map.size.toLong()) for (key in keys) { assertTrue(map.containsKey(Hex.decode(key))) } } internal fun getCount(hash: String): String { val bytes = stateDS!![Hex.decode(hash)] return if (bytes == null) "0" else "" + bytes[3] } } }
mit
edacaf68700881571c3349bca609e77f
39.84063
219
0.6006
4.460597
false
false
false
false
androidx/androidx
wear/compose/compose-material/src/commonMain/kotlin/androidx/wear/compose/material/ToggleControl.kt
3
35017
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.material import androidx.compose.animation.animateColor import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.updateTransition import androidx.compose.animation.core.Transition import androidx.compose.animation.core.tween import androidx.compose.foundation.Canvas import androidx.compose.foundation.Indication import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.requiredSize import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.selection.toggleable import androidx.compose.material.ripple.rememberRipple import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.runtime.remember import androidx.compose.runtime.State import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Fill import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.compositeOver import androidx.compose.ui.semantics.Role import androidx.compose.ui.unit.dp import androidx.compose.ui.util.lerp import kotlin.math.PI import kotlin.math.cos import kotlin.math.min import kotlin.math.sin /** * [Checkbox] provides an animated checkbox for use as a toggle control in * [ToggleChip] or [SplitToggleChip]. * * Example of a [SplitToggleChip] with [Checkbox] toggle control: * @sample androidx.wear.compose.material.samples.SplitToggleChipWithCheckbox * * @param checked Boolean flag indicating whether this checkbox is currently checked. * @param modifier Modifier to be applied to the checkbox. This can be used to provide a * content description for accessibility. * @param colors [CheckboxColors] from which the box and checkmark colors will be obtained. * @param enabled Boolean flag indicating the enabled state of the [Checkbox] (affects * the color). * @param onCheckedChange Callback to be invoked when Checkbox is clicked. If null, then this is * passive and relies entirely on a higher-level component to control the state * (such as [ToggleChip] or [SplitToggleChip]). * @param interactionSource When also providing [onCheckedChange], the [MutableInteractionSource] * representing the stream of [Interaction]s for the "toggleable" tap area - * can be used to customise the appearance / behavior of the Checkbox. */ @Composable public fun Checkbox( checked: Boolean, modifier: Modifier = Modifier, colors: CheckboxColors = CheckboxDefaults.colors(), enabled: Boolean = true, onCheckedChange: ((Boolean) -> Unit)? = null, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, ) { val targetState = if (checked) ToggleStage.Checked else ToggleStage.Unchecked val transition = updateTransition(targetState) val tickProgress = animateProgress(transition, "Checkbox") // For Checkbox, the color and alpha animations have the same duration and easing, // so we don't need to explicitly animate alpha. val boxColor = animateColor( transition, colorFn = { e, c -> colors.boxColor(enabled = e, checked = c) }, enabled = enabled ) val checkColor = animateColor( transition, colorFn = { e, c -> colors.checkmarkColor(enabled = e, checked = c) }, enabled = enabled ) Canvas( modifier = modifier.maybeToggleable( onCheckedChange, enabled, checked, interactionSource, rememberRipple(), Role.Checkbox ) ) { drawBox(color = boxColor.value) if (targetState == ToggleStage.Checked) { drawTick( tickProgress = tickProgress.value, tickColor = checkColor.value, ) } else { eraseTick( tickProgress = tickProgress.value, tickColor = checkColor.value, ) } } } /** * [Switch] provides an animated switch for use as a toggle control in * [ToggleChip] or [SplitToggleChip]. * * Example of a [ToggleChip] with [Switch] toggle control: * @sample androidx.wear.compose.material.samples.ToggleChipWithSwitch * * @param checked Boolean flag indicating whether this switch is currently toggled on. * @param modifier Modifier to be applied to the switch. This can be used to provide a * content description for accessibility. * @param colors [SwitchColors] from which the colors of the thumb and track will be obtained. * @param enabled Boolean flag indicating the enabled state of the [Switch] (affects * the color). * @param onCheckedChange Callback to be invoked when Switch is clicked. If null, then this is * passive and relies entirely on a higher-level component to control the state * (such as [ToggleChip] or [SplitToggleChip]). * @param interactionSource When also providing [onCheckedChange], the [MutableInteractionSource] * representing the stream of [Interaction]s for the "toggleable" tap area - * can be used to customise the appearance / behavior of the Switch. */ @Composable public fun Switch( checked: Boolean, modifier: Modifier = Modifier, colors: SwitchColors = SwitchDefaults.colors(), enabled: Boolean = true, onCheckedChange: ((Boolean) -> Unit)? = null, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, ) { val targetState = if (checked) ToggleStage.Checked else ToggleStage.Unchecked val transition = updateTransition(targetState) // For Switch, the color and alpha animations have the same duration and easing, // so we don't need to explicitly animate alpha. val thumbProgress = animateProgress(transition, "Switch") val thumbColor = animateColor( transition, { e, c -> colors.thumbColor(enabled = e, checked = c) }, enabled ) val trackColor = animateColor( transition, { e, c -> colors.trackColor(enabled = e, checked = c) }, enabled ) Canvas( modifier = modifier.maybeToggleable( onCheckedChange, enabled, checked, interactionSource, rememberRipple(), Role.Switch ) ) { val switchTrackLengthPx = SWITCH_TRACK_LENGTH.toPx() val switchTrackHeightPx = SWITCH_TRACK_HEIGHT.toPx() val switchThumbRadiusPx = SWITCH_THUMB_RADIUS.toPx() val thumbProgressPx = lerp( start = switchThumbRadiusPx, stop = switchTrackLengthPx - switchThumbRadiusPx, fraction = thumbProgress.value ) drawTrack(trackColor.value, switchTrackLengthPx, switchTrackHeightPx) // Use BlendMode.Src to overwrite overlapping pixels with the thumb color // (by default, the track shows through any transparency). drawCircle( color = thumbColor.value, radius = switchThumbRadiusPx, center = Offset(thumbProgressPx, center.y), blendMode = BlendMode.Src) } } /** * [RadioButton] provides an animated radio button for use as a toggle control in * [ToggleChip] or [SplitToggleChip]. * * Example of a [ToggleChip] with [RadioButton] toggle control: * @sample androidx.wear.compose.material.samples.ToggleChipWithRadioButton * * @param selected Boolean flag indicating whether this radio button is currently toggled on. * @param modifier Modifier to be applied to the radio button. This can be used to provide a * content description for accessibility. * @param colors [ToggleChipColors] from which the toggleControlColors will be obtained. * @param enabled Boolean flag indicating the enabled state of the [RadioButton] (affects * the color). * @param onClick Callback to be invoked when RadioButton is clicked. If null, then this is * passive and relies entirely on a higher-level component to control the state * (such as [ToggleChip] or [SplitToggleChip]). * @param interactionSource When also providing [onClick], the [MutableInteractionSource] * representing the stream of [Interaction]s for the "toggleable" tap area - * can be used to customise the appearance / behavior of the RadioButton. */ @Composable public fun RadioButton( selected: Boolean, modifier: Modifier = Modifier, colors: RadioButtonColors = RadioButtonDefaults.colors(), enabled: Boolean = true, onClick: (() -> Unit)? = null, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, ) { val targetState = if (selected) ToggleStage.Checked else ToggleStage.Unchecked val transition = updateTransition(targetState) val circleColor = animateColor( transition, colorFn = { e, s -> colors.ringColor(enabled = e, selected = s) }, enabled ) val dotRadiusProgress = animateProgress( transition, durationMillis = if (selected) QUICK else STANDARD, label = "dot-radius" ) val dotColor = animateColor( transition, colorFn = { e, s -> colors.dotColor(enabled = e, selected = s) }, enabled ) // Animation of the dot alpha only happens when toggling On to Off. val dotAlphaProgress = if (targetState == ToggleStage.Unchecked) animateProgress( transition, durationMillis = RAPID, delayMillis = FLASH, label = "dot-alpha" ) else null Canvas( modifier = modifier.maybeSelectable( onClick, enabled, selected, interactionSource, rememberRipple() ) ) { // Outer circle has a constant radius. drawCircle( radius = RADIO_CIRCLE_RADIUS.toPx(), color = circleColor.value, center = center, style = Stroke(RADIO_CIRCLE_STROKE.toPx()), ) // Inner dot radius expands/shrinks. drawCircle( radius = dotRadiusProgress.value * RADIO_DOT_RADIUS.toPx(), color = dotColor.value.copy( alpha = (dotAlphaProgress?.value ?: 1f) * dotColor.value.alpha ), center = center, style = Fill, ) } } /** * Represents the content colors used in [Checkbox] in different states. */ @Stable public interface CheckboxColors { /** * Represents the box color for this [Checkbox], depending on the [enabled] and [checked] * properties. * * @param enabled Whether the [Checkbox] is enabled * @param checked Whether the [Checkbox] is currently checked or unchecked */ @Composable public fun boxColor(enabled: Boolean, checked: Boolean): State<Color> /** * Represents the checkmark color for this [Checkbox], depending on the [enabled] and [checked] * properties. * * @param enabled Whether the [Checkbox] is enabled * @param checked Whether the [Checkbox] is currently checked or unchecked */ @Composable public fun checkmarkColor(enabled: Boolean, checked: Boolean): State<Color> } /** * Represents the content colors used in [Switch] in different states. */ @Stable public interface SwitchColors { /** * Represents the thumb color for this [Switch], depending on the [enabled] and [checked] * properties. * * @param enabled Whether the [Switch] is enabled * @param checked Whether the [Switch] is currently checked or unchecked */ @Composable public fun thumbColor(enabled: Boolean, checked: Boolean): State<Color> /** * Represents the track color for this [Switch], depending on the [enabled] and [checked] * properties. * * @param enabled Whether the [Switch] is enabled * @param checked Whether the [Switch] is currently checked or unchecked */ @Composable public fun trackColor(enabled: Boolean, checked: Boolean): State<Color> } /** * Represents the content colors used in [RadioButton] in different states. */ @Stable public interface RadioButtonColors { /** * Represents the outer ring color for this [RadioButton], depending on * the [enabled] and [selected] properties. * * @param enabled Whether the [RadioButton] is enabled * @param selected Whether the [RadioButton] is currently selected or unselected */ @Composable public fun ringColor(enabled: Boolean, selected: Boolean): State<Color> /** * Represents the inner dot color for this [RadioButton], depending on * the [enabled] and [selected] properties. * * @param enabled Whether the [RadioButton] is enabled * @param selected Whether the [RadioButton] is currently selected or unselected */ @Composable public fun dotColor(enabled: Boolean, selected: Boolean): State<Color> } /** * Contains the default values used by [Checkbox]. */ public object CheckboxDefaults { /** * Creates a [CheckboxColors] for use in a [Checkbox]. * * @param checkedBoxColor The box color of this [Checkbox] when enabled and checked. * @param uncheckedBoxColor The box color of this [Checkbox] when enabled and unchecked. * @param checkedCheckmarkColor The check mark color of this [Checkbox] when enabled * and checked. * @param uncheckedCheckmarkColor The check mark color of this [Checkbox] when enabled * and unchecked. */ @Composable public fun colors( checkedBoxColor: Color = MaterialTheme.colors.secondary, checkedCheckmarkColor: Color = checkedBoxColor, uncheckedBoxColor: Color = contentColorFor( MaterialTheme.colors.primary.copy(alpha = 0.5f) .compositeOver(MaterialTheme.colors.surface) ), uncheckedCheckmarkColor: Color = uncheckedBoxColor, ): CheckboxColors { return DefaultCheckboxColors( checkedBoxColor = checkedBoxColor, checkedCheckmarkColor = checkedCheckmarkColor, uncheckedBoxColor = uncheckedBoxColor, uncheckedCheckmarkColor = uncheckedCheckmarkColor, disabledCheckedBoxColor = checkedBoxColor.copy(alpha = ContentAlpha.disabled), disabledCheckedCheckmarkColor = checkedCheckmarkColor.copy(alpha = ContentAlpha.disabled), disabledUncheckedBoxColor = uncheckedBoxColor.copy(alpha = ContentAlpha.disabled), disabledUncheckedCheckmarkColor = uncheckedCheckmarkColor.copy(alpha = ContentAlpha.disabled), ) } } /** * Contains the default values used by [Switch]. */ public object SwitchDefaults { /** * Creates a [SwitchColors] for use in a [Switch]. * * @param checkedThumbColor The thumb color of this [Switch] when enabled and checked. * @param checkedTrackColor The track color of this [Switch] when enabled and checked. * @param uncheckedThumbColor The thumb color of this [Switch] when enabled and unchecked. * @param uncheckedTrackColor The track color of this [Switch] when enabled and unchecked. */ @Composable public fun colors( checkedThumbColor: Color = MaterialTheme.colors.secondary, checkedTrackColor: Color = checkedThumbColor.copy(alpha = ContentAlpha.disabled), uncheckedThumbColor: Color = MaterialTheme.colors.onSurface.copy(alpha = 0.6f), uncheckedTrackColor: Color = uncheckedThumbColor.copy(alpha = uncheckedThumbColor.alpha * ContentAlpha.disabled), ): SwitchColors { return DefaultSwitchColors( checkedThumbColor = checkedThumbColor, checkedTrackColor = checkedTrackColor, uncheckedThumbColor = uncheckedThumbColor, uncheckedTrackColor = uncheckedTrackColor, disabledCheckedThumbColor = checkedThumbColor.copy(alpha = ContentAlpha.disabled), disabledCheckedTrackColor = checkedTrackColor.copy( alpha = checkedTrackColor.alpha * ContentAlpha.disabled ), disabledUncheckedThumbColor = uncheckedThumbColor.copy(alpha = uncheckedThumbColor.alpha * ContentAlpha.disabled), disabledUncheckedTrackColor = uncheckedTrackColor.copy(alpha = uncheckedTrackColor.alpha * ContentAlpha.disabled), ) } } /** * Contains the default values used by [RadioButton]. */ public object RadioButtonDefaults { /** * Creates a [RadioButtonColors] for use in a [RadioButton]. * * @param selectedRingColor The outer ring color of this [RadioButton] when enabled * and selected. * @param selectedDotColor The inner dot color of this [RadioButton] when enabled * and selected. * @param unselectedRingColor The outer ring color of this [RadioButton] when enabled * and unselected. * @param unselectedDotColor The inner dot color of this [RadioButton] when enabled * and unselected. */ @Composable public fun colors( selectedRingColor: Color = MaterialTheme.colors.secondary, selectedDotColor: Color = MaterialTheme.colors.secondary, unselectedRingColor: Color = contentColorFor( MaterialTheme.colors.primary.copy(alpha = 0.5f) .compositeOver(MaterialTheme.colors.surface) ), unselectedDotColor: Color = contentColorFor( MaterialTheme.colors.primary.copy(alpha = 0.5f) .compositeOver(MaterialTheme.colors.surface) ), ): RadioButtonColors { return DefaultRadioButtonColors( selectedRingColor = selectedRingColor, selectedDotColor = selectedDotColor, unselectedRingColor = unselectedRingColor, unselectedDotColor = unselectedDotColor, disabledSelectedRingColor = selectedRingColor.copy(alpha = ContentAlpha.disabled), disabledSelectedDotColor = selectedDotColor.copy(alpha = ContentAlpha.disabled), disabledUnselectedRingColor = unselectedRingColor.copy(alpha = ContentAlpha.disabled), disabledUnselectedDotColor = unselectedDotColor.copy(alpha = ContentAlpha.disabled), ) } } @Composable private fun animateProgress( transition: Transition<ToggleStage>, label: String, durationMillis: Int = QUICK, delayMillis: Int = 0, ) = transition.animateFloat( transitionSpec = { tween(durationMillis = durationMillis, delayMillis = delayMillis, easing = STANDARD_IN) }, label = label ) { // Return the tick progress as a Float in Px. when (it) { ToggleStage.Unchecked -> 0f ToggleStage.Checked -> 1f } } @Composable private fun animateColor( transition: Transition<ToggleStage>, colorFn: @Composable (enabled: Boolean, checked: Boolean) -> State<Color>, enabled: Boolean ): State<Color> = transition.animateColor( transitionSpec = { tween(durationMillis = QUICK, easing = STANDARD_IN) }, label = "content-color" ) { colorFn(enabled, (it == ToggleStage.Checked)).value } private fun Modifier.maybeToggleable( onCheckedChange: ((Boolean) -> Unit)?, enabled: Boolean, checked: Boolean, interactionSource: MutableInteractionSource, indication: Indication, role: Role, ): Modifier { val standardModifier = this .wrapContentSize(Alignment.Center) .requiredSize(24.dp) return if (onCheckedChange == null) { standardModifier } else { standardModifier.then( Modifier.toggleable( enabled = enabled, value = checked, onValueChange = onCheckedChange, role = role, indication = indication, interactionSource = interactionSource ) ) } } private fun Modifier.maybeSelectable( onClick: (() -> Unit)?, enabled: Boolean, selected: Boolean, interactionSource: MutableInteractionSource, indication: Indication, ): Modifier { val standardModifier = this .wrapContentSize(Alignment.Center) .requiredSize(24.dp) return if (onClick == null) { standardModifier } else { standardModifier.then( Modifier.selectable( selected = selected, interactionSource = interactionSource, indication = indication, enabled = enabled, role = Role.RadioButton, onClick = onClick, ) ) } } private fun DrawScope.drawBox(color: Color) { val topCornerPx = BOX_CORNER.toPx() val strokeWidthPx = BOX_STROKE.toPx() val halfStrokeWidthPx = strokeWidthPx / 2.0f val radiusPx = BOX_RADIUS.toPx() val checkboxSizePx = BOX_SIZE.toPx() drawRoundRect( color, topLeft = Offset(topCornerPx + halfStrokeWidthPx, topCornerPx + halfStrokeWidthPx), size = Size(checkboxSizePx - strokeWidthPx, checkboxSizePx - strokeWidthPx), cornerRadius = CornerRadius(radiusPx - halfStrokeWidthPx), style = Stroke(strokeWidthPx) ) } private fun DrawScope.drawTick(tickColor: Color, tickProgress: Float) { // Using tickProgress animating from zero to TICK_TOTAL_LENGTH, // rotate the tick as we draw from 15 degrees to zero. val tickBaseLength = TICK_BASE_LENGTH.toPx() val tickStickLength = TICK_STICK_LENGTH.toPx() val tickTotalLength = tickBaseLength + tickStickLength val tickProgressPx = tickProgress * tickTotalLength val center = Offset(12.dp.toPx(), 12.dp.toPx()) val angle = TICK_ROTATION - TICK_ROTATION / tickTotalLength * tickProgressPx val angleRadians = angle.toRadians() // Animate the base of the tick. val baseStart = Offset(6.7f.dp.toPx(), 12.3f.dp.toPx()) val tickBaseProgress = min(tickProgressPx, tickBaseLength) val path = Path() path.moveTo(baseStart.rotate(angleRadians, center)) path.lineTo((baseStart + Offset(tickBaseProgress, tickBaseProgress)) .rotate(angleRadians, center)) if (tickProgressPx > tickBaseLength) { val tickStickProgress = min(tickProgressPx - tickBaseLength, tickStickLength) val stickStart = Offset(9.3f.dp.toPx(), 16.3f.dp.toPx()) // Move back to the start of the stick (without drawing) path.moveTo(stickStart.rotate(angleRadians, center)) path.lineTo( Offset(stickStart.x + tickStickProgress, stickStart.y - tickStickProgress) .rotate(angleRadians, center)) } // Use StrokeCap.Butt because Square adds an extension on the end of each line. drawPath(path, tickColor, style = Stroke(width = 2.dp.toPx(), cap = StrokeCap.Butt)) } private fun DrawScope.eraseTick(tickColor: Color, tickProgress: Float) { val tickBaseLength = TICK_BASE_LENGTH.toPx() val tickStickLength = TICK_STICK_LENGTH.toPx() val tickTotalLength = tickBaseLength + tickStickLength val tickProgressPx = tickProgress * tickTotalLength // Animate the stick of the tick, drawing down the stick from the top. val stickStartX = 17.3f.dp.toPx() val stickStartY = 8.3f.dp.toPx() val tickStickProgress = min(tickProgressPx, tickStickLength) val path = Path() path.moveTo(stickStartX, stickStartY) path.lineTo(stickStartX - tickStickProgress, stickStartY + tickStickProgress) if (tickStickProgress > tickStickLength) { // Animate the base of the tick, drawing up the base from bottom of the stick. val tickBaseProgress = min(tickProgressPx - tickStickLength, tickBaseLength) val baseStartX = 10.7f.dp.toPx() val baseStartY = 16.3f.dp.toPx() path.moveTo(baseStartX, baseStartY) path.lineTo(baseStartX - tickBaseProgress, baseStartY - tickBaseProgress) } drawPath(path, tickColor, style = Stroke(width = 2.dp.toPx(), cap = StrokeCap.Butt)) } private fun DrawScope.drawTrack( color: Color, switchTrackLengthPx: Float, switchTrackHeightPx: Float, ) { val path = Path() val strokeRadius = switchTrackHeightPx / 2f path.moveTo(Offset(strokeRadius, center.y)) path.lineTo(Offset(switchTrackLengthPx - strokeRadius, center.y)) drawPath( path = path, color = color, style = Stroke(width = switchTrackHeightPx, cap = StrokeCap.Round) ) } /** * Default [CheckboxColors] implementation. */ @Immutable private class DefaultCheckboxColors( private val checkedBoxColor: Color, private val checkedCheckmarkColor: Color, private val uncheckedCheckmarkColor: Color, private val uncheckedBoxColor: Color, private val disabledCheckedBoxColor: Color, private val disabledCheckedCheckmarkColor: Color, private val disabledUncheckedBoxColor: Color, private val disabledUncheckedCheckmarkColor: Color, ) : CheckboxColors { @Composable override fun boxColor(enabled: Boolean, checked: Boolean): State<Color> { return rememberUpdatedState( if (enabled) { if (checked) checkedBoxColor else uncheckedBoxColor } else { if (checked) disabledCheckedBoxColor else disabledUncheckedBoxColor } ) } @Composable override fun checkmarkColor(enabled: Boolean, checked: Boolean): State<Color> { return rememberUpdatedState( if (enabled) { if (checked) checkedCheckmarkColor else uncheckedCheckmarkColor } else { if (checked) disabledCheckedCheckmarkColor else disabledUncheckedCheckmarkColor } ) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null) return false if (this::class != other::class) return false other as DefaultCheckboxColors if (checkedBoxColor != other.checkedBoxColor) return false if (checkedCheckmarkColor != other.checkedCheckmarkColor) return false if (uncheckedCheckmarkColor != other.uncheckedCheckmarkColor) return false if (uncheckedBoxColor != other.uncheckedBoxColor) return false if (disabledCheckedBoxColor != other.disabledCheckedBoxColor) return false if (disabledCheckedCheckmarkColor != other.disabledCheckedCheckmarkColor) return false if (disabledUncheckedBoxColor != other.disabledUncheckedBoxColor) return false if (disabledUncheckedCheckmarkColor != other.disabledUncheckedCheckmarkColor) return false return true } override fun hashCode(): Int { var result = checkedBoxColor.hashCode() result = 31 * result + checkedCheckmarkColor.hashCode() result = 31 * result + uncheckedCheckmarkColor.hashCode() result = 31 * result + uncheckedBoxColor.hashCode() result = 31 * result + disabledCheckedBoxColor.hashCode() result = 31 * result + disabledCheckedCheckmarkColor.hashCode() result = 31 * result + disabledUncheckedBoxColor.hashCode() result = 31 * result + disabledUncheckedCheckmarkColor.hashCode() return result } } /** * Default [SwitchColors] implementation. */ @Immutable private class DefaultSwitchColors( private val checkedThumbColor: Color, private val checkedTrackColor: Color, private val uncheckedThumbColor: Color, private val uncheckedTrackColor: Color, private val disabledCheckedThumbColor: Color, private val disabledCheckedTrackColor: Color, private val disabledUncheckedThumbColor: Color, private val disabledUncheckedTrackColor: Color, ) : SwitchColors { @Composable override fun thumbColor(enabled: Boolean, checked: Boolean): State<Color> { return rememberUpdatedState( if (enabled) { if (checked) checkedThumbColor else uncheckedThumbColor } else { if (checked) disabledCheckedThumbColor else disabledUncheckedThumbColor } ) } @Composable override fun trackColor(enabled: Boolean, checked: Boolean): State<Color> { return rememberUpdatedState( if (enabled) { if (checked) checkedTrackColor else uncheckedTrackColor } else { if (checked) disabledCheckedTrackColor else disabledUncheckedTrackColor } ) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null) return false if (this::class != other::class) return false other as DefaultSwitchColors if (checkedThumbColor != other.checkedThumbColor) return false if (checkedTrackColor != other.checkedTrackColor) return false if (uncheckedThumbColor != other.uncheckedThumbColor) return false if (uncheckedTrackColor != other.uncheckedTrackColor) return false if (disabledCheckedThumbColor != other.disabledCheckedThumbColor) return false if (disabledCheckedTrackColor != other.disabledCheckedTrackColor) return false if (disabledUncheckedThumbColor != other.disabledUncheckedThumbColor) return false if (disabledUncheckedTrackColor != other.disabledUncheckedTrackColor) return false return true } override fun hashCode(): Int { var result = checkedThumbColor.hashCode() result = 31 * result + checkedTrackColor.hashCode() result = 31 * result + uncheckedThumbColor.hashCode() result = 31 * result + uncheckedTrackColor.hashCode() result = 31 * result + disabledCheckedThumbColor.hashCode() result = 31 * result + disabledCheckedTrackColor.hashCode() result = 31 * result + disabledUncheckedThumbColor.hashCode() result = 31 * result + disabledUncheckedTrackColor.hashCode() return result } } /** * Default [SwitchColors] implementation. */ @Immutable private class DefaultRadioButtonColors( private val selectedRingColor: Color, private val selectedDotColor: Color, private val unselectedRingColor: Color, private val unselectedDotColor: Color, private val disabledSelectedRingColor: Color, private val disabledSelectedDotColor: Color, private val disabledUnselectedRingColor: Color, private val disabledUnselectedDotColor: Color, ) : RadioButtonColors { @Composable override fun ringColor(enabled: Boolean, selected: Boolean): State<Color> { return rememberUpdatedState( if (enabled) { if (selected) selectedRingColor else unselectedRingColor } else { if (selected) disabledSelectedRingColor else disabledUnselectedRingColor } ) } @Composable override fun dotColor(enabled: Boolean, selected: Boolean): State<Color> { return rememberUpdatedState( if (enabled) { if (selected) selectedDotColor else unselectedDotColor } else { if (selected) disabledSelectedDotColor else disabledUnselectedDotColor } ) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null) return false if (this::class != other::class) return false other as DefaultRadioButtonColors if (selectedRingColor != other.selectedRingColor) return false if (selectedDotColor != other.selectedDotColor) return false if (unselectedRingColor != other.unselectedRingColor) return false if (unselectedDotColor != other.unselectedDotColor) return false if (disabledSelectedRingColor != other.disabledSelectedRingColor) return false if (disabledSelectedDotColor != other.disabledSelectedDotColor) return false if (disabledUnselectedRingColor != other.disabledUnselectedRingColor) return false if (disabledUnselectedDotColor != other.disabledUnselectedDotColor) return false return true } override fun hashCode(): Int { var result = selectedRingColor.hashCode() result = 31 * result + selectedDotColor.hashCode() result = 31 * result + unselectedRingColor.hashCode() result = 31 * result + unselectedDotColor.hashCode() result = 31 * result + disabledSelectedRingColor.hashCode() result = 31 * result + disabledSelectedDotColor.hashCode() result = 31 * result + disabledUnselectedRingColor.hashCode() result = 31 * result + disabledUnselectedDotColor.hashCode() return result } } private fun Path.moveTo(offset: Offset) { moveTo(offset.x, offset.y) } private fun Path.lineTo(offset: Offset) { lineTo(offset.x, offset.y) } private fun Offset.rotate(angleRadians: Float): Offset { val angledDirection = directionVector(angleRadians) return angledDirection * x + angledDirection.rotate90() * y } private fun Offset.rotate(angleRadians: Float, center: Offset): Offset = (this - center).rotate(angleRadians) + center private fun directionVector(angleRadians: Float) = Offset(cos(angleRadians), sin(angleRadians)) private fun Offset.rotate90() = Offset(-y, x) // This is duplicated from wear.compose.foundation/geometry.kt // Any changes should be replicated there. private fun Float.toRadians() = this * PI.toFloat() / 180f private enum class ToggleStage { Unchecked, Checked } private val BOX_CORNER = 3.dp private val BOX_STROKE = 2.dp private val BOX_RADIUS = 2.dp private val BOX_SIZE = 18.dp private val TICK_BASE_LENGTH = 4.dp private val TICK_STICK_LENGTH = 8.dp private const val TICK_ROTATION = 15f private val SWITCH_TRACK_LENGTH = 24.dp private val SWITCH_TRACK_HEIGHT = 10.dp private val SWITCH_THUMB_RADIUS = 7.dp private val RADIO_CIRCLE_RADIUS = 9.dp private val RADIO_CIRCLE_STROKE = 2.dp private val RADIO_DOT_RADIUS = 5.dp
apache-2.0
7a1ee819a0c415ee2acfa401e0a464fd
37.779623
100
0.689122
5.025402
false
false
false
false
djkovrik/YapTalker
app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/posting/adapter/EmojiAdapter.kt
1
2114
package com.sedsoftware.yaptalker.presentation.feature.posting.adapter import androidx.recyclerview.widget.RecyclerView import android.view.ViewGroup import com.sedsoftware.yaptalker.R import com.sedsoftware.yaptalker.presentation.extensions.inflate import com.sedsoftware.yaptalker.presentation.extensions.loadFromUrl import com.sedsoftware.yaptalker.presentation.extensions.loadFromUrlWithGifSupport import com.sedsoftware.yaptalker.presentation.model.base.EmojiModel import kotlinx.android.synthetic.main.fragment_new_post_bottom_sheet_item.view.emoji_code import kotlinx.android.synthetic.main.fragment_new_post_bottom_sheet_item.view.emoji_container import kotlinx.android.synthetic.main.fragment_new_post_bottom_sheet_item.view.emoji_image import java.util.ArrayList import javax.inject.Inject class EmojiAdapter @Inject constructor( private val clickListener: EmojiClickListener ) : RecyclerView.Adapter<EmojiAdapter.EmojiViewHolder>() { private var items: ArrayList<EmojiModel> = ArrayList() init { setHasStableIds(true) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = EmojiViewHolder(parent) override fun onBindViewHolder(holder: EmojiViewHolder, position: Int) { holder.bindTo(items[position]) } override fun getItemId(position: Int): Long = position.toLong() override fun getItemCount(): Int = items.size fun addEmojiItem(item: EmojiModel) { val insertPosition = items.size items.add(item) notifyItemInserted(insertPosition) } fun clearEmojiList() { notifyItemRangeRemoved(0, items.size) items.clear() } inner class EmojiViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(parent.inflate(R.layout.fragment_new_post_bottom_sheet_item)) { fun bindTo(emoji: EmojiModel) { with(itemView) { emoji_code.text = emoji.code emoji_image.loadFromUrlWithGifSupport(emoji.link) emoji_container.setOnClickListener { clickListener.onEmojiClicked(emoji.code) } } } } }
apache-2.0
9d7fb2a8c0e8a3b153d3e2404f967fb6
35.448276
95
0.742668
4.441176
false
false
false
false
jwren/intellij-community
plugins/settings-sync/src/com/intellij/settingsSync/SettingsSyncHistoryAction.kt
3
1512
package com.intellij.settingsSync import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.Messages import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.wm.ToolWindowManager import git4idea.GitVcs import git4idea.log.showExternalGitLogInToolwindow import java.util.function.Supplier class SettingsSyncHistoryAction : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val settingsSyncStorage = SettingsSyncMain.getInstance().controls.settingsSyncStorage val virtualFile = VfsUtil.findFile(settingsSyncStorage, true) if (virtualFile == null) { Messages.showErrorDialog(SettingsSyncBundle.message("history.error.message"), SettingsSyncBundle.message("history.dialog.title")) return } val toolWindowId = "SettingsSync" val toolWindowManager = ToolWindowManager.getInstance(project) val toolWindow = toolWindowManager.getToolWindow(toolWindowId) ?: toolWindowManager.registerToolWindow(toolWindowId) { stripeTitle = Supplier { SettingsSyncBundle.message("title.settings.sync") } } showExternalGitLogInToolwindow(project, toolWindow, GitVcs.getInstance(project), listOf(virtualFile), SettingsSyncBundle.message("history.tab.name"), "") } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = e.project != null && isSettingsSyncEnabledByKey() } }
apache-2.0
fd7d8a70476265c06f10bf6662c12d85
43.5
135
0.77381
5.04
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ListEntityImpl.kt
2
7175
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ListEntityImpl(val dataSource: ListEntityData) : ListEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val data: List<String> get() = dataSource.data override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: ListEntityData?) : ModifiableWorkspaceEntityBase<ListEntity, ListEntityData>(result), ListEntity.Builder { constructor() : this(ListEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ListEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isDataInitialized()) { error("Field ListEntity#data should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override fun afterModification() { val collection_data = getEntityData().data if (collection_data is MutableWorkspaceList<*>) { collection_data.cleanModificationUpdateAction() } } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ListEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.data != dataSource.data) this.data = dataSource.data.toMutableList() if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } private val dataUpdater: (value: List<String>) -> Unit = { value -> changedProperty.add("data") } override var data: MutableList<String> get() { val collection_data = getEntityData().data if (collection_data !is MutableWorkspaceList) return collection_data if (diff == null || modifiable.get()) { collection_data.setModificationUpdateAction(dataUpdater) } else { collection_data.cleanModificationUpdateAction() } return collection_data } set(value) { checkModificationAllowed() getEntityData(true).data = value dataUpdater.invoke(value) } override fun getEntityClass(): Class<ListEntity> = ListEntity::class.java } } class ListEntityData : WorkspaceEntityData<ListEntity>() { lateinit var data: MutableList<String> fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ListEntity> { val modifiable = ListEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): ListEntity { return getCached(snapshot) { val entity = ListEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun clone(): ListEntityData { val clonedEntity = super.clone() clonedEntity as ListEntityData clonedEntity.data = clonedEntity.data.toMutableWorkspaceList() return clonedEntity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ListEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ListEntity(data, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ListEntityData if (this.entitySource != other.entitySource) return false if (this.data != other.data) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ListEntityData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + data.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { this.data?.let { collector.add(it::class.java) } collector.sameForAllEntities = false } }
apache-2.0
4dd47ab2f6bf15c3fae222af44ed5ad7
31.31982
130
0.71777
5.19551
false
false
false
false
GunoH/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/project/path/ExternalSystemWorkingDirectoryInfo.kt
8
2443
// 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.externalSystem.service.ui.project.path import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemLocalSettings import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.externalSystem.util.ExternalSystemBundle import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.getCanonicalPath class ExternalSystemWorkingDirectoryInfo(project: Project, externalSystemId: ProjectSystemId) : WorkingDirectoryInfo { private val readableName = externalSystemId.readableName override val editorLabel: String = ExternalSystemBundle.message("run.configuration.project.path.label", readableName) override val settingsName: String = ExternalSystemBundle.message("run.configuration.project.path.name", readableName) override val fileChooserTitle: String = ExternalSystemBundle.message("settings.label.select.project", readableName) override val fileChooserDescriptor: FileChooserDescriptor = ExternalSystemApiUtil.getExternalProjectConfigDescriptor(externalSystemId) override val emptyFieldError: String = ExternalSystemBundle.message("run.configuration.project.path.empty.error", readableName) override val externalProjects: List<ExternalProject> by lazy { ArrayList<ExternalProject>().apply { val localSettings = ExternalSystemApiUtil.getLocalSettings<AbstractExternalSystemLocalSettings<*>>(project, externalSystemId) val uiAware = ExternalSystemUiUtil.getUiAware(externalSystemId) for ((parent, children) in localSettings.availableProjects) { val parentPath = getCanonicalPath(parent.path) val parentName = uiAware.getProjectRepresentationName(project, parentPath, null) add(ExternalProject(parentName, parentPath)) for (child in children) { val childPath = getCanonicalPath(child.path) if (parentPath == childPath) continue val childName = uiAware.getProjectRepresentationName(project, childPath, parentPath) add(ExternalProject(childName, childPath)) } } } } }
apache-2.0
85c0150d056fc50fc483e7d8e1c3eddd
55.837209
158
0.803111
5.31087
false
true
false
false
zielu/GitToolBox
src/main/kotlin/zielu/gittoolbox/GitToolBoxApp.kt
1
4365
package zielu.gittoolbox import com.google.common.util.concurrent.ThreadFactoryBuilder import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.util.messages.MessageBus import zielu.gittoolbox.metrics.AppMetrics import zielu.gittoolbox.util.AppUtil import zielu.gittoolbox.util.ConcurrentUtil import zielu.gittoolbox.util.ReschedulingExecutor import zielu.intellij.concurrent.ZThreadFactory import java.util.Collections import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.concurrent.Executors import java.util.concurrent.Future import java.util.concurrent.ScheduledFuture import java.util.concurrent.SynchronousQueue import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Supplier internal class GitToolBoxApp : Disposable { private val taskThreadFactory = ZThreadFactory("GitToolBox-task-group") private val taskExecutor = ThreadPoolExecutor( 1, 1024, 60L, TimeUnit.SECONDS, SynchronousQueue(), ThreadFactoryBuilder() .setNameFormat("GitToolBox-task-%d") .setDaemon(true) .setThreadFactory(taskThreadFactory) .build() ) private val asyncThreadFactory = ZThreadFactory("GitToolBox-async-group") private val asyncExecutor = Executors.newFixedThreadPool( Runtime.getRuntime().availableProcessors(), ThreadFactoryBuilder() .setNameFormat("GitToolBox-async-%d") .setDaemon(true) .setThreadFactory(asyncThreadFactory) .build() ) private val scheduledThreadFactory = ZThreadFactory("GitToolBox-schedule-group") private val scheduledExecutor = Executors.newSingleThreadScheduledExecutor( ThreadFactoryBuilder() .setNameFormat("GitToolBox-schedule-%d") .setDaemon(true) .setThreadFactory(scheduledThreadFactory) .build() ) private val active = AtomicBoolean(true) init { val metrics = AppMetrics.getInstance() taskThreadFactory.exposeMetrics(metrics) asyncThreadFactory.exposeMetrics(metrics) scheduledThreadFactory.exposeMetrics(metrics) runInBackground { AppMetrics.startReporting() } } override fun dispose() { if (active.compareAndSet(true, false)) { ConcurrentUtil.shutdown(scheduledExecutor) ConcurrentUtil.shutdown(taskExecutor) ConcurrentUtil.shutdown(asyncExecutor) } } fun runInBackground(task: Runnable) { if (active.get()) { taskExecutor.submit(task) } } fun <T> supplyAsyncList(supplier: Supplier<List<T>>): CompletableFuture<List<T>> { return if (active.get()) { CompletableFuture.supplyAsync(supplier, asyncExecutor) } else { CompletableFuture.completedFuture(Collections.emptyList()) } } fun <T> supplyAsync(supplier: Supplier<T>, fallbackSupplier: Supplier<T>): CompletableFuture<T> { return if (active.get()) { CompletableFuture.supplyAsync(supplier, asyncExecutor) } else { CompletableFuture.completedFuture(fallbackSupplier.get()) } } fun asyncExecutor(): Executor = asyncExecutor fun schedule(task: Runnable, delay: Long, unit: TimeUnit): ScheduledFuture<*>? { return if (active.get()) { scheduledExecutor.schedule({ runInBackground(task) }, delay, unit) } else { null } } fun publishSync(project: Project, publisher: (messageBus: MessageBus) -> Unit) { if (active.get()) { publisher.invoke(project.messageBus) } } fun publishSync(publisher: (messageBus: MessageBus) -> Unit) { if (active.get()) { publisher.invoke(ApplicationManager.getApplication().messageBus) } } companion object { @JvmStatic fun getInstance(): Optional<GitToolBoxApp> { return AppUtil.getServiceInstanceSafe(GitToolBoxApp::class.java) } @JvmStatic fun createReschedulingExecutor(): ReschedulingExecutor { return ReschedulingExecutor( { task, duration -> getInstance().flatMap { val result: Optional<Future<*>> = Optional.ofNullable( it.schedule(task, duration.toMillis(), TimeUnit.MILLISECONDS) ) result } }, true ) } } }
apache-2.0
1075dfb4ba0a3b04d2ac23b86218b42c
30.178571
99
0.724399
4.619048
false
false
false
false
MediaArea/MediaInfo
Source/GUI/Android/app/src/main/java/net/mediaarea/mediainfo/ReportListActivity.kt
1
26414
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ package net.mediaarea.mediainfo import kotlin.jvm.* import java.io.File import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.RecyclerView import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.Observer import androidx.core.app.ActivityCompat import androidx.appcompat.app.AppCompatDelegate import android.os.Build import android.os.Bundle import android.os.AsyncTask import android.os.Environment import android.os.ParcelFileDescriptor import android.net.Uri import android.app.Activity import android.content.Intent import android.database.Cursor import android.provider.OpenableColumns import android.widget.FrameLayout import android.widget.TextView import android.content.Context import android.widget.Toast import android.content.SharedPreferences import android.content.pm.PackageManager import android.content.res.Resources import android.view.* import androidx.preference.PreferenceManager.getDefaultSharedPreferences import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import io.reactivex.android.schedulers.AndroidSchedulers import kotlinx.android.synthetic.main.activity_report_list.* import kotlinx.android.synthetic.main.report_list_content.view.* import kotlinx.android.synthetic.main.report_list.* import kotlinx.android.synthetic.main.hello_layout.* import com.github.angads25.filepicker.model.DialogConfigs import com.github.angads25.filepicker.model.DialogProperties import com.github.angads25.filepicker.view.FilePickerDialog import com.yariksoffice.lingver.Lingver import java.io.BufferedReader import java.util.* /** * An activity representing a list of Pings. This activity * has different presentations for handset and tablet-size devices. On * handsets, the activity presents a list of items, which when touched, * lead to a [ReportDetailActivity] representing * item details. On tablets, the activity presents the list of items and * item details side-by-side using two vertical panes. */ class ReportListActivity : AppCompatActivity(), ReportActivityListener { private lateinit var subscriptionManager: SubscriptionManager private lateinit var reportModel: ReportViewModel private var disposable: CompositeDisposable = CompositeDisposable() private var twoPane: Boolean = false private var reports: List<Report> = listOf() private var pendingFileUris: MutableList<Uri> = mutableListOf() inner class AddFile: AsyncTask<Uri, Int, Boolean>() { override fun onPreExecute() { super.onPreExecute() add_button.hide() val rootLayout: FrameLayout = findViewById(R.id.frame_layout) var found = false for (i: Int in rootLayout.childCount downTo 1) { if (rootLayout.getChildAt(i - 1).id == R.id.spinner_layout) found = true } if (!found) View.inflate(this@ReportListActivity, R.layout.spinner_layout, rootLayout) } override fun onPostExecute(result: Boolean?) { super.onPostExecute(result) add_button.show() val rootLayout: FrameLayout = findViewById(R.id.frame_layout) for (i: Int in rootLayout.childCount downTo 1) { if (rootLayout.getChildAt(i - 1).id == R.id.spinner_layout) rootLayout.removeViewAt(i - 1) } } override fun doInBackground(vararg params: Uri?): Boolean { for (uri: Uri? in params) { if (uri == null) { continue } var fd: ParcelFileDescriptor? = null var displayName = "" when (uri.scheme) { "content" -> { if (Build.VERSION.SDK_INT >= 19) { try { val cursor: Cursor? = contentResolver.query(uri, null, null, null, null, null) // moveToFirst() returns false if the cursor has 0 rows if (cursor != null && cursor.moveToFirst()) { // DISPLAY_NAME is provider-specific, and might not be the file name displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)) cursor.close() } } catch (e: Exception) { } try { fd = contentResolver.openFileDescriptor(uri, "r") } catch (e: Exception) {} } } "file" -> { val file = File(uri.path.orEmpty()) try { fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) } catch (e: Exception) {} displayName = uri.lastPathSegment.orEmpty() } } if (fd == null) { continue } val report: ByteArray = Core.createReport(fd.detachFd(), displayName) disposable.add(reportModel.insertReport(Report(0, displayName, report, Core.version)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnComplete { // Don't go to report view when opening multiples files if (params.size == 1) { disposable.add(reportModel.getLastId() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSuccess { showReport(it) }.subscribe()) } }.subscribe()) } return true } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { when (requestCode) { READ_EXTERNAL_STORAGE_PERMISSION_REQUEST -> { if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { AddFile().execute(*(pendingFileUris.toTypedArray())) pendingFileUris.clear() } else { // Abort all pending request pendingFileUris.clear() } } } } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) handleIntent(intent) } private fun handleUri(uri: Uri) { if (uri.scheme == "file") { if (Build.VERSION.SDK_INT >= 23) { if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { pendingFileUris.add(uri) ActivityCompat.requestPermissions(this@ReportListActivity, arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE), READ_EXTERNAL_STORAGE_PERMISSION_REQUEST) return } } } AddFile().execute(uri) } private fun handleIntent(intent: Intent) { if (intent.action != null) { val action: String? = intent.action if (action == Intent.ACTION_VIEW) { val uri: Uri? = intent.data if (uri != null) { handleUri(uri) } } else if (action == Intent.ACTION_SEND) { val uri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM) if (uri != null) { handleUri(uri) } else if (action == Intent.ACTION_SEND_MULTIPLE) { val uriList = intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM) if (uriList != null) { for (i in uriList) { handleUri(i) } } } } } } private fun updatePreferences() { val sharedPreferences = getDefaultSharedPreferences(this) val key = getString(R.string.preferences_uimode_key) when (sharedPreferences?.contains(key)) { false -> { val oldSharedPreferences = getSharedPreferences(getString(R.string.preferences_key), Context.MODE_PRIVATE) if (oldSharedPreferences?.contains(key) == true) { oldSharedPreferences.getString(key, "").let { when (it) { "ON" -> { oldSharedPreferences.edit()?.remove(key) sharedPreferences.edit()?.putString(key, "on")?.apply() } "OFF" -> { oldSharedPreferences.edit()?.remove(key) sharedPreferences.edit()?.putString(key, "off")?.apply() } else -> { } } } } } true -> { try { sharedPreferences.getBoolean(key, false).let { when (it) { false -> { sharedPreferences.edit()?.remove(key) sharedPreferences.edit()?.putString(key, "off")?.apply() } true -> { sharedPreferences.edit()?.remove(key) sharedPreferences.edit()?.putString(key, "on")?.apply() } } } } catch(_: ClassCastException) {} } } } private fun applyUiMode() { val sharedPreferences = getDefaultSharedPreferences(this) val key = getString(R.string.preferences_uimode_key) sharedPreferences?.getString(getString(R.string.preferences_uimode_key), "system").let { when (it) { "off" -> { if (AppCompatDelegate.getDefaultNightMode()!=AppCompatDelegate.MODE_NIGHT_NO) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) recreate() } } "on" -> { if (AppCompatDelegate.getDefaultNightMode()!=AppCompatDelegate.MODE_NIGHT_YES) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) recreate() } } "system" -> { if (AppCompatDelegate.getDefaultNightMode()!=AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) recreate() } } } } } private fun setLocale() { try { val stream = applicationContext.resources.openRawResource(R.raw.lang) val content = stream.bufferedReader().use(BufferedReader::readText) Core.setLocale(content) } catch (error: Exception) { } } private fun setPrefLocale() { val sharedPreferences: SharedPreferences? = getDefaultSharedPreferences(this) sharedPreferences?.getBoolean(getString(R.string.preferences_report_translate_key), false).let { when (it) { false -> { Core.setLocale("") } true -> { setLocale() } } } sharedPreferences?.getString(getString(R.string.preferences_locale_key), "system").let { val locale: Locale = if (it == null || it == "system") { if (Build.VERSION.SDK_INT >= 24) { Resources.getSystem().configuration.locales.get(0) } else { @Suppress("DEPRECATION") Resources.getSystem().configuration.locale } } else { val language = it.split("-r") if (language.size > 1) { Locale(language[0], language[1]) } else { Locale(language[0]) } } Locale.setDefault(locale) if (Lingver.getInstance().getLocale() != locale) { Lingver.getInstance().setLocale(this, locale) recreate() } } } fun showReport(id: Int) { intent.putExtra(Core.ARG_REPORT_ID, id) if (twoPane) { val fragment: ReportDetailFragment = ReportDetailFragment().apply { arguments = Bundle().apply { putInt(Core.ARG_REPORT_ID, id) } } supportFragmentManager .beginTransaction() .replace(R.id.report_detail_container, fragment) .commit() disposable.add(reportModel.getReport(id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSuccess { title = it.filename }.subscribe()) } else { val intent = Intent(this@ReportListActivity, ReportDetailActivity::class.java) intent.putExtra(Core.ARG_REPORT_ID, id) startActivityForResult(intent, SHOW_REPORT_REQUEST) } } fun deleteReport(id: Int) { disposable.add(reportModel .deleteReport(id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe()) if (intent.getIntExtra(Core.ARG_REPORT_ID, -1)==id) { intent.putExtra(Core.ARG_REPORT_ID, -1) } if (twoPane) { val fragment = supportFragmentManager.findFragmentById(R.id.report_detail_container) if (fragment != null && (fragment as ReportDetailFragment).id == id) { supportFragmentManager .beginTransaction() .detach(fragment) .commit() title = getString(R.string.app_name) } } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_main, menu) menu?.findItem(R.id.action_subscribe)?.isEnabled=false subscriptionManager.ready.observe(this, Observer { if (subscriptionManager.subscribed.value == false) { menu?.findItem(R.id.action_subscribe)?.isEnabled = it } }) subscriptionManager.subscribed.observe(this, Observer { if (it) { if (subscriptionManager.isLifetime.value == true) { menu?.findItem(R.id.action_subscribe).let { item -> item?.title = getString(R.string.subscribe_text) item?.isVisible = false } } else { menu?.findItem(R.id.action_subscribe).let { item -> item?.isEnabled = true item?.title = getString(R.string.subscribed_text) item?.setOnMenuItemClickListener { _ -> val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse(getString(R.string.subscription_manage_url).replace('|', '&')) startActivity(intent) true } } } } else { menu?.findItem(R.id.action_subscribe).let { item -> item?.title = getString(R.string.subscribe_text) item?.setOnMenuItemClickListener { _ -> val intent = Intent(this, SubscribeActivity::class.java) startActivityForResult(intent, SUBSCRIBE_REQUEST) true } } } }) menu?.findItem(R.id.action_about).let { it?.setOnMenuItemClickListener { val intent = Intent(this, AboutActivity::class.java) startActivity(intent) true } } menu?.findItem(R.id.action_settings).let { it?.setOnMenuItemClickListener { val intent = Intent(this, SettingsActivity::class.java) startActivity(intent) true } } return super.onCreateOptionsMenu(menu) } override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) { super.onActivityResult(requestCode, resultCode, resultData) if (resultCode == Activity.RESULT_OK) { when (requestCode) { OPEN_FILE_REQUEST -> { if (Build.VERSION.SDK_INT >= 19) { if (resultData == null) return val clipData = resultData.clipData if (clipData != null) { val uris: Array<Uri> = Array(clipData.itemCount) { clipData.getItemAt(it).uri } AddFile().execute(*(uris)) } else if (resultData.data != null) { AddFile().execute(resultData.data) } } } SUBSCRIBE_REQUEST -> { Toast.makeText(applicationContext, R.string.thanks_text, Toast.LENGTH_SHORT).show() } SHOW_REPORT_REQUEST -> { if (resultData!=null) { val id = resultData.getIntExtra(Core.ARG_REPORT_ID, -1) if (id!=-1 && twoPane) { showReport(id) } } } } } } override fun getReportViewModel(): ReportViewModel { return reportModel } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_report_list) setSupportActionBar(tool_bar) tool_bar.title = title updatePreferences() subscriptionManager = SubscriptionManager.getInstance(application) lifecycle.addObserver(subscriptionManager) setLocale() subscriptionManager.subscribed.observe(this, Observer { if (it==true) { applyUiMode() setPrefLocale() } }) val viewModelFactory = Injection.provideViewModelFactory(this) reportModel = ViewModelProvider(this, viewModelFactory).get(ReportViewModel::class.java) add_button.setOnClickListener { if (Build.VERSION.SDK_INT >= 19) { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT) intent.addCategory(Intent.CATEGORY_OPENABLE) intent.type = "*/*" intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) startActivityForResult(intent, OPEN_FILE_REQUEST) } else { if (Environment.getExternalStorageState() in setOf(Environment.MEDIA_MOUNTED, Environment.MEDIA_MOUNTED_READ_ONLY)) { val properties = DialogProperties() properties.selection_mode = DialogConfigs.MULTI_MODE properties.selection_type = DialogConfigs.FILE_SELECT properties.root = File(DialogConfigs.DEFAULT_DIR) properties.error_dir = File(DialogConfigs.DEFAULT_DIR) properties.offset = File(DialogConfigs.DEFAULT_DIR) properties.extensions = null val dialog = FilePickerDialog(this, properties) dialog.setTitle(R.string.open_title) dialog.setDialogSelectionListener { files: Array<String> -> var uris: Array<Uri> = arrayOf() files.forEach { uri: String -> uris += Uri.parse("file://$uri") } AddFile().execute(*(uris)) } dialog.show() } else { val toast = Toast.makeText(applicationContext, R.string.media_error_text, Toast.LENGTH_LONG) toast.show() } } } clear_btn.setOnClickListener { disposable.add(reportModel.deleteAllReports() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { intent.putExtra(Core.ARG_REPORT_ID, -1) if (twoPane) { val fragment = supportFragmentManager.findFragmentById(R.id.report_detail_container) if (fragment != null) { supportFragmentManager .beginTransaction() .detach(fragment) .commit() title = getString(R.string.app_name) } } }) } // The detail container view will be present only in the // large-screen layouts (res/values-w900dp). // If this view is present, then the // activity should be in two-pane mode. if (report_detail_container != null) twoPane = true setupRecyclerView(report_list) onNewIntent(intent) } override fun onStart() { super.onStart() disposable.add(reportModel.getAllReports() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { reports = it setupRecyclerView(report_list) val rootLayout: FrameLayout = findViewById(R.id.frame_layout) if (reports.isEmpty()) { var found = false for (i: Int in rootLayout.childCount downTo 1) { if (rootLayout.getChildAt(i - 1).id == R.id.hello_layout) found = true } if (!found) View.inflate(this, R.layout.hello_layout, rootLayout) clear_btn.visibility = View.INVISIBLE } else { for (i: Int in rootLayout.childCount downTo 1) { if (rootLayout.getChildAt(i - 1).id == R.id.hello_layout) rootLayout.removeViewAt(i - 1) } rootLayout.removeView(hello_layout) clear_btn.visibility = View.VISIBLE } }) if (twoPane && intent.getIntExtra(Core.ARG_REPORT_ID, -1)!=-1) { showReport(intent.getIntExtra(Core.ARG_REPORT_ID, -1)) } } override fun onStop() { super.onStop() // clear all the subscription disposable.clear() } private fun setupRecyclerView(recyclerView: RecyclerView) { recyclerView.adapter = ItemRecyclerViewAdapter() recyclerView.isNestedScrollingEnabled = false } inner class ItemRecyclerViewAdapter : RecyclerView.Adapter<ItemRecyclerViewAdapter.ViewHolder>() { private val onClickListener: View.OnClickListener init { onClickListener = View.OnClickListener { val report: Report = it.tag as Report showReport(report.id) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.report_list_content, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val report: Report = reports[position] holder.name.text = report.filename holder.id = report.id with(holder.itemView) { tag = report setOnClickListener(onClickListener) } } override fun getItemCount(): Int = reports.size inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val name: TextView = view.name_text var id: Int = -1 init { view.delete_button.setOnClickListener { if (id != -1) deleteReport(id) } } } } companion object { const val SHOW_REPORT_REQUEST = 20 const val SUBSCRIBE_REQUEST = 30 const val OPEN_FILE_REQUEST = 40 const val READ_EXTERNAL_STORAGE_PERMISSION_REQUEST = 50 } }
bsd-2-clause
46366ce2c26a7d03487f4b2d5aea5f18
36.951149
133
0.510184
5.565529
false
false
false
false
twbarber/cash-register
cash-register-public/src/test/kotlin/com/twbarber/register/public/CashRegisterCliRunnerTest.kt
1
2245
package com.twbarber.register.public import com.twbarber.register.public.cli.CashRegisterCliRunner import com.twbarber.register.public.data.Balance import junit.framework.TestCase.assertFalse import junit.framework.TestCase.assertTrue import org.junit.Assert.assertEquals import org.junit.Test class CashRegisterCliRunnerTest { val cli = CashRegisterCliRunner() @Test fun matchPutRegex() { val input = "put 1 1 1 1 1" assertTrue(input.matches(Regex(cli.PUT_REGEX))) } @Test fun badPutRegex_NotEnoughBills() { val input = "put 1 1 1 1" assertFalse(input.matches(Regex(cli.PUT_REGEX))) } @Test fun matchTakeRegex() { val input = "take 1 1 1 1 1" assertTrue(input.matches(Regex(cli.TAKE_REGEX))) } @Test fun badTakeRegex_NotEnoughBills() { val input = "take 1 1 1 1" assertFalse(input.matches(Regex(cli.TAKE_REGEX))) } @Test fun matchShowRegex() { val input = "show" assertTrue(input.matches(Regex(cli.SHOW_REGEX))) } @Test fun matchChangeRegex() { val input = "change 13" assertTrue(input.matches(Regex(cli.CHANGE_REGEX))) } @Test fun matchQuitRegex() { val input = "quit" assertTrue(input.matches(Regex(cli.QUIT_REGEX))) } @Test fun emptyInput() { val input = "" assertTrue(!input.matches(Regex(cli.TAKE_REGEX))) assertTrue(!input.matches(Regex(cli.PUT_REGEX))) assertTrue(!input.matches(Regex(cli.CHANGE_REGEX))) assertTrue(!input.matches(Regex(cli.SHOW_REGEX))) } @Test fun parsePutTransaction() { val input = "put 1 1 1 1 1" assertEquals(Balance(1, 1, 1, 1, 1), cli.parseTransaction(input)) } @Test fun parseTakeTransaction() { val input = "take 1 1 1 1 1" assertEquals(Balance(1, 1, 1, 1, 1), cli.parseTransaction(input)) } @Test fun parseExcessTransactionString() { val input = "take 1 1 1 1 1 EXTRA" assertEquals(Balance(1, 1, 1, 1, 1), cli.parseTransaction(input)) } @Test fun parseChange() { val input = "change 3" assertEquals(3, cli.parseChange(input)) } }
mit
81f1ffb6666fb350ffef9831275b19d3
24.235955
73
0.622272
3.698517
false
true
false
false
migafgarcia/programming-challenges
advent_of_code/2018/solutions/day_5_b.kt
1
884
import java.io.File fun main(args: Array<String>) { val input = File(args[0]).readText().trim() val removals = HashMap<Char,Int>() for(c in 'a'..'z') { var current = input var i = 0 while (i < current.length) { if(current[i].equals(c, true)) { current = current.removeRange(i..i) i = maxOf(i - 1, 0) } else if (i < current.length - 1 && ((current[i].isLowerCase() && current[i + 1].isUpperCase()) || (current[i].isUpperCase() && current[i + 1].isLowerCase())) && current[i].equals(current[i + 1], true)) { current = current.removeRange(i..i + 1) i = maxOf(i - 1, 0) } else i++ } removals.put(c, current.length) } println(removals.minBy { entry -> entry.value }) }
mit
63aa222c0145a5a1008a3dded7e85ec3
24.257143
169
0.479638
3.761702
false
false
false
false
koma-im/koma
src/main/kotlin/link/continuum/desktop/events/invites.kt
1
2801
package link.continuum.desktop.events import koma.Server import koma.matrix.UserId import koma.matrix.event.room_message.state.RoomAvatarContent import koma.matrix.event.room_message.state.RoomCanonAliasContent import koma.matrix.event.room_message.state.RoomJoinRulesContent import koma.matrix.event.room_message.state.RoomNameContent import koma.matrix.event.room_message.state.member.RoomMemberContent import koma.matrix.room.InvitedRoom import koma.matrix.room.naming.RoomAlias import koma.matrix.room.naming.RoomId import koma.matrix.room.participation.Membership import link.continuum.desktop.gui.list.InvitationsView import mu.KotlinLogging import okhttp3.HttpUrl private val logger = KotlinLogging.logger {} /** * need to be on the main thread */ internal fun handleInvitedRoom( roomId: RoomId, data: InvitedRoom, view: InvitationsView, server: Server ) { logger.debug { "Invited to $roomId, data $data" } view.add(InviteData(data, roomId), server) } /** * for list view */ class InviteData(src: InvitedRoom, val id: RoomId) { var roomAvatar: String? = null val roomDisplayName: String var inviterAvatar: String? = null var inviterName: String? = null var inviterId: UserId? = null private var roomCanonAlias: RoomAlias? = null private var roomName: String? = null init { val userNames = mutableMapOf<UserId, String>() val userAvatars = mutableMapOf<UserId, String>() for (e in src.invite_state.events) { val c = e.content when (c) { is RoomMemberContent -> { when (c.membership) { Membership.join -> { c.avatar_url?.let { userAvatars.put(e.sender, it) } c.displayname?.let { userNames.put(e.sender, it) } } Membership.invite -> { inviterId = e.sender } else -> {} } } is RoomCanonAliasContent -> roomCanonAlias = c.alias is RoomNameContent -> roomName = c.name is RoomAvatarContent -> roomAvatar = c.url is RoomJoinRulesContent -> {} } } roomDisplayName = roomName ?: roomCanonAlias.toString() ?: id.id inviterId?.let { inviterAvatar = userAvatars.get(it) inviterName = userNames.get(it) } } override fun toString(): String { return "InviteData(roomAvatar=$roomAvatar, roomDisplayName='$roomDisplayName', inviterAvatar=$inviterAvatar, inviterName=$inviterName, inviterId=$inviterId, roomCanonAlias=$roomCanonAlias, roomName=$roomName)" } }
gpl-3.0
99fdc721374b6b046780a5dfd5eef018
33.592593
217
0.62442
4.369735
false
false
false
false
kaminomobile/AndroidVersion
plugin/src/main/kotlin/si/kamino/gradle/task/ManifestVersionTransformationTask.kt
1
1773
package si.kamino.gradle.task import org.gradle.api.DefaultTask import org.gradle.api.file.RegularFileProperty import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.TaskAction import org.w3c.dom.Element import java.io.FileWriter import javax.xml.parsers.DocumentBuilder import javax.xml.parsers.DocumentBuilderFactory import javax.xml.transform.TransformerFactory import javax.xml.transform.dom.DOMSource import javax.xml.transform.stream.StreamResult abstract class ManifestVersionTransformationTask : DefaultTask() { @get:InputFile abstract val versionFile: RegularFileProperty @get:InputFile abstract val mergedManifestFile: RegularFileProperty @get:OutputFile abstract val updatedManifestFile: RegularFileProperty @TaskAction fun taskAction() { val lines = versionFile.get().asFile.readLines() val versionName = lines.first() val versionCode = lines.last() val factory: DocumentBuilderFactory = DocumentBuilderFactory.newInstance() val builder: DocumentBuilder = factory.newDocumentBuilder() val parse = builder.parse(mergedManifestFile.get().asFile) parse.getElementsByTagName("manifest") .let { assert(it.length == 1) val node = it.item(0) as Element node.setAttribute("android:versionCode", versionCode) node.setAttribute("android:versionName", versionName) } val writer = FileWriter(updatedManifestFile.get().asFile) val result = StreamResult(writer) val tf = TransformerFactory.newInstance() val transformer = tf.newTransformer() transformer.transform(DOMSource(parse), result) } }
mit
959acc70cb1e6689bc6d9f036b08d3a6
31.851852
82
0.719684
4.952514
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/problem/graphql/service/GraphQLBlackBoxFitness.kt
1
2697
package org.evomaster.core.problem.graphql.service import org.evomaster.client.java.controller.api.dto.AdditionalInfoDto import org.evomaster.core.problem.graphql.GraphQLAction import org.evomaster.core.problem.graphql.GraphQLIndividual import org.evomaster.core.problem.graphql.GraphQlCallResult import org.evomaster.core.problem.httpws.service.HttpWsCallResult import org.evomaster.core.search.ActionResult import org.evomaster.core.search.EvaluatedIndividual import org.evomaster.core.search.FitnessValue import org.slf4j.Logger import org.slf4j.LoggerFactory class GraphQLBlackBoxFitness : GraphQLFitness() { companion object { private val log: Logger = LoggerFactory.getLogger(GraphQLBlackBoxFitness::class.java) } override fun doCalculateCoverage(individual: GraphQLIndividual, targets: Set<Int>): EvaluatedIndividual<GraphQLIndividual>? { if(config.bbExperiments){ /* If we have a controller, we MUST reset the SUT at each test execution. This is to avoid memory leaks in the dat structures used by EM. Eg, this was a huge problem for features-service with AdditionalInfo having a memory leak */ rc.resetSUT() } val fv = FitnessValue(individual.size().toDouble()) val actionResults: MutableList<ActionResult> = mutableListOf() val actions = individual.seeMainExecutableActions() as List<GraphQLAction> //run the test, one action at a time for (i in actions.indices) { val a = actions[i] //TODO handle WM here val ok = handleGraphQLCall(a, actionResults, mapOf(), mapOf()) actionResults[i].stopping = !ok if (!ok) { break } } handleResponseTargets(fv, actions, actionResults, listOf()) return EvaluatedIndividual(fv, individual.copy() as GraphQLIndividual, actionResults, trackOperator = individual.trackOperator, index = time.evaluatedIndividuals, config = config) } override fun getlocation5xx(status: Int, additionalInfoList: List<AdditionalInfoDto>, indexOfAction: Int, result: HttpWsCallResult, name: String): String? { /* In Black-Box testing, there is no info from the source/bytecode */ return null } override fun getGraphQLErrorWithLineInfo( additionalInfoList: List<AdditionalInfoDto>, indexOfAction: Int, result: GraphQlCallResult, name: String ): String? { /* In Black-Box testing, there is no info from the source/bytecode */ return null } }
lgpl-3.0
563726158d4c66078d8db1c91c2b0417
34.038961
187
0.675936
4.948624
false
true
false
false
savoirfairelinux/ring-client-android
ring-android/libjamiclient/src/main/kotlin/net/jami/model/Conversation.kt
1
22812
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Author: Adrien Béraud <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package net.jami.model import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.subjects.BehaviorSubject import io.reactivex.rxjava3.subjects.PublishSubject import io.reactivex.rxjava3.subjects.SingleSubject import io.reactivex.rxjava3.subjects.Subject import kotlin.jvm.Synchronized import net.jami.utils.Log import java.lang.IllegalStateException import java.util.* class Conversation : ConversationHistory { val accountId: String val uri: Uri val contacts: MutableList<Contact> private val rawHistory: NavigableMap<Long, Interaction> = TreeMap() private val currentCalls = ArrayList<Conference>() val aggregateHistory = ArrayList<Interaction>(32) private var lastDisplayed: Interaction? = null private val updatedElementSubject: Subject<Pair<Interaction, ElementStatus>> = PublishSubject.create() private val lastDisplayedSubject: Subject<Interaction> = BehaviorSubject.create() private val clearedSubject: Subject<List<Interaction>> = PublishSubject.create() private val callsSubject: Subject<List<Conference>> = BehaviorSubject.createDefault(emptyList()) private val composingStatusSubject: Subject<Account.ComposingStatus> = BehaviorSubject.createDefault(Account.ComposingStatus.Idle) private val color: Subject<Int> = BehaviorSubject.create() private val symbol: Subject<CharSequence> = BehaviorSubject.create() private val mContactSubject: Subject<List<Contact>> = BehaviorSubject.create() var loaded: Single<Conversation>? = null var lastElementLoaded: Completable? = null private val mRoots: MutableSet<String> = HashSet(2) private val mMessages: MutableMap<String, Interaction> = HashMap(16) var lastRead: String? = null private set var lastNotified: String? = null private set private val mMode: Subject<Mode> // runtime flag set to true if the user is currently viewing this conversation private var mVisible = false private val mVisibleSubject: Subject<Boolean> = BehaviorSubject.createDefault(mVisible) // indicate the list needs sorting private var mDirty = false private var mLoadingSubject: SingleSubject<Conversation>? = null val mode: Observable<Mode> get() = mMode val isSwarm: Boolean get() = Uri.SWARM_SCHEME == uri.scheme val contactUpdates: Observable<List<Contact>> get() = mContactSubject var loading: SingleSubject<Conversation>? get() = mLoadingSubject set(l) { mLoadingSubject?.let { loading -> if (!loading.hasValue() && !loading.hasThrowable()) loading.onError(IllegalStateException()) } mLoadingSubject = l } enum class ElementStatus { UPDATE, REMOVE, ADD } val updatedElements: Observable<Pair<Interaction, ElementStatus>> get() = updatedElementSubject val cleared: Observable<List<Interaction>> get() = clearedSubject val calls: Observable<List<Conference>> get() = callsSubject val composingStatus: Observable<Account.ComposingStatus> get() = composingStatusSubject val sortedHistory: Single<List<Interaction>> = Single.fromCallable { sortHistory() aggregateHistory } val lastEventSubject: Subject<Interaction> = BehaviorSubject.create() val currentStateSubject: Observable<Pair<Interaction, Boolean>> = Observable.combineLatest(lastEventSubject, callsSubject.map { calls -> for (call in calls) if (call.isOnGoing) return@map true false }) { event, hasCurrentCall -> Pair(event, hasCurrentCall) } val swarmRoot: Collection<String> get() = mRoots constructor(accountId: String, contact: Contact) { this.accountId = accountId contacts = mutableListOf(contact) uri = contact.uri participant = contact.uri.uri mContactSubject.onNext(contacts) mMode = BehaviorSubject.createDefault(Mode.Legacy) } constructor(accountId: String, uri: Uri, mode: Mode) { this.accountId = accountId this.uri = uri contacts = ArrayList(3) mMode = BehaviorSubject.createDefault(mode) } fun getConference(confId: String?): Conference? { val id = confId ?: return null for (c in currentCalls) if (c.id == id || c.getCallById(id) != null) return c return null } fun composingStatusChanged(contact: Contact?, composing: Account.ComposingStatus) { composingStatusSubject.onNext(composing) } fun matches(query: String): Boolean { for (contact in contacts) { if (contact.matches(query)) return true } return false } /*val displayName: String? get() = contacts[0].displayName*/ fun addContact(contact: Contact) { contacts.add(contact) mContactSubject.onNext(contacts) } fun removeContact(contact: Contact) { contacts.remove(contact) mContactSubject.onNext(contacts) } @Synchronized fun readMessages(): List<Interaction> { val interactions = ArrayList<Interaction>() if (isSwarm) { if (aggregateHistory.isNotEmpty()) { var n = aggregateHistory.size do { if (n == 0) break val i = aggregateHistory[--n] if (!i.isRead) { i.read() interactions.add(i) lastRead = i.messageId } } while (i.type == Interaction.InteractionType.INVALID) } } else { for (e in rawHistory.descendingMap().values) { if (e.type != Interaction.InteractionType.TEXT) continue if (e.isRead) { break } e.read() interactions.add(e) } } // Update the last event if it was just read interactions.firstOrNull { it.type != Interaction.InteractionType.INVALID }?.let { lastEventSubject.onNext(it) } return interactions } @Synchronized fun getMessage(messageId: String): Interaction? { return mMessages[messageId] } fun setLastMessageRead(lastMessageRead: String?) { lastRead = lastMessageRead } fun setLastMessageNotified(lastMessage: String?) { lastNotified = lastMessage } fun stopLoading(): Boolean { val ret = mLoadingSubject mLoadingSubject = null if (ret != null) { ret.onSuccess(this) return true } return false } fun setMode(mode: Mode) { mMode.onNext(mode) } fun getLastDisplayed(): Observable<Interaction> = lastDisplayedSubject fun addConference(conference: Conference?) { if (conference == null) { return } for (i in currentCalls.indices) { val currentConference = currentCalls[i] if (currentConference === conference) { return } if (currentConference.id == conference.id) { currentCalls[i] = conference return } } currentCalls.add(conference) callsSubject.onNext(currentCalls) } fun removeConference(c: Conference) { currentCalls.remove(c) callsSubject.onNext(currentCalls) } var isVisible: Boolean get() = mVisible set(visible) { mVisible = visible mVisibleSubject.onNext(mVisible) } fun getVisible(): Observable<Boolean> = mVisibleSubject val contact: Contact? get() { if (contacts.size == 1) return contacts[0] if (isSwarm) { check(contacts.size <= 2) { "getContact() called for group conversation of size " + contacts.size } } for (contact in contacts) { if (!contact.isUser) return contact } return null } fun addCall(call: Call) { if (!isSwarm && callHistory.contains(call)) { return } mDirty = true aggregateHistory.add(call) updatedElementSubject.onNext(Pair(call, ElementStatus.ADD)) } private fun setInteractionProperties(interaction: Interaction) { interaction.account = accountId if (interaction.contact == null) { if (contacts.size == 1) interaction.contact = contacts[0] else { if (interaction.author == null) { Log.e(TAG, "Can't set interaction properties: no author for type:" + interaction.type + " id:" + interaction.id + " status:" + interaction.mStatus) } else { interaction.contact = findContact(Uri.fromString(interaction.author!!)) } } } } fun findContact(uri: Uri): Contact? { for (contact in contacts) { if (contact.uri == uri) { return contact } } return null } fun addTextMessage(txt: TextMessage) { if (mVisible) txt.read() setInteractionProperties(txt) rawHistory[txt.timestamp] = txt mDirty = true aggregateHistory.add(txt) updatedElementSubject.onNext(Pair(txt, ElementStatus.ADD)) } fun addRequestEvent(request: TrustRequest, contact: Contact) { if (isSwarm) return val event = ContactEvent(contact, request) mDirty = true aggregateHistory.add(event) updatedElementSubject.onNext(Pair(event, ElementStatus.ADD)) } fun addContactEvent(contact: Contact) { addContactEvent(ContactEvent(contact)) } fun addContactEvent(contactEvent: ContactEvent) { mDirty = true aggregateHistory.add(contactEvent) updatedElementSubject.onNext(Pair(contactEvent, ElementStatus.ADD)) } fun addFileTransfer(dataTransfer: DataTransfer) { if (aggregateHistory.contains(dataTransfer)) { return } mDirty = true aggregateHistory.add(dataTransfer) updatedElementSubject.onNext(Pair(dataTransfer, ElementStatus.ADD)) } private fun isAfter(previous: Interaction, query: Interaction?): Boolean { var query = query return if (isSwarm) { while (query?.parentId != null) { if (query.parentId == previous.messageId) return true query = mMessages[query.parentId] } false } else { previous.timestamp < query!!.timestamp } } fun updateInteraction(element: Interaction) { Log.e(TAG, "updateInteraction: ${element.messageId} ${element.status}") val lastDisplayed = lastDisplayed if (isSwarm) { val e = mMessages[element.messageId] if (e != null) { e.status = element.status updatedElementSubject.onNext(Pair(e, ElementStatus.UPDATE)) if (e.status == Interaction.InteractionStatus.DISPLAYED) { if (lastDisplayed == null || isAfter(lastDisplayed, e)) { this.lastDisplayed = e lastDisplayedSubject.onNext(e) } } } else { Log.e(TAG, "Can't find swarm message to update: ${element.messageId}") } } else { setInteractionProperties(element) val time = element.timestamp val msgs = rawHistory.subMap(time, true, time, true) for (txt in msgs.values) { if (txt.id == element.id) { txt.status = element.status updatedElementSubject.onNext(Pair(txt, ElementStatus.UPDATE)) if (element.status == Interaction.InteractionStatus.DISPLAYED) { if (lastDisplayed == null || isAfter(lastDisplayed, element)) { this.lastDisplayed = element lastDisplayedSubject.onNext(element) } } return } } Log.e(TAG, "Can't find message to update: ${element.id}") } } fun sortHistory() { if (mDirty) { Log.w(TAG, "sortHistory()") synchronized(aggregateHistory) { aggregateHistory.sortWith { c1, c2 -> c1.timestamp.compareTo(c2.timestamp) } for (i in aggregateHistory.asReversed()) if (i.type != Interaction.InteractionType.INVALID) { lastEventSubject.onNext(aggregateHistory.last()) break } } mDirty = false } } val lastEvent: Interaction? get() { sortHistory() return aggregateHistory.lastOrNull { it.type != Interaction.InteractionType.INVALID } } val currentCall: Conference? get() = if (currentCalls.isEmpty()) null else currentCalls[0] private val callHistory: Collection<Call> get() { val result: MutableList<Call> = ArrayList() for (interaction in aggregateHistory) { if (interaction.type == Interaction.InteractionType.CALL) { result.add(interaction as Call) } } return result } val unreadTextMessages: TreeMap<Long, TextMessage> get() { val texts = TreeMap<Long, TextMessage>() if (isSwarm) { for (j in aggregateHistory.indices.reversed()) { val i = aggregateHistory[j] if (i !is TextMessage) continue if (i.isRead || i.isNotified) break texts[i.timestamp] = i } } else { for ((key, value) in rawHistory.descendingMap()) { if (value.type == Interaction.InteractionType.TEXT) { val message = value as TextMessage if (message.isRead || message.isNotified) break texts[key] = message } } } return texts } private fun findConversationElement(transferId: Int): Interaction? { for (interaction in aggregateHistory) { if (interaction.type == Interaction.InteractionType.DATA_TRANSFER) { if (transferId == interaction.id) { return interaction } } } return null } private fun removeSwarmInteraction(messageId: String): Boolean { val i = mMessages.remove(messageId) if (i != null) { aggregateHistory.remove(i) return true } return false } private fun removeInteraction(interactionId: Long): Boolean { val it = aggregateHistory.iterator() while (it.hasNext()) { val interaction = it.next() if (interactionId == interaction.id.toLong()) { it.remove() return true } } return false } /** * Clears the conversation cache. * @param delete true if you do not want to re-add contact events */ fun clearHistory(delete: Boolean) { aggregateHistory.clear() rawHistory.clear() mDirty = false if (!delete && contacts.size == 1) aggregateHistory.add(ContactEvent(contacts[0])) clearedSubject.onNext(aggregateHistory) } fun setHistory(loadedConversation: List<Interaction>) { aggregateHistory.ensureCapacity(loadedConversation.size) var last: Interaction? = null for (i in loadedConversation) { val interaction = getTypedInteraction(i) setInteractionProperties(interaction) aggregateHistory.add(interaction) rawHistory[interaction.timestamp] = interaction if (!i.isIncoming && i.status == Interaction.InteractionStatus.DISPLAYED) last = i } if (last != null) { lastDisplayed = last lastDisplayedSubject.onNext(last) } lastEvent?.let { lastEventSubject.onNext(it) } mDirty = false } fun addElement(interaction: Interaction) { setInteractionProperties(interaction) when (interaction.type) { Interaction.InteractionType.TEXT -> addTextMessage(TextMessage(interaction)) Interaction.InteractionType.CALL -> addCall(Call(interaction)) Interaction.InteractionType.CONTACT -> addContactEvent(ContactEvent(interaction)) Interaction.InteractionType.DATA_TRANSFER -> addFileTransfer(DataTransfer(interaction)) else -> {} } } fun addSwarmElement(interaction: Interaction): Boolean { if (mMessages.containsKey(interaction.messageId)) { return false } mMessages[interaction.messageId!!] = interaction mRoots.remove(interaction.messageId) if (interaction.parentId != null && !mMessages.containsKey(interaction.parentId)) { mRoots.add(interaction.parentId!!) // Log.w(TAG, "@@@ Found new root for " + getUri() + " " + parent + " -> " + mRoots); } if (lastRead != null && lastRead == interaction.messageId) interaction.read() if (lastNotified != null && lastNotified == interaction.messageId) interaction.isNotified = true var newLeaf = false var added = false if (aggregateHistory.isEmpty() || aggregateHistory.last().messageId == interaction.parentId) { // New leaf added = true newLeaf = true aggregateHistory.add(interaction) updatedElementSubject.onNext(Pair(interaction, ElementStatus.ADD)) } else { // New root or normal node for (i in aggregateHistory.indices) { if (interaction.messageId == aggregateHistory[i].parentId) { //Log.w(TAG, "@@@ New root node at " + i); aggregateHistory.add(i, interaction) updatedElementSubject.onNext(Pair(interaction, ElementStatus.ADD)) added = true break } } if (!added) { for (i in aggregateHistory.indices.reversed()) { if (aggregateHistory[i].messageId == interaction.parentId) { added = true newLeaf = true aggregateHistory.add(i + 1, interaction) updatedElementSubject.onNext(Pair(interaction, ElementStatus.ADD)) break } } } } if (newLeaf) { if (isVisible) { interaction.read() setLastMessageRead(interaction.messageId) } if (interaction.type != Interaction.InteractionType.INVALID) lastEventSubject.onNext(interaction) } if (!added) { Log.e(TAG, "Can't attach interaction ${interaction.messageId} with parent ${interaction.parentId}") } return newLeaf } fun isLoaded(): Boolean { return mMessages.isNotEmpty() && mRoots.isEmpty() } fun updateFileTransfer(transfer: DataTransfer, eventCode: Interaction.InteractionStatus) { val dataTransfer = (if (isSwarm) transfer else findConversationElement(transfer.id)) as DataTransfer? if (dataTransfer != null) { dataTransfer.status = eventCode updatedElementSubject.onNext(Pair(dataTransfer, ElementStatus.UPDATE)) } } fun removeInteraction(interaction: Interaction) { if (isSwarm) { if (removeSwarmInteraction(interaction.messageId!!)) updatedElementSubject.onNext(Pair(interaction, ElementStatus.REMOVE)) } else { if (removeInteraction(interaction.id.toLong())) updatedElementSubject.onNext(Pair(interaction, ElementStatus.REMOVE)) } } fun removeAll() { aggregateHistory.clear() currentCalls.clear() rawHistory.clear() mDirty = true } fun setColor(c: Int) { color.onNext(c) } fun setSymbol(s: CharSequence) { symbol.onNext(s) } fun getColor(): Observable<Int> { return color } fun getSymbol(): Observable<CharSequence> { return symbol } enum class Mode { OneToOne, AdminInvitesOnly, InvitesOnly, // Non-daemon modes Syncing, Public, Legacy, Request } interface ConversationActionCallback { fun removeConversation(conversationUri: Uri) fun clearConversation(conversationUri: Uri) fun copyContactNumberToClipboard(contactNumber: String) } companion object { private val TAG = Conversation::class.simpleName!! private fun getTypedInteraction(interaction: Interaction): Interaction { return when (interaction.type) { Interaction.InteractionType.TEXT -> TextMessage(interaction) Interaction.InteractionType.CALL -> Call(interaction) Interaction.InteractionType.CONTACT -> ContactEvent(interaction) Interaction.InteractionType.DATA_TRANSFER -> DataTransfer(interaction) else -> interaction } } } }
gpl-3.0
14438ccd807a861c1d647d462d56ef4c
34.588144
167
0.59068
5.162028
false
false
false
false
Petrulak/kotlin-mvp-clean-architecture
app/src/androidTest/java/com/petrulak/cleankotlin/ui/example2/Example2PresenterTest.kt
1
1234
package com.petrulak.cleankotlin.ui.example2 import com.petrulak.cleankotlin.domain.interactor.definition.GetWeatherRemotelyUseCase import io.reactivex.Single import org.junit.Before import org.junit.Test import org.mockito.Mockito import org.mockito.Mockito.mock class Example2PresenterTest { val TAG = "Example2PresenterTest" val mockUseCase = mock(GetWeatherRemotelyUseCase::class.java) val mockView = mock(Example2Contract.View::class.java) val presenter = Example2Presenter(mockUseCase) val CITY = "Bratislava" @Before fun setUp() { presenter.attachView(mockView) } @Test fun shouldDisplayError() { val errorMsg = "Errorrrr" val error = IllegalArgumentException(errorMsg) Mockito.`when`(mockUseCase.execute(CITY)).thenReturn(Single.error(error)) presenter.refresh(CITY) /* TODO make this happen Log.e(TAG, "viewState = " + presenter.view?.viewState.toString()); Log.e(TAG, "mockvie = " + mockView.viewState.toString()); verify(mockView).viewState = Matchers.isA(ViewState.Loading::class.java) verify(mockView).viewState = isA<ViewState.Error>() verifyNoMoreInteractions(mockView) */ } }
mit
39a336c165dd728f237bba2ffe403b6f
28.404762
86
0.707455
4.14094
false
true
false
false
tangying91/profit
src/main/java/org/profit/app/pojo/StockStat.kt
1
1237
package org.profit.app.pojo class StockStat { var day: String = "" // 日期 var code: String = "" // 股票代码 var type: Int = 0 // 分析周期类型 = 0 // 成交量趋势分析,监测是否有放量趋势 var volumeTotal: Long = 0 // 总成交量 var volumeRate: Double = 0.0 // 平均量量比系数=(最近一日成交量 / 前面几日的平均成交量) = 0.0 // 上涨趋势分析,监测上涨趋势 var riseDay: Int = 0 // 上涨天数(今日收盘价高于开盘价视为上涨) = 0 var amplitude: Double = 0.0 // 振幅=(周期最高价-周期最低价)/ 周期前一天收盘价 = 0.0 var gains: Double = 0.0 // 涨幅= 周期开始开盘价 - 周期结束收盘价 = 0.0 // 资金分类动态 var minInflow: Double = 0.0 // 散户资金流入 = 0.0 var midInflow: Double = 0.0 // 中户资金流入 = 0.0 var bigInflow: Double = 0.0 // 大户资金流入 = 0.0 var maxInflow: Double = 0.0 // 超大资金流入 = 0.0 // 资金流入分析,监测资金动态 var inflowAvg: Double = 0.0 // 平均资金流入= (净资金流入 / 周期天数) = 0.0 }
apache-2.0
fcf8e2682d226d74bf4dbef311a5e356
32.36
75
0.536756
2.255263
false
false
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/backend/settings/HexagonSettings.kt
1
6580
package com.battlelancer.seriesguide.backend.settings import android.content.Context import androidx.preference.PreferenceManager import com.battlelancer.seriesguide.provider.SgRoomDatabase import com.battlelancer.seriesguide.util.Utils object HexagonSettings { const val KEY_ENABLED = "com.battlelancer.seriesguide.hexagon.v2.enabled" const val KEY_SHOULD_VALIDATE_ACCOUNT = "com.battlelancer.seriesguide.hexagon.v2.shouldFixAccount" const val KEY_ACCOUNT_NAME = "com.battlelancer.seriesguide.hexagon.v2.accountname" const val KEY_SETUP_COMPLETED = "com.battlelancer.seriesguide.hexagon.v2.setup_complete" const val KEY_MERGED_SHOWS = "com.battlelancer.seriesguide.hexagon.v2.merged.shows" const val KEY_MERGED_MOVIES = "com.battlelancer.seriesguide.hexagon.v2.merged.movies2" const val KEY_MERGED_LISTS = "com.battlelancer.seriesguide.hexagon.v2.merged.lists" const val KEY_LAST_SYNC_SHOWS = "com.battlelancer.seriesguide.hexagon.v2.lastsync.shows" const val KEY_LAST_SYNC_EPISODES = "com.battlelancer.seriesguide.hexagon.v2.lastsync.episodes" const val KEY_LAST_SYNC_MOVIES = "com.battlelancer.seriesguide.hexagon.v2.lastsync.movies" const val KEY_LAST_SYNC_LISTS = "com.battlelancer.seriesguide.hexagon.v2.lastsync.lists" /** * If Cloud is enabled and Cloud specific actions should be performed or UI be shown. */ @JvmStatic fun isEnabled(context: Context): Boolean = Utils.hasAccessToX(context) && PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(KEY_ENABLED, false) fun shouldValidateAccount(context: Context, value: Boolean) { PreferenceManager.getDefaultSharedPreferences(context) .edit() .putBoolean(KEY_SHOULD_VALIDATE_ACCOUNT, value) .apply() } /** * Returns true if there is an issue with the current account and the user should be sent to the * setup screen. */ @JvmStatic fun shouldValidateAccount(context: Context): Boolean { return PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(KEY_SHOULD_VALIDATE_ACCOUNT, false) } /** * Returns the account name used for authenticating against Hexagon, or null if not signed in. */ fun getAccountName(context: Context): String? { return PreferenceManager.getDefaultSharedPreferences(context) .getString(KEY_ACCOUNT_NAME, null) } /** * Whether the Hexagon setup has been completed after the last sign in. */ fun hasCompletedSetup(context: Context): Boolean { return PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(KEY_SETUP_COMPLETED, true) } fun setSetupCompleted(context: Context) { setSetupState(context, true) } fun setSetupIncomplete(context: Context) { setSetupState(context, false) } private fun setSetupState(context: Context, complete: Boolean) { PreferenceManager.getDefaultSharedPreferences(context).edit() .putBoolean(KEY_SETUP_COMPLETED, complete) .apply() } /** * Reset the sync state of shows, episodes, movies and lists so a data merge is triggered when * next syncing with Hexagon. * * @return If the sync settings reset was committed successfully. */ fun resetSyncState(context: Context): Boolean { // set all shows as not merged with Hexagon SgRoomDatabase.getInstance(context).sgShow2Helper().setHexagonMergeNotCompletedForAll() // reset sync properties val editor = PreferenceManager.getDefaultSharedPreferences(context).edit() editor.putBoolean(KEY_MERGED_SHOWS, false) editor.putBoolean(KEY_MERGED_MOVIES, false) editor.putBoolean(KEY_MERGED_LISTS, false) editor.remove(KEY_LAST_SYNC_EPISODES) editor.remove(KEY_LAST_SYNC_SHOWS) editor.remove(KEY_LAST_SYNC_MOVIES) editor.remove(KEY_LAST_SYNC_LISTS) return editor.commit() } /** * Resets the merged state of lists so a data merge is triggered when next syncing with Hexagon. * Returns if the sync settings reset was committed successfully. */ fun setListsNotMerged(context: Context): Boolean { return PreferenceManager.getDefaultSharedPreferences(context) .edit() .putBoolean(KEY_MERGED_LISTS, false) .commit() } /** * Whether shows in the local database have been merged with those on Hexagon. */ @JvmStatic fun hasMergedShows(context: Context): Boolean { return hasMerged(context, KEY_MERGED_SHOWS) } /** * Whether movies in the local database have been merged with those on Hexagon. */ @JvmStatic fun hasMergedMovies(context: Context): Boolean { return hasMerged(context, KEY_MERGED_MOVIES) } /** * Whether lists in the local database have been merged with those on Hexagon. */ @JvmStatic fun hasMergedLists(context: Context): Boolean { return hasMerged(context, KEY_MERGED_LISTS) } private fun hasMerged(context: Context, key: String): Boolean { return PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(key, false) } /** * Set the [.KEY_MERGED_SHOWS] setting. */ @JvmStatic fun setHasMergedShows(context: Context, hasMergedShows: Boolean) { PreferenceManager.getDefaultSharedPreferences(context) .edit() .putBoolean(KEY_MERGED_SHOWS, hasMergedShows) .apply() } @JvmStatic fun getLastEpisodesSyncTime(context: Context): Long { return getLastSyncTime(context, KEY_LAST_SYNC_EPISODES) } fun getLastShowsSyncTime(context: Context): Long { return getLastSyncTime(context, KEY_LAST_SYNC_SHOWS) } fun getLastMoviesSyncTime(context: Context): Long { return getLastSyncTime(context, KEY_LAST_SYNC_MOVIES) } @JvmStatic fun getLastListsSyncTime(context: Context): Long { return getLastSyncTime(context, KEY_LAST_SYNC_LISTS) } private fun getLastSyncTime(context: Context, key: String): Long { val prefs = PreferenceManager.getDefaultSharedPreferences(context) var lastSync = prefs.getLong(key, 0) if (lastSync == 0L) { lastSync = System.currentTimeMillis() // not synced yet, then last time is now! prefs.edit().putLong(key, lastSync).apply() } return lastSync } }
apache-2.0
a0c10ab74819893ee010dbdf6820bfcc
35.97191
100
0.686474
4.604619
false
false
false
false
mpv-android/mpv-android
app/src/main/java/is/xyz/mpv/NotificationButtonReceiver.kt
1
1513
package `is`.xyz.mpv import android.annotation.SuppressLint import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.ComponentName import android.content.Context import android.content.Intent import android.os.Build import android.util.Log class NotificationButtonReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { Log.v(TAG, "NotificationButtonReceiver: ${intent!!.action}") // remember to update AndroidManifest.xml too when adding here when (intent.action) { "$PREFIX.PLAY_PAUSE" -> MPVLib.command(arrayOf("cycle", "pause")) "$PREFIX.ACTION_PREV" -> MPVLib.command(arrayOf("playlist-prev")) "$PREFIX.ACTION_NEXT" -> MPVLib.command(arrayOf("playlist-next")) } } companion object { @SuppressLint("UnspecifiedImmutableFlag") fun createIntent(context: Context, action: String): PendingIntent { val intent = Intent("$PREFIX.$action") // turn into explicit intent intent.component = ComponentName(context, NotificationButtonReceiver::class.java) return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE) else PendingIntent.getBroadcast(context, 0, intent, 0) } private const val TAG = "mpv" private const val PREFIX = "is.xyz.mpv" } }
mit
99406d387fad4aaf941571fbabfd9027
38.815789
93
0.671514
4.669753
false
false
false
false
nickdex/cosmos
code/sorting/src/selection_sort/selection_sort.kt
8
543
// Part of Cosmos by OpenGenus Foundation import java.util.* fun <T : Comparable<T>> sort(array: Array<T>) { for (i in array.indices) { var min = i for (j in i + 1 until array.size) { /* find local min */ if (array[j] < array[min]) { min = j } } val temp = array[i] array[i] = array[min] array[min] = temp } } fun main(args: Array<String>) { val arr = arrayOf(1, 5, 2, 5, 2, 9, 7) sort(arr) print(Arrays.toString(arr)) }
gpl-3.0
59825be8cf71cff3837ca46317cacd52
21.666667
47
0.489871
3.213018
false
false
false
false
RxKotlin/KotlinAndroidDemo
login/src/main/java/com/kotlinchina/logindemo/login/LoginActivity.kt
1
1595
package com.kotlinchina.logindemo.login import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import com.jakewharton.rxbinding.widget.RxTextView import rx.Observable class LoginActivity : AppCompatActivity() { private var usernameEditText: EditText? = null private var passwordEditText: EditText? = null private var loginButton: Button? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) setupUI() setupAction() } private fun setupUI() { usernameEditText = findViewById(R.id.usernameEditText) as EditText passwordEditText = findViewById(R.id.passwordEditText) as EditText loginButton = findViewById(R.id.loginButton) as Button } private fun setupAction() { val usernameET = usernameEditText val passwordET = passwordEditText if (usernameET != null && usernameET is EditText && passwordET != null && passwordET is EditText) { Observable.combineLatest(RxTextView.textChanges(usernameET), RxTextView.textChanges(passwordET), { username, password -> shoudShowLogin(password, username) }).subscribe { result -> loginButton?.isEnabled = result } } } private fun shoudShowLogin(password: CharSequence, username: CharSequence) = username.length > 0 && password.length > 0 }
mit
2385253f1c1ac7c286468c804ce6d976
34.444444
123
0.6721
5.063492
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/routes/api/v1/guild/GetGuildInfoRoute.kt
1
1942
package net.perfectdreams.loritta.morenitta.website.routes.api.v1.guild import com.github.salomonbrys.kotson.jsonObject import io.ktor.server.application.ApplicationCall import net.dv8tion.jda.api.OnlineStatus import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.website.routes.api.v1.RequiresAPIAuthenticationRoute import net.perfectdreams.loritta.morenitta.website.utils.extensions.respondJson class GetGuildInfoRoute(loritta: LorittaBot) : RequiresAPIAuthenticationRoute(loritta, "/api/v1/guilds/{guildId}") { override suspend fun onAuthenticatedRequest(call: ApplicationCall) { val guildId = call.parameters["guildId"] ?: return val guild = loritta.lorittaShards.getGuildById(guildId) if (guild == null) { call.respondJson( jsonObject() ) return } call.respondJson( jsonObject( "id" to guild.id, "name" to guild.name, "iconUrl" to guild.iconUrl, "shardId" to guild.jda.shardInfo.shardId, "ownerId" to guild.ownerId, "count" to jsonObject( "textChannels" to guild.textChannelCache.size(), "voiceChannels" to guild.voiceChannelCache.size(), "members" to guild.memberCount, "onlineMembers" to guild.memberCache.filter { it.onlineStatus == OnlineStatus.ONLINE }.size, "idleMembers" to guild.memberCache.filter { it.onlineStatus == OnlineStatus.IDLE }.size, "doNotDisturbMembers" to guild.memberCache.filter { it.onlineStatus == OnlineStatus.DO_NOT_DISTURB }.size, "offlineMembers" to guild.memberCache.filter { it.onlineStatus == OnlineStatus.OFFLINE }.size, "bots" to guild.memberCache.filter { it.user.isBot }.size ), "timeCreated" to guild.timeCreated.toInstant().toEpochMilli(), "timeJoined" to guild.selfMember.timeJoined.toInstant().toEpochMilli(), "splashUrl" to guild.splashUrl, "boostCount" to guild.boostCount ) ) } }
agpl-3.0
27757b30c570fc717431f4a2f848fbbb
40.340426
116
0.73069
3.830375
false
false
false
false
Haldir65/AndroidRepo
otherprojects/_011_androidX/app/src/main/java/com/me/harris/droidx/MainActivity.kt
1
4318
package com.me.harris.droidx import android.app.Activity import android.app.Dialog import android.content.Context import android.content.Intent import android.graphics.Rect import android.os.Bundle import com.google.android.material.snackbar.Snackbar import androidx.appcompat.app.AppCompatActivity; import android.view.Menu import android.view.MenuItem import android.view.TextureView import android.view.View import androidx.appcompat.widget.Toolbar import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.me.harris.droidx.adapter.CustomAdapter import com.me.harris.droidx.adapter.ItemClickListener import com.me.harris.droidx.cronet.CronetActivity import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.activity_recycler_view.* class MainActivity : AppCompatActivity(), ItemClickListener { lateinit var mAdapter: CustomAdapter class GenericThing<T>(constructorArg: T) { // 1. Define a member property private val thing: T = constructorArg // 2. Define the type of a function argument fun doSomething(thing: T) = println(thing) // 3. Use as a type argument fun emptyList() = listOf<T>() // 4. Use as a type parameter constraint, and... // 5. Cast to the type (produces "unchecked cast" warning) fun <U : T> castIt(): T = thing as U } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_recycler_view) initAdapter() showDlg() } fun showDlg(){ val d = Dialog(this as Context) .apply { setTitle("title") setCancelable(true) setCanceledOnTouchOutside(true) }.show() } fun initAdapter(){ val userList = mutableListOf<Triple<String,Int,Class<out Activity>>>( Triple("Cronet",1, CronetActivity::class.java) // Triple("Retrofit",2,RetrofitSampleActivity::class.java), // Triple("RoundCorner",3,GlideTransformActivity::class.java), // Triple("Constraint",4,ConstraintActivity::class.java), // Triple("Flowable",5,FlowableMainActivity::class.java), // Triple("ClipPath",6,CustomDrawingActivity::class.java), // Triple("Coordinate",7,CoordinateActivity::class.java), // Triple("ClipPath",8,CustomDrawingActivity::class.java), // Triple("Locale",9,UpdatingConfigActivity::class.java), // Triple("Mail",10,SendMailActivity::class.java), // Triple("pager",11,PagerActivity::class.java), // Triple("EditText",12,EditTextActivity::class.java), // Triple("progressbar",13,ProgressBarStyleActivity::class.java), // Triple("shadow",14,ShadowLayerListActivity::class.java), // Triple("Strike",15,StrikeThroughActivity::class.java) ) mAdapter = CustomAdapter(userList,this) recyclerView1.adapter = mAdapter recyclerView1.layoutManager = LinearLayoutManager(this) recyclerView1.addItemDecoration(object : RecyclerView.ItemDecoration(){ override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { super.getItemOffsets(outRect, view, parent, state) outRect.set(12,5,12,5) } }) } override fun onItemClick(position: Int, view: View) { val target = mAdapter.userList[position].third val intent = Intent(this,target) startActivity(intent) } 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. return when (item.itemId) { R.id.action_settings -> true else -> super.onOptionsItemSelected(item) } } }
apache-2.0
5b16b27cf0cfb4fc20d4ef3131707e4e
36.224138
117
0.66767
4.474611
false
false
false
false
RyanAndroidTaylor/Rapido
rapidocommon/src/main/java/com/izeni/rapidocommon/Extensions.kt
1
4528
@file:Suppress("unused") package com.izeni.rapidocommon import com.izeni.rapidocommon.transaction.* import io.reactivex.Observable import io.reactivex.Scheduler import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import java.util.* import kotlin.reflect.KProperty import android.support.v4.app.Fragment as SupportFragment /** * The MIT License (MIT) * * Copyright (c) 2016 Izeni, 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. **/ fun <T> Observable<T>.onMain(subScheduler: Scheduler? = null): Observable<T> = (if (subScheduler != null) this.subscribeOn(subScheduler) else this).observeOn(AndroidSchedulers.mainThread()) fun <T> Observable<T>.watchOnMain(watcher: (T) -> Unit): Disposable = onMain().doOnNext(watcher).onErrorResumeNext({ t: Throwable -> Observable.empty<T>() }).subscribe() fun runOnIo(block: () -> Unit): Disposable { return Observable.just(Unit) .observeOn(Schedulers.io()) .subscribe({ block() }) } fun <T> Observable<T>.filterNetworkErrors(): Observable<Transaction<T>> { return lift(ObservableFilterTransactionError()) } fun <T> Single<T>.filterNetworkErrors(): Single<Transaction<T>> { return lift(SingleFilterError()) } fun String?.prepend(prepend: String) = if (isNullOrEmpty()) "" else "$prepend$this" fun String?.append(append: String) = if (isNullOrEmpty()) "" else "$this$append" fun String?.isNothing(): Boolean { val strLen: Int? = this?.length if (this == null || strLen == 0) return true return (0..strLen!!.minus(1)).none { Character.isWhitespace(this[it]) == false } } fun String.unescape(): String = this.replace("""\/""", "/") fun String?.nullSafe(default: String = ""): String = if (this == null) default else this inline fun <T> T?.ifNotNull(block: (T) -> Unit): T? { if (this != null) block(this) return this } inline fun whenNull(block: () -> Unit) { block() } inline fun <T> T?.ifNull(block: () -> Unit) { if (this == null) block() } inline infix fun Any?.isNotNull(if_true: (Any) -> Unit) { if (this != null) if_true.invoke(this) } class ResettableLazyManager { val managedDelegates = LinkedList<Resettable>() private var preReset: ((LinkedList<Resettable>) -> Boolean)? = null fun addPreResetListener(preReset: ((LinkedList<Resettable>) -> Boolean)?): ResettableLazyManager { this.preReset = preReset return this } fun register(managed: Resettable) { synchronized(managedDelegates) { managedDelegates.add(managed) } } fun reset() { synchronized(managedDelegates) { preReset?.invoke(managedDelegates) managedDelegates.forEach { it.reset() } managedDelegates.clear() } } } interface Resettable { fun reset() } class ResettableLazy<T>(val manager: ResettableLazyManager, val init: () -> T) : Resettable { @Volatile var lazyHolder = makeInitBlock() operator fun getValue(thisRef: Any?, property: KProperty<*>): T { return lazyHolder.value } override fun reset() { lazyHolder = makeInitBlock() } fun makeInitBlock(): Lazy<T> { return lazy { manager.register(this) init() } } } fun <T> resettableLazy(manager: ResettableLazyManager, init: () -> T): ResettableLazy<T> { return ResettableLazy(manager, init) }
mit
f6b27e3bac4e826230cf9b186b004edf
30.894366
118
0.6875
4.123862
false
false
false
false
sbhachu/Android
kotlin-news-reader/app/src/main/java/com/sbhachu/kotlin/newsreader/presentation/main/MainActivity.kt
1
2353
package com.sbhachu.kotlin.newsreader.presentation.main import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Log import android.view.View import com.sbhachu.kotlin.newsreader.R import com.sbhachu.kotlin.newsreader.domain.model.Item import com.sbhachu.kotlin.newsreader.presentation.common.BaseActivity import com.sbhachu.kotlin.newsreader.presentation.common.recycler.BaseRecyclerAdapter import com.sbhachu.kotlin.newsreader.presentation.common.recycler.LineSeparatorDecorator import com.sbhachu.kotlin.newsreader.presentation.main.adapter.ArticlesAdapter class MainActivity : BaseActivity<MainPresenter>(), IMainViewContract, BaseRecyclerAdapter.ItemListener<Item> { private val TAG: String = "MainActivity" override val layoutId: Int = R.layout.activity_main private val recycler: RecyclerView by lazy { findViewById(R.id.article_recycler) as RecyclerView } private var adapter: ArticlesAdapter? = null override fun initialisePresenter(): MainPresenter { return MainPresenter(this); } override fun initialiseViews() { title = "Top Stories" // setup recycler view var linearLayourManager: LinearLayoutManager = LinearLayoutManager(this) linearLayourManager.orientation = LinearLayoutManager.VERTICAL recycler.setHasFixedSize(true) recycler.layoutManager = linearLayourManager recycler.itemAnimator = DefaultItemAnimator() // recycler.addItemDecoration(LineSeparatorDecorator(this)) // setup adapter adapter = ArticlesAdapter(this); adapter?.setItemListener(this) recycler.adapter = adapter } override fun initialiseListeners() { } override fun onResume() { super.onResume() presenter.onResume() } override fun onPause() { super.onPause() presenter.onPause() } override fun updateArticleList(articles: List<Item>) { Log.e(TAG, articles.toString()) adapter?.setItems(articles) adapter?.notifyDataSetChanged() } override fun fetchDataError(error: String) { Log.e(TAG, error) } override fun onItemClicked(view: View, item: Item) { Log.e(TAG, item.toString()) } }
apache-2.0
dba9bab577b97be4fb85cceafcf96495
30.373333
111
0.727582
4.811861
false
false
false
false
carlphilipp/chicago-commutes
android-app/src/main/kotlin/fr/cph/chicago/core/activity/station/BusStopActivity.kt
1
12849
/** * Copyright 2021 Carl-Philipp Harmant * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package fr.cph.chicago.core.activity.station import android.annotation.SuppressLint import android.os.Bundle import android.view.View import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.widget.RelativeLayout import android.widget.TextView import androidx.appcompat.widget.Toolbar import fr.cph.chicago.R import fr.cph.chicago.core.App import fr.cph.chicago.core.listener.GoogleStreetOnClickListener import fr.cph.chicago.core.listener.OpenMapDirectionOnClickListener import fr.cph.chicago.core.listener.OpenMapOnClickListener import fr.cph.chicago.core.model.BusStop import fr.cph.chicago.core.model.Position import fr.cph.chicago.core.model.dto.BusArrivalStopDTO import fr.cph.chicago.databinding.ActivityBusBinding import fr.cph.chicago.redux.AddBusFavoriteAction import fr.cph.chicago.redux.BusStopArrivalsAction import fr.cph.chicago.redux.RemoveBusFavoriteAction import fr.cph.chicago.redux.State import fr.cph.chicago.redux.Status import fr.cph.chicago.redux.store import fr.cph.chicago.service.BusService import fr.cph.chicago.util.Color import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.schedulers.Schedulers import org.apache.commons.lang3.StringUtils import org.rekotlin.StoreSubscriber import timber.log.Timber /** * Activity that represents the bus stop * * @author Carl-Philipp Harmant * @version 1 */ class BusStopActivity : StationActivity(), StoreSubscriber<State> { companion object { private val busService = BusService } private lateinit var busRouteId: String private lateinit var bound: String private lateinit var boundTitle: String private var busStopId: String = StringUtils.EMPTY private lateinit var busStopName: String private lateinit var busRouteName: String private lateinit var action: BusStopArrivalsAction private lateinit var binding: ActivityBusBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityBusBinding.inflate(layoutInflater) setContentView(binding.root) setupView( swipeRefreshLayout = binding.activityStationSwipeRefreshLayout, streetViewImage = binding.header.streetViewImage, streetViewProgressBar = binding.header.streetViewProgressBar, streetViewText = binding.header.streetViewText, favoritesImage = binding.header.favorites.favoritesImage, mapImage = binding.header.favorites.mapImage, favoritesImageContainer = binding.header.favorites.favoritesImageContainer ) busStopId = intent.getStringExtra(getString(R.string.bundle_bus_stop_id)) ?: StringUtils.EMPTY busRouteId = intent.getStringExtra(getString(R.string.bundle_bus_route_id)) ?: StringUtils.EMPTY bound = intent.getStringExtra(getString(R.string.bundle_bus_bound)) ?: StringUtils.EMPTY boundTitle = intent.getStringExtra(getString(R.string.bundle_bus_bound_title)) ?: StringUtils.EMPTY busRouteName = intent.getStringExtra(getString(R.string.bundle_bus_route_name)) ?: StringUtils.EMPTY action = BusStopArrivalsAction( busRouteId = busRouteId, busStopId = busStopId, bound = bound, boundTitle = boundTitle) handleFavorite() val busRouteNameDisplay = "$busRouteName ($boundTitle)" binding.busRouteNameView.text = busRouteNameDisplay buildToolbar(binding.included.toolbar) loadStopDetailsAndStreetImage() } override fun onPause() { super.onPause() store.unsubscribe(this) } override fun onResume() { super.onResume() store.subscribe(this) store.dispatch(action) } override fun newState(state: State) { Timber.d("New state") when (state.busStopStatus) { Status.SUCCESS -> refreshActivity(state.busArrivalStopDTO) Status.FAILURE -> util.showSnackBar(swipeRefreshLayout, state.busStopErrorMessage) Status.ADD_FAVORITES -> { if (applyFavorite) { util.showSnackBar(swipeRefreshLayout, R.string.message_add_fav, true) applyFavorite = false favoritesImage.setColorFilter(Color.yellowLineDark) } } Status.REMOVE_FAVORITES -> { if (applyFavorite) { util.showSnackBar(swipeRefreshLayout, R.string.message_remove_fav, true) applyFavorite = false favoritesImage.drawable.colorFilter = mapImage.drawable.colorFilter } } else -> Timber.d("Status not handled") } stopRefreshing() } override fun refresh() { super.refresh() if (position.latitude == 0.0 && position.longitude == 0.0) { loadStopDetailsAndStreetImage() } else { store.dispatch(action) loadGoogleStreetImage(position) } } @SuppressLint("CheckResult") private fun loadStopDetailsAndStreetImage() { // Load bus stop details and google street image busService.loadAllBusStopsForRouteBound(busRouteId, boundTitle) .observeOn(Schedulers.computation()) .flatMap { stops -> val busStop: BusStop? = stops.firstOrNull { busStop -> busStop.id == busStopId } Single.just(busStop!!) } .map { busStop -> loadGoogleStreetImage(busStop.position) position = Position(busStop.position.latitude, busStop.position.longitude) busStopName = busStop.name busStop } .observeOn(AndroidSchedulers.mainThread()) .doOnError { throwable -> Timber.e(throwable, "Error while loading street image and stop details") onError() } .subscribe( { busStop -> toolbar.title = "$busRouteId - ${busStop.name}" streetViewImage.setOnClickListener(GoogleStreetOnClickListener(position.latitude, position.longitude)) binding.header.favorites.mapContainer.setOnClickListener(OpenMapOnClickListener(position.latitude, position.longitude)) binding.header.favorites.walkContainer.setOnClickListener(OpenMapDirectionOnClickListener(position.latitude, position.longitude)) }, { throwable -> Timber.e(throwable, "Error while loading street image and stop details") onError() }) } private fun onError() { util.showOopsSomethingWentWrong(swipeRefreshLayout) failStreetViewImage(streetViewImage) streetViewProgressBar.visibility = View.GONE } override fun buildToolbar(toolbar: Toolbar) { super.buildToolbar(toolbar) toolbar.title = busRouteId } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) busStopId = savedInstanceState.getString(getString(R.string.bundle_bus_stop_id)) ?: StringUtils.EMPTY busRouteId = savedInstanceState.getString(getString(R.string.bundle_bus_route_id)) ?: StringUtils.EMPTY bound = savedInstanceState.getString(getString(R.string.bundle_bus_bound)) ?: StringUtils.EMPTY boundTitle = savedInstanceState.getString(getString(R.string.bundle_bus_bound_title)) ?: StringUtils.EMPTY busStopName = savedInstanceState.getString(getString(R.string.bundle_bus_stop_name)) ?: StringUtils.EMPTY busRouteName = savedInstanceState.getString(getString(R.string.bundle_bus_route_name)) ?: StringUtils.EMPTY position = savedInstanceState.getParcelable(getString(R.string.bundle_position)) as Position? ?: Position() action = BusStopArrivalsAction( busRouteId = busRouteId, busStopId = busStopId, bound = bound, boundTitle = boundTitle) } override fun onSaveInstanceState(savedInstanceState: Bundle) { savedInstanceState.putString(getString(R.string.bundle_bus_stop_id), busStopId.toString()) if (::busRouteId.isInitialized) savedInstanceState.putString(getString(R.string.bundle_bus_route_id), busRouteId) if (::bound.isInitialized) savedInstanceState.putString(getString(R.string.bundle_bus_bound), bound) if (::boundTitle.isInitialized) savedInstanceState.putString(getString(R.string.bundle_bus_bound_title), boundTitle) if (::busStopName.isInitialized) savedInstanceState.putString(getString(R.string.bundle_bus_stop_name), busStopName) if (::busRouteName.isInitialized) savedInstanceState.putString(getString(R.string.bundle_bus_route_name), busRouteName) savedInstanceState.putParcelable(getString(R.string.bundle_position), position) super.onSaveInstanceState(savedInstanceState) } /** * Draw arrivals in current layout */ private fun refreshActivity(busArrivals: BusArrivalStopDTO) { cleanLayout() if (busArrivals.isEmpty()) { binding.destinationTextView.text = App.instance.getString(R.string.bus_activity_no_service) binding.arrivalsTextView.text = StringUtils.EMPTY } else { val key1 = busArrivals.keys.iterator().next() binding.destinationTextView.text = key1 binding.arrivalsTextView.text = busArrivals[key1]!!.joinToString(separator = " ") { util.formatArrivalTime(it) } var idBelowTitle = binding.destinationTextView.id var idBellowArrival = binding.arrivalsTextView.id busArrivals.entries.drop(1).forEach { val belowTitle = with(TextView(this)) { text = it.key id = util.generateViewId() isSingleLine = true layoutParams = createLineBelowLayoutParams(idBelowTitle) this } idBelowTitle = belowTitle.id val belowArrival = with(TextView(this)) { text = it.value.joinToString(separator = " ") { util.formatArrivalTime(it) } id = util.generateViewId() isSingleLine = true layoutParams = createLineBelowLayoutParams(idBellowArrival) this } idBellowArrival = belowArrival.id binding.leftLayout.addView(belowTitle) binding.rightLayout.addView(belowArrival) } } } private fun cleanLayout() { binding.destinationTextView.text = StringUtils.EMPTY binding.arrivalsTextView.text = StringUtils.EMPTY while (binding.leftLayout.childCount >= 2) { val view = binding.leftLayout.getChildAt(binding.leftLayout.childCount - 1) binding.leftLayout.removeView(view) } while (binding.rightLayout.childCount >= 2) { val view2 = binding.rightLayout.getChildAt(binding.rightLayout.childCount - 1) binding.rightLayout.removeView(view2) } } private fun createLineBelowLayoutParams(id: Int): RelativeLayout.LayoutParams { val arrivalLayoutParams = RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT) arrivalLayoutParams.addRule(RelativeLayout.BELOW, id) return arrivalLayoutParams } override fun isFavorite(): Boolean { return preferenceService.isStopFavorite(busRouteId, busStopId, boundTitle) } /** * Add or remove from favorites */ override fun switchFavorite() { super.switchFavorite() App.instance.refresh = true // because the state is not updated if (isFavorite()) { store.dispatch(RemoveBusFavoriteAction(busRouteId, busStopId.toString(), boundTitle)) } else { store.dispatch(AddBusFavoriteAction(busRouteId, busStopId.toString(), boundTitle, busRouteName, busStopName)) } } }
apache-2.0
ea3ee0272f2a571e44e29236cf69e208
41.127869
149
0.672659
4.9706
false
false
false
false
vhromada/Catalog-Spring
src/main/kotlin/cz/vhromada/catalog/web/mapper/impl/ShowMapperImpl.kt
1
1552
package cz.vhromada.catalog.web.mapper.impl import cz.vhromada.catalog.entity.Show import cz.vhromada.catalog.web.fo.ShowFO import cz.vhromada.catalog.web.mapper.ShowMapper import org.springframework.stereotype.Component /** * A class represents implementation of mapper for shows. * * @author Vladimir Hromada */ @Component("webShowMapper") class ShowMapperImpl : ShowMapper { override fun map(source: Show): ShowFO { return ShowFO(id = source.id, czechName = source.czechName, originalName = source.originalName, csfd = source.csfd, imdb = source.imdbCode!! >= 1, imdbCode = if (source.imdbCode!! < 1) null else source.imdbCode!!.toString(), wikiEn = source.wikiEn, wikiCz = source.wikiCz, picture = source.picture, note = source.note, position = source.position, genres = source.genres!!.map { it!!.id!! }) } override fun mapBack(source: ShowFO): Show { return Show(id = source.id, czechName = source.czechName, originalName = source.originalName, csfd = source.csfd, imdbCode = if (source.imdb) source.imdbCode!!.toInt() else -1, wikiEn = source.wikiEn, wikiCz = source.wikiCz, picture = source.picture, note = source.note, position = source.position, genres = null) } }
mit
9ca0a28488dab7c5ffd0e84dd66d2e8f
33.488889
93
0.570876
4.632836
false
false
false
false
vhromada/Catalog-Spring
src/test/kotlin/cz/vhromada/catalog/web/common/ProgramUtils.kt
1
2482
package cz.vhromada.catalog.web.common import cz.vhromada.catalog.entity.Program import cz.vhromada.catalog.web.fo.ProgramFO import org.assertj.core.api.SoftAssertions.assertSoftly /** * A class represents utility class for programs. * * @author Vladimir Hromada */ object ProgramUtils { /** * Returns FO for program. * * @return FO for program */ fun getProgramFO(): ProgramFO { return ProgramFO(id = CatalogUtils.ID, name = CatalogUtils.NAME, wikiEn = CatalogUtils.EN_WIKI, wikiCz = CatalogUtils.CZ_WIKI, mediaCount = CatalogUtils.MEDIA.toString(), crack = true, serialKey = true, otherData = "Other data", note = CatalogUtils.NOTE, position = CatalogUtils.POSITION) } /** * Returns program. * * @return program */ fun getProgram(): Program { return Program(id = CatalogUtils.ID, name = CatalogUtils.NAME, wikiEn = CatalogUtils.EN_WIKI, wikiCz = CatalogUtils.CZ_WIKI, mediaCount = CatalogUtils.MEDIA, crack = true, serialKey = true, otherData = "Other data", note = CatalogUtils.NOTE, position = CatalogUtils.POSITION) } /** * Asserts program deep equals. * * @param expected expected FO for program * @param actual actual program */ fun assertProgramDeepEquals(expected: ProgramFO?, actual: Program?) { assertSoftly { it.assertThat(expected).isNotNull it.assertThat(actual).isNotNull } assertSoftly { it.assertThat(actual!!.id).isEqualTo(expected!!.id) it.assertThat(actual.name).isEqualTo(expected.name) it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn) it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz) it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount?.toInt()) it.assertThat(actual.crack).isEqualTo(expected.crack) it.assertThat(actual.serialKey).isEqualTo(expected.serialKey) it.assertThat(actual.otherData).isEqualTo(expected.otherData) it.assertThat(actual.note).isEqualTo(expected.note) it.assertThat(actual.position).isEqualTo(expected.position) } } }
mit
46a5a15e15e340b727a53bb310ea4b0a
32.093333
84
0.593473
4.905138
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/features/multiblocks/Containers.kt
2
5125
package com.cout970.magneticraft.features.multiblocks import com.cout970.magneticraft.features.multiblocks.tileentities.TileShelvingUnit import com.cout970.magneticraft.misc.gui.SlotShelvingUnit import com.cout970.magneticraft.misc.inventory.InventoryRegion import com.cout970.magneticraft.misc.inventory.isNotEmpty import com.cout970.magneticraft.misc.network.IBD import com.cout970.magneticraft.misc.vector.vec2Of import com.cout970.magneticraft.systems.config.Config import com.cout970.magneticraft.systems.gui.* import com.cout970.magneticraft.systems.integration.IntegrationHandler import com.cout970.magneticraft.systems.integration.jei.MagneticraftPlugin import com.cout970.magneticraft.systems.tilemodules.ModuleShelvingUnitMb import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.util.math.BlockPos import net.minecraft.world.World /** * Created by cout970 on 2017/08/10. */ class ContainerShelvingUnit(builder: GuiBuilder, configFunc: (AutoContainer) -> Unit, player: EntityPlayer, world: World, pos: BlockPos) : AutoContainer(builder, configFunc, player, world, pos) { val tile: TileShelvingUnit = tileEntity as TileShelvingUnit val allSlots: List<SlotShelvingUnit> var currentSlots = emptyList<SlotShelvingUnit>() var currentLevel = tile.shelvingUnitModule.guiLevel init { val inv = tile.invModule.inventory allSlots = (0 until inv.slots).map { val x = it % 9 * 18 + 8 val y = it / 9 * 18 + 21 SlotShelvingUnit(inv, it, x, y) } allSlots.forEach { addSlotToContainer(it) } bindPlayerInventory(player.inventory, vec2Of(0, 41)) } override fun postInit() { switchLevel(currentLevel) } fun updateCurrentSlots(list: List<SlotShelvingUnit>) { allSlots.forEach { it.hide(); it.lock() } currentSlots = list withScroll(0f) } fun levelButton(id: Int) { val ibd = IBD().apply { setInteger(DATA_ID_SHELVING_UNIT_LEVEL, id) setString(DATA_ID_SHELVING_UNIT_FILTER, "") } sendUpdate(ibd) filterSlots("") switchLevel(ModuleShelvingUnitMb.Level.values()[id]) } fun switchLevel(newLevel: ModuleShelvingUnitMb.Level) { currentLevel = newLevel val available = tile.shelvingUnitModule.getAvailableSlots(currentLevel) updateCurrentSlots(allSlots.filterIndexed { index, _ -> index in available }) } fun withScroll(scrollLevel: Float) { currentSlots.forEach { it.hide(); it.lock() } val column = Math.max(0, Math.round(scrollLevel * ((currentSlots.size / 9f) - 5))) var min = Int.MAX_VALUE var max = Int.MIN_VALUE currentSlots.forEachIndexed { index, it -> val pos = index - column * 9 it.unlock() if ((pos) >= 0 && (pos) < 5 * 9) { it.show() it.xPos = pos % 9 * 18 + 8 it.yPos = pos / 9 * 18 + 21 } if (it.slotIndex > max) max = it.slotIndex if (it.slotIndex < min) min = it.slotIndex } inventoryRegions.clear() inventoryRegions += InventoryRegion(min..max) inventoryRegions += InventoryRegion(648..674) inventoryRegions += InventoryRegion(675..683) } fun filterSlots(filter: String) { if (filter.isEmpty() || filter.isBlank()) { switchLevel(currentLevel) return } fun matches(stack: ItemStack, filter: String): Boolean { if (stack.isEmpty) return false if (filter.startsWith('@')) { val mod = filter.substring(1) return stack.item.registryName!!.resourceDomain.contains(mod, ignoreCase = true) } return stack.displayName.contains(filter, ignoreCase = true) } updateCurrentSlots(allSlots.filter { matches(it.stack, filter) }) } fun serverFilterSlots(slots: IntArray) { if (slots.isEmpty()) { switchLevel(currentLevel) return } updateCurrentSlots(allSlots.filter { it.stack.isNotEmpty && it.slotNumber in slots }) } fun setFilter(text: String) { if (IntegrationHandler.jei && Config.syncShelvingUnitSearchWithJei) { setJeiFilter(text) } filterSlots(text) sendUpdate(IBD().apply { setIntArray(DATA_ID_SHELVING_UNIT_FILTER, currentSlots.map { it.slotNumber }.toIntArray()) }) } fun setJeiFilter(text: String) { MagneticraftPlugin.INSTANCE.getSearchBar().filterText = text } override fun receiveDataFromClient(ibd: IBD) { ibd.getBoolean(DATA_ID_SHELVING_UNIT_SORT) { tile.shelvingUnitModule.sortStacks() } ibd.getInteger(DATA_ID_SHELVING_UNIT_LEVEL) { switchLevel(ModuleShelvingUnitMb.Level.values()[it]) } ibd.getFloat(DATA_ID_SHELVING_UNIT_SCROLL) { withScroll(it) } ibd.getIntArray(DATA_ID_SHELVING_UNIT_FILTER) { serverFilterSlots(it) } } }
gpl-2.0
1f6e8159766d6f0c63875442c9535e29
34.590278
136
0.64878
4.20082
false
false
false
false
spark/photon-tinker-android
devicesetup/src/main/java/io/particle/android/sdk/devicesetup/apconnector/ApConnectorApi29.kt
1
4217
package io.particle.android.sdk.devicesetup.apconnector import android.annotation.SuppressLint import android.content.Context import android.net.* import android.net.wifi.WifiConfiguration import android.net.wifi.WifiNetworkSpecifier import android.os.Build.VERSION_CODES import androidx.annotation.MainThread import androidx.annotation.RequiresApi import androidx.core.content.getSystemService import io.particle.android.sdk.devicesetup.apconnector.ApConnector.Client import io.particle.android.sdk.devicesetup.ui.DeviceSetupState import io.particle.android.sdk.utils.SSID import io.particle.android.sdk.utils.WifiFacade import mu.KotlinLogging private val log = KotlinLogging.logger {} @RequiresApi(VERSION_CODES.LOLLIPOP) class ApConnectorApi29( ctx: Context, private val wifiFacade: WifiFacade ) : ApConnector { private val connectivityManager: ConnectivityManager = ctx.applicationContext.getSystemService()!! private val decoratingClient: DecoratingClient = DecoratingClient { clearState() } private var networkCallbacks: ConnectivityManager.NetworkCallback? = null @SuppressLint("NewApi") @MainThread override fun connectToAP(config: WifiConfiguration, client: Client) { val configSSID = SSID.from(config) log.info { "preparing to connect to $configSSID..." } decoratingClient.wrappedClient = client networkCallbacks = buildNetworkCallbacks(config) val currentConnectionInfo = wifiFacade.connectionInfo // are we already connected to the right AP? (this could happen on retries) if (ApConnectorApi21.isAlreadyConnectedToTargetNetwork(currentConnectionInfo, configSSID)) { // we're already connected to this AP, nothing to do. log.info { "we're already connected to $configSSID, nothing to do." } decoratingClient.onApConnectionSuccessful(config) return } val wifiNetworkSpecifier: WifiNetworkSpecifier = WifiNetworkSpecifier.Builder() .setSsid(configSSID.toString()) .build() val request: NetworkRequest = NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .setNetworkSpecifier(wifiNetworkSpecifier) .build() log.info { "Requesting to connect to $configSSID" } connectivityManager.requestNetwork(request, networkCallbacks!!) } @MainThread override fun stop() { decoratingClient.wrappedClient = null clearState() } private fun buildNetworkCallbacks( config: WifiConfiguration ): ConnectivityManager.NetworkCallback { return object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { log.info { "onAvailable: $network" } decoratingClient.onApConnectionSuccessful(config) } override fun onBlockedStatusChanged(network: Network, blocked: Boolean) { log.info { "onBlockedStatusChanged: $network, blocked=$blocked" } } override fun onCapabilitiesChanged( network: Network, networkCapabilities: NetworkCapabilities ) { log.info { "onCapabilitiesChanged: $network, caps: $networkCapabilities" } } override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) { log.info { "onLinkPropertiesChanged: $network" } } override fun onLosing(network: Network, maxMsToLive: Int) { log.info { "onLosing: $network" } } override fun onLost(network: Network) { log.info { "onLost: $network" } } override fun onUnavailable() { log.info { "onUnavailable" } } } } private fun clearState() { try { DeviceSetupState.networkCallbacks = networkCallbacks } catch (ex: IllegalArgumentException) { // don't worry if we weren't registered. } } }
apache-2.0
af2aad0186cf2d454361e7df50f908fa
34.436975
100
0.670382
5.050299
false
true
false
false
toastkidjp/Jitte
lib/src/main/java/jp/toastkid/lib/view/thumbnail/ThumbnailGenerator.kt
1
1238
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.lib.view.thumbnail import android.graphics.Bitmap import android.graphics.Canvas import android.view.View import androidx.annotation.UiThread import timber.log.Timber /** * @author toastkidjp */ class ThumbnailGenerator { @UiThread operator fun invoke(view: View?): Bitmap? { if (view == null || view.measuredWidth == 0 || view.measuredHeight == 0) { return null } val bitmap = Bitmap.createBitmap( view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888 ) val c = Canvas(bitmap) view.invalidate() // For avoiding IllegalArgumentException: Software rendering doesn't support hardware bitmaps try { view.draw(c) } catch (e: IllegalArgumentException) { Timber.e(e) return null } return bitmap } }
epl-1.0
965977ecfe8f66a0718a295257bb2944
25.361702
101
0.641357
4.619403
false
false
false
false
consp1racy/android-commons
commons/src/main/java/net/xpece/android/content/SharedPreferences.kt
1
1043
@file:JvmName("XpPreferences") @file:Suppress("NOTHING_TO_INLINE") package net.xpece.android.content import android.content.SharedPreferences import androidx.core.content.edit @Deprecated( "Use AndroidX.", ReplaceWith("edit(commit, func)", imports = ["androidx.core.content.edit"]) ) inline fun SharedPreferences.update(commit: Boolean = false, func: SharedPreferences.Editor.() -> Unit) { edit(commit, func) } inline operator fun SharedPreferences.Editor.set(key: String, value: String) = putString(key, value)!! inline operator fun SharedPreferences.Editor.set(key: String, value: Int) = putInt(key, value)!! inline operator fun SharedPreferences.Editor.set(key: String, value: Long) = putLong(key, value)!! inline operator fun SharedPreferences.Editor.set(key: String, value: Boolean) = putBoolean(key, value)!! inline operator fun SharedPreferences.Editor.set(key: String, value: Float) = putFloat(key, value)!! inline operator fun SharedPreferences.Editor.set(key: String, value: Set<String>) = putStringSet(key, value)!!
apache-2.0
1cb5475e8933e3a049b2e87d9ee42b30
46.409091
110
0.760307
3.935849
false
false
false
false
Shynixn/BlockBall
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/commandmenu/TeamTextBookPage.kt
1
8847
package com.github.shynixn.blockball.core.logic.business.commandmenu import com.github.shynixn.blockball.api.business.enumeration.* import com.github.shynixn.blockball.api.persistence.entity.Arena import com.github.shynixn.blockball.api.persistence.entity.ChatBuilder import com.github.shynixn.blockball.api.persistence.entity.TeamMeta import com.github.shynixn.blockball.core.logic.persistence.entity.ChatBuilderEntity /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ class TeamTextBookPage : Page(TeamTextBookPage.ID, MainSettingsPage.ID) { companion object { /** Id of the page. */ const val ID = 27 } /** * Returns the key of the command when this page should be executed. * * @return key */ override fun getCommandKey(): MenuPageKey { return MenuPageKey.TEAMTEXTBOOK } /** * Executes actions for this page. * * @param cache cache */ override fun <P> execute(player: P, command: MenuCommand, cache: Array<Any?>, args: Array<String>): MenuCommandResult { if (command == MenuCommand.TEXTBOOK_OPEN) { cache[5] = cache[2] val teamMeta = getTeamMeta(cache) cache[2] = teamMeta.signLines } else if (command == MenuCommand.TEXTBOOK_JOINMESSAGE && args.size >= 3) { val teamMeta = getTeamMeta(cache) teamMeta.joinMessage = mergeArgs(2, args) } else if (command == MenuCommand.TEXTBOOK_LEAVEMESSAGE && args.size >= 3) { val teamMeta = getTeamMeta(cache) teamMeta.leaveMessage = mergeArgs(2, args) } else if (command == MenuCommand.TEXTBOOK_SCORETIELE && args.size >= 3) { val teamMeta = getTeamMeta(cache) teamMeta.scoreMessageTitle = mergeArgs(2, args) } else if (command == MenuCommand.TEXTBOOK_SCORESUBTITLE && args.size >= 3) { val teamMeta = getTeamMeta(cache) teamMeta.scoreMessageSubTitle = mergeArgs(2, args) } else if (command == MenuCommand.TEXTBOOK_WINTIELE && args.size >= 3) { val teamMeta = getTeamMeta(cache) teamMeta.winMessageTitle = mergeArgs(2, args) } else if (command == MenuCommand.TEXTBOOK_WINSUBTITLE && args.size >= 3) { val teamMeta = getTeamMeta(cache) teamMeta.winMessageSubTitle = mergeArgs(2, args) } else if (command == MenuCommand.TEXTBOOK_DRAWTIELE && args.size >= 3) { val teamMeta = getTeamMeta(cache) teamMeta.drawMessageTitle = mergeArgs(2, args) } else if (command == MenuCommand.TEXTBOOK_DRAWSUBTITLE && args.size >= 3) { val teamMeta = getTeamMeta(cache) teamMeta.drawMessageSubTitle = mergeArgs(2, args) } return super.execute(player, command, cache, args) } /** * Builds the page content. * * @param cache cache * @return content */ override fun buildPage(cache: Array<Any?>): ChatBuilder? { val teamMeta = getTeamMeta(cache) return ChatBuilderEntity() .component("- Join Message: ").builder() .component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color) .setHoverText(teamMeta.joinMessage).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.TEXTBOOK_JOINMESSAGE.command) .setHoverText("Changes the message being played when a player joins this team.") .builder().nextLine() .component("- Leave Message: ").builder() .component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color) .setHoverText(teamMeta.leaveMessage).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.TEXTBOOK_LEAVEMESSAGE.command) .setHoverText("Changes the message being played when a player leaves this team.") .builder().nextLine() .component("- ScoreTitle Message: ").builder() .component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color) .setHoverText(teamMeta.scoreMessageTitle).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.TEXTBOOK_SCORETIELE.command) .setHoverText("Changes the title message getting played when a player scores a goal.") .builder().nextLine() .component("- ScoreSubTitle Message: ").builder() .component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color) .setHoverText(teamMeta.scoreMessageSubTitle).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.TEXTBOOK_SCORESUBTITLE.command) .setHoverText("Changes the subtitle message getting played when a player scores a goal.") .builder().nextLine() .component("- WinTitle Message: ").builder() .component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color) .setHoverText(teamMeta.winMessageTitle).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.TEXTBOOK_WINTIELE.command) .setHoverText("Changes the title message getting played when the team wins the match.") .builder().nextLine() .component("- WinSubTitle Message: ").builder() .component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color) .setHoverText(teamMeta.winMessageSubTitle).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.TEXTBOOK_WINSUBTITLE.command) .setHoverText("Changes the subtitle message getting played when the team wins the match.") .builder().nextLine() .component("- DrawTitle Message: ").builder() .component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color) .setHoverText(teamMeta.drawMessageTitle).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.TEXTBOOK_DRAWTIELE.command) .setHoverText("Changes the title message getting played when the match ends in a draw.") .builder().nextLine() .component("- DrawSubTitle Message: ").builder() .component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color) .setHoverText(teamMeta.drawMessageSubTitle).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.TEXTBOOK_DRAWSUBTITLE.command) .setHoverText("Changes the subtitle message getting played when the match ends in a draw.") .builder() } private fun getTeamMeta(cache: Array<Any?>?): TeamMeta { val arena = cache!![0] as Arena val type = cache[5] as Int return if (type == 0) { arena.meta.redTeamMeta } else { arena.meta.blueTeamMeta } } }
apache-2.0
83a215335fc611fbb22d5d4a40ca12fd
51.982036
123
0.678648
4.800326
false
false
false
false
viacheslavokolitiy/RxBinding-1
rxbinding-kotlin/src/main/kotlin/com/jakewharton/rxbinding/view/RxView.kt
4
15416
package com.jakewharton.rxbinding.view import android.view.DragEvent import android.view.MotionEvent import android.view.View import com.jakewharton.rxbinding.internal.Functions import rx.Observable import rx.functions.Action1 import rx.functions.Func0 import rx.functions.Func1 /** * Create an observable which emits on `view` attach events. The emitted value is * unspecified and should only be used as notification. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.attaches(): Observable<Any> = RxView.attaches(this) /** * Create an observable of attach and detach events on `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.attachEvents(): Observable<ViewAttachEvent> = RxView.attachEvents(this) /** * Create an observable which emits on `view` detach events. The emitted value is * unspecified and should only be used as notification. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.detaches(): Observable<Any> = RxView.detaches(this) /** * Create an observable which emits on `view` click events. The emitted value is * unspecified and should only be used as notification. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnClickListener] to observe * clicks. Only one observable can be used for a view at a time. */ public inline fun View.clicks(): Observable<Any> = RxView.clicks(this) /** * Create an observable of click events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnClickListener] to observe * clicks. Only one observable can be used for a view at a time. */ public inline fun View.clickEvents(): Observable<ViewClickEvent> = RxView.clickEvents(this) /** * Create an observable of [DragEvent] for drags on `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnDragListener] to observe * drags. Only one observable can be used for a view at a time. */ public inline fun View.drags(): Observable<DragEvent> = RxView.drags(this) /** * Create an observable of [DragEvent] for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnDragListener] to observe * drags. Only one observable can be used for a view at a time. * * @param handled Function invoked with each value to determine the return value of the * underlying [View.OnDragListener]. */ public inline fun View.drags(handled: Func1<in DragEvent, Boolean>): Observable<DragEvent> = RxView.drags(this, handled) /** * Create an observable of drag events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnDragListener] to observe * drags. Only one observable can be used for a view at a time. */ public inline fun View.dragEvents(): Observable<ViewDragEvent> = RxView.dragEvents(this) /** * Create an observable of drag events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnDragListener] to observe * drags. Only one observable can be used for a view at a time. * * @param handled Function invoked with each value to determine the return value of the * underlying [View.OnDragListener]. */ public inline fun View.dragEvents(handled: Func1<in ViewDragEvent, Boolean>): Observable<ViewDragEvent> = RxView.dragEvents(this, handled) /** * Create an observable of booleans representing the focus of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnFocusChangeListener] to observe * focus change. Only one observable can be used for a view at a time. * * *Note:* A value will be emitted immediately on subscribe. */ public inline fun View.focusChanges(): Observable<Boolean> = RxView.focusChanges(this) /** * Create an observable of focus-change events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnFocusChangeListener] to observe * focus change. Only one observable can be used for a view at a time. * * *Note:* A value will be emitted immediately on subscribe. */ public inline fun View.focusChangeEvents(): Observable<ViewFocusChangeEvent> = RxView.focusChangeEvents(this) /** * Create an observable of hover events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnHoverListener] to observe * touches. Only one observable can be used for a view at a time. */ public inline fun View.hovers(): Observable<MotionEvent> = RxView.hovers(this) /** * Create an observable of hover events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnHoverListener] to observe * touches. Only one observable can be used for a view at a time. * * @param handled Function invoked with each value to determine the return value of the * underlying [View.OnHoverListener]. */ public inline fun View.hovers(handled: Func1<in MotionEvent, Boolean>): Observable<MotionEvent> = RxView.hovers(this, handled) /** * Create an observable of hover events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnHoverListener] to observe * touches. Only one observable can be used for a view at a time. */ public inline fun View.hoverEvents(): Observable<ViewHoverEvent> = RxView.hoverEvents(this) /** * Create an observable of hover events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnHoverListener] to observe * touches. Only one observable can be used for a view at a time. * * @param handled Function invoked with each value to determine the return value of the * underlying [View.OnHoverListener]. */ public inline fun View.hoverEvents(handled: Func1<in ViewHoverEvent, Boolean>): Observable<ViewHoverEvent> = RxView.hoverEvents(this, handled) /** * Create an observable which emits on `view` layout changes. The emitted value is * unspecified and should only be used as notification. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.layoutChanges(): Observable<Any> = RxView.layoutChanges(this) /** * Create an observable of layout-change events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.layoutChangeEvents(): Observable<ViewLayoutChangeEvent> = RxView.layoutChangeEvents(this) /** * Create an observable which emits on `view` long-click events. The emitted value is * unspecified and should only be used as notification. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnLongClickListener] to observe * long clicks. Only one observable can be used for a view at a time. */ public inline fun View.longClicks(): Observable<Any> = RxView.longClicks(this) /** * Create an observable which emits on `view` long-click events. The emitted value is * unspecified and should only be used as notification. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnLongClickListener] to observe * long clicks. Only one observable can be used for a view at a time. * * @param handled Function invoked each occurrence to determine the return value of the * underlying [View.OnLongClickListener]. */ public inline fun View.longClicks(handled: Func0<Boolean>): Observable<Any> = RxView.longClicks(this, handled) /** * Create an observable of long-clicks events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnLongClickListener] to observe * long clicks. Only one observable can be used for a view at a time. */ public inline fun View.longClickEvents(): Observable<ViewLongClickEvent> = RxView.longClickEvents(this) /** * Create an observable of long-click events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnLongClickListener] to observe * long clicks. Only one observable can be used for a view at a time. * * @param handled Function invoked with each value to determine the return value of the * underlying [View.OnLongClickListener]. */ public inline fun View.longClickEvents(handled: Func1<in ViewLongClickEvent, Boolean>): Observable<ViewLongClickEvent> = RxView.longClickEvents(this, handled) /** * Create an observable of scroll-change events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.scrollChangeEvents(): Observable<ViewScrollChangeEvent> = RxView.scrollChangeEvents(this) /** * Create an observable of integers representing a new system UI visibility for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses * [View.setOnSystemUiVisibilityChangeListener] to observe system UI visibility changes. * Only one observable can be used for a view at a time. */ public inline fun View.systemUiVisibilityChanges(): Observable<Int> = RxView.systemUiVisibilityChanges(this) /** * Create an observable of system UI visibility changes for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses * [View.setOnSystemUiVisibilityChangeListener] to observe system UI visibility changes. * Only one observable can be used for a view at a time. */ public inline fun View.systemUiVisibilityChangeEvents(): Observable<ViewSystemUiVisibilityChangeEvent> = RxView.systemUiVisibilityChangeEvents(this) /** * Create an observable of touch events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnTouchListener] to observe * touches. Only one observable can be used for a view at a time. */ public inline fun View.touches(): Observable<MotionEvent> = RxView.touches(this) /** * Create an observable of touch events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnTouchListener] to observe * touches. Only one observable can be used for a view at a time. * * @param handled Function invoked with each value to determine the return value of the * underlying [View.OnTouchListener]. */ public inline fun View.touches(handled: Func1<in MotionEvent, Boolean>): Observable<MotionEvent> = RxView.touches(this, handled) /** * Create an observable of touch events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnTouchListener] to observe * touches. Only one observable can be used for a view at a time. */ public inline fun View.touchEvents(): Observable<ViewTouchEvent> = RxView.touchEvents(this) /** * Create an observable of touch events for `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [View.setOnTouchListener] to observe * touches. Only one observable can be used for a view at a time. * * @param handled Function invoked with each value to determine the return value of the * underlying [View.OnTouchListener]. */ public inline fun View.touchEvents(handled: Func1<in ViewTouchEvent, Boolean>): Observable<ViewTouchEvent> = RxView.touchEvents(this, handled) /** * An action which sets the activated property of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.activated(): Action1<in Boolean> = RxView.activated(this) /** * An action which sets the clickable property of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.clickable(): Action1<in Boolean> = RxView.clickable(this) /** * An action which sets the enabled property of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.enabled(): Action1<in Boolean> = RxView.enabled(this) /** * An action which sets the pressed property of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.pressed(): Action1<in Boolean> = RxView.pressed(this) /** * An action which sets the selected property of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.selected(): Action1<in Boolean> = RxView.selected(this) /** * An action which sets the visibility property of `view`. `false` values use * `View.GONE`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ public inline fun View.visibility(): Action1<in Boolean> = RxView.visibility(this) /** * An action which sets the visibility property of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * @param visibilityWhenFalse Visibility to set on a `false` value (`View.INVISIBLE` * or `View.GONE`). */ public inline fun View.visibility(visibilityWhenFalse: Int): Action1<in Boolean> = RxView.visibility(this, visibilityWhenFalse)
apache-2.0
b4f521c0515f53e2e2b3f16d01b82ee3
37.929293
158
0.74241
4.245662
false
false
false
false
paronos/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadHolder.kt
3
2063
package eu.kanade.tachiyomi.ui.download import android.view.View import eu.kanade.tachiyomi.data.download.model.Download import eu.kanade.tachiyomi.ui.base.holder.BaseViewHolder import kotlinx.android.synthetic.main.download_item.view.* /** * Class used to hold the data of a download. * All the elements from the layout file "download_item" are available in this class. * * @param view the inflated view for this holder. * @constructor creates a new download holder. */ class DownloadHolder(private val view: View) : BaseViewHolder(view) { private lateinit var download: Download /** * Method called from [DownloadAdapter.onBindViewHolder]. It updates the data for this * holder with the given download. * * @param download the download to bind. */ fun onSetValues(download: Download) { this.download = download // Update the chapter name. view.chapter_title.text = download.chapter.name // Update the manga title view.manga_title.text = download.manga.title // Update the progress bar and the number of downloaded pages val pages = download.pages if (pages == null) { view.download_progress.progress = 0 view.download_progress.max = 1 view.download_progress_text.text = "" } else { view.download_progress.max = pages.size * 100 notifyProgress() notifyDownloadedPages() } } /** * Updates the progress bar of the download. */ fun notifyProgress() { val pages = download.pages ?: return if (view.download_progress.max == 1) { view.download_progress.max = pages.size * 100 } view.download_progress.progress = download.totalProgress } /** * Updates the text field of the number of downloaded pages. */ fun notifyDownloadedPages() { val pages = download.pages ?: return view.download_progress_text.text = "${download.downloadedImages}/${pages.size}" } }
apache-2.0
02553841778e7752555da2b797c44c1b
30.257576
90
0.647116
4.446121
false
false
false
false
alter-ego/unisannio-reboot
app/src/test/java/solutions/alterego/android/unisannio/scienze/ScienzeDetailParserTest.kt
1
846
package solutions.alterego.android.unisannio.scienze import org.jsoup.nodes.Document import org.junit.After import org.junit.Before import org.junit.Test import solutions.alterego.android.assertThat class ScienzeDetailParserTest { val url = "http://www.dstunisannio.it/index.php/scienze-biologiche-27/topic-27/767-registrazione-libretto-esame-ofa-di-chimica-scienze-biologiche-mercoledi-18-gennaio-2016"; val retriver = ScienzeDetailRetriver(url); val parser = ScienzeDetailParser(); lateinit var document : Document; @Before fun setUp(){ assertThat(url).isNotNull; document = retriver.document; assertThat(document).isNotNull; } @After fun tearDown(){ } @Test fun testParseDetail() { var list = parser.bodyelements; assertThat(list).isNotNull; } }
apache-2.0
368d5e8296b6204f6b9ac90c40753294
25.46875
177
0.712766
3.662338
false
true
false
false
john9x/jdbi
kotlin-sqlobject/src/main/kotlin/org/jdbi/v3/sqlobject/kotlin/KotlinDefaultMethodHandlerFactory.kt
2
2473
/* * 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.jdbi.v3.sqlobject.kotlin import org.jdbi.v3.core.kotlin.isKotlinClass import org.jdbi.v3.sqlobject.Handler import org.jdbi.v3.sqlobject.HandlerFactory import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.util.* class KotlinDefaultMethodHandlerFactory : HandlerFactory { private val implsClassCache = Collections.synchronizedMap(WeakHashMap<Class<*>, Map<MethodKey, Method>>()) override fun buildHandler(sqlObjectType: Class<*>, method: Method): Optional<Handler> { val implementation = getImplementation(sqlObjectType, method) ?: return Optional.empty() return Optional.of(Handler { t, a, _ -> try { implementation.invoke(null, *(listOf(t).plus(a).toTypedArray())) } catch (e: InvocationTargetException) { throw e.targetException } }) } fun getImplementation(type: Class<*>, method: Method): Method? { if (!type.isKotlinClass()) return null val implMethods: Map<MethodKey, Method> = implsClassCache.computeIfAbsent(type) { findImplClass(it)?.methods?.associateBy { MethodKey(it.name, it.parameters.map { p -> p.type }, it.returnType) } ?: emptyMap() }!! return findImplMethod(type, method, implMethods) } private fun findImplMethod(type: Class<*>, method: Method, implMethods: Map<MethodKey, Method>): Method? { //default method is generated as static method that takes target interface as first parameter val paramTypes = listOf(type) + method.parameters.map { it.type } return implMethods[MethodKey(method.name, paramTypes, method.returnType)] } private fun findImplClass(type: Class<*>): Class<*>? = type.classes.find { it.simpleName == "DefaultImpls" } } data class MethodKey(val name: String, val paramTypes: List<Class<*>>, val returnType: Class<*>)
apache-2.0
9f95b7a0c11644b98fd8593dedbd0b59
40.216667
138
0.700768
4.323427
false
false
false
false
msebire/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/inference/ListConstraint.kt
1
2217
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.processors.inference import com.intellij.psi.PsiClass import com.intellij.psi.PsiSubstitutor import com.intellij.psi.PsiType import com.intellij.psi.impl.source.resolve.graphInference.constraints.ConstraintFormula import com.intellij.psi.impl.source.resolve.graphInference.constraints.TypeCompatibilityConstraint import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap import org.jetbrains.plugins.groovy.lang.typing.EmptyListLiteralType import org.jetbrains.plugins.groovy.lang.typing.EmptyMapLiteralType class ListConstraint(private val leftType: PsiType?, private val literal: GrListOrMap) : GrConstraintFormula() { override fun reduce(session: GroovyInferenceSession, constraints: MutableList<ConstraintFormula>): Boolean { val type = literal.type if (type is EmptyListLiteralType || type is EmptyMapLiteralType) { // TODO consider adding separate interface for such cases val result = (type as? EmptyListLiteralType)?.resolveResult ?: (type as? EmptyMapLiteralType)?.resolveResult ?: return true val clazz = result.element val contextSubstitutor = result.contextSubstitutor require(contextSubstitutor === PsiSubstitutor.EMPTY) val typeParameters = clazz.typeParameters session.startNestedSession(typeParameters, contextSubstitutor, literal, result) { nested -> runNestedSession(nested, clazz) } return true } if (leftType != null) { constraints.add(TypeConstraint(leftType, type, literal)) } return true } private fun runNestedSession(nested: GroovyInferenceSession, clazz: PsiClass) { if (leftType != null) { val left = nested.substituteWithInferenceVariables(leftType) val classType = nested.substituteWithInferenceVariables(clazz.type()) nested.addConstraint(TypeCompatibilityConstraint(left, classType)) nested.repeatInferencePhases() } } override fun toString(): String = "${leftType?.presentableText} <- ${literal.text}" }
apache-2.0
1f70e58be04237cd2697d34f5b6a9358
46.170213
140
0.755074
4.788337
false
false
false
false
msebire/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/details/GithubPullRequestStatePanel.kt
1
7385
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui.details import com.intellij.icons.AllIcons import com.intellij.openapi.ui.VerticalFlowLayout import com.intellij.ui.components.JBOptionButton import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import icons.GithubIcons import org.jetbrains.plugins.github.api.data.GithubAuthenticatedUser import org.jetbrains.plugins.github.api.data.GithubIssueState import org.jetbrains.plugins.github.api.data.GithubPullRequestDetailed import org.jetbrains.plugins.github.api.data.GithubRepoDetailed import org.jetbrains.plugins.github.pullrequest.data.service.GithubPullRequestsStateService import org.jetbrains.plugins.github.util.GithubUtil.Delegates.equalVetoingObservable import java.awt.FlowLayout import java.awt.event.ActionEvent import javax.swing.AbstractAction import javax.swing.Action import javax.swing.JButton import javax.swing.JLabel internal class GithubPullRequestStatePanel(private val stateService: GithubPullRequestsStateService) : NonOpaquePanel(VerticalFlowLayout(0, 0)) { private val stateLabel = JLabel().apply { border = JBUI.Borders.empty(UIUtil.DEFAULT_VGAP, 0) } private val accessDeniedPanel = JLabel("Repository write access required to merge pull requests").apply { foreground = UIUtil.getContextHelpForeground() } private val closeAction = object : AbstractAction("Close") { override fun actionPerformed(e: ActionEvent?) { state?.run { stateService.close(number) } } } private val closeButton = JButton(closeAction) private val reopenAction = object : AbstractAction("Reopen") { override fun actionPerformed(e: ActionEvent?) { state?.run { stateService.reopen(number) } } } private val reopenButton = JButton(reopenAction) private val mergeAction = object : AbstractAction("Merge...") { override fun actionPerformed(e: ActionEvent?) { state?.run { stateService.merge(number) } } } private val rebaseMergeAction = object : AbstractAction("Rebase and Merge") { override fun actionPerformed(e: ActionEvent?) { state?.run { stateService.rebaseMerge(number) } } } private val squashMergeAction = object : AbstractAction("Squash and Merge...") { override fun actionPerformed(e: ActionEvent?) { state?.run { stateService.squashMerge(number) } } } private val mergeButton = JBOptionButton(null, null) private val buttonsPanel = NonOpaquePanel(FlowLayout(FlowLayout.LEADING, 0, 0)).apply { border = JBUI.Borders.empty(UIUtil.DEFAULT_VGAP, 0) add(mergeButton) add(closeButton) add(reopenButton) } var state: GithubPullRequestStatePanel.State? by equalVetoingObservable<GithubPullRequestStatePanel.State?>(null) { updateText(it) updateActions(it) } private fun updateText(state: GithubPullRequestStatePanel.State?) { if (state == null) { stateLabel.text = "" stateLabel.icon = null accessDeniedPanel.isVisible = false } else { if (state.state == GithubIssueState.closed) { if (state.merged) { stateLabel.icon = GithubIcons.PullRequestClosed stateLabel.text = "Pull request is merged" } else { stateLabel.icon = GithubIcons.PullRequestClosed stateLabel.text = "Pull request is closed" } accessDeniedPanel.isVisible = false } else { val mergeable = state.mergeable if (mergeable == null) { stateLabel.icon = AllIcons.RunConfigurations.TestNotRan stateLabel.text = "Checking for ability to merge automatically..." } else { if (mergeable) { stateLabel.icon = AllIcons.RunConfigurations.TestPassed stateLabel.text = "Branch has no conflicts with base branch" } else { stateLabel.icon = AllIcons.RunConfigurations.TestFailed stateLabel.text = "Branch has conflicts that must be resolved" } } accessDeniedPanel.isVisible = !state.editAllowed } } } private fun updateActions(state: GithubPullRequestStatePanel.State?) { if (state == null) { reopenAction.isEnabled = false reopenButton.isVisible = false closeAction.isEnabled = false closeButton.isVisible = false mergeAction.isEnabled = false rebaseMergeAction.isEnabled = false squashMergeAction.isEnabled = false mergeButton.action = null mergeButton.options = emptyArray() mergeButton.isVisible = false } else { val busy = stateService.isBusy(state.number) reopenButton.isVisible = state.editAllowed && state.state == GithubIssueState.closed && !state.merged reopenAction.isEnabled = reopenButton.isVisible && !busy closeButton.isVisible = (state.editAllowed || state.currentUserIsAuthor) && state.state == GithubIssueState.open closeAction.isEnabled = closeButton.isVisible && !busy mergeButton.isVisible = state.editAllowed && state.state == GithubIssueState.open && !state.merged mergeAction.isEnabled = mergeButton.isVisible && (state.mergeable ?: false) && !busy && !state.mergeForbidden rebaseMergeAction.isEnabled = mergeButton.isVisible && (state.rebaseable ?: false) && !busy && !state.mergeForbidden squashMergeAction.isEnabled = mergeButton.isVisible && (state.mergeable ?: false) && !busy && !state.mergeForbidden mergeButton.optionTooltipText = if (state.mergeForbidden) "Merge actions are disabled for this project" else null val allowedActions = mutableListOf<Action>() if (state.mergeAllowed) allowedActions.add(mergeAction) if (state.rebaseMergeAllowed) allowedActions.add(rebaseMergeAction) if (state.squashMergeAllowed) allowedActions.add(squashMergeAction) val action = allowedActions.firstOrNull() val actions = if (allowedActions.size > 1) Array(allowedActions.size - 1) { allowedActions[it + 1] } else emptyArray() mergeButton.action = action mergeButton.options = actions } } init { isOpaque = false add(stateLabel) add(accessDeniedPanel) add(buttonsPanel) } data class State(val number: Long, val state: GithubIssueState, val merged: Boolean, val mergeable: Boolean?, val rebaseable: Boolean?, val editAllowed: Boolean, val currentUserIsAuthor: Boolean, val busy: Boolean, val mergeAllowed: Boolean, val rebaseMergeAllowed: Boolean, val squashMergeAllowed: Boolean, val mergeForbidden: Boolean) { companion object { fun create(user: GithubAuthenticatedUser, repo: GithubRepoDetailed, details: GithubPullRequestDetailed, busy: Boolean, mergeForbidden: Boolean) = details.let { State(it.number, it.state, it.merged, it.mergeable, it.rebaseable, repo.permissions.isAdmin || repo.permissions.isPush, it.user == user, busy, repo.allowMergeCommit, repo.allowRebaseMerge, repo.allowSquashMerge, mergeForbidden) } } } }
apache-2.0
75bc71f4971df75baf9e897a7d162c4a
38.079365
140
0.698849
4.89397
false
false
false
false
ankidroid/Anki-Android
lint-rules/src/test/java/com/ichi2/anki/lint/rules/NonPositionalFormatSubstitutionsTest.kt
1
6528
/* * Copyright (c) 2022 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki.lint.rules import com.android.tools.lint.checks.infrastructure.TestFiles import com.android.tools.lint.checks.infrastructure.TestLintTask import org.intellij.lang.annotations.Language import org.junit.Test /** Test for [NonPositionalFormatSubstitutions] */ class NonPositionalFormatSubstitutionsTest { /** One substitution is unambiguous */ @Language("XML") private val valid = """<resources> <string name="hello">%s</string> </resources>""" /** Easiest test case: Two exact duplicates in the same file */ @Language("XML") private val invalid = """<resources> <string name="hello">%s %s</string> </resources>""" @Language("XML") private val unambiguous = "<resources><string name=\"hello\">%1\$s %2\$s</string></resources>" /** %% is an encoded percentage */ @Language("XML") private val encoded = "<resources><string name=\"hello\">%%</string></resources>" @Language("XML") private val pluralPass = """ <resources> <plurals name="import_complete_message"> <item quantity="one">Cards imported: %1${'$'}d</item> <item quantity="other">Files imported :%1${'$'}d" Total cards imported: %2${'$'}d</item> </plurals> </resources> """.trimIndent() @Language("XML") private val pluralPartial = """ <resources> <plurals name="import_complete_message"> <item quantity="one">Cards imported: %d</item> <item quantity="other">Files imported :%1${'$'}d" Total cards imported: %2${'$'}d</item> </plurals> </resources> """.trimIndent() @Language("XML") private val pluralFail = """ <resources> <plurals name="import_complete_message"> <item quantity="one">Cards imported: %d</item> <item quantity="other">Files imported: %d\nTotal cards imported: %d</item> </plurals> </resources> """.trimIndent() @Language("XML") private val pluralMultiple = """ <plurals name="reschedule_card_dialog_interval"> <item quantity="one">Current interval: %d day</item> <item quantity="few">Keisti Kortelių mokymosi dieną</item> <item quantity="many">Current interval: %d days</item> <item quantity="other">Current interval: %d days</item> </plurals> """.trimIndent() @Language("XML") private val pluralMultipleTwo = """ <plurals name="in_minutes"> <item quantity="one">%1${'$'}d मिनट</item> <item quantity="other">मिनट</item> </plurals> """.trimIndent() @Test fun errors_if_ambiguous() { TestLintTask.lint() .allowMissingSdk() .allowCompilationErrors() .files(TestFiles.xml("res/values/string.xml", invalid)) .issues(NonPositionalFormatSubstitutions.ISSUE) .run() .expectErrorCount(1) } @Test fun no_errors_if_valid() { TestLintTask.lint() .allowMissingSdk() .allowCompilationErrors() .files(TestFiles.xml("res/values/string.xml", valid)) .issues(NonPositionalFormatSubstitutions.ISSUE) .run() .expectClean() } @Test fun no_errors_if_unambiguous() { TestLintTask.lint() .allowMissingSdk() .allowCompilationErrors() .files(TestFiles.xml("res/values/string.xml", unambiguous)) .issues(NonPositionalFormatSubstitutions.ISSUE) .run() .expectClean() } @Test fun no_errors_if_encoded() { TestLintTask.lint() .allowMissingSdk() .allowCompilationErrors() .files(TestFiles.xml("res/values/string.xml", encoded)) .issues(NonPositionalFormatSubstitutions.ISSUE) .run() .expectClean() } @Test fun valid_plural_passed() { TestLintTask.lint() .allowMissingSdk() .allowCompilationErrors() .files(TestFiles.xml("res/values/string.xml", pluralPass)) .issues(NonPositionalFormatSubstitutions.ISSUE) .run() .expectClean() } @Test fun plural_partial_flags() { // If one plural has $1, $2 etc... the other should as well TestLintTask.lint() .allowMissingSdk() .allowCompilationErrors() .files(TestFiles.xml("res/values/string.xml", pluralPartial)) .issues(NonPositionalFormatSubstitutions.ISSUE) .run() .expectErrorCount(1) } @Test fun errors_on_plural_issue() { TestLintTask.lint() .allowMissingSdk() .allowCompilationErrors() .files(TestFiles.xml("res/values/string.xml", pluralFail)) .issues(NonPositionalFormatSubstitutions.ISSUE) .run() .expectErrorCount(1) } @Test fun plural_integration_test() { TestLintTask.lint() .allowMissingSdk() .allowCompilationErrors() .files(TestFiles.xml("res/values/string.xml", pluralMultiple)) .issues(NonPositionalFormatSubstitutions.ISSUE) .run() .expectClean() } @Test fun plural_integration_test_positional_and_nothing() { TestLintTask.lint() .allowMissingSdk() .allowCompilationErrors() .files(TestFiles.xml("res/values/string.xml", pluralMultipleTwo)) .issues(NonPositionalFormatSubstitutions.ISSUE) .run() .expectClean() } }
gpl-3.0
aaf11502f3076e2c56ea315469230897
32.73057
104
0.589094
4.581281
false
true
false
false
openMF/self-service-app
app/src/main/java/org/mifos/mobile/models/accounts/loan/Summary.kt
1
1742
package org.mifos.mobile.models.accounts.loan import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class Summary( @SerializedName("principalDisbursed") var principalDisbursed: Double = 0.toDouble(), @SerializedName("principalPaid") var principalPaid: Double = 0.toDouble(), @SerializedName("interestCharged") var interestCharged: Double = 0.toDouble(), @SerializedName("interestPaid") var interestPaid: Double = 0.toDouble(), @SerializedName("feeChargesCharged") var feeChargesCharged: Double = 0.toDouble(), @SerializedName("penaltyChargesCharged") var penaltyChargesCharged: Double = 0.toDouble(), @SerializedName("penaltyChargesWaived") var penaltyChargesWaived: Double = 0.toDouble(), @SerializedName("totalExpectedRepayment") var totalExpectedRepayment: Double = 0.toDouble(), @SerializedName("interestWaived") var interestWaived: Double = 0.toDouble(), @SerializedName("totalRepayment") var totalRepayment: Double = 0.toDouble(), @SerializedName("feeChargesWaived") var feeChargesWaived: Double = 0.toDouble(), @SerializedName("totalOutstanding") var totalOutstanding: Double = 0.toDouble(), @SerializedName("overdueSinceDate") private var overdueSinceDate: List<Int>? = null, @SerializedName("currency") var currency: Currency? = null ) : Parcelable { fun getOverdueSinceDate(): List<Int>? { if (overdueSinceDate==null) return null else return overdueSinceDate } }
mpl-2.0
4ff3c04654ae275131fb6ca2a42f9e29
28.542373
58
0.664179
5.049275
false
false
false
false
ratabb/Hishoot2i
app/src/main/java/org/illegaller/ratabb/hishoot2i/ui/common/behavior/FabSnackBarAwareBehavior.kt
1
1927
package org.illegaller.ratabb.hishoot2i.ui.common.behavior import android.content.Context import android.util.AttributeSet import android.view.View import android.view.ViewGroup.MarginLayoutParams import androidx.annotation.Keep import androidx.coordinatorlayout.widget.CoordinatorLayout import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar /** * We use this, because [Snackbar.setAnchorView] buggy **/ @Keep open class FabSnackBarAwareBehavior @JvmOverloads @Keep constructor( context: Context? = null, attrs: AttributeSet? = null ) : CoordinatorLayout.Behavior<FloatingActionButton>(context, attrs) { private var isSnackBarAppear: Boolean = false override fun layoutDependsOn( parent: CoordinatorLayout, child: FloatingActionButton, dependency: View ): Boolean = dependency is Snackbar.SnackbarLayout override fun onDependentViewChanged( parent: CoordinatorLayout, child: FloatingActionButton, dependency: View ): Boolean { when (dependency) { is Snackbar.SnackbarLayout -> { if (isSnackBarAppear) return true isSnackBarAppear = true dependency.apply { val translateY = (child.height - child.translationY).toInt() (layoutParams as MarginLayoutParams).bottomMargin += translateY requestLayout() } return true } else -> return false } } override fun onDependentViewRemoved( parent: CoordinatorLayout, child: FloatingActionButton, dependency: View ) { when (dependency) { is Snackbar.SnackbarLayout -> isSnackBarAppear = false else -> super.onDependentViewRemoved(parent, child, dependency) } } }
apache-2.0
bfb6bb45c1fce1d44dcff0a3528e914c
33.410714
83
0.667359
5.412921
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/attribute/AttributeCalculator.kt
1
1583
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.attribute import org.lanternpowered.api.attribute.AttributeModifier object AttributeCalculator { fun calculateValue(base: Double, modifiers: Collection<AttributeModifier>): Double { @Suppress("NAME_SHADOWING") val modifiers: List<AttributeModifier> = modifiers .sortedBy { it.operation as LanternAttributeOperation } // The last operation var lastOperation: LanternAttributeOperation? = null // The new value var value = base var value0 = 0.0 // Add the incrementations of all the modifiers for (modifier in modifiers) { val operation = modifier.operation as LanternAttributeOperation if (lastOperation == null || operation == lastOperation) { val value1 = operation.getIncrementation(base, modifier.value, value) if (operation.changeValueImmediately) { value += value1 } else { value0 += value1 } } else { lastOperation = operation value += value0 value0 = 0.0 } } value += value0 return value } }
mit
1a0a1c80f26d78b76211b94bc5f9053f
31.979167
88
0.603917
4.885802
false
false
false
false
ekager/focus-android
app/src/main/java/org/mozilla/focus/fragment/InfoFragment.kt
1
4171
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import mozilla.components.browser.session.Session import mozilla.components.concept.engine.HitResult import org.mozilla.focus.R import org.mozilla.focus.web.Download import org.mozilla.focus.web.IWebView class InfoFragment : WebFragment() { private var progressView: ProgressBar? = null private var webView: View? = null override val session: Session? get() = null override val initialUrl: String? get() = arguments?.getString(ARGUMENT_URL) override fun inflateLayout( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val view = inflater.inflate(R.layout.fragment_info, container, false) progressView = view.findViewById(R.id.progress) webView = view.findViewById(R.id.webview) val url = initialUrl if (url != null && !(url.startsWith("http://") || url.startsWith("https://"))) { // Hide webview until content has loaded, if we're loading built in about/rights/etc // pages: this avoid a white flash (on slower devices) between the screen appearing, // and the about/right/etc content appearing. We don't do this for SUMO and other // external pages, because they are both light-coloured, and significantly slower loading. webView?.visibility = View.INVISIBLE } applyLocale() return view } override fun onCreateViewCalled() {} @Suppress("ComplexMethod") override fun createCallback(): IWebView.Callback { return object : IWebView.Callback { override fun onPageStarted(url: String) { progressView?.announceForAccessibility(getString(R.string.accessibility_announcement_loading)) progressView?.visibility = View.VISIBLE } override fun onPageFinished(isSecure: Boolean) { progressView?.announceForAccessibility(getString(R.string.accessibility_announcement_loading_finished)) progressView?.visibility = View.INVISIBLE if (webView?.visibility != View.VISIBLE) { webView?.visibility = View.VISIBLE } } override fun onSecurityChanged( isSecure: Boolean, host: String?, organization: String? ) { } override fun onProgress(progress: Int) { progressView?.progress = progress } override fun onDownloadStart(download: Download) {} override fun onLongPress(hitResult: HitResult) {} override fun onURLChanged(url: String) {} override fun onTitleChanged(title: String) {} override fun onRequest(isTriggeredByUserGesture: Boolean) {} override fun onEnterFullScreen(callback: IWebView.FullscreenCallback, view: View?) {} override fun onExitFullScreen() {} override fun countBlockedTracker() {} override fun resetBlockedTrackers() {} override fun onBlockingStateChanged(isBlockingEnabled: Boolean) {} override fun onHttpAuthRequest( callback: IWebView.HttpAuthCallback, host: String, realm: String ) {} override fun onRequestDesktopStateChanged(shouldRequestDesktop: Boolean) {} } } companion object { private const val ARGUMENT_URL = "url" fun create(url: String): InfoFragment { val arguments = Bundle() arguments.putString(ARGUMENT_URL, url) val fragment = InfoFragment() fragment.arguments = arguments return fragment } } }
mpl-2.0
40a434b0b10dc0276e6d8e96699533c3
34.347458
119
0.630784
5.149383
false
false
false
false
kazhida/surroundcalc
src/com/abplus/surroundcalc/models/Region.kt
1
2415
package com.abplus.surroundcalc.models import android.graphics.PointF import android.graphics.RectF import com.abplus.surroundcalc.models.Stroke.Side import android.graphics.Matrix import android.graphics.Path import java.util.ArrayList /** * Created by kazhida on 2014/01/02. */ class Region(stroke: Stroke) : Pickable() { public val path: Path = {(stroke: Stroke): Path -> val path = Path(); for (segment in stroke) { if (segment == stroke) { path.moveTo(segment.x, segment.y) } else { path.lineTo(segment.x, segment.y) } } path.close() path }(stroke) private val stroke = stroke public val labels: MutableList<ValueLabel> = ArrayList<ValueLabel>() private fun insideBounds(p: PointF): Boolean { val bounds = RectF() path.computeBounds(bounds, true) return bounds.left <= p.x && p.x <= bounds.right && bounds.top <= p.y && p.y <= bounds.bottom; } override protected fun isInside(p: PointF): Boolean { if (insideBounds(p)) { // var side = Side.UNKNOWN // for (segment in stroke) { // if (side == Side.UNKNOWN) { // side = segment.whichSide(p) // } else { // val side2 = segment.whichSide(p) // if (side2 != Side.UNKNOWN && side2 != side) return false // } // } return true } else { return false } } override public fun moveTo(p: PointF) : Unit { val matrix = Matrix(); matrix.setTranslate(p.x - pickedPoint.x, p.y - pickedPoint.y) path.transform(matrix) pickedPoint.x = p.x pickedPoint.y = p.y } public fun bind(label: ValueLabel): Region { if (! labels.contains(label) && isInside(label.centerPoint)) { labels.add(label) } return this } public fun bind(labels: List<ValueLabel>): Region { for (label in labels) bind(label) return this } public fun unbind(label: ValueLabel): Region { labels.remove(label) return this } public fun unbind() : Region { labels.clear() return this } }
bsd-2-clause
ca54a5d1a70f7ddc1a25fda6e9103272
27.761905
102
0.526294
4.259259
false
false
false
false
PKRoma/github-android
app/src/main/java/com/github/pockethub/android/ui/commit/CommitListFragment.kt
5
7684
/* * Copyright (c) 2015 PocketHub * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pockethub.android.ui.commit import android.app.Activity import android.app.Activity.RESULT_OK import android.content.Context import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.github.pockethub.android.Intents.EXTRA_REPOSITORY import com.github.pockethub.android.ui.helpers.ItemListHandler import com.github.pockethub.android.ui.helpers.PagedListFetcher import com.github.pockethub.android.ui.helpers.PagedScrollListener import com.github.pockethub.android.R import com.github.pockethub.android.RequestCodes.COMMIT_VIEW import com.github.pockethub.android.RequestCodes.REF_UPDATE import com.github.pockethub.android.core.commit.CommitStore import com.github.pockethub.android.core.ref.RefUtils import com.github.pockethub.android.ui.base.BaseActivity import com.github.pockethub.android.ui.DialogResultListener import com.github.pockethub.android.ui.base.BaseFragment import com.github.pockethub.android.ui.item.commit.CommitItem import com.github.pockethub.android.ui.ref.RefDialog import com.github.pockethub.android.ui.ref.RefDialogFragment import com.github.pockethub.android.util.AvatarLoader import com.github.pockethub.android.util.ToastUtils import com.meisolsson.githubsdk.model.Commit import com.meisolsson.githubsdk.model.Page import com.meisolsson.githubsdk.model.Repository import com.meisolsson.githubsdk.model.git.GitReference import com.meisolsson.githubsdk.service.repositories.RepositoryCommitService import com.meisolsson.githubsdk.service.repositories.RepositoryService import com.xwray.groupie.Item import com.xwray.groupie.OnItemClickListener import io.reactivex.Single import kotlinx.android.synthetic.main.fragment_commit_list.view.* import kotlinx.android.synthetic.main.ref_footer.view.* import retrofit2.Response import javax.inject.Inject /** * Fragment to display a list of repo commits */ class CommitListFragment : BaseFragment(), DialogResultListener { @Inject protected lateinit var service: RepositoryCommitService @Inject protected lateinit var repoService: RepositoryService /** * Avatar loader */ @Inject protected lateinit var avatars: AvatarLoader @Inject protected lateinit var store: CommitStore protected lateinit var pagedListFetcher: PagedListFetcher<Commit> protected lateinit var itemListHandler: ItemListHandler private var repo: Repository? = null private var dialog: RefDialog? = null private var ref: String? = null protected val errorMessage: Int get() = R.string.error_commits_load override fun onAttach(context: Context) { super.onAttach(context) val activity = context as Activity? repo = activity!!.intent.getParcelableExtra(EXTRA_REPOSITORY) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_commit_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) itemListHandler = ItemListHandler( view.list, view.empty, lifecycle, activity, OnItemClickListener(this::onItemClick) ) pagedListFetcher = PagedListFetcher( view.swipe_item, lifecycle, itemListHandler, { t -> ToastUtils.show(activity, errorMessage) }, this::loadData, this::createItem ) pagedListFetcher.onPageLoaded = this::onPageLoaded view.list.addOnScrollListener( PagedScrollListener(itemListHandler.mainSection, pagedListFetcher) ) itemListHandler.setEmptyText(R.string.no_commits) view.rl_branch.setOnClickListener { switchRefs()} view.rl_branch.visibility = View.VISIBLE } private fun loadData(page: Int): Single<Response<Page<Commit>>> { val refSingle: Single<String> if (TextUtils.isEmpty(ref)) { val defaultBranch = repo!!.defaultBranch() refSingle = if (TextUtils.isEmpty(defaultBranch)) { repoService.getRepository(repo!!.owner()!!.login(), repo!!.name()) .map { it.body()!!.defaultBranch() } .map { return@map if (TextUtils.isEmpty(it)) { "master" } else { it } } } else { Single.just(defaultBranch!!) } } else { refSingle = Single.just(ref!!) } return refSingle .map { ref -> [email protected] = ref ref } .flatMap { branch -> service.getCommits(repo!!.owner()!!.login(), repo!!.name(), branch, page.toLong()) } } protected fun createItem(dataItem: Commit): Item<*> { return CommitItem(avatars, dataItem) } protected fun onPageLoaded(items: MutableList<Item<*>>): MutableList<Item<*>> { if (ref != null) { updateRefLabel() } return items } fun onItemClick(item: Item<*>, view: View) { if (item is CommitItem) { val position = itemListHandler.getItemPosition(item) startActivityForResult( CommitViewActivity.createIntent(repo!!, position, itemListHandler.items), COMMIT_VIEW ) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == COMMIT_VIEW) { itemListHandler.mainSection.notifyChanged() return } super.onActivityResult(requestCode, resultCode, data) } override fun onDialogResult(requestCode: Int, resultCode: Int, arguments: Bundle) { if (RESULT_OK != resultCode) { return } when (requestCode) { REF_UPDATE -> setRef(RefDialogFragment.getSelected(arguments)) } } private fun updateRefLabel() { view!!.tv_branch.text = RefUtils.getName(ref) if (RefUtils.isTag(ref)) { view!!.tv_branch_icon.setText(R.string.icon_tag) } else { view!!.tv_branch_icon.setText(R.string.icon_fork) } } private fun setRef(ref: GitReference) { this.ref = ref.ref() updateRefLabel() pagedListFetcher.refresh() } fun switchRefs() { if (ref == null) { return } if (dialog == null) { dialog = RefDialog(activity as BaseActivity?, REF_UPDATE, repo) } val reference = GitReference.builder() .ref(ref) .build() dialog!!.show(reference) } }
apache-2.0
dd721560b76c225ff0a3903adcd79369
31.559322
98
0.653826
4.679659
false
false
false
false
jrenner/kotlin-algorithms-ds
src/test/QueueTest.kt
1
1732
package test import datastructs.fundamental.queue.Queue import datastructs.fundamental.queue.ArrayQueue import java.util.ArrayList import datastructs.fundamental.queue.LinkedQueue fun createQueueTests() { val basicQueueTest = {(q : Queue<Int>) -> // basics assert(q.isEmpty()) assert(q.size() == 0) q.push(1) assert(!q.isEmpty()) assert(q.size() == 1) assert(q.pop() == 1) assert(q.isEmpty()) assert(q.size() == 0) q.push(1) assert(q.size() == 1) assert(!q.isEmpty()) // clearing q.clear() assert(q.isEmpty()) assert(q.size() == 0) // FIFO q.push(1) q.push(3) q.push(5) assert(q.pop() == 1) q.push(2) q.push(4) assert(q.pop() == 3) q.push(10) q.push(20) assert(q.pop() == 5) assert(q.pop() == 2) assert(q.pop() == 4) assert(q.pop() == 10) assert(q.pop() == 20) assert(q.isEmpty()) // iteration q.clear() val max = 10 for (n in 1..max) { q.push(n) } var count = 0 while (!q.isEmpty()) { q.pop() count++ assert(count <= max, "iteration failed to stay <= max: count: $count") } assert(count == max, "iteration failed to match max, count: $count, max $max") } BenchmarkTest("ArrayQueue", { () -> val q = ArrayQueue<Int>() basicQueueTest(q) }, BenchmarkTest.defaultLoopCount) BenchmarkTest("LinkedQueue", { () -> val q = LinkedQueue<Int>() basicQueueTest(q) }, BenchmarkTest.defaultLoopCount) }
apache-2.0
48999b00014429ae914d5e00904710b6
23.055556
86
0.497113
3.631027
false
true
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/services/RulesService.kt
1
4337
package com.pr0gramm.app.services import android.widget.TextView import com.pr0gramm.app.R import com.pr0gramm.app.util.AndroidUtility import com.pr0gramm.app.util.ignoreAllExceptions import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runInterruptible import okhttp3.OkHttpClient import okhttp3.Request /** */ class RulesService(private val okHttpClient: OkHttpClient) { private var cachedText: String = defaultRulesText suspend fun displayInto(targetView: TextView) { displayInto(targetView, cachedText) // now try to fetch the updated text ignoreAllExceptions { val text = runInterruptible(Dispatchers.IO) { val url = "https://pr0gramm.com/media/templates/rules.html" val request = Request.Builder().url(url).build() val response = okHttpClient.newCall(request).execute() if (response.isSuccessful) response.body?.string() else null } if (text != null) { // display the new text again on success displayInto(targetView, text) } } } private fun displayInto(rulesView: TextView, rules: String) { val list = "<pre>(.+?)</pre>".toRegex(RegexOption.DOT_MATCHES_ALL).findAll(rules).mapIndexed { _, match -> var id = ""; var rule = match.groupValues[1].replace("<b>(.+?)</b>".toRegex(RegexOption.IGNORE_CASE)) { id = it.groupValues[1]; ""} rule = rule.replace("<[^>]+>".toRegex(), "").trim { it <= ' ' } "#$id $rule" } val resources = rulesView.context.resources val offset = resources.getDimensionPixelSize(R.dimen.bullet_list_leading_margin) rulesView.text = AndroidUtility.makeBulletList(offset, list.toList()) } } private const val defaultRulesText = """ <pre><b>1</b> nsfp/nsfw/nsfl Inhalte müssen vor dem Upload entsprechend markiert werden.</pre> <pre><b>2</b> <i>Minderjährige:</i></pre> <pre><b>2.1</b> Keine suggestive oder nackte Darstellung von Minderjährigen.</pre> <pre><b>2.2</b> Keine rohe Gewalt an Minderjährigen.</pre> <pre><b>3</b> <i>Tiere:</i></pre> <pre><b>3.1</b> Keine Tierquälerei.</pre> <pre><b>3.2</b> Keine Zoophilie oder Fetischvideos mit Tieren.</pre> <pre><b>4</b> <i>Rassismus und Hetze:</i></pre> <pre><b>4.1</b> Kein stumpfer Rassismus, kein rechtes Gedankengut.</pre> <pre><b>4.2</b> Keine Hetze, egal ob politisch, rassistisch oder religiös motiviert.</pre> <pre><b>4.3</b> Keine Aufrufe zu Gewalt.</pre> <pre><b>4.4</b> Keine Nazi-Nostalgie/Nazi-Nostalgia</pre> <pre><b>4.5</b> Kein Agenda Pushing oder Verbreiten von Propaganda.</pre> <pre><b>5</b> Keine Werbung</pre> <pre><b>6</b> Keine Informationen oder Bilder/Videos von Privatpersonen.</pre> <pre><b>7</b> <i>Contentqualität:</i></pre> <pre><b>7.1</b> Ein Mindestmaß an Bild/Videoqualität wird erwartet.</pre> <pre><b>7.2</b> Reposts gilt es zu vermeiden.</pre> <pre><b>7.3</b> Keine Müllposts/Privatmüll.</pre> <pre><b>7.4</b> Keine langweiligen Raids.</pre> <pre><b>8</b> Keine Bilder/Videos mit ähnlichem Inhalt kurz hintereinander posten.</pre> <pre><b>9</b> <i>Vandalismus:</i></pre> <pre><b>9.1</b> Kein Tag-Vandalismus.</pre> <pre><b>9.2</b> Kein Spam/Kommentarvandalismus.</pre> <pre><b>9.3</b> Kein Downvote-Spam.</pre> <pre><b>9.4</b> Keine Vote-Manipulation.</pre> <pre><b>9.5</b> Kein Downvoten sinnvoller Tags.</pre> <pre><b>10</b> Keine frühen Spoiler.</pre> <pre><b>11</b> Pro Benutzer ist nur ein Account erlaubt.</pre> <pre><b>12</b> Keine Warez, Links zu illegalen Angeboten, gestohlene Logins zu Pay Sites o.Ä.</pre> <pre><b>13</b> Keine übermäßigen Beleidigungen oder Hetzen gegen andere Benutzer, die Community oder die Moderation.</pre> <pre><b>14</b> Keine “Screamer” oder sonstige Ton-Videos mit der Absicht, Benutzer zu erschrecken oder zu trollen.</pre> <pre><b>15</b> <i>Musikuploads:</i></pre> <pre><b>15.1</b> Keine reinen Musikuploads.</pre> <pre><b>15.2</b> Keine Musikvideos.</pre> <pre><b>16</b> <i>Störungen der Moderation:</i></pre> <pre><b>16.1</b> Kein unnötiges Markieren von Moderatoren oder Nerven von Community-Helfern.</pre> <pre><b>16.2</b> Kein Missbrauch der Melden-Funktion.</pre> """
mit
bd56a39c583544d8751672e9c6cc592a
46.944444
130
0.657163
2.876
false
false
false
false
Mauin/detekt
detekt-cli/src/main/kotlin/io/gitlab/arturbosch/detekt/cli/out/XmlEscape.kt
2
14690
/* * ============================================================================= * * Copyright (c) 2014, The UNBESCAPE team (http://www.unbescape.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ @file:Suppress("ALL") package io.gitlab.arturbosch.detekt.cli.out import java.util.ArrayList import java.util.Arrays import java.util.Collections /** * Adapted from Unbescape - https://github.com/unbescape/unbescape/ * * Utility class for performing XML escape/unescape operations. * * @author Daniel Fernndez * @since 1.0.0 */ object XmlEscape { private val REFERENCE_HEXA_PREFIX = "&#x".toCharArray() private val REFERENCE_SUFFIX = ';' /** * Perform an XML 1.0 level 2 (markup-significant and all non-ASCII chars) **escape** operation * on a <tt>String</tt> input. * * *Level 2* means this method will escape: * * The five markup-significant characters: <tt>&lt;</tt>, <tt>&gt;</tt>, <tt>&amp;</tt>, * <tt>&quot;</tt> and <tt>&#39;</tt> * * All non ASCII characters. * * This escape will be performed by replacing those chars by the corresponding XML Character Entity References * (e.g. <tt>'&amp;lt;'</tt>) when such CER exists for the replaced character, and replacing by a hexadecimal * character reference (e.g. <tt>'&amp;#x2430;'</tt>) when there there is no CER for the replaced character. * * This method is **thread-safe**. * @param text the <tt>String</tt> to be escaped. * * * @return The escaped result <tt>String</tt>. As a memory-performance improvement, will return the exact * * same object as the <tt>text</tt> input argument if no escaping modifications were required (and * * no additional <tt>String</tt> objects will be created during processing). Will * * return <tt>null</tt> if input is <tt>null</tt>. */ fun escapeXml(text: String): String { val symbols = Xml10EscapeSymbolsInitializer.initializeXml10() val level = 2 var strBuilder: StringBuilder? = null val offset = 0 val max = text.length var readOffset = offset var i = offset while (i < max) { val codepoint = Character.codePointAt(text, i) val codepointValid = symbols.CODEPOINT_VALIDATOR.isValid(codepoint) /* * Shortcut: most characters will be ASCII/Alphanumeric, and we won't need to do anything at * all for them */ if (codepoint <= Xml10EscapeSymbolsInitializer.XmlEscapeSymbols.LEVELS_LEN - 2 && level < symbols.ESCAPE_LEVELS[codepoint] && codepointValid) { i++ continue } /* * Shortcut: we might not want to escape non-ASCII chars at all either. */ if (codepoint > Xml10EscapeSymbolsInitializer.XmlEscapeSymbols.LEVELS_LEN - 2 && level < symbols.ESCAPE_LEVELS[Xml10EscapeSymbolsInitializer.XmlEscapeSymbols.LEVELS_LEN - 1] && codepointValid) { if (Character.charCount(codepoint) > 1) { // This is to compensate that we are actually escaping two char[] positions with a single codepoint. i++ } i++ continue } /* * At this point we know for sure we will need some kind of escape, so we * can increase the offset and initialize the string builder if needed, along with * copying to it all the contents pending up to this point. */ if (strBuilder == null) { strBuilder = StringBuilder(max + 20) } if (i - readOffset > 0) { strBuilder.append(text, readOffset, i) } if (Character.charCount(codepoint) > 1) { // This is to compensate that we are actually reading two char[] positions with a single codepoint. i++ } readOffset = i + 1 /* * If the char is invalid, there is nothing to write, simply skip it (which we already did by * incrementing the readOffset. */ if (!codepointValid) { i++ continue } /* * ----------------------------------------------------------------------------------------- * * Perform the real escape, attending the different combinations of NCR, DCR and HCR needs. * * ----------------------------------------------------------------------------------------- */ // We will try to use a CER val codepointIndex = Arrays.binarySearch(symbols.SORTED_CODEPOINTS, codepoint) if (codepointIndex >= 0) { // CER found! just write it and go for the next char strBuilder.append(symbols.SORTED_CERS_BY_CODEPOINT[codepointIndex]) i++ continue } /* * No NCR-escape was possible (or allowed), so we need decimal/hexa escape. */ strBuilder.append(REFERENCE_HEXA_PREFIX) strBuilder.append(Integer.toHexString(codepoint)) strBuilder.append(REFERENCE_SUFFIX) i++ } /* * ----------------------------------------------------------------------------------------------- * Final cleaning: return the original String object if no escape was actually needed. Otherwise * append the remaining unescaped text to the string builder and return. * ----------------------------------------------------------------------------------------------- */ if (strBuilder == null) { return text } if (max - readOffset > 0) { strBuilder.append(text, readOffset, max) } return strBuilder.toString() } } /** * This class initializes the XML10_SYMBOLS structure. */ @Suppress("ALL") private object Xml10EscapeSymbolsInitializer { internal class XmlCodepointValidator { /* * XML 1.0 does not allow many control characters, nor unpaired surrogate chars * (characters used for composing two-char codepoints, but appearing on their own). */ fun isValid(codepoint: Int): Boolean { if (codepoint < 0x20) { return codepoint == 0x9 || codepoint == 0xA || codepoint == 0xD } if (codepoint <= 0xD7FF) { // U+D800 - U+DFFF are reserved for low + high surrogates return true } if (codepoint < 0xE000) { return false } if (codepoint <= 0xFFFD) { // U+FFFE and U+FFFF are non-characters, and therefore not valid return true } if (codepoint < 0x10000) { return false } return true } } fun initializeXml10(): XmlEscapeSymbols { val xml10References = XmlEscapeSymbols.References() /* * -------------------------------------------------------------------------------------------------- * XML 1.0 CHARACTER ENTITY REFERENCES * See: http://www.w3.org/TR/xml * -------------------------------------------------------------------------------------------------- */ xml10References.addReference(34, "&quot;") xml10References.addReference(38, "&amp;") xml10References.addReference(39, "&apos;") xml10References.addReference(60, "&lt;") xml10References.addReference(62, "&gt;") /* * Initialization of escape markup-significant characters plus all non-ASCII */ val escapeLevels = ByteArray(XmlEscapeSymbols.LEVELS_LEN) /* * Everything is level 3 unless contrary indication. */ Arrays.fill(escapeLevels, 3.toByte()) /* * Everything non-ASCII is level 2 unless contrary indication. */ for (c in 0x80..XmlEscapeSymbols.LEVELS_LEN - 1) { escapeLevels[c] = 2 } /* * Alphanumeric characters are level 4. */ run { var c = 'A' while (c <= 'Z') { escapeLevels[c] = 4 c++ } } run { var c = 'a' while (c <= 'z') { escapeLevels[c] = 4 c++ } } run { var c = '0' while (c <= '9') { escapeLevels[c] = 4 c++ } } /* * The five XML predefined entities will be escaped always (level 1) */ escapeLevels['\''] = 1 escapeLevels['"'] = 1 escapeLevels['<'] = 1 escapeLevels['>'] = 1 escapeLevels['&'] = 1 /* * XML 1.0 allows a series of control characters, but they should appear * escaped: [#x7F-#x84] | [#x86-#x9F] */ for (c in 0x7F..0x84) { escapeLevels[c] = 1 } for (c in 0x86..0x9F) { escapeLevels[c] = 1 } /* * Create the new symbols structure */ return XmlEscapeSymbols(xml10References, escapeLevels, XmlCodepointValidator()) } private operator fun ByteArray.set(c: Char, value: Byte) { set(c.toInt(), value) } /** * Instances of this class group all the complex data structures needed to support escape and unescape * operations for XML. * * In contrast with HTML escape operations, the entity references to be used for XML escape/unescape operations * can be defined by the user by manually creating an instance of this class containing all the entities he/she * wants to escape. * * It is **not** recommended to use this XML class for HTML escape/unescape operations. Use the methods * in [org.unbescape.html.HtmlEscape] instead, as HTML escape rules include a series of tweaks not allowed in * XML, as well as being less lenient with regard to aspects such as case-sensitivity. Besides, the HTML escape * infrastructure is able to apply a series of performance optimizations not possible in XML due to the fact that * the number of HTML Character Entity References (*Named Character References* in HTML5 jargon) is fixed * and known in advance. * * Objects of this class are **thread-safe**. */ class XmlEscapeSymbols /* * Create a new XmlEscapeSymbols structure. This will initialize all the structures needed to cover the * specified references and escape levels, including sorted arrays, overflow maps, etc. */ internal constructor(references: References, escapeLevels: ByteArray, /* * This object will be in charge of validating each codepoint in input, in order to determine * whether such codepoint will be allowed in escaped output (escaped or not). Invalid codepoints * will be simply discarded. */ val CODEPOINT_VALIDATOR: XmlCodepointValidator) { /* * This array will hold the 'escape level' assigned to chars (not codepoints) up to LEVELS_LEN. * - The last position of this array will be used for determining the level of all codepoints >= (LEVELS_LEN - 1) */ val ESCAPE_LEVELS = ByteArray(LEVELS_LEN) /* * This array will contain all the codepoints that might be escaped, numerically ordered. * - Positions in this array will correspond to positions in the SORTED_CERS_BY_CODEPOINT array, so that one array * (this one) holds the codepoints while the other one holds the CERs such codepoints refer to. * - Gives the opportunity to store all codepoints in numerical order and therefore be able to perform * binary search operations in order to quickly find codepoints (and translate to CERs) when escaping. */ val SORTED_CODEPOINTS: IntArray /* * This array contains all the CERs corresponding to the codepoints stored in SORTED_CODEPOINTS. This array is * ordered so that each index in SORTED_CODEPOINTS can also be used to retrieve the corresponding CER when used * on this array. */ val SORTED_CERS_BY_CODEPOINT: Array<CharArray?> /* * This array will contain all the CERs that might be unescaped, alphabetically ordered. * - Positions in this array will correspond to positions in the SORTED_CODEPOINTS_BY_CER array, so that one array * (this one) holds the CERs while the other one holds the codepoint(s) such CERs refer to. * - Gives the opportunity to store all CERs in alphabetical order and therefore be able to perform * binary search operations in order to quickly find CERs (and translate to codepoints) when unescaping. */ val SORTED_CERS: Array<CharArray?> /* * This array contains all the codepoints corresponding to the CERs stored in SORTED_CERS. This array is * ordered so that each index in SORTED_CERS can also be used to retrieve the corresponding CODEPOINT when used * on this array. */ val SORTED_CODEPOINTS_BY_CER: IntArray init { // Initialize escape levels: just copy the array System.arraycopy(escapeLevels, 0, ESCAPE_LEVELS, 0, LEVELS_LEN) // Initialize the length of the escaping structures val structureLen = references.references.size // Initialize some auxiliary structures val cers = ArrayList<CharArray>(structureLen + 5) val codepoints = ArrayList<Int>(structureLen + 5) // For each reference, initialize its corresponding codepoint -> CER and CER -> codepoint structures for (reference in references.references) { cers.add(reference.cer) // can be null codepoints.add(Integer.valueOf(reference.codepoint)) } // We can initialize now the arrays SORTED_CODEPOINTS = IntArray(structureLen) SORTED_CERS_BY_CODEPOINT = arrayOfNulls(structureLen) SORTED_CERS = arrayOfNulls(structureLen) SORTED_CODEPOINTS_BY_CER = IntArray(structureLen) val cersOrdered = ArrayList(cers) Collections.sort(cersOrdered) { o1, o2 -> String(o1).compareTo(String(o2)) } val codepointsOrdered = ArrayList(codepoints) Collections.sort(codepointsOrdered) // Order the CODEPOINT -> CERs (escape)structures for (i in 0..structureLen - 1) { val codepoint = codepointsOrdered[i] SORTED_CODEPOINTS[i] = codepoint for (j in 0..structureLen - 1) { if (codepoint == codepoints[j]) { SORTED_CERS_BY_CODEPOINT[i] = cers[j] break } } } // Order the CERs -> CODEPOINT (unescape)structures for (i in 0..structureLen - 1) { val cer = cersOrdered[i] SORTED_CERS[i] = cer for (j in 0..structureLen - 1) { if (Arrays.equals(cer, cers[j])) { SORTED_CODEPOINTS_BY_CER[i] = codepoints[j] break } } } } /* * Inner utility classes that model the named character references to be included in an initialized * instance of the XmlEscapeSymbols class. */ class References { internal val references = ArrayList<Reference>(200) fun addReference(codepoint: Int, cer: String) { this.references.add(Reference(cer, codepoint)) } } class Reference internal constructor(cer: String, internal val codepoint: Int) { // cer CAN be null -> codepoint should be removed from escaped output. internal val cer: CharArray = cer.toCharArray() } companion object { /* * Size of the array specifying the escape levels. */ val LEVELS_LEN = (0x9f + 2) } } }
apache-2.0
e1cf3bdce98ca07c988126a07fc2f77e
32.615561
116
0.649285
3.953175
false
false
false
false
PaulWoitaschek/Voice
playback/src/main/kotlin/voice/playback/session/headset/HeadsetStateChangeFlow.kt
1
846
package voice.playback.session.headset import android.content.Context import android.content.Intent import android.content.IntentFilter import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import voice.logging.core.Logger import voice.playback.misc.flowBroadcastReceiver private val filter = IntentFilter(Intent.ACTION_HEADSET_PLUG) private const val PLUGGED = 1 private const val UNPLUGGED = 0 fun Context.headsetStateChangeFlow(): Flow<HeadsetState> { return flowBroadcastReceiver(filter) .map { Logger.i("onReceive with intent=$it") when (val intState = it.getIntExtra("state", UNPLUGGED)) { UNPLUGGED -> HeadsetState.Unplugged PLUGGED -> HeadsetState.Plugged else -> { Logger.i("Unknown headsetState $intState") HeadsetState.Unknown } } } }
gpl-3.0
61f65c2d452c119011dd94e00e358d4d
29.214286
64
0.730496
4.126829
false
false
false
false
FHannes/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/DependentResolver.kt
9
2409
/* * 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 org.jetbrains.plugins.groovy.lang.resolve import com.intellij.psi.PsiPolyVariantReference import com.intellij.psi.ResolveResult import com.intellij.psi.impl.source.resolve.ResolveCache abstract class DependentResolver<T : PsiPolyVariantReference> : ResolveCache.PolyVariantResolver<T> { companion object { /** * Given: resolve was called on a reference a.r1.r2...rN. * Its dependencies: a, a.r1, a.r1.r2, ... , a.r1.r2...rN-1. * We resolve dependencies in a loop. * Assume currently resolving dependency is a.r1.r2...rK, K < N. * By the time it is being processed all its dependencies are already resolved and the resolve results are stored in a list, * so we do not need to collect/resolve its dependencies again. * This field is needed to memoize currently resolving dependencies. */ private val resolvingDependencies = ThreadLocal.withInitial { mutableSetOf<PsiPolyVariantReference>() } } override final fun resolve(ref: T, incomplete: Boolean): Array<out ResolveResult> { val dependencies = resolveDependencies(ref, incomplete) val result = doResolve(ref, incomplete) dependencies?.clear() return result } private fun resolveDependencies(ref: T, incomplete: Boolean): MutableCollection<Any>? { if (ref in resolvingDependencies.get()) return null return collectDependencies(ref)?.mapNotNullTo(mutableListOf<Any>()) { if (ref === it) return@mapNotNullTo null try { resolvingDependencies.get().add(it) it.multiResolve(incomplete) } finally { resolvingDependencies.get().remove(it) } } } abstract fun collectDependencies(ref: T): Collection<PsiPolyVariantReference>? abstract fun doResolve(ref: T, incomplete: Boolean): Array<out ResolveResult> }
apache-2.0
8691f5a294280c12abac00561443e81b
37.870968
128
0.723537
4.332734
false
false
false
false
GeoffreyMetais/vlc-android
application/resources/src/main/java/org/videolan/resources/opensubtitles/IOpenSubtitleService.kt
1
832
package org.videolan.resources.opensubtitles import retrofit2.http.GET import retrofit2.http.Path //Passing 0 for numbers and "" for strings ignores that parameters interface IOpenSubtitleService { @GET("episode-{episode}/imdbid-{imdbId}/moviebytesize-{movieByteSize}/moviehash-{movieHash}/query-{name}/season-{season}/sublanguageid-{subLanguageId}/tag_{tag}") suspend fun query( @Path("movieByteSize") movieByteSize: String = "", @Path("movieHash") movieHash: String = "", @Path("name") name: String = "", @Path("imdbId") imdbId: String = "" , @Path("tag") tag: String = "", @Path("episode") episode: Int = 0, @Path("season") season: Int = 0, @Path("subLanguageId") languageId: String = ""): List<OpenSubtitle> }
gpl-2.0
804784b6ae5897b045064b75e4cbd2cf
40.6
166
0.622596
4.16
false
false
false
false
CineCor/CinecorAndroid
app/src/main/java/com/cinecor/android/data/source/local/RoomTypeConverter.kt
1
1041
package com.cinecor.android.data.source.local import android.arch.persistence.room.TypeConverter import com.cinecor.android.data.model.Movie import com.google.gson.Gson import com.google.gson.reflect.TypeToken class RoomTypeConverter { @TypeConverter fun jsonToMovies(movies: String): List<Movie> = Gson().fromJson<List<Movie>>(movies, object : TypeToken<List<Movie>>() {}.type) @TypeConverter fun moviesToJson(movies: List<Movie>): String = Gson().toJson(movies) @TypeConverter fun listToJson(list: List<String>) = Gson().toJson(list) @TypeConverter fun jsonToList(list: String) = Gson().fromJson<List<String>>(list, object : TypeToken<List<String>>() {}.type) @TypeConverter fun hashmapToJson(hashMap: HashMap<String, String>) = Gson().toJson(hashMap) @TypeConverter fun jsonToHashmap(hashMap: String) = Gson().fromJson<HashMap<String, String>>(hashMap, object : TypeToken<HashMap<String, String>>() {}.type) }
gpl-3.0
17b8eb2bdc03630ae485a0164f0a9d87
30.545455
116
0.677233
4.164
false
false
false
false
sandjelkovic/dispatchd
content-service/src/test/kotlin/com/sandjelkovic/dispatchd/content/trakt/provider/impl/DefaultTraktMediaProviderTest.kt
1
4451
package com.sandjelkovic.dispatchd.content.trakt.provider.impl import arrow.core.Option import arrow.core.Try import com.sandjelkovic.dispatchd.content.isFailure import com.sandjelkovic.dispatchd.content.isNone import com.sandjelkovic.dispatchd.content.isSome import com.sandjelkovic.dispatchd.content.isSuccess import com.sandjelkovic.dispatchd.content.trakt.dto.ShowTrakt import com.sandjelkovic.dispatchd.content.trakt.dto.ShowUpdateTrakt import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.junit.Before import org.junit.Test import org.springframework.http.HttpStatus import org.springframework.web.client.HttpClientErrorException import org.springframework.web.client.RestTemplate import org.springframework.web.client.getForObject import strikt.api.expectThat import strikt.assertions.* import java.net.URI import java.time.LocalDate import java.time.ZonedDateTime /** * @author sandjelkovic * @date 28.1.18. */ //@RunWith(SpringRunner::class) class DefaultTraktMediaProviderTest { companion object { const val showId = "star-trek-tng" } private val uri: URI = URI.create("https://baseUrl.com/") private val showTrakt: ShowTrakt = ShowTrakt(title = "Title") private val mockRestTemplate: RestTemplate = mockk() private val mockUriProvider: DefaultTraktUriProvider = mockk { every { getShowUri(showId) } returns uri every { getUpdatesUri(LocalDate.now().minusDays(1)) } returns uri } private lateinit var provider: DefaultTraktMediaProvider @Before fun setUp() { provider = DefaultTraktMediaProvider(mockUriProvider, mockRestTemplate) } @Test fun `getShow should return wrapped retrieved show`() { val preparedShow = showTrakt every { mockRestTemplate.getForObject<ShowTrakt?>(uri) } returns preparedShow val attemptedShowOptional: Try<Option<ShowTrakt>> = provider.getShow(showId) expectThat(attemptedShowOptional) .isSuccess { isSome { isEqualTo(preparedShow) } } verify { mockRestTemplate.getForObject<ShowTrakt?>(uri) mockUriProvider.getShowUri(showId) } } @Test fun `getShow should return wrapped empty Option in case the Show is null`() { every { mockRestTemplate.getForObject<ShowTrakt?>(uri) } returns null val attemptedShowOptional: Try<Option<ShowTrakt>> = provider.getShow(showId) expectThat(attemptedShowOptional) .isSuccess { isNone() } verify { mockRestTemplate.getForObject<ShowTrakt?>(uri) mockUriProvider.getShowUri(showId) } } @Test fun `getShow should return wrapped empty Option in case of a Not Found response`() { every { mockRestTemplate.getForObject<ShowTrakt>(uri) } throws HttpClientErrorException(HttpStatus.NOT_FOUND) val attemptedShowOptional: Try<Option<ShowTrakt>> = provider.getShow(showId) expectThat(attemptedShowOptional) .isSuccess { isNone() } verify { mockRestTemplate.getForObject<ShowTrakt>(uri) mockUriProvider.getShowUri(showId) } } @Test fun `getShow should return a Failure if there an unknown HTTP Exception is thrown`() { every { mockRestTemplate.getForObject<ShowTrakt>(uri) } throws HttpClientErrorException(HttpStatus.PAYLOAD_TOO_LARGE) expectThat(provider.getShow(showId)) .isFailure { isA<HttpClientErrorException>() } verify { mockRestTemplate.getForObject<ShowTrakt>(uri) mockUriProvider.getShowUri(showId) } } @Test fun `Should retrieve updates`() { val fromDate = LocalDate.now().minusDays(1) val oneUpdate = ShowUpdateTrakt(ZonedDateTime.now().minusHours(10)) every { mockRestTemplate.getForObject<Array<ShowUpdateTrakt>>(uri) } returns arrayOf(oneUpdate) val updates = provider.getUpdates(fromDate) expectThat(updates) .isSuccess { isNotEmpty() hasSize(1) contains(oneUpdate) } verify { mockRestTemplate.getForObject<Array<ShowUpdateTrakt>>(uri) mockUriProvider.getUpdatesUri(fromDate) } } }
apache-2.0
c0aee5ba2cfcce3c47170b358b972d72
29.909722
125
0.671534
4.945556
false
false
false
false
iiordanov/remote-desktop-clients
bVNC/src/main/java/com/iiordanov/util/MasterPasswordDelegate.kt
1
5011
package com.iiordanov.util import android.content.Context import android.util.Log import com.iiordanov.bVNC.Constants import com.iiordanov.bVNC.Database import com.iiordanov.bVNC.Utils import com.undatech.remoteClientUi.R class MasterPasswordDelegate(val context: Context, val database: Database) { private val TAG: String? = "MasterPasswordDelegate" public fun checkMasterPasswordAndQuitIfWrong( providedPassword: String, dialogWasCancelled: Boolean ): Boolean { Log.i(TAG, "checkMasterPasswordAndQuitIfWrong: Just checking the password.") var result = false if (dialogWasCancelled) { Log.i(TAG, "Dialog cancelled, so quitting.") Utils.showFatalErrorMessage( context, context.getResources().getString(R.string.master_password_error_password_necessary) ) } else if (database.checkMasterPassword(providedPassword, context)) { Log.i(TAG, "Entered password is correct, so proceeding.") Database.setPassword(providedPassword) result = true } else { // Finish the activity if the password was wrong. Log.i(TAG, "Entered password is wrong, so quitting.") Utils.showFatalErrorMessage( context, context.getResources().getString(R.string.master_password_error_wrong_password) ) } return result } public fun toggleMasterPassword( providedPassword: String, dialogWasCancelled: Boolean ): Boolean { Log.i( TAG, "toggleMasterPassword: User asked to toggle master password." ) return if (Utils.querySharedPreferenceBoolean( context, Constants.masterPasswordEnabledTag ) ) { checkAndDisableMasterPassword(providedPassword, dialogWasCancelled) } else { enableMasterPassword(providedPassword, dialogWasCancelled) } } private fun enableMasterPassword( providedPassword: String, dialogWasCancelled: Boolean ): Boolean { Log.i(TAG, "enableMasterPassword: Master password was disabled.") var result = false if (!dialogWasCancelled) { Log.i(TAG, "Setting master password.") Database.setPassword("") if (database.changeDatabasePassword(providedPassword)) { Utils.toggleSharedPreferenceBoolean(context, Constants.masterPasswordEnabledTag) result = true } else { Database.setPassword("") Utils.showErrorMessage( context, context.getResources() .getString(R.string.master_password_error_failed_to_enable) ) } } else { // No need to show error message because user cancelled consciously. Log.i(TAG, "Dialog cancelled, not setting master password.") Utils.showErrorMessage( context, context.getResources().getString(R.string.master_password_error_password_not_set) ) } return result } private fun checkAndDisableMasterPassword( providedPassword: String, dialogWasCancelled: Boolean ): Boolean { Log.i( TAG, "checkAndDisableMasterPassword: User wants to disable master password" ) var result = false // Master password is enabled if (dialogWasCancelled) { Log.i(TAG, "Dialog cancelled, so quitting.") Utils.showFatalErrorMessage( context, context.getResources().getString(R.string.master_password_error_password_necessary) ) } else if (database.checkMasterPassword(providedPassword, context)) { Log.i(TAG, "Entered password was correct, disabling password.") result = disableMasterPassword(providedPassword) } else { Log.i( TAG, "Entered password is wrong or dialog cancelled, so quitting." ) Utils.showFatalErrorMessage( context, context.getResources().getString(R.string.master_password_error_wrong_password) ) } return result } private fun disableMasterPassword(providedPassword: String): Boolean { Log.i(TAG, "disableMasterPassword") var result = false Database.setPassword(providedPassword) if (database.changeDatabasePassword("")) { Utils.toggleSharedPreferenceBoolean(context, Constants.masterPasswordEnabledTag) result = true } else { Utils.showErrorMessage( context, context.getResources().getString(R.string.master_password_error_failed_to_disable) ) } return result } }
gpl-3.0
9d5d63c07e6be07dbec7b55aec4a59de
35.583942
99
0.603472
5.241632
false
false
false
false
nemerosa/ontrack
ontrack-extension-stale/src/test/java/net/nemerosa/ontrack/extension/stale/StaleBranchesJobIT.kt
1
10336
package net.nemerosa.ontrack.extension.stale import net.nemerosa.ontrack.common.Time import net.nemerosa.ontrack.it.AbstractDSLTestJUnit4Support import net.nemerosa.ontrack.job.JobRunListener import net.nemerosa.ontrack.model.structure.Project import org.junit.Test import org.springframework.beans.factory.annotation.Autowired import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue class StaleBranchesJobIT : AbstractDSLTestJUnit4Support() { @Autowired private lateinit var staleJobService: StaleJobService @Test fun `Deleting a branch using last build time`() { project { staleBranches(disabling = 5, deleting = 10) branch { build { updateBuildSignature(time = Time.now().minusDays(16)) } staleJobService.detectAndManageStaleBranches(JobRunListener.out(), project) assertNull(structureService.findBranchByID(id), "Branch has been deleted") } } } @Test fun `Disabling only a branch using last build time when deletion time is not set`() { project { staleBranches(disabling = 5, deleting = null) branch { build { updateBuildSignature(time = Time.now().minusDays(11)) } staleJobService.detectAndManageStaleBranches(JobRunListener.out(), project) assertNotNull(structureService.findBranchByID(id), "Branch has not been deleted") { assertTrue(it.isDisabled, "Branch has been disabled") } } } } @Test fun `Disabling a branch using last build time`() { project { staleBranches(disabling = 5, deleting = 10) branch { build { updateBuildSignature(time = Time.now().minusDays(6)) } staleJobService.detectAndManageStaleBranches(JobRunListener.out(), project) assertNotNull(structureService.findBranchByID(id), "Branch has not been deleted") { assertTrue(it.isDisabled, "Branch has been disabled") } } } } @Test fun `Not touching a branch using last build time`() { project { staleBranches(disabling = 5, deleting = 10) branch { build { updateBuildSignature(time = Time.now().minusDays(4)) } staleJobService.detectAndManageStaleBranches(JobRunListener.out(), project) assertNotNull(structureService.findBranchByID(id), "Branch has not been deleted") { assertFalse(it.isDisabled, "Branch has been disabled") } } } } @Test fun `Deleting a branch using branch creation time`() { project { staleBranches(disabling = 5, deleting = 10) branch { updateBranchSignature(time = Time.now().minusDays(16)) staleJobService.detectAndManageStaleBranches(JobRunListener.out(), project) assertNull(structureService.findBranchByID(id), "Branch has been deleted") } } } @Test fun `Disabling a branch using branch creation time`() { project { staleBranches(disabling = 5, deleting = 10) branch { updateBranchSignature(time = Time.now().minusDays(6)) staleJobService.detectAndManageStaleBranches(JobRunListener.out(), project) assertNotNull(structureService.findBranchByID(id), "Branch has not been deleted") { assertTrue(it.isDisabled, "Branch has been disabled") } } } } @Test fun `Not disabling a branch because of promotions`() { project { branch { updateBranchSignature(time = Time.now().minusDays(7)) val pl = promotionLevel() staleBranches(disabling = 5, deleting = 10, promotionsToKeep = listOf(pl.name)) build { promote(pl) updateBuildSignature(time = Time.now().minusDays(6)) } staleJobService.detectAndManageStaleBranches(JobRunListener.out(), project) assertNotNull(structureService.findBranchByID(id), "Branch has not been deleted") { assertFalse(it.isDisabled, "Branch has not been disabled") } } } } @Test fun `Disabling a branch even if promoted when not configured`() { project { branch { updateBranchSignature(time = Time.now().minusDays(7)) val pl = promotionLevel() staleBranches(disabling = 5, deleting = 10, promotionsToKeep = null) build { promote(pl) updateBuildSignature(time = Time.now().minusDays(6)) } staleJobService.detectAndManageStaleBranches(JobRunListener.out(), project) assertNotNull(structureService.findBranchByID(id), "Branch has not been deleted") { assertTrue(it.isDisabled, "Branch has been disabled") } } } } @Test fun `Not deleting a branch because of promotions`() { project { branch { updateBranchSignature(time = Time.now().minusDays(12)) val pl = promotionLevel() staleBranches(disabling = 5, deleting = 10, promotionsToKeep = listOf(pl.name)) build { promote(pl) updateBuildSignature(time = Time.now().minusDays(11)) } staleJobService.detectAndManageStaleBranches(JobRunListener.out(), project) assertNotNull(structureService.findBranchByID(id), "Branch has not been deleted") { assertFalse(it.isDisabled, "Branch has not been disabled") } } } } @Test fun `Not deleting a branch because of includes rule`() { project { branch("release-1.0") { updateBranchSignature(time = Time.now().minusDays(20)) val pl = promotionLevel() staleBranches(disabling = 5, deleting = 10, includes = "release-.*") build { promote(pl) updateBuildSignature(time = Time.now().minusDays(18)) } staleJobService.detectAndManageStaleBranches(JobRunListener.out(), project) assertNotNull(structureService.findBranchByID(id), "Branch has not been deleted") { assertFalse(it.isDisabled, "Branch has not been disabled") } } } } @Test fun `Not deleting a branch because of includes rule and excludes rule`() { project { branch("release-2.0") { updateBranchSignature(time = Time.now().minusDays(20)) val pl = promotionLevel() staleBranches(disabling = 5, deleting = 10, includes = "release-.*", excludes = "release-1.*") build { promote(pl) updateBuildSignature(time = Time.now().minusDays(18)) } staleJobService.detectAndManageStaleBranches(JobRunListener.out(), project) assertNotNull(structureService.findBranchByID(id), "Branch has not been deleted") { assertFalse(it.isDisabled, "Branch has not been disabled") } } } } @Test fun `Deleting a branch because of includes rule and excludes rule`() { project { branch("release-1.0") { updateBranchSignature(time = Time.now().minusDays(20)) val pl = promotionLevel() staleBranches(disabling = 5, deleting = 10, includes = "release-.*", excludes = "release-1.*") build { promote(pl) updateBuildSignature(time = Time.now().minusDays(18)) } staleJobService.detectAndManageStaleBranches(JobRunListener.out(), project) assertNull(structureService.findBranchByID(id), "Branch has been deleted") } } } @Test fun `Deleting a branch even if promoted when not configured`() { project { branch { updateBranchSignature(time = Time.now().minusDays(6)) val pl = promotionLevel() staleBranches(disabling = 5, deleting = 10, promotionsToKeep = null) build { promote(pl) updateBuildSignature(time = Time.now().minusDays(16)) } staleJobService.detectAndManageStaleBranches(JobRunListener.out(), project) assertNull(structureService.findBranchByID(id), "Branch has been deleted") } } } @Test fun `Not touching a branch using branch creation time`() { project { staleBranches(disabling = 5, deleting = 10) branch { updateBranchSignature(time = Time.now().minusDays(4)) staleJobService.detectAndManageStaleBranches(JobRunListener.out(), project) assertNotNull(structureService.findBranchByID(id), "Branch has not been deleted") { assertFalse(it.isDisabled, "Branch has not been disabled") } } } } private fun Project.staleBranches( disabling: Int = 0, deleting: Int? = null, promotionsToKeep: List<String>? = null, includes: String? = null, excludes: String? = null, ) { setProperty(project, StalePropertyType::class.java, StaleProperty( disablingDuration = disabling, deletingDuration = deleting, promotionsToKeep = promotionsToKeep, includes = includes, excludes = excludes, )) } }
mit
6652690c449a8078f407f51666e71b5b
37.857143
110
0.559888
5.719978
false
true
false
false
americanexpress/bucketlist
examples/src/main/kotlin/io/aexp/bucketlist/examples/Helpers.kt
1
2540
package io.aexp.bucketlist.examples import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import com.ning.http.client.AsyncHttpClient import de.erichseifert.gral.data.DataSource import de.erichseifert.gral.data.DataTable import de.erichseifert.gral.io.data.DataReaderFactory import io.aexp.bucketlist.BucketListClient import io.aexp.bucketlist.HttpBucketListClient import io.aexp.bucketlist.auth.UsernamePasswordAuthenticator import java.net.URL import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.util.Properties /** * Load username/password and url from a props file. * * This means that you never have to put the password in a shell command, so it can stay out of your shell history, * process listing, etc. */ fun getBitBucketClient(configPath: Path, asyncHttpClient: AsyncHttpClient = AsyncHttpClient()): BucketListClient { val props = Properties() props.load(Files.newBufferedReader(configPath, StandardCharsets.UTF_8)) val username = props.getProperty("username") val password = props.getProperty("password") val url = URL(props.getProperty("url")) val objectMapper = ObjectMapper() objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) return HttpBucketListClient(url, UsernamePasswordAuthenticator(username, password), asyncHttpClient, objectMapper.reader(), objectMapper.writer()) } /** * @return DataTable configured with the appropriate columns for a box and whisker plot */ @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") fun getBoxWhiskerPlotDataTable(): DataTable { // need boxed for DataTable, but Kotlin numeric types map to primitives val doubleClass = java.lang.Double::class.java return DataTable(Integer::class.java, doubleClass, doubleClass, doubleClass, doubleClass, doubleClass) } @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") fun getTsvBoxWhiskerDataSource(outputPath: Path): DataSource { val dataReader = DataReaderFactory.getInstance().get("text/tab-separated-values") Files.newInputStream(outputPath).use { stream -> val doubleClass = java.lang.Double::class.java return dataReader.read(stream, Integer::class.java, doubleClass, doubleClass, doubleClass, doubleClass, doubleClass) } }
apache-2.0
d672800afb006332e1934a2436081acd
34.277778
115
0.722835
4.503546
false
true
false
false
langara/MyIntent
mydrawables/src/main/java/pl/mareklangiewicz/mydrawables/MyLessDrawable.kt
1
748
package pl.mareklangiewicz.mydrawables import android.graphics.Path import android.graphics.Rect import androidx.annotation.IntRange /** * Created by Marek Langiewicz on 16.09.15. * A less/equal animation */ class MyLessDrawable : MyLivingDrawable() { override fun drawLivingPath(path: Path, @IntRange(from = 0, to = 10000) level: Int, bounds: Rect, cx: Int, cy: Int) { val w4 = bounds.width() / 4 val h4 = bounds.height() / 4 val h8 = bounds.height() / 8 ln(cx + w4, lvl(cy - h4, cy - h8), cx - w4, lvl(cy, cy - h8)) val y = lvl(cy, cy + h8) if (y != cy) path.moveTo((cx - w4).toFloat(), y.toFloat()) path.lineTo((cx + w4).toFloat(), lvl(cy + h4, cy + h8).toFloat()) } }
apache-2.0
a4f0e4a00ed57b0bebd332cc70b97fb6
25.714286
121
0.605615
3.156118
false
false
false
false
drakeet/MultiType
sample/src/main/kotlin/com/drakeet/multitype/sample/normal/RichView.kt
1
891
package com.drakeet.multitype.sample.normal import android.content.Context import android.graphics.Color import android.view.Gravity import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.widget.LinearLayout import androidx.appcompat.widget.AppCompatImageView import androidx.appcompat.widget.AppCompatTextView import com.drakeet.multitype.sample.R import com.drakeet.multitype.sample.dp /** * @author Drakeet Xu */ class RichView(context: Context) : LinearLayout(context) { val imageView = AppCompatImageView(context).apply { addView(this, LayoutParams(72.dp, 72.dp)) } val textView = AppCompatTextView(context).apply { gravity = Gravity.CENTER setTextColor(Color.BLACK) addView(this, LayoutParams(WRAP_CONTENT, WRAP_CONTENT)) } init { orientation = VERTICAL gravity = Gravity.CENTER setPadding(16.dp, 16.dp, 16.dp, 16.dp) } }
apache-2.0
821f5e55c9812c9ef9e79e938be9fabe
26
59
0.766554
4.013514
false
false
false
false
REBOOTERS/AndroidAnimationExercise
imitate/src/main/java/com/engineer/imitate/ui/widget/headsup/SwipeDismissTouchListener.kt
1
8739
package com.engineer.imitate.ui.widget.headsup import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.os.Build import android.view.MotionEvent import android.view.VelocityTracker import android.view.View import android.view.ViewConfiguration import androidx.annotation.RequiresApi /** * A [View.OnTouchListener] that makes any [View] dismissable when the * user swipes (drags her finger) horizontally across the view. * * @param view The view to make dismissable. * @param callbacks The callback to trigger when the user has indicated that she would like to * dismiss this view. */ internal class SwipeDismissTouchListener( private val mView: View, private val mCallbacks: DismissCallbacks ) : View.OnTouchListener { // Cached ViewConfiguration and system-wide constant values private val mSlop: Int private val mMinFlingVelocity: Int private val mAnimationTime: Long private var mViewWidth = 1 // 1 and not 0 to prevent dividing by zero // Transient properties private var mDownX: Float = 0.toFloat() private var mDownY: Float = 0.toFloat() private var mSwiping: Boolean = false private var mSwipingSlop: Int = 0 private var mVelocityTracker: VelocityTracker? = null private var mTranslationX: Float = 0.toFloat() init { val vc = ViewConfiguration.get(mView.context) mSlop = vc.scaledTouchSlop mMinFlingVelocity = vc.scaledMinimumFlingVelocity * 16 mAnimationTime = mView.context.resources.getInteger( android.R.integer.config_shortAnimTime).toLong() } @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB_MR1) override fun onTouch(view: View, motionEvent: MotionEvent): Boolean { // offset because the view is translated during swipe motionEvent.offsetLocation(mTranslationX, 0f) if (mViewWidth < 2) { mViewWidth = mView.width } when (motionEvent.actionMasked) { MotionEvent.ACTION_DOWN -> { mDownX = motionEvent.rawX mDownY = motionEvent.rawY if (mCallbacks.canDismiss()) { mVelocityTracker = VelocityTracker.obtain() mVelocityTracker!!.addMovement(motionEvent) } mCallbacks.onTouch(view, true) return false } MotionEvent.ACTION_UP -> { mVelocityTracker?.run { val deltaX = motionEvent.rawX - mDownX this.addMovement(motionEvent) this.computeCurrentVelocity(1000) val velocityX = this.xVelocity val absVelocityX = Math.abs(velocityX) val absVelocityY = Math.abs(this.yVelocity) var dismiss = false var dismissRight = false if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) { dismiss = true dismissRight = deltaX > 0 } else if (mMinFlingVelocity <= absVelocityX && absVelocityY < absVelocityX && mSwiping) { // dismiss only if flinging in the same direction as dragging dismiss = velocityX < 0 == deltaX < 0 dismissRight = this.xVelocity > 0 } if (dismiss) { // dismiss mView.animate() .translationX((if (dismissRight) mViewWidth else -mViewWidth).toFloat()) .alpha(0f) .setDuration(mAnimationTime) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { performDismiss() } }) } else if (mSwiping) { // cancel mView.animate() .translationX(0f) .alpha(1f) .setDuration(mAnimationTime) .setListener(null) mCallbacks.onTouch(view, false) } this.recycle() mVelocityTracker = null mTranslationX = 0f mDownX = 0f mDownY = 0f mSwiping = false } } MotionEvent.ACTION_CANCEL -> { mVelocityTracker?.run { mView.animate() .translationX(0f) .alpha(1f) .setDuration(mAnimationTime) .setListener(null) this.recycle() mVelocityTracker = null mTranslationX = 0f mDownX = 0f mDownY = 0f mSwiping = false } } MotionEvent.ACTION_MOVE -> { mVelocityTracker?.run { this.addMovement(motionEvent) val deltaX = motionEvent.rawX - mDownX val deltaY = motionEvent.rawY - mDownY if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) { mSwiping = true mSwipingSlop = if (deltaX > 0) mSlop else -mSlop mView.parent.requestDisallowInterceptTouchEvent(true) // Cancel listview's touch val cancelEvent = MotionEvent.obtain(motionEvent) cancelEvent.action = MotionEvent.ACTION_CANCEL or (motionEvent.actionIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT) mView.onTouchEvent(cancelEvent) cancelEvent.recycle() } if (mSwiping) { mTranslationX = deltaX mView.translationX = deltaX - mSwipingSlop // TODO: use an ease-out interpolator or such mView.alpha = Math.max(0f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth)) return true } } } else -> { view.performClick() return false } } return false } @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB) private fun performDismiss() { // Animate the dismissed view to zero-height and then fire the dismiss callback. // This triggers layout on each animation frame; in the future we may want to do something // smarter and more performant. val lp = mView.layoutParams val originalHeight = mView.height val animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime) animator.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { mCallbacks.onDismiss(mView) // Reset view presentation mView.alpha = 1f mView.translationX = 0f lp.height = originalHeight mView.layoutParams = lp } }) animator.addUpdateListener { valueAnimator -> lp.height = valueAnimator.animatedValue as Int mView.layoutParams = lp } animator.start() } /** * The callback interface used by [SwipeDismissTouchListener] to inform its client * about a successful dismissal of the view for which it was created. */ internal interface DismissCallbacks { /** * Called to determine whether the view can be dismissed. * * @return boolean The view can dismiss. */ fun canDismiss(): Boolean /** * Called when the user has indicated they she would like to dismiss the view. * * @param view The originating [View] */ fun onDismiss(view: View) /** * Called when the user touches the view or release the view. * * @param view The originating [View] * @param touch The view is being touched. */ fun onTouch(view: View, touch: Boolean) } }
apache-2.0
6a5e46b2fa936986758a965703c72899
38.547511
142
0.525575
5.841578
false
false
false
false
thatJavaNerd/JRAW
lib/src/main/kotlin/net/dean/jraw/models/KindConstants.kt
1
1210
package net.dean.jraw.models /** * A list of values for the "kind" node in a typical JSON response. See * [net.dean.jraw.databind.RedditModelAdapterFactory] for more information. */ object KindConstants { /** A [Comment] */ const val COMMENT = "t1" /** An [Account] */ const val ACCOUNT = "t2" /** A [Submission] */ const val SUBMISSION = "t3" /** A [Message] */ const val MESSAGE = "t4" /** A [Subreddit] */ const val SUBREDDIT = "t5" /** A [Trophy] */ const val TROPHY = "t6" /** A [MoreChildren] */ const val MORE_CHILDREN = "more" /** A [Listing] */ const val LISTING = "Listing" /** A [Multireddit] */ const val MULTIREDDIT = "LabeledMulti" /** A [LiveUpdate] */ const val LIVE_UPDATE = "LiveUpdate" /** A [LiveThread] */ const val LIVE_THREAD = "LiveUpdateEvent" /** A list of [Trophy] objects */ const val TROPHY_LIST = "TrophyList" /** A [net.dean.jraw.models.internal.LabeledMultiDescription] */ const val LABELED_MULTI_DESC = "LabeledMultiDescription" /** A [WikiPage] */ const val WIKI_PAGE = "wikipage" /** A [ModAction] */ const val MODACTION = "modaction" }
mit
b407c1de12a8b9ce2705fd9b2ce2faab
22.269231
75
0.596694
3.61194
false
false
false
false
bozaro/git-as-svn
src/main/kotlin/svnserver/parser/MessageParser.kt
1
5512
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.parser import svnserver.parser.MessageParser.Parser import svnserver.parser.token.* import java.io.IOException import java.lang.reflect.Constructor import java.lang.reflect.Parameter import java.util.* /** * Parse data from class. * * @author Artem V. Navrotskiy <[email protected]> */ object MessageParser { private val emptyBytes: ByteArray = byteArrayOf() private val emptyInts: IntArray = intArrayOf() private val parsers: MutableMap<Class<*>?, Parser> @Throws(IOException::class) fun <T> parse(type: Class<T>, tokenParser: SvnServerParser?): T { val typeParser: Parser? = parsers[type] if (typeParser != null) { return typeParser.parse(tokenParser) as T } return parseObject(type, tokenParser) } @Throws(IOException::class) private fun <T> parseObject(type: Class<T>, tokenParser: SvnServerParser?): T { var tokenParser: SvnServerParser? = tokenParser if (tokenParser != null && tokenParser.readItem(ListBeginToken::class.java) == null) tokenParser = null val depth: Int = getDepth(tokenParser) if (type.isArray) { val result = ArrayList<Any>() if (tokenParser != null) { while (true) { val element: Any = parse(type.componentType, tokenParser) if (getDepth(tokenParser) < depth) break result.add(element) } } return result.toArray(java.lang.reflect.Array.newInstance(type.componentType, result.size) as Array<*>) as T } val ctors: Array<Constructor<*>> = type.declaredConstructors if (ctors.size != 1) { throw IllegalStateException("Can't find parser ctor for object: " + type.name) } val ctor: Constructor<*> = ctors[0] val ctorParams: Array<Parameter> = ctor.parameters val params: Array<Any?> = arrayOfNulls(ctorParams.size) for (i in params.indices) { params[i] = parse(ctorParams[i].type, if (getDepth(tokenParser) == depth) tokenParser else null) } while (tokenParser != null && getDepth(tokenParser) >= depth) { tokenParser.readToken() } try { if (!ctor.isAccessible) ctor.isAccessible = true return ctor.newInstance(*params) as T } catch (e: ReflectiveOperationException) { throw IllegalStateException(e) } } @Throws(IOException::class) private fun parseString(tokenParser: SvnServerParser?): String { if (tokenParser == null) { return "" } val token: TextToken? = tokenParser.readItem(TextToken::class.java) return token?.text ?: "" } @Throws(IOException::class) private fun parseBinary(tokenParser: SvnServerParser?): ByteArray? { if (tokenParser == null) { return emptyBytes } val token: StringToken? = tokenParser.readItem(StringToken::class.java) return token?.data ?: emptyBytes } @Throws(IOException::class) private fun parseInt(tokenParser: SvnServerParser?): Int { if (tokenParser == null) { return 0 } val token: NumberToken? = tokenParser.readItem(NumberToken::class.java) return if (token != null) token.number else 0 } @Throws(IOException::class) private fun parseBool(tokenParser: SvnServerParser?): Boolean { if (tokenParser == null) { return false } val token: WordToken? = tokenParser.readItem(WordToken::class.java) return token != null && (token.text == "true") } @Throws(IOException::class) private fun parseInts(tokenParser: SvnServerParser?): IntArray { if (tokenParser == null) { return emptyInts } if (tokenParser.readItem((ListBeginToken::class.java)) != null) { val result = ArrayList<Int>() while (true) { val token: NumberToken = tokenParser.readItem(NumberToken::class.java) ?: break result.add(token.number) } val array = IntArray(result.size) for (i in array.indices) { array[i] = result[i] } return array } return emptyInts } private fun getDepth(tokenParser: SvnServerParser?): Int { return tokenParser?.depth ?: -1 } private fun interface Parser { @Throws(IOException::class) fun parse(tokenParser: SvnServerParser?): Any? } init { parsers = HashMap() parsers[String::class.java] = Parser { obj: SvnServerParser? -> parseString(obj) } parsers[ByteArray::class.java] = Parser { obj: SvnServerParser? -> parseBinary(obj) } parsers[Int::class.javaPrimitiveType] = Parser { obj: SvnServerParser? -> parseInt(obj) } parsers[IntArray::class.java] = Parser { obj: SvnServerParser? -> parseInts(obj) } parsers[Boolean::class.javaPrimitiveType] = Parser { obj: SvnServerParser? -> parseBool(obj) } } }
gpl-2.0
2cf35f952baf54ade3f2542383eef2ae
36.496599
120
0.617017
4.466775
false
false
false
false
donald-w/Anki-Android
AnkiDroid/src/main/java/com/ichi2/utils/ViewGroupUtils.kt
1
2860
/* Copyright (c) 2020 David Allison <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.utils import android.R import android.app.Activity import android.view.View import android.view.ViewGroup import com.ichi2.anki.AnkiDroidApp import timber.log.Timber import java.util.ArrayList object ViewGroupUtils { @JvmStatic fun getAllChildren(viewGroup: ViewGroup): List<View> { val childrenCount = viewGroup.childCount val views: MutableList<View> = ArrayList(childrenCount) for (i in 0 until childrenCount) { views.add(viewGroup.getChildAt(i)) } return views } @JvmStatic fun getAllChildrenRecursive(viewGroup: ViewGroup): MutableList<View> { val views: MutableList<View> = ArrayList() for (i in 0 until viewGroup.childCount) { val child = viewGroup.getChildAt(i) views.add(child) if (child is ViewGroup) { views.addAll(getAllChildrenRecursive(child)) } } return views } @JvmStatic fun setRenderWorkaround(activity: Activity) { if (AnkiDroidApp.getSharedPrefs(activity).getBoolean("softwareRender", false)) { Timber.i("ViewGroupUtils::setRenderWorkaround - software render requested, altering Views...") setContentViewLayerTypeSoftware(activity) } else { Timber.i("ViewGroupUtils::setRenderWorkaround - using default / hardware rendering") } } /** * Gets all the Views for the given Activity's ContentView, and sets their layerType * to the given layerType * * @param activity Activity containing the View hierarchy to alter */ private fun setContentViewLayerTypeSoftware(activity: Activity) { val rootViewGroup = (activity.findViewById<View>(R.id.content) as ViewGroup) .getChildAt(0) as ViewGroup val allViews = getAllChildrenRecursive(rootViewGroup) allViews.add(rootViewGroup) for (v in allViews) { Timber.d( "ViewGroupUtils::setContentViewLayerTypeSoftware for view %s", v.id ) v.setLayerType(View.LAYER_TYPE_SOFTWARE, null) } } }
gpl-3.0
4bca19a2b46bbdfaea3ab4fa993e9b23
34.75
106
0.677972
4.688525
false
false
false
false
ivan-osipov/Clabo
src/main/kotlin/com/github/ivan_osipov/clabo/api/model/PreCheckoutQuery.kt
1
712
package com.github.ivan_osipov.clabo.api.model import com.google.gson.annotations.SerializedName /** * @see <a href="https://core.telegram.org/bots/api#precheckoutquery">docs</a> */ class PreCheckoutQuery : Identifiable() { @SerializedName("from") lateinit var from: User @SerializedName("currency") lateinit var currency: String @SerializedName("total_amount") private val _totalAmount: Int? = null val totalAmount: Int = _totalAmount!! @SerializedName("invoice_payload") lateinit var invoicePayload: String @SerializedName("shipping_option_id") var shippingOptionId: String? = null @SerializedName("order_info") var orderInfo: OrderInfo? = null }
apache-2.0
59399945014611112543c500a0fdf4c9
22.766667
78
0.706461
4.115607
false
false
false
false
edvin/tornadofx
src/main/java/tornadofx/adapters/TornadoFXResizeFeatures.kt
2
1606
package tornadofx.adapters import javafx.collections.ObservableMap import javafx.scene.control.TableColumn import javafx.scene.control.TableView import javafx.scene.control.TreeTableColumn import javafx.scene.control.TreeTableView import javafx.util.Callback typealias Properties = ObservableMap<Any?, Any?> typealias TableViewResizeCallback = Callback<TableView.ResizeFeatures<out Any>, Boolean> typealias TreeTableViewResizeCallback = Callback<TreeTableView.ResizeFeatures<out Any>, Boolean> fun TreeTableView.ResizeFeatures<*>.toTornadoFXResizeFeatures() = TornadoFXTreeTableResizeFeatures(this) fun TableView.ResizeFeatures<*>.toTornadoFXFeatures() = TornadoFxTableResizeFeatures(this) interface TornadoFXResizeFeatures<COLUMN, out TABLE : Any> { val table: TornadoFXTable<COLUMN, TABLE> val delta: Double val column: TornadoFXColumn<COLUMN>? } class TornadoFXTreeTableResizeFeatures(val param: TreeTableView.ResizeFeatures<out Any>) : TornadoFXResizeFeatures<TreeTableColumn<*, *>, TreeTableView<*>> { override val column = param.column?.toTornadoFXColumn() override val table = param.table.toTornadoFXTable() override val delta: Double get() = param.delta } class TornadoFxTableResizeFeatures(val param: TableView.ResizeFeatures<out Any>) : TornadoFXResizeFeatures<TableColumn<*, *>, TableView<*>> { override val table: TornadoFXTable<TableColumn<*, *>, TableView<*>> = TornadoFXNormalTable(param.table) override val delta: Double = param.delta override val column: TornadoFXColumn<TableColumn<*, *>>? = param.column?.let { TornadoFxNormalTableColumn(it) } }
apache-2.0
7ba7a81ed90af8939992b32c1d41e78c
47.69697
157
0.797634
4.79403
false
false
false
false
cashapp/sqldelight
sqldelight-compiler/integration-tests/src/test/kotlin/com/example/PlayerQueries.kt
1
8033
package com.example import app.cash.sqldelight.ExecutableQuery import app.cash.sqldelight.Query import app.cash.sqldelight.TransacterImpl import app.cash.sqldelight.core.integration.Shoots import app.cash.sqldelight.db.QueryResult import app.cash.sqldelight.db.SqlCursor import app.cash.sqldelight.db.SqlDriver import com.example.player.SelectStuff import java.lang.Void import kotlin.Any import kotlin.Long import kotlin.String import kotlin.Unit import kotlin.collections.Collection public class PlayerQueries( driver: SqlDriver, private val playerAdapter: Player.Adapter, ) : TransacterImpl(driver) { public fun <T : Any> insertAndReturn( name: Player.Name, number: Long, team: Team.Name?, shoots: Shoots, mapper: ( name: Player.Name, number: Long, team: Team.Name?, shoots: Shoots, ) -> T, ): ExecutableQuery<T> = InsertAndReturnQuery(name, number, team, shoots) { cursor -> mapper( Player.Name(cursor.getString(0)!!), cursor.getLong(1)!!, cursor.getString(2)?.let { Team.Name(it) }, playerAdapter.shootsAdapter.decode(cursor.getString(3)!!) ) } public fun insertAndReturn( name: Player.Name, number: Long, team: Team.Name?, shoots: Shoots, ): ExecutableQuery<Player> = insertAndReturn(name, number, team, shoots) { name_, number_, team_, shoots_ -> Player( name_, number_, team_, shoots_ ) } public fun <T : Any> allPlayers(mapper: ( name: Player.Name, number: Long, team: Team.Name?, shoots: Shoots, ) -> T): Query<T> = Query(-1634440035, arrayOf("player"), driver, "Player.sq", "allPlayers", """ |SELECT * |FROM player """.trimMargin()) { cursor -> mapper( Player.Name(cursor.getString(0)!!), cursor.getLong(1)!!, cursor.getString(2)?.let { Team.Name(it) }, playerAdapter.shootsAdapter.decode(cursor.getString(3)!!) ) } public fun allPlayers(): Query<Player> = allPlayers { name, number, team, shoots -> Player( name, number, team, shoots ) } public fun <T : Any> playersForTeam(team: Team.Name?, mapper: ( name: Player.Name, number: Long, team: Team.Name?, shoots: Shoots, ) -> T): Query<T> = PlayersForTeamQuery(team) { cursor -> mapper( Player.Name(cursor.getString(0)!!), cursor.getLong(1)!!, cursor.getString(2)?.let { Team.Name(it) }, playerAdapter.shootsAdapter.decode(cursor.getString(3)!!) ) } public fun playersForTeam(team: Team.Name?): Query<Player> = playersForTeam(team) { name, number, team_, shoots -> Player( name, number, team_, shoots ) } public fun <T : Any> playersForNumbers(number: Collection<Long>, mapper: ( name: Player.Name, number: Long, team: Team.Name?, shoots: Shoots, ) -> T): Query<T> = PlayersForNumbersQuery(number) { cursor -> mapper( Player.Name(cursor.getString(0)!!), cursor.getLong(1)!!, cursor.getString(2)?.let { Team.Name(it) }, playerAdapter.shootsAdapter.decode(cursor.getString(3)!!) ) } public fun playersForNumbers(number: Collection<Long>): Query<Player> = playersForNumbers(number) { name, number_, team, shoots -> Player( name, number_, team, shoots ) } public fun <T : Any> selectNull(mapper: (expr: Void?) -> T): ExecutableQuery<T> = Query(106890351, driver, "Player.sq", "selectNull", "SELECT NULL") { cursor -> mapper( null ) } public fun selectNull(): ExecutableQuery<SelectNull> = selectNull { expr -> SelectNull( expr ) } public fun <T : Any> selectStuff(mapper: (expr: Long, expr_: Long) -> T): ExecutableQuery<T> = Query(-976770036, driver, "Player.sq", "selectStuff", "SELECT 1, 2") { cursor -> mapper( cursor.getLong(0)!!, cursor.getLong(1)!! ) } public fun selectStuff(): ExecutableQuery<SelectStuff> = selectStuff { expr, expr_ -> SelectStuff( expr, expr_ ) } public fun insertPlayer( name: Player.Name, number: Long, team: Team.Name?, shoots: Shoots, ): Unit { driver.execute(-1595716666, """ |INSERT INTO player |VALUES (?, ?, ?, ?) """.trimMargin(), 4) { bindString(0, name.name) bindLong(1, number) bindString(2, team?.let { it.name }) bindString(3, playerAdapter.shootsAdapter.encode(shoots)) } notifyQueries(-1595716666) { emit -> emit("player") } } public fun updateTeamForNumbers(team: Team.Name?, number: Collection<Long>): Unit { val numberIndexes = createArguments(count = number.size) driver.execute(null, """ |UPDATE player |SET team = ? |WHERE number IN $numberIndexes """.trimMargin(), 1 + number.size) { bindString(0, team?.let { it.name }) number.forEachIndexed { index, number_ -> bindLong(index + 1, number_) } } notifyQueries(-636585613) { emit -> emit("player") } } public fun foreignKeysOn(): Unit { driver.execute(-1596558949, """PRAGMA foreign_keys = 1""", 0) } public fun foreignKeysOff(): Unit { driver.execute(2046279987, """PRAGMA foreign_keys = 0""", 0) } private inner class InsertAndReturnQuery<out T : Any>( public val name: Player.Name, public val number: Long, public val team: Team.Name?, public val shoots: Shoots, mapper: (SqlCursor) -> T, ) : ExecutableQuery<T>(mapper) { public override fun <R> execute(mapper: (SqlCursor) -> R): QueryResult<R> = transactionWithResult { driver.execute(-452007405, """ |INSERT INTO player | VALUES (?, ?, ?, ?) """.trimMargin(), 4) { bindString(0, name.name) bindLong(1, number) bindString(2, team?.let { it.name }) bindString(3, playerAdapter.shootsAdapter.encode(shoots)) } driver.executeQuery(-452007404, """ |SELECT * | FROM player | WHERE player.rowid = last_insert_rowid() """.trimMargin(), mapper, 0) } public override fun toString(): String = "Player.sq:insertAndReturn" } private inner class PlayersForTeamQuery<out T : Any>( public val team: Team.Name?, mapper: (SqlCursor) -> T, ) : Query<T>(mapper) { public override fun addListener(listener: Query.Listener): Unit { driver.addListener(listener, arrayOf("player")) } public override fun removeListener(listener: Query.Listener): Unit { driver.removeListener(listener, arrayOf("player")) } public override fun <R> execute(mapper: (SqlCursor) -> R): QueryResult<R> = driver.executeQuery(null, """ |SELECT * |FROM player |WHERE team ${ if (team == null) "IS" else "=" } ? """.trimMargin(), mapper, 1) { bindString(0, team?.let { it.name }) } public override fun toString(): String = "Player.sq:playersForTeam" } private inner class PlayersForNumbersQuery<out T : Any>( public val number: Collection<Long>, mapper: (SqlCursor) -> T, ) : Query<T>(mapper) { public override fun addListener(listener: Query.Listener): Unit { driver.addListener(listener, arrayOf("player")) } public override fun removeListener(listener: Query.Listener): Unit { driver.removeListener(listener, arrayOf("player")) } public override fun <R> execute(mapper: (SqlCursor) -> R): QueryResult<R> { val numberIndexes = createArguments(count = number.size) return driver.executeQuery(null, """ |SELECT * |FROM player |WHERE number IN $numberIndexes """.trimMargin(), mapper, number.size) { number.forEachIndexed { index, number_ -> bindLong(index, number_) } } } public override fun toString(): String = "Player.sq:playersForNumbers" } }
apache-2.0
c6ac59f0940b644a6ba6c0200b01aeb8
27.385159
100
0.610357
3.939676
false
false
false
false
Dolvic/gw2-api
jackson/src/main/kotlin/dolvic/gw2/jackson/mechanics/facts/SkillFactMixin.kt
1
2834
package dolvic.gw2.jackson.mechanics.facts import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonSubTypes import com.fasterxml.jackson.annotation.JsonTypeInfo import dolvic.gw2.api.mechanics.facts.AttributeAdjustFact import dolvic.gw2.api.mechanics.facts.BuffConversionFact import dolvic.gw2.api.mechanics.facts.BuffFact import dolvic.gw2.api.mechanics.facts.ComboFieldFact import dolvic.gw2.api.mechanics.facts.ComboFinisherFact import dolvic.gw2.api.mechanics.facts.DamageFact import dolvic.gw2.api.mechanics.facts.DistanceFact import dolvic.gw2.api.mechanics.facts.DurationFact import dolvic.gw2.api.mechanics.facts.HealFact import dolvic.gw2.api.mechanics.facts.HealingAdjustFact import dolvic.gw2.api.mechanics.facts.NoDataFact import dolvic.gw2.api.mechanics.facts.NumberFact import dolvic.gw2.api.mechanics.facts.PercentFact import dolvic.gw2.api.mechanics.facts.PrefixedBuffFact import dolvic.gw2.api.mechanics.facts.RadiusFact import dolvic.gw2.api.mechanics.facts.RangeFact import dolvic.gw2.api.mechanics.facts.RechargeFact import dolvic.gw2.api.mechanics.facts.StunBreakFact import dolvic.gw2.api.mechanics.facts.TimeFact import dolvic.gw2.api.mechanics.facts.UnblockableFact @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") @JsonSubTypes( JsonSubTypes.Type(name = "AttributeAdjust", value = AttributeAdjustFact::class), JsonSubTypes.Type(name = "Buff", value = BuffFact::class), JsonSubTypes.Type(name = "BuffConversion", value = BuffConversionFact::class), JsonSubTypes.Type(name = "ComboField", value = ComboFieldFact::class), JsonSubTypes.Type(name = "ComboFinisher", value = ComboFinisherFact::class), JsonSubTypes.Type(name = "Damage", value = DamageFact::class), JsonSubTypes.Type(name = "Distance", value = DistanceFact::class), JsonSubTypes.Type(name = "Duration", value = DurationFact::class), JsonSubTypes.Type(name = "Heal", value = HealFact::class), JsonSubTypes.Type(name = "HealingAdjust", value = HealingAdjustFact::class), JsonSubTypes.Type(name = "NoData", value = NoDataFact::class), JsonSubTypes.Type(name = "Number", value = NumberFact::class), JsonSubTypes.Type(name = "Percent", value = PercentFact::class), JsonSubTypes.Type(name = "PrefixedBuff", value = PrefixedBuffFact::class), JsonSubTypes.Type(name = "Radius", value = RadiusFact::class), JsonSubTypes.Type(name = "Range", value = RangeFact::class), JsonSubTypes.Type(name = "Recharge", value = RechargeFact::class), JsonSubTypes.Type(name = "StunBreak", value = StunBreakFact::class), JsonSubTypes.Type(name = "Time", value = TimeFact::class), JsonSubTypes.Type(name = "Unblockable", value = UnblockableFact::class) ) @JsonIgnoreProperties(ignoreUnknown = true) internal interface SkillFactMixin
mit
a342db81e717d0566b4f5c960a0c5455
54.568627
84
0.782639
3.709424
false
false
false
false
matejdro/WearMusicCenter
wear/src/main/java/com/matejdro/wearmusiccenter/watch/communication/WatchMusicService.kt
1
4693
package com.matejdro.wearmusiccenter.watch.communication import android.annotation.TargetApi import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import android.os.IBinder import androidx.core.app.NotificationCompat import androidx.lifecycle.LifecycleService import androidx.lifecycle.asFlow import androidx.lifecycle.lifecycleScope import androidx.wear.ongoing.OngoingActivity import com.matejdro.wearmusiccenter.R import com.matejdro.wearmusiccenter.watch.view.MainActivity import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import timber.log.Timber import javax.inject.Inject @AndroidEntryPoint class WatchMusicService : LifecycleService() { @Inject internal lateinit var phoneConnection: PhoneConnection private val uiFlow = MutableSharedFlow<Unit>() private var serviceTimeoutJob: Job? = null override fun onCreate() { super.onCreate() createWearNotification() lifecycleScope.launch { val uiOpenFlow = uiFlow.subscriptionCount .map { it > 0 } val musicPlayingFlow = phoneConnection.musicState.asFlow() .map { it.data?.playing == true } combine(uiOpenFlow, musicPlayingFlow) { uiOpen, musicPlaying -> Timber.d("Service state UI open: %s Music playing: %s", uiOpen, musicPlaying) uiOpen || musicPlaying } .distinctUntilChanged() .collect { isActive -> serviceTimeoutJob?.cancel() if (isActive) { createWearNotification() } else { removeWearNotification() startTimeout() } } } } private fun createWearNotification() { val openAppIntent = Intent(this, MainActivity::class.java) val openAppPendingIntent = PendingIntent.getActivity(this, 1, openAppIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) createNotificationChannel() val notificationBuilder = NotificationCompat.Builder(this, KEY_NOTIFICATION_CHANNEL) .setContentTitle(getString(R.string.music_control_active)) .setContentIntent(openAppPendingIntent) .setSmallIcon(R.drawable.ic_notification_white) .setOngoing(true) val ongoingActivity = OngoingActivity.Builder(this, NOTIFICATION_ID_PERSISTENT, notificationBuilder) .setStaticIcon(R.drawable.ic_notification_white) .setCategory(NotificationCompat.CATEGORY_TRANSPORT) .setTouchIntent(openAppPendingIntent) .build() ongoingActivity.apply(this) startForeground(NOTIFICATION_ID_PERSISTENT, notificationBuilder.build()) } private fun removeWearNotification() { stopForeground(true) } private fun startTimeout() { serviceTimeoutJob = lifecycleScope.launch { delay(SERVICE_TIMEOUT) stopSelf() } } override fun onBind(intent: Intent): IBinder { super.onBind(intent) startService(Intent(this, WatchMusicService::class.java)) return Binder(this) } @TargetApi(Build.VERSION_CODES.O) private fun createNotificationChannel() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { return } val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val persistentChannel = NotificationChannel(KEY_NOTIFICATION_CHANNEL, getString(R.string.music_control), NotificationManager.IMPORTANCE_MIN) notificationManager.createNotificationChannel(persistentChannel) } class Binder(private val service: WatchMusicService) : android.os.Binder() { val uiOpenFlow: Flow<Unit> get() = service.uiFlow } } private const val NOTIFICATION_ID_PERSISTENT = 1 private const val KEY_NOTIFICATION_CHANNEL = "Service_Channel" private const val SERVICE_TIMEOUT = 30_000L
gpl-3.0
c92c3ec46ae6bd7db1ccc1b3a591b2e2
31.818182
108
0.669721
5.273034
false
false
false
false
BilledTrain380/sporttag-psa
app/psa-runtime-service/psa-service-standard/src/main/kotlin/ch/schulealtendorf/psa/service/standard/entity/UnitEntity.kt
1
1967
/* * Copyright (c) 2017 by Nicolas Märchy * * This file is part of Sporttag PSA. * * Sporttag PSA is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Sporttag PSA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Sporttag PSA. If not, see <http://www.gnu.org/licenses/>. * * Diese Datei ist Teil von Sporttag PSA. * * Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen * der GNU General Public License, wie von der Free Software Foundation, * Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren * veröffentlichten Version, weiterverbreiten und/oder modifizieren. * * Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber * OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite * Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. * Siehe die GNU General Public License für weitere Details. * * Sie sollten eine Kopie der GNU General Public License zusammen mit diesem * Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>. * * */ package ch.schulealtendorf.psa.service.standard.entity import javax.persistence.Entity import javax.persistence.Id import javax.persistence.Table import javax.validation.constraints.NotNull import javax.validation.constraints.Size /** * @author nmaerchy * @since 1.0.0 */ @Entity @Table(name = "UNIT") data class UnitEntity( @Id @NotNull @Size(min = 1, max = 45) var name: String = "", @NotNull var factor: Int = 1 )
gpl-3.0
6079582c5b0fb56fca932c9746791a7c
31.616667
77
0.741441
4.181624
false
false
false
false
yzbzz/beautifullife
icore/src/main/java/com/ddu/icore/common/ext/ActivityExt.kt
2
1408
package com.ddu.icore.common.ext import android.app.Activity import android.provider.Settings import android.view.View import android.view.inputmethod.InputMethodManager import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity var Activity.screenBrightness get() = Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS) set(value) { val lp = window.attributes lp.screenBrightness = value / 255f window.attributes = lp } fun Activity.hideKeyboard(view: View?): Boolean? { val currentView = currentFocus ?: view currentView?.let { return inputMethodManager.hideSoftInputFromWindow( currentView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS ) } return false } fun Activity.showKeyboard(view: View?): Boolean? { val currentView = currentFocus ?: view currentView?.let { return inputMethodManager.showSoftInput(currentView, InputMethodManager.HIDE_NOT_ALWAYS) } return false } inline fun <reified F : Fragment> FragmentActivity.newFragment(vararg args: Pair<String, Any?>): F { val fragment = supportFragmentManager.fragmentFactory.instantiate( ClassLoader.getSystemClassLoader(), F::class.java.name ) fragment.arguments = bundleOf(*args) return fragment as F }
apache-2.0
061073d0f442b1b38531d49523516781
30.288889
100
0.716619
4.789116
false
false
false
false
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/common/globals/CrossClientConstants.kt
1
1971
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.app.playhvz.common.globals import android.content.Context import android.graphics.Color import androidx.core.content.ContextCompat import androidx.core.content.contentValuesOf class CrossClientConstants { companion object { const val HUMAN = "resistance" const val ZOMBIE = "horde" const val UNDECLARED = "undeclared" const val BLANK_ALLEGIANCE_FILTER = "none" val DEAD_ALLEGIANCES = arrayOf(ZOMBIE) const val REWARD_POINT_VALUE = 20 const val QUIZ_TYPE_MULTIPLE_CHOICE = "multipleChoice" const val QUIZ_TYPE_TRUE_FALSE = "boolean" const val QUIZ_TYPE_ORDER = "order" const val QUIZ_TYPE_INFO = "info" const val QUIZ_BLANK_ORDER = -1 fun getAliveColor(context: Context): Int { return ContextCompat.getColor(context, com.app.playhvz.R.color.aliveColor) } fun getDeadColor(context: Context): Int { return ContextCompat.getColor(context, com.app.playhvz.R.color.deadColor) } fun getDeclareQuizRewardCode(playerId: String): String { return getPlayerSpecificRewardCode("declare", playerId) } fun getPlayerSpecificRewardCode(rewardShortName: String, playerId: String): String { return rewardShortName + "-" + playerId + "-" + System.currentTimeMillis() } } }
apache-2.0
b3f6bd26d9420fa872ea7c5266cafffd
34.854545
92
0.689498
4.175847
false
false
false
false
kotlinx/kotlinx.html
buildSrc/src/main/kotlin/kotlinx/html/generate/rules.kt
1
7540
package kotlinx.html.generate import java.util.regex.* val globalSuggestedAttributes = listOf( "a" to "href", "a" to "target", "img" to "src", "script" to "type", "script" to "src", "div" to "class", "span" to "class", "meta" to "name", "meta" to "content", "meta" to "charset", "i" to "class", "input" to "type", "input" to "name", "button" to "name", "link" to "rel", "link" to "href", "link" to "type", "style" to "type", "head" to "-class", "html" to "-class", "link" to "-class", "script" to "-class", "style" to "-class", "meta" to "-class", "title" to "-class" ).groupBy { it.first }.mapValues { it.value.map { it.second } } val tagNamespaces = mapOf( "svg" to "http://www.w3.org/2000/svg" ) val tagsWithCustomizableNamespace = setOf("html") val renames = mapOf( "CommonAttributeGroupFacadePhrasingContent" to "HtmlInlineTag", "CommonAttributeGroupFacadeFlowContent" to "HtmlBlockTag", "CommonAttributeGroupFacadeMetaDataContent" to "HtmlHeadTag", "CommonAttributeGroupFacadeFlowPhrasingContent" to "HtmlBlockInlineTag" ) val tagIgnoreList = setOf( "menu", "menuitem" ) fun Iterable<TagInfo>.filterIgnored() = filter { it.name.toLowerCase() !in tagIgnoreList } val globalSuggestedAttributeNames = setOf("class") val specialTypes = listOf( "*.class" to AttributeType.STRING_SET ).groupBy { it.first }.mapValues { it.value.single().second } fun specialTypeFor(tagName: String, attributeName: String): AttributeType? = specialTypes[tagName + "." + attributeName] ?: specialTypes["*." + attributeName] val wellKnownWords = listOf("span", "class", "enabled?", "edit(able)?", "^on", "encoded?", "form", "type", "run", "href", "drag(gable)?", "over", "mouse", "start(ed)?", "legend", "end(ed)?", "stop", "key", "load(ed)?", "check(ed)?", "time", "ready", "content", "changed?", "click", "play(ing)?", "context", "rows?", "cols?", "group(ed)?", "auto", "list", "field", "data", "block", "scripts?", "item", "area", "length", "colors?", "suspend", "focus", "touch" ).map { it.toRegex(RegexOption.IGNORE_CASE) } val excludeAttributes = listOf("^item$").map { Pattern.compile(it, Pattern.CASE_INSENSITIVE) } fun isAttributeExcluded(name: String) = excludeAttributes.any { it.matcher(name).find() } val excludedEnums = listOf("Lang$").map { it.toRegex(RegexOption.IGNORE_CASE) } fun isEnumExcluded(name: String) = excludedEnums.any { it.containsMatchIn(name) } val contentlessTags = setOf("html", "head", "script", "style") val deprecated = listOf(".*FormMethod#(put|patch|delete)" to "method is not allowed in browsers") .map { it.first.toRegex(RegexOption.IGNORE_CASE) to it.second } fun findEnumDeprecation(attribute: AttributeInfo, value: AttributeEnumValue): String? { return deprecated.firstOrNull { p -> p.first.matches("""${attribute.enumTypeName}#${value.realName}""") }?.second } val knownTagClasses = """ HTMLElement HTMLUnknownElement HTMLHtmlElement HTMLHeadElement HTMLTitleElement HTMLBaseElement HTMLLinkElement HTMLMetaElement HTMLStyleElement HTMLBodyElement HTMLHeadingElement HTMLParagraphElement HTMLHRElement HTMLPreElement HTMLQuoteElement HTMLOListElement HTMLUListElement HTMLLIElement HTMLDListElement HTMLDivElement HTMLAnchorElement HTMLDataElement HTMLTimeElement HTMLSpanElement HTMLBRElement HTMLModElement HTMLIFrameElement HTMLEmbedElement HTMLObjectElement HTMLParamElement HTMLVideoElement HTMLAudioElement HTMLSourceElement HTMLTrackElement HTMLMediaElement HTMLMapElement HTMLAreaElement HTMLTableElement HTMLTableCaptionElement HTMLTableColElement HTMLTableSectionElement HTMLTableRowElement HTMLTableDataCellElement HTMLTableHeaderCellElement HTMLTableCellElement HTMLFormElement HTMLLabelElement HTMLInputElement HTMLButtonElement HTMLSelectElement HTMLDataListElement HTMLOptGroupElement HTMLOptionElement HTMLTextAreaElement HTMLKeygenElement HTMLOutputElement HTMLProgressElement HTMLMeterElement HTMLFieldSetElement HTMLLegendElement HTMLDetailsElement HTMLMenuElement HTMLMenuItemElement HTMLDialogElement HTMLScriptElement HTMLTemplateElement HTMLCanvasElement HTMLAppletElement HTMLMarqueeElement HTMLFrameSetElement HTMLFrameElement HTMLAnchorElement HTMLAreaElement HTMLBodyElement HTMLBRElement HTMLTableCaptionElement HTMLTableColElement HTMLDirectoryElement HTMLDivElement HTMLDListElement HTMLEmbedElement HTMLFontElement HTMLHeadingElement HTMLHRElement HTMLHtmlElement HTMLIFrameElement HTMLImageElement HTMLInputElement HTMLLegendElement HTMLLIElement HTMLLinkElement HTMLMenuElement HTMLMetaElement HTMLObjectElement HTMLOListElement HTMLParagraphElement HTMLParamElement HTMLPreElement HTMLScriptElement HTMLTableElement HTMLTableSectionElement HTMLTableCellElement HTMLTableDataCellElement HTMLTableRowElement HTMLUListElement HTMLElement HTMLUnknownElement HTMLHtmlElement HTMLHeadElement HTMLTitleElement HTMLBaseElement HTMLLinkElement HTMLMetaElement HTMLStyleElement HTMLBodyElement HTMLHeadingElement HTMLParagraphElement HTMLHRElement HTMLPreElement HTMLQuoteElement HTMLOListElement HTMLUListElement HTMLLIElement HTMLDListElement HTMLDivElement HTMLAnchorElement HTMLDataElement HTMLTimeElement HTMLSpanElement HTMLBRElement HTMLModElement HTMLPictureElement HTMLSourceElement HTMLImageElement HTMLIFrameElement HTMLEmbedElement HTMLObjectElement HTMLParamElement HTMLVideoElement HTMLAudioElement HTMLSourceElement HTMLTrackElement HTMLMediaElement HTMLMapElement HTMLAreaElement HTMLTableElement HTMLTableCaptionElement HTMLTableColElement HTMLTableSectionElement HTMLTableRowElement HTMLTableDataCellElement HTMLTableHeaderCellElement HTMLTableCellElement HTMLFormElement HTMLLabelElement HTMLInputElement HTMLButtonElement HTMLSelectElement HTMLDataListElement HTMLOptGroupElement HTMLOptionElement HTMLTextAreaElement HTMLKeygenElement HTMLOutputElement HTMLProgressElement HTMLMeterElement HTMLFieldSetElement HTMLLegendElement HTMLDetailsElement HTMLMenuElement HTMLMenuItemElement HTMLDialogElement HTMLScriptElement HTMLTemplateElement HTMLCanvasElement HTMLAppletElement HTMLMarqueeElement HTMLFrameSetElement HTMLFrameElement HTMLAnchorElement HTMLAreaElement HTMLBodyElement HTMLBRElement HTMLTableCaptionElement HTMLTableColElement HTMLDirectoryElement HTMLDivElement HTMLDListElement HTMLEmbedElement HTMLFontElement HTMLHeadingElement HTMLHRElement HTMLHtmlElement HTMLIFrameElement HTMLImageElement HTMLInputElement HTMLLegendElement HTMLLIElement HTMLLinkElement HTMLMenuElement HTMLMetaElement HTMLObjectElement HTMLOListElement HTMLParagraphElement HTMLParamElement HTMLPreElement HTMLScriptElement HTMLTableElement HTMLTableSectionElement HTMLTableCellElement HTMLTableDataCellElement HTMLTableRowElement HTMLUListElement """.split("\\s+".toRegex()).toSet() val tagReplacements = listOf( "img" to "image", "h\\d" to "heading", "p" to "paragraph", "a" to "anchor", "blockquote" to "quote", "td" to "TableCell", "tr" to "TableRow", "th" to "TableCell", "col" to "TableCol", "colGroup" to "TableCol", "thead" to "TableSection", "tbody" to "TableSection", "tfoot" to "TableSection" ) val attributeReplacements = listOf( "class" to "classes" ).map { Pair(it.first.toRegex(), it.second) }
apache-2.0
9d2fac9be99cd83e9e957558badacdc8
22.419255
117
0.773342
4.296296
false
false
false
false
pedroSG94/rtmp-rtsp-stream-client-java
rtmp/src/main/java/com/pedro/rtmp/utils/socket/TcpSocket.kt
1
2233
/* * Copyright (C) 2022 pedroSG94. * * 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.pedro.rtmp.utils.socket import com.pedro.rtmp.utils.TLSSocketFactory import java.io.* import java.net.InetSocketAddress import java.net.Socket import java.net.SocketAddress import java.security.GeneralSecurityException /** * Created by pedro on 5/4/22. */ class TcpSocket(private val host: String, private val port: Int, private val secured: Boolean): RtmpSocket() { private var socket: Socket = Socket() private var input: BufferedInputStream = BufferedInputStream(ByteArrayInputStream(byteArrayOf())) private var output: OutputStream = ByteArrayOutputStream() override fun getOutStream(): OutputStream = output override fun getInputStream(): InputStream = input override fun flush() { getOutStream().flush() } override fun connect() { if (secured) { try { val socketFactory = TLSSocketFactory() socket = socketFactory.createSocket(host, port) } catch (e: GeneralSecurityException) { throw IOException("Create SSL socket failed: ${e.message}") } } else { socket = Socket() val socketAddress: SocketAddress = InetSocketAddress(host, port) socket.connect(socketAddress, timeout) } output = socket.getOutputStream() input = BufferedInputStream(socket.getInputStream()) socket.soTimeout = timeout } override fun close() { if (socket.isConnected) { socket.getInputStream().close() input.close() output.close() socket.close() } } override fun isConnected(): Boolean = socket.isConnected override fun isReachable(): Boolean = socket.inetAddress?.isReachable(5000) ?: false }
apache-2.0
a9fc69e28b24035b2b9ae7ec13105621
29.60274
110
0.713838
4.529412
false
false
false
false
SevenLines/Celebs-Image-Viewer
src/main/kotlin/theplace/parsers/BaseParser.kt
1
2250
package theplace.parsers import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.reflect.TypeToken import org.apache.commons.io.FileUtils import theplace.parsers.elements.* import java.io.* import java.nio.file.Files import java.nio.file.Paths /** * Created by mk on 03.04.16. */ abstract class BaseParser(var url: String = "", var title: String = "") { protected var _galleries: List<Gallery>? = null open var isAlwaysOneAlbum = false open var isAlwaysOneSubGallery = false open var isAlwaysOnePage = false companion object { @JvmStatic val PARSERS_DIR = Paths.get("./parsers").toAbsolutePath().toString() } init { var path = Paths.get(PARSERS_DIR, "$title.json") if (Files.exists(path)) { var data = FileUtils.readFileToString(path.toFile()) var gson = Gson() var typeToken = object : TypeToken<List<Gallery>>() {}.type _galleries = gson.fromJson(data, typeToken) _galleries?.forEach { it.parser = this } } } val galleries: List<Gallery> get() { if (_galleries == null) { refreshGalleries() } return _galleries?.sortedBy { it.title } as? List<Gallery> ?: emptyList() } fun refreshGalleries() { var path = Paths.get(PARSERS_DIR, "$title.json") _galleries = getGalleries_internal() var gson = GsonBuilder().setPrettyPrinting().create() var data = gson.toJson(_galleries) FileUtils.writeStringToFile(path.toFile(), data) } abstract fun getGalleries_internal(): List<Gallery> abstract fun getAlbums(subGallery: SubGallery): List<GalleryAlbum> abstract fun getAlbumPages(album: GalleryAlbum): List<GalleryAlbumPage> abstract fun getImages(albumPage: GalleryAlbumPage): List<GalleryImage> abstract fun downloadImage(image_url: String): InputStream? open fun getSubGalleries(gallery: Gallery) : List<SubGallery> { return listOf(SubGallery( title="", id=gallery.id, url=gallery.url, gallery=gallery)) } override fun toString(): String { return title } }
mit
8e67f50d537ab7ea9ff3796ce7cad07e
30.704225
87
0.632889
4.43787
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/database/table/CommandTable.kt
1
3909
/* * Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.database.table import android.database.sqlite.SQLiteDatabase import android.provider.BaseColumns import org.andstatus.app.data.DbUtils /** * Command queues * @author [email protected] */ object CommandTable : BaseColumns { val TABLE_NAME: String = "command" val QUEUE_TYPE: String = "queue_type" val COMMAND_CODE: String = "command_code" val CREATED_DATE: String = "command_created_date" val IN_FOREGROUND: String = "in_foreground" val MANUALLY_LAUNCHED: String = "manually_launched" val DESCRIPTION: String = "command_description" /** Timeline attributes * Timeline here may have ID=0 for non-persistent timelines */ val TIMELINE_ID: String = TimelineTable.TIMELINE_ID val TIMELINE_TYPE: String = TimelineTable.TIMELINE_TYPE val ACCOUNT_ID: String = ActorTable.ACCOUNT_ID val ACTOR_ID: String = TimelineTable.ACTOR_ID /** This is used e.g. when a [.ACTOR_ID] is not known */ val USERNAME: String = ActorTable.USERNAME val ORIGIN_ID: String = TimelineTable.ORIGIN_ID val SEARCH_QUERY: String = TimelineTable.SEARCH_QUERY /** This is MessageId mostly, but not only... */ val ITEM_ID: String = "item_id" // Command execution result is below val LAST_EXECUTED_DATE: String = "last_executed_date" val EXECUTION_COUNT: String = "execution_count" val RETRIES_LEFT: String = "retries_left" val NUM_AUTH_EXCEPTIONS: String = "num_auth_exceptions" val NUM_IO_EXCEPTIONS: String = "num_io_exceptions" val NUM_PARSE_EXCEPTIONS: String = "num_parse_exceptions" val ERROR_MESSAGE: String = "error_message" val DOWNLOADED_COUNT: String = "downloaded_count" val PROGRESS_TEXT: String = "progress_text" fun create(db: SQLiteDatabase) { DbUtils.execSQL(db, "CREATE TABLE " + TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY NOT NULL," + QUEUE_TYPE + " TEXT NOT NULL," + COMMAND_CODE + " TEXT NOT NULL," + CREATED_DATE + " INTEGER NOT NULL," + DESCRIPTION + " TEXT," + IN_FOREGROUND + " BOOLEAN NOT NULL DEFAULT 0," + MANUALLY_LAUNCHED + " BOOLEAN NOT NULL DEFAULT 0," + TIMELINE_ID + " INTEGER NOT NULL DEFAULT 0," + TIMELINE_TYPE + " TEXT NOT NULL," + ACCOUNT_ID + " INTEGER NOT NULL DEFAULT 0," + ACTOR_ID + " INTEGER NOT NULL DEFAULT 0," + ORIGIN_ID + " INTEGER NOT NULL DEFAULT 0," + SEARCH_QUERY + " TEXT," + ITEM_ID + " INTEGER NOT NULL DEFAULT 0," + USERNAME + " TEXT," + LAST_EXECUTED_DATE + " INTEGER NOT NULL DEFAULT 0," + EXECUTION_COUNT + " INTEGER NOT NULL DEFAULT 0," + RETRIES_LEFT + " INTEGER NOT NULL DEFAULT 0," + NUM_AUTH_EXCEPTIONS + " INTEGER NOT NULL DEFAULT 0," + NUM_IO_EXCEPTIONS + " INTEGER NOT NULL DEFAULT 0," + NUM_PARSE_EXCEPTIONS + " INTEGER NOT NULL DEFAULT 0," + ERROR_MESSAGE + " TEXT," + DOWNLOADED_COUNT + " INTEGER NOT NULL DEFAULT 0," + PROGRESS_TEXT + " TEXT" + ")") } }
apache-2.0
a40d8885b5bafc507b6c4883f2e9afcb
43.420455
75
0.625224
4.216828
false
false
false
false
danwallach/CalWatch
app/src/main/kotlin/org/dwallach/calwatch2/TimeWrapper.kt
1
8460
/* * CalWatch / CalWatch2 * Copyright © 2014-2022 by Dan S. Wallach * Home page: http://www.cs.rice.edu/~dwallach/calwatch/ * Licensing: http://www.cs.rice.edu/~dwallach/calwatch/licensing.html */ package org.dwallach.calwatch2 import android.os.SystemClock import android.text.format.DateUtils import android.util.Log import java.util.TimeZone import kotlin.math.floor private val TAG = "TimeWrapper" /** * We're asking for the time an awful lot for each different frame we draw, which * is actually having a real impact on performance. That's all centralized here * to fix the problem. */ object TimeWrapper { /** * Offset from GMT time to local time (including daylight savings correction, if necessary), in milliseconds. */ var gmtOffset: Int = 0 private set /** Current time, GMT, in milliseconds. */ var gmtTime: Long = 0 private set // private const val magicOffset: Long = -40 * 60 * 60 * 1000 // 12 hours earlier, for debugging // private const val magicOffset: Long = 25 * 60 * 1000 // 25 minutes later, for debugging private const val magicOffset: Long = 0 // for production use fun update() { gmtTime = System.currentTimeMillis() + magicOffset // TODO: do we want to migrate from java.util.TimeZone to android.icu.util.TimeZone? // - might work better in weird cases // - only supported in Android 7.0 and higher, which would be an issue for Wear 1.0. // (assuming any of them are still around?) val tz = TimeZone.getDefault() gmtOffset = tz.getOffset(gmtTime) // includes DST correction } /** * Helper function: returns the local time (including daylight savings correction, if necessary) in milliseconds. */ val localTime: Long get() = gmtTime + gmtOffset /** If it's currently 12:32pm, this value returned will be 12:00pm. */ val localFloorHour: Long get() = (floor(localTime / 3600000.0) * 3600000.0).toLong() private var localMonthDayCache: String = "" private var localDayOfWeekCache: String = "" private var monthDayCacheTime: Long = 0 private fun updateMonthDayCache() { // Assumption: the day and month and such only change when we hit a new hour, // otherwise we can reuse an old result. // In an early beta of CalWatch, I ran the profiler and discovered that calling // DateUtils.formatDateTime(), which I was doing as part of my onDraw() method, // was a huge time sink, generated a bunch of garbage, etc. Needless to say, // this was an obvious performance optimization. // The nice part about using Android's DateUtils here is that we get a fully // localized result. val newCacheTime = localFloorHour if (newCacheTime != monthDayCacheTime || localMonthDayCache == "") { localMonthDayCache = DateUtils.formatDateTime(null, gmtTime, DateUtils.FORMAT_ABBREV_MONTH or DateUtils.FORMAT_SHOW_DATE) localDayOfWeekCache = DateUtils.formatDateTime(null, gmtTime, DateUtils.FORMAT_SHOW_WEEKDAY) monthDayCacheTime = newCacheTime } } /** Fetches something along the lines of "May 5", but in the current locale. */ fun localMonthDay(): String { updateMonthDayCache() return localMonthDayCache } /** Fetches something along the lines of "Monday", but in the current locale. */ fun localDayOfWeek(): String { updateMonthDayCache() return localDayOfWeekCache } private var frameStartTime: Long = 0 private var lastFPSTime: Long = 0 private var samples = 0 private var minRuntime: Long = 0 private var maxRuntime: Long = 0 private var avgRuntimeAccumulator: Long = 0 /** For performance monitoring: start the counters over again from scratch. */ fun frameReset() { samples = 0 minRuntime = 0 maxRuntime = 0 avgRuntimeAccumulator = 0 lastFPSTime = 0 } /** For performance monitoring: report the FPS counters and reset them immediately. */ fun frameReport() = frameReport(SystemClock.elapsedRealtimeNanos()) /** * Internal version, avoids multiple calls to get the system clock. * @param currentTime */ private fun frameReport(currentTime: Long) { // // Note that the externally visible TimeWrapper APIs report the current time at a resolution // of milliseconds, while our internal framerate measurement and reporting are using the // nanosecond-accurate system clock counter. Thus, for the frame* functions, you'll see // different correction factors. // val elapsedTime = currentTime - lastFPSTime // ns since last time we printed something if (samples > 0 && elapsedTime > 0) { val fps = samples * 1000000000f / elapsedTime // * 10^9 so we're not just computing frames per nanosecond Log.i(TAG, "FPS: %.3f, samples: $samples".format(fps)) Log.i(TAG, "Min/Avg/Max frame render speed (ms): %.3f / %.3f / %.3f".format( minRuntime / 1000000f, +avgRuntimeAccumulator / samples / 1000000f, +maxRuntime / 1000000f ) ) // this waketime percentage is really a lower bound; it's not counting work in the render thread // thread that's outside of the ClockFace rendering methods, and it's also not counting // work that happens on other threads Log.i(TAG, "Waketime: %.3f %%".format(100f * avgRuntimeAccumulator / elapsedTime)) lastFPSTime = 0 } frameReset() } /** For performance monitoring: call this at the beginning of every screen refresh. */ fun frameStart() { frameStartTime = SystemClock.elapsedRealtimeNanos() } /** For performance monitoring: call this at the end of every screen refresh. */ fun frameEnd() { val frameEndTime = SystemClock.elapsedRealtimeNanos() // first sample around, we're not remembering anything, just the time it ended; this gets on smooth footing for subsequent samples if (lastFPSTime == 0L) { lastFPSTime = frameEndTime return } val elapsedTime = frameEndTime - lastFPSTime // ns since last time we printed something val runtime = frameEndTime - frameStartTime // ns since frameStart() called if (samples == 0) { avgRuntimeAccumulator = runtime minRuntime = runtime maxRuntime = runtime } else { if (runtime < minRuntime) minRuntime = runtime if (runtime > maxRuntime) maxRuntime = runtime avgRuntimeAccumulator += runtime } samples++ // if at least one minute has elapsed, then it's time to print all the things if (elapsedTime > 60000000000L) { // 60 * 10^9 nanoseconds: one minute frameReport(frameEndTime) } } init { // do this once at startup because why not? update() } } /** Helper function: convert from seconds to our internal time units (milliseconds). */ val Double.seconds: Long get() = (this * 1000.0).toLong() /** Helper function: convert from minutes to our internal time units (milliseconds). */ val Double.minutes: Long get() = (this * 60000.0).toLong() /** Helper function: convert from hours to our internal time units (milliseconds). */ val Double.hours: Long get() = (this * 3600000.0).toLong() /** Helper function: convert from seconds to our internal time units (milliseconds). */ val Long.seconds: Long get() = (this * 1000L) /** Helper function: convert from minutes to our internal time units (milliseconds). */ val Long.minutes: Long get() = (this * 60000L) /** Helper function: convert from hours to our internal time units (milliseconds). */ val Long.hours: Long get() = (this * 3600000L) /** Helper function: convert from seconds to our internal time units (milliseconds). */ val Int.seconds: Long get() = (this * 1000L) /** Helper function: convert from minutes to our internal time units (milliseconds). */ val Int.minutes: Long get() = (this * 60000L) /** Helper function: convert from hours to our internal time units (milliseconds). */ val Int.hours: Long get() = (this * 3600000L)
gpl-3.0
d3ecadb7dddde452164a855620828331
37.276018
138
0.650313
4.61988
false
false
false
false
android/views-widgets-samples
ViewPager2/app/src/main/java/androidx/viewpager2/integration/testapp/OrientationController.kt
1
2802
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.viewpager2.integration.testapp import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Spinner import androidx.viewpager2.widget.ViewPager2 /** * It configures a spinner to show orientations and sets the orientation of a ViewPager2 * when an orientation is selected. */ class OrientationController(private val viewPager: ViewPager2, private val spinner: Spinner) { fun setUp() { val orientation = viewPager.orientation val adapter = ArrayAdapter(spinner.context, android.R.layout.simple_spinner_item, arrayOf(HORIZONTAL, VERTICAL)) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinner.adapter = adapter val initialPosition = adapter.getPosition(orientationToString(orientation)) if (initialPosition >= 0) { spinner.setSelection(initialPosition) } spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>, view: View?, position: Int, id: Long ) { viewPager.orientation = stringToOrientation(parent.selectedItem.toString()) } override fun onNothingSelected(adapterView: AdapterView<*>) {} } } private fun orientationToString(orientation: Int): String { return when (orientation) { ViewPager2.ORIENTATION_HORIZONTAL -> HORIZONTAL ViewPager2.ORIENTATION_VERTICAL -> VERTICAL else -> throw IllegalArgumentException("Orientation $orientation doesn't exist") } } internal fun stringToOrientation(string: String): Int { return when (string) { HORIZONTAL -> ViewPager2.ORIENTATION_HORIZONTAL VERTICAL -> ViewPager2.ORIENTATION_VERTICAL else -> throw IllegalArgumentException("Orientation $string doesn't exist") } } companion object { private const val HORIZONTAL = "horizontal" private const val VERTICAL = "vertical" } }
apache-2.0
631dd09836ac2de56f99cd35006a534c
35.881579
94
0.68237
5.169742
false
false
false
false
inorichi/tachiyomi-extensions
src/th/nekopost/src/eu/kanade/tachiyomi/extension/th/nekopost/APITypes.kt
1
4334
package eu.kanade.tachiyomi.extension.th.nekopost data class RawMangaData( val no_new_chapter: String, val nc_chapter_id: String, val np_project_id: String, val np_name: String, val np_name_link: String, val nc_chapter_no: String, val nc_chapter_name: String, val nc_chapter_cover: String, val nc_provider: String, val np_group_dir: String, val nc_created_date: String, ) data class RawMangaDataList( val code: String, val listItem: Array<RawMangaData>? ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as RawMangaDataList if (code != other.code) return false if (listItem != null) { if (other.listItem == null) return false if (!listItem.contentEquals(other.listItem)) return false } else if (other.listItem != null) return false return true } override fun hashCode(): Int { var result = code.hashCode() result = 31 * result + (listItem?.contentHashCode() ?: 0) return result } } data class RawProjectData( val np_status: String, val np_project_id: String, val np_type: String, val np_name: String, val np_name_link: String, val np_flag_mature: String, val np_info: String, val np_view: String, val np_comment: String, val np_created_date: String, val np_updated_date: String, val author_name: String, val artist_name: String, val np_web: String, val np_licenced_by: String, ) data class RawProjectGenre( val npc_name: String, val npc_name_link: String, ) data class RawChapterData( val nc_chapter_id: String, val nc_chapter_no: String, val nc_chapter_name: String, val nc_provider: String, val cu_displayname: String, val nc_created_date: String, val nc_data_file: String, val nc_owner_id: String, ) data class RawMangaDetailedData( val code: String, val projectInfo: RawProjectData, val projectCategoryUsed: Array<RawProjectGenre>?, val projectChapterList: Array<RawChapterData>, ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as RawMangaDetailedData if (code != other.code) return false if (projectInfo != other.projectInfo) return false if (projectCategoryUsed != null) { if (other.projectCategoryUsed == null) return false if (!projectCategoryUsed.contentEquals(other.projectCategoryUsed)) return false } else if (other.projectCategoryUsed != null) return false if (!projectChapterList.contentEquals(other.projectChapterList)) return false return true } override fun hashCode(): Int { var result = code.hashCode() result = 31 * result + projectInfo.hashCode() result = 31 * result + (projectCategoryUsed?.contentHashCode() ?: 0) result = 31 * result + projectChapterList.contentHashCode() return result } } data class RawPageData( val pageNo: Int, val fileName: String, val width: Int, val height: Int, val pageCount: Int ) data class RawChapterDetailedData( val projectId: String, val chapterId: Int, val chapterNo: String, val pageItem: Array<RawPageData>, ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as RawChapterDetailedData if (projectId != other.projectId) return false if (chapterId != other.chapterId) return false if (chapterNo != other.chapterNo) return false if (!pageItem.contentEquals(other.pageItem)) return false return true } override fun hashCode(): Int { var result = projectId.hashCode() result = 31 * result + chapterId result = 31 * result + chapterNo.hashCode() result = 31 * result + pageItem.contentHashCode() return result } } data class MangaNameList( val np_project_id: String, val np_name: String, val np_name_link: String, val np_type: String, val np_status: String, val np_no_chapter: String, )
apache-2.0
4ed966b42b39478a3a1bf4dee7eebd7a
27.326797
91
0.643516
4.058052
false
false
false
false
ohmae/DmsExplorer
mobile/src/main/java/net/mm2d/dmsexplorer/Const.kt
1
1232
/* * Copyright (c) 2016 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.dmsexplorer /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ object Const { const val PACKAGE_NAME = "net.mm2d.dmsexplorer" // Broadcast private const val PREFIX = "$PACKAGE_NAME." const val ACTION_PLAY = PREFIX + "ACTION_PLAY" const val ACTION_NEXT = PREFIX + "ACTION_NEXT" const val ACTION_PREV = PREFIX + "ACTION_PREV" const val KEY_HAS_TOOLBAR_COLOR = "KEY_HAS_TOOLBAR_COLOR" const val KEY_TOOLBAR_EXPANDED_COLOR = "KEY_TOOLBAR_EXPANDED_COLOR" const val KEY_TOOLBAR_COLLAPSED_COLOR = "KEY_TOOLBAR_COLLAPSED_COLOR" const val SHARE_ELEMENT_NAME_DEVICE_ICON = "SHARE_ELEMENT_NAME_DEVICE_ICON" const val URL_GITHUB_PROJECT = "https://github.com/ohmae/dms-explorer" const val URL_PRIVACY_POLICY = "https://github.com/ohmae/dms-explorer/blob/develop/PRIVACY-POLICY.md" const val URL_OPEN_SOURCE_LICENSE = "file:///android_asset/license.html" const val REQUEST_CODE_ACTION_PLAY = 1 const val REQUEST_CODE_ACTION_NEXT = 2 const val REQUEST_CODE_ACTION_PREVIOUS = 3 }
mit
0e70efea349563d87d2a5ffde9f6a017
32.777778
79
0.698191
3.435028
false
false
false
false
raxden/square
sample/src/main/java/com/raxdenstudios/square/sample/commons/FragmentBottomNavigationActivity.kt
2
3684
package com.raxdenstudios.square.sample.commons import android.os.Bundle import android.support.design.widget.BottomNavigationView import android.support.v4.app.Fragment import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.View import com.raxdenstudios.square.interceptor.Interceptor import com.raxdenstudios.square.interceptor.commons.autoinflatelayout.AutoInflateLayoutInterceptor import com.raxdenstudios.square.interceptor.commons.autoinflatelayout.HasAutoInflateLayoutInterceptor import com.raxdenstudios.square.interceptor.commons.fragmentbottomnavigation.HasFragmentBottomNavigationInterceptor import com.raxdenstudios.square.interceptor.commons.toolbar.HasToolbarInterceptor import com.raxdenstudios.square.interceptor.commons.toolbar.ToolbarInterceptor import com.raxdenstudios.square.sample.R import kotlinx.android.synthetic.main.fragment_bottom_navigation_activity.* class FragmentBottomNavigationActivity : AppCompatActivity(), HasAutoInflateLayoutInterceptor, HasToolbarInterceptor, HasFragmentBottomNavigationInterceptor<Fragment> { private var mAutoInflateLayoutInterceptor: AutoInflateLayoutInterceptor? = null private var mToolbarInterceptor: ToolbarInterceptor? = null var mContentView: View? = null var mToolbarView: Toolbar? = null var mBottomNavigationView: BottomNavigationView? = null var mFirstFragment: Fragment? = null var mSecondFragment: Fragment? = null var mThirdFragment: Fragment? = null // ======== HasInflateLayoutInterceptor ======================================================== override fun onContentViewCreated(view: View) { mContentView = view } // ======== HasToolbarInterceptor ============================================================== override fun onCreateToolbarView(): Toolbar = toolbar_view override fun onToolbarViewCreated(toolbar: Toolbar) { mToolbarView = toolbar } // ======== HasFragmentBottomNavigationInterceptor ===================================================== override fun onCreateBottomNavigationView(): BottomNavigationView = bottom_navigation_view override fun onBottomNavigationViewCreated(bottomNavigationView: BottomNavigationView) { mBottomNavigationView = bottomNavigationView } override fun onLoadFragmentContainer(): View = container_view override fun onCreateFragment(itemId: Int): Fragment = when (itemId) { R.id.navigation_home -> InjectedFragment.newInstance(Bundle().apply { putString("title", "Fragment Home") }) R.id.navigation_dashboard -> InjectedFragment.newInstance(Bundle().apply { putString("title", "Fragment Dashboard") }) R.id.navigation_notifications -> InjectedFragment.newInstance(Bundle().apply { putString("title", "Fragment Notifications") }) else -> InjectedFragment.newInstance(Bundle().apply { putString("title", "Fragment Home") }) } override fun onFragmentLoaded(itemId: Int, fragment: Fragment) { when (itemId) { R.id.navigation_home -> mFirstFragment = fragment R.id.navigation_dashboard -> mSecondFragment = fragment R.id.navigation_notifications -> mThirdFragment = fragment } } override fun onBottomNavigationItemSelected(itemId: Int) { } // ============================================================================================= override fun onInterceptorCreated(interceptor: Interceptor) { mAutoInflateLayoutInterceptor = interceptor as? AutoInflateLayoutInterceptor mToolbarInterceptor = interceptor as? ToolbarInterceptor } }
apache-2.0
b99dd7a4e47eb73b90087d66c08a2162
43.939024
134
0.707655
5.564955
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/api/app/model/TUMCabeVerification.kt
1
1108
package de.tum.`in`.tumcampusapp.api.app.model import android.content.Context import de.tum.`in`.tumcampusapp.api.app.AuthenticationManager import de.tum.`in`.tumcampusapp.api.app.exception.NoPrivateKey import de.tum.`in`.tumcampusapp.utils.Utils import java.math.BigInteger import java.security.SecureRandom import java.util.* data class TUMCabeVerification( val signature: String, val date: String, val rand: String, val device: String, var data: Any? = null ) { companion object { @JvmStatic fun create(context: Context, data: Any? = null): TUMCabeVerification? { val date = Date().toString() val rand = BigInteger(130, SecureRandom()).toString(32) val deviceID = AuthenticationManager.getDeviceID(context) val signature = try { AuthenticationManager(context).sign(date + rand + deviceID) } catch (e: NoPrivateKey) { Utils.log(e) return null } return TUMCabeVerification(signature, date, rand, deviceID, data) } } }
gpl-3.0
cb612dc8ac05b4eb9dc9f120054bec63
28.972973
79
0.644404
4.504065
false
false
false
false
westnordost/osmagent
app/src/main/java/de/westnordost/streetcomplete/quests/bikeway/Cycleway.kt
1
2938
package de.westnordost.streetcomplete.quests.bikeway import de.westnordost.streetcomplete.R enum class Cycleway(private val iconResId: Int, private val iconResIdLeft: Int, val nameResId: Int) { // some kind of cycle lane, not specified if with continuous or dashed lane markings LANE_UNSPECIFIED (R.drawable.ic_cycleway_lane, R.drawable.ic_cycleway_lane_l, R.string.quest_cycleway_value_lane), // a.k.a. exclusive lane, dedicated lane or simply (proper) lane EXCLUSIVE_LANE (R.drawable.ic_cycleway_lane, R.drawable.ic_cycleway_lane_l, R.string.quest_cycleway_value_lane ), // a.k.a. protective lane, multipurpose lane, soft lane or recommended lane ADVISORY_LANE (R.drawable.ic_cycleway_shared_lane, R.drawable.ic_cycleway_shared_lane_l,R.string.quest_cycleway_value_lane_soft), // slight difference to dashed lane only made in NL, BE SUGGESTION_LANE (R.drawable.ic_cycleway_suggestion_lane, R.drawable.ic_cycleway_suggestion_lane, R.string.quest_cycleway_value_suggestion_lane), TRACK (R.drawable.ic_cycleway_track, R.drawable.ic_cycleway_track_l, R.string.quest_cycleway_value_track ), NONE (R.drawable.ic_cycleway_none, R.drawable.ic_cycleway_none, R.string.quest_cycleway_value_none ), NONE_NO_ONEWAY (R.drawable.ic_cycleway_pictograms, R.drawable.ic_cycleway_pictograms_l, R.string.quest_cycleway_value_none_but_no_oneway ), PICTOGRAMS (R.drawable.ic_cycleway_pictograms, R.drawable.ic_cycleway_pictograms_l, R.string.quest_cycleway_value_shared ), SIDEWALK_EXPLICIT (R.drawable.ic_cycleway_sidewalk_explicit, R.drawable.ic_cycleway_sidewalk_explicit_l, R.string.quest_cycleway_value_sidewalk ), SIDEWALK_OK (R.drawable.ic_cycleway_sidewalk, R.drawable.ic_cycleway_sidewalk, R.string.quest_cycleway_value_sidewalk_allowed), DUAL_LANE (R.drawable.ic_cycleway_lane_dual, R.drawable.ic_cycleway_lane_dual_l, R.string.quest_cycleway_value_lane_dual ), DUAL_TRACK (R.drawable.ic_cycleway_track_dual, R.drawable.ic_cycleway_track_dual_l, R.string.quest_cycleway_value_track_dual ), BUSWAY (R.drawable.ic_cycleway_bus_lane, R.drawable.ic_cycleway_bus_lane_l, R.string.quest_cycleway_value_bus_lane ); val isOnSidewalk get() = this == SIDEWALK_EXPLICIT || this == SIDEWALK_OK fun getIconResId(isLeftHandTraffic: Boolean) = if (isLeftHandTraffic) iconResIdLeft else iconResId companion object { // some of the values defined above are special values that should not be visible by default val displayValues = listOf( EXCLUSIVE_LANE, ADVISORY_LANE, TRACK, NONE, PICTOGRAMS, BUSWAY, SIDEWALK_EXPLICIT, SIDEWALK_OK, DUAL_LANE, DUAL_TRACK ) } }
gpl-3.0
64f8bc1bf866f75d72910d42d4c7bd37
64.288889
151
0.681756
3.677096
false
false
false
false
MrSugarCaney/DirtyArrows
src/main/kotlin/nl/sugcube/dirtyarrows/region/Region.kt
1
5837
package nl.sugcube.dirtyarrows.region import org.bukkit.Location import kotlin.math.max import kotlin.math.min /** * Represents a rectangluar DirtyArrows protection region. * * @author SugarCaney */ class Region constructor( /** * The first corner of the region. */ private var location1: Location, /** * The second corner of the region. */ private var location2: Location, /** * The name for the region. Contains only A-Z, a-z, 0-9 and _. */ val name: String ) { init { require(name.matches(NAME_REGEX)) { "Invalid name: '$name'" } } /** * Sets a corner location of the region. * * @param location * The location value. * @param locationNumber * `1` for location 1, and `2` for location 2. */ fun setLocation(location: Location, locationNumber: Int) = when (locationNumber) { 1 -> location1 = location 2 -> location2 = location else -> error("Invalid location number '$locationNumber', only 1|2 allowed.") } /** * Get a corner location of the region. * * @param locationNumber * `1` for location 1, and `2` for location 2. */ fun getLocation(locationNumber: Int) = when (locationNumber) { 1 -> location1 2 -> location2 else -> error("Invalid location number '$locationNumber', only 1|2 allowed.") } /** * Location 1. */ operator fun component1() = location1 /** * Location 2. */ operator fun component2() = location2 companion object { /** * Regex that matches correctly against a valid name. */ val NAME_REGEX = Regex("^[A-Za-z\\d_]+$") } } /** * Checks whether the given location is within the region, expanded with a certain margin. * Only checks the XZ plane, ignores height. * * @param location * The location to check if it lies within the region (+ margin). * @param margin * The distance (in blocks) outside of the region that should still evaluate `true`. * @return `true` if the location lies within the region + margin, `false` otherwise. */ fun Region.isWithinXZMargin(location: Location, margin: Double): Boolean { val (position1, position2) = this // Only return `true` when in the same world. if (position1.world != position2.world) return false if (location.world != position1.world) return false var p1x = position1.x var p1z = position1.z var p2x = position2.x var p2z = position2.z if (p1x <= p2x) { p1x -= margin p2x += margin } else { p1x += margin p2x -= margin } if (p1z <= p2z) { p1z -= margin p2z += margin } else { p1z += margin p2z -= margin } if (p2x <= location.x && location.x < p1x || p1x <= location.x && location.x < p2x) { if (p2z <= location.z && location.z < p1z || p1z <= location.z && location.z < p2z) { return true } } return false } /** * Checks whether the given location is within the region, expanded with a certain margin. * * @param location * The location to check if it lies within the region (+ margin). * @param margin * The distance (in blocks) outside of the region that should still evaluate `true`. * @return `true` if the location lies within the region + margin, `false` otherwise. */ fun Region.isWithinMargin(location: Location, margin: Double): Boolean { val (position1, position2) = this // Only return `true` when in the same world. if (position1.world != position2.world) return false if (location.world != position1.world) return false var p1x = position1.x var p1y = position1.y var p1z = position1.z var p2x = position2.x var p2y = position2.y var p2z = position2.z if (p1x <= p2x) { p1x -= margin p2x += margin } else { p1x += margin p2x -= margin } if (p1y <= p2y) { p1y -= margin p2y += margin } else { p1y += margin p2y -= margin } if (p1z <= p2z) { p1z -= margin p2z += margin } else { p1z += margin p2z -= margin } if (p2x <= location.x && location.x < p1x || p1x <= location.x && location.x < p2x) { if (p2y <= location.y && location.y < p1y || p1y <= location.y && location.y < p2y) { if (p2z <= location.z && location.z < p1z || p1z <= location.z && location.z < p2z) { return true } } } return false } /** * Checks whether the given location is within this region. * * @param location * The location to check if it lies within the region. * @return `true` if the location lies within the region, `false` otherwise. */ fun Region.isWithinRegion(location: Location) = isWithinMargin(location, margin = 0.0) /** * @return All 8 corners of the region. */ fun Region.allCorners(): List<Location> { val world = getLocation(1).world val minX = min(getLocation(1).x, getLocation(2).x) val minY = min(getLocation(1).y, getLocation(2).y) val minZ = min(getLocation(1).z, getLocation(2).z) val maxX = max(getLocation(1).x, getLocation(2).x) val maxY = max(getLocation(1).y, getLocation(2).y) val maxZ = max(getLocation(1).z, getLocation(2).z) return listOf( Location(world, minX, minY, minZ), Location(world, maxX, minY, minZ), Location(world, maxX, minY, maxZ), Location(world, minX, minY, maxZ), Location(world, minX, maxY, minZ), Location(world, maxX, maxY, minZ), Location(world, maxX, maxY, maxZ), Location(world, minX, maxY, maxZ), ) }
gpl-3.0
0a1ceac077d0d5741ea26f98933d51aa
25.536364
97
0.583348
3.634496
false
false
false
false