repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
czyzby/ktx | actors/src/main/kotlin/ktx/actors/actors.kt | 2 | 4758 | package ktx.actors
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.Group
import com.badlogic.gdx.scenes.scene2d.Stage
/**
* Min value of alpha in libGDX Color instances.
*/
const val MIN_ALPHA = 0f
/**
* Max value of alpha in libGDX Color instances.
*/
const val MAX_ALPHA = 1f
/**
* @return true if the actor is not null and is currently shown on a [Stage].
*/
fun Actor?.isShown(): Boolean = this != null && this.stage != null
/**
* Utility method overload. Allows to set actor's position with ints rather than floats.
* @param x actor's position on X axis in stage units.
* @param y actor's position on Y axis in stage units.
*/
fun Actor.setPosition(x: Int, y: Int) = setPosition(x.toFloat(), y.toFloat())
/**
* Modifies this actor position to be centered within the passed bounds. Uses actor's size to calculate the offsets.
* @param width total available width in stage units. Defaults to stage width.
* @param height total available height in stage units. Defaults to stage height.
* @param normalize if true, position will be converted to ints. Defaults to true
*/
fun Actor.centerPosition(width: Float = this.stage.width, height: Float = this.stage.height, normalize: Boolean = true) {
val x = (width - this.width) / 2f
val y = (height - this.height) / 2f
if (normalize) {
this.setPosition(x.toInt(), y.toInt())
} else {
this.setPosition(x, y)
}
}
/**
* @param actor might be stored in this group.
* @return true if this group is the direct parent of the passed actor.
*/
operator fun Group.contains(actor: Actor): Boolean = actor.parent === this
/**
* Alias for [Group.addActor] method. Allows to add actors to the group with += operator.
* @param actor will be added to the group.
*/
operator fun Group.plusAssign(actor: Actor) = addActor(actor)
/**
* Alias for [Group.removeActor] method. Allows to remove actors from the group with -= operator.
* @param actor will be removed from the group.
*/
operator fun Group.minusAssign(actor: Actor) {
removeActor(actor)
}
/**
* @param actor might be on this stage.
* @return true if the passed actor's stage equals this.
*/
operator fun Stage.contains(actor: Actor): Boolean = actor.stage === this
/**
* Alias for [Stage.addActor] method. Allows to add actors to the stage with += operator.
* @param actor will be added to stage.
*/
operator fun Stage.plusAssign(actor: Actor) = addActor(actor)
/**
* Removes actors from root group of the stage. Allows to remove actors from the stage with -= operator.
* If actor is not added directly to the stage this method might have no effect.
* @param actor will be removed if it is added directly to the stage.
*/
operator fun Stage.minusAssign(actor: Actor) {
root.removeActor(actor)
}
/**
* Checks this actor's position and size and makes sure that it is kept within its parent actor bounds (or [Stage]).
*/
fun Actor.keepWithinParent() {
val parentWidth: Float
val parentHeight: Float
if (this.stage != null && this.parent === this.stage.root) {
parentWidth = this.stage.width
parentHeight = this.stage.height
} else {
parentWidth = this.parent.width
parentHeight = this.parent.height
}
if (this.x < 0f) this.x = 0f
if (this.right > parentWidth) this.x = parentWidth - this.width
if (this.y < 0f) this.y = 0f
if (this.top > parentHeight) this.y = parentHeight - this.height
}
/**
* Links to this actor's [Actor.color] instance. Allows to easily modify alpha color value.
*/
inline var Actor.alpha: Float
get() = this.color.a
set(value) {
this.color.a = value
}
/**
* Links to this [Stage.root].color instance. Allows to easily modify alpha color value of stage.
*/
inline var Stage.alpha: Float
get() = this.root.color.a
set(value) {
this.root.color.a = value
}
/**
* Modifies current stage keyboard focus if this actor is currently shown.
* @param focus if true, will set current keyboard focus to this actor. If false and the actor is currently focused,
* will clear keyboard focus of actor's stage.
*/
fun Actor.setKeyboardFocus(focus: Boolean = true) {
if (this.stage != null) {
if (focus) {
stage.keyboardFocus = this
} else if (stage.keyboardFocus === this) {
stage.keyboardFocus = null
}
}
}
/**
* Modifies current stage scroll focus if this actor is currently shown.
* @param focus if true, will set current scroll focus to this actor. If false and the actor is currently focused,
* will clear scroll focus of actor's stage.
*/
fun Actor.setScrollFocus(focus: Boolean = true) {
if (this.stage != null) {
if (focus) {
stage.scrollFocus = this
} else if (stage.scrollFocus === this) {
stage.scrollFocus = null
}
}
}
| cc0-1.0 | 7d354ae06d7bf022777a8e34f9eecf11 | 30.72 | 121 | 0.69546 | 3.685515 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/lexer/XQueryTokenType.kt | 1 | 24109 | /*
* Copyright (C) 2016-2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xquery.lexer
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import uk.co.reecedunn.intellij.plugin.xpath.lexer.IKeywordOrNCNameType
import uk.co.reecedunn.intellij.plugin.xpath.lexer.XPathTokenType
import uk.co.reecedunn.intellij.plugin.xquery.lang.XQuery
import xqt.platform.intellij.ft.XPathFTTokenProvider
import xqt.platform.intellij.lexer.token.INCNameTokenType
import xqt.platform.intellij.marklogic.MarkLogicXPathTokenProvider
import xqt.platform.intellij.xpath.XPathTokenProvider
@Suppress("Reformat")
object XQueryTokenType {
// region Multi-Token Symbols
val XML_COMMENT: IElementType = IElementType("XQUERY_XML_COMMENT_TOKEN", XQuery) // XQuery 1.0
val XML_COMMENT_START_TAG: IElementType = IElementType("XQUERY_XML_COMMENT_START_TAG_TOKEN", XQuery) // XQuery 1.0
val XML_COMMENT_END_TAG: IElementType = IElementType("XQUERY_XML_COMMENT_END_TAG_TOKEN", XQuery) // XQuery 1.0
val PROCESSING_INSTRUCTION_BEGIN: IElementType = IElementType("XQUERY_PROCESSING_INSTRUCTION_BEGIN_TOKEN", XQuery) // XQuery 1.0
val PROCESSING_INSTRUCTION_END: IElementType = IElementType("XQUERY_PROCESSING_INSTRUCTION_END_TOKEN", XQuery) // XQuery 1.0
val PROCESSING_INSTRUCTION_CONTENTS: IElementType = IElementType("XQUERY_PROCESSING_INSTRUCTION_CONTENTS_TOKEN", XQuery) // XQuery 1.0
val DIRELEM_MAYBE_OPEN_XML_TAG: IElementType = IElementType("XQUERY_DIRELEM_MAYBE_OPEN_XML_TAG_TOKEN", XQuery) // XQuery 1.0
val DIRELEM_OPEN_XML_TAG: IElementType = IElementType("XQUERY_DIRELEM_OPEN_XML_TAG_TOKEN", XQuery) // XQuery 1.0
val OPEN_XML_TAG: IElementType = IElementType("XQUERY_OPEN_XML_TAG_TOKEN", XQuery) // XQuery 1.0
val END_XML_TAG: IElementType = IElementType("XQUERY_END_XML_TAG_TOKEN", XQuery) // XQuery 1.0
val CLOSE_XML_TAG: IElementType = IElementType("XQUERY_CLOSE_XML_TAG_TOKEN", XQuery) // XQuery 1.0
val SELF_CLOSING_XML_TAG: IElementType = IElementType("XQUERY_SELF_CLOSING_XML_TAG_TOKEN", XQuery) // XQuery 1.0
val XML_ELEMENT_CONTENTS: IElementType = IElementType("XQUERY_XML_ELEMENT_CONTENTS_TOKEN", XQuery) // XQuery 1.0
val XML_EQUAL: IElementType = IElementType("XQUERY_XML_EQUAL_TOKEN", XQuery) // XQuery 1.0
val XML_WHITE_SPACE: IElementType = IElementType("XQUERY_XML_WHITE_SPACE_TOKEN", XQuery) // XQuery 1.0
val XML_TAG_NCNAME: IElementType = INCNameTokenType("XQUERY_XML_TAG_NCNAME_TOKEN", XQuery) // XQuery 1.0
val XML_TAG_QNAME_SEPARATOR: IElementType = IElementType("XQUERY_XML_TAG_QNAME_SEPARATOR_TOKEN", XQuery) // XQuery 1.0
val XML_ATTRIBUTE_NCNAME: IElementType = INCNameTokenType("XQUERY_XML_ATTRIBUTE_NCNAME_TOKEN", XQuery) // XQuery 1.0
val XML_ATTRIBUTE_XMLNS: IElementType = IKeywordOrNCNameType("XQUERY_XML_ATTRIBUTE_KEYWORD_OR_NCNAME_XMLNS_TOKEN", XQuery) // XQuery 1.0
val XML_ATTRIBUTE_QNAME_SEPARATOR: IElementType = IElementType("XQUERY_XML_ATTRIBUTE_QNAME_SEPARATOR_TOKEN", XQuery) // XQuery 1.0
val XML_PI_TARGET_NCNAME: IElementType = INCNameTokenType("XQUERY_XML_PI_TARGET_NCNAME_TOKEN", XQuery) // XQuery 1.0
val XML_ATTRIBUTE_VALUE_START: IElementType = IElementType("XQUERY_XML_ATTRIBUTE_VALUE_START_TOKEN", XQuery) // XQuery 1.0
val XML_ATTRIBUTE_VALUE_CONTENTS: IElementType = IElementType("XQUERY_XML_ATTRIBUTE_VALUE_CONTENTS_TOKEN", XQuery) // XQuery 1.0
val XML_ATTRIBUTE_VALUE_END: IElementType = IElementType("XQUERY_XML_ATTRIBUTE_VALUE_END_TOKEN", XQuery) // XQuery 1.0
val XML_ESCAPED_CHARACTER: IElementType = IElementType("XQUERY_XML_ESCAPED_CHARACTER_TOKEN", XQuery) // XQuery 1.0
val XML_CHARACTER_REFERENCE: IElementType = IElementType("XQUERY_XML_CHARACTER_REFERENCE_TOKEN", XQuery) // XQuery 1.0
val XML_PREDEFINED_ENTITY_REFERENCE: IElementType = IElementType("XQUERY_XML_PREDEFINED_ENTITY_REFERENCE_TOKEN", XQuery) // XQuery 1.0
val XML_PARTIAL_ENTITY_REFERENCE: IElementType = IElementType("XQUERY_XML_PARTIAL_ENTITY_REFERENCE_TOKEN", XQuery) // XQuery 1.0
val XML_EMPTY_ENTITY_REFERENCE: IElementType = IElementType("XQUERY_XML_EMPTY_ENTITY_REFERENCE_TOKEN", XQuery) // XQuery 1.0
val CDATA_SECTION: IElementType = IElementType("XQUERY_CDATA_SECTION_TOKEN", XQuery) // XQuery 1.0
val CDATA_SECTION_START_TAG: IElementType = IElementType("XQUERY_CDATA_SECTION_START_TAG_TOKEN", XQuery) // XQuery 1.0
val CDATA_SECTION_END_TAG: IElementType = IElementType("XQUERY_CDATA_SECTION_END_TAG_TOKEN", XQuery) // XQuery 1.0
val STRING_CONSTRUCTOR_START: IElementType = IElementType("XQUERY_STRING_CONSTRUCTOR_START_TOKEN", XQuery) // XQuery 3.1
val STRING_CONSTRUCTOR_CONTENTS: IElementType = IElementType("XQUERY_STRING_CONSTRUCTOR_CONTENTS_TOKEN", XQuery) // XQuery 3.1
val STRING_CONSTRUCTOR_END: IElementType = IElementType("XQUERY_STRING_CONSTRUCTOR_END_TOKEN", XQuery) // XQuery 3.1
val STRING_INTERPOLATION_OPEN: IElementType = IElementType("XQUERY_STRING_INTERPOLATION_OPEN_TOKEN", XQuery) // XQuery 3.1
val STRING_INTERPOLATION_CLOSE: IElementType = IElementType("XQUERY_STRING_INTERPOLATION_CLOSE_TOKEN", XQuery) // XQuery 3.1
// endregion
// region Symbols
val ANNOTATION_INDICATOR: IElementType = IElementType("XQUERY_ANNOTATION_INDICATOR_TOKEN", XQuery) // XQuery 3.0
val SEPARATOR: IElementType = IElementType("XQUERY_SEPARATOR_TOKEN", XQuery) // XQuery 1.0
// endregion
// region Keywords
val K_AFTER: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_AFTER", XQuery) // Update Facility 1.0
val K_ALLOWING: IKeywordOrNCNameType = IKeywordOrNCNameType("XPATH_KEYWORD_OR_NCNAME_ALLOWING", XQuery) // XQuery 3.0
val K_ASCENDING: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_ASCENDING", XQuery) // XQuery 1.0
val K_ASSIGNABLE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_ASSIGNABLE", XQuery) // Scripting Extension 1.0
val K_BASE_URI: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_BASE_URI", XQuery) // XQuery 1.0
val K_BEFORE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_BEFORE", XQuery) // Update Facility 1.0
val K_BLOCK: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_BLOCK", XQuery) // Scripting Extension 1.0
val K_BOUNDARY_SPACE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_BOUNDARY_SPACE", XQuery) // XQuery 1.0
val K_BY: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_BY", XQuery) // XQuery 1.0
val K_CATCH: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_CATCH", XQuery) // XQuery 3.0
val K_COLLATION: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_COLLATION", XQuery) // XQuery 1.0
val K_CONSTRUCTION: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_CONSTRUCTION", XQuery) // XQuery 1.0
val K_CONTEXT: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_CONTEXT", XQuery) // XQuery 3.0
val K_COPY: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_COPY", XQuery) // Update Facility 1.0
val K_COPY_NAMESPACES: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_COPY_NAMESPACES", XQuery) // XQuery 1.0
val K_COUNT: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_COUNT", XQuery) // XQuery 3.0
val K_DECIMAL_FORMAT: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_DECIMAL_FORMAT", XQuery) // XQuery 3.0
val K_DECIMAL_SEPARATOR: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_DECIMAL_SEPARATOR", XQuery) // XQuery 3.0
val K_DECLARE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_DECLARE", XQuery) // XQuery 1.0
val K_DELETE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_DELETE", XQuery) // Update Facility 1.0
val K_DESCENDING: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_DESCENDING", XQuery) // XQuery 1.0
val K_DIGIT: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_DIGIT", XQuery) // XQuery 3.0
val K_DOCUMENT: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_DOCUMENT", XQuery) // XQuery 1.0
val K_ENCODING: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_ENCODING", XQuery) // XQuery 1.0
val K_EXIT: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_EXIT", XQuery) // Scripting Extension 1.0
val K_EXPONENT_SEPARATOR: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_EXPONENT_SEPARATOR", XQuery) // XQuery 3.1
val K_EXTERNAL: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_EXTERNAL", XQuery) // XQuery 1.0
val K_FIRST: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_FIRST", XQuery) // Update Facility 1.0
val K_FT_OPTION: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_FT_OPTION", XQuery) // Full Text 1.0
val K_FULL: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_FULL", XQuery) // MarkLogic 6.0
val K_FUZZY: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_FUZZY", XQuery) // BaseX 6.1
val K_GREATEST: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_GREATEST", XQuery) // XQuery 1.0
val K_GROUP: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_GROUP", XQuery) // XQuery 3.0
val K_GROUPING_SEPARATOR: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_GROUPING_SEPARATOR", XQuery) // XQuery 3.0
val K_IMPORT: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_IMPORT", XQuery) // XQuery 1.0
val K_INFINITY: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_INFINITY", XQuery) // XQuery 3.0
val K_INHERIT: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_INHERIT", XQuery) // XQuery 1.0
val K_INSERT: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_INSERT", XQuery) // Update Facility 1.0
val K_INTO: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_INTO", XQuery) // Update Facility 1.0
val K_INVOKE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_INVOKE", XQuery) // Update Facility 3.0
val K_ITEM_TYPE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_ITEM_TYPE", XQuery) // XQuery 4.0 ED
val K_LAST: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_LAST", XQuery) // Update Facility 1.0
val K_LAX: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_LAX", XQuery) // XQuery 1.0
val K_MINUS_SIGN: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_MINUS_SIGN", XQuery) // XQuery 3.0
val K_MODIFY: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_MODIFY", XQuery) // Update Facility 1.0
val K_MODULE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_MODULE", XQuery) // XQuery 1.0
val K_NAN: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_NAN", XQuery) // XQuery 3.0
val K_NEXT: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_NEXT", XQuery) // XQuery 3.0
val K_NO_INHERIT: IKeywordOrNCNameType = IKeywordOrNCNameType("XPATH_KEYWORD_OR_NCNAME_NO_INHERIT", XQuery) // XQuery 1.0
val K_NO_PRESERVE: IKeywordOrNCNameType = IKeywordOrNCNameType("XPATH_KEYWORD_OR_NCNAME_NO_PRESERVE", XQuery) // XQuery 1.0
val K_NODES: IKeywordOrNCNameType = IKeywordOrNCNameType("XPATH_KEYWORD_OR_NCNAME_NODES", XQuery) // Update Facility 1.0
val K_NON_DETERMINISTIC: IKeywordOrNCNameType = IKeywordOrNCNameType("XPATH_KEYWORD_OR_NCNAME_NON_DETERMINISTIC", XQuery) // BaseX 8.4
val K_ONLY: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_ONLY", XQuery) // XQuery 3.0
val K_ORDER: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_ORDER", XQuery) // XQuery 1.0
val K_ORDERING: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_ORDERING", XQuery) // XQuery 1.0
val K_PATTERN_SEPARATOR: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_PATTERN_SEPARATOR", XQuery) // XQuery 3.0
val K_PER_MILLE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_PER_MILLE", XQuery) // XQuery 3.0
val K_PERCENT: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_PERCENT", XQuery) // XQuery 3.0
val K_PRESERVE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_PRESERVE", XQuery) // XQuery 1.0
val K_PRIVATE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_PRIVATE", XQuery) // MarkLogic 6.0
val K_PREVIOUS: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_PREVIOUS", XQuery) // XQuery 3.0
val K_PUBLIC: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_PUBLIC", XQuery) // XQuery 3.0 (§4.15 -- Annotations)
val K_RENAME: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_RENAME", XQuery) // Update Facility 1.0
val K_REPLACE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_REPLACE", XQuery) // Update Facility 1.0
val K_RETURNING: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_RETURNING", XQuery) // Scripting Extension 1.0
val K_REVALIDATION: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_REVALIDATION", XQuery) // Update Facility 1.0
val K_SCHEMA: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_SCHEMA", XQuery) // XQuery 1.0
val K_SEQUENTIAL: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_SEQUENTIAL", XQuery) // Scripting Extension 1.0
val K_SIMPLE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_SIMPLE", XQuery) // Scripting Extension 1.0
val K_SKIP: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_SKIP", XQuery) // Update Facility 1.0
val K_SLIDING: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_SLIDING", XQuery) // XQuery 3.0
val K_STABLE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_STABLE", XQuery) // XQuery 1.0
val K_STRICT: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_STRICT", XQuery) // XQuery 1.0
val K_STRIP: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_STRIP", XQuery) // XQuery 1.0
val K_STYLESHEET: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_STYLESHEET", XQuery) // MarkLogic 6.0
val K_SWITCH: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_SWITCH", XQuery, IKeywordOrNCNameType.KeywordType.XQUERY30_RESERVED_FUNCTION_NAME) // XQuery 3.0
val K_TRANSFORM: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_TRANSFORM", XQuery) // Update Facility 3.0
val K_TRY: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_TRY", XQuery) // XQuery 3.0
val K_TUMBLING: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_TUMBLING", XQuery) // XQuery 3.0
val K_TYPESWITCH: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_TYPESWITCH", XQuery, IKeywordOrNCNameType.KeywordType.RESERVED_FUNCTION_NAME) // XQuery 1.0
val K_UNASSIGNABLE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_UNASSIGNABLE", XQuery) // Scripting Extension 1.0
val K_UNORDERED: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_UNORDERED", XQuery) // XQuery 1.0
val K_UPDATE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_UPDATE", XQuery) // BaseX 7.8
val K_UPDATING: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_UPDATING", XQuery) // Update Facility 1.0
val K_VALIDATE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_VALIDATE", XQuery) // XQuery 1.0
val K_VALUE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_VALUE", XQuery) // Update Facility 1.0
val K_VARIABLE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_VARIABLE", XQuery) // XQuery 1.0
val K_VERSION: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_VERSION", XQuery) // XQuery 1.0
val K_WHEN: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_WHEN", XQuery) // XQuery 3.0
val K_WHERE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_WHERE", XQuery) // XQuery 1.0
val K_WHILE: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_WHILE", XQuery, IKeywordOrNCNameType.KeywordType.SCRIPTING10_RESERVED_FUNCTION_NAME) // Scripting Extension 1.0
val K_XQUERY: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_XQUERY", XQuery) // XQuery 1.0
val K_ZERO_DIGIT: IKeywordOrNCNameType = IKeywordOrNCNameType("XQUERY_KEYWORD_OR_NCNAME_ZERO_DIGIT", XQuery) // XQuery 3.0
// endregion
// region Terminal Symbols
val CHARACTER_REFERENCE: IElementType = IElementType("XQUERY_CHARACTER_REFERENCE_TOKEN", XQuery) // XQuery 1.0
val PREDEFINED_ENTITY_REFERENCE: IElementType = IElementType("XQUERY_PREDEFINED_ENTITY_REFERENCE_TOKEN", XQuery) // XQuery 1.0
// endregion
// region Error Reporting and Recovery
val EMPTY_ENTITY_REFERENCE: IElementType = IElementType("XQUERY_EMPTY_ENTITY_REFERENCE_TOKEN", XQuery)
val ENTITY_REFERENCE_NOT_IN_STRING: IElementType = IElementType("XQUERY_ENTITY_REFERENCE_NOT_IN_STRING_TOKEN", XQuery)
val INVALID: IElementType = IElementType("XQUERY_INVALID_TOKEN", XQuery)
val PARTIAL_ENTITY_REFERENCE: IElementType = IElementType("XQUERY_PARTIAL_ENTITY_REFERENCE_TOKEN", XQuery)
// endregion
// region Reserved Function Names
val RESERVED_FUNCTION_NAMES_FOR_XQUERY_10: TokenSet = TokenSet.create(
XPathTokenProvider.KAttribute,
XPathTokenProvider.KComment,
XPathTokenProvider.KDocumentNode,
XPathTokenProvider.KElement,
XPathTokenProvider.KEmptySequence,
XPathTokenProvider.KIf,
XPathTokenProvider.KItem,
XPathTokenProvider.KNode,
XPathTokenProvider.KProcessingInstruction,
XPathTokenProvider.KSchemaAttribute,
XPathTokenProvider.KSchemaElement,
XPathTokenProvider.KText,
K_TYPESWITCH,
)
val RESERVED_FUNCTION_NAMES_FOR_XQUERY_30: TokenSet = TokenSet.create(
XPathTokenProvider.KFunction,
XPathTokenProvider.KNamespaceNode,
K_SWITCH,
)
val RESERVED_FUNCTION_NAMES_FOR_SCRIPTING_10: TokenSet = TokenSet.create(
K_WHILE,
)
val RESERVED_FUNCTION_NAMES_FOR_MARKLOGIC_60: TokenSet = TokenSet.create(
MarkLogicXPathTokenProvider.KBinary,
)
val RESERVED_FUNCTION_NAMES_FOR_MARKLOGIC_70: TokenSet = TokenSet.create(
MarkLogicXPathTokenProvider.KAttributeDecl,
MarkLogicXPathTokenProvider.KComplexType,
MarkLogicXPathTokenProvider.KElementDecl,
MarkLogicXPathTokenProvider.KModelGroup,
MarkLogicXPathTokenProvider.KSchemaComponent,
MarkLogicXPathTokenProvider.KSchemaParticle,
MarkLogicXPathTokenProvider.KSchemaRoot,
MarkLogicXPathTokenProvider.KSchemaType,
MarkLogicXPathTokenProvider.KSchemaWildcard,
MarkLogicXPathTokenProvider.KSimpleType,
)
val RESERVED_FUNCTION_NAMES_FOR_MARKLOGIC_80: TokenSet = TokenSet.create(
MarkLogicXPathTokenProvider.KArrayNode,
MarkLogicXPathTokenProvider.KBooleanNode,
MarkLogicXPathTokenProvider.KNullNode,
MarkLogicXPathTokenProvider.KNumberNode,
MarkLogicXPathTokenProvider.KObjectNode,
MarkLogicXPathTokenProvider.KSchemaFacet,
)
// endregion
// region Token Sets
val BOUNDARY_SPACE_MODE_TOKENS: TokenSet = TokenSet.create(K_PRESERVE, K_STRIP)
val COMPATIBILITY_ANNOTATION_TOKENS: TokenSet = TokenSet.create(
K_ASSIGNABLE,
K_PRIVATE,
K_SEQUENTIAL,
K_SIMPLE,
K_UNASSIGNABLE,
K_UPDATING
)
val CONSTRUCTION_MODE_TOKENS: TokenSet = TokenSet.create(K_PRESERVE, K_STRIP)
val DEFAULT_NAMESPACE_TOKENS: TokenSet = TokenSet.create(
XPathTokenProvider.KElement,
XPathTokenProvider.KFunction,
XPathTokenProvider.KType
)
val DF_PROPERTY_NAME: TokenSet = TokenSet.create(
K_DECIMAL_SEPARATOR,
K_GROUPING_SEPARATOR,
K_INFINITY,
K_MINUS_SIGN,
K_NAN,
K_PERCENT,
K_PER_MILLE,
K_ZERO_DIGIT,
K_DIGIT,
K_PATTERN_SEPARATOR,
K_EXPONENT_SEPARATOR
)
val EMPTY_ORDERING_MODE_TOKENS: TokenSet = TokenSet.create(K_GREATEST, XPathFTTokenProvider.KLeast)
val FTMATCH_OPTION_START_TOKENS: TokenSet = TokenSet.create(
XPathFTTokenProvider.KCase,
XPathFTTokenProvider.KDiacritics,
K_FUZZY, // BaseX 6.1 XQuery Extension
XPathFTTokenProvider.KLanguage,
XPathFTTokenProvider.KLowerCase,
XPathFTTokenProvider.KNo,
XPathFTTokenProvider.KOption,
XPathFTTokenProvider.KStemming,
XPathFTTokenProvider.KStop,
XPathFTTokenProvider.KThesaurus,
XPathFTTokenProvider.KUpperCase,
XPathFTTokenProvider.KWildcards
)
val INHERIT_MODE_TOKENS: TokenSet = TokenSet.create(K_INHERIT, K_NO_INHERIT)
val INSERT_LOCATION_TOKENS: TokenSet = TokenSet.create(K_INTO, K_BEFORE, K_AFTER)
val INSERT_DELETE_NODE_TOKENS: TokenSet = TokenSet.create(XPathTokenProvider.KNode, K_NODES)
val INSERT_POSITION_TOKENS: TokenSet = TokenSet.create(K_FIRST, K_LAST)
val TYPE_DECL_ASSIGN_ERROR_TOKENS: TokenSet = TokenSet.create(
XPathTokenProvider.KAs,
XPathTokenProvider.AssignEquals
)
val ITEM_TYPE_DECL_ASSIGN_ERROR_TOKENS: TokenSet = TokenSet.create(
XPathTokenProvider.Equals,
XPathTokenProvider.AssignEquals
)
val ITEM_TYPE_DECL_TOKENS: TokenSet = TokenSet.create(XPathTokenProvider.KType, K_ITEM_TYPE)
val ORDERING_MODE_TOKENS: TokenSet = TokenSet.create(XPathFTTokenProvider.KOrdered, K_UNORDERED)
val ORDER_MODIFIER_TOKENS: TokenSet = TokenSet.create(K_ASCENDING, K_DESCENDING)
val PRESERVE_MODE_TOKENS: TokenSet = TokenSet.create(K_PRESERVE, K_NO_PRESERVE)
val REVALIDATION_MODE_TOKENS: TokenSet = TokenSet.create(K_LAX, K_SKIP, K_STRICT)
val VALIDATE_EXPR_TOKENS: TokenSet = TokenSet.create(XPathTokenProvider.KAs, XPathTokenProvider.KType)
val VALIDATION_MODE_TOKENS: TokenSet = TokenSet.create(K_LAX, K_STRICT, K_FULL)
val VALIDATE_EXPR_MODE_OR_TYPE_TOKENS: TokenSet = TokenSet.create(
K_FULL,
K_LAX,
K_STRICT,
XPathTokenProvider.KAs,
XPathTokenProvider.KType
)
val STRING_LITERAL_TOKENS: TokenSet = TokenSet.create(
XPathTokenType.STRING_LITERAL_CONTENTS,
STRING_CONSTRUCTOR_CONTENTS,
XML_ATTRIBUTE_VALUE_CONTENTS,
XML_ELEMENT_CONTENTS
)
val COMMENT_TOKENS: TokenSet = TokenSet.create(
XQDocTokenType.CONTENTS,
XPathTokenProvider.CommentContents,
XML_COMMENT
)
// endregion
}
| apache-2.0 | b82b03590fe44ad30309ee2881408d68 | 66.719101 | 198 | 0.752447 | 3.641692 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-marklogic/main/uk/co/reecedunn/intellij/plugin/marklogic/lang/QueryLanguages.kt | 1 | 3032 | /*
* Copyright (C) 2018-2019 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.marklogic.lang
import com.intellij.lang.Language
import com.intellij.openapi.fileTypes.ExtensionFileNameMatcher
import com.intellij.openapi.fileTypes.FileNameMatcher
import uk.co.reecedunn.intellij.plugin.core.lang.LanguageData
import uk.co.reecedunn.intellij.plugin.marklogic.resources.MarkLogicBundle
object ServerSideJavaScript : Language("MLJavaScript", "application/vnd.marklogic-javascript") {
override fun isCaseSensitive(): Boolean = true
override fun getDisplayName(): String = MarkLogicBundle.message("language.sjs.display-name")
}
val SPARQLQuery: Language by lazy {
Language.findInstancesByMimeType("application/sparql-query").firstOrNull() ?: run {
val language = Language.findLanguageByID("SPARQLQuery") ?: object : Language("SPARQLQuery") {
override fun getDisplayName(): String = "SPARQL Query"
}
language.putUserData(LanguageData.KEY, object : LanguageData {
override val associations: List<FileNameMatcher> = listOf(
ExtensionFileNameMatcher("rq"),
ExtensionFileNameMatcher("sparql")
)
override val mimeTypes: Array<String> = arrayOf("application/sparql-query")
})
language
}
}
val SPARQLUpdate: Language by lazy {
Language.findInstancesByMimeType("application/sparql-update").firstOrNull() ?: run {
val language = Language.findLanguageByID("SPARQLUpdate") ?: object : Language("SPARQLUpdate") {
override fun getDisplayName(): String = "SPARQL Update"
}
language.putUserData(LanguageData.KEY, object : LanguageData {
override val associations: List<FileNameMatcher> = listOf(
ExtensionFileNameMatcher("ru")
)
override val mimeTypes: Array<String> = arrayOf("application/sparql-update")
})
language
}
}
val SQL: Language by lazy {
Language.findInstancesByMimeType("application/sql").firstOrNull() ?: run {
val language = Language.findLanguageByID("SQL") ?: object : Language("SQL") {}
language.putUserData(LanguageData.KEY, object : LanguageData {
override val associations: List<FileNameMatcher> = listOf(
ExtensionFileNameMatcher("sql")
)
override val mimeTypes: Array<String> = arrayOf("application/sql")
})
language
}
}
| apache-2.0 | 232ebd729726a9b8a4a2ef0d1984ac54 | 39.426667 | 103 | 0.691293 | 4.708075 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xslt/main/uk/co/reecedunn/intellij/plugin/xslt/lang/EQNamesOrHashedKeywords.kt | 1 | 2847 | /*
* Copyright (C) 2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xslt.lang
import com.intellij.lang.ASTNode
import com.intellij.lang.Language
import com.intellij.lang.PsiParser
import com.intellij.lexer.Lexer
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.IFileElementType
import uk.co.reecedunn.intellij.plugin.xpath.lexer.XPathLexer
import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathParserDefinition
import uk.co.reecedunn.intellij.plugin.xslt.lang.fileTypes.XsltSchemaTypeFileType
import uk.co.reecedunn.intellij.plugin.xslt.parser.XsltSchemaTypesParser
import uk.co.reecedunn.intellij.plugin.xslt.psi.impl.schema.XsltHashedKeywordPsiImpl
import uk.co.reecedunn.intellij.plugin.xslt.psi.impl.schema.XsltSchemaTypePsiImpl
import uk.co.reecedunn.intellij.plugin.xslt.schema.XsltSchemaTypes
import xqt.platform.intellij.xpath.XPath
object EQNamesOrHashedKeywords : Language(XPath, "EQNames-or-hashed-keywords") {
// region Language
val FileType: LanguageFileType = XsltSchemaTypeFileType(this)
override fun getAssociatedFileType(): LanguageFileType = FileType
// endregion
// region ParserDefinition
val FileElementType: IFileElementType = IFileElementType(this)
val HashedKeywordToken: IElementType = IElementType("SCHEMA_TYPE_HASHED_KEYWORD", this)
class ParserDefinition : XPathParserDefinition() {
override fun createLexer(project: Project): Lexer = XPathLexer(XsltSchemaTypes.KEYWORDS)
override fun createParser(project: Project): PsiParser {
return XsltSchemaTypesParser(EQNamesOrHashedKeywords, HashedKeywordToken)
}
override fun getFileNodeType(): IFileElementType = FileElementType
override fun createFile(viewProvider: FileViewProvider): PsiFile = XsltSchemaTypePsiImpl(viewProvider, FileType)
override fun createElement(node: ASTNode): PsiElement = when (node.elementType) {
HashedKeywordToken -> XsltHashedKeywordPsiImpl(node)
else -> super.createElement(node)
}
}
// endregion
}
| apache-2.0 | 83f39c2afa550df123759203f0218e09 | 39.671429 | 120 | 0.779066 | 4.393519 | false | false | false | false |
kesmarag/megaptera | src/main/org/kesmarag/megaptera/utils/VectorUtils.kt | 1 | 1592 | package org.kesmarag.megaptera.utils
import org.kesmarag.megaptera.linear.ColumnVector
import org.kesmarag.megaptera.linear.RowVector
import org.kesmarag.megaptera.linear.Vector
import org.kesmarag.megaptera.linear.VectorType
fun DoubleArray.toColumnVector(): ColumnVector {
val tmpVector = ColumnVector(this.size)
for (i in 0..this.size - 1) {
tmpVector[i] = this[i]
}
return tmpVector
}
fun DoubleArray.toRowVector(): RowVector {
val tmpVector = RowVector(this.size)
for (i in 0..this.size - 1) {
tmpVector[i] = this[i]
}
return tmpVector
}
fun distance(vector1: ColumnVector, vector2: ColumnVector): Double = (vector1 - vector2).norm2()
fun distance(vector1: RowVector, vector2: RowVector): Double = (vector1 - vector2).norm2()
infix operator fun Double.times(vector: ColumnVector): ColumnVector = vector.times(this)
infix operator fun Int.times(vector: ColumnVector): ColumnVector = vector.times(this.toDouble())
infix operator fun Double.times(vector: RowVector): RowVector = vector.times(this)
infix operator fun Int.times(vector: RowVector): RowVector = vector.times(this.toDouble())
fun Math.exp(a: Double,vector: ColumnVector): ColumnVector{
val expaVector = ColumnVector(vector.dimension)
for (i in 0..vector.dimension-1){
expaVector[i] = Math.exp(a*vector[i])
}
return expaVector
}
fun Math.exp(a: Double, vector: RowVector) : RowVector{
val expaVector = RowVector(vector.dimension)
for (i in 0..vector.dimension-1){
expaVector[i] = Math.exp(a*vector[i])
}
return expaVector
} | apache-2.0 | 55e1ddd397283e107ceeb3ab7fc3ca20 | 32.1875 | 96 | 0.720477 | 3.282474 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/Anilist.kt | 1 | 7581 | package eu.kanade.tachiyomi.data.track.anilist
import android.content.Context
import android.graphics.Color
import androidx.annotation.StringRes
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.track.TrackService
import eu.kanade.tachiyomi.data.track.model.TrackSearch
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import uy.kohesive.injekt.injectLazy
class Anilist(private val context: Context, id: Long) : TrackService(id) {
companion object {
const val READING = 1
const val COMPLETED = 2
const val ON_HOLD = 3
const val DROPPED = 4
const val PLAN_TO_READ = 5
const val REREADING = 6
const val POINT_100 = "POINT_100"
const val POINT_10 = "POINT_10"
const val POINT_10_DECIMAL = "POINT_10_DECIMAL"
const val POINT_5 = "POINT_5"
const val POINT_3 = "POINT_3"
}
private val json: Json by injectLazy()
private val interceptor by lazy { AnilistInterceptor(this, getPassword()) }
private val api by lazy { AnilistApi(client, interceptor) }
override val supportsReadingDates: Boolean = true
private val scorePreference = trackPreferences.anilistScoreType()
init {
// If the preference is an int from APIv1, logout user to force using APIv2
try {
scorePreference.get()
} catch (e: ClassCastException) {
logout()
scorePreference.delete()
}
}
@StringRes
override fun nameRes() = R.string.tracker_anilist
override fun getLogo() = R.drawable.ic_tracker_anilist
override fun getLogoColor() = Color.rgb(18, 25, 35)
override fun getStatusList(): List<Int> {
return listOf(READING, COMPLETED, ON_HOLD, DROPPED, PLAN_TO_READ, REREADING)
}
override fun getStatus(status: Int): String = with(context) {
when (status) {
READING -> getString(R.string.reading)
PLAN_TO_READ -> getString(R.string.plan_to_read)
COMPLETED -> getString(R.string.completed)
ON_HOLD -> getString(R.string.on_hold)
DROPPED -> getString(R.string.dropped)
REREADING -> getString(R.string.repeating)
else -> ""
}
}
override fun getReadingStatus(): Int = READING
override fun getRereadingStatus(): Int = REREADING
override fun getCompletionStatus(): Int = COMPLETED
override fun getScoreList(): List<String> {
return when (scorePreference.get()) {
// 10 point
POINT_10 -> IntRange(0, 10).map(Int::toString)
// 100 point
POINT_100 -> IntRange(0, 100).map(Int::toString)
// 5 stars
POINT_5 -> IntRange(0, 5).map { "$it ★" }
// Smiley
POINT_3 -> listOf("-", "😦", "😐", "😊")
// 10 point decimal
POINT_10_DECIMAL -> IntRange(0, 100).map { (it / 10f).toString() }
else -> throw Exception("Unknown score type")
}
}
override fun indexToScore(index: Int): Float {
return when (scorePreference.get()) {
// 10 point
POINT_10 -> index * 10f
// 100 point
POINT_100 -> index.toFloat()
// 5 stars
POINT_5 -> when (index) {
0 -> 0f
else -> index * 20f - 10f
}
// Smiley
POINT_3 -> when (index) {
0 -> 0f
else -> index * 25f + 10f
}
// 10 point decimal
POINT_10_DECIMAL -> index.toFloat()
else -> throw Exception("Unknown score type")
}
}
override fun displayScore(track: Track): String {
val score = track.score
return when (scorePreference.get()) {
POINT_5 -> when (score) {
0f -> "0 ★"
else -> "${((score + 10) / 20).toInt()} ★"
}
POINT_3 -> when {
score == 0f -> "0"
score <= 35 -> "😦"
score <= 60 -> "😐"
else -> "😊"
}
else -> track.toAnilistScore()
}
}
private suspend fun add(track: Track): Track {
return api.addLibManga(track)
}
override suspend fun update(track: Track, didReadChapter: Boolean): Track {
// If user was using API v1 fetch library_id
if (track.library_id == null || track.library_id!! == 0L) {
val libManga = api.findLibManga(track, getUsername().toInt())
?: throw Exception("$track not found on user library")
track.library_id = libManga.library_id
}
if (track.status != COMPLETED) {
if (didReadChapter) {
if (track.last_chapter_read.toInt() == track.total_chapters && track.total_chapters > 0) {
track.status = COMPLETED
track.finished_reading_date = System.currentTimeMillis()
} else if (track.status != REREADING) {
track.status = READING
if (track.last_chapter_read == 1F) {
track.started_reading_date = System.currentTimeMillis()
}
}
}
}
return api.updateLibManga(track)
}
override suspend fun bind(track: Track, hasReadChapters: Boolean): Track {
val remoteTrack = api.findLibManga(track, getUsername().toInt())
return if (remoteTrack != null) {
track.copyPersonalFrom(remoteTrack)
track.library_id = remoteTrack.library_id
if (track.status != COMPLETED) {
val isRereading = track.status == REREADING
track.status = if (isRereading.not() && hasReadChapters) READING else track.status
}
update(track)
} else {
// Set default fields if it's not found in the list
track.status = if (hasReadChapters) READING else PLAN_TO_READ
track.score = 0F
add(track)
}
}
override suspend fun search(query: String): List<TrackSearch> {
return api.search(query)
}
override suspend fun refresh(track: Track): Track {
val remoteTrack = api.getLibManga(track, getUsername().toInt())
track.copyPersonalFrom(remoteTrack)
track.title = remoteTrack.title
track.total_chapters = remoteTrack.total_chapters
return track
}
override suspend fun login(username: String, password: String) = login(password)
suspend fun login(token: String) {
try {
val oauth = api.createOAuth(token)
interceptor.setAuth(oauth)
val (username, scoreType) = api.getCurrentUser()
scorePreference.set(scoreType)
saveCredentials(username.toString(), oauth.access_token)
} catch (e: Throwable) {
logout()
}
}
override fun logout() {
super.logout()
trackPreferences.trackToken(this).delete()
interceptor.setAuth(null)
}
fun saveOAuth(oAuth: OAuth?) {
trackPreferences.trackToken(this).set(json.encodeToString(oAuth))
}
fun loadOAuth(): OAuth? {
return try {
json.decodeFromString<OAuth>(trackPreferences.trackToken(this).get())
} catch (e: Exception) {
null
}
}
}
| apache-2.0 | 7e8b53a3005e4fb4f4956d7caf4c22ad | 32 | 106 | 0.566892 | 4.406414 | false | false | false | false |
Mindera/skeletoid | rxjava/src/test/java/com/mindera/skeletoid/rxjava/ObservableExtensionsTest.kt | 1 | 3221 | package com.mindera.skeletoid.rxjava
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import org.junit.Assert.assertEquals
import org.junit.Test
class ObservableExtensionsTest {
@Test
fun testFilterOrElseWithPredicate() {
val list = mutableListOf<Int>()
val subject = PublishSubject.create<Int>()
subject
.doOnNext { list.add(it) }
.test()
Observable.just(1, 2, 3, 4, 5, 6)
.filterOrElse({ it % 2 == 0 }) { subject.onNext(it) }
.test()
.assertNoErrors()
.assertComplete()
.assertValueCount(3)
.assertValues(2, 4, 6)
assertEquals(listOf(1, 3, 5), list)
}
@Test
fun testFilterOrElseWithConditionFalse() {
val list = mutableListOf<Int>()
val subject = PublishSubject.create<Int>()
subject
.doOnNext { list.add(it) }
.test()
Observable.just(1, 2, 3, 4, 5, 6)
.filterOrElse(false) { subject.onNext(it) }
.test()
.assertNoErrors()
.assertComplete()
.assertNoValues()
assertEquals(listOf(1, 2, 3, 4, 5, 6), list)
}
@Test
fun testFilterOrElseWithConditionTrue() {
val list = mutableListOf<Int>()
val subject = PublishSubject.create<Int>()
subject
.doOnNext { list.add(it) }
.test()
Observable.just(1, 2, 3, 4, 5, 6)
.filterOrElse(true) { subject.onNext(it) }
.test()
.assertNoErrors()
.assertComplete()
.assertValues(1, 2, 3, 4, 5, 6)
assertEquals(emptyList<Int>(), list)
}
@Test
fun testSkipWhileAndDoWithPredicate() {
val list = mutableListOf<Int>()
val subject = PublishSubject.create<Int>()
subject
.doOnNext { list.add(it) }
.test()
Observable.just(1, 2, 3, 4, 5, 6)
.skipWhileAndDo({ it < 4 }) { subject.onNext(it) }
.test()
.assertNoErrors()
.assertComplete()
.assertValues(4, 5, 6)
assertEquals(listOf(1, 2, 3), list)
}
@Test
fun testSkipWhileAndDoWithConditionTrue() {
val list = mutableListOf<Int>()
val subject = PublishSubject.create<Int>()
subject
.doOnNext { list.add(it) }
.test()
Observable.just(1, 2, 3, 4, 5, 6)
.skipWhileAndDo(true) { subject.onNext(it) }
.test()
.assertNoErrors()
.assertComplete()
.assertNoValues()
assertEquals(listOf(1, 2, 3, 4, 5, 6), list)
}
@Test
fun testSkipWhileAndDoWithConditionFalse() {
val list = mutableListOf<Int>()
val subject = PublishSubject.create<Int>()
subject
.doOnNext { list.add(it) }
.test()
Observable.just(1, 2, 3, 4, 5, 6)
.skipWhileAndDo(false) { subject.onNext(it) }
.test()
.assertNoErrors()
.assertComplete()
.assertValues(1, 2, 3, 4, 5, 6)
assertEquals(emptyList<Int>(), list)
}
} | mit | 70348cce8623b490baf0b5e31634209e | 24.983871 | 65 | 0.527476 | 4.19401 | false | true | false | false |
maxoumime/emoji-data-java | src/main/java/com/maximebertheau/emoji/SkinVariationType.kt | 1 | 1037 | package com.maximebertheau.emoji
/**
* Enum that represents the Fitzpatrick modifiers supported by the emojis.
*/
enum class SkinVariationType(val unified: String, val alias: String) {
/**
* Fitzpatrick modifier of type 1/2 (pale white/white)
*/
TYPE_1_2("1F3FB", "skin-tone-2"),
/**
* Fitzpatrick modifier of type 3 (cream white)
*/
TYPE_3("1F3FC", "skin-tone-3"),
/**
* Fitzpatrick modifier of type 4 (moderate brown)
*/
TYPE_4("1F3FD", "skin-tone-4"),
/**
* Fitzpatrick modifier of type 5 (dark brown)
*/
TYPE_5("1F3FE", "skin-tone-5"),
/**
* Fitzpatrick modifier of type 6 (black)
*/
TYPE_6("1F3FF", "skin-tone-6");
companion object {
@JvmStatic
fun fromUnified(unified: String) = values().firstOrNull { it.unified == unified }
?: throw Error("$unified doesn't exist!")
@JvmStatic
fun fromAlias(alias: String): SkinVariationType? = values().firstOrNull { it.alias == alias }
}
} | mit | 5d4adad68dcac28649d54f83d6632d7e | 24.95 | 101 | 0.592093 | 3.690391 | false | false | false | false |
k9mail/k-9 | app/storage/src/main/java/com/fsck/k9/storage/messages/FlagMessageOperations.kt | 1 | 4244 | package com.fsck.k9.storage.messages
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import com.fsck.k9.mail.Flag
import com.fsck.k9.mailstore.LockableDatabase
internal val SPECIAL_FLAGS = setOf(Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED, Flag.FORWARDED)
internal class FlagMessageOperations(private val lockableDatabase: LockableDatabase) {
fun setFlag(messageIds: Collection<Long>, flag: Flag, set: Boolean) {
require(messageIds.isNotEmpty()) { "'messageIds' must not be empty" }
if (flag in SPECIAL_FLAGS) {
setSpecialFlags(messageIds, flag, set)
} else {
rebuildFlagsColumnValue(messageIds, flag, set)
}
}
fun setMessageFlag(folderId: Long, messageServerId: String, flag: Flag, set: Boolean) {
when (flag) {
Flag.DELETED -> setBoolean(folderId, messageServerId, "deleted", set)
Flag.SEEN -> setBoolean(folderId, messageServerId, "read", set)
Flag.FLAGGED -> setBoolean(folderId, messageServerId, "flagged", set)
Flag.ANSWERED -> setBoolean(folderId, messageServerId, "answered", set)
Flag.FORWARDED -> setBoolean(folderId, messageServerId, "forwarded", set)
else -> rebuildFlagsColumnValue(folderId, messageServerId, flag, set)
}
}
private fun setSpecialFlags(messageIds: Collection<Long>, flag: Flag, set: Boolean) {
val columnName = when (flag) {
Flag.SEEN -> "read"
Flag.FLAGGED -> "flagged"
Flag.ANSWERED -> "answered"
Flag.FORWARDED -> "forwarded"
else -> error("Unsupported flag: $flag")
}
val columnValue = if (set) 1 else 0
val contentValues = ContentValues().apply {
put(columnName, columnValue)
}
lockableDatabase.execute(true) { database ->
performChunkedOperation(
arguments = messageIds,
argumentTransformation = Long::toString
) { selectionSet, selectionArguments ->
database.update("messages", contentValues, "id $selectionSet", selectionArguments)
}
}
}
private fun rebuildFlagsColumnValue(messageIds: Collection<Long>, flag: Flag, set: Boolean) {
throw UnsupportedOperationException("not implemented")
}
private fun rebuildFlagsColumnValue(folderId: Long, messageServerId: String, flag: Flag, set: Boolean) {
lockableDatabase.execute(true) { database ->
val oldFlags = database.readFlagsColumn(folderId, messageServerId)
val newFlags = if (set) oldFlags + flag else oldFlags - flag
val newFlagsString = newFlags.joinToString(separator = ",")
val values = ContentValues().apply {
put("flags", newFlagsString)
}
database.update(
"messages",
values,
"folder_id = ? AND uid = ?",
arrayOf(folderId.toString(), messageServerId)
)
}
}
private fun SQLiteDatabase.readFlagsColumn(folderId: Long, messageServerId: String): Set<Flag> {
return query(
"messages",
arrayOf("flags"),
"folder_id = ? AND uid = ?",
arrayOf(folderId.toString(), messageServerId),
null,
null,
null
).use { cursor ->
if (!cursor.moveToFirst()) error("Message not found $folderId:$messageServerId")
if (!cursor.isNull(0)) {
cursor.getString(0).split(',').map { flagString -> Flag.valueOf(flagString) }.toSet()
} else {
emptySet()
}
}
}
private fun setBoolean(folderId: Long, messageServerId: String, columnName: String, value: Boolean) {
lockableDatabase.execute(false) { database ->
val values = ContentValues().apply {
put(columnName, if (value) 1 else 0)
}
database.update(
"messages",
values,
"folder_id = ? AND uid = ?",
arrayOf(folderId.toString(), messageServerId)
)
}
}
}
| apache-2.0 | d0a0c9e9f2da7a8e1b5e2cde702181fb | 35.904348 | 108 | 0.58836 | 4.736607 | false | false | false | false |
fcostaa/kotlin-rxjava-android | buildSrc/src/main/kotlin/Versions.kt | 1 | 2196 | internal object Kotlin {
const val version = "1.4.10"
}
object Versions {
const val androidGradlePlugin = "4.2.0-alpha10"
const val dependencyGraphGeneratorPlugin = "0.2.0"
const val androidJunitJacocoPlugin = "0.15.0"
const val detektGradlePlugin = "1.0.1"
const val canidropjetifierPlugin = "0.4"
const val compileSdkVersion = 28
const val buildToolsVersion = "28.0.3"
const val minSdkVersion = 21
const val targetSdkVersion = 28
const val versionCode = 1
const val versionName = "1.0"
const val androidxSupportV4Library = "1.0.0"
const val androidxAppCompatLibrary = "1.1.0"
const val androidxMaterialLibrary = "1.0.0-rc01"
const val androidxRecyclerViewLibrary = "1.0.0"
const val androidxSupportAnnotationLibrary = "1.1.0"
const val androidxConstraintLayoutLibrary = "1.1.3"
const val androidxKtxLibrary = "1.0.0"
const val lifecycleLibrary = "2.2.0"
const val androidxFragmentTesting = "1.2.0-rc04"
const val roomLibrary = "2.2.5"
const val rxJavaLibrary = "2.2.13"
const val rxJavaAndroidLibrary = "2.1.0"
const val rxJavaRelayLibrary = "2.1.0"
const val rxJavaBindingLibrary = "3.0.0-alpha2"
const val rxActionLibrary = "1.2.0"
const val okhttpLibrary = "3.12.0"
const val retrofitLibrary = "2.5.0"
const val kotlinSerializationConverterLibrary = "0.7.0"
const val daggerLibrary = "2.29.1"
const val javaxAnnotationLibrary = "1.0"
const val imageLoaderLibrary = "1.9.5"
const val galleryLayoutManagerLibrary = "1.2.0"
const val recyclerViewDslLibrary = "0.8.0"
const val junitLibrary = "4.12"
const val mockkLibrary = "1.9.1"
const val robolectricLibrary = "4.3.1"
const val androidxJunitLibrary = "1.1.2-beta02"
const val androidxTruthLibrary = "1.3.0-beta02"
const val androidxRunnerLibrary = "1.3.0-beta02"
const val androidxRulesLibrary = "1.3.0-beta02"
const val androidxOrchestratorLibrary = "1.3.0-beta02"
const val androidxEspressoCoreLibrary = "3.2.0"
const val androidxEspressoContribLibrary = "3.2.0"
const val rx2IdlerLibrary = "0.10.0"
const val testButlerLibrary = "1.3.1"
}
| mit | 4c131a556172d7b4ff978f822a9f4e33 | 34.419355 | 59 | 0.694444 | 3.368098 | false | false | false | false |
JohnnyShieh/Gank | app/src/main/kotlin/com/johnny/gank/widget/BaseLoadingIndicator.kt | 1 | 2740 | package com.johnny.gank.widget
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.animation.Animator
import android.graphics.Canvas
import android.graphics.Paint
import android.view.View
import androidx.annotation.LongDef
import java.lang.ref.WeakReference
/**
* Created by Jack on 2015/10/15.
*/
abstract class BaseLoadingIndicator {
@Retention(AnnotationRetention.SOURCE)
@LongDef(STATUS_START, STATUS_END, STATUS_CANCEL)
annotation class AnimStatus
private var mTarget: WeakReference<View>? = null
private var mAnimators: List<Animator>? = null
fun setTarget(target: View) {
mTarget = WeakReference(target)
}
fun getTarget(): View? {
return mTarget?.get()
}
fun getWidth(): Int {
return mTarget?.get()?.width ?: 0
}
fun getHeight(): Int {
return mTarget?.get()?.height ?: 0
}
fun postInvalidate() {
getTarget()?.postInvalidate()
}
/**
* draw indicator
* @param canvas
* @param paint
*/
abstract fun draw(canvas: Canvas, paint: Paint)
/**
* create animation or animations
*/
abstract fun createAnimation(): List<Animator>
fun initAnimation() {
mAnimators = createAnimation()
}
/**
* make animation to start or end when target
* view was be Visible or Gone or Invisible.
* make animation to cancel when target view
* be onDetachedFromWindow.
* @param animStatus
*/
fun setAnimationStatus(@AnimStatus animStatus: Long){
if (mAnimators == null){
return
}
val count = mAnimators!!.size
for (i in 0 until count) {
val animator = mAnimators!![i]
val isRunning = animator.isRunning
when (animStatus) {
STATUS_START -> if (!isRunning) animator.start()
STATUS_END -> if (isRunning) animator.end()
STATUS_CANCEL -> if (isRunning) animator.cancel()
}
}
}
companion object {
const val STATUS_START = 1L
const val STATUS_END = 2L
const val STATUS_CANCEL = -1L
}
}
| apache-2.0 | f5af9b38356f1036337e18fb887b01d4 | 25.346154 | 75 | 0.634307 | 4.462541 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/deeplearning/birnn/deepbirnn/DeepBiRNN.kt | 1 | 6792 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.deeplearning.birnn.deepbirnn
import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction
import com.kotlinnlp.simplednn.core.functionalities.initializers.GlorotInitializer
import com.kotlinnlp.simplednn.core.functionalities.initializers.Initializer
import com.kotlinnlp.simplednn.core.layers.LayerType
import com.kotlinnlp.simplednn.deeplearning.birnn.BiRNN
import com.kotlinnlp.simplednn.core.layers.models.merge.mergeconfig.ConcatMerge
import com.kotlinnlp.utils.Serializer
import java.io.InputStream
import java.io.OutputStream
import java.io.Serializable
import kotlin.math.roundToInt
/**
* The DeepBiRNN.
*
* A deep bidirectional RNN (or k-layer BiRNN) is composed of k BiRNNs that feed into each other: the output of the i-th
* BIRNN becomes the input of the (i+1)-th BiRNN. Stacking BiRNNs in this way has been empirically shown to be effective
* (Irsoy and Cardie, 2014).
*
* The output size of each BiRNN must be equal to the input size of the following one.
*
* @property levels the list of BiRNNs
*/
class DeepBiRNN(val levels: List<BiRNN>) : Serializable {
/**
* @property levels the list of BiRNNs
*/
constructor(vararg levels: BiRNN): this(levels.toList())
companion object {
/**
* Private val used to serialize the class (needed by Serializable).
*/
@Suppress("unused")
private const val serialVersionUID: Long = 1L
/**
* Read a [DeepBiRNN] (serialized) from an input stream and decode it.
*
* @param inputStream the [InputStream] from which to read the serialized [DeepBiRNN]
*
* @return the [DeepBiRNN] read from [inputStream] and decoded
*/
fun load(inputStream: InputStream): DeepBiRNN = Serializer.deserialize(inputStream)
/**
* Build a DeepBiRNN stacking more BiRNNs.
*
* Each BiRNN reduces (or increases) the size of its output respect to its input thanks to its hidden layer size
* and a concatenation of the output of its two RNNs.
* The gain factor between the input and the output of each BiRNN is controlled passing a list of gain factors, one
* for each level.
*
* @param inputSize the input size
* @param inputType the input type
* @param recurrentConnectionType the type of recurrent layers connection
* @param numberOfLevels the number of BiRNN levels
* @param gainFactors the gain factors between the input size and the output size of each BiRNN
* @param weightsInitializer the initializer of the weights (zeros if null, default: Glorot)
* @param biasesInitializer the initializer of the biases (zeros if null, default: null)
*
* @return a list of BiRNNs
*/
fun byReduceConcat(inputSize: Int,
inputType: LayerType.Input,
recurrentConnectionType: LayerType.Connection,
hiddenActivation: ActivationFunction?,
numberOfLevels: Int,
gainFactors: List<Double> = List(
size = numberOfLevels,
init = { i -> if (i == 0) 2.0 else 1.0 }),
weightsInitializer: Initializer? = GlorotInitializer(),
biasesInitializer: Initializer? = null): DeepBiRNN {
require(numberOfLevels > 0) { "Required at least one BiRNN level." }
require(recurrentConnectionType.property == LayerType.Property.Recurrent) {
"Required a recurrent connection type with Recurrent property."
}
require(gainFactors.size == numberOfLevels) {
"The number of gain factors (%d) doesn't match the number of layers (%d)"
.format(gainFactors.size, numberOfLevels)
}
var levelInputSize: Int = inputSize
return DeepBiRNN(List(
size = numberOfLevels,
init = { i ->
val outputSize: Int = this.getBiRNNOutputSize(inputSize = levelInputSize, gain = gainFactors[i])
val biRNN = BiRNN(
inputSize = levelInputSize,
inputType = if (i == 0) inputType else LayerType.Input.Dense,
hiddenSize = outputSize / 2,
hiddenActivation = hiddenActivation,
recurrentConnectionType = recurrentConnectionType,
outputMergeConfiguration = ConcatMerge(),
weightsInitializer = weightsInitializer,
biasesInitializer = biasesInitializer)
levelInputSize = outputSize
biRNN
}
))
}
/**
* Get the size of the output of a BiRNN level.
*
* Since the output of the BiRNN which uses a ConcatMerge is the concatenation of the outputs of 2 RNNs, the output
* size must be rounded to an odd integer (the next following in this case).
*
* @param inputSize the size of the input
* @param gain the gain factor to calculate the output size
*
* @return the output size of a BiRNN level
*/
private fun getBiRNNOutputSize(inputSize: Int, gain: Double): Int {
val roughOutputSize: Int = (gain * inputSize).roundToInt()
return if (roughOutputSize % 2 == 0) roughOutputSize else roughOutputSize + 1
}
}
/**
* The model parameters.
*/
val model = DeepBiRNNParameters(paramsPerBiRNN = this.levels.map { it.model })
/**
* The size of the input level (the first BiRNN).
*/
val inputSize: Int = this.levels.first().inputSize
/**
* The size of the output level (the last BiRNN).
*/
val outputSize: Int = this.levels.last().outputSize
/**
* Check the compatibility of the BiRNNs.
*/
init {
require(this.levels.isNotEmpty()) { "The list of BiRNNs cannot be empty." }
require(this.areLevelsCompatible()) { "The input-output size of the levels must be compatible." }
}
/**
* Serialize this [DeepBiRNN] and write it to an output stream.
*
* @param outputStream the [OutputStream] in which to write this serialized [DeepBiRNN]
*/
fun dump(outputStream: OutputStream) = Serializer.serialize(this, outputStream)
/**
* @return a boolean indicating if the input-output size of the levels are compatible
*/
private fun areLevelsCompatible(): Boolean {
var lastOutputSize: Int = this.levels.first().inputSize
return this.levels.all {
val isCompatible: Boolean = it.inputSize == lastOutputSize
lastOutputSize = it.outputSize
isCompatible
}
}
}
| mpl-2.0 | c477b258cc5a9e53d12e32b53a9c2ed1 | 35.320856 | 120 | 0.666519 | 4.450852 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/utils/LargeValueFormatter.kt | 1 | 1702 | package org.wordpress.android.ui.stats.refresh.utils
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.formatter.ValueFormatter
import com.github.mikephil.charting.utils.ViewPortHandler
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.Locale
import kotlin.math.round
/**
* This class is based on the {@link com.github.mikephil.charting.formatter.LargeValueFormatter} and fixes the issue
* with Locale other than US (in some languages is the DecimalFormat different).
*/
class LargeValueFormatter : ValueFormatter() {
private var mSuffix = arrayOf("", "k", "m", "b", "t")
private var mMaxLength = 5
private val mFormat: DecimalFormat = DecimalFormat("###E00", DecimalFormatSymbols(Locale.US))
override fun getFormattedValue(
value: Float,
entry: Entry,
dataSetIndex: Int,
viewPortHandler: ViewPortHandler
): String {
return makePretty(round(value).toDouble())
}
override fun getFormattedValue(value: Float): String {
return makePretty(round(value).toDouble())
}
private fun makePretty(number: Double): String {
var r = mFormat.format(number)
val numericValue1 = Character.getNumericValue(r[r.length - 1])
val numericValue2 = Character.getNumericValue(r[r.length - 2])
val combined = Integer.valueOf(numericValue2.toString() + "" + numericValue1)
r = r.replace("E[0-9][0-9]".toRegex(), mSuffix[combined / 3])
while (r.length > mMaxLength || r.matches("[0-9]+\\.[a-z]".toRegex())) {
r = r.substring(0, r.length - 2) + r.substring(r.length - 1)
}
return r
}
}
| gpl-2.0 | 3ecedfe98b9fcd858f08a8e926882532 | 34.458333 | 116 | 0.682726 | 4.014151 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/ui/widgets/EmptyRecyclerView.kt | 1 | 1177 | package com.kelsos.mbrc.ui.widgets
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.recyclerview.widget.RecyclerView
class EmptyRecyclerView : RecyclerView {
var emptyView: View? = null
set(value) {
field = value
checkIfEmpty()
}
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
context,
attrs,
defStyle
)
internal fun checkIfEmpty() {
val adapter = adapter
emptyView?.visibility =
if (adapter != null && adapter.itemCount > 0) View.GONE else View.VISIBLE
}
internal val observer: RecyclerView.AdapterDataObserver =
object : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
super.onChanged()
checkIfEmpty()
}
}
override fun setAdapter(adapter: RecyclerView.Adapter<*>?) {
val oldAdapter = getAdapter()
oldAdapter?.unregisterAdapterDataObserver(observer)
super.setAdapter(adapter)
adapter?.registerAdapterDataObserver(observer)
}
}
| gpl-3.0 | f440d07d76c6d737b58fb781030be992 | 24.586957 | 79 | 0.708581 | 4.652174 | false | false | false | false |
ingokegel/intellij-community | plugins/devkit/intellij.devkit.workspaceModel/tests/testData/updateOldCode/after/gen/SimpleEntityImpl.kt | 1 | 6874 | //new comment
package com.intellij.workspaceModel.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SimpleEntityImpl : SimpleEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override var version: Int = 0
@JvmField
var _name: String? = null
override val name: String
get() = _name!!
override var isSimple: Boolean = false
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: SimpleEntityData?) : ModifiableWorkspaceEntityBase<SimpleEntity>(), SimpleEntity.Builder {
constructor() : this(SimpleEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SimpleEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isNameInitialized()) {
error("Field SimpleEntity#name should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as SimpleEntity
this.entitySource = dataSource.entitySource
this.version = dataSource.version
this.name = dataSource.name
this.isSimple = dataSource.isSimple
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var version: Int
get() = getEntityData().version
set(value) {
checkModificationAllowed()
getEntityData().version = value
changedProperty.add("version")
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData().name = value
changedProperty.add("name")
}
override var isSimple: Boolean
get() = getEntityData().isSimple
set(value) {
checkModificationAllowed()
getEntityData().isSimple = value
changedProperty.add("isSimple")
}
override fun getEntityData(): SimpleEntityData = result ?: super.getEntityData() as SimpleEntityData
override fun getEntityClass(): Class<SimpleEntity> = SimpleEntity::class.java
}
}
class SimpleEntityData : WorkspaceEntityData<SimpleEntity>() {
var version: Int = 0
lateinit var name: String
var isSimple: Boolean = false
fun isNameInitialized(): Boolean = ::name.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<SimpleEntity> {
val modifiable = SimpleEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SimpleEntity {
val entity = SimpleEntityImpl()
entity.version = version
entity._name = name
entity.isSimple = isSimple
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SimpleEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SimpleEntity(version, name, isSimple, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SimpleEntityData
if (this.entitySource != other.entitySource) return false
if (this.version != other.version) return false
if (this.name != other.name) return false
if (this.isSimple != other.isSimple) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SimpleEntityData
if (this.version != other.version) return false
if (this.name != other.name) return false
if (this.isSimple != other.isSimple) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + version.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + isSimple.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + version.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + isSimple.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | c44ef626bb0e5462c4f4f43dcbb2a929 | 29.415929 | 118 | 0.708903 | 5.219438 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/gradle/HierarchicalStructureByDefaultImportAndHighlightingTest.kt | 1 | 3320 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.gradle
import com.intellij.openapi.roots.DependencyScope
import org.jetbrains.kotlin.checkers.utils.clearTextFromDiagnosticMarkup
import org.jetbrains.kotlin.idea.codeInsight.gradle.MultiplePluginVersionGradleImportingTestCase
import org.jetbrains.plugins.gradle.tooling.annotation.PluginTargetVersions
import org.junit.Test
abstract class HierarchicalStructureByDefaultImportAndHighlightingTest : MultiplePluginVersionGradleImportingTestCase() {
override fun testDataDirName(): String = "hierarchicalStructureByDefaultImportAndHighlighting"
override fun clearTextFromMarkup(text: String): String = clearTextFromDiagnosticMarkup(text)
class TestBucket : HierarchicalStructureByDefaultImportAndHighlightingTest() {
@Test
@PluginTargetVersions(pluginVersion = "1.8.0+")
fun testCommonKlibHighlighting() {
configureByFiles()
importProject()
checkProjectStructure(exhaustiveModuleList = false, exhaustiveSourceSourceRootList = false, exhaustiveDependencyList = false) {
module("commonKlibHighlighting.commonMain") {
libraryDependency("Gradle: org.jetbrains.kotlinx:kotlinx-serialization-core:commonMain:1.3.2", DependencyScope.COMPILE)
libraryDependency("Gradle: org.jetbrains.kotlinx:kotlinx-coroutines-core:commonMain:1.6.3", DependencyScope.COMPILE)
}
module("commonKlibHighlighting.commonTest") {
libraryDependency("Gradle: org.jetbrains.kotlinx:kotlinx-serialization-core:commonMain:1.3.2", DependencyScope.TEST)
libraryDependency("Gradle: org.jetbrains.kotlinx:kotlinx-coroutines-core:commonMain:1.6.3", DependencyScope.TEST)
}
module("commonKlibHighlighting.jvmMain") {
libraryDependency("Gradle: org.jetbrains.kotlinx:kotlinx-serialization-core-jvm:1.3.2", DependencyScope.COMPILE)
libraryDependency("Gradle: org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.6.3", DependencyScope.COMPILE)
}
module("commonKlibHighlighting.jvmTest") {
libraryDependency("Gradle: org.jetbrains.kotlinx:kotlinx-serialization-core-jvm:1.3.2", DependencyScope.TEST)
libraryDependency("Gradle: org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.6.3", DependencyScope.TEST)
}
module("commonKlibHighlighting.jsMain") {
libraryDependency("Gradle: org.jetbrains.kotlinx:kotlinx-serialization-core-js:1.3.2", DependencyScope.COMPILE)
libraryDependency("Gradle: org.jetbrains.kotlinx:kotlinx-coroutines-core-js:1.6.3", DependencyScope.COMPILE)
}
module("commonKlibHighlighting.jsTest") {
libraryDependency("Gradle: org.jetbrains.kotlinx:kotlinx-serialization-core-js:1.3.2", DependencyScope.TEST)
libraryDependency("Gradle: org.jetbrains.kotlinx:kotlinx-coroutines-core-js:1.6.3", DependencyScope.TEST)
}
}
checkHighlightingOnAllModules()
}
}
} | apache-2.0 | 4eada14ff5df755dc2cdd13b0da16206 | 61.660377 | 139 | 0.698795 | 5.015106 | false | true | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/card/classic/PlusProtocol.kt | 1 | 5311 | /*
* PlusProtocol.kt
*
* Copyright 2018 Merlok
* Copyright 2018 drHatson
* Copyright 2019 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.card.classic
import au.id.micolous.metrodroid.key.ClassicSectorKey
import au.id.micolous.metrodroid.multi.Log
import au.id.micolous.metrodroid.util.Aes
import au.id.micolous.metrodroid.util.Cmac
import au.id.micolous.metrodroid.util.ImmutableByteArray
import au.id.micolous.metrodroid.card.CardTransceiver
/**
* Protocol implementation for MIFARE Plus in SL0 / SL3 mode.
*
* This is adapted from the implementation in Proxmark3.
*
* NOTE: This module is insecure, but it is enough to read cards.
*/
class PlusProtocol private constructor(private val tag: CardTransceiver,
override val sectorCount: Int) : ClassicCardTech {
var kmac: ImmutableByteArray? = null
var ti: ImmutableByteArray? = null
var rctr: Int = 0
override fun getBlockCountInSector(sectorIndex: Int) = if (sectorIndex >= 32) 16 else 4
override fun sectorToBlock(sectorIndex: Int) = if (sectorIndex < 32) sectorIndex * 4 else
(16 * sectorIndex - 32 * 12)
override val tagId: ImmutableByteArray
get() = tag.uid!!
private fun aesCmac8(macdata: ImmutableByteArray, key: ImmutableByteArray): ImmutableByteArray {
val cmac = Cmac.aesCmac(macdata, key)
return ImmutableByteArray(8) { cmac[2 * it + 1] }
}
private fun rotate(input: ImmutableByteArray) = input.sliceOffLen(1, input.size - 1) + input.sliceOffLen(0,1)
override suspend fun authenticate(sectorIndex: Int, key: ClassicSectorKey): Boolean {
if (key.key.size != ClassicSectorKey.AES_KEY_LEN) {
return false
}
val keyNum = 2 * sectorIndex + (if (key.type == ClassicSectorKey.KeyType.B) 1 else 0) + 0x4000
val cmd = ImmutableByteArray.of(0x70, keyNum.toByte(), (keyNum shr 8).toByte(), 0x06,
0, 0, 0, 0, 0, 0)
val reply = tag.transceive(cmd)
if (reply.size != 17 || reply[0] != 0x90.toByte()) {
Log.w(TAG, "Card response error $reply")
return false
}
val rndA = ImmutableByteArray(16) { (it * it).toByte() } // Doesn't matter
val rndB = Aes.decryptCbc(reply.sliceOffLen(1, 16), key.key)
val raw = rndA + rotate(rndB)
val cmd2 = ImmutableByteArray.of(0x72) + Aes.encryptCbc(raw, key.key)
val reply2 = tag.transceive(cmd2)
if (reply2.size < 33) {
Log.w(TAG, "Card response error $reply2")
return false
}
val raw2 = Aes.decryptCbc(reply2.sliceOffLen(1, 32), key.key)
val rndAPrime = raw2.sliceOffLen(4, 16)
if (rndAPrime != rotate(rndA)) {
return false
}
val kmacPlain = rndA.sliceOffLen(7, 5) + rndB.sliceOffLen(7, 5) +
(rndA.sliceOffLen(0, 5) xor rndB.sliceOffLen(0, 5)) + ImmutableByteArray.of(0x22)
ti = raw2.sliceOffLen(0, 4)
kmac = Aes.encryptCbc(kmacPlain, key.key)
rctr = 0
return true
}
private fun computeMac(input: ImmutableByteArray, ctr: Int): ImmutableByteArray {
val macdata = ImmutableByteArray.of(input[0], ctr.toByte(), (ctr shr 8).toByte()) +
ti!! + input.sliceOffLen(1, input.size - 1)
return aesCmac8(key=kmac!!, macdata=macdata)
}
override suspend fun readBlock(block: Int): ImmutableByteArray {
val cmd = ImmutableByteArray.of(0x33, block.toByte(), 0, 1)
val reply = tag.transceive(cmd + computeMac(cmd, rctr))
rctr++
return reply.sliceOffLen(1, 16)
}
override val subType: ClassicCard.SubType
get() = ClassicCard.SubType.PLUS
companion object {
private const val TAG = "PlusProtocol"
private suspend fun checkSectorPresence(tag: CardTransceiver, sectorIndex: Int): Boolean {
val keyNum = 2 * sectorIndex + 0x4000
val cmd = ImmutableByteArray.of(0x70, keyNum.toByte(), (keyNum shr 8).toByte(), 0x06,
0, 0, 0, 0, 0, 0)
val reply = tag.transceive(cmd)
return (reply.size == 17 && reply[0] == 0x90.toByte())
}
suspend fun connect(tag: CardTransceiver): PlusProtocol? {
try {
if (!checkSectorPresence(tag, 0)) {
return null
}
val capacity = if (checkSectorPresence(tag, 32)) 40 else 32
return PlusProtocol(tag = tag, sectorCount = capacity)
} catch (e: Exception) {
return null
}
}
}
}
| gpl-3.0 | 614979603f7eddd97911862c046e80af | 36.935714 | 113 | 0.629637 | 3.902278 | false | false | false | false |
android/play-billing-samples | PlayBillingCodelab/start/src/main/java/com/sample/subscriptionscodelab/ui/theme/Theme.kt | 2 | 1876 | /*
* Copyright 2022 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sample.subscriptionscodelab.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val DarkColorPalette = darkColors(
primary = Purple200,
primaryVariant = Purple700,
secondary = Teal200
)
private val LightColorPalette = lightColors(
// primary = Purple500,
// primaryVariant = Purple700,
// secondary = Teal200
surface = Blue,
onSurface = Color.White,
primary = LightBlue,
onPrimary = Navy
/* Other default colors to override
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
@Composable
fun BasicsCodelabTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable() () -> Unit
) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
}
| apache-2.0 | a3bc825870e92f87d140864f87516a2f | 26.188406 | 75 | 0.709488 | 4.434988 | false | false | false | false |
JetBrains/kotlin-spec | grammar/src/test/org/jetbrains/kotlin/spec/grammar/parsetree/KotlinParseTree.kt | 1 | 1211 | package org.jetbrains.kotlin.spec.grammar.parsetree
import org.jetbrains.kotlin.spec.grammar.util.TestUtil.ls
import java.util.regex.Pattern
enum class KotlinParseTreeNodeType { RULE, TERMINAL }
class KotlinParseTree(
private val type: KotlinParseTreeNodeType,
private val name: String,
private val text: String? = null,
val children: MutableList<KotlinParseTree> = mutableListOf()
) {
private fun stringifyTree(builder: StringBuilder, node: KotlinParseTree, depth: Int = 1): StringBuilder =
builder.apply {
node.children.forEach { child ->
when (child.type) {
KotlinParseTreeNodeType.RULE -> append(" ".repeat(depth) + child.name + ls)
KotlinParseTreeNodeType.TERMINAL -> append(
" ".repeat(depth) + child.name +
"(\"" + child.text!!.replace(ls, Pattern.quote(ls)) + "\")" + ls
)
}
stringifyTree(builder, child, depth + 1)
}
}
fun stringifyTree(root: String) = root + ls + stringifyTree(StringBuilder(), this)
}
| apache-2.0 | aa40ea57ebc387d09d1bf5342ba40691 | 40.758621 | 109 | 0.5673 | 4.535581 | false | false | false | false |
ACRA/acra | acra-limiter/src/main/java/org/acra/startup/LimiterStartupProcessor.kt | 1 | 2639 | /*
* Copyright (c) 2018
*
* 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.acra.startup
import android.content.Context
import com.google.auto.service.AutoService
import org.acra.ACRA
import org.acra.config.CoreConfiguration
import org.acra.config.LimiterConfiguration
import org.acra.config.LimiterData
import org.acra.config.getPluginConfiguration
import org.acra.log.warn
import org.acra.plugins.HasConfigPlugin
import org.acra.prefs.SharedPreferencesFactory
import org.acra.util.PackageManagerWrapper
import java.io.IOException
/**
* @author lukas
* @since 15.09.18
*/
@AutoService(StartupProcessor::class)
class LimiterStartupProcessor : HasConfigPlugin(LimiterConfiguration::class.java), StartupProcessor {
override fun processReports(context: Context, config: CoreConfiguration, reports: List<Report>) {
val limiterConfiguration = config.getPluginConfiguration<LimiterConfiguration>()
if (limiterConfiguration.deleteReportsOnAppUpdate || limiterConfiguration.resetLimitsOnAppUpdate) {
val prefs = SharedPreferencesFactory(context, config).create()
val lastVersionNr = prefs.getInt(ACRA.PREF_LAST_VERSION_NR, 0).toLong()
val appVersion = getAppVersion(context)
if (appVersion > lastVersionNr) {
if (limiterConfiguration.deleteReportsOnAppUpdate) {
prefs.edit().putInt(ACRA.PREF_LAST_VERSION_NR, appVersion).apply()
for (report in reports) {
report.delete = true
}
}
if (limiterConfiguration.resetLimitsOnAppUpdate) {
try {
LimiterData().store(context)
} catch (e: IOException) {
warn(e) { "Failed to reset LimiterData" }
}
}
}
}
}
/**
* @return app version or 0 if PackageInfo was not available.
*/
private fun getAppVersion(context: Context): Int {
return PackageManagerWrapper(context).getPackageInfo()?.versionCode ?: 0
}
} | apache-2.0 | 665c8c2035ec95618f3cc09e53b9539c | 38.402985 | 107 | 0.672224 | 4.589565 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/tests/testData/newJ2k/constructors/secondaryConstructorWithDefaultValues.kt | 7 | 197 | internal class A {
private var s = ""
private var x = 0
constructor()
@JvmOverloads
constructor(p: Int, s: String, x: Int = 1) {
this.s = s
this.x = x
}
}
| apache-2.0 | a11e9e69edc60a92e58b2a6d2e436d74 | 15.416667 | 48 | 0.502538 | 3.45614 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/startup/CheckProjectActivity.kt | 1 | 2823 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.startup
import com.intellij.configurationStore.checkUnknownMacros
import com.intellij.ide.IdeCoreBundle
import com.intellij.internal.statistic.collectors.fus.project.ProjectFsStatsCollector
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl
import com.intellij.util.TimeoutUtil
import com.intellij.util.concurrency.NonUrgentExecutor
internal class CheckProjectActivity : StartupActivity.DumbAware {
init {
if (ApplicationManager.getApplication().isHeadlessEnvironment || ApplicationManager.getApplication().isUnitTestMode) {
throw ExtensionNotApplicableException.create()
}
}
override fun runActivity(project: Project) {
NonUrgentExecutor.getInstance().execute {
checkUnknownMacros(project, true)
checkProjectRoots(project)
}
}
private fun checkProjectRoots(project: Project) {
val roots = ProjectRootManager.getInstance(project).contentRoots
if (roots.isEmpty()) {
return
}
val watcher = (LocalFileSystem.getInstance() as? LocalFileSystemImpl)?.fileWatcher
if (watcher == null || !watcher.isOperational) {
ProjectFsStatsCollector.watchedRoots(project, -1)
return
}
val logger = logger<CheckProjectActivity>()
logger.debug("FW/roots waiting started")
while (watcher.isSettingRoots) {
if (project.isDisposed) {
return
}
TimeoutUtil.sleep(10)
}
logger.debug("FW/roots waiting finished")
val manualWatchRoots = watcher.manualWatchRoots
var pctNonWatched = 0
if (manualWatchRoots.isNotEmpty()) {
val unwatched = roots.filter { root -> root.isInLocalFileSystem && manualWatchRoots.any { VfsUtilCore.isAncestorOrSelf(it, root) } }
if (unwatched.isNotEmpty()) {
val message = IdeCoreBundle.message("watcher.non.watchable.project", ApplicationNamesInfo.getInstance().fullProductName)
watcher.notifyOnFailure(message, null)
logger.info("unwatched roots: ${unwatched.map { it.presentableUrl }}")
logger.info("manual watches: ${manualWatchRoots}")
pctNonWatched = (100.0 * unwatched.size / roots.size).toInt()
}
}
ProjectFsStatsCollector.watchedRoots(project, pctNonWatched)
}
}
| apache-2.0 | eb052b456cafd0640706479607293d3b | 39.328571 | 138 | 0.759122 | 4.650741 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/views/MessageCardView.kt | 1 | 4835 | package org.wikipedia.views
import android.content.Context
import android.net.Uri
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.analytics.LoginFunnel.Companion.SOURCE_SUGGESTED_EDITS
import org.wikipedia.databinding.ViewMessageCardBinding
import org.wikipedia.login.LoginActivity
import org.wikipedia.util.StringUtil
import org.wikipedia.util.UriUtil
class MessageCardView constructor(context: Context, attrs: AttributeSet? = null) : WikiCardView(context, attrs) {
val binding = ViewMessageCardBinding.inflate(LayoutInflater.from(context), this, true)
fun setMessageTitle(title: String) {
binding.messageTitleView.text = title
}
fun setMessageText(text: String) {
binding.messageTextView.text = text
}
fun setImageResource(@DrawableRes imageResource: Int, visible: Boolean) {
if (visible) {
binding.imageView.visibility = View.VISIBLE
binding.imageView.setImageResource(imageResource)
} else {
binding.imageView.visibility = View.GONE
}
}
fun setPositiveButton(@StringRes stringRes: Int, listener: OnClickListener, applyListenerToContainer: Boolean) {
binding.positiveButton.text = context.getString(stringRes)
binding.positiveButton.setOnClickListener(listener)
if (applyListenerToContainer) {
binding.containerClickArea.setOnClickListener(listener)
}
}
fun setNegativeButton(@StringRes stringRes: Int, listener: OnClickListener, applyListenerToContainer: Boolean) {
binding.negativeButton.text = context.getString(stringRes)
binding.negativeButton.setOnClickListener(listener)
binding.negativeButton.visibility = View.VISIBLE
if (applyListenerToContainer) {
binding.containerClickArea.setOnClickListener(listener)
}
}
fun setPaused(message: String) {
setDefaultState()
binding.messageTitleView.text = context.getString(R.string.suggested_edits_paused_title)
binding.messageTextView.text = StringUtil.fromHtml(message)
binding.imageView.setImageResource(R.drawable.ic_suggested_edits_paused)
}
fun setDisabled(message: String) {
setDefaultState()
binding.messageTitleView.text = context.getString(R.string.suggested_edits_disabled_title)
binding.messageTextView.text = StringUtil.fromHtml(message)
binding.imageView.setImageResource(R.drawable.ic_suggested_edits_disabled)
}
fun setIPBlocked() {
setDefaultState()
binding.imageView.visibility = GONE
binding.messageTitleView.text = context.getString(R.string.suggested_edits_ip_blocked_title)
binding.messageTextView.text = context.getString(R.string.suggested_edits_ip_blocked_message)
binding.positiveButton.setOnClickListener { UriUtil.visitInExternalBrowser(context, Uri.parse(context.getString(R.string.create_account_ip_block_help_url))) }
setOnClickListener { UriUtil.visitInExternalBrowser(context, Uri.parse(context.getString(R.string.create_account_ip_block_help_url))) }
}
fun setRequiredLogin(fragment: Fragment) {
binding.imageView.visibility = View.VISIBLE
binding.messageTitleView.text = context.getString(R.string.suggested_edits_encourage_account_creation_title)
binding.messageTextView.text = context.getString(R.string.suggested_edits_encourage_account_creation_message)
binding.imageView.setImageResource(R.drawable.ic_require_login_header)
binding.positiveButton.text = context.getString(R.string.suggested_edits_encourage_account_creation_login_button)
binding.positiveButton.setOnClickListener { fragment.startActivityForResult(LoginActivity.newIntent(context, SOURCE_SUGGESTED_EDITS), Constants.ACTIVITY_REQUEST_LOGIN) }
binding.containerClickArea.setOnClickListener { fragment.startActivityForResult(LoginActivity.newIntent(context, SOURCE_SUGGESTED_EDITS), Constants.ACTIVITY_REQUEST_LOGIN) }
}
private fun setDefaultState() {
binding.imageView.visibility = View.VISIBLE
binding.positiveButton.text = context.getString(R.string.suggested_edits_learn_more)
binding.positiveButton.setIconResource(R.drawable.ic_open_in_new_black_24px)
binding.positiveButton.setOnClickListener { UriUtil.visitInExternalBrowser(context, Uri.parse(context.getString(R.string.android_app_edit_help_url))) }
binding.containerClickArea.setOnClickListener { UriUtil.visitInExternalBrowser(context, Uri.parse(context.getString(R.string.android_app_edit_help_url))) }
}
}
| apache-2.0 | a4d8400a03a99594e918833cc02aa349 | 48.845361 | 181 | 0.756774 | 4.587287 | false | false | false | false |
McMoonLakeDev/MoonLake | API/src/main/kotlin/com/mcmoonlake/api/packet/PacketBuffer.kt | 1 | 12564 | /*
* Copyright (C) 2016-Present The MoonLake ([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.mcmoonlake.api.packet
import com.mcmoonlake.api.block.BlockPosition
import com.mcmoonlake.api.chat.ChatComponent
import com.mcmoonlake.api.chat.ChatSerializer
import com.mcmoonlake.api.nbt.NBTCompound
import com.mcmoonlake.api.nbt.NBTFactory
import io.netty.buffer.ByteBuf
import io.netty.buffer.ByteBufInputStream
import io.netty.buffer.ByteBufOutputStream
import io.netty.buffer.Unpooled
import io.netty.handler.codec.EncoderException
import org.bukkit.Location
import org.bukkit.Material
import org.bukkit.inventory.ItemStack
import java.io.IOException
import java.nio.charset.Charset
import java.util.*
data class PacketBuffer(
private var byteBuf: ByteBuf) {
/** constructor */
constructor() : this(Unpooled.buffer())
constructor(buffer: ByteArray) : this(Unpooled.wrappedBuffer(buffer))
/** api */
fun getByteBuf(): ByteBuf
= byteBuf
fun setByteBuf(buffer: ByteBuf): PacketBuffer
{ byteBuf = buffer; return this; }
fun setByteBuf(buffer: ByteArray): PacketBuffer
{ byteBuf = Unpooled.wrappedBuffer(buffer); return this; }
fun writeByte(value: Byte): PacketBuffer
{ byteBuf.writeByte(value.toInt()); return this; }
fun writeByte(value: Int): PacketBuffer
{ byteBuf.writeByte(value); return this; }
fun writeBytes(value: ByteArray): PacketBuffer
{ byteBuf.writeBytes(value); return this; }
fun writeBytes(value: ByteBuf): PacketBuffer
{ byteBuf.writeBytes(value); return this; }
fun writeBytes(value: ByteBuf, length: Int): PacketBuffer
{ byteBuf.writeBytes(value, length); return this; }
fun writeBytes(value: ByteBuf, index: Int, length: Int): PacketBuffer
{ byteBuf.writeBytes(value, index, length); return this; }
fun writeBytes(value: PacketBuffer): PacketBuffer
{ byteBuf.writeBytes(value.byteBuf); return this; }
fun writeBytes(value: PacketBuffer, length: Int): PacketBuffer
{ byteBuf.writeBytes(value.byteBuf, length); return this; }
fun writeBytes(value: PacketBuffer, index: Int, length: Int): PacketBuffer
{ byteBuf.writeBytes(value.byteBuf, index, length); return this; }
fun writeShort(value: Int): PacketBuffer
{ byteBuf.writeShort(value); return this; }
fun writeInt(value: Int): PacketBuffer
{ byteBuf.writeInt(value); return this; }
fun writeLong(value: Long): PacketBuffer
{ byteBuf.writeLong(value); return this; }
fun writeFloat(value: Float): PacketBuffer
{ byteBuf.writeFloat(value); return this; }
fun writeDouble(value: Double): PacketBuffer
{ byteBuf.writeDouble(value); return this; }
/**
* @throws IllegalArgumentException If string [value] bytes length > 32767.
*/
@Throws(IllegalArgumentException::class)
fun writeString(value: String): PacketBuffer {
val buffer = value.toByteArray()
if(buffer.size > 32767)
throw IllegalArgumentException("字符串值字节不能大于 32767 长度.")
writeVarInt(buffer.size)
writeBytes(buffer)
return this
}
/**
* @throws IllegalArgumentException If per string for [value] bytes length > 32767.
*/
@Throws(IllegalArgumentException::class)
fun writeStrings(value: Array<out String>): PacketBuffer
{ value.forEach { writeString(it) }; return this; }
fun writeUUID(value: UUID): PacketBuffer
{ writeLong(value.mostSignificantBits); writeLong(value.leastSignificantBits); return this; }
fun writeChatComponent(value: ChatComponent): PacketBuffer
{ writeString(value.toJson()); return this; }
fun writeNBTComponent(value: NBTCompound?): PacketBuffer {
if(value == null)
return writeByte(0)
try {
val stream = ByteBufOutputStream(byteBuf)
stream.use { NBTFactory.writeData(value, it) }
} catch(e: Exception) {
throw EncoderException(e)
}
return this
}
fun writeItemStack(itemStack: ItemStack?): PacketBuffer {
if(itemStack == null || itemStack.type == Material.AIR)
return writeShort(-1)
writeShort(itemStack.type.id) // TODO v1.13
writeByte(itemStack.amount)
writeShort(itemStack.durability.toInt())
writeNBTComponent(NBTFactory.readStackTag(itemStack))
return this
}
fun writeBlockPosition(x: Int, y: Int, z: Int): PacketBuffer
{ writeLong((x.toLong() and 0x3FFFFFF shl 38) or (y.toLong() and 0xFFF shl 26) or (z.toLong() and 0x3FFFFFF)); return this; }
fun writeBlockPosition(blockPosition: BlockPosition): PacketBuffer
{ writeBlockPosition(blockPosition.x, blockPosition.y, blockPosition.z); return this; }
fun writeBlockPosition(location: Location): PacketBuffer
= writeBlockPosition(location.blockX, location.blockY, location.blockZ)
fun writeVarInt(value: Int): PacketBuffer {
var value0 = value
while((value0 and 0x7F.inv()) != 0) {
writeByte((value0 and 0x7F).or(0x80))
value0 = value0.ushr(7)
}
writeByte(value0)
return this
}
fun writeVarLong(value: Long): PacketBuffer {
var value0 = value
while((value0 and 0x7F.inv()) != 0L) {
writeByte(((value0 and 0x7F).or(0x80)).toInt())
value0 = value0.ushr(7)
}
writeByte(value0.toInt())
return this
}
fun writeBoolean(value: Boolean): PacketBuffer
{ byteBuf.writeBoolean(value); return this; }
fun readByte(): Byte
= byteBuf.readByte()
fun readUnsignedByte(): Short
= byteBuf.readUnsignedByte()
/**
* @throws IllegalArgumentException If [length] < 0.
*/
@Throws(IllegalArgumentException::class)
fun readBytes(length: Int): ByteArray {
val buffer = if(length >= 0) ByteArray(length) else throw IllegalArgumentException("待读取的数组不能小于 0 长度.")
byteBuf.readBytes(buffer)
return buffer
}
fun readBytes(value: ByteBuf): PacketBuffer
{ byteBuf.readBytes(value); return this; }
fun readBytes(value: ByteBuf, length: Int): PacketBuffer
{ byteBuf.readBytes(value, length); return this; }
fun readBytes(value: ByteBuf, index: Int, length: Int): PacketBuffer
{ byteBuf.readBytes(value, index, length); return this; }
fun readBytes(value: PacketBuffer): PacketBuffer
{ byteBuf.readBytes(value.byteBuf); return this; }
fun readBytes(value: PacketBuffer, length: Int): PacketBuffer
{ byteBuf.readBytes(value.byteBuf, length); return this; }
fun readBytes(value: PacketBuffer, index: Int, length: Int): PacketBuffer
{ byteBuf.readBytes(value.byteBuf, index, length); return this; }
fun readShort(): Short
= byteBuf.readShort()
fun readUnsignedShort(): Int
= byteBuf.readUnsignedShort()
fun readInt(): Int
= byteBuf.readInt()
fun readLong(): Long
= byteBuf.readLong()
fun readFloat(): Float
= byteBuf.readFloat()
fun readDouble(): Double
= byteBuf.readDouble()
fun readString(): String {
val length = readVarInt()
val buffer = readBytes(length)
return String(buffer)
}
fun readUUID(): UUID
= UUID(readLong(), readLong())
fun readChatComponent(): ChatComponent
= ChatSerializer.fromJsonLenient(readString())
fun readNBTComponent(): NBTCompound? {
val index = readerIndex()
val type = readByte().toInt()
if(type == 0)
return null
readerIndex(index)
try {
return NBTFactory.readDataCompound(ByteBufInputStream(byteBuf))
} catch(e: IOException) {
throw EncoderException(e)
}
}
fun readItemStack(): ItemStack? {
val typeId = readShort()
if(typeId < 0)
return ItemStack(Material.AIR)
val amount = readByte()
val durability = readShort()
val tag = readNBTComponent() // TODO v1.13
val itemStack = ItemStack(Material.getMaterial(typeId.toInt()), amount.toInt(), durability)
return NBTFactory.writeStackTag(itemStack, tag)
}
fun readBlockPosition(): BlockPosition {
val value = readLong()
val x = (value shr 38).toInt()
val y = (value shr 26 and 0xFFF).toInt()
val z = (value shl 38 shr 38).toInt()
return BlockPosition(x, y, z)
}
/**
* @throws IllegalArgumentException If VarInt length > 5.
*/
@Throws(IllegalArgumentException::class)
fun readVarInt(): Int {
var value = 0
var size = 0
var b = 0
while((readByte().toInt().apply { b = this }.and(0x80)) == 0x80) {
value = value or ((b and 0x7F) shl (size++ * 7))
if(size > 5)
throw IllegalArgumentException("VarInt 值数据太大,必须小于或等于 5 长度.")
}
return value or ((b and 0x7F) shl (size * 7))
}
/**
* @throws IllegalArgumentException If VarLong length > 10.
*/
@Throws(IllegalArgumentException::class)
fun readVarLong(): Long {
var value = 0L
var size = 0
var b = 0
while((readByte().toInt().apply { b = this }.and(0x80)) == 0x80) {
value = value or ((b and 0x7F) shl (size++ * 7)).toLong()
if(size > 10)
throw IllegalArgumentException("VarLong 值数据太大,必须小于或等于 10 长度.")
}
return value or ((b and 0x7F) shl (size * 7)).toLong()
}
fun readBoolean(): Boolean
= byteBuf.readBoolean()
fun writerIndex(): Int
= byteBuf.writerIndex()
fun writerIndex(value: Int): PacketBuffer
{ byteBuf.writerIndex(value); return this; }
fun readerIndex(): Int
= byteBuf.readerIndex()
fun readerIndex(value: Int): PacketBuffer
{ byteBuf.readerIndex(value); return this; }
fun readableBytes(): Int
= byteBuf.readableBytes()
fun writableBytes(): Int
= byteBuf.writableBytes()
fun maxWritableBytes(): Int
= byteBuf.maxWritableBytes()
fun hasArray(): Boolean
= byteBuf.hasArray()
fun array(): ByteArray
= byteBuf.array()
fun arrayOffset(): Int
= byteBuf.arrayOffset()
fun hasMemoryAddress(): Boolean
= byteBuf.hasMemoryAddress()
fun memoryAddress(): Long
= byteBuf.memoryAddress()
fun toString(charset: Charset = Charsets.UTF_8): String
= byteBuf.toString(charset)
fun toString(index: Int, length: Int, charset: Charset = Charsets.UTF_8): String
= byteBuf.toString(index, length, charset)
fun clear(): PacketBuffer
{ byteBuf.clear(); return this; }
fun release(): Boolean
= byteBuf.release()
fun release(decrement: Int): Boolean
= byteBuf.release(decrement)
override fun equals(other: Any?): Boolean {
if(other === this)
return true
if(other is PacketBuffer)
return byteBuf == other.byteBuf
else if(other is ByteBuf)
return byteBuf == other
return false
}
override fun hashCode(): Int {
return byteBuf.hashCode()
}
override fun toString(): String {
return "PacketBuffer(byteBuf=$byteBuf)"
}
companion object {
/**
* * Empty bytes of PacketBuffer.
*/
@JvmField
val EMPTY = PacketBuffer(Unpooled.EMPTY_BUFFER)
}
}
| gpl-3.0 | 8e6cc976c2cc50ddbd7a79c0a7ad206d | 31.26943 | 137 | 0.627649 | 4.522876 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/project/actions/MavenDependencyAnalyzerAction.kt | 1 | 3550 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.project.actions
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.externalSystem.dependency.analyzer.*
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.module.Module
import com.intellij.ui.treeStructure.SimpleTree
import org.jetbrains.idea.maven.navigator.MavenProjectsStructure.*
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.utils.MavenUtil
class ViewDependencyAnalyzerAction : AbstractDependencyAnalyzerAction<MavenSimpleNode>() {
override fun getSystemId(e: AnActionEvent): ProjectSystemId = MavenUtil.SYSTEM_ID
override fun getSelectedData(e: AnActionEvent): MavenSimpleNode? {
val data = e.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT)
return (data as? SimpleTree)?.selectedNode as? MavenSimpleNode
}
override fun getModule(e: AnActionEvent, selectedData: MavenSimpleNode): Module? {
val project = e.project ?: return null
val projectNode = selectedData.findNode(ProjectNode::class.java) ?: return null
val mavenProjectsManager = MavenProjectsManager.getInstance(project)
return mavenProjectsManager.findModule(projectNode.mavenProject)
}
override fun getDependencyData(e: AnActionEvent, selectedData: MavenSimpleNode): DependencyAnalyzerDependency.Data? {
return when (selectedData) {
is DependencyNode -> {
DAArtifact(
selectedData.artifact.groupId,
selectedData.artifact.artifactId,
selectedData.artifact.version
)
}
is ProjectNode -> {
DAModule(selectedData.mavenProject.displayName)
}
else -> null
}
}
override fun getDependencyScope(e: AnActionEvent, selectedData: MavenSimpleNode): String? {
if (selectedData is DependencyNode) {
return selectedData.artifact.scope
}
return null
}
}
class NavigatorDependencyAnalyzerAction : DependencyAnalyzerAction() {
private val viewAction = ViewDependencyAnalyzerAction()
override fun getSystemId(e: AnActionEvent): ProjectSystemId = MavenUtil.SYSTEM_ID
override fun isEnabledAndVisible(e: AnActionEvent) = true
override fun setSelectedState(view: DependencyAnalyzerView, e: AnActionEvent) {
viewAction.setSelectedState(view, e)
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
}
class ProjectViewDependencyAnalyzerAction : AbstractDependencyAnalyzerAction<Module>() {
override fun getSystemId(e: AnActionEvent): ProjectSystemId = MavenUtil.SYSTEM_ID
override fun getSelectedData(e: AnActionEvent): Module? {
val project = e.project ?: return null
val module = e.getData(PlatformCoreDataKeys.MODULE) ?: return null
if (MavenProjectsManager.getInstance(project).isMavenizedModule(module)) {
return module
}
return null
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun getModule(e: AnActionEvent, selectedData: Module): Module {
return selectedData
}
override fun getDependencyData(e: AnActionEvent, selectedData: Module): DependencyAnalyzerDependency.Data {
return DAModule(selectedData.name)
}
override fun getDependencyScope(e: AnActionEvent, selectedData: Module) = null
}
| apache-2.0 | ea5b2ac1e3ec0a64c87ab37cc9f46fcd | 36.368421 | 158 | 0.774085 | 4.896552 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/notification/impl/NotificationsEventLogGroup.kt | 6 | 3818 | // 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.notification.impl
import com.intellij.internal.statistic.collectors.fus.actions.persistence.ActionsEventLogGroup
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.*
import com.intellij.internal.statistic.eventLog.events.EventFields.Boolean
import com.intellij.internal.statistic.eventLog.events.EventFields.Enum
import com.intellij.internal.statistic.eventLog.events.EventFields.StringValidatedByCustomRule
import com.intellij.internal.statistic.eventLog.events.EventFields.StringValidatedByInlineRegexp
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.notification.NotificationDisplayType
import com.intellij.notification.impl.NotificationCollector.*
import java.util.stream.Collectors
class NotificationsEventLogGroup : CounterUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
companion object {
@JvmField
val GROUP = EventLogGroup("notifications", 66)
@JvmField
val DISPLAY_TYPE: EnumEventField<NotificationDisplayType> = Enum("display_type", NotificationDisplayType::class.java)
@JvmField
val SEVERITY: EnumEventField<NotificationSeverity> = Enum("severity", NotificationSeverity::class.java)
@JvmField
val IS_EXPANDABLE = Boolean("is_expandable")
@JvmField
val ID: StringEventField = StringValidatedByInlineRegexp("id", "\\d+.\\d+")
@JvmField
val NOTIFICATION_ID = NotificationIdField()
@JvmField
val ADDITIONAL = ObjectEventField("additional", NOTIFICATION_ID)
@JvmField
val NOTIFICATION_GROUP_ID = StringValidatedByCustomRule("notification_group", NotificationGroupValidator::class.java)
@JvmField
val NOTIFICATION_PLACE: EnumEventField<NotificationPlace> = Enum("notification_place", NotificationPlace::class.java)
@JvmField
val SHOWN = registerNotificationEvent("shown", DISPLAY_TYPE, SEVERITY, IS_EXPANDABLE)
@JvmField
val LOGGED = registerNotificationEvent("logged", SEVERITY)
@JvmField
val CLOSED_BY_USER = registerNotificationEvent("closed.by.user")
@JvmField
val ACTION_INVOKED = registerNotificationEvent("action.invoked", ActionsEventLogGroup.ACTION_CLASS,
ActionsEventLogGroup.ACTION_ID, ActionsEventLogGroup.ACTION_PARENT, NOTIFICATION_PLACE)
@JvmField
val HYPERLINK_CLICKED = registerNotificationEvent("hyperlink.clicked")
@JvmField
val EVENT_LOG_BALLOON_SHOWN = registerNotificationEvent("event.log.balloon.shown")
@JvmField
val SETTINGS_CLICKED = registerNotificationEvent("settings.clicked")
@JvmField
val BALLOON_EXPANDED = registerNotificationEvent("balloon.expanded")
@JvmField
val BALLOON_COLLAPSED = registerNotificationEvent("balloon.collapsed")
fun registerNotificationEvent(eventId: String, vararg extraFields: EventField<*>): VarargEventId {
return GROUP.registerVarargEvent(
eventId,
ID,
ADDITIONAL,
NOTIFICATION_GROUP_ID,
EventFields.PluginInfo,
*extraFields
)
}
}
class NotificationIdField : StringEventField("display_id") {
override val validationRule: List<String>
get() {
val validationRules = NotificationIdsHolder.EP_NAME.extensionList.stream()
.flatMap { holder: NotificationIdsHolder -> holder.notificationIds.stream() }
.collect(Collectors.toList())
validationRules.add(NotificationCollector.UNKNOWN)
return listOf("{enum:${validationRules.joinToString("|")}}", "{util#notification_display_id}")
}
}
} | apache-2.0 | 355f512689e09b5d34a4d82770d2e9d8 | 38.371134 | 158 | 0.751702 | 5.056954 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/kendra/src/main/kotlin/com/example/kendra/CreateIndexAndDataSourceExample.kt | 1 | 6599 | // snippet-sourcedescription:[CreateIndexAndDataSourceExample.kt demonstrates how to create an Amazon Kendra index and data source.]
// snippet-keyword:[SDK for Kotlin]
// snippet-service:[Amazon Kendra]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.kendra
// snippet-start:[kendra.kotlin.index.import]
import aws.sdk.kotlin.services.kendra.KendraClient
import aws.sdk.kotlin.services.kendra.model.CreateDataSourceRequest
import aws.sdk.kotlin.services.kendra.model.CreateIndexRequest
import aws.sdk.kotlin.services.kendra.model.DataSourceConfiguration
import aws.sdk.kotlin.services.kendra.model.DataSourceStatus
import aws.sdk.kotlin.services.kendra.model.DataSourceType
import aws.sdk.kotlin.services.kendra.model.DescribeDataSourceRequest
import aws.sdk.kotlin.services.kendra.model.DescribeIndexRequest
import aws.sdk.kotlin.services.kendra.model.IndexStatus
import aws.sdk.kotlin.services.kendra.model.S3DataSourceConfiguration
import aws.sdk.kotlin.services.kendra.model.StartDataSourceSyncJobRequest
import kotlinx.coroutines.delay
import java.util.concurrent.TimeUnit
import kotlin.system.exitProcess
// snippet-end:[kendra.kotlin.index.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<indexDescription> <indexName> <indexRoleArn> <dataSourceRoleArn> <dataSourceName> <dataSourceDescription> <s3BucketName>
Where:
indexDescription - A description for the index.
indexName - The name for the new index.
indexRoleArn - An AWS Identity and Access Management (IAM) role that gives Amazon Kendra permissions to access your Amazon CloudWatch logs and metrics.
dataSourceRoleArn - The Amazon Resource Name (ARN) of an IAM role with permissions to access the data source.
dataSourceName - The name for the new data source.
dataSourceDescription - A description for the data source.
s3BucketName - An Amazon S3 bucket used as your data source.
"""
if (args.size != 7) {
println(usage)
exitProcess(1)
}
val indexDescription = args[0]
val indexName = args[1]
val indexRoleArn = args[2]
val dataSourceRoleArn = args[3]
val dataSourceName = args[4]
val dataSourceDescription = args[5]
val s3BucketName = args[6]
val indexId = createIndex(indexDescription, indexName, indexRoleArn)
println("The index is is $indexId")
val dsIdValue = createDataSource(s3BucketName, dataSourceName, dataSourceDescription, indexId, dataSourceRoleArn)
startDataSource(indexId, dsIdValue)
}
// snippet-start:[kendra.kotlin.index.main]
suspend fun createIndex(indexDescription: String, indexName: String, indexRoleArn: String): String {
println("Creating an index named $indexName")
val createIndexRequest = CreateIndexRequest {
description = indexDescription
name = indexName
roleArn = indexRoleArn
}
KendraClient { region = "us-east-1" }.use { kendra ->
val createIndexResponse = kendra.createIndex(createIndexRequest)
val indexId = createIndexResponse.id
println("Waiting until the index with index ID $indexId is created.")
while (true) {
val describeIndexRequest = DescribeIndexRequest {
id = indexId
}
val describeIndexResponse = kendra.describeIndex(describeIndexRequest)
val status = describeIndexResponse.status
println("Status is $status")
if (status !== IndexStatus.Creating) {
break
}
TimeUnit.SECONDS.sleep(60)
}
return indexId.toString()
}
}
// snippet-end:[kendra.kotlin.index.main]
// snippet-start:[kendra.kotlin.datasource.main]
suspend fun createDataSource(s3BucketName: String?, dataSourceName: String?, dataSourceDescription: String?, indexIdVal: String?, dataSourceRoleArn: String?): String {
println("Creating an S3 data source")
val createDataSourceRequest = CreateDataSourceRequest {
indexId = indexIdVal
name = dataSourceName
description = dataSourceDescription
roleArn = dataSourceRoleArn
type = DataSourceType.S3
configuration = DataSourceConfiguration {
s3Configuration = S3DataSourceConfiguration {
bucketName = s3BucketName
}
}
}
KendraClient { region = "us-east-1" }.use { kendra ->
val createDataSourceResponse = kendra.createDataSource(createDataSourceRequest)
println("Response of creating data source $createDataSourceResponse")
val dataSourceId = createDataSourceResponse.id
println("Waiting for Kendra to create the data source $dataSourceId")
val describeDataSourceRequest = DescribeDataSourceRequest {
indexId = indexIdVal
id = dataSourceId
}
var finished = false
while (!finished) {
val describeDataSourceResponse = kendra.describeDataSource(describeDataSourceRequest)
val status = describeDataSourceResponse.status
println("Status is $status")
if (status !== DataSourceStatus.Creating)
finished = true
delay(30000)
}
return dataSourceId.toString()
}
}
// snippet-end:[kendra.kotlin.datasource.main]
// snippet-start:[kendra.kotlin.start.datasource.main]
suspend fun startDataSource(indexIdVal: String?, dataSourceId: String?) {
println("Synchronize the data source $dataSourceId")
val startDataSourceSyncJobRequest = StartDataSourceSyncJobRequest {
indexId = indexIdVal
id = dataSourceId
}
KendraClient { region = "us-east-1" }.use { kendra ->
val startDataSourceSyncJobResponse = kendra.startDataSourceSyncJob(startDataSourceSyncJobRequest)
println("Waiting for the data source to sync with the index $indexIdVal for execution ID ${startDataSourceSyncJobResponse.executionId}")
}
println("Index setup is complete")
}
// snippet-end:[kendra.kotlin.start.datasource.main]
| apache-2.0 | d8bbf2677294f29d64577a1c13723f60 | 38.734568 | 167 | 0.691771 | 4.495232 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/sns/src/main/kotlin/com/kotlin/sns/DeleteTopic.kt | 1 | 1625 | // snippet-sourcedescription:[DeleteTopic.kt demonstrates how to delete an Amazon Simple Notification Service (Amazon SNS) topic.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-keyword:[Amazon Simple Notification Service]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.sns
// snippet-start:[sns.kotlin.DeleteTopic.import]
import aws.sdk.kotlin.services.sns.SnsClient
import aws.sdk.kotlin.services.sns.model.DeleteTopicRequest
import kotlin.system.exitProcess
// snippet-end:[sns.kotlin.DeleteTopic.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<topicName>
Where:
topicArn - The ARN of the topic to delete.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val topicArn = args[0]
deleteSNSTopic(topicArn)
}
// snippet-start:[sns.kotlin.DeleteTopic.main]
suspend fun deleteSNSTopic(topicArnVal: String) {
val request = DeleteTopicRequest {
topicArn = topicArnVal
}
SnsClient { region = "us-east-1" }.use { snsClient ->
snsClient.deleteTopic(request)
println("$topicArnVal was successfully deleted.")
}
}
// snippet-end:[sns.kotlin.DeleteTopic.main]
| apache-2.0 | fb30e54d9426fa5ea0a4854d7a33793e | 26.508772 | 130 | 0.675077 | 3.832547 | false | false | false | false |
JuliaSoboleva/SmartReceiptsLibrary | app/src/main/java/co/smartreceipts/android/model/impl/columns/distance/DistanceColumnDefinitions.kt | 2 | 3500 | package co.smartreceipts.android.model.impl.columns.distance
import androidx.annotation.StringRes
import co.smartreceipts.android.R
import co.smartreceipts.android.date.DateFormatter
import co.smartreceipts.android.model.*
import co.smartreceipts.android.model.impl.columns.AbstractColumnImpl
import co.smartreceipts.android.model.impl.columns.distance.DistanceColumnDefinitions.ActualDefinition.*
import co.smartreceipts.android.settings.UserPreferenceManager
import co.smartreceipts.core.sync.model.SyncState
import co.smartreceipts.core.sync.model.impl.DefaultSyncState
import co.smartreceipts.android.workers.reports.ReportResourcesManager
import java.util.*
/**
* Provides specific definitions for all [Distance] [Column] objects
*/
class DistanceColumnDefinitions(
private val reportResourcesManager: ReportResourcesManager,
private val preferences: UserPreferenceManager,
private val dateFormatter: DateFormatter,
private val allowSpecialCharacters: Boolean
) : ColumnDefinitions<Distance> {
private val actualDefinitions = values()
/**
* Note: Column types must be unique
* Column type must be >= 0
*/
internal enum class ActualDefinition(
override val columnType: Int,
@StringRes override val columnHeaderId: Int
) : ActualColumnDefinition {
LOCATION(0, R.string.distance_location_field),
PRICE(1, R.string.distance_price_field),
DISTANCE(2, R.string.distance_distance_field),
CURRENCY(3, R.string.dialog_currency_field),
RATE(4, R.string.distance_rate_field),
DATE(5, R.string.distance_date_field),
COMMENT(6, R.string.distance_comment_field);
}
override fun getColumn(
id: Int,
columnType: Int,
syncState: SyncState,
ignoredCustomOrderId: Long,
ignoredUUID: UUID
): Column<Distance> {
for (definition in actualDefinitions) {
if (columnType == definition.columnType) {
return getColumnFromClass(definition, id, syncState)
}
}
throw IllegalArgumentException("Unknown column type: $columnType")
}
override fun getAllColumns(): List<Column<Distance>> {
val columns = ArrayList<AbstractColumnImpl<Distance>>(actualDefinitions.size)
for (definition in actualDefinitions) {
columns.add(getColumnFromClass(definition))
}
return ArrayList<Column<Distance>>(columns)
}
override fun getDefaultInsertColumn(): Column<Distance> {
// Hack for the distance default until we let users dynamically set columns. Actually, this will never be called
return getColumnFromClass(DISTANCE)
}
private fun getColumnFromClass(
definition: ActualDefinition,
id: Int = Keyed.MISSING_ID,
syncState: SyncState = DefaultSyncState()
): AbstractColumnImpl<Distance> {
val localizedContext = reportResourcesManager.getLocalizedContext()
return when (definition) {
LOCATION -> DistanceLocationColumn(id, syncState, localizedContext)
PRICE -> DistancePriceColumn(id, syncState, allowSpecialCharacters)
DISTANCE -> DistanceDistanceColumn(id, syncState)
CURRENCY -> DistanceCurrencyColumn(id, syncState)
RATE -> DistanceRateColumn(id, syncState)
DATE -> DistanceDateColumn(id, syncState, dateFormatter)
COMMENT -> DistanceCommentColumn(id, syncState)
}
}
}
| agpl-3.0 | 5934df56f975b406e579c52d74406455 | 37.888889 | 120 | 0.705714 | 4.840941 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/service/internship/InternshipCompanyServiceImpl.kt | 1 | 24640 | package top.zbeboy.isy.service.internship
import org.jooq.*
import org.jooq.impl.DSL
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import org.springframework.util.ObjectUtils
import org.springframework.util.StringUtils
import top.zbeboy.isy.domain.Tables.*
import top.zbeboy.isy.domain.tables.daos.InternshipCompanyDao
import top.zbeboy.isy.domain.tables.pojos.InternshipCompany
import top.zbeboy.isy.domain.tables.records.InternshipApplyRecord
import top.zbeboy.isy.domain.tables.records.InternshipChangeHistoryRecord
import top.zbeboy.isy.domain.tables.records.InternshipCompanyRecord
import top.zbeboy.isy.service.plugin.DataTablesPlugin
import top.zbeboy.isy.service.util.DateTimeUtils
import top.zbeboy.isy.service.util.SQLQueryUtils
import top.zbeboy.isy.service.util.UUIDUtils
import top.zbeboy.isy.web.util.DataTablesUtils
import top.zbeboy.isy.web.vo.internship.apply.InternshipCompanyVo
import java.sql.Timestamp
import java.time.Clock
import java.util.*
import javax.annotation.Resource
/**
* Created by zbeboy 2017-12-27 .
**/
@Service("internshipCompanyService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
open class InternshipCompanyServiceImpl @Autowired constructor(dslContext: DSLContext) : DataTablesPlugin<InternshipCompany>(), InternshipCompanyService {
private val create: DSLContext = dslContext
@Resource
open lateinit var internshipCompanyDao: InternshipCompanyDao
override fun findById(id: String): InternshipCompany {
return internshipCompanyDao.findById(id)
}
override fun findByInternshipReleaseIdAndStudentId(internshipReleaseId: String, studentId: Int): Optional<Record> {
return create.select()
.from(INTERNSHIP_COMPANY)
.where(INTERNSHIP_COMPANY.INTERNSHIP_RELEASE_ID.eq(internshipReleaseId).and(INTERNSHIP_COMPANY.STUDENT_ID.eq(studentId)))
.fetchOptional()
}
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
override fun save(internshipCompany: InternshipCompany) {
internshipCompanyDao.insert(internshipCompany)
}
override fun saveWithTransaction(internshipCompanyVo: InternshipCompanyVo) {
create.transaction { configuration ->
val now = Timestamp(Clock.systemDefaultZone().millis())
val state = 0
DSL.using(configuration)
.insertInto<InternshipApplyRecord>(INTERNSHIP_APPLY)
.set(INTERNSHIP_APPLY.INTERNSHIP_APPLY_ID, UUIDUtils.getUUID())
.set(INTERNSHIP_APPLY.INTERNSHIP_RELEASE_ID, internshipCompanyVo.internshipReleaseId)
.set(INTERNSHIP_APPLY.STUDENT_ID, internshipCompanyVo.studentId)
.set(INTERNSHIP_APPLY.APPLY_TIME, now)
.set(INTERNSHIP_APPLY.INTERNSHIP_APPLY_STATE, state)
.execute()
val headmasterArr = internshipCompanyVo.headmaster!!.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (headmasterArr.size >= 2) {
internshipCompanyVo.headmaster = headmasterArr[0]
internshipCompanyVo.headmasterContact = headmasterArr[1]
}
val schoolGuidanceTeacherArr = internshipCompanyVo.schoolGuidanceTeacher!!.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (schoolGuidanceTeacherArr.size >= 2) {
internshipCompanyVo.schoolGuidanceTeacher = schoolGuidanceTeacherArr[0]
internshipCompanyVo.schoolGuidanceTeacherTel = schoolGuidanceTeacherArr[1]
}
DSL.using(configuration)
.insertInto<InternshipCompanyRecord>(INTERNSHIP_COMPANY)
.set(INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID, UUIDUtils.getUUID())
.set(INTERNSHIP_COMPANY.STUDENT_ID, internshipCompanyVo.studentId)
.set(INTERNSHIP_COMPANY.STUDENT_USERNAME, internshipCompanyVo.studentUsername)
.set(INTERNSHIP_COMPANY.INTERNSHIP_RELEASE_ID, internshipCompanyVo.internshipReleaseId)
.set(INTERNSHIP_COMPANY.STUDENT_NAME, internshipCompanyVo.studentName)
.set(INTERNSHIP_COMPANY.COLLEGE_CLASS, internshipCompanyVo.collegeClass)
.set(INTERNSHIP_COMPANY.STUDENT_SEX, internshipCompanyVo.studentSex)
.set(INTERNSHIP_COMPANY.STUDENT_NUMBER, internshipCompanyVo.studentNumber)
.set(INTERNSHIP_COMPANY.PHONE_NUMBER, internshipCompanyVo.phoneNumber)
.set(INTERNSHIP_COMPANY.QQ_MAILBOX, internshipCompanyVo.qqMailbox)
.set(INTERNSHIP_COMPANY.PARENTAL_CONTACT, internshipCompanyVo.parentalContact)
.set(INTERNSHIP_COMPANY.HEADMASTER, internshipCompanyVo.headmaster)
.set(INTERNSHIP_COMPANY.HEADMASTER_CONTACT, internshipCompanyVo.headmasterContact)
.set(INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_NAME, internshipCompanyVo.internshipCompanyName)
.set(INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ADDRESS, internshipCompanyVo.internshipCompanyAddress)
.set(INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_CONTACTS, internshipCompanyVo.internshipCompanyContacts)
.set(INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_TEL, internshipCompanyVo.internshipCompanyTel)
.set(INTERNSHIP_COMPANY.SCHOOL_GUIDANCE_TEACHER, internshipCompanyVo.schoolGuidanceTeacher)
.set(INTERNSHIP_COMPANY.SCHOOL_GUIDANCE_TEACHER_TEL, internshipCompanyVo.schoolGuidanceTeacherTel)
.set(INTERNSHIP_COMPANY.START_TIME, DateTimeUtils.formatDate(internshipCompanyVo.startTime!!))
.set(INTERNSHIP_COMPANY.END_TIME, DateTimeUtils.formatDate(internshipCompanyVo.endTime!!))
.execute()
DSL.using(configuration)
.insertInto<InternshipChangeHistoryRecord>(INTERNSHIP_CHANGE_HISTORY)
.set(INTERNSHIP_CHANGE_HISTORY.INTERNSHIP_CHANGE_HISTORY_ID, UUIDUtils.getUUID())
.set(INTERNSHIP_CHANGE_HISTORY.INTERNSHIP_RELEASE_ID, internshipCompanyVo.internshipReleaseId)
.set(INTERNSHIP_CHANGE_HISTORY.STUDENT_ID, internshipCompanyVo.studentId)
.set(INTERNSHIP_CHANGE_HISTORY.STATE, state)
.set(INTERNSHIP_CHANGE_HISTORY.APPLY_TIME, now)
.execute()
}
}
override fun update(internshipCompany: InternshipCompany) {
internshipCompanyDao.update(internshipCompany)
}
override fun deleteByInternshipReleaseIdAndStudentId(internshipReleaseId: String, studentId: Int) {
create.deleteFrom<InternshipCompanyRecord>(INTERNSHIP_COMPANY)
.where(INTERNSHIP_COMPANY.INTERNSHIP_RELEASE_ID.eq(internshipReleaseId).and(INTERNSHIP_COMPANY.STUDENT_ID.eq(studentId)))
.execute()
}
override fun findAllByPage(dataTablesUtils: DataTablesUtils<InternshipCompany>, internshipCompany: InternshipCompany): Result<Record> {
return dataPagingQueryAllWithCondition(dataTablesUtils, create, INTERNSHIP_COMPANY, INTERNSHIP_COMPANY.INTERNSHIP_RELEASE_ID.eq(internshipCompany.internshipReleaseId))
}
override fun countAll(internshipCompany: InternshipCompany): Int {
return statisticsAllWithCondition(create, INTERNSHIP_COMPANY, INTERNSHIP_COMPANY.INTERNSHIP_RELEASE_ID.eq(internshipCompany.internshipReleaseId))
}
override fun countByCondition(dataTablesUtils: DataTablesUtils<InternshipCompany>, internshipCompany: InternshipCompany): Int {
return statisticsWithCondition(dataTablesUtils, create, INTERNSHIP_COMPANY, INTERNSHIP_COMPANY.INTERNSHIP_RELEASE_ID.eq(internshipCompany.internshipReleaseId))
}
override fun exportData(dataTablesUtils: DataTablesUtils<InternshipCompany>, internshipCompany: InternshipCompany): Result<Record> {
return dataPagingQueryAllWithConditionNoPage(dataTablesUtils, create, INTERNSHIP_COMPANY, INTERNSHIP_COMPANY.INTERNSHIP_RELEASE_ID.eq(internshipCompany.internshipReleaseId))
}
/**
* 全局搜索条件
*
* @param dataTablesUtils datatables工具类
* @return 搜索条件
*/
override fun searchCondition(dataTablesUtils: DataTablesUtils<InternshipCompany>): Condition? {
var a: Condition? = null
val search = dataTablesUtils.search
if (!ObjectUtils.isEmpty(search)) {
val studentName = StringUtils.trimWhitespace(search!!.getString("studentName"))
val studentNumber = StringUtils.trimWhitespace(search.getString("studentNumber"))
val collegeClass = StringUtils.trimWhitespace(search.getString("collegeClass"))
val phoneNumber = StringUtils.trimWhitespace(search.getString("phoneNumber"))
val headmaster = StringUtils.trimWhitespace(search.getString("headmaster"))
val schoolGuidanceTeacher = StringUtils.trimWhitespace(search.getString("schoolGuidanceTeacher"))
if (StringUtils.hasLength(studentName)) {
a = INTERNSHIP_COMPANY.STUDENT_NAME.like(SQLQueryUtils.likeAllParam(studentName))
}
if (StringUtils.hasLength(studentNumber)) {
a = if (ObjectUtils.isEmpty(a)) {
INTERNSHIP_COMPANY.STUDENT_NUMBER.like(SQLQueryUtils.likeAllParam(studentNumber))
} else {
a!!.and(INTERNSHIP_COMPANY.STUDENT_NUMBER.like(SQLQueryUtils.likeAllParam(studentNumber)))
}
}
if (StringUtils.hasLength(collegeClass)) {
a = if (ObjectUtils.isEmpty(a)) {
INTERNSHIP_COMPANY.COLLEGE_CLASS.like(SQLQueryUtils.likeAllParam(collegeClass))
} else {
a!!.and(INTERNSHIP_COMPANY.COLLEGE_CLASS.like(SQLQueryUtils.likeAllParam(collegeClass)))
}
}
if (StringUtils.hasLength(phoneNumber)) {
a = if (ObjectUtils.isEmpty(a)) {
INTERNSHIP_COMPANY.PHONE_NUMBER.like(SQLQueryUtils.likeAllParam(phoneNumber))
} else {
a!!.and(INTERNSHIP_COMPANY.PHONE_NUMBER.like(SQLQueryUtils.likeAllParam(phoneNumber)))
}
}
if (StringUtils.hasLength(headmaster)) {
a = if (ObjectUtils.isEmpty(a)) {
INTERNSHIP_COMPANY.HEADMASTER.like(SQLQueryUtils.likeAllParam(headmaster))
} else {
a!!.and(INTERNSHIP_COMPANY.HEADMASTER.like(SQLQueryUtils.likeAllParam(headmaster)))
}
}
if (StringUtils.hasLength(schoolGuidanceTeacher)) {
a = if (ObjectUtils.isEmpty(a)) {
INTERNSHIP_COMPANY.SCHOOL_GUIDANCE_TEACHER.like(SQLQueryUtils.likeAllParam(schoolGuidanceTeacher))
} else {
a!!.and(INTERNSHIP_COMPANY.SCHOOL_GUIDANCE_TEACHER.like(SQLQueryUtils.likeAllParam(schoolGuidanceTeacher)))
}
}
}
return a
}
/**
* 数据排序
*
* @param dataTablesUtils datatables工具类
* @param selectConditionStep 条件
*/
override fun sortCondition(dataTablesUtils: DataTablesUtils<InternshipCompany>, selectConditionStep: SelectConditionStep<Record>?, selectJoinStep: SelectJoinStep<Record>?, type: Int) {
val orderColumnName = dataTablesUtils.orderColumnName
val orderDir = dataTablesUtils.orderDir
val isAsc = "asc".equals(orderDir, ignoreCase = true)
var sortField: Array<SortField<*>?>? = null
if (StringUtils.hasLength(orderColumnName)) {
if ("student_name".equals(orderColumnName!!, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.STUDENT_NAME.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.STUDENT_NAME.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("student_number".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(1)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.STUDENT_NUMBER.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.STUDENT_NUMBER.desc()
}
}
if ("college_class".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.COLLEGE_CLASS.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.COLLEGE_CLASS.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("student_sex".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.STUDENT_SEX.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.STUDENT_SEX.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("phone_number".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(1)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.PHONE_NUMBER.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.PHONE_NUMBER.desc()
}
}
if ("qq_mailbox".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.QQ_MAILBOX.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.QQ_MAILBOX.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("parental_contact".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.PARENTAL_CONTACT.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.PARENTAL_CONTACT.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("headmaster".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.HEADMASTER.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.HEADMASTER.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("headmaster_contact".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.HEADMASTER_CONTACT.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.HEADMASTER_CONTACT.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("internship_company_name".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_NAME.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_NAME.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("internship_company_address".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ADDRESS.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ADDRESS.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("internship_company_contacts".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_CONTACTS.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_CONTACTS.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("internship_company_tel".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_TEL.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_TEL.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("school_guidance_teacher".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.SCHOOL_GUIDANCE_TEACHER.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.SCHOOL_GUIDANCE_TEACHER.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("school_guidance_teacher_tel".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.SCHOOL_GUIDANCE_TEACHER_TEL.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.SCHOOL_GUIDANCE_TEACHER_TEL.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("start_time".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.START_TIME.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.START_TIME.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("end_time".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.END_TIME.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.END_TIME.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("commitment_book".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.COMMITMENT_BOOK.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.COMMITMENT_BOOK.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("safety_responsibility_book".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.SAFETY_RESPONSIBILITY_BOOK.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.SAFETY_RESPONSIBILITY_BOOK.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("practice_agreement".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.PRACTICE_AGREEMENT.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.PRACTICE_AGREEMENT.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("internship_application".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.INTERNSHIP_APPLICATION.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.INTERNSHIP_APPLICATION.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("practice_receiving".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.PRACTICE_RECEIVING.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.PRACTICE_RECEIVING.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("security_education_agreement".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.SECURITY_EDUCATION_AGREEMENT.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.SECURITY_EDUCATION_AGREEMENT.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
if ("parental_consent".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = INTERNSHIP_COMPANY.PARENTAL_CONSENT.asc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.asc()
} else {
sortField[0] = INTERNSHIP_COMPANY.PARENTAL_CONSENT.desc()
sortField[1] = INTERNSHIP_COMPANY.INTERNSHIP_COMPANY_ID.desc()
}
}
}
sortToFinish(selectConditionStep, selectJoinStep, type, *sortField!!)
}
} | mit | d56783271a5d8b6f7b22f292105fe30c | 49.925466 | 188 | 0.602334 | 5.070295 | false | false | false | false |
google/intellij-community | uast/uast-common/src/org/jetbrains/uast/generate/UastCodeGenerationPlugin.kt | 3 | 8075 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.uast.generate
import com.intellij.lang.Language
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.*
/**
* Extensions which provides code generation support for generating UAST expressions.
*
* @see org.jetbrains.uast.UastLanguagePlugin
*/
@ApiStatus.Experimental
interface UastCodeGenerationPlugin {
companion object {
private val extensionPointName = ExtensionPointName<UastCodeGenerationPlugin>("org.jetbrains.uast.generate.uastCodeGenerationPlugin")
@JvmStatic
fun byLanguage(language: Language) = extensionPointName.extensionList.asSequence().firstOrNull { it.language == language }
}
/**
* @return An element factory that allows generating various UAST expressions.
*/
fun getElementFactory(project: Project): UastElementFactory
/**
* The underlying programming language.
*/
val language: Language
/**
* Replaces a [UElement] by another [UElement] and automatically shortens the reference, if any.
*/
fun <T : UElement> replace(oldElement: UElement, newElement: T, elementType: Class<T>): T?
/**
* Changes the reference so that it starts to point to the specified element. This is called,
* for example, by the "Create Class from New" quickfix, to bind the (invalid) reference on
* which the quickfix was called to the newly created class.
*
* @param reference the reference to rebind
* @param element the element which should become the target of the reference.
* @return the new underlying element of the reference.
*/
fun bindToElement(reference: UReferenceExpression, element: PsiElement): PsiElement?
/**
* Replaces fully-qualified class names in the contents of the specified element with
* non-qualified names and adds import statements as necessary.
*
* Example:
* ```
* com.jetbrains.uast.generate.UastCodeGenerationPlugin.byLanguage(...)
* ```
* Becomes:
* ```
* import com.jetbrains.uast.generate.UastCodeGenerationPlugin
*
* UastCodeGenerationPlugin.byLanguage(...)
* ```
*
* @param reference the element to shorten references in.
* @return the element after the shorten references operation corresponding to the original element.
*/
fun shortenReference(reference: UReferenceExpression): UReferenceExpression?
/**
* Import the qualifier of the specified element as an on demand import (star import).
*
* Example:
* ```
* UastCodeGenerationPlugin.byLanguage(...)
* ```
* Becomes:
* ```
* import com.jetbrains.uast.generate.UastCodeGenerationPlugin.*
*
* byLanguage(...)
* ```
*
* @param reference the qualified element to import
* @return the selector part of the qualified reference after importing
*/
fun importMemberOnDemand(reference: UQualifiedReferenceExpression): UExpression?
}
/**
* UAST element factory for UAST expressions.
*
* @see com.intellij.lang.jvm.actions.JvmElementActionsFactory for more complex JVM based code generation.
*/
@ApiStatus.Experimental
interface UastElementFactory {
fun createBinaryExpression(leftOperand: UExpression, rightOperand: UExpression, operator: UastBinaryOperator,
context: PsiElement?): UBinaryExpression?
/**
* Create binary expression, and possibly remove unnecessary parenthesis, so it could become [UPolyadicExpression], e.g
* [createFlatBinaryExpression] (1 + 2, 2, +) could produce 1 + 2 + 2, which is polyadic expression
*/
@JvmDefault
fun createFlatBinaryExpression(leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator,
context: PsiElement?): UPolyadicExpression? =
createBinaryExpression(leftOperand, rightOperand, operator, context)
fun createSimpleReference(name: String, context: PsiElement?): USimpleNameReferenceExpression?
fun createSimpleReference(variable: UVariable, context: PsiElement?): USimpleNameReferenceExpression?
fun createQualifiedReference(qualifiedName: String, context: PsiElement?): UQualifiedReferenceExpression?
fun createParenthesizedExpression(expression: UExpression,
context: PsiElement?): UParenthesizedExpression?
fun createReturnExpresion(expression: UExpression?,
inLambda: Boolean = false,
context: PsiElement?): UReturnExpression?
fun createLocalVariable(suggestedName: String?,
type: PsiType?,
initializer: UExpression,
immutable: Boolean = false,
context: PsiElement?): ULocalVariable?
fun createBlockExpression(expressions: List<UExpression>, context: PsiElement?): UBlockExpression?
fun createLambdaExpression(parameters: List<UParameterInfo>, body: UExpression, context: PsiElement?): ULambdaExpression?
fun createDeclarationExpression(declarations: List<UDeclaration>, context: PsiElement?): UDeclarationsExpression?
/**
* For providing additional information pass it via [context] only, otherwise it can be lost.
* It is not guaranteed, that [receiver] will be part of returned [UCallExpression].
* If its necessary, use [getQualifiedParentOrThis].
*/
fun createCallExpression(receiver: UExpression?,
methodName: String,
parameters: List<UExpression>,
expectedReturnType: PsiType?,
kind: UastCallKind,
context: PsiElement? = null): UCallExpression?
fun createCallableReferenceExpression(receiver: UExpression?, methodName: String, context: PsiElement?): UCallableReferenceExpression?
fun createIfExpression(condition: UExpression, thenBranch: UExpression, elseBranch: UExpression?, context: PsiElement?): UIfExpression?
fun createStringLiteralExpression(text: String, context: PsiElement?): ULiteralExpression?
fun createLongConstantExpression(long: Long, context: PsiElement?): UExpression?
fun createNullLiteral(context: PsiElement?): ULiteralExpression?
}
@ApiStatus.Experimental
data class UParameterInfo(val type: PsiType?, val suggestedName: String?)
@ApiStatus.Experimental
infix fun String?.ofType(type: PsiType?): UParameterInfo = UParameterInfo(type, this)
@ApiStatus.Experimental
inline fun <reified T : UElement> UElement.replace(newElement: T): T? =
UastCodeGenerationPlugin.byLanguage(this.lang)
?.replace(this, newElement, T::class.java).also {
if (it == null) {
logger<UastCodeGenerationPlugin>().warn("failed replacing the $this with $newElement")
}
}
fun UReferenceExpression.bindToElement(element: PsiElement): PsiElement? =
UastCodeGenerationPlugin.byLanguage(this.lang)?.bindToElement(this, element)
fun UReferenceExpression.shortenReference(): UReferenceExpression? =
UastCodeGenerationPlugin.byLanguage(this.lang)?.shortenReference(this)
fun UQualifiedReferenceExpression.importMemberOnDemand(): UExpression? =
UastCodeGenerationPlugin.byLanguage(this.lang)?.importMemberOnDemand(this)
@ApiStatus.Experimental
inline fun <reified T : UElement> T.refreshed() = sourcePsi?.also {
logger<UastCodeGenerationPlugin>().assertTrue(it.isValid,
"psi $it of class ${it.javaClass} should be valid, containing file = ${it.containingFile}")
}?.toUElementOfType<T>()
val UElement.generationPlugin: UastCodeGenerationPlugin?
@ApiStatus.Experimental
get() = UastCodeGenerationPlugin.byLanguage(this.lang)
@ApiStatus.Experimental
fun UElement.getUastElementFactory(project: Project): UastElementFactory? =
generationPlugin?.getElementFactory(project)
| apache-2.0 | 946a305e13c63e3b7234c1494d05fab2 | 39.577889 | 137 | 0.725573 | 5.236706 | false | false | false | false |
Werb/MoreType | app/src/main/java/com/werb/moretype/main/MainActivity.kt | 1 | 1346 | package com.werb.moretype.main
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.werb.library.MoreAdapter
import com.werb.library.action.MoreClickListener
import com.werb.moretype.R
import com.werb.moretype.data.DataServer
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private val adapter = MoreAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
adapter.apply {
injectValueInAllHolder(mapOf("qqqqqq" to "1233333333"))
register(MainCardViewHolder::class.java, playLoadClick, mapOf("someValue" to "123"))
attachTo(more_list)
}
adapter.loadData(DataServer.getMainCardData())
}
private val playLoadClick = object : MoreClickListener() {
override fun onItemClick(view: View, position: Int) {
if (view.id == R.id.card_playLoad) {
val payLoad = view.tag as Boolean
if (payLoad) {
adapter.notifyItemChanged(position, PayLoadOne(true))
} else {
adapter.notifyItemChanged(position, PayLoadOne(false))
}
}
}
}
}
| apache-2.0 | 0341305107be26a741a924c36da55df5 | 30.302326 | 96 | 0.652303 | 4.442244 | false | false | false | false |
google/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/CodeFragmentParameterAnalyzer.kt | 2 | 19098 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.evaluate.compilation
import com.intellij.debugger.engine.evaluation.EvaluateExceptionUtil
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.getCallLabelForLambdaArgument
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor
import org.jetbrains.kotlin.descriptors.impl.SyntheticFieldDescriptor
import org.jetbrains.kotlin.idea.debugger.base.util.evaluate.ExecutionContext
import org.jetbrains.kotlin.idea.debugger.evaluate.*
import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinCodeFragmentFactory.Companion.FAKE_JAVA_CONTEXT_FUNCTION_NAME
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CodeFragmentParameter.*
import org.jetbrains.kotlin.idea.debugger.base.util.safeLocation
import org.jetbrains.kotlin.idea.debugger.base.util.safeMethod
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.psi.psiUtil.isDotSelector
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.checkers.COROUTINE_CONTEXT_FQ_NAME
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.scopes.receivers.ExtensionReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.expressions.createFunctionType
class CodeFragmentParameterInfo(
val parameters: List<Smart>,
val crossingBounds: Set<Dumb>
)
/*
The purpose of this class is to figure out what parameters the received code fragment captures.
It handles both directly mentioned names such as local variables or parameters and implicit values (dispatch/extension receivers).
*/
class CodeFragmentParameterAnalyzer(
private val context: ExecutionContext,
private val codeFragment: KtCodeFragment,
private val bindingContext: BindingContext,
private val evaluationStatus: EvaluationStatus
) {
private val parameters = LinkedHashMap<DeclarationDescriptor, Smart>()
private val crossingBounds = mutableSetOf<Dumb>()
private val onceUsedChecker = OnceUsedChecker(CodeFragmentParameterAnalyzer::class.java)
private val containingPrimaryConstructor: ConstructorDescriptor? by lazy {
context.frameProxy.safeLocation()?.safeMethod()?.takeIf { it.isConstructor } ?: return@lazy null
val constructor = codeFragment.context?.getParentOfType<KtPrimaryConstructor>(false) ?: return@lazy null
bindingContext[BindingContext.CONSTRUCTOR, constructor]
}
fun analyze(): CodeFragmentParameterInfo {
onceUsedChecker.trigger()
codeFragment.accept(object : KtTreeVisitor<Unit>() {
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression, data: Unit?): Void? {
val resolvedCall = expression.getResolvedCall(bindingContext) ?: return null
processResolvedCall(resolvedCall, expression)
return null
}
private fun processResolvedCall(resolvedCall: ResolvedCall<*>, expression: KtSimpleNameExpression) {
if (resolvedCall is VariableAsFunctionResolvedCall) {
processResolvedCall(resolvedCall.functionCall, expression)
processResolvedCall(resolvedCall.variableCall, expression)
return
}
// Capture dispatch receiver for the extension callable
run {
val descriptor = resolvedCall.resultingDescriptor
val containingClass = descriptor?.containingDeclaration as? ClassDescriptor
val extensionParameter = descriptor?.extensionReceiverParameter
if (descriptor != null && descriptor !is DebuggerFieldPropertyDescriptor
&& extensionParameter != null && containingClass != null
) {
if (containingClass.kind != ClassKind.OBJECT) {
val parameter = processDispatchReceiver(containingClass)
checkBounds(descriptor, expression, parameter)
}
}
}
if (runReadAction { expression.isDotSelector() }) {
val descriptor = resolvedCall.resultingDescriptor
val parameter = processCoroutineContextCall(resolvedCall.resultingDescriptor)
if (parameter != null) {
checkBounds(descriptor, expression, parameter)
}
// If the receiver expression is not a coroutine context call, it is already captured for this reference
return
}
if (isCodeFragmentDeclaration(resolvedCall.resultingDescriptor)) {
// The reference is from the code fragment we analyze, no need to capture
return
}
var processed = false
val extensionReceiver = resolvedCall.extensionReceiver
if (extensionReceiver is ImplicitReceiver) {
val descriptor = extensionReceiver.declarationDescriptor
val parameter = processReceiver(extensionReceiver)
checkBounds(descriptor, expression, parameter)
processed = true
}
val dispatchReceiver = resolvedCall.dispatchReceiver
if (dispatchReceiver is ImplicitReceiver) {
val descriptor = dispatchReceiver.declarationDescriptor
val parameter = processReceiver(dispatchReceiver)
if (parameter != null) {
checkBounds(descriptor, expression, parameter)
processed = true
}
}
if (!processed && resolvedCall.resultingDescriptor is SyntheticFieldDescriptor) {
val descriptor = resolvedCall.resultingDescriptor as SyntheticFieldDescriptor
val parameter = processSyntheticFieldVariable(descriptor)
checkBounds(descriptor, expression, parameter)
processed = true
}
// If a reference has receivers, we can calculate its value using them, no need to capture
if (!processed) {
val descriptor = resolvedCall.resultingDescriptor
val parameter = processDescriptor(descriptor, expression)
checkBounds(descriptor, expression, parameter)
}
}
private fun processDescriptor(descriptor: DeclarationDescriptor, expression: KtSimpleNameExpression): Smart? {
return processDebugLabel(descriptor)
?: processCoroutineContextCall(descriptor)
?: processSimpleNameExpression(descriptor, expression)
}
override fun visitThisExpression(expression: KtThisExpression, data: Unit?): Void? {
val instanceReference = runReadAction { expression.instanceReference }
val target = bindingContext[BindingContext.REFERENCE_TARGET, instanceReference]
if (isCodeFragmentDeclaration(target)) {
// The reference is from the code fragment we analyze, no need to capture
return null
}
val parameter = when (target) {
is ClassDescriptor -> processDispatchReceiver(target)
is CallableDescriptor -> {
val type = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, expression]?.type
type?.let { processExtensionReceiver(target, type, expression.getLabelName()) }
}
else -> null
}
if (parameter != null) {
checkBounds(target, expression, parameter)
}
return null
}
override fun visitSuperExpression(expression: KtSuperExpression, data: Unit?): Void? {
val type = bindingContext[BindingContext.THIS_TYPE_FOR_SUPER_EXPRESSION, expression] ?: return null
val descriptor = type.constructor.declarationDescriptor as? ClassDescriptor ?: return null
parameters.getOrPut(descriptor) {
val name = descriptor.name.asString()
Smart(Dumb(Kind.DISPATCH_RECEIVER, "", "super@$name"), type, descriptor)
}
return null
}
override fun visitCallExpression(expression: KtCallExpression, data: Unit?): Void? {
val resolvedCall = expression.getResolvedCall(bindingContext)
if (resolvedCall != null) {
val descriptor = resolvedCall.resultingDescriptor
if (descriptor is ConstructorDescriptor && KotlinBuiltIns.isNothing(descriptor.returnType)) {
throw EvaluateExceptionUtil.createEvaluateException(
KotlinDebuggerEvaluationBundle.message("error.nothing.initialization")
)
}
}
return super.visitCallExpression(expression, data)
}
}, Unit)
return CodeFragmentParameterInfo(parameters.values.toList(), crossingBounds)
}
private fun processReceiver(receiver: ImplicitReceiver): Smart? {
if (isCodeFragmentDeclaration(receiver.declarationDescriptor)) {
return null
}
return when (receiver) {
is ImplicitClassReceiver -> processDispatchReceiver(receiver.classDescriptor)
is ExtensionReceiver -> processExtensionReceiver(receiver.declarationDescriptor, receiver.type, null)
else -> null
}
}
private fun processDispatchReceiver(descriptor: ClassDescriptor): Smart? {
if (descriptor.kind == ClassKind.OBJECT || containingPrimaryConstructor != null) {
return null
}
val type = descriptor.defaultType
return parameters.getOrPut(descriptor) {
val name = descriptor.name
val debugLabel = if (name.isSpecial) "" else "@" + name.asString()
Smart(Dumb(Kind.DISPATCH_RECEIVER, "", AsmUtil.THIS + debugLabel), type, descriptor)
}
}
private fun processExtensionReceiver(descriptor: CallableDescriptor, receiverType: KotlinType, label: String?): Smart? {
if (isFakeFunctionForJavaContext(descriptor)) {
return processFakeJavaCodeReceiver(descriptor)
}
val actualLabel = label ?: getLabel(descriptor) ?: return null
val receiverParameter = descriptor.extensionReceiverParameter ?: return null
return parameters.getOrPut(descriptor) {
Smart(Dumb(Kind.EXTENSION_RECEIVER, actualLabel, AsmUtil.THIS + "@" + actualLabel), receiverType, receiverParameter)
}
}
private fun getLabel(callableDescriptor: CallableDescriptor): String? {
val source = callableDescriptor.source.getPsi()
if (source is KtFunctionLiteral) {
getCallLabelForLambdaArgument(source, bindingContext)?.let { return it }
}
return callableDescriptor.name.takeIf { !it.isSpecial }?.asString()
}
private fun isFakeFunctionForJavaContext(descriptor: CallableDescriptor): Boolean {
return descriptor is FunctionDescriptor
&& descriptor.name.asString() == FAKE_JAVA_CONTEXT_FUNCTION_NAME
&& codeFragment.getCopyableUserData(KtCodeFragment.FAKE_CONTEXT_FOR_JAVA_FILE) != null
}
private fun processFakeJavaCodeReceiver(descriptor: CallableDescriptor): Smart? {
val receiverParameter = descriptor
.takeIf { descriptor is FunctionDescriptor }
?.extensionReceiverParameter
?: return null
val label = FAKE_JAVA_CONTEXT_FUNCTION_NAME
val type = receiverParameter.type
return parameters.getOrPut(descriptor) {
Smart(Dumb(Kind.FAKE_JAVA_OUTER_CLASS, label, AsmUtil.THIS), type, receiverParameter)
}
}
private fun processSyntheticFieldVariable(descriptor: SyntheticFieldDescriptor): Smart {
val propertyDescriptor = descriptor.propertyDescriptor
val fieldName = propertyDescriptor.name.asString()
val type = propertyDescriptor.type
return parameters.getOrPut(descriptor) {
Smart(Dumb(Kind.FIELD_VAR, fieldName, "field"), type, descriptor)
}
}
private fun processSimpleNameExpression(target: DeclarationDescriptor, expression: KtSimpleNameExpression): Smart? {
if (target is ValueParameterDescriptor && target.isCrossinline) {
evaluationStatus.error(EvaluationError.CrossInlineLambda)
throw EvaluateExceptionUtil.createEvaluateException(
KotlinDebuggerEvaluationBundle.message("error.crossinline.lambda.evaluation")
)
}
val isLocalTarget = (target as? DeclarationDescriptorWithVisibility)?.visibility == DescriptorVisibilities.LOCAL
val isPrimaryConstructorParameter = !isLocalTarget
&& target is PropertyDescriptor
&& isContainingPrimaryConstructorParameter(target)
if (!isLocalTarget && !isPrimaryConstructorParameter) {
return null
}
return when (target) {
is SimpleFunctionDescriptor -> {
val type = target.createFunctionType(target.builtIns, target.isSuspend) ?: return null
parameters.getOrPut(target) {
Smart(Dumb(Kind.LOCAL_FUNCTION, target.name.asString()), type, target.original)
}
}
is ValueDescriptor -> {
val unwrappedExpression = KtPsiUtil.deparenthesize(expression)
val isLValue = unwrappedExpression?.let { isAssignmentLValue(it) } ?: false
parameters.getOrPut(target) {
val kind = if (target is LocalVariableDescriptor && target.isDelegated) Kind.DELEGATED else Kind.ORDINARY
Smart(Dumb(kind, target.name.asString()), target.type, target, isLValue)
}
}
else -> null
}
}
private fun isAssignmentLValue(expression: PsiElement): Boolean {
val assignmentExpression = (expression.parent as? KtBinaryExpression)?.takeIf { KtPsiUtil.isAssignment(it) } ?: return false
return assignmentExpression.left == expression
}
private fun isContainingPrimaryConstructorParameter(target: PropertyDescriptor): Boolean {
val primaryConstructor = containingPrimaryConstructor ?: return false
for (parameter in primaryConstructor.valueParameters) {
val property = bindingContext[BindingContext.VALUE_PARAMETER_AS_PROPERTY, parameter]
if (target == property) {
return true
}
}
return false
}
private fun processCoroutineContextCall(target: DeclarationDescriptor): Smart? {
if (target is PropertyDescriptor && target.fqNameSafe == COROUTINE_CONTEXT_FQ_NAME) {
return parameters.getOrPut(target) {
Smart(Dumb(Kind.COROUTINE_CONTEXT, ""), target.type, target)
}
}
return null
}
private fun processDebugLabel(target: DeclarationDescriptor): Smart? {
val debugLabelPropertyDescriptor = target as? DebugLabelPropertyDescriptor ?: return null
val labelName = debugLabelPropertyDescriptor.labelName
val debugString = debugLabelPropertyDescriptor.name.asString()
return parameters.getOrPut(target) {
val type = debugLabelPropertyDescriptor.type
Smart(Dumb(Kind.DEBUG_LABEL, labelName, debugString), type, debugLabelPropertyDescriptor)
}
}
fun checkBounds(descriptor: DeclarationDescriptor?, expression: KtExpression, parameter: Smart?) {
if (parameter == null || descriptor !is DeclarationDescriptorWithSource) {
return
}
val targetPsi = descriptor.source.getPsi()
if (targetPsi != null && doesCrossInlineBounds(expression, targetPsi)) {
crossingBounds += parameter.dumb
}
}
private fun doesCrossInlineBounds(expression: PsiElement, declaration: PsiElement): Boolean {
val declarationParent = declaration.parent ?: return false
var currentParent: PsiElement? = expression.parent?.takeIf { it.isInside(declarationParent) } ?: return false
while (currentParent != null && currentParent != declarationParent) {
if (currentParent is KtFunction) {
val functionDescriptor = bindingContext[BindingContext.FUNCTION, currentParent]
if (functionDescriptor != null && !functionDescriptor.isInline) {
return true
}
}
currentParent = when (currentParent) {
is KtCodeFragment -> currentParent.context
else -> currentParent.parent
}
}
return false
}
private fun isCodeFragmentDeclaration(descriptor: DeclarationDescriptor?): Boolean {
if (descriptor is ValueParameterDescriptor && isCodeFragmentDeclaration(descriptor.containingDeclaration)) {
return true
}
if (descriptor !is DeclarationDescriptorWithSource) {
return false
}
return descriptor.source.getPsi()?.containingFile is KtCodeFragment
}
private tailrec fun PsiElement.isInside(parent: PsiElement): Boolean {
if (parent.isAncestor(this)) {
return true
}
val context = (this.containingFile as? KtCodeFragment)?.context ?: return false
return context.isInside(parent)
}
}
private class OnceUsedChecker(private val clazz: Class<*>) {
private var used = false
fun trigger() {
if (used) {
error(clazz.name + " may be only used once")
}
used = true
}
}
| apache-2.0 | 66a51f9f7d6adbbfb597d0d5b7844e23 | 44.042453 | 134 | 0.653314 | 5.977465 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/openapi/application/rw/InternalReadAction.kt | 1 | 4881 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.application.rw
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ReadAction.CannotReadException
import com.intellij.openapi.application.ReadConstraint
import com.intellij.openapi.application.ex.ApplicationEx
import com.intellij.openapi.progress.Cancellation
import com.intellij.openapi.progress.blockingContext
import kotlinx.coroutines.*
import kotlin.coroutines.coroutineContext
import kotlin.coroutines.resume
internal class InternalReadAction<T>(
private val constraints: List<ReadConstraint>,
private val blocking: Boolean,
private val action: () -> T
) {
private val application: ApplicationEx = ApplicationManager.getApplication() as ApplicationEx
suspend fun runReadAction(): T = withContext(Dispatchers.Default) {
check(!application.isReadAccessAllowed) {
"This thread unexpectedly holds the read lock"
}
readLoop()
}
private fun findUnsatisfiedConstraint(): ReadConstraint? {
for (constraint in constraints) {
if (!constraint.isSatisfied()) {
return constraint
}
}
return null
}
private suspend fun readLoop(): T {
val loopJob = coroutineContext.job
while (true) {
loopJob.ensureActive()
if (application.isWriteActionPending || application.isWriteActionInProgress) {
yieldToPendingWriteActions() // Write actions are executed on the write thread => wait until write action is processed.
}
when (val readResult = tryReadAction(loopJob)) {
is ReadResult.Successful -> return readResult.value
is ReadResult.UnsatisfiedConstraint -> readResult.waitForConstraint.join()
is ReadResult.WritePending -> Unit // retry
}
}
}
private suspend fun tryReadAction(loopJob: Job): ReadResult<T> = blockingContext {
if (blocking) {
tryReadBlocking(loopJob)
}
else {
tryReadCancellable(loopJob)
}
}
private fun tryReadBlocking(loopJob: Job): ReadResult<T> {
var result: ReadResult<T>? = null
application.tryRunReadAction {
result = insideReadAction(loopJob)
}
return result
?: ReadResult.WritePending
}
private fun tryReadCancellable(loopJob: Job): ReadResult<T> = try {
cancellableReadActionInternal(loopJob) {
insideReadAction(loopJob)
}
}
catch (e: CancellationException) {
val cause = Cancellation.getCause(e)
if (cause is CannotReadException) {
ReadResult.WritePending
}
else {
throw e
}
}
private fun insideReadAction(loopJob: Job): ReadResult<T> {
val unsatisfiedConstraint = findUnsatisfiedConstraint()
return if (unsatisfiedConstraint == null) {
ReadResult.Successful(action())
}
else {
ReadResult.UnsatisfiedConstraint(waitForConstraint(loopJob, unsatisfiedConstraint))
}
}
}
private sealed class ReadResult<out T> {
class Successful<T>(val value: T) : ReadResult<T>()
class UnsatisfiedConstraint(val waitForConstraint: Job) : ReadResult<Nothing>()
object WritePending : ReadResult<Nothing>()
}
/**
* Suspends the execution until the write thread queue is processed.
*/
private suspend fun yieldToPendingWriteActions() {
// the runnable is executed on the write thread _after_ the current or pending write action
yieldUntilRun { runnable ->
// Even if there is a modal dialog shown,
// it doesn't make sense to yield until it's finished
// to run a read action concurrently in background
// => yield until the current WA finishes in any modality.
ApplicationManager.getApplication().invokeLater(runnable, ModalityState.any())
}
}
private fun waitForConstraint(loopJob: Job, constraint: ReadConstraint): Job {
return CoroutineScope(loopJob).launch(Dispatchers.Unconfined + CoroutineName("waiting for constraint '$constraint'")) {
check(ApplicationManager.getApplication().isReadAccessAllowed) // schedule while holding read lock
yieldUntilRun(constraint::schedule)
check(constraint.isSatisfied())
// Job is finished, readLoop may continue the next attempt
}
}
private suspend fun yieldUntilRun(schedule: (Runnable) -> Unit) {
suspendCancellableCoroutine { continuation ->
schedule(ResumeContinuationRunnable(continuation))
}
}
private class ResumeContinuationRunnable(continuation: CancellableContinuation<Unit>) : Runnable {
@Volatile
private var myContinuation: CancellableContinuation<Unit>? = continuation
init {
continuation.invokeOnCancellation {
myContinuation = null // it's not possible to unschedule the runnable, so we make it do nothing instead
}
}
override fun run() {
myContinuation?.resume(Unit)
}
}
| apache-2.0 | 7968f8768ca9ad83a8230b127bc2524b | 32.204082 | 127 | 0.732022 | 4.818361 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/LibraryEntityImpl.kt | 1 | 20695 | // 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.bridgeEntities.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.SoftLinkable
import com.intellij.workspaceModel.storage.impl.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 com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import java.io.Serializable
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class LibraryEntityImpl(val dataSource: LibraryEntityData) : LibraryEntity, WorkspaceEntityBase() {
companion object {
internal val SDK_CONNECTION_ID: ConnectionId = ConnectionId.create(LibraryEntity::class.java, SdkEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
internal val LIBRARYPROPERTIES_CONNECTION_ID: ConnectionId = ConnectionId.create(LibraryEntity::class.java,
LibraryPropertiesEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
internal val LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID: ConnectionId = ConnectionId.create(LibraryEntity::class.java,
LibraryFilesPackagingElementEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE,
false)
val connections = listOf<ConnectionId>(
SDK_CONNECTION_ID,
LIBRARYPROPERTIES_CONNECTION_ID,
LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID,
)
}
override val name: String
get() = dataSource.name
override val tableId: LibraryTableId
get() = dataSource.tableId
override val roots: List<LibraryRoot>
get() = dataSource.roots
override val excludedRoots: List<VirtualFileUrl>
get() = dataSource.excludedRoots
override val sdk: SdkEntity?
get() = snapshot.extractOneToOneChild(SDK_CONNECTION_ID, this)
override val libraryProperties: LibraryPropertiesEntity?
get() = snapshot.extractOneToOneChild(LIBRARYPROPERTIES_CONNECTION_ID, this)
override val libraryFilesPackagingElement: LibraryFilesPackagingElementEntity?
get() = snapshot.extractOneToOneChild(LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: LibraryEntityData?) : ModifiableWorkspaceEntityBase<LibraryEntity>(), LibraryEntity.Builder {
constructor() : this(LibraryEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity LibraryEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
index(this, "excludedRoots", this.excludedRoots.toHashSet())
indexLibraryRoots(roots)
// 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().isNameInitialized()) {
error("Field LibraryEntity#name should be initialized")
}
if (!getEntityData().isTableIdInitialized()) {
error("Field LibraryEntity#tableId should be initialized")
}
if (!getEntityData().isRootsInitialized()) {
error("Field LibraryEntity#roots should be initialized")
}
if (!getEntityData().isExcludedRootsInitialized()) {
error("Field LibraryEntity#excludedRoots should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as LibraryEntity
this.entitySource = dataSource.entitySource
this.name = dataSource.name
this.tableId = dataSource.tableId
this.roots = dataSource.roots.toMutableList()
this.excludedRoots = dataSource.excludedRoots.toMutableList()
if (parents != null) {
}
}
private fun indexLibraryRoots(libraryRoots: List<LibraryRoot>) {
val jarDirectories = mutableSetOf<VirtualFileUrl>()
val libraryRootList = libraryRoots.map {
if (it.inclusionOptions != LibraryRoot.InclusionOptions.ROOT_ITSELF) {
jarDirectories.add(it.url)
}
it.url
}.toHashSet()
index(this, "roots", libraryRootList)
indexJarDirectories(this, jarDirectories)
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData().name = value
changedProperty.add("name")
}
override var tableId: LibraryTableId
get() = getEntityData().tableId
set(value) {
checkModificationAllowed()
getEntityData().tableId = value
changedProperty.add("tableId")
}
private val rootsUpdater: (value: List<LibraryRoot>) -> Unit = { value ->
val _diff = diff
if (_diff != null) {
indexLibraryRoots(value)
}
changedProperty.add("roots")
}
override var roots: MutableList<LibraryRoot>
get() {
val collection_roots = getEntityData().roots
if (collection_roots !is MutableWorkspaceList) return collection_roots
collection_roots.setModificationUpdateAction(rootsUpdater)
return collection_roots
}
set(value) {
checkModificationAllowed()
getEntityData().roots = value
rootsUpdater.invoke(value)
}
private val excludedRootsUpdater: (value: List<VirtualFileUrl>) -> Unit = { value ->
val _diff = diff
if (_diff != null) index(this, "excludedRoots", value.toHashSet())
changedProperty.add("excludedRoots")
}
override var excludedRoots: MutableList<VirtualFileUrl>
get() {
val collection_excludedRoots = getEntityData().excludedRoots
if (collection_excludedRoots !is MutableWorkspaceList) return collection_excludedRoots
collection_excludedRoots.setModificationUpdateAction(excludedRootsUpdater)
return collection_excludedRoots
}
set(value) {
checkModificationAllowed()
getEntityData().excludedRoots = value
excludedRootsUpdater.invoke(value)
}
override var sdk: SdkEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(SDK_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, SDK_CONNECTION_ID)] as? SdkEntity
}
else {
this.entityLinks[EntityLink(true, SDK_CONNECTION_ID)] as? SdkEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, SDK_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(SDK_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, SDK_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, SDK_CONNECTION_ID)] = value
}
changedProperty.add("sdk")
}
override var libraryProperties: LibraryPropertiesEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(LIBRARYPROPERTIES_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
LIBRARYPROPERTIES_CONNECTION_ID)] as? LibraryPropertiesEntity
}
else {
this.entityLinks[EntityLink(true, LIBRARYPROPERTIES_CONNECTION_ID)] as? LibraryPropertiesEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, LIBRARYPROPERTIES_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(LIBRARYPROPERTIES_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, LIBRARYPROPERTIES_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, LIBRARYPROPERTIES_CONNECTION_ID)] = value
}
changedProperty.add("libraryProperties")
}
override var libraryFilesPackagingElement: LibraryFilesPackagingElementEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] as? LibraryFilesPackagingElementEntity
}
else {
this.entityLinks[EntityLink(true, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] as? LibraryFilesPackagingElementEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, LIBRARYFILESPACKAGINGELEMENT_CONNECTION_ID)] = value
}
changedProperty.add("libraryFilesPackagingElement")
}
override fun getEntityData(): LibraryEntityData = result ?: super.getEntityData() as LibraryEntityData
override fun getEntityClass(): Class<LibraryEntity> = LibraryEntity::class.java
}
}
class LibraryEntityData : WorkspaceEntityData.WithCalculablePersistentId<LibraryEntity>(), SoftLinkable {
lateinit var name: String
lateinit var tableId: LibraryTableId
lateinit var roots: MutableList<LibraryRoot>
lateinit var excludedRoots: MutableList<VirtualFileUrl>
fun isNameInitialized(): Boolean = ::name.isInitialized
fun isTableIdInitialized(): Boolean = ::tableId.isInitialized
fun isRootsInitialized(): Boolean = ::roots.isInitialized
fun isExcludedRootsInitialized(): Boolean = ::excludedRoots.isInitialized
override fun getLinks(): Set<PersistentEntityId<*>> {
val result = HashSet<PersistentEntityId<*>>()
val _tableId = tableId
when (_tableId) {
is LibraryTableId.GlobalLibraryTableId -> {
}
is LibraryTableId.ModuleLibraryTableId -> {
result.add(_tableId.moduleId)
}
is LibraryTableId.ProjectLibraryTableId -> {
}
}
for (item in roots) {
}
for (item in excludedRoots) {
}
return result
}
override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
val _tableId = tableId
when (_tableId) {
is LibraryTableId.GlobalLibraryTableId -> {
}
is LibraryTableId.ModuleLibraryTableId -> {
index.index(this, _tableId.moduleId)
}
is LibraryTableId.ProjectLibraryTableId -> {
}
}
for (item in roots) {
}
for (item in excludedRoots) {
}
}
override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
// TODO verify logic
val mutablePreviousSet = HashSet(prev)
val _tableId = tableId
when (_tableId) {
is LibraryTableId.GlobalLibraryTableId -> {
}
is LibraryTableId.ModuleLibraryTableId -> {
val removedItem__tableId_moduleId = mutablePreviousSet.remove(_tableId.moduleId)
if (!removedItem__tableId_moduleId) {
index.index(this, _tableId.moduleId)
}
}
is LibraryTableId.ProjectLibraryTableId -> {
}
}
for (item in roots) {
}
for (item in excludedRoots) {
}
for (removed in mutablePreviousSet) {
index.remove(this, removed)
}
}
override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean {
var changed = false
val _tableId = tableId
val res_tableId = when (_tableId) {
is LibraryTableId.GlobalLibraryTableId -> {
_tableId
}
is LibraryTableId.ModuleLibraryTableId -> {
val _tableId_moduleId_data = if (_tableId.moduleId == oldLink) {
changed = true
newLink as ModuleId
}
else {
null
}
var _tableId_data = _tableId
if (_tableId_moduleId_data != null) {
_tableId_data = _tableId_data.copy(moduleId = _tableId_moduleId_data)
}
_tableId_data
}
is LibraryTableId.ProjectLibraryTableId -> {
_tableId
}
}
if (res_tableId != null) {
tableId = res_tableId
}
return changed
}
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<LibraryEntity> {
val modifiable = LibraryEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): LibraryEntity {
return getCached(snapshot) {
val entity = LibraryEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun clone(): LibraryEntityData {
val clonedEntity = super.clone()
clonedEntity as LibraryEntityData
clonedEntity.roots = clonedEntity.roots.toMutableWorkspaceList()
clonedEntity.excludedRoots = clonedEntity.excludedRoots.toMutableWorkspaceList()
return clonedEntity
}
override fun persistentId(): PersistentEntityId<*> {
return LibraryId(name, tableId)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return LibraryEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return LibraryEntity(name, tableId, roots, excludedRoots, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as LibraryEntityData
if (this.entitySource != other.entitySource) return false
if (this.name != other.name) return false
if (this.tableId != other.tableId) return false
if (this.roots != other.roots) return false
if (this.excludedRoots != other.excludedRoots) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as LibraryEntityData
if (this.name != other.name) return false
if (this.tableId != other.tableId) return false
if (this.roots != other.roots) return false
if (this.excludedRoots != other.excludedRoots) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + tableId.hashCode()
result = 31 * result + roots.hashCode()
result = 31 * result + excludedRoots.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + tableId.hashCode()
result = 31 * result + roots.hashCode()
result = 31 * result + excludedRoots.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.add(LibraryRootTypeId::class.java)
collector.add(LibraryRoot.InclusionOptions::class.java)
collector.add(LibraryRoot::class.java)
collector.add(LibraryTableId::class.java)
collector.add(LibraryTableId.ModuleLibraryTableId::class.java)
collector.add(LibraryTableId.GlobalLibraryTableId::class.java)
collector.add(ModuleId::class.java)
collector.addObject(LibraryTableId.ProjectLibraryTableId::class.java)
this.roots?.let { collector.add(it::class.java) }
this.excludedRoots?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| apache-2.0 | ce84c09275c6a05ecc2d2a54d667081c | 37.042279 | 201 | 0.669099 | 5.399165 | false | false | false | false |
allotria/intellij-community | java/java-impl/src/com/intellij/codeInspection/javaDoc/JavadocHtmlLintAnnotator.kt | 3 | 7903 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE")
package com.intellij.codeInspection.javaDoc
import com.intellij.codeInsight.daemon.HighlightDisplayKey
import com.intellij.codeInsight.intention.EmptyIntentionAction
import com.intellij.codeInspection.InspectionsBundle
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.configurations.SimpleJavaParameters
import com.intellij.execution.util.ExecUtil
import com.intellij.java.JavaBundle
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.ExternalAnnotator
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdkVersion
import com.intellij.openapi.projectRoots.JdkUtil
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.ex.JavaSdkUtil
import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.java.LanguageLevel
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.javadoc.PsiDocComment
import com.intellij.psi.util.PsiTreeUtil
import com.sun.tools.doclint.DocLint
import java.io.File
class JavadocHtmlLintAnnotator : ExternalAnnotator<JavadocHtmlLintAnnotator.Info, JavadocHtmlLintAnnotator.Result>() {
data class Info(val file: PsiFile)
data class Anno(val row: Int, val col: Int, val error: Boolean, val message: String)
data class Result(val annotations: List<Anno>)
override fun getPairedBatchInspectionShortName(): String = JavadocHtmlLintInspection.SHORT_NAME
override fun collectInformation(file: PsiFile): Info? =
runReadAction { if (isJava8SourceFile(file) && "/**" in file.text) Info(file) else null }
override fun doAnnotate(collectedInfo: Info): Result? {
val text = runReadAction { if (collectedInfo.file.isValid) collectedInfo.file.text else null } ?: return null
val file = collectedInfo.file.virtualFile ?: return null
val copy = createTempFile(text.toByteArray(file.charset))
try {
val command = toolCommand(file, collectedInfo.file.project, copy)
val output = ExecUtil.execAndGetOutput(command)
if (output.exitCode != 0) {
val log = Logger.getInstance(JavadocHtmlLintAnnotator::class.java)
if (log.isDebugEnabled) log.debug("${file}: ${output.exitCode}, ${output.stderr}")
return null
}
val annotations = parse(output.stdoutLines)
return if (annotations.isNotEmpty()) Result(annotations) else null
}
catch (e: Exception) {
val log = Logger.getInstance(JavadocHtmlLintAnnotator::class.java)
log.debug(file.path, e)
return null
}
finally {
FileUtil.delete(copy)
}
}
override fun apply(file: PsiFile, annotationResult: Result, holder: AnnotationHolder) {
val text = file.text
val offsets = text.foldIndexed(mutableListOf(0)) { i, offsets, c -> if (c == '\n') offsets += (i + 1); offsets }
for ((row, col, error, message) in annotationResult.annotations) {
if (row < offsets.size) {
val offset = offsets[row] + col
val element = file.findElementAt(offset)
if (element != null && PsiTreeUtil.getParentOfType(element, PsiDocComment::class.java) != null) {
val range = adjust(element, text, offset)
val description = StringUtil.capitalize(message)
val severity = if (error) HighlightSeverity.ERROR else HighlightSeverity.WARNING
holder.newAnnotation(severity, description).range(range)
.newFix(EmptyIntentionAction(JavaBundle.message("inspection.javadoc.lint.display.name"))).key(key.value).registerFix()
.create()
}
}
}
}
//<editor-fold desc="Helpers">
private val key = lazy { HighlightDisplayKey.find(JavadocHtmlLintInspection.SHORT_NAME) }
private val lintOptions = "${DocLint.XMSGS_CUSTOM_PREFIX}html/private,accessibility/private"
private val lintPattern = "^.+:(\\d+):\\s+(error|warning):\\s+(.+)$".toPattern()
private fun isJava8SourceFile(file: PsiFile) =
file.isValid &&
file is PsiJavaFile &&
file.languageLevel.isAtLeast(LanguageLevel.JDK_1_8) &&
file.virtualFile != null &&
ProjectFileIndex.SERVICE.getInstance(file.project).isInSourceContent(file.virtualFile)
private fun createTempFile(bytes: ByteArray): File {
val tempFile = FileUtil.createTempFile(File(PathManager.getTempPath()), "javadocHtmlLint", ".java")
tempFile.writeBytes(bytes)
return tempFile
}
private fun toolCommand(file: VirtualFile, project: Project, copy: File): GeneralCommandLine {
val parameters = SimpleJavaParameters()
val jdk = findJdk(file, project)
parameters.jdk = jdk
if (!JavaSdkUtil.isJdkAtLeast(jdk, JavaSdkVersion.JDK_1_9)) {
val toolsJar = FileUtil.findFirstThatExist("${jdk.homePath}/lib/tools.jar", "${jdk.homePath}/../lib/tools.jar")
if (toolsJar != null) parameters.classPath.add(toolsJar.path)
}
parameters.charset = file.charset
parameters.vmParametersList.addProperty("user.language", "en")
parameters.mainClass = DocLint::class.java.name
parameters.programParametersList.add(lintOptions)
parameters.programParametersList.add(copy.path)
return parameters.toCommandLine()
}
private fun findJdk(file: VirtualFile, project: Project): Sdk {
val rootManager = ProjectRootManager.getInstance(project)
val module = runReadAction { rootManager.fileIndex.getModuleForFile(file) }
if (module != null) {
val sdk = ModuleRootManager.getInstance(module).sdk
if (isJdk8(sdk)) return sdk!!
}
val sdk = rootManager.projectSdk
if (isJdk8(sdk)) return sdk!!
return JavaAwareProjectJdkTableImpl.getInstanceEx().internalJdk
}
private fun isJdk8(sdk: Sdk?) =
sdk != null && JavaSdkUtil.isJdkAtLeast(sdk, JavaSdkVersion.JDK_1_8) && JdkUtil.checkForJre(sdk.homePath!!)
private fun parse(lines: List<String>): List<Anno> {
val result = mutableListOf<Anno>()
val i = lines.iterator()
while (i.hasNext()) {
val line = i.next()
val matcher = lintPattern.matcher(line)
if (matcher.matches() && i.hasNext() && i.next().isNotEmpty() && i.hasNext()) {
val row = matcher.group(1).toInt() - 1
val col = i.next().indexOf('^')
val error = matcher.group(2) == "error"
val message = matcher.group(3)
result += Anno(row, col, error, message)
}
}
return result
}
private fun adjust(element: PsiElement, text: String, offset: Int): TextRange {
val range = element.textRange
if (text[offset] == '<') {
val right = text.indexOf('>', offset)
if (right > 0) return TextRange(offset, Integer.min(right + 1, range.endOffset))
}
else if (text[offset] == '&') {
val right = text.indexOf(';', offset)
if (right > 0) return TextRange(offset, Integer.min(right + 1, range.endOffset))
}
else if (text[offset].isLetter() && !text[offset - 1].isLetter()) {
var right = offset + 1
while (text[right].isLetter() && right <= range.endOffset) right++
return TextRange(offset, right)
}
return range
}
//</editor-fold>
} | apache-2.0 | f3bb0f7a3ae989f2fb1e41df2a8f0f07 | 39.326531 | 140 | 0.720865 | 4.163857 | false | false | false | false |
CORDEA/MackerelClient | app/src/main/java/jp/cordea/mackerelclient/repository/HostLocalDataSource.kt | 1 | 1544 | package jp.cordea.mackerelclient.repository
import io.realm.Realm
import io.realm.kotlin.createObject
import jp.cordea.mackerelclient.MetricsType
import jp.cordea.mackerelclient.model.DisplayHostState
import jp.cordea.mackerelclient.model.UserMetric
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class HostLocalDataSource @Inject constructor() {
fun getDisplayHostStates(defaults: Array<String>): List<DisplayHostState> {
val realm = Realm.getDefaultInstance()
if (realm.where(DisplayHostState::class.java).count() == 0L) {
realm.executeTransaction {
for (key in defaults) {
it.createObject<DisplayHostState>(key).apply {
isDisplay = (key == "standby" || key == "working")
}
}
}
}
return realm.copyFromRealm(realm.where(DisplayHostState::class.java).findAll())
}
fun deleteOldMetrics(hosts: List<String>) {
val realm = Realm.getDefaultInstance()
val results = realm.where(UserMetric::class.java)
.equalTo("type", MetricsType.HOST.name).findAll()
val olds = results.map { it.parentId }.distinct().filter { !hosts.contains(it) }
realm.executeTransaction {
for (old in olds) {
realm.where(UserMetric::class.java)
.equalTo("parentId", old)
.findAll()
.deleteAllFromRealm()
}
}
realm.close()
}
}
| apache-2.0 | b849bbdd6175bc4987c1dbf30a44213e | 35.761905 | 88 | 0.609456 | 4.608955 | false | false | false | false |
zdary/intellij-community | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateSettingsConfigurable.kt | 2 | 7963 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.updateSettings.impl
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.WhatsNewAction
import com.intellij.ide.plugins.newui.PluginLogo
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.options.BoundConfigurable
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.ex.MultiLineLabel
import com.intellij.openapi.updateSettings.UpdateStrategyCustomization
import com.intellij.openapi.util.NlsContexts.Label
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.CollectionComboBoxModel
import com.intellij.ui.SeparatorComponent
import com.intellij.ui.components.BrowserLink
import com.intellij.ui.components.JBLabel
import com.intellij.ui.layout.*
import com.intellij.util.text.DateFormatUtil
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.BorderLayout
import java.awt.FlowLayout
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.SwingConstants
private const val TOOLBOX_URL =
"https://www.jetbrains.com/toolbox-app/?utm_source=product&utm_medium=link&utm_campaign=toolbox_app_in_IDE_updatewindow&utm_content=we_recommend"
class UpdateSettingsConfigurable @JvmOverloads constructor (private val checkNowEnabled: Boolean = true) :
BoundConfigurable(IdeBundle.message("updates.settings.title"), "preferences.updates") {
private lateinit var myLink: JComponent
private lateinit var myLastCheckedLabel: JLabel
override fun createPanel(): DialogPanel {
val settings = UpdateSettings.getInstance()
val manager = ExternalUpdateManager.ACTUAL
val eapLocked = ApplicationInfoEx.getInstanceEx().isMajorEAP && UpdateStrategyCustomization.getInstance().forceEapUpdateChannelForEapBuilds()
val appInfo = ApplicationInfo.getInstance()
val channelModel = CollectionComboBoxModel(settings.activeChannels)
return panel {
row {
cell {
label(IdeBundle.message("updates.settings.current.version") + ' ' + ApplicationNamesInfo.getInstance().fullProductName + ' ' + appInfo.fullVersion)
contextLabel(appInfo.build.asString() + ' ' + DateFormatUtil.formatAboutDialogDate(appInfo.buildDate.time))
}
}.largeGapAfter()
row {
cell {
when {
manager != null -> {
contextLabel(IdeBundle.message("updates.settings.external", manager.toolName))
}
eapLocked -> {
checkBox(IdeBundle.message("updates.settings.checkbox"), settings.state::isCheckNeeded)
contextLabel(IdeBundle.message("updates.settings.channel.locked")).withLargeLeftGap()
}
else -> {
val checkBox = checkBox(IdeBundle.message("updates.settings.checkbox.for"), settings.state::isCheckNeeded)
comboBox(channelModel,
getter = { settings.selectedActiveChannel },
setter = { settings.selectedChannelStatus = selectedChannel(it) }).enableIf(checkBox.selected)
}
}
}
}
row {
checkBox(IdeBundle.message("updates.plugins.settings.checkbox"), settings.state::isPluginsCheckNeeded)
}.largeGapAfter()
row {
cell {
if (checkNowEnabled) {
button(IdeBundle.message("updates.settings.check.now.button")) {
val project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(myLastCheckedLabel))
val settingsCopy = UpdateSettings()
settingsCopy.state.copyFrom(settings.state)
settingsCopy.state.isCheckNeeded = true
settingsCopy.state.isPluginsCheckNeeded = true
settingsCopy.selectedChannelStatus = selectedChannel(channelModel.selected)
UpdateChecker.updateAndShowResult(project, settingsCopy)
updateLastCheckedLabel(settings.lastTimeChecked)
}
}
myLastCheckedLabel = contextLabel("").withLargeLeftGap().component
updateLastCheckedLabel(settings.lastTimeChecked)
}
}.largeGapAfter()
if (WhatsNewAction.isAvailable()) {
row { checkBox(IdeBundle.message("updates.settings.show.editor"), settings.state::isShowWhatsNewEditor) }.largeGapAfter()
}
if (settings.ignoredBuildNumbers.isNotEmpty()) {
row {
myLink = link(IdeBundle.message("updates.settings.ignored")) {
val text = settings.ignoredBuildNumbers.joinToString("\n")
val project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(myLink))
val result = Messages.showMultilineInputDialog(project, null, IdeBundle.message("updates.settings.ignored.title"), text, null, null)
if (result != null) {
settings.ignoredBuildNumbers.clear()
settings.ignoredBuildNumbers.addAll(result.split('\n'))
}
}.component
}.largeGapAfter()
}
if (!(manager == ExternalUpdateManager.TOOLBOX || Registry.`is`("ide.hide.toolbox.promo"))) {
row(" ") { }
row { component(SeparatorComponent()) }
row {
val logo = JBLabel(PluginLogo.reloadIcon(AllIcons.Nodes.Toolbox, 40, 40, null))
logo.verticalAlignment = SwingConstants.TOP
val linkLine = JPanel(FlowLayout(FlowLayout.LEFT, 0, 0))
val font = JBFont.label().asBold()
linkLine.add(JBLabel(IdeBundle.message("updates.settings.recommend.toolbox.first.part")).withBorder(JBUI.Borders.emptyRight(5)).withFont(font))
linkLine.add(BrowserLink(ExternalUpdateManager.TOOLBOX.toolName, TOOLBOX_URL).withFont(font))
val textBlock = JPanel(BorderLayout(0, JBUI.scale(3)))
textBlock.add(linkLine, BorderLayout.NORTH)
textBlock.add(MultiLineLabel(IdeBundle.message("updates.settings.recommend.toolbox.multiline.description")), BorderLayout.CENTER)
val panel = JPanel(BorderLayout(JBUI.scale(10), 0))
panel.add(logo, BorderLayout.WEST)
panel.add(textBlock, BorderLayout.CENTER)
component(panel)
}
}
var wasEnabled = settings.isCheckNeeded || settings.isPluginsCheckNeeded
onGlobalApply {
val isEnabled = settings.isCheckNeeded || settings.isPluginsCheckNeeded
if (isEnabled != wasEnabled) {
when {
isEnabled -> UpdateCheckerComponent.getInstance().queueNextCheck()
else -> UpdateCheckerComponent.getInstance().cancelChecks()
}
wasEnabled = isEnabled
}
}
}
}
private fun Cell.contextLabel(@Label buildText: String): CellBuilder<JLabel> {
val label = label(buildText)
label.component.foreground = UIUtil.getContextHelpForeground()
return label
}
private fun selectedChannel(value: ChannelStatus?): ChannelStatus = value ?: ChannelStatus.RELEASE
private fun updateLastCheckedLabel(time: Long): Unit =
if (time > 0) {
myLastCheckedLabel.text = IdeBundle.message("updates.settings.last.check", DateFormatUtil.formatPrettyDateTime(time))
myLastCheckedLabel.toolTipText = DateFormatUtil.formatDate(time) + ' ' + DateFormatUtil.formatTimeWithSeconds(time)
}
else {
myLastCheckedLabel.text = IdeBundle.message("updates.settings.last.check", IdeBundle.message("updates.last.check.never"))
myLastCheckedLabel.toolTipText = null
}
}
| apache-2.0 | d5afe31f6c940bdf9f157867386e360a | 43.988701 | 157 | 0.705639 | 4.75403 | false | false | false | false |
alvarlagerlof/temadagar-android | app/src/main/java/com/alvarlagerlof/temadagarapp/Main/MainActivity.kt | 1 | 2920 | package com.alvarlagerlof.temadagarapp.Main
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import com.alvarlagerlof.koda.Extensions.replaceFragment
import com.alvarlagerlof.temadagarapp.Main.List.Tab.TabAll
import com.alvarlagerlof.temadagarapp.Main.List.Tab.TabNew
import com.alvarlagerlof.temadagarapp.Main.List.Tab.TabPopular
import com.alvarlagerlof.temadagarapp.R
import com.alvarlagerlof.temadagarapp.Sync.SyncData
import io.realm.Realm
import io.realm.RealmConfiguration
import kotlinx.android.synthetic.main.main_activity.*
class MainActivity : AppCompatActivity() {
internal lateinit var fragment_new: TabNew
internal lateinit var fragment_all: TabAll
internal lateinit var fragment_popular: TabPopular
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
// Realm
setupRealmMigration()
// Sync
SyncData(this)
// Fix subscriptions
//FirebaseSubscriptionsOnUpdate(this)
// Init frags
fragment_new = TabNew()
fragment_all = TabAll()
fragment_popular = TabPopular()
// Views
setSupportActionBar(toolbar)
setUpBottomBar()
}
fun setupRealmMigration() {
Realm.init(this)
Realm.setDefaultConfiguration(RealmConfiguration.Builder()
.name(Realm.DEFAULT_REALM_NAME)
.deleteRealmIfMigrationNeeded()
//.schemaVersion(1)
//.migration(MigrationRealm())
.build())
}
fun setUpBottomBar() {
fragment_container.replaceFragment(supportFragmentManager, fragment_all)
toolbar.title = "Alla dagar"
bottom_bar.setDefaultTab(R.id.tab_all)
bottom_bar.setOnTabSelectListener({ tabId ->
when (tabId) {
R.id.tab_new -> {
fragment_container.replaceFragment(supportFragmentManager, fragment_new)
toolbar.title = "Senast tillagda"
}
R.id.tab_all -> {
fragment_container.replaceFragment(supportFragmentManager, fragment_all)
toolbar.title = "Alla dagar"
}
R.id.tab_popular -> {
fragment_container.replaceFragment(supportFragmentManager, fragment_popular)
toolbar.title = "Populära"
}
}
})
}
// Save bottom_bar position
public override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
bottom_bar.onSaveInstanceState()
}
// Menu
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.main, menu)
return true
}
}
| mit | 109f357f3ff6b40511a3ad2171bc8a45 | 27.339806 | 96 | 0.638917 | 4.416036 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ui/layout/ComponentPredicate.kt | 4 | 3409 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.layout
import com.intellij.ui.DocumentAdapter
import javax.swing.AbstractButton
import javax.swing.JComboBox
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import javax.swing.text.JTextComponent
abstract class ComponentPredicate : () -> Boolean {
abstract fun addListener(listener: (Boolean) -> Unit)
}
val AbstractButton.selected: ComponentPredicate
get() = object : ComponentPredicate() {
override fun invoke(): Boolean = isSelected
override fun addListener(listener: (Boolean) -> Unit) {
addChangeListener { listener(isSelected) }
}
}
fun <T> JComboBox<T>.selectedValueMatches(predicate: (T?) -> Boolean): ComponentPredicate {
return ComboBoxPredicate(this, predicate)
}
class ComboBoxPredicate<T>(private val comboBox: JComboBox<T>, private val predicate: (T?) -> Boolean) : ComponentPredicate() {
override fun invoke(): Boolean = predicate(comboBox.selectedItem as T?)
override fun addListener(listener: (Boolean) -> Unit) {
comboBox.addActionListener {
listener(predicate(comboBox.selectedItem as T?))
}
}
}
fun JTextComponent.enteredTextSatisfies(predicate: (String) -> Boolean): ComponentPredicate {
return TextComponentPredicate(this, predicate)
}
private class TextComponentPredicate(private val component: JTextComponent, private val predicate: (String) -> Boolean) : ComponentPredicate() {
override fun invoke(): Boolean = predicate(component.text)
override fun addListener(listener: (Boolean) -> Unit) {
component.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
listener(invoke())
}
})
}
}
fun <T> JComboBox<T>.selectedValueIs(value: T): ComponentPredicate = selectedValueMatches { it == value }
infix fun ComponentPredicate.and(other: ComponentPredicate): ComponentPredicate {
return AndPredicate(this, other)
}
infix fun ComponentPredicate.or(other: ComponentPredicate): ComponentPredicate {
return OrPredicate(this, other)
}
fun ComponentPredicate.not() : ComponentPredicate {
return NotPredicate(this)
}
private class AndPredicate(private val lhs: ComponentPredicate, private val rhs: ComponentPredicate) : ComponentPredicate() {
override fun invoke(): Boolean = lhs.invoke() && rhs.invoke()
override fun addListener(listener: (Boolean) -> Unit) {
val andListener: (Boolean) -> Unit = { listener(lhs.invoke() && rhs.invoke()) }
lhs.addListener(andListener)
rhs.addListener(andListener)
}
}
private class OrPredicate(private val lhs: ComponentPredicate, private val rhs: ComponentPredicate) : ComponentPredicate() {
override fun invoke(): Boolean = lhs.invoke() || rhs.invoke()
override fun addListener(listener: (Boolean) -> Unit) {
val andListener: (Boolean) -> Unit = { listener(lhs.invoke() || rhs.invoke()) }
lhs.addListener(andListener)
rhs.addListener(andListener)
}
}
private class NotPredicate(private val that: ComponentPredicate) : ComponentPredicate() {
override fun invoke(): Boolean = !that.invoke()
override fun addListener(listener: (Boolean) -> Unit) {
val notListener: (Boolean) -> Unit = { listener(!that.invoke()) }
that.addListener(notListener)
}
} | apache-2.0 | af222e4eb91bbd62a8a2242b997c430e | 34.894737 | 144 | 0.7357 | 4.438802 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/diagnostic/ScanningStatistics.kt | 9 | 3648 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.indexing.diagnostic
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.indexing.UnindexedFileStatus
import com.intellij.util.indexing.diagnostic.dump.paths.PortableFilePath
import com.intellij.util.indexing.diagnostic.dump.paths.PortableFilePaths
import com.intellij.util.indexing.roots.IndexableFilesIterator
class ScanningStatistics(val fileSetName: String) {
var numberOfScannedFiles: Int = 0
/**
* Number of files that have been scanned (iterated) by a different iterator than the one used to iterate this [fileSetName].
* If multiple "file iterators" would iterate the same file, only one of the iterators actually "scans" the file
* (and increments [numberOfScannedFiles] in his statistics).
*/
var numberOfSkippedFiles: Int = 0
var numberOfFilesForIndexing: Int = 0
var numberOfFilesFullyIndexedByInfrastructureExtension: Int = 0
var listOfFilesFullyIndexedByInfrastructureExtension = arrayListOf<String>()
var scanningTime: TimeNano = 0
var statusTime: TimeNano = 0
var timeProcessingUpToDateFiles: TimeNano = 0
var timeUpdatingContentLessIndexes: TimeNano = 0
var timeIndexingWithoutContent: TimeNano = 0
var providerRoots = emptyList<String>()
val scannedFiles = arrayListOf<ScannedFile>()
data class ScannedFile(val portableFilePath: PortableFilePath, val isUpToDate: Boolean, val wasFullyIndexedByInfrastructureExtension: Boolean)
fun addStatus(fileOrDir: VirtualFile, unindexedFileStatus: UnindexedFileStatus, statusTime: Long, project: Project) {
if (fileOrDir.isDirectory) return
numberOfScannedFiles++
if (unindexedFileStatus.shouldIndex) {
numberOfFilesForIndexing++
}
this.statusTime += statusTime
timeProcessingUpToDateFiles += unindexedFileStatus.timeProcessingUpToDateFiles
timeUpdatingContentLessIndexes += unindexedFileStatus.timeUpdatingContentLessIndexes
timeIndexingWithoutContent += unindexedFileStatus.timeIndexingWithoutContent
if (unindexedFileStatus.wasFullyIndexedByInfrastructureExtension) {
numberOfFilesFullyIndexedByInfrastructureExtension++
listOfFilesFullyIndexedByInfrastructureExtension.add(fileOrDir.toString())
}
if (IndexDiagnosticDumper.shouldDumpPathsOfIndexedFiles) {
val portableFilePath = getIndexedFilePath(fileOrDir, project)
scannedFiles += ScannedFile(portableFilePath, !unindexedFileStatus.shouldIndex,
unindexedFileStatus.wasFullyIndexedByInfrastructureExtension)
}
}
private fun getIndexedFilePath(file: VirtualFile, project: Project): PortableFilePath = try {
PortableFilePaths.getPortableFilePath(file, project)
}
catch (e: Exception) {
PortableFilePath.AbsolutePath(file.url)
}
fun addScanningTime(time: Long) {
scanningTime += time
}
fun setNoRootsForRefresh() {
providerRoots = listOf("Not collected for refresh")
}
fun setProviderRoots(provider: IndexableFilesIterator, project: Project) {
if(!IndexDiagnosticDumper.shouldDumpProviderRootPaths) return
val rootUrls = provider.getRootUrls(project)
if (rootUrls.isEmpty()) return
val basePath = project.basePath
if (basePath == null) {
providerRoots = rootUrls.toList()
}
else {
val baseUrl = "file://$basePath"
providerRoots = rootUrls.map { url ->
if (url.startsWith(baseUrl)) url.replaceRange(0, baseUrl.length, "<project root>") else url
}.toList()
}
}
}
| apache-2.0 | 4a0498a7e54b68353ad19da2cba4ffe3 | 39.533333 | 144 | 0.767544 | 4.731518 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/user/Preferences.kt | 1 | 3208 | package com.habitrpg.android.habitica.models.user
import com.google.gson.annotations.SerializedName
import com.habitrpg.android.habitica.models.AvatarPreferences
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import java.util.*
open class Preferences : RealmObject(), AvatarPreferences {
@PrimaryKey
private var userId: String? = null
private var hair: Hair? = null
var suppressModals: SuppressedModals? = null
private var costume: Boolean = false
@SerializedName("disableClasses")
var isDisableClasses: Boolean = false
@SerializedName("sleep")
var isSleep: Boolean = false
var dailyDueDefaultView: Boolean = false
var automaticAllocation: Boolean = false
var allocationMode: String? = null
private var shirt: String? = null
private var skin: String? = null
private var size: String? = null
private var background: String? = null
private var chair: String? = null
var language: String? = null
var sound: String? = null
var dayStart: Int = 0
var timezoneOffset: Int = 0
var timezoneOffsetAtLastCron: Int = 0
var pushNotifications: PushNotificationsPreference? = null
var emailNotifications: EmailNotificationsPreference? = null
var autoEquip: Boolean = true
override fun getBackground(): String? {
return background
}
fun setBackground(background: String) {
this.background = background
}
override fun getCostume(): Boolean {
return costume
}
fun setCostume(costume: Boolean) {
this.costume = costume
}
override fun getDisableClasses(): Boolean {
return isDisableClasses
}
override fun getSleep(): Boolean {
return isSleep
}
override fun getShirt(): String? {
return shirt
}
fun setShirt(shirt: String) {
this.shirt = shirt
}
override fun getSkin(): String? {
return skin
}
fun setSkin(skin: String) {
this.skin = skin
}
override fun getSize(): String? {
return size
}
fun setSize(size: String) {
this.size = size
}
override fun getHair(): Hair? {
return hair
}
fun setHair(hair: Hair) {
this.hair = hair
}
override fun getChair(): String? {
return if (chair != null && chair != "none") {
if (chair?.contains("chair_") == true) {
chair
} else {
"chair_" + chair!!
}
} else null
}
fun setChair(chair: String) {
this.chair = chair
}
override fun getUserId(): String? {
return userId
}
fun setUserId(userId: String?) {
this.userId = userId
if (hair?.isManaged == false) {
hair?.userId = userId
}
if (suppressModals?.isManaged == false) {
suppressModals?.userId = userId
}
}
fun hasTaskBasedAllocation(): Boolean {
return allocationMode?.toLowerCase(Locale.ROOT) == "taskbased" && automaticAllocation
}
}
| gpl-3.0 | ec392ad31ef1f2d659bc8986e01ab3ef | 23.259843 | 93 | 0.592581 | 4.582857 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/viewmodels/ProfileViewModel.kt | 1 | 9239 | package com.kickstarter.viewmodels
import android.util.Pair
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.ApiPaginator
import com.kickstarter.libs.Environment
import com.kickstarter.libs.rx.transformers.Transformers.neverError
import com.kickstarter.libs.utils.EventContextValues
import com.kickstarter.libs.utils.NumberUtils
import com.kickstarter.libs.utils.extensions.isNonZero
import com.kickstarter.libs.utils.extensions.isZero
import com.kickstarter.models.Project
import com.kickstarter.services.DiscoveryParams
import com.kickstarter.services.apiresponses.DiscoverEnvelope
import com.kickstarter.ui.activities.ProfileActivity
import com.kickstarter.ui.adapters.ProfileAdapter
import com.kickstarter.ui.viewholders.EmptyProfileViewHolder
import com.kickstarter.ui.viewholders.ProfileCardViewHolder
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
interface ProfileViewModel {
interface Inputs {
/** Call when the Explore Projects button in the empty state has been clicked. */
fun exploreProjectsButtonClicked()
/** Call when the messages button has been clicked. */
fun messagesButtonClicked()
/** Call when the next page has been invoked. */
fun nextPage()
/** Call when a project card has been clicked. */
fun projectCardClicked(project: Project)
}
interface Outputs {
/** Emits the user avatar image to be displayed. */
fun avatarImageViewUrl(): Observable<String>
/** Emits when the backed projects count should be hidden. */
fun backedCountTextViewHidden(): Observable<Boolean>
/** Emits the backed projects count to be displayed. */
fun backedCountTextViewText(): Observable<String>
/** Emits when the backed projects text view should be hidden. */
fun backedTextViewHidden(): Observable<Boolean>
/** Emits when the created projects count should be hidden. */
fun createdCountTextViewHidden(): Observable<Boolean>
/** Emits the created projects count to be displayed. */
fun createdCountTextViewText(): Observable<String>
/** Emits when the created projects text view should be hidden. */
fun createdTextViewHidden(): Observable<Boolean>
/** Emits when the divider view should be hidden. */
fun dividerViewHidden(): Observable<Boolean>
/** Emits a boolean indicating whether projects are being fetched from the API. */
fun isFetchingProjects(): Observable<Boolean>
/** Emits a list of projects to display in the profile. */
fun projectList(): Observable<List<Project>>
/** Emits when we should resume the [com.kickstarter.ui.activities.DiscoveryActivity]. */
fun resumeDiscoveryActivity(): Observable<Void>
/** Emits when we should start the [com.kickstarter.ui.activities.MessageThreadsActivity]. */
fun startMessageThreadsActivity(): Observable<Void>
/** Emits when we should start the [com.kickstarter.ui.activities.ProjectActivity]. */
fun startProjectActivity(): Observable<Project>
/** Emits the user name to be displayed. */
fun userNameTextViewText(): Observable<String>
}
class ViewModel(environment: Environment) : ActivityViewModel<ProfileActivity>(environment), ProfileAdapter.Delegate, Inputs, Outputs {
private val client = requireNotNull(environment.apiClient())
private val currentUser = requireNotNull(environment.currentUser())
private val exploreProjectsButtonClicked = PublishSubject.create<Void>()
private val messagesButtonClicked = PublishSubject.create<Void>()
private val nextPage = PublishSubject.create<Void>()
private val projectCardClicked = PublishSubject.create<Project>()
private val avatarImageViewUrl: Observable<String>
private val backedCountTextViewHidden: Observable<Boolean>
private val backedCountTextViewText: Observable<String>
private val backedTextViewHidden: Observable<Boolean>
private val createdCountTextViewHidden: Observable<Boolean>
private val createdCountTextViewText: Observable<String>
private val createdTextViewHidden: Observable<Boolean>
private val dividerViewHidden: Observable<Boolean>
private val isFetchingProjects = BehaviorSubject.create<Boolean>()
private val projectList: Observable<List<Project>>
private val resumeDiscoveryActivity: Observable<Void>
private val startMessageThreadsActivity: Observable<Void>
private val userNameTextViewText: Observable<String>
val inputs: Inputs = this
val outputs: Outputs = this
init {
val freshUser = this.client.fetchCurrentUser()
.retry(2)
.compose(neverError())
freshUser.subscribe { this.currentUser.refresh(it) }
val params = DiscoveryParams.builder()
.backed(1)
.perPage(18)
.sort(DiscoveryParams.Sort.ENDING_SOON)
.build()
val paginator = ApiPaginator.builder<Project, DiscoverEnvelope, DiscoveryParams>()
.nextPage(this.nextPage)
.envelopeToListOfData { it.projects() }
.envelopeToMoreUrl { env -> env.urls()?.api()?.moreProjects() }
.loadWithParams { this.client.fetchProjects(params).compose(neverError()) }
.loadWithPaginationPath { this.client.fetchProjects(it).compose(neverError()) }
.build()
paginator.isFetching
.compose(bindToLifecycle())
.subscribe(this.isFetchingProjects)
val loggedInUser = this.currentUser.loggedInUser()
this.avatarImageViewUrl = loggedInUser.map { u -> u.avatar().medium() }
this.backedCountTextViewHidden = loggedInUser
.map { u -> u.backedProjectsCount().isZero() }
this.backedTextViewHidden = this.backedCountTextViewHidden
this.backedCountTextViewText = loggedInUser
.map<Int> { it.backedProjectsCount() }
.filter { it.isNonZero() }
.map { NumberUtils.format(it) }
this.createdCountTextViewHidden = loggedInUser
.map { u -> u.createdProjectsCount().isZero() }
this.createdTextViewHidden = this.createdCountTextViewHidden
this.createdCountTextViewText = loggedInUser
.map<Int> { it.createdProjectsCount() }
.filter { it.isNonZero() }
.map { NumberUtils.format(it) }
this.dividerViewHidden = Observable.combineLatest<Boolean, Boolean, Pair<Boolean, Boolean>>(
this.backedTextViewHidden,
this.createdTextViewHidden
) { a, b -> Pair.create(a, b) }
.map { p -> p.first || p.second }
this.projectList = paginator.paginatedData()
this.resumeDiscoveryActivity = this.exploreProjectsButtonClicked
this.startMessageThreadsActivity = this.messagesButtonClicked
this.userNameTextViewText = loggedInUser.map { it.name() }
projectCardClicked
.compose(bindToLifecycle())
.subscribe { analyticEvents.trackProjectCardClicked(it, EventContextValues.ContextPageName.PROFILE.contextName) }
}
override fun emptyProfileViewHolderExploreProjectsClicked(viewHolder: EmptyProfileViewHolder) = this.exploreProjectsButtonClicked()
override fun exploreProjectsButtonClicked() = this.exploreProjectsButtonClicked.onNext(null)
override fun messagesButtonClicked() = this.messagesButtonClicked.onNext(null)
override fun nextPage() = this.nextPage.onNext(null)
override fun profileCardViewHolderClicked(viewHolder: ProfileCardViewHolder, project: Project) = this.projectCardClicked(project)
override fun projectCardClicked(project: Project) = this.projectCardClicked.onNext(project)
override fun avatarImageViewUrl() = this.avatarImageViewUrl
override fun backedCountTextViewText() = this.backedCountTextViewText
override fun backedCountTextViewHidden() = this.backedCountTextViewHidden
override fun backedTextViewHidden() = this.backedTextViewHidden
override fun createdCountTextViewHidden() = this.createdCountTextViewHidden
override fun createdCountTextViewText() = this.createdCountTextViewText
override fun createdTextViewHidden() = this.createdTextViewHidden
override fun dividerViewHidden() = this.dividerViewHidden
override fun isFetchingProjects(): BehaviorSubject<Boolean> = this.isFetchingProjects
override fun projectList() = this.projectList
override fun resumeDiscoveryActivity() = this.resumeDiscoveryActivity
override fun startProjectActivity() = this.projectCardClicked
override fun startMessageThreadsActivity() = this.startMessageThreadsActivity
override fun userNameTextViewText() = this.userNameTextViewText
}
}
| apache-2.0 | 1424707b0e11f3f2a4c5a84f6ef61749 | 42.375587 | 139 | 0.693906 | 5.288495 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/adapter/SkillsRecyclerViewAdapter.kt | 1 | 6385 | package com.habitrpg.android.habitica.ui.adapter
import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.facebook.drawee.view.SimpleDraweeView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.extensions.inflate
import com.habitrpg.android.habitica.models.Skill
import com.habitrpg.android.habitica.models.user.SpecialItems
import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import io.reactivex.BackpressureStrategy
import io.reactivex.subjects.PublishSubject
class SkillsRecyclerViewAdapter : RecyclerView.Adapter<SkillsRecyclerViewAdapter.SkillViewHolder>() {
private val useSkillSubject = PublishSubject.create<Skill>()
val useSkillEvents = useSkillSubject.toFlowable(BackpressureStrategy.DROP)
var mana: Double = 0.0
set(value) {
field = value
notifyDataSetChanged()
}
var level: Int = 0
set(value) {
field = value
notifyDataSetChanged()
}
var specialItems: SpecialItems? = null
set(value) {
field = value
notifyDataSetChanged()
}
private var skillList: List<Skill> = emptyList()
fun setSkillList(skillList: List<Skill>) {
this.skillList = skillList
this.notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SkillViewHolder {
return SkillViewHolder(parent.inflate(R.layout.skill_list_item))
}
override fun onBindViewHolder(holder: SkillViewHolder, position: Int) {
holder.bind(skillList[position])
}
override fun getItemCount(): Int {
return skillList.size
}
inner class SkillViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
private val magicDrawable: Drawable
private val lockDrawable: Drawable
private val skillImageView: SimpleDraweeView by bindView(R.id.skill_image)
private val skillNameTextView: TextView by bindView(R.id.skill_text)
private val skillNotesTextView: TextView by bindView(R.id.skill_notes)
private val buttonWrapper: ViewGroup by bindView(itemView, R.id.button_wrapper)
private val priceLabel: TextView by bindView(itemView, R.id.price_label)
private val buttonIconView: ImageView by bindView(itemView, R.id.button_icon_view)
private val countLabel: TextView by bindView(itemView, R.id.count_label)
var skill: Skill? = null
var context: Context = itemView.context
init {
buttonWrapper.setOnClickListener(this)
magicDrawable = BitmapDrawable(context.resources, HabiticaIconsHelper.imageOfMagic())
lockDrawable = BitmapDrawable(context.resources, HabiticaIconsHelper.imageOfLocked(ContextCompat.getColor(context, R.color.gray_400)))
}
fun bind(skill: Skill) {
this.skill = skill
skillNameTextView.text = skill.text
skillNotesTextView.text = skill.notes
skillNameTextView.setTextColor(ContextCompat.getColor(context, R.color.gray_50))
skillNotesTextView.setTextColor(ContextCompat.getColor(context, R.color.gray_200))
skillNotesTextView.visibility = View.VISIBLE
priceLabel.visibility = View.VISIBLE
if ("special" == skill.habitClass) {
countLabel.visibility = View.VISIBLE
countLabel.text = getOwnedCount(skill.key).toString()
priceLabel.setText(R.string.skill_transformation_use)
priceLabel.setTextColor(ContextCompat.getColor(context, R.color.brand_400))
buttonIconView.setImageDrawable(null)
buttonWrapper.setBackgroundColor(ContextCompat.getColor(context, R.color.gray_600))
buttonIconView.alpha = 1.0f
priceLabel.alpha = 1.0f
} else {
countLabel.visibility = View.GONE
priceLabel.text = skill.mana?.toString()
priceLabel.setTextColor(ContextCompat.getColor(context, R.color.blue_10))
buttonIconView.setImageDrawable(magicDrawable)
if (skill.mana ?: 0 > mana) {
buttonWrapper.setBackgroundColor(ContextCompat.getColor(context, R.color.gray_600))
buttonIconView.alpha = 0.3f
priceLabel.alpha = 0.3f
} else {
buttonWrapper.setBackgroundColor(ContextCompat.getColor(context, R.color.blue_500_24))
buttonIconView.alpha = 1.0f
priceLabel.alpha = 1.0f
}
if ((skill.lvl ?: 0) > level) {
buttonWrapper.setBackgroundColor(ContextCompat.getColor(context, R.color.gray_600))
skillNameTextView.setTextColor(ContextCompat.getColor(context, R.color.task_gray))
skillNameTextView.text = context.getString(R.string.skill_unlocks_at, skill.lvl)
skillNotesTextView.visibility = View.GONE
buttonIconView.setImageDrawable(lockDrawable)
priceLabel.visibility = View.GONE
}
}
DataBindingUtils.loadImage(skillImageView, "shop_" + skill.key)
}
override fun onClick(v: View) {
if ((skill?.lvl ?: 0) <= level) {
skill?.let { useSkillSubject.onNext(it) }
}
}
private fun getOwnedCount(key: String): Int {
return when (key) {
"snowball" -> specialItems?.snowball
"shinySeed" -> specialItems?.shinySeed
"seafoam" -> specialItems?.seafoam
"spookySparkles" -> specialItems?.spookySparkles
else -> 0
} ?: 0
}
}
}
| gpl-3.0 | a315df22eabcecdc9a9aeb76aef6f080 | 41.435374 | 146 | 0.641973 | 4.815234 | false | false | false | false |
agoda-com/Kakao | kakao/src/main/kotlin/com/agoda/kakao/image/ImageViewAssertions.kt | 1 | 2349 | @file:Suppress("unused")
package com.agoda.kakao.image
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.test.espresso.assertion.ViewAssertions
import com.agoda.kakao.common.assertions.BaseAssertions
import com.agoda.kakao.common.matchers.DrawableMatcher
/**
* Provides assertion for image views
*/
interface ImageViewAssertions : BaseAssertions {
/**
* Checks if the view displays given drawable
*
* @param resId Drawable resource to be matched
* @param toBitmap Lambda with custom Drawable -> Bitmap converter (default is null)
*/
fun hasDrawable(@DrawableRes resId: Int, toBitmap: ((drawable: Drawable) -> Bitmap)? = null) {
view.check(ViewAssertions.matches(DrawableMatcher(resId = resId, toBitmap = toBitmap)))
}
/**
* Checks if the view displays given drawable
*
* @param resId Drawable resource to be matched
* @param tintColorId Tint color resource id
* @param toBitmap Lambda with custom Drawable -> Bitmap converter (default is null)
*/
fun hasDrawableWithTint(@DrawableRes resId: Int, @ColorRes tintColorId: Int, toBitmap: ((drawable: Drawable) -> Bitmap)? = null) {
view.check(ViewAssertions.matches(DrawableMatcher(resId = resId, tintColorId = tintColorId, toBitmap = toBitmap)))
}
/**
* Checks if the view displays given drawable
*
* @param drawable Drawable to be matched
* @param toBitmap Lambda with custom Drawable -> Bitmap converter (default is null)
*/
fun hasDrawable(drawable: Drawable, toBitmap: ((drawable: Drawable) -> Bitmap)? = null) {
view.check(ViewAssertions.matches(DrawableMatcher(drawable = drawable, toBitmap = toBitmap)))
}
/**
* Checks if the view displays given drawable
*
* @param drawable Drawable to be matched
* @param tintColorId Tint color resource id
* @param toBitmap Lambda with custom Drawable -> Bitmap converter (default is null)
*/
fun hasDrawableWithTint(drawable: Drawable, @ColorRes tintColorId: Int, toBitmap: ((drawable: Drawable) -> Bitmap)? = null) {
view.check(ViewAssertions.matches(DrawableMatcher(drawable = drawable, tintColorId = tintColorId , toBitmap = toBitmap)))
}
}
| apache-2.0 | 115e2bbf42b072942fcedf17a013a0b4 | 39.5 | 134 | 0.709238 | 4.624016 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/output/ToolWindowScratchOutputHandler.kt | 1 | 9887 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.scratch.output
import com.intellij.execution.filters.OpenFileHyperlinkInfo
import com.intellij.execution.impl.ConsoleViewImpl
import com.intellij.execution.runners.ExecutionUtil
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.icons.AllIcons
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.TransactionGuard
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.scratch.ScratchExpression
import org.jetbrains.kotlin.idea.scratch.ScratchFile
import org.jetbrains.kotlin.psi.KtPsiFactory
/**
* Method to retrieve shared instance of scratches ToolWindow output handler.
*
* [releaseToolWindowHandler] must be called for every output handler received from this method.
*
* Can be called from EDT only.
*
* @return new toolWindow output handler if one does not exist, otherwise returns the existing one. When application in test mode,
* returns [TestOutputHandler].
*/
fun requestToolWindowHandler(): ScratchOutputHandler {
return if (ApplicationManager.getApplication().isUnitTestMode) {
TestOutputHandler
} else {
ScratchToolWindowHandlerKeeper.requestOutputHandler()
}
}
/**
* Should be called once with the output handler received from the [requestToolWindowHandler] call.
*
* When release is called for every request, the output handler is actually disposed.
*
* When application in test mode, does nothing.
*
* Can be called from EDT only.
*/
fun releaseToolWindowHandler(scratchOutputHandler: ScratchOutputHandler) {
if (!ApplicationManager.getApplication().isUnitTestMode) {
ScratchToolWindowHandlerKeeper.releaseOutputHandler(scratchOutputHandler)
}
}
/**
* Implements logic of shared pointer for the toolWindow output handler.
*
* Not thread safe! Can be used only from the EDT.
*/
private object ScratchToolWindowHandlerKeeper {
private var toolWindowHandler: ScratchOutputHandler? = null
private var toolWindowDisposable = Disposer.newDisposable()
private var counter = 0
fun requestOutputHandler(): ScratchOutputHandler {
if (counter == 0) {
toolWindowHandler = ToolWindowScratchOutputHandler(toolWindowDisposable)
}
counter += 1
return toolWindowHandler!!
}
fun releaseOutputHandler(scratchOutputHandler: ScratchOutputHandler) {
require(counter > 0) { "Counter is $counter, nothing to release!" }
require(toolWindowHandler === scratchOutputHandler) { "$scratchOutputHandler differs from stored $toolWindowHandler" }
counter -= 1
if (counter == 0) {
Disposer.dispose(toolWindowDisposable)
toolWindowDisposable = Disposer.newDisposable()
toolWindowHandler = null
}
}
}
private class ToolWindowScratchOutputHandler(private val parentDisposable: Disposable) : ScratchOutputHandlerAdapter() {
override fun handle(file: ScratchFile, expression: ScratchExpression, output: ScratchOutput) {
printToConsole(file) {
val psiFile = file.getPsiFile()
if (psiFile != null) {
printHyperlink(
getLineInfo(psiFile, expression),
OpenFileHyperlinkInfo(
project,
psiFile.virtualFile,
expression.lineStart
)
)
print(" ", ConsoleViewContentType.NORMAL_OUTPUT)
}
print(output.text, output.type.convert())
}
}
override fun error(file: ScratchFile, message: String) {
printToConsole(file) {
print(message, ConsoleViewContentType.ERROR_OUTPUT)
}
}
private fun printToConsole(file: ScratchFile, print: ConsoleViewImpl.() -> Unit) {
ApplicationManager.getApplication().invokeLater {
val project = file.project.takeIf { !it.isDisposed } ?: return@invokeLater
val toolWindow = getToolWindow(project) ?: createToolWindow(file)
val contents = toolWindow.contentManager.contents
for (content in contents) {
val component = content.component
if (component is ConsoleViewImpl) {
component.print()
component.print("\n", ConsoleViewContentType.NORMAL_OUTPUT)
}
}
toolWindow.setAvailable(true, null)
if (!file.options.isInteractiveMode) {
toolWindow.show(null)
}
toolWindow.setIcon(ExecutionUtil.getLiveIndicator(AllIcons.FileTypes.Text))
}
}
override fun clear(file: ScratchFile) {
ApplicationManager.getApplication().invokeLater {
val toolWindow = getToolWindow(file.project) ?: return@invokeLater
val contents = toolWindow.contentManager.contents
for (content in contents) {
val component = content.component
if (component is ConsoleViewImpl) {
component.clear()
}
}
if (!file.options.isInteractiveMode) {
toolWindow.hide(null)
}
toolWindow.setIcon(AllIcons.FileTypes.Text)
}
}
private fun ScratchOutputType.convert() = when (this) {
ScratchOutputType.OUTPUT -> ConsoleViewContentType.SYSTEM_OUTPUT
ScratchOutputType.RESULT -> ConsoleViewContentType.NORMAL_OUTPUT
ScratchOutputType.ERROR -> ConsoleViewContentType.ERROR_OUTPUT
}
private fun getToolWindow(project: Project): ToolWindow? {
val toolWindowManager = ToolWindowManager.getInstance(project)
return toolWindowManager.getToolWindow(ScratchToolWindowFactory.ID)
}
private fun createToolWindow(file: ScratchFile): ToolWindow {
val project = file.project
val toolWindowManager = ToolWindowManager.getInstance(project)
toolWindowManager.registerToolWindow(ScratchToolWindowFactory.ID, true, ToolWindowAnchor.BOTTOM)
val window =
toolWindowManager.getToolWindow(ScratchToolWindowFactory.ID) ?: error("ScratchToolWindowFactory.ID should be registered")
ScratchToolWindowFactory().createToolWindowContent(project, window)
Disposer.register(parentDisposable, Disposable {
toolWindowManager.unregisterToolWindow(ScratchToolWindowFactory.ID)
})
return window
}
}
private fun getLineInfo(psiFile: PsiFile, expression: ScratchExpression) =
"${psiFile.name}:${expression.lineStart + 1}"
private class ScratchToolWindowFactory : ToolWindowFactory {
companion object {
const val ID = "Scratch Output"
}
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
val consoleView = ConsoleViewImpl(project, true)
toolWindow.setToHideOnEmptyContent(true)
toolWindow.setIcon(AllIcons.FileTypes.Text)
toolWindow.hide(null)
val contentManager = toolWindow.contentManager
val content = contentManager.factory.createContent(consoleView.component, null, false)
contentManager.addContent(content)
val editor = consoleView.editor
if (editor is EditorEx) {
editor.isRendererMode = true
}
Disposer.register(KotlinPluginDisposable.getInstance(project), consoleView)
}
}
private object TestOutputHandler : ScratchOutputHandlerAdapter() {
private val errors = arrayListOf<String>()
private val inlays = arrayListOf<Pair<ScratchExpression, String>>()
override fun handle(file: ScratchFile, expression: ScratchExpression, output: ScratchOutput) {
inlays.add(expression to output.text)
}
override fun error(file: ScratchFile, message: String) {
errors.add(message)
}
override fun onFinish(file: ScratchFile) {
TransactionGuard.submitTransaction(KotlinPluginDisposable.getInstance(file.project), Runnable {
val psiFile = file.getPsiFile()
?: error(
"PsiFile cannot be found for scratch to render inlays in tests:\n" +
"project.isDisposed = ${file.project.isDisposed}\n" +
"inlays = ${inlays.joinToString { it.second }}\n" +
"errors = ${errors.joinToString()}"
)
if (inlays.isNotEmpty()) {
testPrint(psiFile, inlays.map { (expression, text) ->
"/** ${getLineInfo(psiFile, expression)} $text */"
})
inlays.clear()
}
if (errors.isNotEmpty()) {
testPrint(psiFile, listOf(errors.joinToString(prefix = "/** ", postfix = " */")))
errors.clear()
}
})
}
private fun testPrint(file: PsiFile, comments: List<String>) {
WriteCommandAction.runWriteCommandAction(file.project) {
for (comment in comments) {
file.addAfter(
KtPsiFactory(file.project).createComment(comment),
file.lastChild
)
}
}
}
}
| apache-2.0 | fa24ca1c45a02d60122f9fb35cd12355 | 36.881226 | 158 | 0.667139 | 5.379217 | false | false | false | false |
itachi1706/DroidEggs | app/src/main/java/com/itachi1706/droideggs/QEgg/EasterEgg/quares/Quare.kt | 1 | 5078 | /*
* 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 com.itachi1706.droideggs.QEgg.EasterEgg.quares
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.graphics.drawable.Icon
import android.os.Parcel
import android.os.Parcelable
import androidx.annotation.RequiresApi
import java.util.ArrayList
import kotlin.math.abs
import kotlin.math.round
@RequiresApi(23)
class Quare(val width: Int, val height: Int, val depth: Int) : Parcelable {
private val data: IntArray = IntArray(width * height)
private val user: IntArray = data.copyOf()
private fun loadAndQuantize(bitmap8bpp: Bitmap) {
bitmap8bpp.getPixels(data, 0, width, 0, 0, width, height)
if (depth == 8) return
val s = (255f / depth)
for (i in 0 until data.size) {
var f = (data[i] ushr 24).toFloat() / s
// f = f.pow(0.75f) // gamma adjust for bolder lines
f *= 1.25f // brightness adjust for bolder lines
f.coerceAtMost(1f)
data[i] = (round(f) * s).toInt() shl 24
}
}
fun isBlank(): Boolean {
return data.sum() == 0
}
fun load(drawable: Drawable) {
val resized = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8)
val canvas = Canvas(resized)
drawable.setBounds(0, 0, width, height)
drawable.setTint(0xFF000000.toInt())
drawable.draw(canvas)
loadAndQuantize(resized)
resized.recycle()
}
fun load(context: Context, icon: Icon) {
icon.loadDrawable(context)?.let {
load(it)
}
}
fun bitmap(): Bitmap {
return Bitmap.createBitmap(data, width, height, Bitmap.Config.ALPHA_8)
}
fun getUserMark(x: Int, y: Int): Int {
return user[y * width + x] ushr 24
}
fun setUserMark(x: Int, y: Int, v: Int) {
user[y * width + x] = v shl 24
}
fun getDataAt(x: Int, y: Int): Int {
return data[y * width + x] ushr 24
}
fun check(): Boolean {
return data.contentEquals(user)
}
fun check(xSel: Int, ySel: Int): Boolean {
val xStart = if (xSel < 0) 0 else xSel
val xEnd = if (xSel < 0) width - 1 else xSel
val yStart = if (ySel < 0) 0 else ySel
val yEnd = if (ySel < 0) height - 1 else ySel
for (y in yStart..yEnd)
for (x in xStart..xEnd)
if (getDataAt(x, y) != getUserMark(x, y)) return false
return true
}
fun errors(): IntArray {
return IntArray(width * height) {
abs(data[it] - user[it])
}
}
fun getRowClue(y: Int): IntArray {
return getClue(-1, y)
}
fun getColumnClue(x: Int): IntArray {
return getClue(x, -1)
}
fun getClue(xSel: Int, ySel: Int): IntArray {
val arr = ArrayList<Int>()
var len = 0
val xStart = if (xSel < 0) 0 else xSel
val xEnd = if (xSel < 0) width - 1 else xSel
val yStart = if (ySel < 0) 0 else ySel
val yEnd = if (ySel < 0) height - 1 else ySel
for (y in yStart..yEnd)
for (x in xStart..xEnd)
if (getDataAt(x, y) != 0) {
len++
} else if (len > 0) {
arr.add(len)
len = 0
}
if (len > 0) arr.add(len)
else if (arr.size == 0) arr.add(0)
return arr.toIntArray()
}
fun resetUserMarks() {
user.forEachIndexed { index, _ -> user[index] = 0 }
}
// Parcelable interface
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(p: Parcel?, flags: Int) {
p?.let {
p.writeInt(width)
p.writeInt(height)
p.writeInt(depth)
p.writeIntArray(data)
p.writeIntArray(user)
}
}
companion object CREATOR : Parcelable.Creator<Quare> {
override fun createFromParcel(p: Parcel?): Quare {
return p!!.let {
Quare(
p.readInt(), // width
p.readInt(), // height
p.readInt() // depth
).also {
p.readIntArray(it.data)
p.readIntArray(it.user)
}
}
}
override fun newArray(size: Int): Array<Quare?> {
return arrayOfNulls(size)
}
}
} | apache-2.0 | dbc4cbe9ecb14fe9b5abe301ca2e62b6 | 32.414474 | 79 | 0.564986 | 3.812312 | false | false | false | false |
loxal/FreeEthereum | free-ethereum-core/src/main/java/org/ethereum/vm/program/ProgramPrecompile.kt | 1 | 3319 | /*
* 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.vm.program
import org.ethereum.util.ByteUtil
import org.ethereum.util.RLP
import org.ethereum.util.RLPList
import org.ethereum.vm.OpCode
import java.util.*
class ProgramPrecompile {
private val jumpdest = HashSet<Int>()
fun serialize(): ByteArray {
val jdBytes = arrayOfNulls<ByteArray>(jumpdest.size + 1)
var cnt = 0
jdBytes[cnt++] = RLP.encodeInt(version)
for (dst in jumpdest) {
jdBytes[cnt++] = RLP.encodeInt(dst)
}
return RLP.encodeList(*jdBytes)
}
fun hasJumpDest(pc: Int): Boolean {
return jumpdest.contains(pc)
}
companion object {
private val version = 1
fun deserialize(stream: ByteArray): ProgramPrecompile? {
val l = RLP.decode2(stream)[0] as RLPList
val ver = ByteUtil.byteArrayToInt(l[0].rlpData)
if (ver != version) return null
val ret = ProgramPrecompile()
for (i in 1..l.size - 1) {
ret.jumpdest.add(ByteUtil.byteArrayToInt(l[i].rlpData))
}
return ret
}
fun compile(ops: ByteArray): ProgramPrecompile {
val ret = ProgramPrecompile()
var i = 0
while (i < ops.size) {
val op = OpCode.code(ops[i])
if (op == null) {
++i
continue
}
if (op == OpCode.JUMPDEST) ret.jumpdest.add(i)
if (op.asInt() >= OpCode.PUSH1.asInt() && op.asInt() <= OpCode.PUSH32.asInt()) {
i += op.asInt() - OpCode.PUSH1.asInt() + 1
}
++i
}
return ret
}
@Throws(Exception::class)
@JvmStatic fun main(args: Array<String>) {
val pp = ProgramPrecompile()
pp.jumpdest.add(100)
pp.jumpdest.add(200)
val bytes = pp.serialize()
val pp1 = ProgramPrecompile.deserialize(bytes)
println(pp1!!.jumpdest)
}
}
}
| mit | 15de7eb043e422517c1ed1ec0d6f4a27 | 32.19 | 96 | 0.608014 | 4.174843 | false | false | false | false |
JonathanxD/CodeAPI | src/main/kotlin/com/github/jonathanxd/kores/base/TryWithResources.kt | 1 | 3794 | /*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.jonathanxd.kores.base
import com.github.jonathanxd.kores.Instructions
/**
* Try-with-resources
*
* @property variable Variable to try-with-resources (value must be [AutoCloseable]).
* @property body Body of try-with-resources
* @property catchStatements Catch clauses/Exception handlers
* @property finallyStatement Finally statement (in bytecode generator the finally statement is inlined).
*/
data class TryWithResources(
val variable: VariableDeclaration,
override val body: Instructions,
override val catchStatements: List<CatchStatement>,
override val finallyStatement: Instructions
) : TryStatementBase {
init {
BodyHolder.checkBody(this)
}
override fun builder(): Builder = Builder(this)
class Builder() : TryStatementBase.Builder<TryWithResources, Builder> {
lateinit var variable: VariableDeclaration
var body: Instructions = Instructions.empty()
var catchStatements: List<CatchStatement> = emptyList()
var finallyStatement: Instructions = Instructions.empty()
constructor(defaults: TryWithResources) : this() {
this.variable = defaults.variable
this.body = defaults.body
this.catchStatements = defaults.catchStatements
this.finallyStatement = defaults.finallyStatement
}
/**
* See [TryWithResources.variable]
*/
fun variable(value: VariableDeclaration): Builder {
this.variable = value
return this
}
override fun body(value: Instructions): Builder {
this.body = value
return this
}
override fun catchStatements(value: List<CatchStatement>): Builder {
this.catchStatements = value
return this
}
override fun finallyStatement(value: Instructions): Builder {
this.finallyStatement = value
return this
}
override fun build(): TryWithResources =
TryWithResources(this.variable, this.body, this.catchStatements, this.finallyStatement)
companion object {
@JvmStatic
fun builder(): Builder = Builder()
@JvmStatic
fun builder(defaults: TryWithResources): Builder = Builder(defaults)
}
}
}
| mit | 518dbc1d46048ae52034958eb0064cfb | 36.196078 | 118 | 0.673432 | 4.972477 | false | false | false | false |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/widget/FadingSnackbar.kt | 5 | 2894 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.widget
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.Button
import android.widget.FrameLayout
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.core.view.postDelayed
import com.google.samples.apps.iosched.R
/**
* A custom snackbar implementation allowing more control over placement and entry/exit animations.
*/
class FadingSnackbar(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {
private val message: TextView
private val action: Button
init {
val view = LayoutInflater.from(context).inflate(R.layout.fading_snackbar_layout, this, true)
message = view.findViewById(R.id.snackbar_text)
action = view.findViewById(R.id.snackbar_action)
}
fun dismiss() {
if (visibility == VISIBLE && alpha == 1f) {
animate()
.alpha(0f)
.withEndAction { visibility = GONE }
.duration = EXIT_DURATION
}
}
fun show(
@StringRes messageId: Int = 0,
messageText: CharSequence? = null,
@StringRes actionId: Int? = null,
longDuration: Boolean = true,
actionClick: () -> Unit = { dismiss() },
dismissListener: () -> Unit = { }
) {
message.text = messageText ?: context.getString(messageId)
if (actionId != null) {
action.run {
visibility = VISIBLE
text = context.getString(actionId)
setOnClickListener {
actionClick()
}
}
} else {
action.visibility = GONE
}
alpha = 0f
visibility = VISIBLE
animate()
.alpha(1f)
.duration = ENTER_DURATION
val showDuration = ENTER_DURATION + if (longDuration) LONG_DURATION else SHORT_DURATION
postDelayed(showDuration) {
dismiss()
dismissListener()
}
}
companion object {
private const val ENTER_DURATION = 300L
private const val EXIT_DURATION = 200L
private const val SHORT_DURATION = 1_500L
private const val LONG_DURATION = 2_750L
}
}
| apache-2.0 | 9f544a83f149fe0b3547277530c96322 | 31.155556 | 100 | 0.633379 | 4.55748 | false | false | false | false |
androidx/androidx | collection/collection/src/commonTest/kotlin/androidx/collection/CircularArrayTest.kt | 3 | 4355 | /*
* 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.collection
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
public class CircularArrayTest {
private val ELEMENT_X = "x"
private val ELEMENT_Y = "y"
private val ELEMENT_Z = "z"
@Test
public fun creatingWithZeroCapacity() {
assertFailsWith<IllegalArgumentException> {
CircularArray<String>(0)
}
}
@Test
public fun creatingWithOverCapacity() {
assertFailsWith<IllegalArgumentException> {
CircularArray<String>(Int.MAX_VALUE)
}
}
@Test
public fun basicOperations() {
val array = CircularArray<String>()
assertTrue(array.isEmpty())
assertEquals(0, array.size())
array.addFirst(ELEMENT_X)
array.addFirst(ELEMENT_Y)
array.addLast(ELEMENT_Z)
assertFalse(array.isEmpty())
assertEquals(3, array.size())
assertEquals(ELEMENT_Y, array.first)
assertEquals(ELEMENT_Z, array.last)
assertEquals(ELEMENT_X, array[1])
assertEquals(ELEMENT_Y, array.popFirst())
assertEquals(ELEMENT_Z, array.popLast())
assertEquals(ELEMENT_X, array.first)
assertEquals(ELEMENT_X, array.last)
assertEquals(ELEMENT_X, array.popFirst())
assertTrue(array.isEmpty())
assertEquals(0, array.size())
}
@Test
public fun overpoppingFromStart() {
val array = CircularArray<String>()
array.addFirst(ELEMENT_X)
array.popFirst()
assertFailsWith<IndexOutOfBoundsException> {
array.popFirst()
}
}
@Test
public fun overpoppingFromEnd() {
val array = CircularArray<String>()
array.addFirst(ELEMENT_X)
array.popLast()
assertFailsWith<IndexOutOfBoundsException> {
array.popLast()
}
}
@Test
public fun removeFromEitherEnd() {
val array = CircularArray<String>()
array.addFirst(ELEMENT_X)
array.addFirst(ELEMENT_Y)
array.addLast(ELEMENT_Z)
// These are no-ops.
array.removeFromStart(0)
array.removeFromStart(-1)
array.removeFromEnd(0)
array.removeFromEnd(-1)
array.removeFromStart(2)
assertEquals(ELEMENT_Z, array.first)
array.removeFromEnd(1)
assertTrue(array.isEmpty())
assertEquals(0, array.size())
}
@Test
public fun overremovalFromStart() {
val array = CircularArray<String>()
array.addFirst(ELEMENT_X)
array.addFirst(ELEMENT_Y)
array.addLast(ELEMENT_Z)
assertFailsWith<IndexOutOfBoundsException> {
array.removeFromStart(4)
}
}
@Test
public fun overremovalFromEnd() {
val array = CircularArray<String>()
array.addFirst(ELEMENT_X)
array.addFirst(ELEMENT_Y)
array.addLast(ELEMENT_Z)
assertFailsWith<IndexOutOfBoundsException> {
array.removeFromEnd(4)
}
}
@Test
public fun grow() {
val array = CircularArray<String>(1)
val expectedSize = 32768
repeat(expectedSize) {
array.addFirst("String $it")
}
assertEquals(expectedSize, array.size())
}
@Test
public fun storeAndRetrieveNull() {
val array = CircularArray<String?>(1)
array.addFirst(null)
assertNull(array.popFirst())
array.addLast(null)
assertNull(array.popLast())
// Collection is empty so this should throw.
assertFailsWith<IndexOutOfBoundsException> {
array.popLast()
}
}
} | apache-2.0 | 27065cc4b230ce0f38062e21689bb6d9 | 27.285714 | 75 | 0.633754 | 4.494324 | false | true | false | false |
androidx/androidx | work/work-lint/src/main/java/androidx/work/lint/RemoveWorkManagerInitializerDetector.kt | 3 | 6149 | /*
* 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.
*/
@file:Suppress("UnstableApiUsage")
package androidx.work.lint
import com.android.SdkConstants.ANDROID_URI
import com.android.SdkConstants.ATTR_NAME
import com.android.SdkConstants.TOOLS_URI
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Context
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Location
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.android.tools.lint.detector.api.XmlContext
import com.android.tools.lint.detector.api.XmlScanner
import java.util.EnumSet
import org.jetbrains.uast.UClass
import org.w3c.dom.Element
import org.w3c.dom.Node
import org.w3c.dom.NodeList
class RemoveWorkManagerInitializerDetector : Detector(), SourceCodeScanner, XmlScanner {
private var removedDefaultInitializer = false
private var location: Location? = null
// The `Application` subclass.
private var javaContext: JavaContext? = null
private var klass: UClass? = null
private var applicationImplementsConfigurationProvider = false
companion object {
private const val DESCRIPTION = "Remove androidx.work.WorkManagerInitializer from " +
"your AndroidManifest.xml when using on-demand initialization."
val ISSUE = Issue.create(
id = "RemoveWorkManagerInitializer",
briefDescription = DESCRIPTION,
explanation = """
If an `android.app.Application` implements `androidx.work.Configuration.Provider`,
the default `androidx.startup.InitializationProvider` needs to be removed from the
AndroidManifest.xml file.
""",
androidSpecific = true,
category = Category.CORRECTNESS,
severity = Severity.FATAL,
implementation = Implementation(
RemoveWorkManagerInitializerDetector::class.java,
EnumSet.of(Scope.JAVA_FILE, Scope.MANIFEST)
)
)
private const val ATTR_NODE = "node"
fun NodeList?.find(fn: (node: Node) -> Boolean): Node? {
if (this == null) {
return null
} else {
for (i in 0 until this.length) {
val node = this.item(i)
if (fn(node)) {
return node
}
}
return null
}
}
}
override fun getApplicableElements() = listOf("application")
override fun applicableSuperClasses() = listOf(
"android.app.Application",
"androidx.work.Configuration.Provider"
)
override fun visitElement(context: XmlContext, element: Element) {
// Check providers
val providers = element.getElementsByTagName("provider")
val provider = providers.find { node ->
val name = node.attributes.getNamedItemNS(ANDROID_URI, ATTR_NAME)?.textContent
name == "androidx.startup.InitializationProvider"
}
if (provider != null) {
location = context.getLocation(provider)
val remove = provider.attributes.getNamedItemNS(TOOLS_URI, ATTR_NODE)
if (remove?.textContent == "remove") {
removedDefaultInitializer = true
}
}
// Check metadata
val metadataElements = element.getElementsByTagName("meta-data")
val metadata = metadataElements.find { node ->
val name = node.attributes.getNamedItemNS(ANDROID_URI, ATTR_NAME)?.textContent
name == "androidx.work.WorkManagerInitializer"
}
if (metadata != null && !removedDefaultInitializer) {
location = context.getLocation(metadata)
val remove = metadata.attributes.getNamedItemNS(TOOLS_URI, ATTR_NODE)
if (remove?.textContent == "remove") {
removedDefaultInitializer = true
}
}
}
override fun visitClass(context: JavaContext, declaration: UClass) {
javaContext = context
if (context.evaluator.inheritsFrom(
declaration.javaPsi,
"android.app.Application",
false
)
) {
klass = declaration
if (context.evaluator.implementsInterface(
declaration.javaPsi,
"androidx.work.Configuration.Provider",
false
)
) {
applicationImplementsConfigurationProvider = true
}
}
}
override fun afterCheckRootProject(context: Context) {
val location = location ?: Location.create(context.file)
val javaKlass = klass
val isSuppressed = if (javaContext != null && javaKlass != null) {
context.driver.isSuppressed(javaContext, ISSUE, javaKlass.javaPsi)
} else {
false
}
if (applicationImplementsConfigurationProvider) {
if (!removedDefaultInitializer && !isSuppressed) {
context.report(
issue = ISSUE,
location = location,
message = DESCRIPTION
)
}
}
}
}
| apache-2.0 | 479e3bd0949c378adcc961a41cef32d2 | 36.266667 | 98 | 0.629371 | 4.876289 | false | false | false | false |
androidx/androidx | compose/ui/ui-test/src/androidAndroidTest/kotlin/androidx/compose/ui/test/gesturescope/SendDoubleClickTest.kt | 3 | 4093 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.test.gesturescope
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.test.InputDispatcher.Companion.eventPeriodMillis
import androidx.compose.ui.test.doubleClick
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performGesture
import androidx.compose.ui.test.util.ClickableTestBox
import androidx.compose.ui.test.util.ClickableTestBox.defaultSize
import androidx.compose.ui.test.util.ClickableTestBox.defaultTag
import androidx.compose.ui.test.util.SinglePointerInputRecorder
import androidx.compose.ui.test.util.recordedDurationMillis
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@MediumTest
@RunWith(Parameterized::class)
class SendDoubleClickTest(private val config: TestConfig) {
data class TestConfig(val position: Offset?, val delayMillis: Long?)
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun createTestSet(): List<TestConfig> {
return mutableListOf<TestConfig>().apply {
for (delay in listOf(null, 50L)) {
for (x in listOf(1.0f, 33.0f, 99.0f)) {
for (y in listOf(1.0f, 33.0f, 99.0f)) {
add(TestConfig(Offset(x, y), delay))
}
}
add(TestConfig(null, delay))
}
}
}
}
@get:Rule
val rule = createComposeRule()
private val recordedDoubleClicks = mutableListOf<Offset>()
private val expectedClickPosition =
config.position ?: Offset(defaultSize / 2, defaultSize / 2)
// The delay plus 2 clicks
private val expectedDurationMillis =
(config.delayMillis ?: 145L) + (2 * eventPeriodMillis)
private fun recordDoubleClick(position: Offset) {
recordedDoubleClicks.add(position)
}
@Test
fun testDoubleClick() {
// Given some content
val recorder = SinglePointerInputRecorder()
rule.setContent {
ClickableTestBox(
Modifier
.pointerInput(Unit) { detectTapGestures(onDoubleTap = ::recordDoubleClick) }
.then(recorder)
)
}
// When we inject a double click
@Suppress("DEPRECATION")
rule.onNodeWithTag(defaultTag).performGesture {
if (config.position != null && config.delayMillis != null) {
doubleClick(config.position, config.delayMillis)
} else if (config.position != null) {
doubleClick(config.position)
} else if (config.delayMillis != null) {
doubleClick(delayMillis = config.delayMillis)
} else {
doubleClick()
}
}
rule.waitForIdle()
// Then we record 1 double click at the expected position
assertThat(recordedDoubleClicks).isEqualTo(listOf(expectedClickPosition))
// And that the duration was as expected
assertThat(recorder.recordedDurationMillis).isEqualTo(expectedDurationMillis)
}
}
| apache-2.0 | 69e2c71fa1ca3afbebdcc0998bf18249 | 35.873874 | 96 | 0.671634 | 4.598876 | false | true | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/index/actions/GitStageCompareWithVersionAction.kt | 6 | 3262 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.index.actions
import com.intellij.diff.DiffDialogHints
import com.intellij.diff.DiffManager
import com.intellij.diff.chains.SimpleDiffRequestChain
import com.intellij.diff.chains.SimpleDiffRequestProducer
import com.intellij.diff.requests.DiffRequest
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.vfs.VirtualFile
import git4idea.index.*
import git4idea.index.vfs.GitIndexVirtualFile
import git4idea.index.vfs.filePath
abstract class GitStageCompareWithVersionAction(private val currentVersion: ContentVersion,
private val compareWithVersion: ContentVersion) : DumbAwareAction() {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun update(e: AnActionEvent) {
val project = e.project
val file = e.getData(CommonDataKeys.VIRTUAL_FILE)
if (project == null || !isStagingAreaAvailable(project) || file == null
|| (file is GitIndexVirtualFile != (currentVersion == ContentVersion.STAGED))) {
e.presentation.isEnabledAndVisible = false
return
}
val status = GitStageTracker.getInstance(project).status(file)
e.presentation.isVisible = (status != null)
e.presentation.isEnabled = (status?.has(compareWithVersion) == true)
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val file = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE)
val root = getRoot(project, file) ?: return
val status = GitStageTracker.getInstance(project).status(root, file) ?: return
val producer = SimpleDiffRequestProducer.create(file.filePath(), ThrowableComputable {
createDiffRequest(project, root, status)
})
DiffManager.getInstance().showDiff(e.project, SimpleDiffRequestChain.fromProducer(producer), DiffDialogHints.DEFAULT)
}
abstract fun createDiffRequest(project: Project, root: VirtualFile, status: GitFileStatus): DiffRequest
}
class GitStageCompareLocalWithStagedAction : GitStageCompareWithVersionAction(ContentVersion.LOCAL, ContentVersion.STAGED) {
override fun createDiffRequest(project: Project, root: VirtualFile, status: GitFileStatus): DiffRequest {
return compareStagedWithLocal(project, root, status)
}
}
class GitStageCompareStagedWithLocalAction : GitStageCompareWithVersionAction(ContentVersion.STAGED, ContentVersion.LOCAL) {
override fun createDiffRequest(project: Project, root: VirtualFile, status: GitFileStatus): DiffRequest {
return compareStagedWithLocal(project, root, status)
}
}
class GitStageCompareStagedWithHeadAction : GitStageCompareWithVersionAction(ContentVersion.STAGED, ContentVersion.HEAD) {
override fun createDiffRequest(project: Project, root: VirtualFile, status: GitFileStatus): DiffRequest {
return compareHeadWithStaged(project, root, status)
}
} | apache-2.0 | b5b0cb6578523281cfc1a760764878d7 | 45.614286 | 124 | 0.784795 | 4.883234 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/jps/src/com/intellij/workspaceModel/ide/impl/jps/serialization/FacetsSerializer.kt | 2 | 5421 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.jps.serialization
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.xmlb.XmlSerializer
import com.intellij.workspaceModel.ide.JpsFileEntitySource
import com.intellij.workspaceModel.ide.JpsImportedEntitySource
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.bridgeEntities.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.jps.model.serialization.JDomSerializationUtil
import org.jetbrains.jps.model.serialization.facet.FacetManagerState
import org.jetbrains.jps.model.serialization.facet.FacetState
import com.intellij.workspaceModel.storage.bridgeEntities.modifyEntity
internal class FacetsSerializer(private val imlFileUrl: VirtualFileUrl, private val internalSource: JpsFileEntitySource,
private val componentName: String, private val baseModuleDirPath: String?, private val externalStorage: Boolean) {
/**
* This function should return void (Unit)
* The current result value is a temporal solution to find the root cause of https://ea.jetbrains.com/browser/ea_problems/239676
*/
internal fun loadFacetEntities(builder: MutableEntityStorage, moduleEntity: ModuleEntity, reader: JpsFileContentReader) {
val facetManagerTag = reader.loadComponent(imlFileUrl.url, componentName, baseModuleDirPath) ?: return
val facetManagerState = XmlSerializer.deserialize(facetManagerTag, FacetManagerState::class.java)
val orderOfFacets = ArrayList<String>()
loadFacetEntities(facetManagerState.facets, builder, moduleEntity, orderOfFacets)
if (orderOfFacets.size > 1 && !externalStorage) {
val entity = moduleEntity.facetOrder
if (entity != null) {
builder.modifyEntity(entity) {
this.orderOfFacets = orderOfFacets
}
}
else {
builder.addEntity(FacetsOrderEntity(orderOfFacets, internalSource) {
this.moduleEntity = moduleEntity
})
}
}
}
private fun loadFacetEntities(facetStates: List<FacetState>, builder: MutableEntityStorage, moduleEntity: ModuleEntity,
orderOfFacets: MutableList<String>) {
fun evaluateExternalSystemIdAndEntitySource(facetState: FacetState): Pair<String?, EntitySource> {
val externalSystemId = facetState.externalSystemId ?: facetState.externalSystemIdInInternalStorage
val entitySource = if (externalSystemId == null) internalSource
else JpsImportedEntitySource(internalSource, externalSystemId, externalStorage)
val actualExternalSystemId = if (externalSystemId != null && !externalStorage) externalSystemId else null
return actualExternalSystemId to entitySource
}
val facetTypeToSerializer = CustomFacetRelatedEntitySerializer.EP_NAME.extensionList.associateBy { it.supportedFacetType }
for (facetState in facetStates) {
orderOfFacets.add(facetState.name)
val serializer = facetTypeToSerializer[facetState.facetType] ?: DefaultFacetEntitySerializer.instance
serializer.loadEntitiesFromFacetState(builder, moduleEntity, facetState, ::evaluateExternalSystemIdAndEntitySource)
}
}
internal fun saveFacetEntities(moduleEntity: ModuleEntity?,
affectedEntities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>,
writer: JpsFileContentWriter,
entitySourceFilter: (EntitySource) -> Boolean) {
val fileUrl = imlFileUrl.url
val facetStatesFromEP = CustomFacetRelatedEntitySerializer.EP_NAME.extensionList
.mapNotNull { entitySerializer ->
val entitiesToSave = affectedEntities[entitySerializer.rootEntityType]?.filter { entitySourceFilter.invoke(it.entitySource) }
?: return@mapNotNull null
entitySerializer.createFacetStateFromEntities(entitiesToSave, externalStorage)
}.flatten()
if (facetStatesFromEP.isEmpty()) {
writer.saveComponent(fileUrl, componentName, null)
return
}
val facetManagerState = FacetManagerState()
val facetNameToFacetState = facetStatesFromEP.groupByTo(HashMap()) { it.name }
val orderOfFacets = moduleEntity?.facetOrder?.orderOfFacets ?: emptyList()
for (facetName in orderOfFacets) {
facetNameToFacetState.remove(facetName)?.forEach {
facetManagerState.facets.add(it)
}
}
facetManagerState.facets.addAll(facetNameToFacetState.values.flatten())
val componentTag = JDomSerializationUtil.createComponentElement(componentName)
XmlSerializer.serializeInto(facetManagerState, componentTag)
if (externalStorage && FileUtil.extensionEquals(fileUrl, "iml")) {
// Trying to catch https://ea.jetbrains.com/browser/ea_problems/239676
logger<FacetsSerializer>().error("""Incorrect file for the serializer
|externalStorage: $externalStorage
|file path: $fileUrl
|componentName: $componentName
""".trimMargin())
}
writer.saveComponent(fileUrl, componentName, componentTag)
}
}
| apache-2.0 | 1f57c7f9e915634616ef156341edff1f | 51.125 | 146 | 0.750231 | 5.138389 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/data/database/models/ChapterImpl.kt | 1 | 798 | package eu.kanade.tachiyomi.data.database.models
class ChapterImpl : Chapter {
override var id: Long? = null
override var manga_id: Long? = null
override lateinit var url: String
override lateinit var name: String
override var read: Boolean = false
override var last_page_read: Int = 0
override var date_fetch: Long = 0
override var date_upload: Long = 0
override var chapter_number: Float = 0f
override var source_order: Int = 0
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val chapter = other as Chapter
return url == chapter.url
}
override fun hashCode(): Int {
return url.hashCode()
}
} | gpl-3.0 | f98a96f04cc3a61cd55c23e73640c01f | 19.487179 | 71 | 0.640351 | 4.336957 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinLocalFunctionUVariable.kt | 4 | 1328 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.kotlin
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiExpression
import com.intellij.psi.PsiVariable
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable
@ApiStatus.Internal
class KotlinLocalFunctionUVariable(
val function: KtFunction,
override val javaPsi: PsiVariable,
givenParent: UElement?
) : KotlinAbstractUElement(givenParent), UVariableEx, PsiVariable by javaPsi {
override val psi get() = javaPsi
override val sourcePsi: PsiElement = (javaPsi as? UastKotlinPsiVariable?)?.ktElement ?: javaPsi
override val uastInitializer: UExpression? by lz {
createLocalFunctionLambdaExpression(function, this)
}
override val typeReference: UTypeReferenceExpression? = null
override val uastAnchor: UElement? = null
override val uAnnotations: List<UAnnotation> = emptyList()
override fun getOriginalElement(): PsiElement {
return psi.originalElement
}
override fun getInitializer(): PsiExpression? {
return psi.initializer
}
}
| apache-2.0 | 6dabb2834d262198064f9e0c0e97d93c | 35.888889 | 158 | 0.767319 | 4.900369 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/objcexport/localEA.kt | 4 | 1309 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
// All classes and methods should be used in tests
@file:Suppress("UNUSED")
package localEA
class ArraysConstructor {
private val memberArray: IntArray
constructor(int1: Int, int2: Int) {
memberArray = IntArray(2)
set(int1, int2)
}
fun set(int1: Int, int2: Int) {
memberArray[0] = int1
memberArray[1] = int2
}
fun log() = "size: ${memberArray.size}, contents: ${memberArray.contentToString()}"
}
class ArraysDefault {
private val memberArray = IntArray(2)
constructor(int1: Int, int2: Int) {
set(int1, int2)
}
fun set(int1: Int, int2: Int) {
memberArray[0] = int1
memberArray[1] = int2
}
fun log() = "size: ${memberArray.size}, contents: ${memberArray.contentToString()}"
}
class ArraysInitBlock {
private val memberArray : IntArray
init {
memberArray = IntArray(2)
}
constructor(int1: Int, int2: Int) {
set(int1, int2)
}
fun set(int1: Int, int2: Int) {
memberArray[0] = int1
memberArray[1] = int2
}
fun log() = "size: ${memberArray.size}, contents: ${memberArray.contentToString()}"
}
| apache-2.0 | 39fd61f3fad348b3f7738cd589544e21 | 26.270833 | 101 | 0.620321 | 3.435696 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ReorderParametersFix.kt | 2 | 5076 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parentOfType
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.psi.childrenDfsSequence
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.variableCallOrThis
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeSignatureConfiguration
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor
import org.jetbrains.kotlin.idea.refactoring.changeSignature.modify
import org.jetbrains.kotlin.idea.refactoring.changeSignature.runChangeSignature
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.util.graph.DirectedGraph
import org.jetbrains.kotlin.util.graph.sortTopologically
import org.jetbrains.kotlin.util.sortedConservativelyBy
class ReorderParametersFix(
element: KtNamedFunction,
private val newParametersOrder: List<String>,
) : KotlinQuickFixAction<KtNamedFunction>(element) {
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val function = element ?: return
val descriptor =
ActionUtil.underModalProgress(project, KotlinBundle.message("analyzing.functions"), function::descriptor)
as? FunctionDescriptor ?: return
runChangeSignature(
function.project,
editor,
descriptor,
object : KotlinChangeSignatureConfiguration {
override fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor =
originalDescriptor.modify { descriptor ->
if (descriptor.parametersCount == newParametersOrder.size) {
val parameterToIndex = newParametersOrder.withIndex().associate { it.value to it.index }
descriptor.parameters.sortBy { parameterToIndex[it.name] ?: -1 /*-1 is for receiver*/ }
}
}
override fun performSilently(affectedFunctions: Collection<PsiElement>) = true
},
function,
KotlinBundle.message("reorder.parameters.command")
)
}
override fun startInWriteAction(): Boolean = false
override fun getText(): String = KotlinBundle.message("reorder.parameters")
override fun getFamilyName(): String = text
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val function = diagnostic.psiElement.parentOfType<KtNamedFunction>(withSelf = true) ?: return null
val functionDescriptor = function.descriptor as? FunctionDescriptor ?: return null
val parameters = function.valueParameterList?.parameters ?: return null
val parametersDependencyGraph = parameters.asSequence().flatMap { parameter ->
parameter.name?.let { parameterName ->
parameter.defaultValue
?.childrenDfsSequence()
?.filterIsInstance<KtNameReferenceExpression>()
?.mapNotNull { it.resolveToCall()?.variableCallOrThis()?.resultingDescriptor as? ValueParameterDescriptor }
?.filter { it.containingDeclaration == functionDescriptor }
?.map { DirectedGraph.Edge(from = it.name.asString(), to = parameterName) }
?.toList()
} ?: emptyList()
}.toSet()
val parametersSortedTopologically = DirectedGraph(parametersDependencyGraph).sortTopologically() ?: return null
val parameterToTopologicalIndex = parametersSortedTopologically.asSequence().withIndex()
.flatMap { (topologicalIndex, parameters) -> parameters.map { IndexedValue(topologicalIndex, it) } }
.associate { (topologicalIndex, parameterName) -> parameterName to topologicalIndex }
val sortedParameters = parameters.asSequence()
.mapNotNull(KtParameter::getName)
.sortedConservativelyBy(parameterToTopologicalIndex::getValue)
.toList()
if (sortedParameters.size != parameters.size) return null
return ReorderParametersFix(function, sortedParameters)
}
}
}
| apache-2.0 | 6e7d4a089cc7743486b58b8b9fa401c2 | 56.033708 | 131 | 0.702916 | 5.529412 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/handlers/KotlinFindMemberUsagesHandler.kt | 1 | 18938 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.findUsages.handlers
import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector
import com.intellij.find.FindManager
import com.intellij.find.findUsages.AbstractFindUsagesDialog
import com.intellij.find.findUsages.FindUsagesOptions
import com.intellij.find.impl.FindManagerImpl
import com.intellij.icons.AllIcons.Actions
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.MethodReferencesSearch
import com.intellij.psi.search.searches.OverridingMethodsSearch
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.usageView.UsageInfo
import com.intellij.util.*
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.KotlinIndependentBundle
import org.jetbrains.kotlin.idea.asJava.LightClassProvider.Companion.providedToLightMethods
import org.jetbrains.kotlin.idea.findUsages.*
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesSupport.Companion.getTopMostOverriddenElementsToHighlight
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesSupport.Companion.isDataClassComponentFunction
import org.jetbrains.kotlin.idea.findUsages.dialogs.KotlinFindFunctionUsagesDialog
import org.jetbrains.kotlin.idea.findUsages.dialogs.KotlinFindPropertyUsagesDialog
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.filterDataClassComponentsIfDisabled
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.isOverridable
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchOverriders
import org.jetbrains.kotlin.idea.search.excludeKotlinSources
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReadWriteAccessDetector
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters
import org.jetbrains.kotlin.idea.search.isImportUsage
import org.jetbrains.kotlin.idea.search.isOnlyKotlinSearch
import org.jetbrains.kotlin.idea.search.isPotentiallyOperator
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parameterIndex
import javax.swing.event.HyperlinkEvent
import javax.swing.event.HyperlinkListener
abstract class KotlinFindMemberUsagesHandler<T : KtNamedDeclaration> protected constructor(
declaration: T,
elementsToSearch: Collection<PsiElement>,
factory: KotlinFindUsagesHandlerFactory
) : KotlinFindUsagesHandler<T>(declaration, elementsToSearch, factory) {
private class Function(
declaration: KtFunction,
elementsToSearch: Collection<PsiElement>,
factory: KotlinFindUsagesHandlerFactory
) : KotlinFindMemberUsagesHandler<KtFunction>(declaration, elementsToSearch, factory) {
override fun getFindUsagesOptions(dataContext: DataContext?): FindUsagesOptions = factory.findFunctionOptions
override fun getPrimaryElements(): Array<PsiElement> =
if (factory.findFunctionOptions.isSearchForBaseMethod) {
val supers = KotlinFindUsagesSupport.getSuperMethods(psiElement as KtFunction, null)
if (supers.contains(psiElement)) supers.toTypedArray() else (supers + psiElement).toTypedArray()
} else super.getPrimaryElements()
override fun getFindUsagesDialog(
isSingleFile: Boolean,
toShowInNewTab: Boolean,
mustOpenInNewTab: Boolean
): AbstractFindUsagesDialog {
val options = factory.findFunctionOptions
val lightMethod = getElement().providedToLightMethods().firstOrNull()
if (lightMethod != null) {
return KotlinFindFunctionUsagesDialog(lightMethod, project, options, toShowInNewTab, mustOpenInNewTab, isSingleFile, this)
}
return super.getFindUsagesDialog(isSingleFile, toShowInNewTab, mustOpenInNewTab)
}
override fun createKotlinReferencesSearchOptions(options: FindUsagesOptions, forHighlight: Boolean): KotlinReferencesSearchOptions {
val kotlinOptions = options as KotlinFunctionFindUsagesOptions
return KotlinReferencesSearchOptions(
acceptCallableOverrides = true,
acceptOverloads = kotlinOptions.isIncludeOverloadUsages,
acceptExtensionsOfDeclarationClass = kotlinOptions.isIncludeOverloadUsages,
searchForExpectedUsages = kotlinOptions.searchExpected,
searchForComponentConventions = !forHighlight
)
}
override fun applyQueryFilters(element: PsiElement, options: FindUsagesOptions, query: Query<PsiReference>): Query<PsiReference> {
val kotlinOptions = options as KotlinFunctionFindUsagesOptions
return query
.applyFilter(kotlinOptions.isSkipImportStatements) { !it.isImportUsage() }
}
}
private class Property(
propertyDeclaration: KtNamedDeclaration,
elementsToSearch: Collection<PsiElement>,
factory: KotlinFindUsagesHandlerFactory
) : KotlinFindMemberUsagesHandler<KtNamedDeclaration>(propertyDeclaration, elementsToSearch, factory) {
override fun processElementUsages(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions
): Boolean {
if (isUnitTestMode() ||
!isPropertyOfDataClass ||
psiElement.getDisableComponentAndDestructionSearch(resetSingleFind = false)
) return super.processElementUsages(element, processor, options)
val indicator = ProgressManager.getInstance().progressIndicator
val notificationCanceller = scheduleNotificationForDataClassComponent(project, element, indicator)
try {
return super.processElementUsages(element, processor, options)
} finally {
Disposer.dispose(notificationCanceller)
}
}
private val isPropertyOfDataClass = runReadAction {
propertyDeclaration.parent is KtParameterList &&
propertyDeclaration.parent.parent is KtPrimaryConstructor &&
propertyDeclaration.parent.parent.parent.let { it is KtClass && it.isData() }
}
override fun getPrimaryElements(): Array<PsiElement> {
val element = psiElement as KtNamedDeclaration
if (element is KtParameter && !element.hasValOrVar() && factory.findPropertyOptions.isSearchInOverridingMethods) {
val function = element.ownerFunction
if (function != null && function.isOverridable()) {
function.providedToLightMethods().singleOrNull()?.let { method ->
if (OverridingMethodsSearch.search(method).any()) {
val parametersCount = method.parameterList.parametersCount
val parameterIndex = element.parameterIndex()
assert(parameterIndex < parametersCount)
return OverridingMethodsSearch.search(method, true)
.filter { method.parameterList.parametersCount == parametersCount }
.mapNotNull { method.parameterList.parameters[parameterIndex].unwrapped }
.toTypedArray()
}
}
}
} else if (factory.findPropertyOptions.isSearchForBaseAccessors) {
val supers = KotlinFindUsagesSupport.getSuperMethods(element, null)
return if (supers.contains(psiElement)) supers.toTypedArray() else (supers + psiElement).toTypedArray()
}
return super.getPrimaryElements()
}
override fun getFindUsagesOptions(dataContext: DataContext?): FindUsagesOptions = factory.findPropertyOptions
override fun getFindUsagesDialog(
isSingleFile: Boolean,
toShowInNewTab: Boolean,
mustOpenInNewTab: Boolean
): AbstractFindUsagesDialog {
return KotlinFindPropertyUsagesDialog(
getElement(),
project,
factory.findPropertyOptions,
toShowInNewTab,
mustOpenInNewTab,
isSingleFile,
this
)
}
override fun applyQueryFilters(element: PsiElement, options: FindUsagesOptions, query: Query<PsiReference>): Query<PsiReference> {
val kotlinOptions = options as KotlinPropertyFindUsagesOptions
if (!kotlinOptions.isReadAccess && !kotlinOptions.isWriteAccess) {
return EmptyQuery()
}
val result = query.applyFilter(kotlinOptions.isSkipImportStatements) { !it.isImportUsage() }
if (!kotlinOptions.isReadAccess || !kotlinOptions.isWriteAccess) {
val detector = KotlinReadWriteAccessDetector()
return FilteredQuery(result) {
when (detector.getReferenceAccess(element, it)) {
ReadWriteAccessDetector.Access.Read -> kotlinOptions.isReadAccess
ReadWriteAccessDetector.Access.Write -> kotlinOptions.isWriteAccess
ReadWriteAccessDetector.Access.ReadWrite -> kotlinOptions.isReadWriteAccess
}
}
}
return result
}
private fun PsiElement.getDisableComponentAndDestructionSearch(resetSingleFind: Boolean): Boolean {
if (!isPropertyOfDataClass) return false
if (forceDisableComponentAndDestructionSearch) return true
if (KotlinFindPropertyUsagesDialog.getDisableComponentAndDestructionSearch(project)) return true
return if (getUserData(FIND_USAGES_ONES_FOR_DATA_CLASS_KEY) == true) {
if (resetSingleFind) {
putUserData(FIND_USAGES_ONES_FOR_DATA_CLASS_KEY, null)
}
true
} else false
}
override fun createKotlinReferencesSearchOptions(options: FindUsagesOptions, forHighlight: Boolean): KotlinReferencesSearchOptions {
val kotlinOptions = options as KotlinPropertyFindUsagesOptions
val disabledComponentsAndOperatorsSearch =
!forHighlight && psiElement.getDisableComponentAndDestructionSearch(resetSingleFind = true)
return KotlinReferencesSearchOptions(
acceptCallableOverrides = true,
acceptOverloads = false,
acceptExtensionsOfDeclarationClass = false,
searchForExpectedUsages = kotlinOptions.searchExpected,
searchForOperatorConventions = !disabledComponentsAndOperatorsSearch,
searchForComponentConventions = !disabledComponentsAndOperatorsSearch
)
}
}
override fun createSearcher(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions
): Searcher {
return MySearcher(element, processor, options)
}
private inner class MySearcher(
element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions
) : Searcher(element, processor, options) {
private val kotlinOptions = options as KotlinCallableFindUsagesOptions
override fun buildTaskList(forHighlight: Boolean): Boolean {
val referenceProcessor = createReferenceProcessor(processor)
val uniqueProcessor = CommonProcessors.UniqueProcessor(processor)
if (options.isUsages) {
val baseKotlinSearchOptions = createKotlinReferencesSearchOptions(options, forHighlight)
val kotlinSearchOptions = if (element.isPotentiallyOperator()) {
baseKotlinSearchOptions
} else {
baseKotlinSearchOptions.copy(searchForOperatorConventions = false)
}
val searchParameters = KotlinReferencesSearchParameters(element, options.searchScope, kotlinOptions = kotlinSearchOptions)
addTask { applyQueryFilters(element, options, ReferencesSearch.search(searchParameters)).forEach(referenceProcessor) }
if (element is KtElement && !isOnlyKotlinSearch(options.searchScope)) {
// TODO: very bad code!! ReferencesSearch does not work correctly for constructors and annotation parameters
val psiMethodScopeSearch = when {
element is KtParameter && element.isDataClassComponentFunction ->
options.searchScope.excludeKotlinSources()
else -> options.searchScope
}
for (psiMethod in element.providedToLightMethods().filterDataClassComponentsIfDisabled(kotlinSearchOptions)) {
addTask {
val query = MethodReferencesSearch.search(psiMethod, psiMethodScopeSearch, true)
applyQueryFilters(
element,
options,
query
).forEach(referenceProcessor)
}
}
}
}
if (kotlinOptions.searchOverrides) {
addTask {
val overriders = HierarchySearchRequest(element, options.searchScope, true).searchOverriders()
overriders.all {
val element = runReadAction { it.takeIf { it.isValid }?.navigationElement } ?: return@all true
processUsage(uniqueProcessor, element)
}
}
}
return true
}
}
protected abstract fun createKotlinReferencesSearchOptions(
options: FindUsagesOptions,
forHighlight: Boolean
): KotlinReferencesSearchOptions
protected abstract fun applyQueryFilters(
element: PsiElement,
options: FindUsagesOptions,
query: Query<PsiReference>
): Query<PsiReference>
override fun isSearchForTextOccurrencesAvailable(psiElement: PsiElement, isSingleFile: Boolean): Boolean =
!isSingleFile && psiElement !is KtParameter
override fun findReferencesToHighlight(target: PsiElement, searchScope: SearchScope): Collection<PsiReference> {
val baseDeclarations = getTopMostOverriddenElementsToHighlight(target)
return if (baseDeclarations.isNotEmpty()) {
baseDeclarations.flatMap {
val handler = (FindManager.getInstance(project) as FindManagerImpl).findUsagesManager.getFindUsagesHandler(it!!, true)
handler?.findReferencesToHighlight(it, searchScope) ?: emptyList()
}
} else {
super.findReferencesToHighlight(target, searchScope)
}
}
companion object {
@Volatile
@get:TestOnly
var forceDisableComponentAndDestructionSearch = false
private const val DISABLE_ONCE = "DISABLE_ONCE"
private const val DISABLE = "DISABLE"
private val DISABLE_COMPONENT_AND_DESTRUCTION_SEARCH_TEXT
@Nls
get() = KotlinIndependentBundle.message(
"find.usages.text.find.usages.for.data.class.components.and.destruction.declarations",
DISABLE_ONCE,
DISABLE
)
private const val DISABLE_COMPONENT_AND_DESTRUCTION_SEARCH_TIMEOUT = 5000
private val FIND_USAGES_ONES_FOR_DATA_CLASS_KEY = Key<Boolean>("FIND_USAGES_ONES")
private fun scheduleNotificationForDataClassComponent(
project: Project,
element: PsiElement,
indicator: ProgressIndicator
): Disposable {
val notification = {
val listener = HyperlinkListener { event ->
if (event.eventType == HyperlinkEvent.EventType.ACTIVATED) {
indicator.cancel()
if (event.description == DISABLE) {
KotlinFindPropertyUsagesDialog.setDisableComponentAndDestructionSearch(project, /* value = */ true)
} else {
element.putUserData(FIND_USAGES_ONES_FOR_DATA_CLASS_KEY, true)
}
FindManager.getInstance(project).findUsages(element)
}
}
val windowManager = ToolWindowManager.getInstance(project)
windowManager.getToolWindow(ToolWindowId.FIND)?.let { toolWindow ->
windowManager.notifyByBalloon(
toolWindow.id,
MessageType.INFO,
DISABLE_COMPONENT_AND_DESTRUCTION_SEARCH_TEXT,
Actions.Find,
listener
)
}
Unit
}
return Alarm().also {
it.addRequest(notification, DISABLE_COMPONENT_AND_DESTRUCTION_SEARCH_TIMEOUT)
}
}
fun getInstance(
declaration: KtNamedDeclaration,
elementsToSearch: Collection<PsiElement> = emptyList(),
factory: KotlinFindUsagesHandlerFactory
): KotlinFindMemberUsagesHandler<out KtNamedDeclaration> {
return if (declaration is KtFunction)
Function(declaration, elementsToSearch, factory)
else
Property(declaration, elementsToSearch, factory)
}
}
}
fun Query<PsiReference>.applyFilter(flag: Boolean, condition: (PsiReference) -> Boolean): Query<PsiReference> {
return if (flag) FilteredQuery(this, condition) else this
}
| apache-2.0 | 9dc2616b9e534668a0ca80f883248e5e | 45.303178 | 158 | 0.664484 | 6.010156 | false | false | false | false |
smmribeiro/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/ShowStandaloneDiffFromLogActionProvider.kt | 2 | 1227 | // 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.vcs.log.ui.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.AnActionExtensionProvider
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys
class ShowStandaloneDiffFromLogActionProvider : AnActionExtensionProvider {
override fun isActive(e: AnActionEvent): Boolean {
return e.getData(VcsLogInternalDataKeys.MAIN_UI) != null && e.getData(ChangesBrowserBase.DATA_KEY) == null
}
override fun update(e: AnActionEvent) {
val project = e.project
val logUi = e.getData(VcsLogInternalDataKeys.MAIN_UI)
if (project == null || logUi == null) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.isVisible = true
e.presentation.isEnabled = logUi.changesBrowser.canShowDiff()
}
override fun actionPerformed(e: AnActionEvent) {
ChangesBrowserBase.ShowStandaloneDiff.showStandaloneDiff(e.project!!, e.getRequiredData(VcsLogInternalDataKeys.MAIN_UI).changesBrowser)
}
} | apache-2.0 | 4055bb78ed14ba22603772e316b7395f | 42.857143 | 158 | 0.778321 | 4.429603 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/RenameClassToFileNameIntention.kt | 22 | 1500 | /*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package org.jetbrains.plugins.groovy.intentions.conversions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.refactoring.RefactoringFactory
import com.intellij.util.Consumer
import org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle.message
import org.jetbrains.plugins.groovy.intentions.base.Intention
import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate
class RenameClassToFileNameIntention : Intention() {
private lateinit var myFileName: String
override fun getElementPredicate(): PsiElementPredicate = ClassNameDiffersFromFileNamePredicate(
fileNameConsumer = Consumer { fileName ->
myFileName = fileName
}
)
override fun isStopElement(element: PsiElement?): Boolean = true
override fun getText(): String = message("rename.class.to.0", myFileName)
override fun startInWriteAction(): Boolean = false
override fun processIntention(element: PsiElement, project: Project, editor: Editor?) {
var clazz: PsiClass? = null
val predicate = ClassNameDiffersFromFileNamePredicate(classConsumer = Consumer { clazz = it })
if (!predicate.satisfiedBy(element)) return
RefactoringFactory.getInstance(project).createRename(clazz!!, myFileName).run()
}
}
| apache-2.0 | 643b587525cdadcfca5c7b627010a14b | 38.473684 | 140 | 0.790667 | 4.531722 | false | false | false | false |
smmribeiro/intellij-community | java/java-impl/src/com/intellij/lang/java/actions/CreateMethodAction.kt | 11 | 6330 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.java.actions
import com.intellij.codeInsight.CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement
import com.intellij.codeInsight.daemon.QuickFixBundle.message
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.positionCursor
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils.setupEditor
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils.setupMethodBody
import com.intellij.codeInsight.daemon.impl.quickfix.GuessTypeParameters
import com.intellij.codeInsight.template.Template
import com.intellij.codeInsight.template.TemplateBuilder
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.codeInsight.template.TemplateEditingAdapter
import com.intellij.lang.java.request.CreateMethodFromJavaUsageRequest
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.actions.*
import com.intellij.openapi.command.WriteCommandAction.runWriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.presentation.java.ClassPresentationUtil.getNameForClass
import com.intellij.psi.util.JavaElementKind
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil.setModifierProperty
/**
* @param abstract whether this action creates a method with explicit abstract modifier
*/
internal class CreateMethodAction(
targetClass: PsiClass,
override val request: CreateMethodRequest,
private val abstract: Boolean
) : CreateMemberAction(targetClass, request), JvmGroupIntentionAction {
override fun getActionGroup(): JvmActionGroup = if (abstract) CreateAbstractMethodActionGroup else CreateMethodActionGroup
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
return super.isAvailable(project, editor, file) && PsiNameHelper.getInstance(project).isIdentifier(request.methodName)
}
override fun getRenderData() = JvmActionGroup.RenderData { request.methodName }
override fun getFamilyName(): String = message("create.method.from.usage.family")
override fun getText(): String {
val what = request.methodName
val where = getNameForClass(target, false)
val kind = if (abstract) JavaElementKind.ABSTRACT_METHOD else JavaElementKind.METHOD
return message("create.element.in.class", kind.`object`(), what, where)
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
JavaMethodRenderer(project, abstract, target, request).doMagic()
}
}
private class JavaMethodRenderer(
val project: Project,
val abstract: Boolean,
val targetClass: PsiClass,
val request: CreateMethodRequest
) {
val factory = JavaPsiFacade.getElementFactory(project)!!
val requestedModifiers = request.modifiers
val javaUsage = request as? CreateMethodFromJavaUsageRequest
val withoutBody = abstract || targetClass.isInterface && JvmModifier.STATIC !in requestedModifiers
fun doMagic() {
var method = renderMethod()
method = insertMethod(method)
method = forcePsiPostprocessAndRestoreElement(method) ?: return
val builder = setupTemplate(method)
method = forcePsiPostprocessAndRestoreElement(method) ?: return
val template = builder.buildInlineTemplate()
startTemplate(method, template)
}
private fun renderMethod(): PsiMethod {
val method = factory.createMethod(request.methodName, PsiType.VOID)
val modifiersToRender = requestedModifiers.toMutableList()
if (targetClass.isInterface) {
modifiersToRender -= (visibilityModifiers + JvmModifier.ABSTRACT)
}
else if (abstract) {
if (modifiersToRender.remove(JvmModifier.PRIVATE)) {
modifiersToRender += JvmModifier.PROTECTED
}
modifiersToRender += JvmModifier.ABSTRACT
}
for (modifier in modifiersToRender) {
setModifierProperty(method, modifier.toPsiModifier(), true)
}
for (annotation in request.annotations) {
method.modifierList.addAnnotation(annotation.qualifiedName)
}
if (withoutBody) method.body?.delete()
return method
}
private fun insertMethod(method: PsiMethod): PsiMethod {
val anchor = javaUsage?.getAnchor(targetClass)
val inserted = if (anchor == null) {
targetClass.add(method)
}
else {
targetClass.addAfter(method, anchor)
}
return inserted as PsiMethod
}
private fun setupTemplate(method: PsiMethod): TemplateBuilderImpl {
val builder = TemplateBuilderImpl(method)
createTemplateContext(builder).run {
setupTypeElement(method.returnTypeElement, request.returnType)
setupParameters(method, request.expectedParameters)
}
builder.setEndVariableAfter(method.body ?: method)
return builder
}
private fun createTemplateContext(builder: TemplateBuilder): TemplateContext {
val substitutor = request.targetSubstitutor.toPsiSubstitutor(project)
val guesser = GuessTypeParameters(project, factory, builder, substitutor)
return TemplateContext(project, factory, targetClass, builder, guesser, javaUsage?.context)
}
private fun startTemplate(method: PsiMethod, template: Template) {
val targetFile = targetClass.containingFile
val newEditor = positionCursor(project, targetFile, method) ?: return
val templateListener = if (withoutBody) null else MyMethodBodyListener(project, newEditor, targetFile)
CreateFromUsageBaseFix.startTemplate(newEditor, template, project, templateListener, null)
}
}
private class MyMethodBodyListener(val project: Project, val editor: Editor, val file: PsiFile) : TemplateEditingAdapter() {
override fun templateFinished(template: Template, brokenOff: Boolean) {
if (brokenOff) return
runWriteCommandAction(project) {
PsiDocumentManager.getInstance(project).commitDocument(editor.document)
val offset = editor.caretModel.offset
PsiTreeUtil.findElementOfClassAtOffset(file, offset - 1, PsiMethod::class.java, false)?.let { method ->
setupMethodBody(method)
setupEditor(method, editor)
}
}
}
}
| apache-2.0 | 19be4ac250f61759f63ab6b0d01cc5e4 | 39.83871 | 140 | 0.777093 | 4.843152 | false | false | false | false |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/ui/appdetail/page/activity/AppActivityDetailListAdapter.kt | 1 | 5981 | package sk.styk.martin.apkanalyzer.ui.appdetail.page.activity
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.LiveData
import androidx.recyclerview.widget.DiffUtil
import sk.styk.martin.apkanalyzer.R
import sk.styk.martin.apkanalyzer.databinding.ListItemActivityDetailBinding
import sk.styk.martin.apkanalyzer.databinding.ListItemActivityDetailExpandedBinding
import sk.styk.martin.apkanalyzer.model.detail.ActivityData
import sk.styk.martin.apkanalyzer.ui.appdetail.adapters.DetailInfoAdapter
import sk.styk.martin.apkanalyzer.ui.appdetail.page.DetailInfoDescriptionAdapter
import sk.styk.martin.apkanalyzer.ui.appdetail.recycler.ExpandableItemViewModel
import sk.styk.martin.apkanalyzer.ui.appdetail.recycler.LazyExpandableViewHolder
import sk.styk.martin.apkanalyzer.util.TextInfo
import sk.styk.martin.apkanalyzer.util.live.SingleLiveEvent
import javax.inject.Inject
const val ARROW_ANIMATION_DURATION = 500L
const val ROTATION_STANDARD = 0f
const val ROTATION_FLIPPED = 180f
class AppActivityDetailListAdapter @Inject constructor() : DetailInfoDescriptionAdapter<AppActivityDetailListAdapter.ViewHolder>() {
data class ExpandedActivityData(val activityData: ActivityData, val expanded: Boolean)
private val runActivityEvent = SingleLiveEvent<ActivityData>()
val runActivity: LiveData<ActivityData> = runActivityEvent
private val activityUpdateEvent = SingleLiveEvent<ExpandedActivityData>()
val activityUpdate: LiveData<ExpandedActivityData> = activityUpdateEvent
var items = emptyList<ExpandedActivityData>()
set(value) {
val diffResult = DiffUtil.calculateDiff(ActivityDiffCallback(value, field))
field = value
diffResult.dispatchUpdatesTo(this)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemBinding = ListItemActivityDetailBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(itemBinding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(ActivityDataViewModel(items[position]))
override fun getItemCount() = items.size
inner class ActivityDataViewModel(private val expandedActivityData: ExpandedActivityData) : ExpandableItemViewModel {
val name = expandedActivityData.activityData.name.substring(expandedActivityData.activityData.name.lastIndexOf(".") + 1)
val packageName = expandedActivityData.activityData.name.substring(0, expandedActivityData.activityData.name.lastIndexOf("."))
override val expanded = expandedActivityData.expanded
val labelDetailItemInfo = DetailInfoAdapter.DetailInfo(
name = TextInfo.from(R.string.activity_label),
value = if (expandedActivityData.activityData.label != null) TextInfo.from(expandedActivityData.activityData.label) else TextInfo.from(R.string.NA),
description = TextInfo.from(R.string.activity_label_description)
)
val parentDetailItemInfo = DetailInfoAdapter.DetailInfo(
name = TextInfo.from(R.string.activity_parent),
value = if (expandedActivityData.activityData.parentName != null) TextInfo.from(expandedActivityData.activityData.parentName) else TextInfo.from(R.string.NA),
description = TextInfo.from(R.string.activity_parent_description)
)
val permissionDetailItemInfo = DetailInfoAdapter.DetailInfo(
name = TextInfo.from(R.string.activity_permission),
value = if (expandedActivityData.activityData.permission != null) TextInfo.from(expandedActivityData.activityData.permission) else TextInfo.from(R.string.NA),
description = TextInfo.from(R.string.activity_permission_description)
)
val runButtonVisible = expandedActivityData.activityData.isExported
fun onDetailClick(detailInfo: DetailInfoAdapter.DetailInfo) {
openDescriptionEvent.value = Description.from(detailInfo)
}
fun onLongClick(detailInfo: DetailInfoAdapter.DetailInfo): Boolean {
copyToClipboardEvent.value = CopyToClipboard.from(detailInfo)
return true
}
fun onTitleLongClick() : Boolean {
copyToClipboardEvent.value = CopyToClipboard(TextInfo.from(expandedActivityData.activityData.name))
return true
}
fun onRunClick() {
runActivityEvent.value = expandedActivityData.activityData
}
override fun toggleExpanded(newlyExpanded: Boolean) {
activityUpdateEvent.value = expandedActivityData.copy(expanded = newlyExpanded)
}
}
inner class ViewHolder(binding: ListItemActivityDetailBinding) :
LazyExpandableViewHolder<ListItemActivityDetailBinding, ListItemActivityDetailExpandedBinding, ActivityDataViewModel>(binding) {
override fun baseContainer() = baseBinding.container
override fun expandedInflation() = ListItemActivityDetailExpandedBinding.inflate(LayoutInflater.from(baseBinding.root.context))
override fun expandableContainer() = expandedBinding.expandableContainer
override fun toggleArrow() = baseBinding.toggleArrow
override fun headerContainer() = baseBinding.headerContainer
}
private inner class ActivityDiffCallback(private val newList: List<ExpandedActivityData>,
private val oldList: List<ExpandedActivityData>) : DiffUtil.Callback() {
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) = oldList[oldItemPosition].activityData == newList[newItemPosition].activityData
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) = oldList[oldItemPosition] == newList[newItemPosition]
}
} | gpl-3.0 | 7d0bb50f5fdd4019e93131462c5fca11 | 48.032787 | 174 | 0.749373 | 4.93075 | false | false | false | false |
WYKCode/WYK-Android | app/src/main/java/college/wyk/app/model/directus/Directus.kt | 1 | 1682 | package college.wyk.app.model.directus
import college.wyk.app.R
import college.wyk.app.WykApplication
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
object Directus {
val baseUrl = "http://wyk.tigerhix.me"
val api: DirectusApi
val key: String by lazy { WykApplication.instance.resources.getString(R.string.directus_key) }
init {
val httpClient = OkHttpClient.Builder()
.addInterceptor {
chain ->
val original = chain.request()
// add request headers: authorization
val requestBuilder = original.newBuilder()
.header("Authorization", "Bearer " + key)
.method(original.method(), original.body())
chain.proceed(requestBuilder.build())
}
.build()
val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(MoshiConverterFactory.create())
.client(httpClient)
.build()
api = retrofit.create(DirectusApi::class.java)
}
fun getFeed(perPage: Int, currentPage: Int): Call<DirectusPostRoot> {
return api.getFeed(active = 1, sortBy = "date", sortOrder = "DESC", perPage = perPage, currentPage = currentPage)
}
fun getPublications(): Call<PublicationRoot> {
return api.getPublications(active = 1, sortBy = "date", sortOrder = "DESC")
}
fun mediaUrl(filename: String): String {
return baseUrl + "/storage/uploads/" + filename
}
} | mit | e9544588a8b07400b715ea3886a820dc | 33.346939 | 121 | 0.602259 | 4.724719 | false | false | false | false |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/project/petal/Model/BoardPinsInfo.kt | 1 | 1019 | package stan.androiddemo.project.petal.Model
/**
* Created by hugfo on 2017/8/12.
*/
class BoardPinsInfo{
var board_id: Int = 0
var user_id: Int = 0
var title: String? = null
var description: String? = null
var category_id: String? = null
var seq: Int = 0
var pin_count: Int = 0
var follow_count: Int = 0
var like_count: Int = 0
var created_at: Int = 0
var updated_at: Int = 0
var deleting: Int = 0
var is_private: Int = 0
var extra: ExtraBean? = null
var cover: ExtraBean.CoverBean? = null
var user: UserBean? = null
var following: Boolean = false
var pins: List<PinsSimpleInfo>? = null
class ExtraBean {
var cover: CoverBean? = null
class CoverBean {
var pin_id: String? = null
}
}
class UserBean {
var user_id: Int = 0
var username: String? = null
var urlname: String? = null
var created_at: Int = 0
var avatar: String? = null
}
} | mit | e1a26620fd09233b199eb4c545e1a787 | 25.153846 | 44 | 0.575074 | 3.639286 | false | false | false | false |
nischalbasnet/kotlin-android-tictactoe | app/src/main/java/com/nbasnet/tictactoe/models/Player.kt | 1 | 7005 | package com.nbasnet.tictactoe.models
import android.content.res.Resources
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.support.v4.content.res.ResourcesCompat
import android.util.Log
import com.nbasnet.tictactoe.ai.IPlayGameAI
import com.nbasnet.tictactoe.controllers.TicTacToeGameController
data class Player(
val name: String,
val symbolResource: Int,
val color: Int,
val aIController: IPlayGameAI? = null
) {
val maxRow: Int = 3
val isAI: Boolean = aIController != null
private val _selectedAreas = mutableListOf<PlayAreaInfo>()
var isWinner = false
private set
private val _scoreMap = hashMapOf<String, Int>()
private val LOG_TAG = "Player"
/**
* Get the draw symbol for the player
* Always returns a new drawable
*/
fun getDrawableSymbol(resources: Resources, theme: Resources.Theme): Drawable? {
val drawable: Drawable? = ResourcesCompat.getDrawable(resources, symbolResource, theme)
drawable?.setColorFilter(
resources.getColor(color),
PorterDuff.Mode.SRC_IN
)
return drawable
}
/**
* Check and return if the area is selected by user
*/
fun isSelected(areaInfo: PlayAreaInfo): Boolean = _selectedAreas.contains(areaInfo)
/**
* Set the selected area for user and perform calculation for win
*/
fun setSelectedArea(selectArea: PlayAreaInfo, gameController: TicTacToeGameController): Player {
_selectedAreas.add(selectArea)
_scoreMap["rowx${selectArea.row}"] = (_scoreMap["rowx${selectArea.row}"] ?: 0) + 1
isWinner = checkForWinner(_scoreMap["rowx${selectArea.row}"] ?: 0)
_scoreMap["colx${selectArea.column}"] = (_scoreMap["colx${selectArea.column}"] ?: 0) + 1
isWinner = checkForWinner(_scoreMap["colx${selectArea.column}"] ?: 0)
if (!isWinner && selectArea.isDiagonal) {
if (selectArea.row == selectArea.column) {
//is a back diagonal
_scoreMap["backD"] = (_scoreMap["backD"] ?: 0) + 1
isWinner = checkForWinner(_scoreMap["backD"] ?: 0)
}
//check for front diagonal
if (gameController.frontDiagonalRows.contains(PlayAreaInfo(selectArea.row, selectArea.column))) {
//is a front diagonal point
_scoreMap["forwardD"] = (_scoreMap["forwardD"] ?: 0) + 1
isWinner = checkForWinner(_scoreMap["forwardD"] ?: 0)
}
}
if (isWinner) Log.v(LOG_TAG, "$name won the game ${_selectedAreas.toString()}")
return this
}
/**
* Return the winning row or column or diagonal
*/
fun winningRow(): FullRegionInfo {
var returnRegionInfo = FullRegionInfo(0, RegionType.NONE)
for ((regionInfo, score) in _scoreMap) {
if (score > maxRow - 1) {
returnRegionInfo = FullRegionInfo.getFromPlayerScoreMap(regionInfo)
}
}
return returnRegionInfo
}
/**
* Check if the player has won
*/
private fun checkForWinner(value: Int): Boolean {
return if (isWinner) isWinner else value > maxRow - 1
}
/**
* Get the winning areas for player
*/
fun getWinningAreas(gameController: TicTacToeGameController): List<PlayAreaInfo> {
val winningRegion = mutableListOf<PlayAreaInfo>()
val rowColSeq = 1..maxRow
for ((regionInfo, score) in _scoreMap) {
if (score == maxRow - 1) {
//this region has winning area get the winning point now
val fullRegionInfo = FullRegionInfo.getFromPlayerScoreMap(regionInfo)
if (fullRegionInfo.regionType == RegionType.COL) {
val winCol = fullRegionInfo.rowCol
val selectedRows: List<Int> = _selectedAreas
.filter { it.column == winCol }
.map { it.row }
val winRow: Int? = rowColSeq.subtract(selectedRows).firstOrNull()
//add if winning row is present
if (winRow != null) {
val playArea = PlayAreaInfo(winRow, winCol)
if (gameController.isAreaPlayable(playArea)) winningRegion.add(playArea)
}
} else if (fullRegionInfo.regionType == RegionType.ROW) {
val winRow = fullRegionInfo.rowCol
val selectedCols: List<Int> = _selectedAreas
.filter { it.row == winRow }
.map { it.column }
val winCol: Int? = rowColSeq.subtract(selectedCols).firstOrNull()
//add if winning col is present
if (winCol != null) {
val playArea = PlayAreaInfo(winRow, winCol)
if (gameController.isAreaPlayable(playArea)) winningRegion.add(playArea)
}
} else if (fullRegionInfo.regionType == RegionType.BACK_DIAGONAL) {
val selectedRows = _selectedAreas
.filter { it.row == it.column }
.map { it.row }
val winRowCol: Int? = rowColSeq.subtract(selectedRows).firstOrNull()
//add if winning col is present
if (winRowCol != null) {
val playArea = PlayAreaInfo(winRowCol, winRowCol)
if (gameController.isAreaPlayable(playArea)) winningRegion.add(playArea)
}
} else if (fullRegionInfo.regionType == RegionType.FORWARD_DIAGONAL) {
//TODO implement this
val selectRegions = gameController.frontDiagonalRows.subtract(_selectedAreas)
.filter { gameController.isAreaPlayable(it) }
winningRegion.addAll(selectRegions)
}
}
}
return winningRegion
}
}
data class FullRegionInfo(val rowCol: Int, val regionType: RegionType) {
companion object {
fun getFromPlayerScoreMap(scoreKey: String): FullRegionInfo {
val region: RegionType
val rowCol: Int
if (scoreKey == "forwardD") {
region = RegionType.FORWARD_DIAGONAL
rowCol = 0
} else if (scoreKey == "backD") {
region = RegionType.BACK_DIAGONAL
rowCol = 0
} else {
val regionContents = scoreKey.split("x")
region = if (regionContents.first() == "row") RegionType.ROW else RegionType.COL
rowCol = regionContents.last().toInt()
}
return FullRegionInfo(rowCol, region)
}
}
}
enum class RegionType {
COL, ROW, FORWARD_DIAGONAL, BACK_DIAGONAL, NONE
} | mit | 01b4b2f85cfd5f2c342f0749d50615ef | 38.139665 | 109 | 0.570735 | 4.39185 | false | false | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/ui/txdetails/TxDetailsUpdate.kt | 1 | 7825 | /**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 9/17/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.txdetails
import android.util.Base64
import com.breadwallet.breadbox.defaultUnit
import com.breadwallet.breadbox.feeForToken
import com.breadwallet.breadbox.isErc20
import com.breadwallet.breadbox.isEthereum
import com.breadwallet.breadbox.isReceived
import com.breadwallet.breadbox.toBigDecimal
import com.breadwallet.breadbox.toSanitizedString
import com.breadwallet.ui.models.TransactionState
import com.breadwallet.ui.send.TransferField
import com.breadwallet.ui.txdetails.TxDetails.E
import com.breadwallet.ui.txdetails.TxDetails.F
import com.breadwallet.ui.txdetails.TxDetails.M
import com.breadwallet.util.isBitcoinLike
import com.breadwallet.platform.entities.TxMetaDataEmpty
import com.breadwallet.platform.entities.TxMetaDataValue
import com.breadwallet.tools.util.GIFT_BASE_URL
import com.spotify.mobius.Next
import com.spotify.mobius.Next.dispatch
import com.spotify.mobius.Next.next
import com.spotify.mobius.Next.noChange
import com.spotify.mobius.Update
import java.util.Date
const val MAX_CRYPTO_DIGITS = 8
private const val DELEGATE = "Delegate"
object TxDetailsUpdate : Update<M, E, F>, TxDetailsUpdateSpec {
override fun update(
model: M,
event: E
): Next<M, F> = patch(model, event)
override fun onTransactionUpdated(
model: M,
event: E.OnTransactionUpdated
): Next<M, F> {
val updatedModel = with(event.transaction) {
val confirmations = confirmations.orNull()?.toInt() ?: 0
val confirmationsUntilFinal =
wallet.walletManager.network.confirmationsUntilFinal.toInt()
val delegateAddr = attributes.find { it.key.equals(DELEGATE, true) }?.value?.orNull()
model.copy(
isEth = amount.currency.isEthereum(),
isErc20 = amount.currency.isErc20(),
cryptoTransferredAmount = amount.toBigDecimal(wallet.defaultUnit),
fee = fee.toBigDecimal(wallet.defaultUnit),
feeCurrency = fee.currency.code,
isReceived = isReceived(),
blockNumber = confirmation.orNull()?.blockNumber?.toInt() ?: 0,
toOrFromAddress = when {
isReceived() && !model.currencyCode.isBitcoinLike() -> source.orNull()?.toSanitizedString()
delegateAddr != null -> delegateAddr
else -> target.orNull()?.toSanitizedString()
} ?: "",
confirmationDate = confirmation
.transform { it?.confirmationTime }
.or { Date() },
confirmedInBlockNumber = confirmation
.transform { it?.blockNumber?.toString() }
.or(""),
transactionState = TransactionState.valueOf(state),
isCompleted = confirmations >= confirmationsUntilFinal,
gasPrice = event.gasPrice,
gasLimit = event.gasLimit,
feeToken = feeForToken(),
confirmations = confirmations,
transferFields = event.transaction
.attributes
.map { attribute ->
TransferField(
key = attribute.key,
required = attribute.isRequired,
invalid = false,
value = attribute.value.orNull()
)
}
)
}
return next(
updatedModel,
setOf(
F.LoadFiatAmountNow(
updatedModel.cryptoTransferredAmount,
updatedModel.currencyCode,
updatedModel.preferredFiatIso
)
)
)
}
override fun onFiatAmountNowUpdated(
model: M,
event: E.OnFiatAmountNowUpdated
): Next<M, F> =
next(
model.copy(
fiatAmountNow = event.fiatAmountNow
)
)
override fun onMetaDataUpdated(
model: M,
event: E.OnMetaDataUpdated
): Next<M, F> =
when (event.metaData) {
is TxMetaDataValue -> {
next(
model.copy(
memo = event.metaData.comment ?: "",
memoLoaded = true,
exchangeCurrencyCode = event.metaData.exchangeCurrency ?: "",
exchangeRate = event.metaData.exchangeRate.toBigDecimal(),
gift = event.metaData.gift
)
)
}
is TxMetaDataEmpty -> next(
model.copy(
memo = "",
memoLoaded = true
)
)
}
override fun onMemoChanged(
model: M,
event: E.OnMemoChanged
): Next<M, F> {
return when {
model.memoLoaded -> dispatch(
setOf(
F.UpdateMemo(
model.currencyCode,
model.transactionHash,
event.memo
)
)
)
else -> noChange()
}
}
override fun onClosedClicked(model: M): Next<M, F> =
dispatch(setOf(F.Close))
override fun onShowHideDetailsClicked(
model: M
): Next<M, F> = next(
model.copy(
showDetails = !model.showDetails
)
)
override fun onAddressClicked(model: M): Next<M, F> =
dispatch(setOf(F.CopyToClipboard(model.toOrFromAddress)))
override fun onTransactionHashClicked(model: M): Next<M, F> =
dispatch(setOf(F.CopyToClipboard(model.transactionHash)))
override fun onGiftResendClicked(model: M): Next<M, F> {
val gift = model.gift!!
val key = gift.keyData!!.toByteArray()
val encodedPrivateKey = Base64.encode(key, Base64.NO_PADDING).toString(Charsets.UTF_8)
val giftUrl = "$GIFT_BASE_URL$encodedPrivateKey"
return dispatch(
setOf(
F.ShareGift(
giftUrl,
model.transactionHash,
gift.recipientName!!,
model.cryptoTransferredAmount,
model.fiatAmountNow,
model.exchangeRate
)
)
)
}
override fun onGiftReclaimClicked(model: M): Next<M, F> =
dispatch(setOf(F.ImportGift(model.gift!!.keyData!!, model.transactionHash)))
}
| mit | e5d4b7b21e69c0532296c8d73b5ba73c | 36.261905 | 111 | 0.585176 | 4.857232 | false | false | false | false |
koma-im/koma | src/main/kotlin/koma/gui/element/control/inputmap/KInputMap.kt | 1 | 13685 | package koma.gui.element.control.inputmap
import javafx.beans.property.ReadOnlyObjectWrapper
import javafx.beans.property.SimpleObjectProperty
import javafx.collections.FXCollections
import javafx.collections.ListChangeListener
import javafx.collections.ObservableList
import javafx.event.Event
import javafx.event.EventHandler
import javafx.event.EventType
import javafx.scene.Node
import javafx.scene.input.KeyEvent
import javafx.scene.input.MouseEvent
import koma.gui.element.control.inputmap.mapping.KeyMapping
import koma.gui.element.control.inputmap.mapping.Mapping
import java.util.*
import java.util.function.Predicate
import kotlin.collections.HashMap
sealed class MappingType(val _mapping: Mapping<out Event>) {
class Any private constructor(val mapping: Mapping<Event>): MappingType(mapping)
class Key(val mapping: Mapping<KeyEvent>): MappingType(mapping)
class Mouse(val mapping: Mapping<MouseEvent>): MappingType(mapping)
val eventType: EventType<out Event>
get() = when(this) {
is Any -> this.mapping.eventType!!
is Key -> this.mapping.eventType!!
is Mouse -> this.mapping.eventType!!
}
val isDisabled
get() = when(this) {
is Any -> this.mapping.isDisabled
is Key -> this.mapping.isDisabled
is Mouse -> this.mapping.isDisabled
}
val mappingKey
get() = this._mapping.mappingKey
val isAutoConsume
get() = this._mapping.isAutoConsume
fun handleEvent(ev: Event) {
if (ev is KeyEvent && this is Key) {
this.mapping.eventHandler.handle(ev)
} else if (ev is MouseEvent && this is Mouse) {
this.mapping.eventHandler.handle(ev)
} else if (this is Any){
this.mapping.eventHandler.handle(ev)
} else {
System.err.println("Event $ev not handled in MappingType")
}
}
fun testInterceptor(event: Event): Boolean? {
if (event is KeyEvent && this is Key) {
return this.mapping.testInterceptor(event)
} else if (event is MouseEvent && this is Mouse) {
return this.mapping.testInterceptor(event)
}
if (this is MappingType.Any) {
return this.mapping.testInterceptor(event)
}
return null
}
fun getSpecificity(event: Event): Int {
if (event is KeyEvent && this is Key) {
return this.mapping.getSpecificity(event)
} else if (event is MouseEvent && this is Mouse) {
return this.mapping.getSpecificity(event)
}
if (this is MappingType.Any) {
return this.mapping.getSpecificity(event)
}
return -1
}
}
class KInputMap<N: Node>(private val node: Node): EventHandler<Event> {
val mappings: ObservableList<MappingType> = FXCollections.observableArrayList()
private val eventTypeMappings = HashMap<EventType<out Event>, MutableList<MappingType>>()
private val installedEventHandlers = HashMap<EventType<*>, MutableList<EventHandler<in Event>>>()
val childInputMaps: ObservableList<KInputMap<N>> = FXCollections.observableArrayList<KInputMap<N>>()
fun addKeyMappings(ms: List<KeyMapping>) {
val m = ms.map { MappingType.Key(it) }
this.mappings.addAll(m)
}
private val _parentInputMap = object :ReadOnlyObjectWrapper<KInputMap<N>>(this, "parentInputMap") {
override fun invalidated() {
// whenever the parent InputMap changes, we uninstall all mappings and
// then reprocess them so that they are installed in the correct root.
reprocessAllMappings()
}
}
private var parentInputMap
get() = _parentInputMap.get()
set(value) = _parentInputMap.set(value)
private val interceptorProperty = SimpleObjectProperty<Predicate<Event>>(this, "interceptor")
var interceptor: Predicate<Event>?
get() = interceptorProperty.get()
set(value) = interceptorProperty.set(value)
init {
mappings.addListener(ListChangeListener<MappingType> { c -> processMappingsChange(c) })
childInputMaps.addListener(object: ListChangeListener<KInputMap<N>> {
override fun onChanged(c: ListChangeListener.Change<out KInputMap<N>>) {
processChildMapsChange(c)
}
})
}
private fun processChildMapsChange(c: ListChangeListener.Change<out KInputMap<N>>) {
while (c.next()) {
if (c.wasRemoved()) {
for (map in c.removed) {
map.parentInputMap = null
}
}
if (c.wasAdded()) {
val toRemove = mutableListOf<KInputMap<N>>()
for (map in c.addedSubList) {
// we check that the child input map maps to the same node
// as this input map
if (map.node !== node) {
toRemove.add(map)
} else {
map.parentInputMap = this
}
}
if (!toRemove.isEmpty()) {
childInputMaps.removeAll(toRemove)
throw IllegalArgumentException("Child InputMap intances need to share a common Node object")
}
}
}
}
private fun processMappingsChange(c: ListChangeListener.Change<out MappingType>) {
while (c.next()) {
// TODO handle mapping removal
if (c.wasRemoved()) {
for (mapping in c.getRemoved()) {
removeMapping(mapping)
}
}
if (c.wasAdded()) {
val toRemove = mutableListOf<MappingType?>()
for (mapping in c.getAddedSubList()) {
if (mapping == null) {
toRemove.add(null)
} else {
addMapping(mapping)
}
}
if (!toRemove.isEmpty()) {
mappings.removeAll(toRemove)
throw IllegalArgumentException("Null mappings not permitted")
}
}
}}
/**
* Invoked when a specific event of the type for which this handler is
* registered happens.
*
* @param event the event which occurred
*/
override fun handle(e: Event?) {
if (e == null || e.isConsumed) return
val mappings = lookup(e, true)
for (mapping in mappings) {
mapping.handleEvent(e)
if (mapping.isAutoConsume) {
e.consume()
}
if (e.isConsumed()) {
break
}
// If we are here, the event has not been consumed, so we continue
// looping through our list of matches. Refer to the documentation in
// lookup(Event) for more details on the list ordering.
}
}
private fun removeMapping(mapping: MappingType) {
val et: EventType<out Event> = mapping.eventType
this.eventTypeMappings.get(et)?.remove(mapping)
}
private fun addMapping(mapping: MappingType) {
val rootInputMap = getRootInputMap();
rootInputMap.addEventHandler(mapping.eventType)
// we maintain a separate map of all mappings, which maps from the
// mapping event type into a list of mappings. This allows for easier
// iteration in the lookup methods.
val et: EventType<out Event>? = mapping.eventType
val ms = this.eventTypeMappings.computeIfAbsent(et!!) { mutableListOf() }
ms.add(mapping)
}
private fun getRootInputMap(): KInputMap<N> {
var rootInputMap: KInputMap<N> = this
while (true) {
val parentInputMap = rootInputMap.parentInputMap ?: break
rootInputMap = parentInputMap
}
return rootInputMap
}
private fun addEventHandler(et: EventType<out Event>) {
val eventHandlers = installedEventHandlers.computeIfAbsent(et) { _ -> mutableListOf() }
val eventHandler = EventHandler<Event> { this.handle(it) }
if (eventHandlers.isEmpty()) {
//println("Added event handler for type $et")
node.addEventHandler(et, eventHandler)
}
// We need to store these event handlers so we can dispose cleanly.
eventHandlers.add(eventHandler)
}
private fun removeAllEventHandlers() {
for ((et, handlers) in installedEventHandlers.entries) {
for (handler in handlers) {
//println("Removed event handler for type $et");
node.removeEventHandler(et, handler)
}
}
}
private fun reprocessAllMappings() {
removeAllEventHandlers()
this.mappings.forEach { this.addMapping(it) }
// now do the same for all children
for (child in childInputMaps) {
child.reprocessAllMappings()
}
}
fun dispose() {
for (childInputMap in childInputMaps) {
childInputMap.dispose()
}
// uninstall event handlers
removeAllEventHandlers()
// clear out all mappings
mappings.clear()
}
private fun lookupMappingAndSpecificity(
event: Event, minSpecificity: Int
): List<Pair<Int, MappingType>> {
var _minSpecificity = minSpecificity
val mappings = this.eventTypeMappings.getOrDefault(event.eventType, mutableListOf())
val result = mutableListOf<Pair<Int, MappingType>>()
for (mapping in mappings) {
if (mapping.isDisabled) continue
// test if mapping has an interceptor that will block this event.
// Interceptors return true if the interception should occur.
val interceptorsApplies = mapping.testInterceptor(event)
if (interceptorsApplies == true) {
continue
}
val specificity = mapping.getSpecificity(event)
if (specificity > 0 && specificity == _minSpecificity) {
result.add(Pair(specificity, mapping))
} else if (specificity > _minSpecificity) {
result.clear()
result.add(Pair(specificity, mapping))
_minSpecificity = specificity
}
}
return result
}
private fun lookup(event: Event, testInterceptors: Boolean): List<MappingType> {
// firstly we look at ourselves to see if we have a mapping, assuming our
// interceptors are valid
if (testInterceptors) {
val interceptorsApplies = interceptor?.test(event)
if (interceptorsApplies == true) {
return listOf()
}
}
val mappings = mutableListOf<MappingType>()
var minSpecificity = 0
val results = lookupMappingAndSpecificity(event, minSpecificity)
if (!results.isEmpty()) {
minSpecificity = results[0].first
mappings.addAll( results.map { it.second } )
}
// but we always descend into our child input maps as well, to see if there
// is a more specific mapping there. If there is a mapping of equal
// specificity, we take the child mapping over the parent mapping.
for (childInputMap in childInputMaps) {
minSpecificity = scanRecursively(childInputMap, event, testInterceptors, minSpecificity,
mappings)
}
return mappings
}
private fun scanRecursively(inputMap: KInputMap<*>, event: Event, testInterceptors: Boolean, minSpecificity: Int,
mappings: MutableList<MappingType>): Int {
var minSpecificity1 = minSpecificity
// test if the childInputMap should be considered
if (testInterceptors) {
val interceptorsApplies = inputMap.interceptor?.test(event)
if (interceptorsApplies == true) {
return minSpecificity1
}
}
// look at the given InputMap
val childResults = inputMap.lookupMappingAndSpecificity(event, minSpecificity1)
if (!childResults.isEmpty()) {
val specificity = childResults[0].first
val childMappings = childResults.map { pair -> pair.second }
if (specificity == minSpecificity1) {
mappings.addAll(0, childMappings)
} else if (specificity > minSpecificity1) {
mappings.clear()
minSpecificity1 = specificity
mappings.addAll(childMappings)
}
}
// now look at the children of this input map, if any exist
for (i in 0 until inputMap.childInputMaps.size) {
minSpecificity1 = scanRecursively(inputMap.childInputMaps[i], event, testInterceptors, minSpecificity1, mappings)
}
return minSpecificity1
}
private fun lookupMappingKey(mappingKey: Any): List<MappingType> {
return mappings
.filter { !it.isDisabled }
.filter { it.mappingKey == mappingKey }
}
fun lookupMapping(mappingKey: Any?): Optional<MappingType> {
if (mappingKey == null) {
return Optional.empty()
}
val mappings = lookupMappingKey(mappingKey).toMutableList()
// descend into our child input maps as well
for (childInputMap in childInputMaps) {
val childMappings = childInputMap.lookupMappingKey(mappingKey)
mappings.addAll(0, childMappings)
}
return if (mappings.size > 0) Optional.of(mappings[0]) else Optional.empty()
}
}
| gpl-3.0 | b5e8a15b2d053df59efb1e103d9dd991 | 34.73107 | 125 | 0.602631 | 4.810193 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/listener/RPKBukkitCharacterDeleteListener.kt | 1 | 2655 | /*
* Copyright 2019 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.professions.bukkit.listener
import com.rpkit.characters.bukkit.event.character.RPKBukkitCharacterDeleteEvent
import com.rpkit.professions.bukkit.RPKProfessionsBukkit
import com.rpkit.professions.bukkit.database.table.RPKCharacterProfessionChangeCooldownTable
import com.rpkit.professions.bukkit.database.table.RPKCharacterProfessionExperienceTable
import com.rpkit.professions.bukkit.database.table.RPKCharacterProfessionTable
import com.rpkit.professions.bukkit.database.table.RPKProfessionHiddenTable
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
class RPKBukkitCharacterDeleteListener(private val plugin: RPKProfessionsBukkit): Listener {
@EventHandler
fun onCharacterDelete(event: RPKBukkitCharacterDeleteEvent) {
val characterProfessionChangeCooldownTable = plugin.core.database.getTable(RPKCharacterProfessionChangeCooldownTable::class)
val characterProfessionChangeCooldown = characterProfessionChangeCooldownTable.get(event.character)
if (characterProfessionChangeCooldown != null) {
characterProfessionChangeCooldownTable.delete(characterProfessionChangeCooldown)
}
val characterProfessionExperienceTable = plugin.core.database.getTable(RPKCharacterProfessionExperienceTable::class)
characterProfessionExperienceTable.get(event.character).forEach { characterProfessionExperience ->
characterProfessionExperienceTable.delete(characterProfessionExperience)
}
val characterProfessionTable = plugin.core.database.getTable(RPKCharacterProfessionTable::class)
characterProfessionTable.get(event.character).forEach { characterProfession ->
characterProfessionTable.delete(characterProfession)
}
val professionHiddenTable = plugin.core.database.getTable(RPKProfessionHiddenTable::class)
val professionHidden = professionHiddenTable.get(event.character)
if (professionHidden != null) {
professionHiddenTable.delete(professionHidden)
}
}
} | apache-2.0 | b6febbe1c6055699295fd4aa22d95ada | 46.428571 | 132 | 0.789831 | 4.981238 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/korau/format/atrac3plus/util/Atrac3PlusUtil.kt | 1 | 8071 | package com.soywiz.korau.format.atrac3plus.util
import com.soywiz.klogger.Logger
import com.soywiz.kmem.extract8
import com.soywiz.korio.lang.format
import com.soywiz.korio.stream.SyncStream
import com.soywiz.korio.stream.readS32_le
import com.soywiz.korio.stream.readU16_le
import com.soywiz.korio.stream.readU8
/**
* From JPCSP
*/
object Atrac3PlusUtil {
val log = Logger("Atrac3PlusUtil")
val AT3_MAGIC = 0x0270 // "AT3"
val AT3_PLUS_MAGIC = 0xFFFE // "AT3PLUS"
val RIFF_MAGIC = 0x46464952 // "RIFF"
val WAVE_MAGIC = 0x45564157 // "WAVE"
val FMT_CHUNK_MAGIC = 0x20746D66 // "FMT "
val FACT_CHUNK_MAGIC = 0x74636166 // "FACT"
val SMPL_CHUNK_MAGIC = 0x6C706D73 // "SMPL"
val DATA_CHUNK_MAGIC = 0x61746164 // "DATA"
val ATRAC3_CONTEXT_READ_SIZE_OFFSET = 160
val ATRAC3_CONTEXT_REQUIRED_SIZE_OFFSET = 164
val ATRAC3_CONTEXT_DECODE_RESULT_OFFSET = 188
val PSP_ATRAC_ALLDATA_IS_ON_MEMORY = -1
val PSP_ATRAC_NONLOOP_STREAM_DATA_IS_ON_MEMORY = -2
val PSP_ATRAC_LOOP_STREAM_DATA_IS_ON_MEMORY = -3
val PSP_ATRAC_STATUS_NONLOOP_STREAM_DATA = 0
val PSP_ATRAC_STATUS_LOOP_STREAM_DATA = 1
val ATRAC_HEADER_HASH_LENGTH = 512
val ERROR_ATRAC_UNKNOWN_FORMAT = -0x7f9cfffa
val ERROR_ATRAC_INVALID_SIZE = -0x7f9cffef
val PSP_CODEC_AT3PLUS = 0x00001000
val PSP_CODEC_AT3 = 0x00001001
val PSP_CODEC_MP3 = 0x00001002
val PSP_CODEC_AAC = 0x00001003
private fun readUnaligned32(mem: SyncStream, addr: Int): Int {
mem.position = addr.toLong()
return mem.readS32_le()
}
fun SyncStream.read8(addr: Int): Int {
this.position = addr.toLong()
return this.readU8()
}
fun SyncStream.read16(addr: Int): Int {
this.position = addr.toLong()
return this.readU16_le()
}
/**
* From JPCSP
*/
fun analyzeRiffFile(mem: SyncStream, addr: Int, length: Int, info: AtracFileInfo): Int {
var result = ERROR_ATRAC_UNKNOWN_FORMAT
var currentAddr = addr
var bufferSize = length
info.atracEndSample = -1
info.numLoops = 0
info.inputFileDataOffset = 0
if (bufferSize < 12) {
log.error { "Atrac buffer too small %d".format(bufferSize) }
return ERROR_ATRAC_INVALID_SIZE
}
// RIFF file format:
// Offset 0: 'RIFF'
// Offset 4: file length - 8
// Offset 8: 'WAVE'
val magic = readUnaligned32(mem, currentAddr)
val WAVEMagic = readUnaligned32(mem, currentAddr + 8)
if (magic != RIFF_MAGIC || WAVEMagic != WAVE_MAGIC) {
//log.error(String_format("Not a RIFF/WAVE format! %s", Utilities.getMemoryDump(currentAddr, 16)))
log.error { "Not a RIFF/WAVE format!" }
return ERROR_ATRAC_UNKNOWN_FORMAT
}
info.inputFileSize = readUnaligned32(mem, currentAddr + 4) + 8
info.inputDataSize = info.inputFileSize
//if (log.isDebugEnabled()) {
log.trace { "FileSize 0x%X".format(info.inputFileSize) }
//}
currentAddr += 12
bufferSize -= 12
var foundData = false
while (bufferSize >= 8 && !foundData) {
val chunkMagic = readUnaligned32(mem, currentAddr)
val chunkSize = readUnaligned32(mem, currentAddr + 4)
currentAddr += 8
bufferSize -= 8
when (chunkMagic) {
DATA_CHUNK_MAGIC -> {
foundData = true
// Offset of the data chunk in the input file
info.inputFileDataOffset = currentAddr - addr
info.inputDataSize = chunkSize
log.trace { "DATA Chunk: data offset=0x%X, data size=0x%X".format(info.inputFileDataOffset, info.inputDataSize) }
}
FMT_CHUNK_MAGIC -> {
if (chunkSize >= 16) {
val compressionCode = mem.read16(currentAddr)
info.atracChannels = mem.read16(currentAddr + 2)
info.atracSampleRate = readUnaligned32(mem, currentAddr + 4)
info.atracBitrate = readUnaligned32(mem, currentAddr + 8)
info.atracBytesPerFrame = mem.read16(currentAddr + 12)
val hiBytesPerSample = mem.read16(currentAddr + 14)
val extraDataSize = mem.read16(currentAddr + 16)
if (extraDataSize == 14) {
info.atracCodingMode = mem.read16(currentAddr + 18 + 6)
}
if (log.isTraceEnabled) {
log.trace { "WAVE format: magic=0x%08X('%s'), chunkSize=%d, compressionCode=0x%04X, channels=%d, sampleRate=%d, bitrate=%d, bytesPerFrame=0x%X, hiBytesPerSample=%d, codingMode=%d".format(chunkMagic, getStringFromInt32(chunkMagic), chunkSize, compressionCode, info.atracChannels, info.atracSampleRate, info.atracBitrate, info.atracBytesPerFrame, hiBytesPerSample, info.atracCodingMode) }
// Display rest of chunk as debug information
val restChunk = StringBuilder()
for (i in 16 until chunkSize) {
val b = mem.read8(currentAddr + i)
restChunk.append(" %02X".format(b))
}
if (restChunk.length > 0) {
log.trace { "Additional chunk data:%s".format(restChunk) }
}
}
if (compressionCode == AT3_MAGIC) {
result = PSP_CODEC_AT3
} else if (compressionCode == AT3_PLUS_MAGIC) {
result = PSP_CODEC_AT3PLUS
} else {
return ERROR_ATRAC_UNKNOWN_FORMAT
}
}
}
FACT_CHUNK_MAGIC -> {
if (chunkSize >= 8) {
info.atracEndSample = readUnaligned32(mem, currentAddr)
if (info.atracEndSample > 0) {
info.atracEndSample -= 1
}
if (chunkSize >= 12) {
// Is the value at offset 4 ignored?
info.atracSampleOffset = readUnaligned32(mem, currentAddr + 8) // The loop samples are offset by this value
} else {
info.atracSampleOffset = readUnaligned32(mem, currentAddr + 4) // The loop samples are offset by this value
}
log.trace { "FACT Chunk: chunkSize=%d, endSample=0x%X, sampleOffset=0x%X".format(chunkSize, info.atracEndSample, info.atracSampleOffset) }
}
}
SMPL_CHUNK_MAGIC -> {
if (chunkSize >= 36) {
val checkNumLoops = readUnaligned32(mem, currentAddr + 28)
if (chunkSize >= 36 + checkNumLoops * 24) {
info.numLoops = checkNumLoops
info.loops = Array<LoopInfo>(info.numLoops) { LoopInfo() }
var loopInfoAddr = currentAddr + 36
for (i in 0 until info.numLoops) {
val loop = info.loops[i]
info.loops[i] = loop
loop.cuePointID = readUnaligned32(mem, loopInfoAddr)
loop.type = readUnaligned32(mem, loopInfoAddr + 4)
loop.startSample = readUnaligned32(mem, loopInfoAddr + 8) - info.atracSampleOffset
loop.endSample = readUnaligned32(mem, loopInfoAddr + 12) - info.atracSampleOffset
loop.fraction = readUnaligned32(mem, loopInfoAddr + 16)
loop.playCount = readUnaligned32(mem, loopInfoAddr + 20)
log.trace { "Loop #%d: %s".format(i, loop.toString()) }
loopInfoAddr += 24
}
// TODO Second buffer processing disabled because still incomplete
//isSecondBufferNeeded = true;
}
}
}
}
if (chunkSize > bufferSize) {
break
}
currentAddr += chunkSize
bufferSize -= chunkSize
}
// If a loop end is past the atrac end, assume the atrac end
for (loop in info.loops) {
if (loop.endSample > info.atracEndSample) {
loop.endSample = info.atracEndSample
}
}
return result
}
private fun getStringFromInt32(chunkMagic: Int): String = charArrayOf(chunkMagic.extract8(0).toChar(), chunkMagic.extract8(8).toChar(), chunkMagic.extract8(16).toChar(), chunkMagic.extract8(24).toChar()).contentToString()
class LoopInfo {
var cuePointID: Int = 0
var type: Int = 0
var startSample: Int = 0
var endSample: Int = 0
var fraction: Int = 0
var playCount: Int = 0
override fun toString(): String =
"LoopInfo[cuePointID %d, type %d, startSample 0x%X, endSample 0x%X, fraction %d, playCount %d]".format(cuePointID, type, startSample, endSample, fraction, playCount)
}
data class AtracFileInfo(
var atracBitrate: Int = 64,
var atracChannels: Int = 2,
var atracSampleRate: Int = 0xAC44,
var atracBytesPerFrame: Int = 0x0230,
var atracEndSample: Int = 0,
var atracSampleOffset: Int = 0,
var atracCodingMode: Int = 0,
var inputFileDataOffset: Int = 0,
var inputFileSize: Int = 0,
var inputDataSize: Int = 0,
var loopNum: Int = 0,
var numLoops: Int = 0,
var loops: Array<LoopInfo> = arrayOf()
)
} | mit | 5b0e3a4db32bd0fa90e0982ab985a716 | 33.20339 | 393 | 0.675753 | 3.066489 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/json/references/GdxJsonPropertyNameReference.kt | 1 | 1728 | package com.gmail.blueboxware.libgdxplugin.filetypes.json.references
import com.gmail.blueboxware.libgdxplugin.filetypes.json.psi.GdxJsonProperty
import com.intellij.openapi.util.TextRange
import com.intellij.psi.ElementManipulators
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
/*
* Copyright 2021 Blue Box Ware
*
* 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.
*/
class GdxJsonPropertyNameReference(val property: GdxJsonProperty) : PsiReference {
override fun getElement(): PsiElement = property
override fun getRangeInElement(): TextRange =
ElementManipulators.getValueTextRange(property.propertyName)
override fun resolve(): PsiElement = property
override fun getCanonicalText(): String = property.propertyName.getValue()
override fun handleElementRename(newElementName: String): PsiElement =
property.setName(newElementName)
override fun bindToElement(element: PsiElement): PsiElement? = null
override fun isReferenceTo(element: PsiElement): Boolean =
(element as? GdxJsonProperty)?.propertyName?.getValue() == property.propertyName.getValue()
&& element != property
override fun isSoft(): Boolean = true
}
| apache-2.0 | 8c7ebb9f133142262361a33a4a49f376 | 35.765957 | 99 | 0.760417 | 4.867606 | false | false | false | false |
eurofurence/ef-app_android | app/src/main/kotlin/org/eurofurence/connavigator/notifications/NotificationFactory.kt | 1 | 4767 | package org.eurofurence.connavigator.notifications
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Color
import android.media.RingtoneManager
import android.os.Build
import androidx.core.app.NotificationCompat
import org.eurofurence.connavigator.BuildConfig
import org.eurofurence.connavigator.R
import org.jetbrains.anko.intentFor
import org.jetbrains.anko.notificationManager
import org.joda.time.DateTime
import java.util.*
fun NotificationManager.cancelFromRelated(identity: UUID) =
cancel(identity.toString(), 0)
/**
* Creates a basic notification
*/
class NotificationFactory(var context: Context) {
var builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationCompat.Builder(context, NotificationChannel.DEFAULT_CHANNEL_ID)
} else {
NotificationCompat.Builder(context)
}
fun broadcast(tag: String) {
val notification = builder.build()
val intent = context.intentFor<NotificationPublisher>(
NotificationPublisher.TAG to tag,
NotificationPublisher.ITEM to notification
)
context.sendBroadcast(intent)
}
fun setupChannels() {
EFNotificationChannel.values().map {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// If we're debugging, remove the notification channels
if (BuildConfig.DEBUG) context.notificationManager.deleteNotificationChannel(it.toString())
context.notificationManager.createNotificationChannel(this.getChannel(it))
}
}
}
/**
* Creates a basic notification that features the EF logo, colours and vibration
*/
fun createBasicNotification() = this.apply {
builder = builder.setSmallIcon(R.drawable.ic_launcher_negative)
.setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher))
.setLights(Color.argb(255, 0, 100, 89), 1000, 1000)
.setVibrate(longArrayOf(250, 100, 250, 100))
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel("default", "Default", NotificationManager.IMPORTANCE_DEFAULT)
context.notificationManager.createNotificationChannel(channel)
builder = builder.setChannelId(channel.id)
}
}
/**
* Sets an activity to launch on notification taps
*/
fun setPendingIntent(pendingIntent: PendingIntent) = this.apply {
builder = builder.setContentIntent(pendingIntent)
}
fun addBigText(bigText: String) = this.apply {
builder = builder.setStyle(NotificationCompat.BigTextStyle()
.bigText(bigText))
}
fun addRegularText(title: String, text: String) = this.apply {
builder = builder.setContentTitle(title)
builder = builder.setContentText(text)
}
fun countdownTo(date: DateTime) = this.apply {
builder = builder.setWhen(date.millis)
.setUsesChronometer(true)
}
fun setChannel(channel: EFNotificationChannel) = this.apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = builder.setChannelId(getChannel(channel).id)
}
}
@SuppressLint("NewApi")
private fun getChannel(channel: EFNotificationChannel) = when (channel) {
EFNotificationChannel.EVENT -> NotificationChannel(channel.toString(), "Event Reminders", NotificationManager.IMPORTANCE_DEFAULT).apply {
description = "Receive a reminder when an event you added to your favorites is about to happen."
}
EFNotificationChannel.ANNOUNCEMENT -> NotificationChannel(channel.toString(), "Announcements", NotificationManager.IMPORTANCE_DEFAULT).apply {
description = "Receive a notification when EF sends convention wide announcements."
}
EFNotificationChannel.PRIVATE_MESSAGE -> NotificationChannel(channel.toString(), "Private Messages", NotificationManager.IMPORTANCE_HIGH).apply {
description = "Receive a notification when you have logged in and received a private message."
}
else -> NotificationChannel(channel.toString(), "Default", NotificationManager.IMPORTANCE_LOW)
}
fun build(): Notification = builder.build()
}
enum class EFNotificationChannel {
DEFAULT,
EVENT,
ANNOUNCEMENT,
PRIVATE_MESSAGE
} | mit | 59b55acadc1dcc3b9f20737d276a23e0 | 36.84127 | 153 | 0.696245 | 4.914433 | false | false | false | false |
premnirmal/StockTicker | app/src/main/kotlin/com/github/premnirmal/ticker/portfolio/PortfolioFragment.kt | 1 | 6083 | package com.github.premnirmal.ticker.portfolio
import android.appwidget.AppWidgetManager
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.view.View
import android.widget.PopupMenu
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import com.github.premnirmal.ticker.analytics.ClickEvent
import com.github.premnirmal.ticker.base.BaseFragment
import com.github.premnirmal.ticker.components.InAppMessage
import com.github.premnirmal.ticker.home.ChildFragment
import com.github.premnirmal.ticker.network.data.Quote
import com.github.premnirmal.ticker.news.QuoteDetailActivity
import com.github.premnirmal.ticker.portfolio.StocksAdapter.QuoteClickListener
import com.github.premnirmal.ticker.portfolio.drag_drop.OnStartDragListener
import com.github.premnirmal.ticker.portfolio.drag_drop.SimpleItemTouchHelperCallback
import com.github.premnirmal.ticker.ui.SpacingDecoration
import com.github.premnirmal.ticker.viewBinding
import com.github.premnirmal.tickerwidget.R
import com.github.premnirmal.tickerwidget.databinding.FragmentPortfolioBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
/**
* Created by premnirmal on 2/25/16.
*/
@AndroidEntryPoint
class PortfolioFragment : BaseFragment<FragmentPortfolioBinding>(), ChildFragment, QuoteClickListener, OnStartDragListener {
override val binding: (FragmentPortfolioBinding) by viewBinding(FragmentPortfolioBinding::inflate)
interface Parent {
fun onDragStarted()
fun onDragEnded()
}
companion object {
private const val LIST_INSTANCE_STATE = "LIST_INSTANCE_STATE"
private const val KEY_WIDGET_ID = "KEY_WIDGET_ID"
fun newInstance(widgetId: Int): PortfolioFragment {
val fragment = PortfolioFragment()
val args = Bundle()
args.putInt(KEY_WIDGET_ID, widgetId)
fragment.arguments = args
return fragment
}
fun newInstance(): PortfolioFragment {
val fragment = PortfolioFragment()
val args = Bundle()
args.putInt(KEY_WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID)
fragment.arguments = args
return fragment
}
}
override val simpleName: String = "PortfolioFragment"
private val viewModel: PortfolioViewModel by viewModels()
private val parent: Parent
get() = parentFragment as Parent
private var widgetId = AppWidgetManager.INVALID_APPWIDGET_ID
private val stocksAdapter by lazy {
val widgetData = viewModel.dataForWidgetId(widgetId)
StocksAdapter(widgetData, this as QuoteClickListener, this as OnStartDragListener)
}
private var itemTouchHelper: ItemTouchHelper? = null
override fun onOpenQuote(
view: View,
quote: Quote,
position: Int
) {
analytics.trackClickEvent(ClickEvent("InstrumentClick"))
val intent = Intent(view.context, QuoteDetailActivity::class.java)
intent.putExtra(QuoteDetailActivity.TICKER, quote.symbol)
startActivity(intent)
}
override fun onClickQuoteOptions(
view: View,
quote: Quote,
position: Int
) {
val popupWindow = PopupMenu(view.context, view)
popupWindow.menuInflater.inflate(R.menu.menu_portfolio, popupWindow.menu)
popupWindow.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.remove -> {
remove(quote)
}
}
true
}
popupWindow.show()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
widgetId = requireArguments().getInt(KEY_WIDGET_ID)
}
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?
) {
super.onViewCreated(view, savedInstanceState)
binding.stockList.addItemDecoration(
SpacingDecoration(requireContext().resources.getDimensionPixelSize(R.dimen.list_spacing_double))
)
val gridLayoutManager = androidx.recyclerview.widget.GridLayoutManager(context, 2)
binding.stockList.layoutManager = gridLayoutManager
binding.stockList.adapter = stocksAdapter
val callback: ItemTouchHelper.Callback = SimpleItemTouchHelperCallback(stocksAdapter)
itemTouchHelper = ItemTouchHelper(callback)
itemTouchHelper?.attachToRecyclerView(binding.stockList)
savedInstanceState?.let { state ->
val listViewState = state.getParcelable<Parcelable>(LIST_INSTANCE_STATE)
listViewState?.let { binding.stockList?.layoutManager?.onRestoreInstanceState(it) }
}
val widgetData = viewModel.dataForWidgetId(widgetId)
if (widgetData.getTickers().isEmpty()) {
binding.viewFlipper.displayedChild = 0
} else {
binding.viewFlipper.displayedChild = 1
}
viewModel.portfolio.observe(viewLifecycleOwner) {
stocksAdapter.refresh()
}
viewModel.fetchPortfolioInRealTime()
lifecycleScope.launch {
widgetData.autoSortEnabled.collect {
update()
}
}
}
private fun update() {
stocksAdapter.refresh()
}
private fun remove(quote: Quote) {
viewModel.removeStock(widgetId, quote.symbol)
stocksAdapter.refresh()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
val listViewState = binding.stockList?.layoutManager?.onSaveInstanceState()
listViewState?.let {
outState.putParcelable(LIST_INSTANCE_STATE, it)
}
}
override fun onStartDrag(viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder) {
parent.onDragStarted()
val widgetData = viewModel.dataForWidgetId(widgetId)
if (widgetData.autoSortEnabled()) {
InAppMessage.showMessage(requireActivity(), R.string.autosort_disabled)
}
itemTouchHelper?.startDrag(viewHolder)
}
override fun onStopDrag() {
parent.onDragEnded()
val widgetData = viewModel.dataForWidgetId(widgetId)
widgetData.setAutoSort(false)
viewModel.broadcastUpdateWidget(widgetId)
}
override fun setData(bundle: Bundle) {
}
override fun scrollToTop() {
binding.stockList.smoothScrollToPosition(0)
}
} | gpl-3.0 | cdd0086a8830a6bc394b1200dea73ee6 | 32.8 | 124 | 0.753576 | 4.643511 | false | false | false | false |
Maxr1998/MaxLock | app/src/main/java/de/Maxr1998/xposed/maxlock/ui/settings/applist/AppListModel.kt | 1 | 4549 | /*
* MaxLock, an Xposed applock module for Android
* Copyright (C) 2014-2018 Max Rumpf alias Maxr1998
*
* 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 any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.Maxr1998.xposed.maxlock.ui.settings.applist
import android.app.ActivityManager
import android.app.Application
import android.content.Context.ACTIVITY_SERVICE
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.AsyncTask
import android.util.LruCache
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.SortedList
import de.Maxr1998.xposed.maxlock.BuildConfig
import de.Maxr1998.xposed.maxlock.util.GenericEventLiveData
import de.Maxr1998.xposed.maxlock.util.KUtil.getLauncherPackages
import kotlinx.coroutines.*
import java.text.Collator
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.collections.ArrayList
import kotlin.coroutines.CoroutineContext
class AppListModel(application: Application) : AndroidViewModel(application), CoroutineScope {
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main
val adapter: AppListAdapter by lazy { AppListAdapter(this, application) }
private val appListCallback = AppListCallback(adapter)
val appList = SortedList(AppInfo::class.java, appListCallback)
val appListBackup = ArrayList<AppInfo>()
val appsLoadedListener = GenericEventLiveData<Any?>()
val dialogDispatcher = GenericEventLiveData<AlertDialog?>()
val fragmentFunctionDispatcher = MutableLiveData<(Fragment.() -> Any)?>()
var loadAll = false
val iconCache = LruCache<String, Drawable>(
if ((application.getSystemService(ACTIVITY_SERVICE) as ActivityManager).isLowRamDevice) 80 else 300
)
private lateinit var launcherPackages: List<String>
val loaded = AtomicBoolean(false)
init {
loadData()
}
fun loadData() {
loaded.set(false)
launch {
withContext(AsyncTask.THREAD_POOL_EXECUTOR.asCoroutineDispatcher()) {
val pm = getApplication<Application>().packageManager
launcherPackages = getLauncherPackages(pm)
val allApps = pm.getInstalledApplications(0)
val result = ArrayList<AppInfo>(allApps.size * 3 / 4)
for (i in allApps.indices) {
val info = allApps[i]
if (includeApp(pm, info.packageName)) {
result.add(AppInfo(i, info, pm))
}
}
val collator = Collator.getInstance()
result.sortWith(Comparator { a, b ->
compareValuesBy(a, b, collator, AppInfo::name)
})
result
}.let {
appListBackup.clear()
appListBackup.addAll(it)
appsLoadedListener.call(null)
appList.replaceAll(it)
loaded.set(true)
}
}
}
private fun includeApp(pm: PackageManager, packageName: String): Boolean {
return when {
packageName == BuildConfig.APPLICATION_ID -> false
launcherPackages.contains(packageName) -> false
packageName.matches(Regex("com.(google.)?android.packageinstaller")) -> true
loadAll && pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES).activities != null -> true
else -> pm.getLaunchIntentForPackage(packageName) != null
}
}
data class AppInfo(val id: Int, private val appInfo: ApplicationInfo, private val pm: PackageManager) {
val packageName: String = appInfo.packageName
val name: String by lazy { appInfo.loadLabel(pm).toString() }
fun loadIcon(): Drawable = appInfo.loadIcon(pm)
}
} | gpl-3.0 | 0ca071e577be3201ed6c1ddfaba06322 | 40.363636 | 111 | 0.687843 | 4.798523 | false | false | false | false |
AlmasB/FXGL | fxgl/src/main/kotlin/com/almasb/fxgl/dsl/components/KeepInBoundsComponent.kt | 1 | 2099 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.dsl.components
import com.almasb.fxgl.dsl.FXGL
import com.almasb.fxgl.entity.component.Component
import javafx.geometry.Rectangle2D
/**
* A component that keeps an entity within the viewport.
* Entities with physics enabled are not supported.
*
* @author Almas Baimagambetov ([email protected])
*/
open class KeepInBoundsComponent(var bounds: Rectangle2D) : Component() {
/**
* Keep in bounds in X axis.
*/
var isHorizontal = true
/**
* Keep in bounds in Y axis.
*/
var isVertical = true
override fun onUpdate(tpf: Double) {
blockWithBBox()
}
private fun blockWithBBox() {
if (isHorizontal) {
if (getEntity().x < bounds.minX) {
getEntity().x = bounds.minX
} else if (getEntity().rightX > bounds.maxX) {
getEntity().x = bounds.maxX - getEntity().width
}
}
if (isVertical) {
if (getEntity().y < bounds.minY) {
getEntity().y = bounds.minY
} else if (getEntity().bottomY > bounds.maxY) {
getEntity().y = bounds.maxY - getEntity().height
}
}
}
fun onlyHorizontally() = this.apply {
isVertical = false
isHorizontal = true
}
fun onlyVertically() = this.apply {
isVertical = true
isHorizontal = false
}
fun bothAxes() = this.apply {
isVertical = true
isHorizontal = true
}
override fun isComponentInjectionRequired(): Boolean = false
}
/**
* A component that keeps an entity within the viewport.
* Entities with physics enabled are not supported.
* Do NOT use this component if viewport is bound to an entity.
*/
class KeepOnScreenComponent : KeepInBoundsComponent(Rectangle2D.EMPTY) {
override fun onUpdate(tpf: Double) {
bounds = FXGL.getGameScene().viewport.visibleArea
super.onUpdate(tpf)
}
} | mit | 38f648218cf463c1bfb7c990ec706df8 | 24.609756 | 73 | 0.61172 | 4.336777 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-auctions-bukkit/src/main/kotlin/com/rpkit/auctions/bukkit/command/auction/AuctionCreateCommand.kt | 1 | 15327 | /*
* Copyright 2021 Ren Binden
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.auctions.bukkit.command.auction
import com.rpkit.auctions.bukkit.RPKAuctionsBukkit
import com.rpkit.auctions.bukkit.auction.RPKAuctionService
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.economy.bukkit.currency.RPKCurrency
import com.rpkit.economy.bukkit.currency.RPKCurrencyName
import com.rpkit.economy.bukkit.currency.RPKCurrencyService
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.conversations.*
import org.bukkit.entity.Player
/**
* Auction creation command.
* Currently does not take any further arguments, instead using conversations to obtain data needed to create the auction.
*/
class AuctionCreateCommand(private val plugin: RPKAuctionsBukkit) : CommandExecutor {
val conversationFactory: ConversationFactory = ConversationFactory(plugin)
.withModality(true)
.withFirstPrompt(CurrencyPrompt())
.withEscapeSequence("cancel")
.thatExcludesNonPlayersWithMessage(plugin.messages.notFromConsole)
.addConversationAbandonedListener { event ->
if (!event.gracefulExit()) {
val conversable = event.context.forWhom
if (conversable is Player) {
conversable.sendMessage(plugin.messages.operationCancelled)
}
}
}
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (sender !is Player) {
sender.sendMessage(plugin.messages.notFromConsole)
return true
}
if (!sender.hasPermission("rpkit.auctions.command.auction.create")) {
sender.sendMessage(plugin.messages.noPermissionAuctionCreate)
return true
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
sender.sendMessage(plugin.messages.noMinecraftProfileService)
return true
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
sender.sendMessage(plugin.messages.noCharacterService)
return true
}
val currencyService = Services[RPKCurrencyService::class.java]
if (currencyService == null) {
sender.sendMessage(plugin.messages.noCurrencyService)
return true
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(sender)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages.noMinecraftProfile)
return true
}
val character = characterService.getPreloadedActiveCharacter(minecraftProfile)
if (character != null) {
conversationFactory.buildConversation(sender).begin()
} else {
sender.sendMessage(plugin.messages.noCharacter)
}
return true
}
private inner class CurrencyPrompt : ValidatingPrompt() {
override fun isInputValid(context: ConversationContext, input: String): Boolean {
return Services[RPKCurrencyService::class.java]?.getCurrency(RPKCurrencyName(input)) != null
}
override fun acceptValidatedInput(context: ConversationContext, input: String): Prompt {
context.setSessionData("currency", Services[RPKCurrencyService::class.java]?.getCurrency(RPKCurrencyName(input)))
return CurrencySetPrompt()
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages.auctionSetCurrencyPrompt + "\n" +
Services[RPKCurrencyService::class.java]
?.currencies
?.joinToString("\n") { currency ->
plugin.messages.auctionSetCurrencyPromptListItem.withParameters(
currency = currency
)
}
}
override fun getFailedValidationText(context: ConversationContext, invalidInput: String): String {
return plugin.messages.auctionSetCurrencyInvalidCurrency
}
}
private inner class CurrencySetPrompt : MessagePrompt() {
override fun getNextPrompt(context: ConversationContext): Prompt {
return DurationPrompt()
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages.auctionSetCurrencyValid
}
}
private inner class DurationPrompt : NumericPrompt() {
override fun acceptValidatedInput(context: ConversationContext, input: Number): Prompt {
context.setSessionData("duration", input.toInt())
return DurationSetPrompt()
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages.auctionSetDurationPrompt
}
override fun isNumberValid(context: ConversationContext, input: Number): Boolean {
return input.toInt() > 0
}
override fun getInputNotNumericText(context: ConversationContext, invalidInput: String): String {
return plugin.messages.auctionSetDurationInvalidNumber
}
override fun getFailedValidationText(context: ConversationContext, invalidInput: Number): String {
return plugin.messages.auctionSetDurationInvalidNegative
}
}
private inner class DurationSetPrompt : MessagePrompt() {
override fun getNextPrompt(context: ConversationContext): Prompt {
return StartPricePrompt()
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages.auctionSetDurationValid
}
}
private inner class StartPricePrompt : NumericPrompt() {
override fun acceptValidatedInput(context: ConversationContext, input: Number): Prompt {
context.setSessionData("start_price", input.toInt())
return StartPriceSetPrompt()
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages.auctionSetStartPricePrompt
}
override fun isNumberValid(context: ConversationContext, input: Number): Boolean {
return input.toInt() >= 0
}
override fun getInputNotNumericText(context: ConversationContext, invalidInput: String): String {
return plugin.messages.auctionSetStartPriceInvalidNumber
}
override fun getFailedValidationText(context: ConversationContext, invalidInput: Number): String {
return plugin.messages.auctionSetStartPriceInvalidNegative
}
}
private inner class StartPriceSetPrompt : MessagePrompt() {
override fun getNextPrompt(context: ConversationContext): Prompt {
return BuyOutPricePrompt()
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages.auctionSetStartPriceValid
}
}
private inner class BuyOutPricePrompt : NumericPrompt() {
override fun acceptValidatedInput(context: ConversationContext, input: Number): Prompt {
context.setSessionData("buy_out_price", input.toInt())
return BuyOutPriceSetPrompt()
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages.auctionSetBuyOutPricePrompt
}
override fun isNumberValid(context: ConversationContext, input: Number): Boolean {
return input.toInt() >= 0
}
override fun getInputNotNumericText(context: ConversationContext, invalidInput: String): String {
return plugin.messages.auctionSetBuyOutPriceInvalidNumber
}
override fun getFailedValidationText(context: ConversationContext, invalidInput: Number): String {
return plugin.messages.auctionSetBuyOutPriceInvalidNegative
}
}
private inner class BuyOutPriceSetPrompt : MessagePrompt() {
override fun getNextPrompt(context: ConversationContext): Prompt {
return NoSellPricePrompt()
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages.auctionSetBuyOutPriceValid
}
}
private inner class NoSellPricePrompt : NumericPrompt() {
override fun acceptValidatedInput(context: ConversationContext, input: Number): Prompt {
context.setSessionData("no_sell_price", input.toInt())
return NoSellPriceSetPrompt()
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages.auctionSetNoSellPricePrompt
}
override fun isNumberValid(context: ConversationContext, input: Number): Boolean {
return input.toInt() >= 0
}
override fun getInputNotNumericText(context: ConversationContext, invalidInput: String): String {
return plugin.messages.auctionSetNoSellPriceInvalidNumber
}
override fun getFailedValidationText(context: ConversationContext, invalidInput: Number): String {
return plugin.messages.auctionSetNoSellPriceInvalidNegative
}
}
private inner class NoSellPriceSetPrompt : MessagePrompt() {
override fun getNextPrompt(context: ConversationContext): Prompt {
return MinimumBidIncrementPrompt()
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages.auctionSetNoSellPriceValid
}
}
private inner class MinimumBidIncrementPrompt : NumericPrompt() {
override fun acceptValidatedInput(context: ConversationContext, input: Number): Prompt {
context.setSessionData("minimum_bid_increment", input.toInt())
return MinimumBidIncrementSetPrompt()
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages.auctionSetMinimumBidIncrementPrompt
}
override fun isNumberValid(context: ConversationContext, input: Number): Boolean {
return input.toInt() >= 0
}
override fun getInputNotNumericText(context: ConversationContext, invalidInput: String): String {
return plugin.messages.auctionSetMinimumBidIncrementInvalidNumber
}
override fun getFailedValidationText(context: ConversationContext, invalidInput: Number): String {
return plugin.messages.auctionSetMinimumBidIncrementInvalidNegative
}
}
private inner class MinimumBidIncrementSetPrompt : MessagePrompt() {
override fun getNextPrompt(context: ConversationContext): Prompt {
return AuctionCreatedPrompt()
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages.auctionSetMinimumBidIncrementValid
}
}
private inner class AuctionCreatedPrompt : MessagePrompt() {
override fun getNextPrompt(context: ConversationContext): Prompt? {
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
?: return AuctionErrorPrompt(plugin.messages.noMinecraftProfileService)
val characterService = Services[RPKCharacterService::class.java]
?: return AuctionErrorPrompt(plugin.messages.noCharacterService)
val auctionService = Services[RPKAuctionService::class.java]
?: return AuctionErrorPrompt(plugin.messages.noAuctionService)
val bukkitPlayer = context.forWhom as Player
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(bukkitPlayer)
?: return AuctionErrorPrompt(plugin.messages.noMinecraftProfile)
val character = characterService.getPreloadedActiveCharacter(minecraftProfile)
?: return AuctionErrorPrompt(plugin.messages.noCharacter)
auctionService.createAuction(
bukkitPlayer.inventory.itemInMainHand,
context.getSessionData("currency") as RPKCurrency,
bukkitPlayer.location,
character,
(context.getSessionData("duration") as Int) * 3600000L, // 60 mins * 60 secs * 1000 millisecs
System.currentTimeMillis() + ((context.getSessionData("duration") as Int) * 3600000L),
context.getSessionData("start_price") as Int,
context.getSessionData("buy_out_price") as Int,
context.getSessionData("no_sell_price") as Int,
context.getSessionData("minimum_bid_increment") as Int
).thenAccept { auction ->
if (auction == null) {
bukkitPlayer.sendMessage(plugin.messages.auctionCreateFailed)
} else {
plugin.server.scheduler.runTask(plugin, Runnable {
auction.openBidding()
auctionService.updateAuction(auction)
.thenAccept { updateSuccessful ->
if (!updateSuccessful) {
bukkitPlayer.sendMessage(plugin.messages.auctionUpdateFailed)
} else {
plugin.server.scheduler.runTask(plugin, Runnable {
bukkitPlayer.inventory.setItemInMainHand(null)
})
bukkitPlayer.sendMessage(plugin.messages.auctionCreateId.withParameters(id = auction.id?.value ?: 0))
}
}
})
}
}
return END_OF_CONVERSATION
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages.auctionCreateValid
}
}
private inner class AuctionErrorPrompt(val errorMessage: String) : MessagePrompt() {
override fun getNextPrompt(context: ConversationContext): Prompt? {
return END_OF_CONVERSATION
}
override fun getPromptText(context: ConversationContext): String {
return errorMessage
}
}
} | apache-2.0 | 457f7463d4df75978004eb837f0d4e2d | 39.550265 | 137 | 0.657011 | 5.885945 | false | false | false | false |
roamingthings/dev-workbench | dev-workbench-backend/src/main/kotlin/de/roamingthings/devworkbench/link/resource/LinkResource.kt | 1 | 1188 | package de.roamingthings.devworkbench.link.resource
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import de.roamingthings.devworkbench.link.api.LinkDto
import org.springframework.hateoas.ResourceSupport
import java.time.LocalDateTime
/**
*
*
* @author Alexander Sparkowsky [[email protected]]
* @version 2017/07/01
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
data class LinkResource
@JsonCreator
constructor(
@JsonProperty("id") val _id: Long,
@JsonProperty("uri") val uri: String?,
@JsonProperty("title") val title: String?,
@JsonProperty("lastAccessed") val lastAccessed: LocalDateTime?,
@JsonProperty("accessCount") val accessCount: Int) : ResourceSupport() {
companion object {
fun fromDto(dto: LinkDto): LinkResource =
LinkResource(
_id = dto.id,
uri = dto.uri,
title = dto.title,
lastAccessed = dto.lastAccessed,
accessCount = dto.accessCount
)
}
} | apache-2.0 | 1ab0c888fae8c99b78de007e53b61993 | 31.135135 | 80 | 0.64899 | 4.534351 | false | false | false | false |
Doist/TodoistModels | src/main/java/com/todoist/pojo/Avatar.kt | 2 | 1747 | package com.todoist.pojo
enum class Avatar constructor(private val size: Int, private val arg: String) {
// In ascending order of size.
SMALL(35, "small"),
MEDIUM(60, "medium"),
BIG(195, "big"),
HUGE(640, "s640");
fun getUrl(imageId: String?): String? {
return if (imageId != null) {
"https://dcff1xvirvpfp.cloudfront.net/${imageId}_${getForSize(size).arg}.jpg"
} else {
null
}
}
companion object {
/**
* Returns the first [Avatar] to be larger than `size`. If none exist, returns the largest
* one.
*/
@JvmStatic
fun getForSize(size: Int) = values().firstOrNull { it.size >= size } ?: values().last()
/**
* Returns an array of [Avatar] ordered by how optimal they are. The first should be the
* best, followed by larger sizes and finally the smaller ones.
*/
@JvmStatic
fun getOrderedForSize(size: Int): Array<Avatar> {
val bestAvatar = getForSize(size)
val bestOrdinal = bestAvatar.ordinal
return arrayListOf<Avatar>().apply {
add(0, bestAvatar)
for (i in 1 until values().size) {
val prevOrdinal = this[i - 1].ordinal
val ordinal = when {
prevOrdinal >= bestOrdinal -> {
prevOrdinal + if (prevOrdinal < values().lastIndex) 1 else -1
}
else -> {
prevOrdinal - 1
}
}
add(i, values()[ordinal])
}
}.toTypedArray()
}
}
}
| mit | 46adece275afc73f5d4ba0ae85d4f6f2 | 31.962264 | 98 | 0.488266 | 4.696237 | false | false | false | false |
quarck/CalendarNotification | app/src/main/java/com/github/quarck/calnotify/calendar/EventAlertRecord.kt | 1 | 11353 | //
// Calendar Notifications Plus
// Copyright (C) 2016 Sergey Parshin ([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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
package com.github.quarck.calnotify.calendar
import android.content.Context
import android.provider.CalendarContract
import com.github.quarck.calnotify.Consts
import com.github.quarck.calnotify.R
enum class EventOrigin(val code: Int) {
ProviderBroadcast(0),
ProviderManual(1),
ProviderBroadcastFollowingManual(2),
FullManual(3);
override fun toString(): String
= when (this) {
ProviderBroadcast -> "PB"
ProviderManual -> "PM"
ProviderBroadcastFollowingManual -> "pbPM"
FullManual -> "FM"
}
companion object {
@JvmStatic
fun fromInt(v: Int) = values()[v]
}
}
enum class EventStatus(val code: Int) {
Tentative(CalendarContract.Events.STATUS_TENTATIVE),
Confirmed(CalendarContract.Events.STATUS_CONFIRMED),
Cancelled(CalendarContract.Events.STATUS_CANCELED),
Unknown(-1);
companion object {
@JvmStatic
fun fromInt(v: Int?): EventStatus {
if (v == null)
return Confirmed
return when (v) {
CalendarContract.Events.STATUS_TENTATIVE -> Tentative
CalendarContract.Events.STATUS_CONFIRMED -> Confirmed
CalendarContract.Events.STATUS_CANCELED -> Cancelled
else -> Unknown
}
}
}
}
enum class AttendanceStatus(val code: Int) {
None(CalendarContract.Attendees.ATTENDEE_STATUS_NONE),
Accepted(CalendarContract.Attendees.ATTENDEE_STATUS_ACCEPTED),
Declined(CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED),
Invited(CalendarContract.Attendees.ATTENDEE_STATUS_INVITED),
Tentative(CalendarContract.Attendees.ATTENDEE_STATUS_TENTATIVE),
Unknown(-1);
companion object {
@JvmStatic
fun fromInt(v: Int?): AttendanceStatus {
if (v == null)
return Accepted
return when (v) {
CalendarContract.Attendees.ATTENDEE_STATUS_NONE -> None
CalendarContract.Attendees.ATTENDEE_STATUS_ACCEPTED -> Accepted
CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED -> Declined
CalendarContract.Attendees.ATTENDEE_STATUS_INVITED -> Invited
CalendarContract.Attendees.ATTENDEE_STATUS_TENTATIVE -> Tentative
else -> Unknown
}
}
}
}
object EventAlertFlags {
const val IS_MUTED = 1L
const val IS_TASK = 2L
const val IS_ALARM = 4L
}
fun Long.isFlagSet(flag: Long)
= (this and flag) != 0L
fun Long.setFlag(flag: Long, value: Boolean)
= if (value)
this or flag
else
this and flag.inv()
data class EventAlertRecordKey(val eventId: Long, val instanceStartTime: Long)
data class EventAlertRecord(
val calendarId: Long,
val eventId: Long,
var isAllDay: Boolean,
var isRepeating: Boolean,
var alertTime: Long,
var notificationId: Int,
var title: String,
var desc: String,
var startTime: Long,
var endTime: Long,
var instanceStartTime: Long,
var instanceEndTime: Long,
var location: String,
var lastStatusChangeTime: Long,
var snoozedUntil: Long = 0,
var displayStatus: EventDisplayStatus = EventDisplayStatus.Hidden,
var color: Int = 0,
var origin: EventOrigin = EventOrigin.ProviderBroadcast,
var timeFirstSeen: Long = 0L,
var eventStatus: EventStatus = EventStatus.Confirmed,
var attendanceStatus: AttendanceStatus = AttendanceStatus.None,
var flags: Long = 0
) {
fun toPublicString() =
"EventAlertRecord($calendarId,$eventId,$isAllDay,$isRepeating,$alertTime,$notificationId,$startTime,$endTime,$instanceStartTime,$instanceEndTime,$lastStatusChangeTime,$snoozedUntil,$displayStatus,$origin,$timeFirstSeen,$flags)"
var isMuted: Boolean
get() = flags.isFlagSet(EventAlertFlags.IS_MUTED)
set(value) { flags = flags.setFlag(EventAlertFlags.IS_MUTED, value) }
var isTask: Boolean
get() = flags.isFlagSet(EventAlertFlags.IS_TASK)
set(value) { flags = flags.setFlag(EventAlertFlags.IS_TASK, value) }
var isAlarm: Boolean
get() = flags.isFlagSet(EventAlertFlags.IS_ALARM)
set(value) { flags = flags.setFlag(EventAlertFlags.IS_ALARM, value) }
val isUnmutedAlarm: Boolean
get() = isAlarm && !isMuted
val key: EventAlertRecordKey
get() = EventAlertRecordKey(eventId, instanceStartTime)
val titleAsOneLine: String by lazy { title.replace("\r\n", " ").replace("\n", " ")}
}
fun EventAlertRecord.updateFrom(newEvent: EventAlertRecord): Boolean {
var ret = false
if (title != newEvent.title) {
title = newEvent.title
ret = true
}
if (desc != newEvent.desc) {
desc = newEvent.desc
ret = true
}
if (alertTime != newEvent.alertTime) {
alertTime = newEvent.alertTime
ret = true
}
if (startTime != newEvent.startTime) {
startTime = newEvent.startTime
ret = true
}
if (endTime != newEvent.endTime) {
endTime = newEvent.endTime
ret = true
}
if (instanceStartTime != newEvent.instanceStartTime) {
instanceStartTime = newEvent.instanceStartTime
ret = true
}
if (instanceEndTime != newEvent.instanceEndTime) {
instanceEndTime = newEvent.instanceEndTime
ret = true
}
if (isAllDay != newEvent.isAllDay) {
isAllDay = newEvent.isAllDay
ret = true
}
if (location != newEvent.location) {
location = newEvent.location
ret = true
}
if (color != newEvent.color) {
color = newEvent.color
ret = true
}
if (isRepeating != newEvent.isRepeating) { // only for upgrading from prev versions of DB
isRepeating = newEvent.isRepeating
ret = true
}
if (eventStatus != newEvent.eventStatus) {
eventStatus = newEvent.eventStatus
ret = true
}
if (attendanceStatus != newEvent.attendanceStatus) {
attendanceStatus = newEvent.attendanceStatus
ret = true
}
return ret
}
fun EventAlertRecord.updateFrom(newEvent: EventRecord): Boolean {
var ret = false
if (title != newEvent.title) {
title = newEvent.title
ret = true
}
if (desc != newEvent.desc) {
desc = newEvent.desc
ret = true
}
if (location != newEvent.location) {
location = newEvent.location
ret = true
}
if (startTime != newEvent.startTime) {
startTime = newEvent.startTime
ret = true
}
if (endTime != newEvent.endTime) {
endTime = newEvent.endTime
ret = true
}
if (color != newEvent.color) {
color = newEvent.color
ret = true
}
if (isAllDay != newEvent.isAllDay) {
isAllDay = newEvent.isAllDay
ret = true
}
if (eventStatus != newEvent.eventStatus) {
eventStatus = newEvent.eventStatus
ret = true
}
if (attendanceStatus != newEvent.attendanceStatus) {
attendanceStatus = newEvent.attendanceStatus
ret = true
}
return ret
}
fun EventAlertRecord.updateFromWithoutTime(newEvent: EventRecord): Boolean {
var ret = false
if (title != newEvent.title) {
title = newEvent.title
ret = true
}
if (color != newEvent.color) {
color = newEvent.color
ret = true
}
if (isAllDay != newEvent.isAllDay) {
isAllDay = newEvent.isAllDay
ret = true
}
if (eventStatus != newEvent.eventStatus) {
eventStatus = newEvent.eventStatus
ret = true
}
if (attendanceStatus != newEvent.attendanceStatus) {
attendanceStatus = newEvent.attendanceStatus
ret = true
}
return ret
}
val EventAlertRecord.displayedStartTime: Long
get() = if (instanceStartTime != 0L) instanceStartTime else startTime
val EventAlertRecord.displayedEndTime: Long
get() = if (instanceEndTime != 0L) instanceEndTime else endTime
val EventAlertRecord.isSnoozed: Boolean
get() = snoozedUntil != 0L
val EventAlertRecord.isNotSnoozed: Boolean
get() = snoozedUntil == 0L
val EventAlertRecord.isActiveAlarm: Boolean
get() = isNotSnoozed && isNotSpecial && isAlarm
val EventAlertRecord.isSpecial: Boolean
get() = instanceStartTime == Long.MAX_VALUE
val EventAlertRecord.isNotSpecial: Boolean
get() = instanceStartTime != Long.MAX_VALUE
val EventAlertRecord.specialId: Long
get() {
if (instanceStartTime == Long.MAX_VALUE)
return eventId
else
return -1L
}
enum class EventAlertRecordSpecialType(val code: Int) {
ScanMaxOneMonth(1),
ScanMaxHundredOverdueEvents(2);
companion object {
@JvmStatic
fun fromInt(v: Int) = values()[v]
}
}
fun CreateEventAlertSpecialScanOverHundredEvents(ctx: Context, missedEvents: Int): EventAlertRecord {
val title =
ctx.resources.getString(R.string.special_event_title)
return EventAlertRecord(
calendarId = -1L,
eventId = EventAlertRecordSpecialType.ScanMaxHundredOverdueEvents.code.toLong(),
isAllDay = false,
isRepeating = false,
alertTime = missedEvents.toLong(),
notificationId = 0,
title = title,
desc = "",
startTime = 0L,
endTime = 0L,
instanceStartTime = Long.MAX_VALUE,
instanceEndTime = Long.MAX_VALUE,
location = "",
lastStatusChangeTime = Long.MAX_VALUE - 2,
snoozedUntil = 0L,
color = 0xffff0000.toInt()
)
}
val EventAlertRecord.scanMissedTotalEvents: Long
get() {
if (instanceStartTime == Long.MAX_VALUE)
return alertTime
else
return 0L
}
fun EventAlertRecord.getSpecialDetail(ctx: Context): Pair<String, String> {
val detail1 =
String.format(
ctx.resources.getString(R.string.special_event_detail_format),
Consts.MAX_DUE_ALERTS_FOR_MANUAL_SCAN,
scanMissedTotalEvents + Consts.MAX_DUE_ALERTS_FOR_MANUAL_SCAN
)
val detail2 = ctx.resources.getString(R.string.special_event_detail2)
return Pair(detail1, detail2)
}
| gpl-3.0 | 4eda7acd5cbf8b080724c30a934a7cb9 | 27.171216 | 239 | 0.629966 | 4.371583 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/lang/core/types/visitors/impl/RustEqualityTypeVisitor.kt | 1 | 4877 | package org.rust.lang.core.types.visitors.impl
import org.rust.lang.core.types.*
import org.rust.lang.core.types.unresolved.*
import org.rust.lang.core.types.visitors.RustInvariantTypeVisitor
import org.rust.lang.core.types.visitors.RustTypeVisitor
import org.rust.lang.core.types.visitors.RustUnresolvedTypeVisitor
import org.rust.utils.safely
open class RustEqualityTypeVisitor(override var lop: RustType)
: RustEqualityTypeVisitorBase<RustType>()
, RustTypeVisitor<Boolean> {
protected fun visit(lop: RustType, rop: RustType): Boolean {
val prev = this.lop
this.lop = lop
return safely({ rop.accept(this) }) {
this.lop = prev
}
}
protected fun visitTypeList(lop: Iterable<RustType>, rop: Iterable<RustType>): Boolean =
lop.zip(rop).all({ visit(it.first, it.second) })
override fun visitStruct(type: RustStructType): Boolean {
val lop = lop
if (lop !is RustStructType)
return false
return lop.item == type.item
}
override fun visitEnum(type: RustEnumType): Boolean {
val lop = lop
if (lop !is RustEnumType)
return false
return lop.item == type.item
}
override fun visitTupleType(type: RustTupleType): Boolean {
val lop = lop
if (lop !is RustTupleType || lop.size != type.size)
return false
return visitTypeList(lop.types, type.types)
}
override fun visitFunctionType(type: RustFunctionType): Boolean {
val lop = lop
if (lop !is RustFunctionType)
return false
return visit(lop.retType, type.retType) && visitTypeList(lop.paramTypes, type.paramTypes)
}
override fun visitTypeParameter(type: RustTypeParameterType): Boolean {
val lop = lop
if (lop !is RustTypeParameterType)
return false
return lop.parameter === type.parameter
}
override fun visitTrait(type: RustTraitType): Boolean {
val lop = lop
if (lop !is RustTraitType)
return false
return lop.trait == type.trait
}
override fun visitReference(type: RustReferenceType): Boolean {
val lop = lop
if (lop !is RustReferenceType)
return false
return lop.mutable == type.mutable && visit(lop.referenced, type.referenced)
}
}
open class RustEqualityUnresolvedTypeVisitor(override var lop: RustUnresolvedType)
: RustEqualityTypeVisitorBase<RustUnresolvedType>()
, RustUnresolvedTypeVisitor<Boolean> {
fun visit(lop: RustUnresolvedType, rop: RustUnresolvedType): Boolean {
val prev = this.lop
this.lop = lop
return safely({ rop.accept(this) }) {
this.lop = prev
}
}
fun visitTypeList(lop: Iterable<RustUnresolvedType>, rop: Iterable<RustUnresolvedType>): Boolean =
lop.count() == rop.count() && lop.zip(rop).all({ visit(it.first, it.second) })
override fun visitPathType(type: RustUnresolvedPathType): Boolean {
val lop = lop
if (lop !is RustUnresolvedPathType)
return false
return lop.path == type.path
}
override fun visitTupleType(type: RustUnresolvedTupleType): Boolean {
val lop = lop
if (lop !is RustUnresolvedTupleType)
return false
return visitTypeList(lop.types, type.types)
}
override fun visitFunctionType(type: RustUnresolvedFunctionType): Boolean {
val lop = lop
if (lop !is RustUnresolvedFunctionType)
return false
return visit(lop.retType, type.retType) && visitTypeList(lop.paramTypes, type.paramTypes)
}
override fun visitReference(type: RustUnresolvedReferenceType): Boolean {
val lop = lop
if (lop !is RustUnresolvedReferenceType)
return false
return lop.mutable == type.mutable && visit(lop.referenced, type.referenced)
}
}
abstract class RustEqualityTypeVisitorBase<T>() : RustInvariantTypeVisitor<Boolean> {
protected abstract var lop: T
override fun visitInteger(type: RustIntegerType): Boolean {
val lop = lop
return lop is RustIntegerType && lop.kind === type.kind
}
override fun visitFloat(type: RustFloatType): Boolean {
val lop = lop
return lop is RustFloatType && lop.kind == type.kind
}
override fun visitUnknown(type: RustUnknownType): Boolean {
return lop === type
}
override fun visitUnitType(type: RustUnitType): Boolean {
return lop === type
}
override fun visitString(type: RustStringSliceType): Boolean {
return lop === type
}
override fun visitChar(type: RustCharacterType): Boolean {
return lop === type
}
override fun visitBoolean(type: RustBooleanType): Boolean {
return lop === type
}
}
| mit | a86dced9587c0ddbe44d8900b2be0568 | 28.379518 | 102 | 0.649785 | 4.150638 | false | false | false | false |
NoodleMage/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/main/MainActivity.kt | 1 | 9253 | package eu.kanade.tachiyomi.ui.main
import android.animation.ObjectAnimator
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.graphics.drawable.DrawerArrowDrawable
import android.view.ViewGroup
import com.bluelinelabs.conductor.*
import eu.kanade.tachiyomi.Migrations
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.ui.base.activity.BaseActivity
import eu.kanade.tachiyomi.ui.base.controller.*
import eu.kanade.tachiyomi.ui.catalogue.CatalogueController
import eu.kanade.tachiyomi.ui.download.DownloadController
import eu.kanade.tachiyomi.ui.extension.ExtensionController
import eu.kanade.tachiyomi.ui.library.LibraryController
import eu.kanade.tachiyomi.ui.manga.MangaController
import eu.kanade.tachiyomi.ui.recent_updates.RecentChaptersController
import eu.kanade.tachiyomi.ui.recently_read.RecentlyReadController
import eu.kanade.tachiyomi.ui.setting.SettingsMainController
import kotlinx.android.synthetic.main.main_activity.*
import uy.kohesive.injekt.injectLazy
class MainActivity : BaseActivity() {
private lateinit var router: Router
val preferences: PreferencesHelper by injectLazy()
private var drawerArrow: DrawerArrowDrawable? = null
private var secondaryDrawer: ViewGroup? = null
private val startScreenId by lazy {
when (preferences.startScreen()) {
2 -> R.id.nav_drawer_recently_read
3 -> R.id.nav_drawer_recent_updates
else -> R.id.nav_drawer_library
}
}
lateinit var tabAnimator: TabsAnimator
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(when (preferences.theme()) {
2 -> R.style.Theme_Tachiyomi_Dark
3 -> R.style.Theme_Tachiyomi_Amoled
else -> R.style.Theme_Tachiyomi
})
super.onCreate(savedInstanceState)
// Do not let the launcher create a new activity http://stackoverflow.com/questions/16283079
if (!isTaskRoot) {
finish()
return
}
setContentView(R.layout.main_activity)
setSupportActionBar(toolbar)
drawerArrow = DrawerArrowDrawable(this)
drawerArrow?.color = Color.WHITE
toolbar.navigationIcon = drawerArrow
tabAnimator = TabsAnimator(tabs)
// Set behavior of Navigation drawer
nav_view.setNavigationItemSelectedListener { item ->
val id = item.itemId
val currentRoot = router.backstack.firstOrNull()
if (currentRoot?.tag()?.toIntOrNull() != id) {
when (id) {
R.id.nav_drawer_library -> setRoot(LibraryController(), id)
R.id.nav_drawer_recent_updates -> setRoot(RecentChaptersController(), id)
R.id.nav_drawer_recently_read -> setRoot(RecentlyReadController(), id)
R.id.nav_drawer_catalogues -> setRoot(CatalogueController(), id)
R.id.nav_drawer_extensions -> setRoot(ExtensionController(), id)
R.id.nav_drawer_downloads -> {
router.pushController(DownloadController().withFadeTransaction())
}
R.id.nav_drawer_settings -> {
router.pushController(SettingsMainController().withFadeTransaction())
}
}
}
drawer.closeDrawer(GravityCompat.START)
true
}
val container: ViewGroup = findViewById(R.id.controller_container)
router = Conductor.attachRouter(this, container, savedInstanceState)
if (!router.hasRootController()) {
// Set start screen
if (!handleIntentAction(intent)) {
setSelectedDrawerItem(startScreenId)
}
}
toolbar.setNavigationOnClickListener {
if (router.backstackSize == 1) {
drawer.openDrawer(GravityCompat.START)
} else {
onBackPressed()
}
}
router.addChangeListener(object : ControllerChangeHandler.ControllerChangeListener {
override fun onChangeStarted(to: Controller?, from: Controller?, isPush: Boolean,
container: ViewGroup, handler: ControllerChangeHandler) {
syncActivityViewWithController(to, from)
}
override fun onChangeCompleted(to: Controller?, from: Controller?, isPush: Boolean,
container: ViewGroup, handler: ControllerChangeHandler) {
}
})
syncActivityViewWithController(router.backstack.lastOrNull()?.controller())
if (savedInstanceState == null) {
// Show changelog if needed
if (Migrations.upgrade(preferences)) {
ChangelogDialogController().showDialog(router)
}
}
}
override fun onNewIntent(intent: Intent) {
if (!handleIntentAction(intent)) {
super.onNewIntent(intent)
}
}
private fun handleIntentAction(intent: Intent): Boolean {
when (intent.action) {
SHORTCUT_LIBRARY -> setSelectedDrawerItem(R.id.nav_drawer_library)
SHORTCUT_RECENTLY_UPDATED -> setSelectedDrawerItem(R.id.nav_drawer_recent_updates)
SHORTCUT_RECENTLY_READ -> setSelectedDrawerItem(R.id.nav_drawer_recently_read)
SHORTCUT_CATALOGUES -> setSelectedDrawerItem(R.id.nav_drawer_catalogues)
SHORTCUT_MANGA -> router.setRoot(RouterTransaction.with(MangaController(intent.extras)))
SHORTCUT_DOWNLOADS -> {
if (router.backstack.none { it.controller() is DownloadController }) {
setSelectedDrawerItem(R.id.nav_drawer_downloads)
}
}
else -> return false
}
return true
}
override fun onDestroy() {
super.onDestroy()
nav_view?.setNavigationItemSelectedListener(null)
toolbar?.setNavigationOnClickListener(null)
}
override fun onBackPressed() {
val backstackSize = router.backstackSize
if (drawer.isDrawerOpen(GravityCompat.START) || drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawers()
} else if (backstackSize == 1 && router.getControllerWithTag("$startScreenId") == null) {
setSelectedDrawerItem(startScreenId)
} else if (backstackSize == 1 || !router.handleBack()) {
super.onBackPressed()
}
}
private fun setSelectedDrawerItem(itemId: Int) {
if (!isFinishing) {
nav_view.setCheckedItem(itemId)
nav_view.menu.performIdentifierAction(itemId, 0)
}
}
private fun setRoot(controller: Controller, id: Int) {
router.setRoot(controller.withFadeTransaction().tag(id.toString()))
}
private fun syncActivityViewWithController(to: Controller?, from: Controller? = null) {
if (from is DialogController || to is DialogController) {
return
}
val showHamburger = router.backstackSize == 1
if (showHamburger) {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
} else {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
}
ObjectAnimator.ofFloat(drawerArrow, "progress", if (showHamburger) 0f else 1f).start()
if (from is TabbedController) {
from.cleanupTabs(tabs)
}
if (to is TabbedController) {
tabAnimator.expand()
to.configureTabs(tabs)
} else {
tabAnimator.collapse()
tabs.setupWithViewPager(null)
}
if (from is SecondaryDrawerController) {
if (secondaryDrawer != null) {
from.cleanupSecondaryDrawer(drawer)
drawer.removeView(secondaryDrawer)
secondaryDrawer = null
}
}
if (to is SecondaryDrawerController) {
secondaryDrawer = to.createSecondaryDrawer(drawer)?.also { drawer.addView(it) }
}
if (to is NoToolbarElevationController) {
appbar.disableElevation()
} else {
appbar.enableElevation()
}
}
companion object {
// Shortcut actions
const val SHORTCUT_LIBRARY = "eu.kanade.tachiyomi.SHOW_LIBRARY"
const val SHORTCUT_RECENTLY_UPDATED = "eu.kanade.tachiyomi.SHOW_RECENTLY_UPDATED"
const val SHORTCUT_RECENTLY_READ = "eu.kanade.tachiyomi.SHOW_RECENTLY_READ"
const val SHORTCUT_CATALOGUES = "eu.kanade.tachiyomi.SHOW_CATALOGUES"
const val SHORTCUT_DOWNLOADS = "eu.kanade.tachiyomi.SHOW_DOWNLOADS"
const val SHORTCUT_MANGA = "eu.kanade.tachiyomi.SHOW_MANGA"
}
}
| apache-2.0 | 42213f1374aaadfd3cb5b6b6cda03642 | 36.078189 | 100 | 0.617421 | 4.895767 | false | false | false | false |
NoodleMage/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChaptersController.kt | 1 | 17686 | package eu.kanade.tachiyomi.ui.manga.chapter
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.view.ActionMode
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.view.*
import com.jakewharton.rxbinding.support.v4.widget.refreshes
import com.jakewharton.rxbinding.view.clicks
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.SelectableAdapter
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.ui.base.controller.NucleusController
import eu.kanade.tachiyomi.ui.base.controller.popControllerWithTag
import eu.kanade.tachiyomi.ui.manga.MangaController
import eu.kanade.tachiyomi.ui.reader.ReaderActivity
import eu.kanade.tachiyomi.util.getCoordinates
import eu.kanade.tachiyomi.util.snack
import eu.kanade.tachiyomi.util.toast
import kotlinx.android.synthetic.main.chapters_controller.*
import timber.log.Timber
class ChaptersController : NucleusController<ChaptersPresenter>(),
ActionMode.Callback,
FlexibleAdapter.OnItemClickListener,
FlexibleAdapter.OnItemLongClickListener,
ChaptersAdapter.OnMenuItemClickListener,
SetDisplayModeDialog.Listener,
SetSortingDialog.Listener,
DownloadChaptersDialog.Listener,
DownloadCustomChaptersDialog.Listener,
DeleteChaptersDialog.Listener {
/**
* Adapter containing a list of chapters.
*/
private var adapter: ChaptersAdapter? = null
/**
* Action mode for multiple selection.
*/
private var actionMode: ActionMode? = null
/**
* Selected items. Used to restore selections after a rotation.
*/
private val selectedItems = mutableSetOf<ChapterItem>()
init {
setHasOptionsMenu(true)
setOptionsMenuHidden(true)
}
override fun createPresenter(): ChaptersPresenter {
val ctrl = parentController as MangaController
return ChaptersPresenter(ctrl.manga!!, ctrl.source!!,
ctrl.chapterCountRelay, ctrl.lastUpdateRelay, ctrl.mangaFavoriteRelay)
}
override fun inflateView(inflater: LayoutInflater, container: ViewGroup): View {
return inflater.inflate(R.layout.chapters_controller, container, false)
}
override fun onViewCreated(view: View) {
super.onViewCreated(view)
// Init RecyclerView and adapter
adapter = ChaptersAdapter(this, view.context)
recycler.adapter = adapter
recycler.layoutManager = LinearLayoutManager(view.context)
recycler.addItemDecoration(DividerItemDecoration(view.context, DividerItemDecoration.VERTICAL))
recycler.setHasFixedSize(true)
adapter?.fastScroller = fast_scroller
swipe_refresh.refreshes().subscribeUntilDestroy { fetchChaptersFromSource() }
fab.clicks().subscribeUntilDestroy {
val item = presenter.getNextUnreadChapter()
if (item != null) {
// Create animation listener
val revealAnimationListener: Animator.AnimatorListener = object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator?) {
openChapter(item.chapter, true)
}
}
// Get coordinates and start animation
val coordinates = fab.getCoordinates()
if (!reveal_view.showRevealEffect(coordinates.x, coordinates.y, revealAnimationListener)) {
openChapter(item.chapter)
}
} else {
view.context.toast(R.string.no_next_chapter)
}
}
}
override fun onDestroyView(view: View) {
adapter = null
actionMode = null
super.onDestroyView(view)
}
override fun onActivityResumed(activity: Activity) {
if (view == null) return
// Check if animation view is visible
if (reveal_view.visibility == View.VISIBLE) {
// Show the unReveal effect
val coordinates = fab.getCoordinates()
reveal_view.hideRevealEffect(coordinates.x, coordinates.y, 1920)
}
super.onActivityResumed(activity)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.chapters, menu)
}
override fun onPrepareOptionsMenu(menu: Menu) {
// Initialize menu items.
val menuFilterRead = menu.findItem(R.id.action_filter_read) ?: return
val menuFilterUnread = menu.findItem(R.id.action_filter_unread)
val menuFilterDownloaded = menu.findItem(R.id.action_filter_downloaded)
val menuFilterBookmarked = menu.findItem(R.id.action_filter_bookmarked)
// Set correct checkbox values.
menuFilterRead.isChecked = presenter.onlyRead()
menuFilterUnread.isChecked = presenter.onlyUnread()
menuFilterDownloaded.isChecked = presenter.onlyDownloaded()
menuFilterBookmarked.isChecked = presenter.onlyBookmarked()
if (presenter.onlyRead())
//Disable unread filter option if read filter is enabled.
menuFilterUnread.isEnabled = false
if (presenter.onlyUnread())
//Disable read filter option if unread filter is enabled.
menuFilterRead.isEnabled = false
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_display_mode -> showDisplayModeDialog()
R.id.manga_download -> showDownloadDialog()
R.id.action_sorting_mode -> showSortingDialog()
R.id.action_filter_unread -> {
item.isChecked = !item.isChecked
presenter.setUnreadFilter(item.isChecked)
activity?.invalidateOptionsMenu()
}
R.id.action_filter_read -> {
item.isChecked = !item.isChecked
presenter.setReadFilter(item.isChecked)
activity?.invalidateOptionsMenu()
}
R.id.action_filter_downloaded -> {
item.isChecked = !item.isChecked
presenter.setDownloadedFilter(item.isChecked)
}
R.id.action_filter_bookmarked -> {
item.isChecked = !item.isChecked
presenter.setBookmarkedFilter(item.isChecked)
}
R.id.action_filter_empty -> {
presenter.removeFilters()
activity?.invalidateOptionsMenu()
}
R.id.action_sort -> presenter.revertSortOrder()
else -> return super.onOptionsItemSelected(item)
}
return true
}
fun onNextChapters(chapters: List<ChapterItem>) {
// If the list is empty, fetch chapters from source if the conditions are met
// We use presenter chapters instead because they are always unfiltered
if (presenter.chapters.isEmpty())
initialFetchChapters()
val adapter = adapter ?: return
adapter.updateDataSet(chapters)
if (selectedItems.isNotEmpty()) {
adapter.clearSelection() // we need to start from a clean state, index may have changed
createActionModeIfNeeded()
selectedItems.forEach { item ->
val position = adapter.indexOf(item)
if (position != -1 && !adapter.isSelected(position)) {
adapter.toggleSelection(position)
}
}
actionMode?.invalidate()
}
}
private fun initialFetchChapters() {
// Only fetch if this view is from the catalog and it hasn't requested previously
if ((parentController as MangaController).fromCatalogue && !presenter.hasRequested) {
fetchChaptersFromSource()
}
}
private fun fetchChaptersFromSource() {
swipe_refresh?.isRefreshing = true
presenter.fetchChaptersFromSource()
}
fun onFetchChaptersDone() {
swipe_refresh?.isRefreshing = false
}
fun onFetchChaptersError(error: Throwable) {
swipe_refresh?.isRefreshing = false
activity?.toast(error.message)
}
fun onChapterStatusChange(download: Download) {
getHolder(download.chapter)?.notifyStatus(download.status)
}
private fun getHolder(chapter: Chapter): ChapterHolder? {
return recycler?.findViewHolderForItemId(chapter.id!!) as? ChapterHolder
}
fun openChapter(chapter: Chapter, hasAnimation: Boolean = false) {
val activity = activity ?: return
val intent = ReaderActivity.newIntent(activity, presenter.manga, chapter)
if (hasAnimation) {
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
}
startActivity(intent)
}
override fun onItemClick(position: Int): Boolean {
val adapter = adapter ?: return false
val item = adapter.getItem(position) ?: return false
if (actionMode != null && adapter.mode == SelectableAdapter.Mode.MULTI) {
toggleSelection(position)
return true
} else {
openChapter(item.chapter)
return false
}
}
override fun onItemLongClick(position: Int) {
createActionModeIfNeeded()
toggleSelection(position)
}
// SELECTIONS & ACTION MODE
private fun toggleSelection(position: Int) {
val adapter = adapter ?: return
val item = adapter.getItem(position) ?: return
adapter.toggleSelection(position)
if (adapter.isSelected(position)) {
selectedItems.add(item)
} else {
selectedItems.remove(item)
}
actionMode?.invalidate()
}
private fun getSelectedChapters(): List<ChapterItem> {
val adapter = adapter ?: return emptyList()
return adapter.selectedPositions.mapNotNull { adapter.getItem(it) }
}
private fun createActionModeIfNeeded() {
if (actionMode == null) {
actionMode = (activity as? AppCompatActivity)?.startSupportActionMode(this)
}
}
private fun destroyActionModeIfNeeded() {
actionMode?.finish()
}
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.menuInflater.inflate(R.menu.chapter_selection, menu)
adapter?.mode = SelectableAdapter.Mode.MULTI
return true
}
@SuppressLint("StringFormatInvalid")
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
val count = adapter?.selectedItemCount ?: 0
if (count == 0) {
// Destroy action mode if there are no items selected.
destroyActionModeIfNeeded()
} else {
mode.title = resources?.getString(R.string.label_selected, count)
}
return false
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_select_all -> selectAll()
R.id.action_mark_as_read -> markAsRead(getSelectedChapters())
R.id.action_mark_as_unread -> markAsUnread(getSelectedChapters())
R.id.action_download -> downloadChapters(getSelectedChapters())
R.id.action_delete -> showDeleteChaptersConfirmationDialog()
else -> return false
}
return true
}
override fun onDestroyActionMode(mode: ActionMode) {
adapter?.mode = SelectableAdapter.Mode.SINGLE
adapter?.clearSelection()
selectedItems.clear()
actionMode = null
}
override fun onMenuItemClick(position: Int, item: MenuItem) {
val chapter = adapter?.getItem(position) ?: return
val chapters = listOf(chapter)
when (item.itemId) {
R.id.action_download -> downloadChapters(chapters)
R.id.action_bookmark -> bookmarkChapters(chapters, true)
R.id.action_remove_bookmark -> bookmarkChapters(chapters, false)
R.id.action_delete -> deleteChapters(chapters)
R.id.action_mark_as_read -> markAsRead(chapters)
R.id.action_mark_as_unread -> markAsUnread(chapters)
R.id.action_mark_previous_as_read -> markPreviousAsRead(chapter)
}
}
// SELECTION MODE ACTIONS
private fun selectAll() {
val adapter = adapter ?: return
adapter.selectAll()
selectedItems.addAll(adapter.items)
actionMode?.invalidate()
}
private fun markAsRead(chapters: List<ChapterItem>) {
presenter.markChaptersRead(chapters, true)
if (presenter.preferences.removeAfterMarkedAsRead()) {
deleteChapters(chapters)
}
}
private fun markAsUnread(chapters: List<ChapterItem>) {
presenter.markChaptersRead(chapters, false)
}
private fun downloadChapters(chapters: List<ChapterItem>) {
val view = view
destroyActionModeIfNeeded()
presenter.downloadChapters(chapters)
if (view != null && !presenter.manga.favorite) {
recycler?.snack(view.context.getString(R.string.snack_add_to_library), Snackbar.LENGTH_INDEFINITE) {
setAction(R.string.action_add) {
presenter.addToLibrary()
}
}
}
}
private fun showDeleteChaptersConfirmationDialog() {
DeleteChaptersDialog(this).showDialog(router)
}
override fun deleteChapters() {
deleteChapters(getSelectedChapters())
}
private fun markPreviousAsRead(chapter: ChapterItem) {
val adapter = adapter ?: return
val chapters = if (presenter.sortDescending()) adapter.items.reversed() else adapter.items
val chapterPos = chapters.indexOf(chapter)
if (chapterPos != -1) {
presenter.markChaptersRead(chapters.take(chapterPos), true)
}
}
private fun bookmarkChapters(chapters: List<ChapterItem>, bookmarked: Boolean) {
destroyActionModeIfNeeded()
presenter.bookmarkChapters(chapters, bookmarked)
}
fun deleteChapters(chapters: List<ChapterItem>) {
destroyActionModeIfNeeded()
if (chapters.isEmpty()) return
DeletingChaptersDialog().showDialog(router)
presenter.deleteChapters(chapters)
}
fun onChaptersDeleted() {
dismissDeletingDialog()
adapter?.notifyDataSetChanged()
}
fun onChaptersDeletedError(error: Throwable) {
dismissDeletingDialog()
Timber.e(error)
}
private fun dismissDeletingDialog() {
router.popControllerWithTag(DeletingChaptersDialog.TAG)
}
// OVERFLOW MENU DIALOGS
private fun showDisplayModeDialog() {
val preselected = if (presenter.manga.displayMode == Manga.DISPLAY_NAME) 0 else 1
SetDisplayModeDialog(this, preselected).showDialog(router)
}
override fun setDisplayMode(id: Int) {
presenter.setDisplayMode(id)
adapter?.notifyDataSetChanged()
}
private fun showSortingDialog() {
val preselected = if (presenter.manga.sorting == Manga.SORTING_SOURCE) 0 else 1
SetSortingDialog(this, preselected).showDialog(router)
}
override fun setSorting(id: Int) {
presenter.setSorting(id)
}
private fun showDownloadDialog() {
DownloadChaptersDialog(this).showDialog(router)
}
private fun getUnreadChaptersSorted() = presenter.chapters
.filter { !it.read && it.status == Download.NOT_DOWNLOADED }
.distinctBy { it.name }
.sortedByDescending { it.source_order }
override fun downloadCustomChapters(amount: Int) {
val chaptersToDownload = getUnreadChaptersSorted().take(amount)
if (chaptersToDownload.isNotEmpty()) {
downloadChapters(chaptersToDownload)
}
}
private fun showCustomDownloadDialog() {
DownloadCustomChaptersDialog(this, presenter.chapters.size).showDialog(router)
}
override fun downloadChapters(choice: Int) {
// i = 0: Download 1
// i = 1: Download 5
// i = 2: Download 10
// i = 3: Download x
// i = 4: Download unread
// i = 5: Download all
val chaptersToDownload = when (choice) {
0 -> getUnreadChaptersSorted().take(1)
1 -> getUnreadChaptersSorted().take(5)
2 -> getUnreadChaptersSorted().take(10)
3 -> {
showCustomDownloadDialog()
return
}
4 -> presenter.chapters.filter { !it.read }
5 -> presenter.chapters
else -> emptyList()
}
if (chaptersToDownload.isNotEmpty()) {
downloadChapters(chaptersToDownload)
}
}
}
| apache-2.0 | d54129b1a0b7a0079684beeb507d8ebd | 34.390947 | 112 | 0.628011 | 5.113038 | false | false | false | false |
Haldir65/AndroidRepo | app/src/main/java/com/me/harris/androidanimations/_36_fun_kt/KActivity.kt | 1 | 3960 | package com.me.harris.androidanimations._36_fun_kt
import android.database.sqlite.SQLiteDatabase
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import com.me.harris.androidanimations.BaseAppCompatActivity
import com.me.harris.androidanimations.R
import java.net.ServerSocket
import java.util.*
import kotlin.system.measureTimeMillis
/**
* Created by Harris on 2017/5/23.
*/
class KActivity : BaseAppCompatActivity() {
var mIvBeauty: View? = null
private val deleteByFirstName by lazy {
// lazy load
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.kt_main_activity)
mIvBeauty = findViewById(R.id.iv_beauty)
}
fun iteratingViewGroups(views: ViewGroup) {
// 1. verbose mode
for (index in 0 until views.childCount) {
val view = views.getChildAt(index)
}
// 2. more simplified version
views.forEach { view -> print("height is " + view.height) } // a much more simplify version
// 3. if wanna index , here they are
views.forEachIndexed { i, view -> print("child index at $i height is ${view.height}") }
}
inline fun ViewGroup.forEach(action: (View) -> Unit) {
for (index in 0 until childCount) {
action(getChildAt(`index`))
}
}
// inline keywords prevent anonymous inner class
inline fun ViewGroup.forEachIndexed(action: (Int, View) -> Unit) {
for (index in 0 until childCount) {
action(index, getChildAt(`index`))
}
}
fun tryOperatorFunction(v: ViewGroup) {
val views = v
val first = views[0] // retrieve the first child of a view
// add or remove a view like treating an collection
views += first
views -= first
// you can also use
views.plusAssign(first)
views.minusAssign(first)
if (first in views) doSomething()
// extension properities
print(views.size)
// pass some function to trace and expect some result
val result = trace("foo"){
doSomething()
}
}
fun doSomething() {
println("do someThing")
}
// this allowed you to manipulate viewGroups like collections
operator fun ViewGroup.get(index: Int): View = getChildAt(index)
operator fun ViewGroup.minusAssign(child: View) = removeView(child)
operator fun ViewGroup.plusAssign(child: View) = addView(child)
operator fun ViewGroup.contains(child: View) = indexOfChild(child) != -1
val ViewGroup.size: Int
get() = childCount
inline fun SQLiteDatabase.transaction(body: () -> Unit) {
beginTransaction()
try {
body()
setTransactionSuccessful()
}finally {
endTransaction()
}
}
inline fun SQLiteDatabase.transaction(body: (SQLiteDatabase) -> Unit) {
beginTransaction()
try {
body(this)
setTransactionSuccessful()
}finally {
endTransaction()
}
}
fun createDummyList() {
val list = listOf(1, 2, 3, 4, 5)
var ViewList = arrayListOf<String>()
ViewList.add("")
}
fun calTime() {
val startTime = System.currentTimeMillis()
print("HelloWorld")
val helloTook = System.currentTimeMillis() - startTime
print("Saying Hello took me ${helloTook}ms")
}
fun callTime() {
val mime = measureTimeMillis { print("hahha") }
print("Hello Took ${mime} ms")
}
fun joint(sep: String, strings: List<String>): String {
require(sep.length < 2) { "go eat shit!" }
return "sss"
}
fun runServer(serverSocket: ServerSocket) {
print("")
}
// extension functions
fun Date.isTuesDay(): Boolean {
return false
}
} | apache-2.0 | b78e05724a6791eb360af9c227586064 | 23.006061 | 99 | 0.609343 | 4.454443 | false | false | false | false |
angcyo/RLibrary | uiview/src/main/java/com/angcyo/uiview/viewgroup/SoftInputDialogContentLayout.kt | 1 | 2871 | package com.angcyo.uiview.viewgroup
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import com.angcyo.uiview.kotlin.exactlyMeasure
import java.lang.IllegalStateException
/**
* Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved.
* 项目名称:
* 类的描述:在对话框中, 弹出软键盘, 用来控制内容布局的显示. 当键盘没有弹出, 半屏幕显示; 键盘弹出, 全屏显示
* 创建人员:Robi
* 创建时间:2017/09/08 15:31
* 修改人员:Robi
* 修改时间:2017/09/08 15:31
* 修改备注:
* Version: 1.0.0
*/
open class SoftInputDialogContentLayout(context: Context, attributeSet: AttributeSet? = null) :
ViewGroup(context, attributeSet) {
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
if (childCount > 0) {
val view = getChildAt(0)
view.layout(0, measuredHeight - view.measuredHeight, measuredWidth, measuredHeight)
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var widthSize = MeasureSpec.getSize(widthMeasureSpec)
val widthMode = MeasureSpec.getMode(widthMeasureSpec)
var heightSize = MeasureSpec.getSize(heightMeasureSpec)
val heightMode = MeasureSpec.getMode(heightMeasureSpec)
if (childCount > 0) {
if (isSoftKeyboardShow()) {
getChildAt(0).measure(exactlyMeasure(widthSize), exactlyMeasure(heightSize - paddingTop))
} else {
getChildAt(0).measure(exactlyMeasure(widthSize), exactlyMeasure(heightSize / 2))
}
}
setMeasuredDimension(widthSize, heightSize)
}
override fun addView(child: View?, index: Int, params: ViewGroup.LayoutParams?) {
super.addView(child, index, params)
if (childCount > 1) {
throw IllegalStateException("只允许一个ChildView")
}
}
/**
* 判断键盘是否显示
*/
fun isSoftKeyboardShow(): Boolean {
val screenHeight = getScreenHeightPixels()
val keyboardHeight = getSoftKeyboardHeight()
return screenHeight != keyboardHeight && keyboardHeight > 100
}
/**
* 获取键盘的高度
*/
fun getSoftKeyboardHeight(): Int {
val screenHeight = getScreenHeightPixels()
val rect = Rect()
getWindowVisibleDisplayFrame(rect)
val visibleBottom = rect.bottom
return screenHeight - visibleBottom
}
/**
* 屏幕高度(不包含虚拟导航键盘的高度)
*/
private fun getScreenHeightPixels(): Int {
return resources.displayMetrics.heightPixels
}
} | apache-2.0 | 603df5522e364f3299226928b7f1ee49 | 29.939024 | 105 | 0.640428 | 4.332781 | false | false | false | false |
vanniktech/Emoji | emoji-google-compat/src/commonMain/kotlin/com/vanniktech/emoji/googlecompat/GoogleCompatEmoji.kt | 1 | 2247 | /*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.vanniktech.emoji.googlecompat
import com.vanniktech.emoji.Emoji
import com.vanniktech.emoji.IgnoredOnParcel
import com.vanniktech.emoji.Parcelable
import com.vanniktech.emoji.Parcelize
@Parcelize internal class GoogleCompatEmoji internal constructor(
override val unicode: String,
override val shortcodes: List<String>,
override val isDuplicate: Boolean,
override val variants: List<GoogleCompatEmoji> = emptyList(),
private var parent: GoogleCompatEmoji? = null,
) : Emoji, Parcelable {
@IgnoredOnParcel override val base by lazy(LazyThreadSafetyMode.NONE) {
var result = this
while (result.parent != null) {
result = result.parent!!
}
result
}
init {
@Suppress("LeakingThis")
for (variant in variants) {
variant.parent = this
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as GoogleCompatEmoji
if (unicode != other.unicode) return false
if (shortcodes != other.shortcodes) return false
if (isDuplicate != other.isDuplicate) return false
if (variants != other.variants) return false
return true
}
override fun toString(): String {
return "GoogleCompatEmoji(unicode='$unicode', shortcodes=$shortcodes, isDuplicate=$isDuplicate, variants=$variants)"
}
override fun hashCode(): Int {
var result = unicode.hashCode()
result = 31 * result + shortcodes.hashCode()
result = 31 * result + isDuplicate.hashCode()
result = 31 * result + variants.hashCode()
return result
}
}
| apache-2.0 | bcb509a384e2fae73b14b835a3765f81 | 30.619718 | 120 | 0.716258 | 4.34236 | false | false | false | false |
halawata13/ArtichForAndroid | app/src/main/java/net/halawata/artich/HatenaListFragment.kt | 2 | 5437 | package net.halawata.artich
import android.content.Intent
import android.graphics.PorterDuff
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v4.widget.SwipeRefreshLayout
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import net.halawata.artich.entity.HatenaArticle
import net.halawata.artich.enum.Media
import net.halawata.artich.model.ApiUrlString
import net.halawata.artich.model.ArticleListAdapter
import net.halawata.artich.model.Log
import net.halawata.artich.model.list.HatenaList
import java.net.HttpURLConnection
import java.net.URL
class HatenaListFragment : Fragment(), ListFragmentInterface {
override val list = HatenaList()
override var selectedTitle = "新着エントリー"
override var selectedUrlString = ApiUrlString.Hatena.newEntry
private var listView: ListView? = null
private var loadingView: RelativeLayout? = null
private var loadingText: TextView? = null
private var loadingProgress: ProgressBar? = null
private var adapter: ArticleListAdapter<HatenaArticle>? = null
private lateinit var listSwipeRefresh: SwipeRefreshLayout
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_list, container, false)
listView = view.findViewById(R.id.list) as ListView
loadingView = view.findViewById(R.id.loading_view) as RelativeLayout
loadingText = view.findViewById(R.id.loading_text) as TextView
loadingProgress = view.findViewById(R.id.loading_progress) as ProgressBar
loadingProgress?.indeterminateDrawable?.setColorFilter(ContextCompat.getColor(context!!, R.color.hatena), PorterDuff.Mode.SRC_IN)
val data = ArrayList<HatenaArticle>()
adapter = ArticleListAdapter(context!!, data, R.layout.article_list_item)
listView?.adapter = adapter
listView?.onItemClickListener = AdapterView.OnItemClickListener { parent, v, position, id ->
val urlString = (v.findViewById(R.id.url) as TextView).text as String
launchUrl(activity!!, context!!, urlString, R.color.hatena)
}
listView?.onItemLongClickListener = AdapterView.OnItemLongClickListener { parent, v, position, id ->
try {
val article = adapter?.data?.get(position) as HatenaArticle
val title = URL(article.url).host
val dialog = ArticleDialogFragment()
dialog.mediaType = Media.HATENA
dialog.title = title
dialog.article = article
dialog.setTargetFragment(this, 0)
dialog.show(fragmentManager, "articleDialog")
} catch (ex: Exception) {
Log.e(ex.message)
}
true
}
// SwipeRefreshLayout setup
listSwipeRefresh = view.findViewById(R.id.list_swipe_refresh) as SwipeRefreshLayout
listSwipeRefresh.setOnRefreshListener {
reload(false)
}
reload()
return view
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
applyFilter()
}
override fun reserve(urlString: String, title: String) {
selectedUrlString = urlString
selectedTitle = title
}
override fun update(urlString: String, title: String, useCache: Boolean) {
activity ?: return
selectedTitle = title
selectedUrlString = urlString
loadingView?.alpha = 1F
loadingText?.text = resources.getString(R.string.loading)
request(urlString, title, { responseCode, content ->
var articles = ArrayList<HatenaArticle>()
content?.let {
when (responseCode) {
HttpURLConnection.HTTP_OK -> {
list.parse(content)?.let {
articles = list.filter(it, activity!!)
if (articles.count() > 0) {
loadingView?.alpha = 0F
} else {
loadingText?.text = resources.getString(R.string.loading_not_found)
}
}
}
HttpURLConnection.HTTP_NOT_FOUND -> {
loadingText?.text = resources.getString(R.string.loading_not_found)
}
else -> {
loadingText?.text = resources.getString(R.string.loading_fail)
}
}
} ?: run {
loadingText?.text = resources.getString(R.string.loading_fail)
}
if (articles.count() == 0) {
loadingProgress?.visibility = View.INVISIBLE
}
adapter?.data = articles
listView?.adapter = adapter
listSwipeRefresh.isRefreshing = false
}, useCache)
}
override fun applyFilter() {
adapter?.let {
adapter?.data = list.filter(it.data, activity!!)
adapter?.notifyDataSetChanged()
}
}
override fun reload(useCache: Boolean) {
update(selectedUrlString, selectedTitle, useCache)
}
}
| mit | 4f06559848d63f2c65e43e409e5f0465 | 34.677632 | 137 | 0.620321 | 4.984375 | false | false | false | false |
Kiskae/Twitch-Archiver | twitch/src/main/kotlin/net/serverpeon/twitcharchiver/twitch/OAuthHelper.kt | 1 | 1770 | package net.serverpeon.twitcharchiver.twitch
import com.google.common.base.Joiner
import okhttp3.HttpUrl
import java.net.URLDecoder
object OAuthHelper {
private val AUTH_URL: HttpUrl = HttpUrl.parse("https://api.twitch.tv/kraken/oauth2/authorize?response_type=token&force_verify=true")
private val STATE_PARAM = "state"
fun authenticationUrl(redirectUri: HttpUrl, scope: List<String>, state: String): HttpUrl {
return AUTH_URL.newBuilder()
.addQueryParameter("client_id", TwitchApi.TWITCH_CLIENT_ID)
.addQueryParameter("redirect_uri", redirectUri.toString())
.addQueryParameter("scope", Joiner.on(' ').join(scope))
.addQueryParameter(STATE_PARAM, state)
.build()
}
fun extractAccessToken(redirectedUrl: String, expectedState: String): String {
val fragment = HttpUrl.parse(redirectedUrl)?.encodedFragment() ?: throw IllegalStateException("Invalid URL")
// Very basic URL decoder for the fragment
val response = fragment.splitToSequence('&').associateTo(mutableMapOf<String, String?>()) { part ->
val parts = part.split('=', limit = 2)
when (parts.size) {
1 -> Pair(parts[0], null)
2 -> Pair(parts[0], URLDecoder.decode(parts[1], "UTF-8"))
else -> error("limit = 2 doesn't work?")
}
}
val state = checkNotNull(response[STATE_PARAM]) {
"Failed to include a valid state"
}
check(expectedState == state) {
"Unexpected state; expected: $expectedState, got: $state"
}
return checkNotNull(response["access_token"]) {
"Failed to include an access token"
}
}
} | mit | 2ebc1d7c4768bc96cf7049619417ca3f | 39.25 | 136 | 0.617514 | 4.538462 | false | false | false | false |
mayuki/AgqrPlayer4Tv | AgqrPlayer4Tv/app/src/main/java/org/misuzilla/agqrplayer4tv/model/UpdateRecommendation.kt | 1 | 9682 | package org.misuzilla.agqrplayer4tv.model
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.*
import android.graphics.drawable.VectorDrawable
import android.support.v4.content.ContextCompat
import android.text.Layout
import android.text.StaticLayout
import android.text.TextPaint
import android.util.Log
import com.microsoft.appcenter.analytics.Analytics
import com.squareup.picasso.Picasso
import com.squareup.picasso.Transformation
import org.misuzilla.agqrplayer4tv.R
import org.misuzilla.agqrplayer4tv.component.activity.MainActivity
import org.misuzilla.agqrplayer4tv.component.activity.PlayConfirmationActivity
import org.misuzilla.agqrplayer4tv.infrastracture.OkHttpClientHelper
import org.misuzilla.agqrplayer4tv.infrastracture.extension.*
import org.misuzilla.agqrplayer4tv.model.preference.ApplicationPreference
import rx.Completable
import rx.Observable
import rx.Single
class UpdateRecommendation(private val context: Context) {
/**
* 番組とそのタイトル画像のマッピングファイルを取得、解析します。
*/
fun getProgramImageMappingAsync(): Single<Map<String, String>> {
val imageMappingUrl = context.resources.getString(R.string.url_image_mapping)
val client = OkHttpClientHelper.create(context)
return client.get(imageMappingUrl).enqueueAndToSingle()
.map { it.body().string() }
.onErrorResumeNext {
Analytics.trackEvent("Exception", mapOf("caller" to "UpdateRecommendation.getProgramImageMappingAsync", "name" to it.javaClass.name, "message" to it.message.toString()))
Single.just("")
}
.map {
// カンマ区切りファイルを雑にパースする
it.split('\n')
.map { it.trim() }
.filter { !it.startsWith("#") }
.filter { !it.isNullOrBlank() }
.map { it.split(',') }
.filter { it.size >= 3 }
.flatMap { listOf(Pair(it[0], it[2]), Pair(if (it[1].isNullOrBlank()) it[0] + "-EmailAddress" else it[1], it[2])) } // メールアドレスがないとき用に適当に返す
.toMap()
}
.cache()
}
/**
* タイムテーブルの更新 & マッピングの取得、その後画像も取得
*/
fun getCurrentAndNextProgramAndIcon(timetable: Timetable): Single<List<ProgramWithIcon>> {
val mappingTask = this.getProgramImageMappingAsync()
return Single.zip(timetable.getDatasetAsync(), mappingTask, { l, r -> l })
.flatMap { timetableDataset ->
val now = LogicalDateTime.now
// 現在と次の番組を取得する
val currentAndNext = timetableDataset.data[now.dayOfWeek]!!.filter { it.end >= now.time }.take(2)
// マッピングから画像を取得する
currentAndNext.map { program ->
getCardImageFromProgramAsync(mappingTask, program).map { ProgramWithIcon(program, it) }
}.whenAll()
}
}
fun getCardImageFromProgramAsync(mappingTask: Single<Map<String, String>>, program: TimetableProgram): Single<Bitmap> {
val width = context.resources.displayMetrics.toDevicePixel(context.resources.getDimension(R.dimen.recommendation_empty_width))
val height = context.resources.displayMetrics.toDevicePixel(context.resources.getDimension(R.dimen.recommendation_empty_height))
return mappingTask
.flatMap {
when {
it.containsKey(program.mailAddress) -> Picasso.with(context).load(it[program.mailAddress]).centerInside().resize(width, height).toSingle()
it.containsKey(program.title) -> Picasso.with(context).load(it[program.title]).centerInside().resize(width, height).toSingle()
else -> Single.just(createNotificationImageFromText(program))
}
}
.onErrorReturn {
Log.e(TAG, it.message, it)
createNotificationImageFromText(program)
}
.map { bitmap ->
if (Reservation.instance.isScheduled(program)) {
val newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(newBitmap)
canvas.drawBitmap(bitmap, (width - bitmap.width) / 2f, (height - bitmap.height) / 2f, Paint())
(ContextCompat.getDrawable(context, R.drawable.ic_timer_white) as VectorDrawable).let {
it.bounds = Rect(16, 16, 128 + 16, 128 + 16)
canvas.drawPath(
Path().apply {
moveTo(0f, 0f)
lineTo(0f, it.bounds.height() * 2f)
lineTo(it.bounds.width() * 2f, 0f)
close()
},
Paint().apply {
color = ContextCompat.getColor(context, R.color.accent_dark)
style = Paint.Style.FILL
}
)
it.draw(canvas)
}
newBitmap
} else {
bitmap
}
}
.cache()
}
private fun createNotificationImageFromText(program: TimetableProgram): Bitmap {
val colorAccent = ContextCompat.getColor(context, R.color.accent)
val colorAccentDark = ContextCompat.getColor(context, R.color.accent_dark)
val width = context.resources.displayMetrics.toDevicePixel(context.resources.getDimension(R.dimen.recommendation_empty_width))
val height = context.resources.displayMetrics.toDevicePixel(context.resources.getDimension(R.dimen.recommendation_empty_height))
val textSizeRec = context.resources.displayMetrics.toDevicePixel(context.resources.getDimension(R.dimen.recommendation_text_size))
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val paint = Paint().apply {
textSize = textSizeRec.toFloat()
color = Color.WHITE
isAntiAlias = true
}
val textPaint = TextPaint().apply {
textSize = textSizeRec.toFloat()
color = Color.WHITE
isAntiAlias = true
}
val canvas = Canvas(bitmap)
canvas.save()
// Fill: background rectangle
paint.color = colorAccent
canvas.drawRect(0f, 0f, bitmap.width.toFloat(), bitmap.height.toFloat(), paint)
// Draw: Program title
paint.color = Color.WHITE
val textWidth = paint.measureText(program.title)
val margin = 16f
val textLayout = StaticLayout(program.title, textPaint, canvas.width - (margin.toInt() * 2), Layout.Alignment.ALIGN_CENTER, 1f, 0f, false)
canvas.translate(margin, (canvas.height / 2f) - (textLayout.height / 2f))
textLayout.draw(canvas)
canvas.restore()
return bitmap
}
/**
* プログラムとそのアイコン(大きな画像)のセットです。
*/
class ProgramWithIcon(val program: TimetableProgram, val icon: Bitmap) {
/**
* 通知用のオブジェクトを生成します。
*/
fun createNotification(context: Context): Notification {
val colorAccentDark = ContextCompat.getColor(context, R.color.accent_dark)
val isNowPlaying = program.isPlaying
// 現在放送中かどうかで起動するものが違う
val intent = if (isNowPlaying) {
Intent(context, MainActivity::class.java)
} else {
PlayConfirmationActivity.createIntent(context, program, true)
}
val builder = Notification.Builder(context)
.setContentTitle(program.title)
.setContentText(
if (isNowPlaying)
String.format(context.resources.getString(R.string.recommendation_current), program.end.toShortString())
else
String.format(context.resources.getString(R.string.recommendation_upcoming), program.start.toShortString())
)
.setPriority(if (isNowPlaying) Notification.PRIORITY_MAX else Notification.PRIORITY_DEFAULT)
.setLocalOnly(true)
.setOngoing(true)
.setCategory(Notification.CATEGORY_RECOMMENDATION)
.setLargeIcon(icon)
.setSmallIcon(R.mipmap.small_icon)
.setContentIntent(PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT))
.setColor(colorAccentDark)
val builderBigPicture = Notification.BigPictureStyle()
builderBigPicture.setBuilder(builder)
return builder.build()
}
}
companion object {
const val TAG = "UpdateRecommendation"
}
} | mit | fe9cc8b372e2e4bbe1e51c9edebf962a | 43.8125 | 189 | 0.578863 | 4.77459 | false | false | false | false |
Kotlin/dokka | plugins/base/src/test/kotlin/transformers/SourceLinkTransformerTest.kt | 1 | 2331 | package transformers
import org.jetbrains.dokka.SourceLinkDefinitionImpl
import org.jetbrains.dokka.base.testApi.testRunner.BaseAbstractTest
import org.junit.jupiter.api.Test
import signatures.renderedContent
import utils.TestOutputWriterPlugin
import java.net.URL
import kotlin.test.assertEquals
import org.jsoup.nodes.Element
class SourceLinkTransformerTest : BaseAbstractTest() {
private fun Element.getSourceLink() = select(".symbol .floating-right")
.select("a[href]")
.attr("href")
@Test
fun `source link should lead to name`() {
val configuration = dokkaConfiguration {
sourceSets {
sourceSet {
sourceRoots = listOf("src/")
sourceLinks = listOf(
SourceLinkDefinitionImpl(
localDirectory = "src/main/kotlin",
remoteUrl = URL("https://github.com/user/repo/tree/master/src/main/kotlin"),
remoteLineSuffix = "#L"
)
)
}
}
}
val writerPlugin = TestOutputWriterPlugin()
testInline(
"""
|/src/main/kotlin/basic/Deprecated.kt
|package testpackage
|
|/**
|* Marks the annotated declaration as deprecated. ...
|*/
|@Target(CLASS, FUNCTION, PROPERTY, ANNOTATION_CLASS, CONSTRUCTOR, PROPERTY_SETTER, PROPERTY_GETTER, TYPEALIAS)
|@MustBeDocumented
|public annotation class Deprecated(
| val message: String,
| val replaceWith: ReplaceWith = ReplaceWith(""),
| val level: DeprecationLevel = DeprecationLevel.WARNING
|)
""".trimMargin(),
configuration,
pluginOverrides = listOf(writerPlugin)
) {
renderingStage = { _, _ ->
val page = writerPlugin.writer.renderedContent("root/testpackage/-deprecated/index.html")
val sourceLink = page.getSourceLink()
assertEquals(
"https://github.com/user/repo/tree/master/src/main/kotlin/basic/Deprecated.kt#L8",
sourceLink
)
}
}
}
} | apache-2.0 | f08391834858d09ef341f995e179c27c | 33.80597 | 123 | 0.552124 | 5.433566 | false | true | false | false |
Commit451/LabCoat | buildSrc/src/main/kotlin/BuildHelper.kt | 2 | 1512 | import org.gradle.api.Project
import java.io.File
@Suppress("MemberVisibilityCanBePrivate")
object BuildHelper {
private var locatedFile: Boolean? = null
fun appVersionName(): String {
return "2.7.4"
}
fun appVersionCode(): Int {
val parts = appVersionName().split(".")
val versionMajor = parts[0].toInt()
val versionMinor = parts[1].toInt()
val versionPatch = parts[2].toInt()
// this is something I got from u2020 a while back... meh
return versionMajor * 1000000 + versionMinor * 10000 + versionPatch * 100
}
fun firebaseEnabled(project: Project): Boolean {
return fileExists(project)
}
fun keystoreFile(project: Project): File {
return project.file("${project.rootDir}/app/${project.propertyOrEmpty("KEYSTORE_NAME")}")
}
private fun fileExists(project: Project): Boolean {
val located = locatedFile
return if (located != null) {
located
} else {
val fileExists = project.file("${project.rootDir}/app/google-services.json").exists()
locatedFile = fileExists
printFirebase()
fileExists
}
}
private fun printFirebase() {
println(
"""
/ _(_) | |
| |_ _ _ __ ___| |__ __ _ ___ ___
| _| | '__/ _ \ '_ \ / _` / __|/ _ \
| | | | | | __/ |_) | (_| \__ \ __/
|_| |_|_| \___|_.__/ \__,_|___/\___|
enabled
""".trimIndent()
)
}
}
| apache-2.0 | 231e837d630d6fb645571648211c08bc | 26 | 97 | 0.52381 | 4.165289 | false | false | false | false |
chrisbanes/tivi | common/imageloading/src/main/java/app/tivi/common/imageloading/EpisodeEntityCoilInterceptor.kt | 1 | 1896 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.common.imageloading
import app.tivi.data.entities.Episode
import app.tivi.tmdb.TmdbImageUrlProvider
import coil.annotation.ExperimentalCoilApi
import coil.intercept.Interceptor
import coil.request.ImageResult
import coil.size.Size
import coil.size.pxOrElse
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import javax.inject.Inject
import javax.inject.Provider
@ExperimentalCoilApi
class EpisodeEntityCoilInterceptor @Inject constructor(
private val tmdbImageUrlProvider: Provider<TmdbImageUrlProvider>
) : Interceptor {
override suspend fun intercept(chain: Interceptor.Chain): ImageResult {
val data = chain.request.data
val request = when {
data is Episode && handles(data) -> {
chain.request.newBuilder()
.data(map(data, chain.size))
.build()
}
else -> chain.request
}
return chain.proceed(request)
}
private fun handles(data: Episode): Boolean = data.tmdbBackdropPath != null
private fun map(data: Episode, size: Size): HttpUrl {
return tmdbImageUrlProvider.get().getBackdropUrl(
path = data.tmdbBackdropPath!!,
imageWidth = size.width.pxOrElse { 0 }
).toHttpUrl()
}
}
| apache-2.0 | b60a759a969570f21dc9a31ae3e17c13 | 32.857143 | 79 | 0.701477 | 4.409302 | false | false | false | false |
wuseal/JsonToKotlinClass | src/test/kotlin/wu/seal/jsontokotlin/ConfigManagerTestHelper.kt | 1 | 3524 | package wu.seal.jsontokotlin
import org.junit.Before
import org.junit.Test
import wu.seal.jsontokotlin.model.ConfigManager
import wu.seal.jsontokotlin.model.DefaultValueStrategy
import wu.seal.jsontokotlin.model.PropertyTypeStrategy
import wu.seal.jsontokotlin.model.TargetJsonConverter
import wu.seal.jsontokotlin.test.TestConfig
import kotlin.reflect.KMutableProperty0
class ConfigManagerTestHelper {
@Before
fun before() {
TestConfig.setToTestInitState()
}
fun testAllConfigWithAction(action: () -> Unit) {
testAllBoolConfigsWithAction {
testAllNoBoolConfigWithAction {
action()
}
}
}
fun testAllBoolConfigsWithAction(action: () -> Unit) {
traverseBoolConfigOnAction(ConfigManager::enableMapType) {
traverseBoolConfigOnAction(ConfigManager::enableMinimalAnnotation) {
traverseBoolConfigOnAction(ConfigManager::isCommentOff) {
traverseBoolConfigOnAction(ConfigManager::isInnerClassModel) {
traverseBoolConfigOnAction(ConfigManager::isPropertiesVar) {
traverseBoolConfigOnAction(ConfigManager::autoDetectJsonScheme) {
action()
}
}
}
}
}
}
}
private fun testAllNoBoolConfigWithAction(action: () -> Unit) {
traverseConfigOnAction(ConfigManager::indent, listOf(2,4,8)){
traverseConfigOnAction(ConfigManager::propertyTypeStrategy, PropertyTypeStrategy.values().toList()){
traverseConfigOnAction(ConfigManager::targetJsonConverterLib, TargetJsonConverter.values().toList()){
traverseConfigOnAction(ConfigManager::defaultValueStrategy, DefaultValueStrategy.values().toList()) {
action()
}
}
}
}
}
private fun traverseBoolConfigOnAction(boolConfig: KMutableProperty0<Boolean>, action: () -> Unit) {
traverseConfigOnAction(boolConfig, listOf(true, false), action)
}
private fun <R> traverseConfigOnAction(config: KMutableProperty0<R>, configAbleValues: List<R>, action: () -> Unit) {
configAbleValues.forEach {
config.set(it)
action()
}
}
var color = false
var weight = false
@Test
fun testTraverseBoolConfigOnAction() {
traverseBoolConfigOnAction(::color) {
traverseBoolConfigOnAction(::weight) {
val print = buildString {
if (color) {
append("color")
}
if (weight) {
append("weight")
}
}
println(print)
}
}
}
@Test
fun testIncludeAction() {
var action = { println("action") }
action = combineActions(action, {
println("Contianer")
})
action.invoke()
}
@Test
fun testIncludeRunable() {
val runable = Runnable { println("runable") }
val runable1 = Runnable {
println("Container runable")
runable.run()
}
runable1.run()
}
fun combineActions(vararg actions: () -> Unit): () -> Unit {
return {
actions.forEach { it.invoke() }
}
}
}
| gpl-3.0 | 6d8f1db7bc010fe6064da5f397ea6bae | 28.613445 | 121 | 0.563564 | 5.144526 | false | true | false | false |
square/moshi | moshi-kotlin-codegen/src/main/java/com/squareup/moshi/kotlin/codegen/ksp/MoshiApiUtil.kt | 1 | 3296 | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.moshi.kotlin.codegen.ksp
import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSDeclaration
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.moshi.JsonQualifier
import com.squareup.moshi.kotlin.codegen.api.DelegateKey
import com.squareup.moshi.kotlin.codegen.api.PropertyGenerator
import com.squareup.moshi.kotlin.codegen.api.TargetProperty
import com.squareup.moshi.kotlin.codegen.api.rawType
private val TargetProperty.isSettable get() = propertySpec.mutable || parameter != null
private val TargetProperty.isVisible: Boolean
get() {
return visibility == KModifier.INTERNAL ||
visibility == KModifier.PROTECTED ||
visibility == KModifier.PUBLIC
}
/**
* Returns a generator for this property, or null if either there is an error and this property
* cannot be used with code gen, or if no codegen is necessary for this property.
*/
internal fun TargetProperty.generator(
logger: KSPLogger,
resolver: Resolver,
originalType: KSDeclaration,
): PropertyGenerator? {
if (jsonIgnore) {
if (!hasDefault) {
logger.error(
"No default value for transient/ignored property $name",
originalType
)
return null
}
return PropertyGenerator(this, DelegateKey(type, emptyList()), true)
}
if (!isVisible) {
logger.error(
"property $name is not visible",
originalType
)
return null
}
if (!isSettable) {
return null // This property is not settable. Ignore it.
}
// Merge parameter and property annotations
val qualifiers = parameter?.qualifiers.orEmpty() + propertySpec.annotations
for (jsonQualifier in qualifiers) {
val qualifierRawType = jsonQualifier.typeName.rawType()
// Check Java types since that covers both Java and Kotlin annotations.
resolver.getClassDeclarationByName(qualifierRawType.canonicalName)?.let { annotationElement ->
annotationElement.findAnnotationWithType<Retention>()?.let {
if (it.value != AnnotationRetention.RUNTIME) {
logger.error(
"JsonQualifier @${qualifierRawType.simpleName} must have RUNTIME retention"
)
}
}
}
}
val jsonQualifierSpecs = qualifiers.map {
it.toBuilder()
.useSiteTarget(AnnotationSpec.UseSiteTarget.FIELD)
.build()
}
return PropertyGenerator(
this,
DelegateKey(type, jsonQualifierSpecs)
)
}
internal val KSClassDeclaration.isJsonQualifier: Boolean
get() = isAnnotationPresent(JsonQualifier::class)
| apache-2.0 | 7783de3783b03763a1489d373b2c4d8f | 32.292929 | 98 | 0.73301 | 4.400534 | false | false | false | false |
GabrielGouv/Android-Customizable-Buttons | CustomizableButtonsModule/src/main/java/com/github/gabrielgouv/customizablebuttons/BaseButton.kt | 1 | 1228 | package com.github.gabrielgouv.customizablebuttons
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.support.v7.widget.AppCompatButton
import android.util.AttributeSet
abstract class BaseButton : AppCompatButton {
protected var mContext: Context
protected var mAttrs: AttributeSet?
protected var mDefStyleAttr: Int? = 0
constructor(context: Context) : super(context) {
mContext = context
mAttrs = null
this.initButton()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
mContext = context
mAttrs = attrs
this.initButton()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
mContext = context
mAttrs = attrs
mDefStyleAttr = defStyleAttr
this.initButton()
}
protected abstract fun initButton()
protected fun setButtonBackground(drawable: Drawable) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
this.background = drawable
} else {
this.setBackgroundDrawable(drawable)
}
}
} | mit | 6fabe4a9755cf5ad44fc1f85b4384719 | 25.717391 | 113 | 0.679153 | 4.599251 | false | false | false | false |
alashow/music-android | modules/data/src/main/java/tm/alashow/datmusic/data/repos/search/DatmusicSearchPagingSource.kt | 1 | 1642 | /*
* Copyright (C) 2021, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.datmusic.data.repos.search
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.dropbox.android.external.store4.get
import tm.alashow.datmusic.data.interactors.SearchDatmusic
import tm.alashow.datmusic.data.repos.DATMUSIC_FIRST_PAGE_INDEX
import tm.alashow.domain.models.PaginatedEntity
/**
* Uses [DatmusicSearchStore] to paginate in-memory items that were already fetched via [SearchDatmusic].
* Not being used anymore, keeping just for reference.
*/
class DatmusicSearchPagingSource<T : PaginatedEntity>(
private val datmusicSearchStore: DatmusicSearchStore<T>,
private val searchParams: DatmusicSearchParams
) : PagingSource<Int, T>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, T> {
val page = params.key ?: DATMUSIC_FIRST_PAGE_INDEX
return try {
val items = datmusicSearchStore.get(searchParams.copy(page = page))
LoadResult.Page(
data = items,
prevKey = if (page == DATMUSIC_FIRST_PAGE_INDEX) null else page - 1,
nextKey = if (items.isEmpty()) null else page + 1
)
} catch (exception: Exception) {
return LoadResult.Error(exception)
}
}
override fun getRefreshKey(state: PagingState<Int, T>): Int? {
return state.anchorPosition?.let { anchorPosition ->
state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
}
}
}
| apache-2.0 | 99f73374988207f9f4a67ed91f02d810 | 36.318182 | 105 | 0.684531 | 4.242894 | false | false | false | false |
caiorrs/FastHub | app/src/main/java/com/fastaccess/ui/modules/editor/emoji/EmojiBottomSheet.kt | 5 | 2622 | package com.fastaccess.ui.modules.editor.emoji
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.view.View
import butterknife.BindView
import butterknife.OnTextChanged
import com.fastaccess.R
import com.fastaccess.provider.emoji.Emoji
import com.fastaccess.ui.adapter.EmojiAdapter
import com.fastaccess.ui.base.BaseMvpBottomSheetDialogFragment
import com.fastaccess.ui.widgets.recyclerview.DynamicRecyclerView
import com.fastaccess.ui.widgets.recyclerview.layout_manager.GridManager
import com.fastaccess.ui.widgets.recyclerview.scroll.RecyclerViewFastScroller
/**
* Created by kosh on 17/08/2017.
*/
class EmojiBottomSheet : BaseMvpBottomSheetDialogFragment<EmojiMvp.View, EmojiPresenter>(), EmojiMvp.View {
@BindView(R.id.recycler) lateinit var recycler: DynamicRecyclerView
@BindView(R.id.fastScroller) lateinit var fastScroller: RecyclerViewFastScroller
val adapter: EmojiAdapter by lazy { EmojiAdapter(this) }
var emojiCallback: EmojiMvp.EmojiCallback? = null
@OnTextChanged(value = [(R.id.editText)], callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
fun onTextChange(text: Editable) {
adapter.filter.filter(text)
}
override fun onAttach(context: Context) {
super.onAttach(context)
emojiCallback = when {
parentFragment is EmojiMvp.EmojiCallback -> parentFragment as EmojiMvp.EmojiCallback
context is EmojiMvp.EmojiCallback -> context
else -> throw IllegalArgumentException("${context.javaClass.simpleName} must implement EmojiMvp.EmojiCallback")
}
}
override fun onDetach() {
emojiCallback = null
super.onDetach()
}
override fun fragmentLayout(): Int = R.layout.emoji_popup_layout
override fun providePresenter(): EmojiPresenter = EmojiPresenter()
override fun clearAdapter() {
adapter.clear()
}
override fun onAddEmoji(emoji: Emoji) {
adapter.addItem(emoji)
}
override fun onItemClick(position: Int, v: View?, item: Emoji) {
emojiCallback?.onEmojiAdded(item)
dismiss()
}
override fun onItemLongClick(position: Int, v: View?, item: Emoji?) {}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recycler.adapter = adapter
fastScroller.attachRecyclerView(recycler)
presenter.onLoadEmoji()
val gridManager = recycler.layoutManager as GridManager
gridManager.iconSize = resources.getDimensionPixelSize(R.dimen.header_icon_zie)
}
} | gpl-3.0 | 64d49aef0757f26cc381aae25fcb1a77 | 33.513158 | 123 | 0.734554 | 4.616197 | false | false | false | false |
mixitconf/mixit | src/main/kotlin/mixit/event/model/EventService.kt | 1 | 4182 | package mixit.event.model
import kotlinx.coroutines.reactor.awaitSingle
import mixit.MixitApplication.Companion.speakerStarInCurrentEvent
import mixit.MixitApplication.Companion.speakerStarInHistory
import mixit.event.repository.EventRepository
import mixit.user.model.CachedOrganization
import mixit.user.model.CachedSpeaker
import mixit.user.model.CachedSponsor
import mixit.user.model.CachedStaff
import mixit.user.model.User
import mixit.user.model.UserService
import mixit.user.model.UserUpdateEvent
import mixit.util.cache.CacheTemplate
import mixit.util.cache.CacheZone
import org.springframework.context.event.EventListener
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.kotlin.core.publisher.switchIfEmpty
import java.time.Duration
@Service
class EventService(
private val repository: EventRepository,
private val userService: UserService
) : CacheTemplate<CachedEvent>() {
override val cacheZone: CacheZone = CacheZone.EVENT
override fun findAll(): Mono<List<CachedEvent>> =
findAll { repository.findAll().flatMap { event -> loadEventUsers(event) }.collectList() }
suspend fun coFindAll(): List<CachedEvent> =
findAll().awaitSingle()
fun findByYear(year: Int): Mono<CachedEvent> =
findAll().map { events -> events.first { it.year == year } }
suspend fun coFindByYear(year: Int): CachedEvent =
findByYear(year).awaitSingle()
fun save(event: Event) =
repository.save(event).doOnSuccess { cache.invalidateAll() }
@EventListener
fun handleUserUpdate(userUpdateEvent: UserUpdateEvent) {
findAll()
.switchIfEmpty { Mono.just(emptyList()) }
.map { events ->
events.any { event ->
event.organizations.map { it.login }.contains(userUpdateEvent.user.login)
event.volunteers.map { it.login }.contains(userUpdateEvent.user.login)
event.sponsors.map { it.login }.contains(userUpdateEvent.user.login)
}
}
.switchIfEmpty { Mono.just(true) }
.block(Duration.ofSeconds(10))
.also {
if (it != null && it) {
invalidateCache()
}
}
}
private fun loadEventUsers(event: Event): Mono<CachedEvent> {
val userIds = event.organizations.map { it.organizationLogin } +
event.sponsors.map { it.sponsorId } +
event.volunteers.map { it.volunteerLogin } +
speakerStarInHistory.map { it.login } +
speakerStarInCurrentEvent.map { it.login }
return userService.findAllByIds(userIds).map { users ->
CachedEvent(
event.id,
event.start,
event.end,
event.current,
event.sponsors.map { eventSponsoring ->
val sponsor = users.firstOrNull { it.login == eventSponsoring.sponsorId }
CachedSponsor(sponsor?.toUser() ?: User(), eventSponsoring)
},
event.organizations.map { orga ->
val user = users.firstOrNull { it.login == orga.organizationLogin }
CachedOrganization(user?.toUser() ?: User())
},
event.volunteers.map { volunteer ->
val user = users.firstOrNull { it.login == volunteer.volunteerLogin }
CachedStaff(user?.toUser() ?: User())
},
event.photoUrls,
event.videoUrl,
event.schedulingFileUrl,
speakerStarInHistory.map { starLogin ->
val user = users.firstOrNull { it.login == starLogin.login }?.toUser() ?: User()
CachedSpeaker(user, starLogin.year)
},
speakerStarInCurrentEvent.map { starLogin ->
val user = users.firstOrNull { it.login == starLogin.login }?.toUser() ?: User()
CachedSpeaker(user, starLogin.year)
},
event.year
)
}
}
}
| apache-2.0 | 25e3eae4acd59eab87e1b38ec1ceae29 | 38.828571 | 100 | 0.607365 | 4.746879 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/view/activity/ConversationRequestActivity.kt | 1 | 4172 | /*
* Copyright (c) 2017. Toshi Inc
*
* 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.toshi.view.activity
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import com.toshi.R
import com.toshi.extensions.addHorizontalLineDivider
import com.toshi.extensions.isEmpty
import com.toshi.extensions.startActivityAndFinish
import com.toshi.model.local.Conversation
import com.toshi.model.local.User
import com.toshi.view.adapter.ConversationRequestAdapter
import com.toshi.viewModel.ConversationRequestViewModel
import kotlinx.android.synthetic.main.activity_conversation_request.closeButton
import kotlinx.android.synthetic.main.activity_conversation_request.requests
class ConversationRequestActivity : AppCompatActivity() {
private lateinit var viewModel: ConversationRequestViewModel
private lateinit var requestAdapter: ConversationRequestAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_conversation_request)
init()
}
private fun init() {
initViewModel()
initClickListeners()
initRecyclerView()
initObservers()
getConversationsAndLocalUser()
}
private fun initViewModel() {
viewModel = ViewModelProviders.of(this).get(ConversationRequestViewModel::class.java)
}
private fun initClickListeners() = closeButton.setOnClickListener { finish() }
private fun initRecyclerView() {
requestAdapter = ConversationRequestAdapter(
onItemCLickListener = { startActivityAndFinish<ChatActivity> { putExtra(ChatActivity.EXTRA__THREAD_ID, it.threadId) } },
onAcceptClickListener = { viewModel.acceptConversation(it) },
onRejectClickListener = { viewModel.rejectConversation(it) }
)
requests.apply {
layoutManager = LinearLayoutManager(context)
adapter = requestAdapter
addHorizontalLineDivider()
}
}
private fun initObservers() {
viewModel.conversationsAndLocalUser.observe(this, Observer {
conversationsAndUser -> conversationsAndUser?.let { handleConversations(it.first, it.second) }
})
viewModel.updatedConversation.observe(this, Observer {
updatedConversation -> updatedConversation?.let { requestAdapter.addConversation(it) }
})
viewModel.acceptConversation.observe(this, Observer {
acceptedConversation -> acceptedConversation?.let { requestAdapter.remove(it); goToConversation(it) }
})
viewModel.rejectConversation.observe(this, Observer {
rejectedConversation -> rejectedConversation?.let { requestAdapter.remove(it); finishIfEmpty() }
})
}
private fun handleConversations(conversations: List<Conversation>, localUser: User?) {
if (conversations.isEmpty()) finish()
requestAdapter.setConversations(localUser, conversations)
}
private fun getConversationsAndLocalUser() = viewModel.getUnacceptedConversationsAndLocalUser()
private fun goToConversation(conversation: Conversation) {
startActivityAndFinish<ChatActivity> { putExtra(ChatActivity.EXTRA__THREAD_ID, conversation.threadId) }
}
private fun finishIfEmpty() {
if (requestAdapter.isEmpty()) finish()
}
} | gpl-3.0 | 9b567ce4961c5d6a65d707532dff96dc | 39.125 | 136 | 0.725312 | 4.902468 | false | false | false | false |
akvo/akvo-flow-mobile | app/src/main/java/org/akvo/flow/service/time/TimeCheckWorker.kt | 1 | 2999 | /*
* Copyright (C) 2021 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Flow.
*
* Akvo Flow 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.
*
* Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.flow.service.time
import android.content.Context
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import org.akvo.flow.app.FlowApp
import org.akvo.flow.domain.interactor.time.FetchServerTime
import org.akvo.flow.util.NotificationHelper
import timber.log.Timber
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import kotlin.math.abs
class TimeCheckWorker(context: Context, workerParams: WorkerParameters) :
CoroutineWorker(context, workerParams) {
@Inject
lateinit var fetchServerTime: FetchServerTime
init {
val application = applicationContext as FlowApp
application.getApplicationComponent().inject(this)
}
override suspend fun doWork(): Result {
return try {
val serverTime = fetchServerTime.execute()
val local = System.currentTimeMillis()
val onTime = serverTime == INVALID_TIME || abs(serverTime - local) < OFFSET_THRESHOLD
if (!onTime) {
NotificationHelper.showTimeCheckNotification(applicationContext)
}
Result.success()
} catch (e: Exception) {
Timber.e(e, "Error fetching time")
Result.failure()
}
}
companion object {
private const val TAG = "TimeCheckWorker"
private const val OFFSET_THRESHOLD = (13 * 60 * 1000 ).toLong()// 13 minutes
private const val INVALID_TIME = -1L
@JvmStatic
fun scheduleWork(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val oneTimeWorkRequest = OneTimeWorkRequest.Builder(TimeCheckWorker::class.java)
.setConstraints(constraints)
.setInitialDelay(0, TimeUnit.SECONDS)
.addTag(TAG)
.build()
WorkManager.getInstance(context.applicationContext)
.enqueueUniqueWork(TAG, ExistingWorkPolicy.REPLACE, oneTimeWorkRequest)
}
}
}
| gpl-3.0 | 85c01cf5d9023813769d96c412d00ff6 | 35.13253 | 97 | 0.689563 | 4.722835 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.