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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kunny/RxBinding
|
rxbinding-kotlin/src/main/kotlin/com/jakewharton/rxbinding/view/RxView.kt
|
1
|
13123
|
package com.jakewharton.rxbinding.view
import android.view.DragEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewTreeObserver
import com.jakewharton.rxbinding.internal.Functions
import rx.Observable
import rx.functions.Action1
import rx.functions.Func0
import rx.functions.Func1
/**
* Create an observable which emits on `view` attach events. The emitted value is
* unspecified and should only be used as notification.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
public inline fun View.attaches(): Observable<Unit> = RxView.attaches(this).map { Unit }
/**
* Create an observable of attach and detach events on `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
public inline fun View.attachEvents(): Observable<ViewAttachEvent> = RxView.attachEvents(this)
/**
* Create an observable which emits on `view` detach events. The emitted value is
* unspecified and should only be used as notification.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
public inline fun View.detaches(): Observable<Unit> = RxView.detaches(this).map { Unit }
/**
* Create an observable which emits on `view` click events. The emitted value is
* unspecified and should only be used as notification.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [View.setOnClickListener] to observe
* clicks. Only one observable can be used for a view at a time.
*/
public inline fun View.clicks(): Observable<Unit> = RxView.clicks(this).map { Unit }
/**
* Create an observable of [DragEvent] for drags on `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [View.setOnDragListener] to observe
* drags. Only one observable can be used for a view at a time.
*/
public inline fun View.drags(): Observable<DragEvent> = RxView.drags(this)
/**
* Create an observable of [DragEvent] for `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [View.setOnDragListener] to observe
* drags. Only one observable can be used for a view at a time.
*
* @param handled Function invoked with each value to determine the return value of the
* underlying [View.OnDragListener].
*/
public inline fun View.drags(handled: Func1<in DragEvent, Boolean>): Observable<DragEvent> = RxView.drags(this, handled)
/**
* Create an observable for draws on `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [ViewTreeObserver.addOnDrawListener] to
* observe draws. Multiple observables can be used for a view at a time.
*/
public inline fun View.draws(): Observable<Unit> = RxView.draws(this).map { Unit }
/**
* Create an observable of booleans representing the focus of `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [View.setOnFocusChangeListener] to observe
* focus change. Only one observable can be used for a view at a time.
*
* *Note:* A value will be emitted immediately on subscribe.
*/
public inline fun View.focusChanges(): Observable<Boolean> = RxView.focusChanges(this)
/**
* Create an observable which emits on `view` globalLayout events. The emitted value is
* unspecified and should only be used as notification.
* </p>
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses {@link
* ViewTreeObserver#addOnGlobalLayoutListener} to observe global layouts. Multiple observables
* can be used for a view at a time.
*/
public inline fun View.globalLayouts(): Observable<Unit> = RxView.globalLayouts(this).map { Unit }
/**
* Create an observable of hover events for `view`.
*
* *Warning:* Values emitted by this observable are <b>mutable</b> and part of a shared
* object pool and thus are <b>not safe</b> to cache or delay reading (such as by observing
* on a different thread). If you want to cache or delay reading the items emitted then you must
* map values through a function which calls {@link MotionEvent#obtain(MotionEvent)} or
* {@link MotionEvent#obtainNoHistory(MotionEvent)} to create a copy.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [View.setOnHoverListener] to observe
* touches. Only one observable can be used for a view at a time.
*/
public inline fun View.hovers(): Observable<MotionEvent> = RxView.hovers(this)
/**
* Create an observable of hover events for `view`.
*
* *Warning:* Values emitted by this observable are <b>mutable</b> and part of a shared
* object pool and thus are <b>not safe</b> to cache or delay reading (such as by observing
* on a different thread). If you want to cache or delay reading the items emitted then you must
* map values through a function which calls {@link MotionEvent#obtain(MotionEvent)} or
* {@link MotionEvent#obtainNoHistory(MotionEvent)} to create a copy.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [View.setOnHoverListener] to observe
* touches. Only one observable can be used for a view at a time.
*
* @param handled Function invoked with each value to determine the return value of the
* underlying [View.OnHoverListener].
*/
public inline fun View.hovers(handled: Func1<in MotionEvent, Boolean>): Observable<MotionEvent> = RxView.hovers(this, handled)
/**
* Create an observable which emits on `view` layout changes. The emitted value is
* unspecified and should only be used as notification.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
public inline fun View.layoutChanges(): Observable<Unit> = RxView.layoutChanges(this).map { Unit }
/**
* Create an observable of layout-change events for `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
public inline fun View.layoutChangeEvents(): Observable<ViewLayoutChangeEvent> = RxView.layoutChangeEvents(this)
/**
* Create an observable which emits on `view` long-click events. The emitted value is
* unspecified and should only be used as notification.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [View.setOnLongClickListener] to observe
* long clicks. Only one observable can be used for a view at a time.
*/
public inline fun View.longClicks(): Observable<Unit> = RxView.longClicks(this).map { Unit }
/**
* Create an observable which emits on `view` long-click events. The emitted value is
* unspecified and should only be used as notification.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [View.setOnLongClickListener] to observe
* long clicks. Only one observable can be used for a view at a time.
*
* @param handled Function invoked each occurrence to determine the return value of the
* underlying [View.OnLongClickListener].
*/
public inline fun View.longClicks(handled: Func0<Boolean>): Observable<Unit> = RxView.longClicks(this, handled).map { Unit }
/**
* Create an observable for pre-draws on `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [ViewTreeObserver.addOnPreDrawListener] to
* observe pre-draws. Multiple observables can be used for a view at a time.
*/
public inline fun View.preDraws(proceedDrawingPass: Func0<Boolean>): Observable<Unit> = RxView.preDraws(this, proceedDrawingPass).map { Unit }
/**
* Create an observable of scroll-change events for `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
public inline fun View.scrollChangeEvents(): Observable<ViewScrollChangeEvent> = RxView.scrollChangeEvents(this)
/**
* Create an observable of integers representing a new system UI visibility for `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses
* [View.setOnSystemUiVisibilityChangeListener] to observe system UI visibility changes.
* Only one observable can be used for a view at a time.
*/
public inline fun View.systemUiVisibilityChanges(): Observable<Int> = RxView.systemUiVisibilityChanges(this)
/**
* Create an observable of touch events for `view`.
*
* *Warning:* Values emitted by this observable are <b>mutable</b> and part of a shared
* object pool and thus are <b>not safe</b> to cache or delay reading (such as by observing
* on a different thread). If you want to cache or delay reading the items emitted then you must
* map values through a function which calls {@link MotionEvent#obtain(MotionEvent)} or
* {@link MotionEvent#obtainNoHistory(MotionEvent)} to create a copy.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [View.setOnTouchListener] to observe
* touches. Only one observable can be used for a view at a time.
*/
public inline fun View.touches(): Observable<MotionEvent> = RxView.touches(this)
/**
* Create an observable of touch events for `view`.
*
* *Warning:* Values emitted by this observable are <b>mutable</b> and part of a shared
* object pool and thus are <b>not safe</b> to cache or delay reading (such as by observing
* on a different thread). If you want to cache or delay reading the items emitted then you must
* map values through a function which calls {@link MotionEvent#obtain(MotionEvent)} or
* {@link MotionEvent#obtainNoHistory(MotionEvent)} to create a copy.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [View.setOnTouchListener] to observe
* touches. Only one observable can be used for a view at a time.
*
* @param handled Function invoked with each value to determine the return value of the
* underlying [View.OnTouchListener].
*/
public inline fun View.touches(handled: Func1<in MotionEvent, Boolean>): Observable<MotionEvent> = RxView.touches(this, handled)
/**
* An action which sets the activated property of `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
public inline fun View.activated(): Action1<in Boolean> = RxView.activated(this)
/**
* An action which sets the clickable property of `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
public inline fun View.clickable(): Action1<in Boolean> = RxView.clickable(this)
/**
* An action which sets the enabled property of `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
public inline fun View.enabled(): Action1<in Boolean> = RxView.enabled(this)
/**
* An action which sets the pressed property of `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
public inline fun View.pressed(): Action1<in Boolean> = RxView.pressed(this)
/**
* An action which sets the selected property of `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
public inline fun View.selected(): Action1<in Boolean> = RxView.selected(this)
/**
* An action which sets the visibility property of `view`. `false` values use
* `View.GONE`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
public inline fun View.visibility(): Action1<in Boolean> = RxView.visibility(this)
/**
* An action which sets the visibility property of `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* @param visibilityWhenFalse Visibility to set on a `false` value (`View.INVISIBLE`
* or `View.GONE`).
*/
public inline fun View.visibility(visibilityWhenFalse: Int): Action1<in Boolean> = RxView.visibility(this, visibilityWhenFalse)
|
apache-2.0
|
d0e85cfa06ee78f970d77726f8cd17fe
| 40.009375 | 142 | 0.742513 | 4.176639 | false | false | false | false |
dahlstrom-g/intellij-community
|
platform/platform-impl/src/com/intellij/toolWindow/ToolWindowPaneNewButtonManager.kt
|
2
|
4239
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.toolWindow
import com.intellij.openapi.wm.RegisterToolWindowTask
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.WindowInfo
import com.intellij.openapi.wm.impl.AbstractDroppableStripe
import com.intellij.openapi.wm.impl.SquareStripeButton
import com.intellij.openapi.wm.impl.ToolWindowImpl
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.Point
import javax.swing.Icon
import javax.swing.JComponent
internal class ToolWindowPaneNewButtonManager : ToolWindowButtonManager {
private val left = ToolWindowLeftToolbar()
private val right = ToolWindowRightToolbar()
override val isNewUi: Boolean
get() = true
override fun add(pane: JComponent) {
pane.add(left, BorderLayout.WEST)
pane.add(right, BorderLayout.EAST)
}
override fun updateToolStripesVisibility(showButtons: Boolean, state: ToolWindowPaneState): Boolean {
val oldSquareVisible = left.isVisible && right.isVisible
val visible = showButtons || state.isStripesOverlaid
left.isVisible = visible
right.isVisible = visible
return oldSquareVisible != visible
}
override fun initMoreButton() {
left.initMoreButton()
}
override fun layout(size: Dimension, layeredPane: JComponent) {
layeredPane.setBounds(0, 0, size.width, size.height)
}
override fun validateAndRepaint() {
}
override fun revalidateNotEmptyStripes() {
}
override fun getBottomHeight() = 0
override fun getStripeFor(anchor: ToolWindowAnchor): AbstractDroppableStripe {
return when (anchor) {
ToolWindowAnchor.LEFT, ToolWindowAnchor.BOTTOM -> left.getStripeFor(anchor)
ToolWindowAnchor.RIGHT, ToolWindowAnchor.TOP -> right.getStripeFor(anchor)
else -> throw IllegalArgumentException("Anchor=$anchor")
}
}
override fun getStripeFor(screenPoint: Point, preferred: AbstractDroppableStripe, pane: JComponent): AbstractDroppableStripe? {
if (preferred.containsPoint(screenPoint)) {
return preferred
}
else {
return left.getStripeFor(screenPoint) ?: right.getStripeFor(screenPoint)
}
}
fun getSquareStripeFor(anchor: ToolWindowAnchor): ToolWindowToolbar {
return when (anchor) {
ToolWindowAnchor.TOP, ToolWindowAnchor.RIGHT -> right
ToolWindowAnchor.BOTTOM, ToolWindowAnchor.LEFT -> left
else -> throw java.lang.IllegalArgumentException("Anchor=$anchor")
}
}
override fun startDrag() {
if (right.isVisible) {
right.startDrag()
}
if (left.isVisible) {
left.startDrag()
}
}
override fun stopDrag() {
if (right.isVisible) {
right.stopDrag()
}
if (left.isVisible) {
left.stopDrag()
}
}
override fun reset() {
left.reset()
right.reset()
}
fun refreshUi() {
left.repaint()
right.repaint()
}
private fun findToolbar(anchor: ToolWindowAnchor): ToolWindowToolbar = if (anchor == ToolWindowAnchor.RIGHT) right else left
override fun createStripeButton(toolWindow: ToolWindowImpl, info: WindowInfo, task: RegisterToolWindowTask?): StripeButtonManager {
val squareStripeButton = SquareStripeButton(toolWindow)
val manager = object : StripeButtonManager {
override val id: String
get() = toolWindow.id
override val windowDescriptor: WindowInfo
get() = toolWindow.windowInfo
override fun updateState(toolWindow: ToolWindowImpl) {
squareStripeButton.updateIcon()
}
override fun updatePresentation() {
squareStripeButton.updatePresentation()
}
override fun updateIcon(icon: Icon?) {
squareStripeButton.updatePresentation()
}
override fun remove() {
findToolbar(toolWindow.anchor).getStripeFor(toolWindow.windowInfo.anchor).removeButton(this)
}
override fun getComponent() = squareStripeButton
override fun toString(): String {
return "SquareStripeButtonManager(windowInfo=${toolWindow.windowInfo})"
}
}
findToolbar(toolWindow.anchor).getStripeFor(toolWindow.windowInfo.anchor).addButton(manager)
return manager
}
}
|
apache-2.0
|
982261adef7a6b02a4df6f3b876b9ecf
| 29.070922 | 133 | 0.723284 | 4.757576 | false | false | false | false |
TheMrMilchmann/lwjgl3
|
modules/lwjgl/stb/src/templates/kotlin/stb/STBTypes.kt
|
4
|
10804
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package stb
import org.lwjgl.generator.*
fun GeneratorTargetNative.includeSTBAPI(directives: String) = nativeDirective(
"""DISABLE_WARNINGS()
$directives
ENABLE_WARNINGS()""")
// stb_image.h
val stbi_uc = typedef(unsigned_char, "stbi_uc")
val stbi_us = typedef(unsigned_short, "stbi_us")
val stbi_io_callbacks = struct(Module.STB, "STBIIOCallbacks", nativeName = "stbi_io_callbacks") {
documentation = "Image IO callbacks, used by #load_from_callbacks()."
Module.STB.callback {
int(
"STBIReadCallback",
"The {@code stbi_io_callbacks.read} callback.",
void.p("user", "a pointer to user data"),
char.p("data", "the data buffer to fill"),
AutoSize("data")..int("size", "the number of bytes to read"),
returnDoc = "the number of bytes actually read"
) {
documentation = "Instances of this interface may be set to the {@code read} field of the ##STBIIOCallbacks struct."
javaImport("java.nio.*")
additionalCode = """
/**
* Converts the specified {@link STBIReadCallback} arguments to a ByteBuffer.
*
* <p>This method may only be used inside a STBIReadCallback invocation.</p>
*
* @param data the STBIReadCallback {@code data} argument
* @param size the STBIReadCallback {@code size} argument
*
* @return the data as a ByteBuffer
*/
public static ByteBuffer getData(long data, int size) {
return memByteBuffer(data, size);
}
"""
}
}("read", "fill {@code data} with {@code size} bytes. Return number of bytes actually read.")
Module.STB.callback {
void(
"STBISkipCallback",
"The {@code stbi_io_callbacks.skip} callback.",
void.p("user", "a pointer to user data"),
int("n", "the number of bytes to skip if positive, or <em>unget</em> the last {@code -n} bytes if negative")
) {
documentation = "Instances of this interface may be set to the {@code skip} field of the ##STBIIOCallbacks struct."
}
}("skip", "skip the next {@code n} bytes, or {@code unget} the last -n bytes if negative")
Module.STB.callback {
int(
"STBIEOFCallback",
"The {@code stbi_io_callbacks.eof} callback.",
void.p("user", "a pointer to user data"),
returnDoc = "nonzero if we are at the end of file/data"
) {
documentation = "Instances of this interface may be set to the {@code eof} field of the ##STBIIOCallbacks struct."
}
}("eof", "returns nonzero if we are at end of file/data")
}
// stb_image_resize.h
val stbir_uint16 = typedef(unsigned_short, "stbir_uint16")
val stbir_edge = "stbir_edge".enumType
val stbir_filter = "stbir_filter".enumType
val stbir_colorspace = "stbir_colorspace".enumType
val stbir_datatype = "stbir_datatype".enumType
// stb_image_write.h
val stbi_write_func = Module.STB.callback {
void(
"STBIWriteCallback",
"The {@code stbi_write_func} callback.",
void.p("context", "the context passed to the write function"),
void.p("data", "the data to write"),
AutoSize("data")..int("size", "the number of bytes in {@code data}"),
nativeType = "stbi_write_func *"
) {
documentation = "Instances of this interface may be used with the ##STBImageWrite {@code write_type_to_func} functions."
javaImport("java.nio.*")
additionalCode = """
/**
* Converts the specified {@link STBIWriteCallback} arguments to a ByteBuffer.
*
* <p>This method may only be used inside a STBIWriteCallback invocation.</p>
*
* @param data the STBIWriteCallback {@code data} argument
* @param size the STBIWriteCallback {@code size} argument
*
* @return the data as a ByteBuffer
*/
public static ByteBuffer getData(long data, int size) {
return memByteBuffer(data, size);
}
"""
}
}
val stbi_zlib_compress = Module.STB.callback {
unsigned_char.p(
"STBIZlibCompress",
"""
Compresses a block of data using Zlib compression.
The returned data will be freed with MemoryUtil#memFree() so it must be heap allocated with MemoryUtil#memAlloc().
""",
unsigned_char.p("data", "the data to compress"),
AutoSize("data")..int("data_len", "the data length, in bytes"),
AutoSizeResult..Check(1)..int.p("out_len", "returns the compressed data length, in bytes"),
int("quality", "the compression quality to use"),
returnDoc = "the compressed data"
) {
documentation = "Instances of this interface may be set to STBImageWrite#stbi_zlib_compress()."
}
}
// stb_rect_pack.h
val stbrp_coord = typedef(int, "stbrp_coord")
val stbrp_rect = struct(Module.STB, "STBRPRect", nativeName = "stbrp_rect") {
documentation = "A packed rectangle."
int("id", "reserved for your use")
stbrp_coord("w", "input width")
stbrp_coord("h", "input height")
stbrp_coord("x", "output x coordinate")
stbrp_coord("y", "output y coordinate")
intb("was_packed", "non-zero if valid packing")
}
private val _stbrp_node = struct(Module.STB, "STBRPNode", nativeName = "stbrp_node")
val stbrp_node = struct(Module.STB, "STBRPNode", nativeName = "stbrp_node", mutable = false) {
documentation = "The opaque {@code stbrp_node} struct."
stbrp_coord("x", "")
stbrp_coord("y", "")
nullable.._stbrp_node.p("next", "")
}
val stbrp_context = struct(Module.STB, "STBRPContext", nativeName = "stbrp_context", mutable = false) {
documentation = "The opaque {@code stbrp_context} struct."
int("width", "")
int("height", "")
int("align", "")
int("init_mode", "")
int("heuristic", "")
int("num_nodes", "")
nullable..stbrp_node.p("active_head", "")
nullable..stbrp_node.p("free_head", "")
stbrp_node("extra", "we allocate two extra nodes so optimal user-node-count is {@code width} not {@code width+2}")[2]
}
// stb_truetype.h
val stbtt_bakedchar = struct(Module.STB, "STBTTBakedChar", nativeName = "stbtt_bakedchar", mutable = false) {
documentation = "Baked character data, returned by #BakeFontBitmap()."
unsigned_short("x0", "")
unsigned_short("y0", "")
unsigned_short("x1", "")
unsigned_short("y1", "")
float("xoff", "")
float("yoff", "")
float("xadvance", "")
}
val stbtt_aligned_quad = struct(Module.STB, "STBTTAlignedQuad", nativeName = "stbtt_aligned_quad", mutable = false) {
documentation = "Quad used for drawing a baked character, returned by #GetBakedQuad()."
float("x0", "")
float("y0", "")
float("s0", "")
float("t0", "")
float("x1", "")
float("y1", "")
float("s1", "")
float("t1", "")
}
val stbtt_pack_context = struct(Module.STB, "STBTTPackContext", nativeName = "stbtt_pack_context", mutable = false) {
documentation = "An opaque structure which holds all the context needed from #PackBegin() to #PackEnd()."
nullable..opaque_p("user_allocator_context", "")
stbrp_context.p("pack_info", "")
int("width", "")
int("height", "")
int("stride_in_bytes", "")
int("padding", "")
intb("skip_missing", "")
unsigned_int("h_oversample", "")
unsigned_int("v_oversample", "")
unsigned_char.p("pixels", "")
Unsafe..stbrp_node.p("nodes", "")
}
val stbtt_packedchar = struct(Module.STB, "STBTTPackedchar", nativeName = "stbtt_packedchar") {
documentation = "Packed character data, returned by #PackFontRange()"
unsigned_short("x0", "")
unsigned_short("y0", "")
unsigned_short("x1", "")
unsigned_short("y1", "")
float("xoff", "")
float("yoff", "")
float("xadvance", "")
float("xoff2", "")
float("yoff2", "")
}
val stbtt_pack_range = struct(Module.STB, "STBTTPackRange", nativeName = "stbtt_pack_range") {
documentation = "A range of packed character data, used by #PackFontRanges()"
float("font_size", "the font size")
int("first_unicode_codepoint_in_range", "if non-zero, then the chars are continuous, and this is the first codepoint")
nullable..int.p("array_of_unicode_codepoints", "if non-zero, then this is an array of unicode codepoints")
AutoSize("array_of_unicode_codepoints", "chardata_for_range")..int("num_chars", "the number of codepoints in the range")
Unsafe..stbtt_packedchar.p("chardata_for_range", "output")
unsigned_char("h_oversample", "used internally")
unsigned_char("v_oversample", "used internally")
}
val stbtt_fontinfo = struct(Module.STB, "STBTTFontinfo", nativeName = "stbtt_fontinfo", mutable = false) {
documentation = "An opaque structure that contains font information."
includeSTBAPI("#include \"stb_truetype.h\"")
}
val stbtt_kerningentry = struct(Module.STB, "STBTTKerningentry", nativeName = "stbtt_kerningentry", mutable = false) {
int("glyph1", "")
int("glyph2", "")
int("advance", "")
}
val stbtt_vertex_type = IntegerType("stbtt_vertex_type", PrimitiveMapping.SHORT)
val stbtt_vertex = struct(Module.STB, "STBTTVertex", nativeName = "stbtt_vertex", mutable = false) {
documentation = "Vertex data."
stbtt_vertex_type("x", "")
stbtt_vertex_type("y", "")
stbtt_vertex_type("cx", "")
stbtt_vertex_type("cy", "")
stbtt_vertex_type("cx1", "")
stbtt_vertex_type("cy1", "")
unsigned_char("type", "")
}
val stbtt__bitmap = struct(Module.STB, "STBTTBitmap", nativeName = "stbtt__bitmap") {
documentation = "Bitmap data."
int("w", "the bitmap width")
int("h", "the bitmap height")
int("stride", "the row stride, in bytes")
unsigned_char.p("pixels", "the bitmap data")
}
// stb_vorbis.c
val stb_vorbis = "stb_vorbis".opaque
val stb_vorbis_alloc = struct(Module.STB, "STBVorbisAlloc", nativeName = "stb_vorbis_alloc") {
documentation = "A buffer to use for allocations by ##STBVorbis"
char.p("alloc_buffer", "")
AutoSize("alloc_buffer")..int("alloc_buffer_length_in_bytes", "")
}
val stb_vorbis_info = struct(Module.STB, "STBVorbisInfo", nativeName = "stb_vorbis_info", mutable = false) {
documentation = "Information about a Vorbis stream."
unsigned_int("sample_rate", "")
int("channels", "")
unsigned_int("setup_memory_required", "")
unsigned_int("setup_temp_memory_required", "")
unsigned_int("temp_memory_required", "")
int("max_frame_size", "")
}
val stb_vorbis_comment = struct(Module.STB, "STBVorbisComment", nativeName = "stb_vorbis_comment", mutable = false) {
charASCII.p("vendor", "");
AutoSize("comment_list")..int("comment_list_length", "")
charASCII.p.p("comment_list", "")
}
|
bsd-3-clause
|
6450701e7e96aff9f5b416b475c45623
| 34.660066 | 128 | 0.632266 | 3.583416 | false | false | false | false |
cbeust/klaxon
|
klaxon/src/test/kotlin/com/beust/klaxon/InstanceSettingsTest.kt
|
1
|
3293
|
package com.beust.klaxon
import org.testng.annotations.Test
import kotlin.test.assertContains
import kotlin.test.assertFalse
@Test
class InstanceSettingsTest {
@Suppress("unused")
class UnannotatedGeolocationCoordinates(
val latitude: Int,
val longitude: Int,
val speed: Int? // nullable field
)
@Suppress("unused")
class NoNullAnnotatedGeolocationCoordinates(
val latitude: Int,
val longitude: Int,
@Json(serializeNull = false) val speed: Int? // nullable field
)
@Suppress("unused")
class NullAnnotatedGeolocationCoordinates(
val latitude: Int,
val longitude: Int,
@Json(serializeNull = true) val speed: Int? // nullable field
)
private val unannotatedCoordinates = UnannotatedGeolocationCoordinates(1, 2, null)
private val noNullCoordinates = NoNullAnnotatedGeolocationCoordinates(1, 2, null)
private val nullCoordinates = NullAnnotatedGeolocationCoordinates(1, 2, null)
// Defaults & single-type settings
@Test
fun defaultSerialization() {
val klaxon = Klaxon()
val json = klaxon.toJsonString(unannotatedCoordinates)
assertContains(json, "null") // {"latitude" : 1, "longitude" : 2, "speed" : null}
}
@Test // no local settings, instance serializeNull = true -> null
fun instanceSettingsNullSerialization() {
val klaxon = Klaxon(instanceSettings = KlaxonSettings(serializeNull = true))
val json = klaxon.toJsonString(unannotatedCoordinates)
assertContains(json, "null") // {"latitude" : 1, "longitude" : 2, "speed" : null}
}
@Test // no local settings, instance serializeNull = false -> no null
fun instanceSettingsNoNullSerialization() {
val klaxon = Klaxon(KlaxonSettings(serializeNull = false))
val json = klaxon.toJsonString(unannotatedCoordinates)
assertFalse { json.contains("null") } // {"latitude" : 1, "longitude" : 2}
}
@Test // local serializeNull = false, no instance settings -> no null
fun localSettingsNoNullSerialization() {
val klaxon = Klaxon()
val json = klaxon.toJsonString(noNullCoordinates)
assertFalse { json.contains("null") } // {"latitude" : 1, "longitude" : 2}
}
@Test // local serializeNull = true, no instance settings -> null
fun localSettingsNullSerialization() {
val klaxon = Klaxon()
val json = klaxon.toJsonString(nullCoordinates)
assertContains(json, "null") // {"latitude" : 1, "longitude" : 2, "speed" : null}
}
//
// Mixed tests
@Test // local serializeNull = true, instance serializeNull = false -> null
fun localNullInstanceNoNullSerialization() {
val klaxon = Klaxon(KlaxonSettings(serializeNull = false))
val json = klaxon.toJsonString(nullCoordinates)
assertContains(json, "null") // {"latitude" : 1, "longitude" : 2, "speed" : null}
}
@Test // local serializeNull = false, instance serializeNull = true -> no null
fun localNoNullInstanceNullSerialization() {
val klaxon = Klaxon(KlaxonSettings(serializeNull = true))
val json = klaxon.toJsonString(noNullCoordinates)
assertFalse { json.contains("null") } // {"latitude" : 1, "longitude" : 2}
}
}
|
apache-2.0
|
25cdbcfd65defa7ad529e826d79881a5
| 36.420455 | 89 | 0.665958 | 4.498634 | false | true | false | false |
vladmm/intellij-community
|
plugins/settings-repository/testSrc/IcsTestCase.kt
|
5
|
2235
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository.test
import com.intellij.testFramework.TemporaryDirectory
import com.intellij.testFramework.writeChild
import org.eclipse.jgit.lib.Repository
import org.jetbrains.jgit.dirCache.AddLoadedFile
import org.jetbrains.jgit.dirCache.edit
import org.jetbrains.settingsRepository.IcsManager
import org.jetbrains.settingsRepository.git.createRepository as createGitRepository
import org.junit.Rule
import java.nio.file.FileSystem
import java.nio.file.Path
fun Repository.add(path: String, data: String) = add(path, data.toByteArray())
fun Repository.add(path: String, data: ByteArray): Repository {
workTree.writeChild(path, data)
edit(AddLoadedFile(path, data))
return this
}
val Repository.workTree: Path
get() = getWorkTree().toPath()
val SAMPLE_FILE_NAME = "file.xml"
val SAMPLE_FILE_CONTENT = """<application>
<component name="Encoding" default_encoding="UTF-8" />
</application>"""
abstract class IcsTestCase {
val tempDirManager = TemporaryDirectory()
@Rule fun getTemporaryFolder() = tempDirManager
private val fsRule = InMemoryFsRule()
@Rule fun _inMemoryFsRule() = fsRule
val fs: FileSystem
get() = fsRule.fs
val icsManager by lazy(LazyThreadSafetyMode.NONE) {
val icsManager = IcsManager(tempDirManager.newDirectory())
icsManager.repositoryManager.createRepositoryIfNeed()
icsManager.repositoryActive = true
icsManager
}
val provider by lazy(LazyThreadSafetyMode.NONE) { icsManager.ApplicationLevelProvider() }
}
fun TemporaryDirectory.createRepository(directoryName: String? = null) = createGitRepository(newDirectory(directoryName))
|
apache-2.0
|
2184f965a04a344da42165cbb4ed0d7f
| 33.384615 | 121 | 0.774944 | 4.314672 | false | true | false | false |
neilellis/kontrol
|
digitalocean/src/main/kotlin/kontrol/impl/ocean/DigitalOceanMachineGroup.kt
|
1
|
10447
|
/*
* Copyright 2014 Cazcade Limited (http://cazcade.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kontrol.digitalocean
import kontrol.api.MachineGroup
import kontrol.api.Machine
import kontrol.api.MachineState
import kontrol.api.MachineGroupState
import kontrol.api.Monitor
import java.util.ArrayList
import java.util.concurrent.ConcurrentHashMap
import kontrol.api.sensors.SensorArray
import kontrol.api.MonitorRule
import kontrol.doclient.Droplet
import kontrol.api.DownStreamKonfigurator
import kontrol.api.UpStreamKonfigurator
import java.util.SortedSet
import java.util.TreeSet
import kontrol.api.Postmortem
import kontrol.api.Controller
import kontrol.common.*
import kontrol.ext.string.ssh.onHost
import kontrol.api.Monitorable
import kontrol.api.sensors.GroupSensorArray
/**
* @todo document.
* @author <a href="http://uk.linkedin.com/in/neilellis">Neil Ellis</a>
*/
public class DigitalOceanMachineGroup(val clientFactory: DigitalOceanClientFactory,
public override val controller: Controller,
val name: String,
override val sensors: SensorArray,
val config: DigitalOceanConfig,
val sshKeys: String,
public override val min: Int,
public override val max: Int,
public override val hardMax: Int,
override val upstreamGroups: MutableList<MachineGroup>,
override val postmortems: List<Postmortem>,
override val downStreamKonfigurator: DownStreamKonfigurator? = null,
override val upStreamKonfigurator: UpStreamKonfigurator? = null, override val groupSensors: GroupSensorArray = DefaultGroupSensorArray()) : MachineGroup{
override var disableAction: ((Monitorable<MachineGroupState>) -> Unit)? = null
override var enableAction: ((Monitorable<MachineGroupState>) -> Unit)? = null
override val downStreamGroups: MutableList<MachineGroup> = ArrayList()
override var enabled: Boolean = true
override val machineMonitorRules: SortedSet<MonitorRule<MachineState, Machine>> = TreeSet();
override val groupMonitorRules: SortedSet<MonitorRule<MachineGroupState, MachineGroup>> = TreeSet()
override val stateMachine = DefaultStateMachine<MachineGroupState>(this);
override val monitor: Monitor<MachineGroupState, MachineGroup> = DigitalOceanMachineGroupMonitor(this, sensors, controller)
override val defaultMachineRules = DefaultStateMachineRules<MachineState>();
val machines = ConcurrentHashMap<String, DigitalOceanMachine>();
{
machines().forEach { it.fsm.rules = defaultMachineRules }
stateMachine.rules = DefaultStateMachineRules<MachineGroupState>();
upstreamGroups.forEach { (it as DigitalOceanMachineGroup).downStreamGroups.add(this) }
}
override fun costPerHourInDollars(): Double = machines.map { it.getValue().costPerHourInDollars() }.sum()
override fun groupName(): String = name;
override fun name(): String = name;
override fun machines(): List<Machine> {
val arrayList: ArrayList<DigitalOceanMachine> = ArrayList();
synchronized(machines) {
arrayList.addAll(machines.values())
}
return arrayList;
}
override fun contract(): MachineGroup {
if ( this.workingSize() < this.min) {
throw IllegalStateException("Too few machines, cancelling contract")
}
val digitalOcean = clientFactory.instance()
println("CONTRACTING GROUP ${name()} REQUESTED")
try {
println("Destroying m/c")
var machs = machines.values().filter { it.enabled && it.state() !in listOf(MachineState.OK, MachineState.STALE, MachineState.OVERLOADED) }
if (machs.size() == 0) {
machs = machines.values().filter { it.enabled && it.state() in listOf(MachineState.OVERLOADED) }
}
if (machs.size() == 0) {
machs = machines.values().filter { it.enabled && it.droplet.status?.toLowerCase() == "active" }.sortBy { it.id() };
}
val machine = machs.first()
machine.disable()
//Don't bother failing over machines that are already in the state DEAD or FAILED, they should have been failed over already.
if (max > 0 && machine.state() !in listOf(MachineState.FAILED, MachineState.DEAD)) {
failover(machine)
}
val id = machine.droplet.id!!
digitalOcean.deleteDroplet(id)
while (digitalOcean.getDropletInfo(id).status?.toLowerCase() == "active") {
println("Awaiting Machine ${id} OFF")
Thread.sleep(5000);
}
println("Machine ${id} is OFF")
if (stateMachine.currentState != MachineGroupState.QUIET) {
println("CONTRACTED GROUP ${name()}")
} else {
Thread.sleep(10000)
}
} catch(e: Exception) {
println("(${name()}) DO: " + e.getMessage())
} finally {
monitor.update();
}
return this
}
override fun expand(): Machine {
if ( this.machines().size >= this.hardMax) {
throw IllegalStateException("Too many machines, cancelling expand")
}
val droplet = Droplet()
droplet.name = (config.machinePrefix + name)
droplet.size_id = (config.dropletSizeId)
val instance = clientFactory.instance()
val availableRegions = instance.getAvailableRegions()
// droplet.setRegionId(availableRegions?.get((Math.random() * (availableRegions?.size()?.toDouble()?:0.0)).toInt())?.getId());
droplet.region_id = (config.regionId)
val images = instance.getAvailableImages()
for (image in images) {
if ((config.templatePrefix + name) == image.name) {
droplet.image_id = image.id
}
}
if (droplet.image_id == null) {
throw RuntimeException("No image ${config.templatePrefix + name} available in ${droplet.region_id} ")
}
var createdDroplet = instance.createDroplet(droplet, sshKeys, privateNetworking = true)
println("Created droplet with ID " + createdDroplet.id + " ip address " + createdDroplet.ip_address)
var count = 0
while (createdDroplet.ip_address == null && count++ < 20) {
try {
println("Waiting for IP ...")
createdDroplet = instance.getDropletInfo(createdDroplet.id!!)
} catch (e: Exception) {
e.printStackTrace();
}
Thread.sleep(5000)
}
if (stateMachine.currentState != MachineGroupState.BUSY) {
println("EXPANDED GROUP ${name()}")
Thread.sleep(20000);
} else {
}
val newMachine = DigitalOceanMachine(createdDroplet, clientFactory, sensors, controller, name)
machines.put(createdDroplet.id.toString(), newMachine);
newMachine.fsm.rules = defaultMachineRules
Thread.sleep(60 * 1000)
monitor.update();
return newMachine;
}
override fun destroy(machine: Machine): MachineGroup {
val id = machine.id().toInt()
try {
println("Destroying $machine")
val digitalOcean = clientFactory.instance();
digitalOcean.deleteDroplet(id);
monitor.update();
} catch (e: Exception) {
println("Failed to destroy ${id} due to ${e.getMessage()}")
}
return this;
}
fun waitForRestart(id: Int) {
var count1: Int = 0;
val instance = clientFactory.instance()
while (instance.getDropletInfo(id).status == "active" && count1++ < 10) {
println("Waiting for machine ${id} to stop being active")
Thread.sleep(5000);
}
var count2: Int = 0;
while (instance.getDropletInfo(id).status != "active" && count2++ < 60) {
println("Waiting for machine ${id} to become active")
Thread.sleep(5000);
}
Thread.sleep(120000);
}
override fun rebuild(machine: Machine): MachineGroup {
super.rebuild(machine)
val id = machine.id().toInt()
try {
val instance = clientFactory.instance()
val images = instance.getAvailableImages()
var imageId: Int? = null;
for (image in images) {
if ((config.templatePrefix + name) == image.name) {
imageId = image.id;
break;
}
}
println("Rebuilding ${machine.id()} with ${imageId}")
if (imageId != null) {
instance.rebuildDroplet(id, imageId!!)
waitForRestart(id)
println("Rebuilt ${machine.id()}")
} else {
println("No valid image to rebuild ${machine.id()}")
}
} catch (e: Exception) {
println("Failed to reImage ${id} due to ${e.getMessage()}")
}
return this;
}
override fun fix(machine: Machine): MachineGroup {
val id = machine.id().toInt()
try {
println("Rebooting $machine")
"reboot".onHost(machine.ip(), timeoutInSeconds = 20)
waitForRestart(id)
println("Rebuilt ${id}")
} catch (e: Exception) {
println("Failed to restart ${id} due to ${e.getMessage()}")
machine.fsm.attemptTransition(MachineState.DEAD)
}
return this;
}
}
|
apache-2.0
|
39e22d8a8e66eef6b8ac33ba62f4491a
| 39.030651 | 191 | 0.599789 | 4.688959 | false | false | false | false |
paplorinc/intellij-community
|
plugins/configuration-script/test/ConfigurationSchemaTest.kt
|
1
|
3556
|
package com.intellij.configurationScript
import com.intellij.codeInsight.completion.CompletionTestCase
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementPresentation
import com.intellij.json.JsonFileType
import com.intellij.testFramework.EditorTestUtil
import com.intellij.testFramework.LightVirtualFile
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.jetbrains.jsonSchema.impl.JsonSchemaCompletionContributor
import com.jetbrains.jsonSchema.impl.JsonSchemaReader
import org.intellij.lang.annotations.Language
import java.nio.charset.StandardCharsets
// this test requires YamlJsonSchemaCompletionContributor, that's why intellij.yaml is added as test dependency
internal class ConfigurationSchemaTest : CompletionTestCase() {
private var schemaFile: LightVirtualFile? = null
override fun setUp() {
super.setUp()
schemaFile = LightVirtualFile("scheme.json", JsonFileType.INSTANCE, generateConfigurationSchema(), StandardCharsets.UTF_8, 0)
}
fun `test map and description`() {
val variants = test("""
runConfigurations:
java:
<caret>
""".trimIndent())
checkDescription(variants, "env", "Environment variables")
checkDescription(variants, "isAllowRunningInParallel", "Allow parallel run")
checkDescription(variants, "isShowConsoleOnStdErr", "Show console when a message is printed to standard error stream")
checkDescription(variants, "isShowConsoleOnStdOut", "Show console when a message is printed to standard output stream")
}
fun `test array or object`() {
val variants = test("""
runConfigurations:
java: <caret>
""".trimIndent())
val texts = variants.map {
val presentation = LookupElementPresentation()
it.renderElement(presentation)
presentation.itemText
}
assertThat(texts).contains("{...}", "[...]")
}
fun `test no isAllowRunningInParallel if singleton policy not configurable`() {
val variants = test("""
runConfigurations:
compound:
<caret>
""".trimIndent())
assertThat(variantsToText(variants)).isEqualTo("""
configurations (array)
""".trimIndent())
}
private fun checkDescription(variants: List<LookupElement>, name: String, expectedDescription: String) {
val variant = variants.first { it.lookupString == name }
val presentation = LookupElementPresentation()
variant.renderElement(presentation)
assertThat(presentation.typeText).isEqualTo(expectedDescription)
}
private fun test(@Language("YAML") text: String): List<LookupElement> {
val position = EditorTestUtil.getCaretPosition(text)
assertThat(position).isGreaterThan(0)
@Suppress("SpellCheckingInspection")
val file = createFile(myModule, "intellij.yaml", text.replace("<caret>", "IntelliJIDEARulezzz"))
val element = file.findElementAt(position)
assertThat(element).isNotNull
val schemaObject = JsonSchemaReader.readFromFile(myProject, schemaFile!!)
assertThat(schemaObject).isNotNull
return JsonSchemaCompletionContributor.getCompletionVariants(schemaObject, element!!, element)
}
}
private fun variantsToText(variants: List<LookupElement>): String {
return variants
.asSequence()
.sortedBy { it.lookupString }
.joinToString("\n") { "${it.lookupString} (${getTypeTest(it)})" }
}
private fun getTypeTest(variant: LookupElement): String {
val presentation = LookupElementPresentation()
variant.renderElement(presentation)
return presentation.typeText!!
}
|
apache-2.0
|
a0c5d0f8bac47429405a1560371eedb7
| 36.052083 | 129 | 0.751969 | 4.932039 | false | true | false | false |
google/intellij-community
|
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/CollectionFieldEntityImpl.kt
|
1
|
8483
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceSet
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class CollectionFieldEntityImpl(val dataSource: CollectionFieldEntityData) : CollectionFieldEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val versions: Set<Int>
get() = dataSource.versions
override val names: List<String>
get() = dataSource.names
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: CollectionFieldEntityData?) : ModifiableWorkspaceEntityBase<CollectionFieldEntity>(), CollectionFieldEntity.Builder {
constructor() : this(CollectionFieldEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity CollectionFieldEntity 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().isVersionsInitialized()) {
error("Field CollectionFieldEntity#versions should be initialized")
}
if (!getEntityData().isNamesInitialized()) {
error("Field CollectionFieldEntity#names 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 CollectionFieldEntity
this.entitySource = dataSource.entitySource
this.versions = dataSource.versions.toMutableSet()
this.names = dataSource.names.toMutableList()
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
private val versionsUpdater: (value: Set<Int>) -> Unit = { value ->
changedProperty.add("versions")
}
override var versions: MutableSet<Int>
get() {
val collection_versions = getEntityData().versions
if (collection_versions !is MutableWorkspaceSet) return collection_versions
collection_versions.setModificationUpdateAction(versionsUpdater)
return collection_versions
}
set(value) {
checkModificationAllowed()
getEntityData().versions = value
versionsUpdater.invoke(value)
}
private val namesUpdater: (value: List<String>) -> Unit = { value ->
changedProperty.add("names")
}
override var names: MutableList<String>
get() {
val collection_names = getEntityData().names
if (collection_names !is MutableWorkspaceList) return collection_names
collection_names.setModificationUpdateAction(namesUpdater)
return collection_names
}
set(value) {
checkModificationAllowed()
getEntityData().names = value
namesUpdater.invoke(value)
}
override fun getEntityData(): CollectionFieldEntityData = result ?: super.getEntityData() as CollectionFieldEntityData
override fun getEntityClass(): Class<CollectionFieldEntity> = CollectionFieldEntity::class.java
}
}
class CollectionFieldEntityData : WorkspaceEntityData<CollectionFieldEntity>() {
lateinit var versions: MutableSet<Int>
lateinit var names: MutableList<String>
fun isVersionsInitialized(): Boolean = ::versions.isInitialized
fun isNamesInitialized(): Boolean = ::names.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<CollectionFieldEntity> {
val modifiable = CollectionFieldEntityImpl.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): CollectionFieldEntity {
return getCached(snapshot) {
val entity = CollectionFieldEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun clone(): CollectionFieldEntityData {
val clonedEntity = super.clone()
clonedEntity as CollectionFieldEntityData
clonedEntity.versions = clonedEntity.versions.toMutableWorkspaceSet()
clonedEntity.names = clonedEntity.names.toMutableWorkspaceList()
return clonedEntity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return CollectionFieldEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return CollectionFieldEntity(versions, names, 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 CollectionFieldEntityData
if (this.entitySource != other.entitySource) return false
if (this.versions != other.versions) return false
if (this.names != other.names) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as CollectionFieldEntityData
if (this.versions != other.versions) return false
if (this.names != other.names) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + versions.hashCode()
result = 31 * result + names.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + versions.hashCode()
result = 31 * result + names.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.versions?.let { collector.add(it::class.java) }
this.names?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
|
apache-2.0
|
a74485c554a530311e91be35e5a96ae3
| 33.62449 | 145 | 0.73217 | 5.379201 | false | false | false | false |
google/intellij-community
|
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/GHPRListPanelFactory.kt
|
2
|
9181
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.github.pullrequest.ui.toolwindow
import com.intellij.ide.DataManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBList
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.StatusText
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.scroll.BoundedRangeModelThresholdListener
import com.intellij.vcs.log.ui.frame.ProgressStripe
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys
import org.jetbrains.plugins.github.pullrequest.data.GHListLoader
import org.jetbrains.plugins.github.pullrequest.data.GHPRListLoader
import org.jetbrains.plugins.github.pullrequest.data.GHPRListUpdatesChecker
import org.jetbrains.plugins.github.pullrequest.data.service.GHPRRepositoryDataService
import org.jetbrains.plugins.github.pullrequest.data.service.GHPRSecurityService
import org.jetbrains.plugins.github.pullrequest.ui.GHApiLoadingErrorHandler
import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.ui.component.GHHandledErrorPanelModel
import org.jetbrains.plugins.github.ui.component.GHHtmlErrorPanel
import java.awt.FlowLayout
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.ScrollPaneConstants
import javax.swing.event.ChangeEvent
internal class GHPRListPanelFactory(private val project: Project,
private val repositoryDataService: GHPRRepositoryDataService,
private val securityService: GHPRSecurityService,
private val listLoader: GHPRListLoader,
private val listUpdatesChecker: GHPRListUpdatesChecker,
private val account: GithubAccount,
private val disposable: Disposable) {
private val scope = MainScope().also { Disposer.register(disposable) { it.cancel() } }
fun create(list: JBList<GHPullRequestShort>, avatarIconsProvider: GHAvatarIconsProvider): JComponent {
val actionManager = ActionManager.getInstance()
val historyModel = GHPRSearchHistoryModel(project.service<GHPRListPersistentSearchHistory>())
val searchVm = GHPRSearchPanelViewModel(scope, repositoryDataService, historyModel, securityService.currentUser)
scope.launch {
searchVm.searchState.collectLatest {
listLoader.searchQuery = it.toQuery()
}
}
ListEmptyTextController(scope, listLoader, searchVm, list.emptyText, disposable)
val searchPanel = GHPRSearchPanelFactory(searchVm, avatarIconsProvider).create(scope)
val outdatedStatePanel = JPanel(FlowLayout(FlowLayout.LEFT, JBUIScale.scale(5), 0)).apply {
background = UIUtil.getPanelBackground()
border = JBUI.Borders.empty(4, 0)
add(JLabel(GithubBundle.message("pull.request.list.outdated")))
add(ActionLink(GithubBundle.message("pull.request.list.refresh")) {
listLoader.reset()
})
isVisible = false
}
OutdatedPanelController(listLoader, listUpdatesChecker, outdatedStatePanel, disposable)
val errorHandler = GHApiLoadingErrorHandler(project, account) {
listLoader.reset()
}
val errorModel = GHHandledErrorPanelModel(GithubBundle.message("pull.request.list.cannot.load"), errorHandler).apply {
error = listLoader.error
}
listLoader.addErrorChangeListener(disposable) {
errorModel.error = listLoader.error
}
val errorPane = GHHtmlErrorPanel.create(errorModel)
val controlsPanel = JPanel(VerticalLayout(0)).apply {
isOpaque = false
add(searchPanel)
add(outdatedStatePanel)
add(errorPane)
}
val listLoaderPanel = createListLoaderPanel(listLoader, list, disposable)
return JBUI.Panels.simplePanel(listLoaderPanel).addToTop(controlsPanel).andTransparent().also {
DataManager.registerDataProvider(it) { dataId ->
if (GHPRActionKeys.SELECTED_PULL_REQUEST.`is`(dataId)) {
if (list.isSelectionEmpty) null else list.selectedValue
}
else null
}
actionManager.getAction("Github.PullRequest.List.Reload").registerCustomShortcutSet(it, disposable)
}
}
private fun createListLoaderPanel(loader: GHListLoader<*>, list: JComponent, disposable: Disposable): JComponent {
val scrollPane = ScrollPaneFactory.createScrollPane(list, true).apply {
isOpaque = false
viewport.isOpaque = false
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
val model = verticalScrollBar.model
val listener = object : BoundedRangeModelThresholdListener(model, 0.7f) {
override fun onThresholdReached() {
if (!loader.loading && loader.canLoadMore()) {
loader.loadMore()
}
}
}
model.addChangeListener(listener)
loader.addLoadingStateChangeListener(disposable) {
if (!loader.loading) listener.stateChanged(ChangeEvent(loader))
}
}
loader.addDataListener(disposable, object : GHListLoader.ListDataListener {
override fun onAllDataRemoved() {
if (scrollPane.isShowing) loader.loadMore()
}
})
val progressStripe = ProgressStripe(scrollPane, disposable,
ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS).apply {
if (loader.loading) startLoadingImmediately() else stopLoading()
}
loader.addLoadingStateChangeListener(disposable) {
if (loader.loading) progressStripe.startLoading() else progressStripe.stopLoading()
}
return progressStripe
}
private class ListEmptyTextController(scope: CoroutineScope,
private val listLoader: GHListLoader<*>,
private val searchVm: GHPRSearchPanelViewModel,
private val emptyText: StatusText,
listenersDisposable: Disposable) {
init {
listLoader.addLoadingStateChangeListener(listenersDisposable, ::update)
scope.launch {
searchVm.searchState.collect {
update()
}
}
}
private fun update() {
emptyText.clear()
if (listLoader.loading || listLoader.error != null) return
val search = searchVm.searchState.value
if (search == GHPRListSearchValue.DEFAULT) {
emptyText.appendText(GithubBundle.message("pull.request.list.no.matches"))
.appendSecondaryText(GithubBundle.message("pull.request.list.reset.filters"),
SimpleTextAttributes.LINK_ATTRIBUTES) {
searchVm.searchState.update { GHPRListSearchValue.EMPTY }
}
}
else if (search.filterCount == 0) {
emptyText.appendText(GithubBundle.message("pull.request.list.nothing.loaded"))
}
else {
emptyText.appendText(GithubBundle.message("pull.request.list.no.matches"))
.appendSecondaryText(GithubBundle.message("pull.request.list.reset.filters.to.default",
GHPRListSearchValue.DEFAULT.toQuery().toString()),
SimpleTextAttributes.LINK_ATTRIBUTES) {
searchVm.searchState.update { GHPRListSearchValue.DEFAULT }
}
}
}
}
private class OutdatedPanelController(private val listLoader: GHListLoader<*>,
private val listChecker: GHPRListUpdatesChecker,
private val panel: JPanel,
listenersDisposable: Disposable) {
init {
listLoader.addLoadingStateChangeListener(listenersDisposable, ::update)
listLoader.addErrorChangeListener(listenersDisposable, ::update)
listChecker.addOutdatedStateChangeListener(listenersDisposable, ::update)
}
private fun update() {
panel.isVisible = listChecker.outdated && (!listLoader.loading && listLoader.error == null)
}
}
}
|
apache-2.0
|
f64ce944386ac9ad369ccf9e18f2cadc
| 43.572816 | 122 | 0.71038 | 5.030685 | false | false | false | false |
RuneSuite/client
|
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Varcs.kt
|
1
|
5344
|
package org.runestar.client.updater.mapper.std.classes
import org.objectweb.asm.Opcodes.AALOAD
import org.objectweb.asm.Opcodes.AASTORE
import org.objectweb.asm.Opcodes.PUTFIELD
import org.objectweb.asm.Type.BOOLEAN_TYPE
import org.objectweb.asm.Type.INT_TYPE
import org.objectweb.asm.Type.LONG_TYPE
import org.objectweb.asm.Type.VOID_TYPE
import org.runestar.client.common.startsWith
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
import org.runestar.client.updater.mapper.Instruction2
import org.runestar.client.updater.mapper.Method2
class Varcs : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == Any::class.type }
.and { it.instanceFields.count { it.type == BooleanArray::class.type } >= 1 }
.and { it.instanceFields.count { it.type == IntArray::class.type } <= 1 }
.and { it.instanceFields.count { it.type == Array<String>::class.type } == 1 }
class strings : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == Array<String>::class.type }
}
class map : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == Map::class.type }
}
@DependsOn(AccessFile::class)
class getPreferencesFile : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<AccessFile>() }
}
@DependsOn(AccessFile.read::class)
class read : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.instructions.any { it.isMethod && it.methodId == method<AccessFile.read>().id } }
}
@DependsOn(AccessFile.write::class)
class write : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.instructions.any { it.isMethod && it.methodId == method<AccessFile.write>().id } }
}
class intsPersistence : OrderMapper.InConstructor.Field(Varcs::class, 0, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == BooleanArray::class.type }
}
class unwrittenChanges : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == BOOLEAN_TYPE }
}
class lastWriteTimeMs : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == LONG_TYPE }
}
@MethodParameters("index")
class getStringOld : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == String::class.type }
.and { it.instructions.any { it.opcode == AALOAD } }
}
@MethodParameters("index")
class getString : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == String::class.type }
.and { it.instructions.none { it.opcode == AALOAD } }
}
@MethodParameters("index")
class getInt : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE }
}
@MethodParameters()
class hasUnwrittenChanges : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE }
}
@MethodParameters("index", "s")
class setStringOld : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(INT_TYPE, String::class.type) }
.and { it.instructions.any { it.opcode == AASTORE } }
}
@MethodParameters("index", "s")
class setString : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(INT_TYPE, String::class.type) }
.and { it.instructions.none { it.opcode == AASTORE } }
}
@MethodParameters("index", "n")
class setInt : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.startsWith(INT_TYPE, INT_TYPE) }
}
@MethodParameters()
class clearTransient : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.size in 0..1 }
.and { it.node.tryCatchBlocks.isEmpty() }
.and { it.instructions.any { it.opcode == AASTORE } }
}
@MethodParameters()
class tryWrite : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.arguments.size in 0..1 }
.and { it.node.tryCatchBlocks.isEmpty() }
.and { it.instructions.none { it.opcode == AASTORE } }
}
}
|
mit
|
dd4b6445ba5563f9baf6e4d2f6855e95
| 42.811475 | 141 | 0.677769 | 4.248013 | false | false | false | false |
RuneSuite/client
|
plugins/src/main/java/org/runestar/client/plugins/hotkeyattackoption/HotkeyAttackOption.kt
|
1
|
1366
|
package org.runestar.client.plugins.hotkeyattackoption
import org.runestar.client.api.forms.KeyStrokeForm
import org.runestar.client.api.plugins.DisposablePlugin
import org.runestar.client.api.game.AttackOptionId
import org.runestar.client.api.game.live.AttackOptions
import org.runestar.client.api.game.live.Keyboard
import org.runestar.client.raw.access.XClient
import org.runestar.client.api.plugins.PluginSettings
class HotkeyAttackOption : DisposablePlugin<HotkeyAttackOption.Settings>() {
override val defaultSettings = Settings()
override val name = "Hotkey Attack Option"
override fun onStart() {
Keyboard.strokes
.filter(settings.keyStroke.value::equals)
.delay { XClient.doCycle.enter }
.subscribe {
AttackOptions.player = if (AttackOptions.player == settings.playerAttackOption1) {
settings.playerAttackOption2
} else {
settings.playerAttackOption1
}
}
.add()
}
class Settings(
val playerAttackOption1: Int = AttackOptionId.HIDDEN,
val playerAttackOption2: Int = AttackOptionId.LEFT_CLICK_WHERE_AVAILABLE,
val keyStroke: KeyStrokeForm = KeyStrokeForm("released CONTROL")
) : PluginSettings()
}
|
mit
|
8492ac51cdb54375c12224e823c98ec3
| 36.972222 | 102 | 0.664714 | 4.662116 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2
|
core/src/main/kotlin/io/github/chrislo27/rhre3/editor/stage/Java32BitWarningStage.kt
|
2
|
3130
|
package io.github.chrislo27.rhre3.editor.stage
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.TextureRegion
import io.github.chrislo27.rhre3.PreferenceKeys
import io.github.chrislo27.rhre3.RHRE3
import io.github.chrislo27.rhre3.screen.EditorScreen
import io.github.chrislo27.rhre3.stage.GenericStage
import io.github.chrislo27.rhre3.stage.TrueCheckbox
import io.github.chrislo27.toolboks.registry.AssetRegistry
import io.github.chrislo27.toolboks.ui.*
class Java32BitWarningStage(val screen: EditorScreen) : Stage<EditorScreen>(screen.stage, screen.stage.camera) {
val genericStage: GenericStage<EditorScreen> = GenericStage(screen.main.uiPalette, this, this.camera)
init {
genericStage.run {
drawBackground = false
titleLabel.text = "Java 32-bit ver. detected"
titleLabel.isLocalizationKey = false
titleIcon.image = TextureRegion(AssetRegistry.get<Texture>("logo_256"))
backButton.visible = true
onBackButtonClick = {
Gdx.app.postRunnable {
([email protected] as Stage<EditorScreen>).elements.remove(this@Java32BitWarningStage)
}
}
}
elements += ColourPane(this, this).apply {
this.colour.set(0f, 0f, 0f, 1f)
}
elements += InputSponge(this, this).apply {
this.shouldAbsorbInput = true
}
elements += genericStage
val palette = screen.main.uiPalette
genericStage.centreStage.elements += TextLabel(palette, genericStage.centreStage, genericStage.centreStage).apply {
this.text = """A 32-bit version of the Java Runtime Environment was detected.
|
|Please note that only 64-bit versions of Java are supported for use with
|the Rhythm Heaven Remix Editor. You may experience crashes due to running out of memory on a 32-bit Java version.
|
|Please open the link below and download & install the appropriate 64-bit Java version.
|Be sure to uninstall your existing Java installation first.
|
|Windows: Windows Offline (64-bit)
|Linux: Linux x64 (or through your system package manager)
""".trimMargin()
this.isLocalizationKey = false
this.textWrapping = true
this.fontScaleMultiplier = 0.85f
}
genericStage.bottomStage.elements += Button(palette, genericStage.bottomStage, genericStage.bottomStage).apply {
this.leftClickAction = { _, _ ->
Gdx.net.openURI("""https://java.com/en/download/manual.jsp""")
}
addLabel(TextLabel(palette, this, this.stage).apply {
this.isLocalizationKey = false
this.textWrapping = false
this.text = "Open Java downloads page\n[#8CB8FF]https://java.com/en/download/manual.jsp[]"
})
this.location.set(0.275f, 0f, 0.45f, 1f)
}
}
}
|
gpl-3.0
|
766720b450b1e8bb6066f74f06867e07
| 43.098592 | 130 | 0.639617 | 4.408451 | false | false | false | false |
mikepenz/Android-Iconics
|
iconics-core/src/main/java/com/mikepenz/iconics/utils/IconicsDrawableProducerExtensions.kt
|
1
|
7412
|
/*
* Copyright 2020 Mike Penz
*
* 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("NOTHING_TO_INLINE", "LargeClass")
package com.mikepenz.iconics.utils
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.Typeface
import com.mikepenz.iconics.IconicsColor
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.IconicsSize
import com.mikepenz.iconics.typeface.IIcon
/** Loads and draws given text */
@JvmName("iconFromString")
fun IconicsDrawable.icon(iconProducer: () -> String?): IconicsDrawable {
iconProducer()?.let { icon(it) }
return this
}
/** Loads and draws given char */
@JvmName("iconFromChar")
fun IconicsDrawable.icon(iconProducer: () -> Char?): IconicsDrawable {
iconProducer()?.let { icon(it) }
return this
}
/** Loads and draws given text */
@JvmName("iconTextFromString")
fun IconicsDrawable.iconText(iconTextProducer: () -> String?): IconicsDrawable {
iconTextProducer()?.let { iconText(it) }
return this
}
/** Loads and draws given icon */
fun IconicsDrawable.icon(iconProducer: () -> IIcon?): IconicsDrawable {
iconProducer()?.let { icon(it) }
return this
}
/** Set the color of the drawable.*/
fun IconicsDrawable.color(colorProducer: () -> IconicsColor?): IconicsDrawable {
colorProducer()?.let { color = it }
return this
}
/** Set the icon offset for X axis */
fun IconicsDrawable.iconOffsetX(iconOffsetXProducer: () -> IconicsSize?): IconicsDrawable {
iconOffsetXProducer()?.let { iconOffsetX = it }
return this
}
/** Set the icon offset for Y axis */
fun IconicsDrawable.iconOffsetY(iconOffsetYProducer: () -> IconicsSize?): IconicsDrawable {
iconOffsetYProducer()?.let { iconOffsetY = it }
return this
}
/** Set the padding for the drawable. */
fun IconicsDrawable.padding(paddingProducer: () -> IconicsSize?): IconicsDrawable {
paddingProducer()?.let { padding = it }
return this
}
/** Set the size by X and Y axis of the drawable.*/
fun IconicsDrawable.size(sizeProducer: () -> IconicsSize?): IconicsDrawable {
sizeProducer()?.let { size = it }
return this
}
/**
* Set if it should respect the original bounds of the icon. (DEFAULT is false)
* This will break the "padding" functionality, but keep the padding defined by the font itself
* Check it out with the oct_arrow_down and oct_arrow_small_down of the Octicons font
*/
fun IconicsDrawable.respectFontBounds(respectFontBoundsProducer: () -> Boolean?): IconicsDrawable {
respectFontBoundsProducer()?.let { respectFontBounds = it }
return this
}
/** Set the size by X axis of the drawable. */
fun IconicsDrawable.sizeX(sizeXProducer: () -> IconicsSize?): IconicsDrawable {
sizeXProducer()?.let { sizeX = it }
return this
}
/** Set the size by Y axis of the drawable. */
fun IconicsDrawable.sizeY(sizeYProducer: () -> IconicsSize?): IconicsDrawable {
sizeYProducer()?.let { sizeY = it }
return this
}
/** Set background contour colors. */
fun IconicsDrawable.backgroundContourColor(backgroundContourColorProducer: () -> IconicsColor?): IconicsDrawable {
backgroundContourColorProducer()?.let { backgroundContourColor = it }
return this
}
/** Set contour colors */
fun IconicsDrawable.contourColor(contourColorProducer: () -> IconicsColor?): IconicsDrawable {
contourColorProducer()?.let { contourColor = it }
return this
}
/**Set the shadow for the icon
* This requires shadow support to be enabled on the view holding this `IconicsDrawable`*/
fun IconicsDrawable.shadow(
radiusProducer: () -> IconicsSize? = { IconicsSize.px(shadowRadiusPx) },
dxProducer: () -> IconicsSize? = { IconicsSize.px(shadowDxPx) },
dyProducer: () -> IconicsSize? = { IconicsSize.px(shadowDyPx) },
colorProducer: () -> IconicsColor? = { IconicsColor.colorInt(shadowColorInt) }
): IconicsDrawable {
val radius = radiusProducer()
val dx = dxProducer()
val dy = dyProducer()
val color = colorProducer()
@Suppress("ComplexCondition")
if (radius != null && dx != null && dy != null && color != null) {
applyShadow {
shadowRadius = radius
shadowDx = dx
shadowDy = dy
shadowColor = color
}
}
return this
}
/** Set background colors. */
fun IconicsDrawable.backgroundColor(backgroundColorProducer: () -> IconicsColor?): IconicsDrawable {
backgroundColorProducer()?.let { backgroundColor = it }
return this
}
/** Set rounded corners. */
fun IconicsDrawable.roundedCornersRx(roundedCornersRxProducer: () -> IconicsSize?): IconicsDrawable {
roundedCornersRxProducer()?.let { roundedCornersRx = it }
return this
}
/** Set rounded corner from px */
fun IconicsDrawable.roundedCornersRy(roundedCornersRyProducer: () -> IconicsSize?): IconicsDrawable {
roundedCornersRyProducer()?.let { roundedCornersRy = it }
return this
}
/** Set rounded corner from px */
fun IconicsDrawable.roundedCorners(roundedCornersProducer: () -> IconicsSize?): IconicsDrawable {
roundedCornersProducer()?.let { roundedCorners = it }
return this
}
/** Set contour width for the icon. */
fun IconicsDrawable.contourWidth(contourWidthProducer: () -> IconicsSize?): IconicsDrawable {
contourWidthProducer()?.let { contourWidth = it }
return this
}
/** Set background contour width for the icon. */
fun IconicsDrawable.backgroundContourWidth(backgroundContourWidthProducer: () -> IconicsSize?): IconicsDrawable {
backgroundContourWidthProducer()?.let { backgroundContourWidth = it }
return this
}
/** Enable/disable contour drawing. */
fun IconicsDrawable.drawContour(drawContourProducer: () -> Boolean?): IconicsDrawable {
drawContourProducer()?.let { drawContour = it }
return this
}
/** Enable/disable background contour drawing. */
fun IconicsDrawable.drawBackgroundContour(drawBackgroundContourProducer: () -> Boolean?): IconicsDrawable {
drawBackgroundContourProducer()?.let { drawBackgroundContour = it }
return this
}
/** Set the ColorFilter */
fun IconicsDrawable.colorFilter(colorFilterProducer: () -> ColorFilter?): IconicsDrawable {
colorFilterProducer()?.let { colorFilter = it }
return this
}
/**
* Set the opacity
* **NOTE** if you define a color (or as part of a colorStateList) with alpha
* the alpha value of that color will ALWAYS WIN! */
fun IconicsDrawable.alpha(alphaProducer: () -> Int?): IconicsDrawable {
alphaProducer()?.let { compatAlpha = it }
return this
}
/** Set the style */
fun IconicsDrawable.style(styleProducer: () -> Paint.Style?): IconicsDrawable {
styleProducer()?.let { style = it }
return this
}
/** Set the typeface of the drawable
* NOTE THIS WILL OVERWRITE THE ICONFONT! */
fun IconicsDrawable.typeface(typefaceProducer: () -> Typeface?): IconicsDrawable {
typefaceProducer()?.let { typeface = it }
return this
}
|
apache-2.0
|
994fe9487a89ce6cb885adb9c0e30b90
| 32.695455 | 114 | 0.711414 | 4.357437 | false | false | false | false |
Skatteetaten/boober
|
src/main/kotlin/no/skatteetaten/aurora/boober/feature/AbstractDeployFeature.kt
|
1
|
20316
|
package no.skatteetaten.aurora.boober.feature
import org.apache.commons.codec.digest.DigestUtils
import org.springframework.beans.factory.annotation.Value
import com.fkorotkov.kubernetes.apps.metadata
import com.fkorotkov.kubernetes.apps.newDeployment
import com.fkorotkov.kubernetes.apps.rollingUpdate
import com.fkorotkov.kubernetes.apps.spec
import com.fkorotkov.kubernetes.apps.strategy
import com.fkorotkov.kubernetes.apps.template
import com.fkorotkov.kubernetes.emptyDir
import com.fkorotkov.kubernetes.fieldRef
import com.fkorotkov.kubernetes.httpGet
import com.fkorotkov.kubernetes.metadata
import com.fkorotkov.kubernetes.newContainer
import com.fkorotkov.kubernetes.newContainerPort
import com.fkorotkov.kubernetes.newEnvVar
import com.fkorotkov.kubernetes.newLabelSelector
import com.fkorotkov.kubernetes.newProbe
import com.fkorotkov.kubernetes.newService
import com.fkorotkov.kubernetes.newServicePort
import com.fkorotkov.kubernetes.newVolume
import com.fkorotkov.kubernetes.newVolumeMount
import com.fkorotkov.kubernetes.securityContext
import com.fkorotkov.kubernetes.spec
import com.fkorotkov.kubernetes.tcpSocket
import com.fkorotkov.kubernetes.valueFrom
import com.fkorotkov.openshift.from
import com.fkorotkov.openshift.imageChangeParams
import com.fkorotkov.openshift.importPolicy
import com.fkorotkov.openshift.metadata
import com.fkorotkov.openshift.newDeploymentConfig
import com.fkorotkov.openshift.newDeploymentTriggerPolicy
import com.fkorotkov.openshift.newImageStream
import com.fkorotkov.openshift.newTagReference
import com.fkorotkov.openshift.recreateParams
import com.fkorotkov.openshift.rollingParams
import com.fkorotkov.openshift.spec
import com.fkorotkov.openshift.strategy
import com.fkorotkov.openshift.template
import io.fabric8.kubernetes.api.model.Container
import io.fabric8.kubernetes.api.model.EnvVarBuilder
import io.fabric8.kubernetes.api.model.IntOrString
import io.fabric8.kubernetes.api.model.IntOrStringBuilder
import io.fabric8.kubernetes.api.model.Probe
import io.fabric8.kubernetes.api.model.Service
import io.fabric8.kubernetes.api.model.apps.Deployment
import io.fabric8.openshift.api.model.DeploymentConfig
import no.skatteetaten.aurora.boober.model.AuroraConfigFieldHandler
import no.skatteetaten.aurora.boober.model.AuroraConfigFileType
import no.skatteetaten.aurora.boober.model.AuroraContextCommand
import no.skatteetaten.aurora.boober.model.AuroraDeploymentSpec
import no.skatteetaten.aurora.boober.model.AuroraResource
import no.skatteetaten.aurora.boober.model.AuroraVersion
import no.skatteetaten.aurora.boober.model.Paths
import no.skatteetaten.aurora.boober.model.PortNumbers
import no.skatteetaten.aurora.boober.model.Validator
import no.skatteetaten.aurora.boober.model.openshift.ApplicationDeployment
import no.skatteetaten.aurora.boober.utils.addIfNotNull
import no.skatteetaten.aurora.boober.utils.boolean
import no.skatteetaten.aurora.boober.utils.ensureStartWith
import no.skatteetaten.aurora.boober.utils.length
import no.skatteetaten.aurora.boober.utils.normalizeLabels
import no.skatteetaten.aurora.boober.utils.oneOf
import no.skatteetaten.aurora.boober.utils.allowedPattern
import no.skatteetaten.aurora.boober.utils.removeExtension
val AuroraDeploymentSpec.envName get(): String = this.getOrNull("env/name") ?: this["envName"]
val AuroraDeploymentSpec.name get(): String = this["name"]
val AuroraDeploymentSpec.affiliation get(): String = this["affiliation"]
val AuroraDeploymentSpec.type get(): TemplateType = this["type"]
val AuroraDeploymentSpec.deployState get(): DeploymentState = this["deployState"]
val AuroraDeploymentSpec.isJob get(): Boolean = this.type in listOf(TemplateType.job, TemplateType.cronjob)
val AuroraDeploymentSpec.applicationDeploymentId: String get() = this["applicationDeploymentId"]
val AuroraDeploymentSpec.applicationDeploymentRef: String get() = this["applicationDeploymentRef"]
val AuroraDeploymentSpec.namespace
get(): String {
return when {
envName.isBlank() -> affiliation
envName.startsWith("-") -> "${affiliation}$envName"
else -> "$affiliation-$envName"
}
}
val AuroraDeploymentSpec.releaseTo: String? get() = if (this.type == TemplateType.deploy || this.type == TemplateType.cronjob) { this.getOrNull<String>("releaseTo")?.takeUnless { it.isEmpty() } } else { null }
val AuroraDeploymentSpec.groupId: String get() = this["groupId"]
val AuroraDeploymentSpec.artifactId: String get() = this["artifactId"]
val AuroraDeploymentSpec.envAutoDeploy: Boolean get() = this["env/autoDeploy"] ?: false
val AuroraDeploymentSpec.dockerGroup get() = groupId.replace(".", "_")
val AuroraDeploymentSpec.dockerImagePath: String get() = "$dockerGroup/${this.artifactId}"
// TODO: This version/deployTag can be empty if template and version is not set in auroraConfig, can we just enforce
// TODO: everybody to have version for template and say it is required?
val AuroraDeploymentSpec.version: String get() = this["version"]
val podEnvVariables = listOf(
newEnvVar {
name = "POD_NAME"
valueFrom {
fieldRef {
apiVersion = "v1"
fieldPath = "metadata.name"
}
}
},
newEnvVar {
name = "POD_NAMESPACE"
valueFrom {
fieldRef {
apiVersion = "v1"
fieldPath = "metadata.namespace"
}
}
}
)
val loggingMount = newVolumeMount {
name = "application-log-volume"
mountPath = Paths.logPath
}
// transform to resource right away?
fun AuroraDeploymentSpec.probe(name: String): Probe? {
val adc = this
return this.featureEnabled(name) { field ->
newProbe {
val probePort = IntOrStringBuilder().withIntVal(adc["$field/port"]).build()
adc.getOrNull<String>("$field/path")?.let { probePath ->
httpGet {
path = probePath.ensureStartWith("/")
port = probePort
}
} ?: tcpSocket {
port = probePort
}
initialDelaySeconds = adc["$field/delay"]
timeoutSeconds = adc["$field/timeout"]
}
}
}
val AuroraDeploymentSpec.cluster: String get() = this["cluster"]
fun AuroraDeploymentSpec.extractPlaceHolders(): Map<String, String> {
val segmentPair = this.getOrNull<String>("segment")?.let {
"segment" to it
}
val placeholders = mapOf(
"name" to name,
"env" to envName,
"affiliation" to affiliation,
"cluster" to cluster
).addIfNotNull(segmentPair)
return placeholders
}
val AuroraDeploymentSpec.versionHandler: AuroraConfigFieldHandler
get() =
AuroraConfigFieldHandler(
"version",
validator = {
it.allowedPattern(
pattern = "^[\\w][\\w.-]{0,127}$",
message = "Version must be a 128 characters or less, alphanumeric and can contain dots and dashes",
required = true
)
}
)
val AuroraDeploymentSpec.groupIdHandler: AuroraConfigFieldHandler
get() = AuroraConfigFieldHandler(
"groupId",
validator = {
it.length(
length = 200,
message = "GroupId must be set and be shorter then 200 characters",
required = this.type.isGroupIdRequired
)
}
)
fun gavHandlers(spec: AuroraDeploymentSpec, cmd: AuroraContextCommand): Set<AuroraConfigFieldHandler> {
val artifactValidator: Validator =
{ it.length(50, "ArtifactId must be set and be shorter then 50 characters", false) }
val artifactHandler = AuroraConfigFieldHandler(
"artifactId",
defaultValue = cmd.applicationFiles.find { it.type == AuroraConfigFileType.BASE }?.name?.removeExtension(),
defaultSource = "fileName",
validator = artifactValidator
)
return setOf(
artifactHandler,
spec.groupIdHandler,
spec.versionHandler
)
}
abstract class AbstractDeployFeature(
@Value("\${integrations.docker.registry}") val dockerRegistry: String
) : Feature {
abstract fun createContainers(adc: AuroraDeploymentSpec): List<Container>
abstract fun enable(platform: ApplicationPlatform): Boolean
override fun enable(header: AuroraDeploymentSpec): Boolean {
return header.type in listOf(
TemplateType.deploy,
TemplateType.development,
) && enable(header.applicationPlatform)
}
override fun handlers(header: AuroraDeploymentSpec, cmd: AuroraContextCommand): Set<AuroraConfigFieldHandler> =
gavHandlers(header, cmd) + setOf(
AuroraConfigFieldHandler("releaseTo"),
AuroraConfigFieldHandler(
"deployStrategy/type",
defaultValue = "rolling",
validator = { it.oneOf(listOf("recreate", "rolling")) }
),
AuroraConfigFieldHandler("deployStrategy/timeout", defaultValue = 180),
AuroraConfigFieldHandler("replicas", defaultValue = 1),
AuroraConfigFieldHandler("serviceAccount"),
AuroraConfigFieldHandler(
"prometheus",
defaultValue = true,
validator = { it.boolean() },
canBeSimplifiedConfig = true
),
AuroraConfigFieldHandler(
"prometheus/path",
defaultValue = "/prometheus"
),
AuroraConfigFieldHandler("prometheus/port", defaultValue = 8081),
AuroraConfigFieldHandler(
"readiness",
defaultValue = true,
validator = { it.boolean() },
canBeSimplifiedConfig = true
),
AuroraConfigFieldHandler("readiness/port", defaultValue = 8080),
AuroraConfigFieldHandler("readiness/path"),
AuroraConfigFieldHandler("readiness/delay", defaultValue = 10),
AuroraConfigFieldHandler("readiness/timeout", defaultValue = 1),
AuroraConfigFieldHandler(
"liveness",
validator = { it.boolean() },
defaultValue = false,
canBeSimplifiedConfig = true
),
AuroraConfigFieldHandler("liveness/port", defaultValue = 8080),
AuroraConfigFieldHandler("liveness/path"),
AuroraConfigFieldHandler("liveness/delay", defaultValue = 10),
AuroraConfigFieldHandler("liveness/timeout", defaultValue = 1)
)
override fun generate(adc: AuroraDeploymentSpec, context: FeatureContext): Set<AuroraResource> {
return if (adc.deployState == DeploymentState.deployment) {
setOf(
generateResource(createDeployment(adc, createContainers(adc))),
generateResource(createService(adc))
)
} else {
setOf(
generateResource(createDeploymentConfig(adc, createContainers(adc))),
generateResource(createService(adc)),
generateResource(createImageStream(adc, dockerRegistry))
)
}
}
override fun modify(
adc: AuroraDeploymentSpec,
resources: Set<AuroraResource>,
context: FeatureContext
) {
val name = adc.artifactId
val id = DigestUtils.sha1Hex("${adc.groupId}/$name")
resources.forEach {
if (it.resource.kind == "ApplicationDeployment") {
val labels = mapOf("applicationId" to id).normalizeLabels()
modifyResource(it, "Added application name and id")
val ad: ApplicationDeployment = it.resource as ApplicationDeployment
if (adc.deployState == DeploymentState.deployment) {
ad.spec.runnableType = "Deployment"
} else {
ad.spec.runnableType = "DeploymentConfig"
}
ad.spec.applicationName = name
ad.spec.applicationId = id
ad.metadata.labels = ad.metadata.labels?.addIfNotNull(labels) ?: labels
}
}
}
fun createService(adc: AuroraDeploymentSpec): Service {
val prometheus = adc.featureEnabled("prometheus") {
HttpEndpoint(adc["$it/path"], adc.getOrNull("$it/port"))
}
val prometheusAnnotations = prometheus?.takeIf { it.path != "" }?.let {
mapOf(
"prometheus.io/scheme" to "http",
"prometheus.io/scrape" to "true",
"prometheus.io/path" to it.path,
"prometheus.io/port" to "${it.port}"
)
} ?: mapOf("prometheus.io/scrape" to "false")
return newService {
metadata {
name = adc.name
namespace = adc.namespace
annotations = prometheusAnnotations
}
spec {
ports = listOf(
newServicePort {
name = "http"
protocol = "TCP"
port = PortNumbers.HTTP_PORT
targetPort = IntOrString(PortNumbers.INTERNAL_HTTP_PORT)
},
newServicePort {
name = "extra"
protocol = "TCP"
port = PortNumbers.EXTRA_APPLICATION_PORT
targetPort = IntOrString(PortNumbers.EXTRA_APPLICATION_PORT)
}
)
selector = mapOf("name" to adc.name)
type = "ClusterIP"
sessionAffinity = "None"
}
}
}
fun createImageStream(adc: AuroraDeploymentSpec, dockerRegistry: String) = newImageStream {
metadata {
name = adc.name
namespace = adc.namespace
labels = mapOf("releasedVersion" to adc.version).normalizeLabels()
}
spec {
dockerImageRepository = "$dockerRegistry/${adc.dockerImagePath}"
tags = listOf(
newTagReference {
name = "default"
from {
kind = "DockerImage"
name = "$dockerRegistry/${adc.dockerImagePath}:${adc.version}"
}
if (!AuroraVersion.isFullAuroraVersion(adc.version)) {
importPolicy {
scheduled = true
}
}
}
)
}
}
fun createContainer(
adc: AuroraDeploymentSpec,
containerName: String,
containerPorts: Map<String, Int>,
containerArgs: List<String> = emptyList()
): Container {
val dockerImage = "$dockerRegistry/${adc.dockerImagePath}:${adc.version}"
return newContainer {
terminationMessagePath = "/dev/termination-log"
imagePullPolicy = "IfNotPresent"
securityContext {
privileged = false
}
volumeMounts = listOf(loggingMount)
if (adc.deployState == DeploymentState.deployment) {
image = dockerImage
}
name = containerName
ports = containerPorts.map {
newContainerPort {
name = it.key
containerPort = it.value
protocol = "TCP"
}
}
args = containerArgs
val portEnv = containerPorts.map {
val portName = if (it.key == "http") "HTTP_PORT" else "${it.key}_HTTP_PORT".uppercase()
EnvVarBuilder().withName(portName).withValue(it.value.toString()).build()
}
env = podEnvVariables + portEnv
adc.probe("liveness")?.let {
livenessProbe = it
}
adc.probe("readiness")?.let { readinessProbe = it }
}
}
fun createDeploymentConfig(
adc: AuroraDeploymentSpec,
container: List<Container>
): DeploymentConfig {
return newDeploymentConfig {
metadata {
name = adc.name
namespace = adc.namespace
}
spec {
strategy {
val deployType: String = adc["deployStrategy/type"]
if (deployType == "rolling") {
type = "Rolling"
rollingParams {
intervalSeconds = 1
maxSurge = IntOrString("25%")
maxUnavailable = IntOrString(0)
timeoutSeconds = adc["deployStrategy/timeout"]
updatePeriodSeconds = 1L
}
} else {
type = "Recreate"
recreateParams {
timeoutSeconds = adc["deployStrategy/timeout"]
}
}
}
triggers = listOf(
newDeploymentTriggerPolicy {
type = "ImageChange"
imageChangeParams {
automatic = true
containerNames = container.map { it.name }
from {
name = "${adc.name}:default"
kind = "ImageStreamTag"
}
}
}
)
replicas = adc["replicas"]
selector = mapOf("name" to adc.name)
template {
spec {
volumes = volumes + newVolume {
name = "application-log-volume"
emptyDir()
}
containers = container
restartPolicy = "Always"
dnsPolicy = "ClusterFirst"
adc.getOrNull<String>("serviceAccount")?.let {
serviceAccount = it
}
}
}
}
}
}
fun createDeployment(
adc: AuroraDeploymentSpec,
container: List<Container>
): Deployment {
// https://kubernetes.io/docs/concepts/workloads/controllers/deployment/
return newDeployment {
metadata {
name = adc.name
namespace = adc.namespace
}
spec {
progressDeadlineSeconds = adc["deployStrategy/timeout"]
strategy {
val deployType: String = adc["deployStrategy/type"]
if (deployType == "rolling") {
type = "RollingUpdate"
rollingUpdate {
maxSurge = IntOrString("25%")
maxUnavailable = IntOrString(0)
}
} else {
type = "Recreate"
}
}
replicas = adc["replicas"]
selector = newLabelSelector {
matchLabels = mapOf("name" to adc.name)
}
template {
metadata {
labels = mapOf("name" to adc.name)
}
spec {
volumes = volumes + newVolume {
name = "application-log-volume"
emptyDir()
}
containers = container
restartPolicy = "Always"
dnsPolicy = "ClusterFirst"
adc.getOrNull<String>("serviceAccount")?.let {
serviceAccount = it
}
}
}
}
}
}
}
data class HttpEndpoint(
val path: String,
val port: Int?
)
|
apache-2.0
|
e96a3840bf095dddc6bae409e903330b
| 36.622222 | 209 | 0.57531 | 5.35054 | false | true | false | false |
allotria/intellij-community
|
platform/platform-impl/src/com/intellij/ide/plugins/marketplace/MarketplacePluginDownloadService.kt
|
3
|
9117
|
// 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.ide.plugins.marketplace
import com.fasterxml.jackson.databind.ObjectMapper
import com.intellij.ide.IdeBundle
import com.intellij.ide.plugins.PluginInstaller
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.PathUtil
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.exists
import com.jetbrains.plugin.blockmap.core.BlockMap
import com.jetbrains.plugin.blockmap.core.FileHash
import java.io.*
import java.net.URLConnection
import java.nio.file.Path
import java.nio.file.Paths
import java.util.zip.ZipInputStream
private val LOG = Logger.getInstance(MarketplacePluginDownloadService::class.java)
private const val BLOCKMAP_ZIP_SUFFIX = ".blockmap.zip"
private const val BLOCKMAP_FILENAME = "blockmap.json"
private const val HASH_FILENAME_SUFFIX = ".hash.json"
private const val FILENAME = "filename="
private const val MAXIMUM_DOWNLOAD_PERCENT = 0.65 // 100% = 1.0
open class MarketplacePluginDownloadService {
companion object {
@JvmStatic
val instance = MarketplacePluginDownloadService()
@JvmStatic
@Throws(IOException::class)
fun getPluginTempFile(): File {
val pluginsTemp = File(PathManager.getPluginTempPath())
if (!pluginsTemp.exists() && !pluginsTemp.mkdirs()) {
throw IOException(IdeBundle.message("error.cannot.create.temp.dir", pluginsTemp))
}
return FileUtil.createTempFile(pluginsTemp, "plugin_", "_download", true, false)
}
@JvmStatic
fun renameFileToZipRoot(zip: File): File {
val newName = "${PluginInstaller.rootEntryName(zip.toPath())}.zip"
val newZip = File("${zip.parent}/$newName")
if (newZip.exists()) {
FileUtil.delete(newZip)
}
FileUtil.rename(zip, newName)
return newZip
}
}
private val objectMapper by lazy { ObjectMapper() }
@Throws(IOException::class)
open fun downloadPlugin(pluginUrl: String, indicator: ProgressIndicator): File {
val file = getPluginTempFile()
return HttpRequests.request(pluginUrl).gzip(false).productNameAsUserAgent().connect(
HttpRequests.RequestProcessor { request: HttpRequests.Request ->
request.saveToFile(file, indicator)
val pluginFileUrl = getPluginFileUrl(request.connection)
if (pluginFileUrl.endsWith(".zip")) {
renameFileToZipRoot(file)
}
else {
val contentDisposition: String? = request.connection.getHeaderField("Content-Disposition")
val url = request.connection.url.toString()
guessPluginFile(contentDisposition, url, file, pluginUrl)
}
})
}
@Throws(IOException::class)
fun downloadPluginViaBlockMap(pluginUrl: String, prevPlugin: Path, indicator: ProgressIndicator): File {
val prevPluginArchive = getPrevPluginArchive(prevPlugin)
if (!prevPluginArchive.exists()) {
LOG.info(IdeBundle.message("error.file.not.found.message", prevPluginArchive.toString()))
return downloadPlugin(pluginUrl, indicator)
}
val (pluginFileUrl, guessFileParameters) = getPluginFileUrlAndGuessFileParameters(pluginUrl)
val blockMapFileUrl = "$pluginFileUrl$BLOCKMAP_ZIP_SUFFIX"
val pluginHashFileUrl = "$pluginFileUrl$HASH_FILENAME_SUFFIX"
try {
val newBlockMap = HttpRequests.request(blockMapFileUrl).productNameAsUserAgent().connect { request ->
request.inputStream.use { input ->
getBlockMapFromZip(input)
}
}
LOG.info("Plugin's blockmap file downloaded")
val newPluginHash = HttpRequests.request(pluginHashFileUrl).productNameAsUserAgent().connect { request ->
request.inputStream.reader().buffered().use { input ->
objectMapper.readValue(input.readText(), FileHash::class.java)
}
}
LOG.info("Plugin's hash file downloaded")
val oldBlockMap = FileInputStream(prevPluginArchive.toFile()).use { input ->
BlockMap(input, newBlockMap.algorithm, newBlockMap.minSize, newBlockMap.maxSize, newBlockMap.normalSize)
}
val downloadPercent = downloadPercent(oldBlockMap, newBlockMap)
LOG.info("Plugin's download percent is = %.2f".format(downloadPercent * 100))
if (downloadPercent > MAXIMUM_DOWNLOAD_PERCENT) {
LOG.info(IdeBundle.message("too.large.download.size"))
return downloadPlugin(pluginFileUrl, indicator)
}
val file = getPluginTempFile()
val merger = PluginChunkMerger(prevPluginArchive.toFile(), oldBlockMap, newBlockMap, indicator)
FileOutputStream(file).use { output -> merger.merge(output, PluginChunkDataSource(oldBlockMap, newBlockMap, pluginFileUrl)) }
val curFileHash = FileInputStream(file).use { input -> FileHash(input, newPluginHash.algorithm) }
if (curFileHash != newPluginHash) {
LOG.info(IdeBundle.message("hashes.doesnt.match"))
return downloadPlugin(pluginFileUrl, indicator)
}
return if (pluginFileUrl.endsWith(".zip")) {
renameFileToZipRoot(file)
}
else {
guessPluginFile(guessFileParameters.contentDisposition, guessFileParameters.url, file, pluginUrl)
}
}
catch (e: Exception) {
LOG.info(IdeBundle.message("error.download.plugin.via.blockmap"), e)
return downloadPlugin(pluginFileUrl, indicator)
}
}
@Throws(IOException::class)
private fun getBlockMapFromZip(input: InputStream): BlockMap {
return input.buffered().use { source ->
ZipInputStream(source).use { zip ->
var entry = zip.nextEntry
while (entry.name != BLOCKMAP_FILENAME && entry.name != null) entry = zip.nextEntry
if (entry.name == BLOCKMAP_FILENAME) {
// there is must only one entry otherwise we can't properly
// read entry because we don't know it size (entry.size returns -1)
objectMapper.readValue(zip.readBytes(), BlockMap::class.java)
}
else {
throw IOException("There is no entry $BLOCKMAP_FILENAME")
}
}
}
}
}
private fun guessPluginFile(contentDisposition: String?, url: String, file: File, pluginUrl: String): File {
val fileName: String = guessFileName(contentDisposition, url, file, pluginUrl)
val newFile = File(file.parentFile, fileName)
FileUtil.rename(file, newFile)
return newFile
}
@Throws(IOException::class)
private fun guessFileName(contentDisposition: String?, usedURL: String, file: File, pluginUrl: String): String {
var fileName: String? = null
LOG.debug("header: $contentDisposition")
if (contentDisposition != null && contentDisposition.contains(FILENAME)) {
val startIdx = contentDisposition.indexOf(FILENAME)
val endIdx = contentDisposition.indexOf(';', startIdx)
fileName = contentDisposition.substring(startIdx + FILENAME.length, if (endIdx > 0) endIdx else contentDisposition.length)
if (StringUtil.startsWithChar(fileName, '\"') && StringUtil.endsWithChar(fileName, '\"')) {
fileName = fileName.substring(1, fileName.length - 1)
}
}
if (fileName == null) {
// try to find a filename in an URL
LOG.debug("url: $usedURL")
fileName = usedURL.substring(usedURL.lastIndexOf('/') + 1)
if (fileName.isEmpty() || fileName.contains("?")) {
fileName = pluginUrl.substring(pluginUrl.lastIndexOf('/') + 1)
}
}
if (!PathUtil.isValidFileName(fileName)) {
LOG.debug("fileName: $fileName")
FileUtil.delete(file)
throw IOException("Invalid filename returned by a server")
}
return fileName
}
private fun downloadPercent(oldBlockMap: BlockMap, newBlockMap: BlockMap): Double {
val oldSet = oldBlockMap.chunks.toSet()
val newChunks = newBlockMap.chunks.filter { chunk -> !oldSet.contains(chunk) }
return newChunks.sumBy { chunk -> chunk.length }.toDouble() /
newBlockMap.chunks.sumBy { chunk -> chunk.length }.toDouble()
}
private fun getPluginFileUrl(connection: URLConnection): String {
val url = connection.url
val port = url.port
return if (port == -1) {
"${url.protocol}://${url.host}${url.path}"
}
else {
"${url.protocol}://${url.host}:${port}${url.path}"
}
}
private data class GuessFileParameters(val contentDisposition: String?, val url: String)
private fun getPluginFileUrlAndGuessFileParameters(pluginUrl: String): Pair<String, GuessFileParameters> {
return HttpRequests.request(pluginUrl).productNameAsUserAgent().connect { request ->
val connection = request.connection
Pair(getPluginFileUrl(connection),
GuessFileParameters(connection.getHeaderField("Content-Disposition"), connection.url.toString()))
}
}
private fun getPrevPluginArchive(prevPlugin: Path): Path {
val suffix = if (prevPlugin.endsWith(".jar")) "" else ".zip"
return Paths.get(PathManager.getPluginTempPath()).resolve("${prevPlugin.fileName}$suffix")
}
|
apache-2.0
|
8bfe308464a6e8efe15b4d96b550e4f9
| 38.812227 | 140 | 0.712844 | 4.222788 | false | false | false | false |
allotria/intellij-community
|
java/java-impl/src/com/intellij/pom/java/JavaLanguageVersionsCollector.kt
|
2
|
2363
|
// 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.pom.java
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.beans.newMetric
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.roots.LanguageLevelModuleExtensionImpl
import com.intellij.openapi.roots.LanguageLevelProjectExtension
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.util.lang.JavaVersion
import java.util.*
class JavaLanguageVersionsCollector : ProjectUsagesCollector() {
override fun getGroupId(): String {
return "java.language"
}
public override fun getMetrics(project: Project): Set<MetricEvent> {
val sdks = ModuleManager.getInstance(project).modules.mapNotNullTo(HashSet()) {
ModuleRootManager.getInstance(it).sdk
}.filter { it.sdkType is JavaSdk }
val jdkVersions = sdks.mapTo(HashSet()) {
JavaVersion.tryParse(it.versionString)
}
val metrics = HashSet<MetricEvent>()
jdkVersions.mapTo(metrics) {
newMetric("MODULE_JDK_VERSION", FeatureUsageData().apply {
addData("feature", it?.feature ?: -1)
addData("minor", it?.minor ?: -1)
addData("update", it?.update ?: -1)
addData("ea", it?.ea ?: false)
})
}
val projectExtension = LanguageLevelProjectExtension.getInstance(project)
if (projectExtension != null) {
val projectLanguageLevel = projectExtension.languageLevel
val languageLevels = ModuleManager.getInstance(project).modules.mapTo(EnumSet.noneOf(LanguageLevel::class.java)) {
LanguageLevelModuleExtensionImpl.getInstance(it)?.languageLevel ?: projectLanguageLevel
}
languageLevels.mapTo(metrics) {
newMetric("MODULE_LANGUAGE_LEVEL", FeatureUsageData().apply {
addData("version", it.toJavaVersion().feature)
addData("preview", it.isPreview)
})
}
}
return metrics
}
override fun requiresReadAccess() = true
override fun getVersion(): Int = 2
}
|
apache-2.0
|
200e4b136fb18dbb58fe3b6d3ec51f5b
| 37.737705 | 140 | 0.738891 | 4.66996 | false | false | false | false |
JetBrains/teamcity-dnx-plugin
|
plugin-dotnet-agent/src/test/kotlin/jetbrains/buildServer/dotnet/test/dotnet/CustomCommandTest.kt
|
1
|
2369
|
package jetbrains.buildServer.dotnet.test.dotnet
import jetbrains.buildServer.agent.CommandLineArgument
import jetbrains.buildServer.agent.Path
import jetbrains.buildServer.agent.ToolPath
import jetbrains.buildServer.dotnet.*
import jetbrains.buildServer.dotnet.test.agent.runner.ParametersServiceStub
import org.testng.Assert
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
class CustomCommandTest {
@DataProvider
fun testCustomArgumentsData(): Array<Array<Any>> {
return arrayOf(
arrayOf(mapOf(Pair(DotnetConstants.PARAM_ARGUMENTS, "custom command arguments")),
listOf("custom", "command", "arguments")))
}
@Test(dataProvider = "testCustomArgumentsData")
fun shouldGetArguments(
parameters: Map<String, String>,
expectedArguments: List<String>) {
// Given
val arguments = parameters[DotnetConstants.PARAM_ARGUMENTS]!!.split(' ').map { CommandLineArgument(it) }.asSequence()
val command = createCommand(arguments = arguments)
// When
val actualArguments = command.getArguments(DotnetBuildContext(ToolPath(Path("wd")), command)).map { it.value }.toList()
// Then
Assert.assertEquals(actualArguments, expectedArguments)
}
@Test
fun shouldProvideCommandType() {
// Given
val command = createCommand()
// When
val actualCommand = command.commandType
// Then
Assert.assertEquals(actualCommand, DotnetCommandType.Custom)
}
@Test
fun shouldProvideToolExecutableFile() {
// Given
val command = createCommand()
// When
val actualExecutable = command.toolResolver.executable
// Then
Assert.assertEquals(actualExecutable, ToolPath(Path("dotnet")))
}
fun createCommand(
parameters: Map<String, String> = emptyMap(),
arguments: Sequence<CommandLineArgument> = emptySequence(),
resultsAnalyzer: ResultsAnalyzer = TestsResultsAnalyzerStub()): DotnetCommand {
return CustomCommand(
ParametersServiceStub(parameters),
resultsAnalyzer,
ArgumentsProviderStub(arguments),
DotnetToolResolverStub(ToolPlatform.CrossPlatform, ToolPath(Path("dotnet")),true))
}
}
|
apache-2.0
|
7cbe58161ca576b3a41fc6e6d1ed971e
| 33.347826 | 127 | 0.672436 | 5.172489 | false | true | false | false |
Kotlin/kotlinx.coroutines
|
benchmarks/src/jmh/kotlin/benchmarks/ParametrizedDispatcherBase.kt
|
1
|
1438
|
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package benchmarks
import benchmarks.akka.CORES_COUNT
import kotlinx.coroutines.*
import kotlinx.coroutines.scheduling.*
import org.openjdk.jmh.annotations.Param
import org.openjdk.jmh.annotations.Setup
import org.openjdk.jmh.annotations.TearDown
import java.io.Closeable
import java.util.concurrent.*
import kotlin.coroutines.CoroutineContext
/**
* Base class to use different [CoroutineContext] in benchmarks via [Param] in inheritors.
* Currently allowed values are "fjp" for [CommonPool] and ftp_n for [ThreadPoolDispatcher] with n threads.
*/
abstract class ParametrizedDispatcherBase : CoroutineScope {
abstract var dispatcher: String
override lateinit var coroutineContext: CoroutineContext
private var closeable: Closeable? = null
@Setup
open fun setup() {
coroutineContext = when {
dispatcher == "fjp" -> ForkJoinPool.commonPool().asCoroutineDispatcher()
dispatcher == "scheduler" -> {
Dispatchers.Default
}
dispatcher.startsWith("ftp") -> {
newFixedThreadPoolContext(dispatcher.substring(4).toInt(), dispatcher).also { closeable = it }
}
else -> error("Unexpected dispatcher: $dispatcher")
}
}
@TearDown
fun tearDown() {
closeable?.close()
}
}
|
apache-2.0
|
09da916fb4763783c69be7d06d662358
| 30.26087 | 110 | 0.687761 | 4.668831 | false | false | false | false |
byoutline/kickmaterial
|
app/src/main/java/com/byoutline/kickmaterial/features/projectlist/ProjectsListScrollListener.kt
|
1
|
1836
|
package com.byoutline.kickmaterial.features.projectlist
import android.content.Context
import android.graphics.Color
import android.support.v7.widget.RecyclerView
import com.byoutline.kickmaterial.R
import com.byoutline.kickmaterial.databinding.FragmentProjectsBinding
import com.byoutline.kickmaterial.utils.KickMaterialFragment
import com.byoutline.secretsauce.utils.ViewUtils
private const val BG_COLOR_MAX = 255
private const val BG_COLOR_MIN = 232
class ProjectsListScrollListener(context: Context,
private val hostActivityProv: () -> KickMaterialFragment.HostActivity?,
private val binding: FragmentProjectsBinding) : RecyclerView.OnScrollListener() {
var summaryScrolled: Float = 0f
private val toolbarScrollPoint: Float = ViewUtils.dpToPx(24f, context).toFloat()
private val maxScroll: Float = (2 * context.resources.getDimensionPixelSize(R.dimen.project_header_padding_top) + ViewUtils.dpToPx(48f, context)).toFloat()
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (dy > toolbarScrollPoint) {
hostActivityProv()?.showToolbar(false, true)
}
if (dy < toolbarScrollPoint * -1) {
hostActivityProv()?.showToolbar(true, true)
}
summaryScrolled += dy.toFloat()
binding.bubblesIv.translationY = -0.5f * summaryScrolled
var alpha = summaryScrolled / maxScroll
alpha = Math.min(1.0f, alpha)
hostActivityProv()?.setToolbarAlpha(alpha)
//change background color on scroll
val color = Math.max(BG_COLOR_MIN.toDouble(), BG_COLOR_MAX - summaryScrolled * 0.05).toInt()
binding.mainParentRl.setBackgroundColor(Color.argb(255, color, color, color))
}
}
|
apache-2.0
|
1722634db117ef6939242f61a53695b6
| 39.822222 | 159 | 0.705338 | 4.434783 | false | false | false | false |
FuturemanGaming/FutureBot-Discord
|
src/main/kotlin/com/futuremangaming/futurebot/internal/CommandManagement.kt
|
1
|
2643
|
/*
* Copyright 2014-2017 FuturemanGaming
*
* 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.futuremangaming.futurebot.internal
import club.minnced.kjda.entities.div
import com.futuremangaming.futurebot.FutureBot
import com.futuremangaming.futurebot.command.*
import com.futuremangaming.futurebot.command.help.Helpers
import net.dv8tion.jda.core.JDA
import net.dv8tion.jda.core.events.Event
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent
import net.dv8tion.jda.core.hooks.EventListener
class CommandManagement(val bot: FutureBot, val jda: JDA) : EventListener {
val prefix: String get() = System.getProperty("bot.prefix", "!")
val helpers = Helpers(this)
private val commands: Set<Command> = mutableSetOf(helpers.adapter) +
getMusic() + // Music : Play, Skip, Queue, Shuffle
getStats() + // Stats : Ping, Uptime
getAdmin() + // Admin : Eval, Shutdown, Settings
getMods() + // Mods : Prune, Lock, Unlock, Giveaway, Draw
getSocial() // Social: Merch, Twitter, Youtube, Twitch
val groups: Map<CommandGroup, List<Command>> by lazy { groups() }
fun group(shortName: String)
= commands.asSequence()
.filter { shortName == it.group.shortName }
.toList()
private fun groups() = commands.asSequence().groupBy { it.group }
fun onMessage(event: GuildMessageReceivedEvent) {
if (event.author.isBot) return
val rawC = event.message.rawContent
//val user = event.author
//val channel = event.channel
if (rawC.startsWith(prefix).not()) return
val args = event.message / 2
val name = args[0].substring(prefix.length).toLowerCase()
val cArgs = if (args.size > 1) args[1] else ""
commands.filter { name == it.name }
.forEach { it.onCommand(cArgs, event, bot) }
}
override fun onEvent(event: Event?) {
if (event is GuildMessageReceivedEvent)
onMessage(event)
}
}
|
apache-2.0
|
30be5a06e88f7d66cf9699b7b93c0715
| 36.757143 | 86 | 0.654181 | 4.11042 | false | false | false | false |
mdaniel/intellij-community
|
platform/execution-impl/src/com/intellij/execution/target/TargetUIUtil.kt
|
1
|
3891
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName(name = "TargetUIUtil")
package com.intellij.execution.target
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.TextComponentAccessor
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.MutableProperty
import com.intellij.ui.layout.*
import com.intellij.util.ui.JBInsets
import java.util.function.Supplier
import javax.swing.JComponent
import javax.swing.JPanel
/**
* See [BrowsableTargetEnvironmentType.createBrowser]
*/
@Deprecated("Use overloaded method with Kotlin UI DSL 2 API")
fun textFieldWithBrowseTargetButton(row: Row,
targetType: BrowsableTargetEnvironmentType,
targetSupplier: Supplier<out TargetEnvironmentConfiguration>,
project: Project,
@NlsContexts.DialogTitle title: String,
property: PropertyBinding<String>,
noLocalFs: Boolean = false): CellBuilder<TextFieldWithBrowseButton> {
val textFieldWithBrowseButton = TextFieldWithBrowseButton()
val browser = targetType.createBrowser(project,
title,
TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT,
textFieldWithBrowseButton.textField,
targetSupplier,
noLocalFs)
textFieldWithBrowseButton.addActionListener(browser)
textFieldWithBrowseButton.text = property.get()
return row.component(textFieldWithBrowseButton).withBinding(TextFieldWithBrowseButton::getText,
TextFieldWithBrowseButton::setText,
property)
}
/**
* See [BrowsableTargetEnvironmentType.createBrowser]
*/
fun com.intellij.ui.dsl.builder.Row.textFieldWithBrowseTargetButton(targetType: BrowsableTargetEnvironmentType,
targetSupplier: Supplier<out TargetEnvironmentConfiguration>,
project: Project,
@NlsContexts.DialogTitle title: String,
property: MutableProperty<String>): Cell<TextFieldWithBrowseButton> {
val textFieldWithBrowseButton = TextFieldWithBrowseButton()
val browser = targetType.createBrowser(project,
title,
TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT,
textFieldWithBrowseButton.textField,
targetSupplier,
false)
textFieldWithBrowseButton.addActionListener(browser)
return cell(textFieldWithBrowseButton)
.bind(TextFieldWithBrowseButton::getText, TextFieldWithBrowseButton::setText, property)
}
/**
* Workarounds cropping the focus highlighting frame around UI components (e.g. around text fields and combo boxes) when Kotlin UI DSL
* [panel] is placed inside arbitrary [JPanel].
*
* @receiver the panel where Kotlin UI DSL elements are placed
*/
@Deprecated("Not needed for Kotlin UI DSL 2, should be removed")
fun <T : JComponent> T.fixHighlightingOfUiDslComponents(): T = apply {
border = IdeBorderFactory.createEmptyBorder(JBInsets(4, 0, 3, 3))
}
|
apache-2.0
|
560496b3f80b4d9a40526520bf35b01f
| 52.315068 | 140 | 0.606528 | 6.306321 | false | false | false | false |
SkyTreasure/Kotlin-Firebase-Group-Chat
|
app/src/main/java/io/skytreasure/kotlingroupchat/chat/ui/adapter/ChatMessagesRecyclerAdapter.kt
|
1
|
4373
|
package io.skytreasure.kotlingroupchat.chat.ui.adapter
import android.content.Context
import android.databinding.DataBindingUtil
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import com.firebase.ui.database.FirebaseRecyclerAdapter
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.Query
import io.skytreasure.kotlingroupchat.R
import io.skytreasure.kotlingroupchat.R.id.chat_messages_recycler
import io.skytreasure.kotlingroupchat.chat.model.MessageModel
import io.skytreasure.kotlingroupchat.chat.model.UserModel
import io.skytreasure.kotlingroupchat.common.constants.DataConstants.Companion.groupMessageMap
import io.skytreasure.kotlingroupchat.common.constants.DataConstants.Companion.userMap
import io.skytreasure.kotlingroupchat.common.util.MyTextUtil
import io.skytreasure.kotlingroupchat.common.util.SharedPrefManager
import io.skytreasure.kotlingroupchat.databinding.ItemChatRowBinding
/**
* Created by akash on 24/10/17.
*/
class ChatMessagesRecyclerAdapter(var groupId: String, var context: Context, var ref: Query) :
FirebaseRecyclerAdapter<MessageModel, ChatMessagesRecyclerAdapter.ViewHolder>(
MessageModel::class.java, R.layout.item_chat_row,
ChatMessagesRecyclerAdapter.ViewHolder::class.java, ref) {
var firstMessage: MessageModel = MessageModel()
var totalCount: Int = 0;
override fun populateViewHolder(holder: ViewHolder?, model: MessageModel?, position: Int) {
val viewHolder = holder as ViewHolder
val chatMessage = model!!
totalCount = position
if (position == 0) {
firstMessage = chatMessage
}
if (chatMessage.sender_id.toString() == currentUser.uid) {
viewHolder.llParent.gravity = Gravity.END
viewHolder.llChild.background =
ContextCompat.getDrawable(context, R.drawable.chat_bubble_grey_sender)
viewHolder.name.text = "You"
} else {
viewHolder.llParent.gravity = Gravity.START
viewHolder.name.text = userMap?.get(chatMessage.sender_id!!)?.name
viewHolder.llChild.background = ContextCompat.getDrawable(viewHolder.llParent.context, R.drawable.chat_bubble_grey)
}
viewHolder.message.text = chatMessage.message
try {
viewHolder.timestamp.text = MyTextUtil().getTimestamp(chatMessage.timestamp?.toLong()!!)
} catch (e: Exception) {
e.printStackTrace()
}
viewHolder.rlName.layoutParams.width = viewHolder.message.layoutParams.width
}
var currentUser: UserModel = SharedPrefManager.getInstance(context).savedUserModel!!
/* override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ChatMessagesRecyclerAdapter.ViewHolder =
ViewHolder(DataBindingUtil.inflate(LayoutInflater.from(parent?.context),
R.layout.item_chat_row, parent, false)
)*/
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder =
ViewHolder(LayoutInflater.from(parent?.context).inflate(R.layout.item_chat_row, parent, false))
override fun getItem(position: Int): MessageModel {
return super.getItem(position)
}
override fun getItemCount(): Int {
return super.getItemCount()
}
/* override fun getItemCount(): Int {
*//**//* if (MyChatManager.getChatMessages(mKey) == null) return 0
else return MyChatManager.getChatMessages(mKey)!!.size*//**//*
return messageList.size
} */
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var llParent = itemView.findViewById(R.id.ll_parent) as LinearLayout
var llChild = itemView.findViewById(R.id.ll_child) as LinearLayout
var name = itemView.findViewById(R.id.name) as TextView
var timestamp = itemView.findViewById(R.id.timestamp) as TextView
var rlName = itemView.findViewById(R.id.rl_name) as RelativeLayout
var message = itemView.findViewById(R.id.message) as TextView
}
}
|
mit
|
6f46235a1d02d62c7e6083df9d8eb53f
| 40.264151 | 127 | 0.723073 | 4.647184 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/BooleanLiteralArgumentInspection.kt
|
1
|
4683
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING
import com.intellij.codeInspection.ProblemHighlightType.INFORMATION
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.intentions.AddNameToArgumentIntention
import org.jetbrains.kotlin.idea.intentions.AddNamesToCallArgumentsIntention
import org.jetbrains.kotlin.idea.intentions.AddNamesToFollowingArgumentsIntention
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import javax.swing.JComponent
class BooleanLiteralArgumentInspection(
@JvmField var reportSingle: Boolean = false
) : AbstractKotlinInspection() {
companion object {
private val ignoreConstructors = listOf("kotlin.Pair", "kotlin.Triple").map { FqName(it) }
}
private fun KtExpression.isBooleanLiteral(): Boolean =
this is KtConstantExpression && node.elementType == KtNodeTypes.BOOLEAN_CONSTANT
private fun KtValueArgument.isUnnamedBooleanLiteral(): Boolean =
!isNamed() && getArgumentExpression()?.isBooleanLiteral() == true
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
valueArgumentVisitor(fun(argument: KtValueArgument) {
if (argument.isNamed()) return
val argumentExpression = argument.getArgumentExpression() ?: return
if (!argumentExpression.isBooleanLiteral()) return
val call = argument.getStrictParentOfType<KtCallExpression>() ?: return
val valueArguments = call.valueArguments
if (argumentExpression.safeAnalyzeNonSourceRootCode().diagnostics.forElement(argumentExpression).any { it.severity == Severity.ERROR }) return
if (AddNameToArgumentIntention.detectNameToAdd(argument, shouldBeLastUnnamed = false) == null) return
val resolvedCall = call.resolveToCall() ?: return
if ((resolvedCall.resultingDescriptor as? ClassConstructorDescriptor)?.constructedClass?.fqNameOrNull() in ignoreConstructors) {
return
}
if (!resolvedCall.candidateDescriptor.hasStableParameterNames()) return
val languageVersionSettings = call.languageVersionSettings
if (valueArguments.any {
!AddNameToArgumentIntention.argumentMatchedAndCouldBeNamedInCall(it, resolvedCall, languageVersionSettings)
}
) return
val highlightType = if (reportSingle) {
GENERIC_ERROR_OR_WARNING
} else {
val hasNeighbourUnnamedBoolean = valueArguments.asSequence().windowed(size = 2, step = 1).any { (prev, next) ->
prev == argument && next.isUnnamedBooleanLiteral() ||
next == argument && prev.isUnnamedBooleanLiteral()
}
if (hasNeighbourUnnamedBoolean) GENERIC_ERROR_OR_WARNING else INFORMATION
}
val fix = if (argument != valueArguments.lastOrNull { !it.isNamed() }) {
if (argument == valueArguments.firstOrNull()) {
AddNamesToCallArgumentsIntention()
} else {
AddNamesToFollowingArgumentsIntention()
}
} else {
AddNameToArgumentIntention()
}
holder.registerProblemWithoutOfflineInformation(
argument, KotlinBundle.message("boolean.literal.argument.without.parameter.name"),
isOnTheFly, highlightType, IntentionWrapper(fix)
)
})
override fun createOptionsPanel(): JComponent {
val panel = MultipleCheckboxOptionsPanel(this)
panel.addCheckbox(KotlinBundle.message("report.also.on.call.with.single.boolean.literal.argument"), "reportSingle")
return panel
}
}
|
apache-2.0
|
9a8f932f4c1a4d8423e6868850004f7d
| 51.033333 | 158 | 0.71215 | 5.477193 | false | false | false | false |
fluidsonic/fluid-json
|
ktor-serialization/sources-jvm/FluidJsonConverter.kt
|
1
|
1372
|
package io.fluidsonic.json
import io.ktor.content.TextContent
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.serialization.*
import io.ktor.util.reflect.*
import io.ktor.utils.io.*
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.jvm.javaio.*
import kotlinx.coroutines.*
public class FluidJsonConverter(
private val parser: JsonCodingParser<*> = JsonCodingParser.nonRecursive,
private val serializer: JsonCodingSerializer = JsonCodingSerializer.nonRecursive,
) : ContentConverter {
@Suppress("INVISIBLE_MEMBER")
override suspend fun deserialize(charset: Charset, typeInfo: TypeInfo, content: ByteReadChannel): Any? =
withContext(Dispatchers.IO) {
parser.parseValueOfTypeOrNull(content.toInputStream().reader(charset), JsonCodingType.of(typeInfo.reifiedType))
}
override suspend fun serializeNullable(contentType: ContentType, charset: Charset, typeInfo: TypeInfo, value: Any?): OutgoingContent =
TextContent(serializer.serializeValue(value), contentType)
}
public fun Configuration.fluidJson(
contentType: ContentType = ContentType.Application.Json,
parser: JsonCodingParser<*> = JsonCodingParser.nonRecursive,
serializer: JsonCodingSerializer = JsonCodingSerializer.nonRecursive,
) {
register(
contentType = contentType,
converter = FluidJsonConverter(
parser = parser,
serializer = serializer,
),
)
}
|
apache-2.0
|
a3098a47c21a94bb9fba5ea0556b81e8
| 30.906977 | 135 | 0.78863 | 3.988372 | false | false | false | false |
apollographql/apollo-android
|
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/java/file/UnionBuilder.kt
|
1
|
1461
|
package com.apollographql.apollo3.compiler.codegen.java.file
import com.apollographql.apollo3.compiler.codegen.java.CodegenJavaFile
import com.apollographql.apollo3.compiler.codegen.java.JavaClassBuilder
import com.apollographql.apollo3.compiler.codegen.java.JavaContext
import com.apollographql.apollo3.compiler.codegen.java.helpers.maybeAddDeprecation
import com.apollographql.apollo3.compiler.codegen.java.helpers.maybeAddDescription
import com.apollographql.apollo3.compiler.ir.IrUnion
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.TypeSpec
import javax.lang.model.element.Modifier
class UnionBuilder(
private val context: JavaContext,
private val union: IrUnion
): JavaClassBuilder {
private val layout = context.layout
private val packageName = layout.typePackageName()
private val simpleName = layout.compiledTypeName(name = union.name)
override fun prepare() {
context.resolver.registerSchemaType(union.name, ClassName.get(packageName, simpleName))
}
override fun build(): CodegenJavaFile {
return CodegenJavaFile(
packageName = packageName,
typeSpec = union.typeSpec()
)
}
private fun IrUnion.typeSpec(): TypeSpec {
return TypeSpec
.classBuilder(simpleName)
.addModifiers(Modifier.PUBLIC)
.maybeAddDescription(description)
.maybeAddDeprecation(deprecationReason)
.addField(typeFieldSpec(context.resolver))
.build()
}
}
|
mit
|
e3245012818c8779034e772ceeecf428
| 34.634146 | 91 | 0.776181 | 4.440729 | false | false | false | false |
androidx/androidx
|
collection/collection/src/nativeMain/kotlin/androidx/collection/internal/Lock.native.kt
|
3
|
2650
|
/*
* 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.internal
import kotlin.native.internal.createCleaner
import kotlinx.cinterop.Arena
import kotlinx.cinterop.alloc
import kotlinx.cinterop.ptr
import platform.posix.pthread_mutex_destroy
import platform.posix.pthread_mutex_init
import platform.posix.pthread_mutex_lock
import platform.posix.pthread_mutex_t
import platform.posix.pthread_mutex_unlock
import platform.posix.pthread_mutexattr_destroy
import platform.posix.pthread_mutexattr_init
import platform.posix.pthread_mutexattr_settype
import platform.posix.pthread_mutexattr_t
/**
* Wrapper for platform.posix.PTHREAD_MUTEX_RECURSIVE which
* is represented as kotlin.Int on darwin platforms and kotlin.UInt on linuxX64
* See: // https://youtrack.jetbrains.com/issue/KT-41509
*/
internal expect val PTHREAD_MUTEX_RECURSIVE: Int
@Suppress("ACTUAL_WITHOUT_EXPECT") // https://youtrack.jetbrains.com/issue/KT-37316
internal actual class Lock actual constructor() {
private val resources = Resources()
@Suppress("unused") // The returned Cleaner must be assigned to a property
@ExperimentalStdlibApi
private val cleaner = createCleaner(resources, Resources::destroy)
actual inline fun <T> synchronizedImpl(block: () -> T): T {
lock()
return try {
block()
} finally {
unlock()
}
}
fun lock() {
pthread_mutex_lock(resources.mutex.ptr)
}
fun unlock() {
pthread_mutex_unlock(resources.mutex.ptr)
}
private class Resources {
private val arena = Arena()
private val attr: pthread_mutexattr_t = arena.alloc()
val mutex: pthread_mutex_t = arena.alloc()
init {
pthread_mutexattr_init(attr.ptr)
pthread_mutexattr_settype(attr.ptr, PTHREAD_MUTEX_RECURSIVE)
pthread_mutex_init(mutex.ptr, attr.ptr)
}
fun destroy() {
pthread_mutex_destroy(mutex.ptr)
pthread_mutexattr_destroy(attr.ptr)
arena.clear()
}
}
}
|
apache-2.0
|
db5c4a7a057092619948c6864e563ef7
| 30.927711 | 83 | 0.700377 | 4.160126 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/code-insight/inspections-shared/src/org/jetbrains/kotlin/idea/codeInsight/inspections/shared/RedundantConstructorKeywordInspection.kt
|
2
|
1972
|
// 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.codeInsight.inspections.shared
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
import org.jetbrains.kotlin.psi.primaryConstructorVisitor
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
class RedundantConstructorKeywordInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return primaryConstructorVisitor { constructor ->
val constructorKeyword = constructor.getConstructorKeyword()
if (constructor.containingClassOrObject is KtClass &&
constructorKeyword != null &&
constructor.modifierList == null
) {
holder.registerProblem(
constructor,
KotlinBundle.message("redundant.constructor.keyword"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
constructorKeyword.textRangeInParent,
RemoveRedundantConstructorFix()
)
}
}
}
}
private class RemoveRedundantConstructorFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.redundant.constructor.keyword.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val constructor = descriptor.psiElement as? KtPrimaryConstructor ?: return
constructor.removeRedundantConstructorKeywordAndSpace()
}
}
|
apache-2.0
|
d1744b2836b578fac637c7b0f3918348
| 43.818182 | 120 | 0.725659 | 5.55493 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/contributors/FirClassifierCompletionContributor.kt
|
4
|
5599
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.completion.contributors
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.analysis.api.types.KtNonErrorClassType
import org.jetbrains.kotlin.idea.completion.checkers.CompletionVisibilityChecker
import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext
import org.jetbrains.kotlin.idea.completion.context.FirNameReferencePositionContext
import org.jetbrains.kotlin.idea.completion.contributors.helpers.FirClassifierProvider.getAvailableClassifiersCurrentScope
import org.jetbrains.kotlin.idea.completion.contributors.helpers.FirClassifierProvider.getAvailableClassifiersFromIndex
import org.jetbrains.kotlin.idea.completion.contributors.helpers.getStaticScope
import org.jetbrains.kotlin.idea.completion.lookups.ImportStrategy
import org.jetbrains.kotlin.idea.completion.weighers.WeighingContext
import org.jetbrains.kotlin.idea.completion.weighers.WeighingContext.Companion.createWeighingContext
import org.jetbrains.kotlin.psi.KtExpression
internal open class FirClassifierCompletionContributor(
basicContext: FirBasicCompletionContext,
priority: Int,
) : FirCompletionContributorBase<FirNameReferencePositionContext>(basicContext, priority) {
protected open fun KtAnalysisSession.filterClassifiers(classifierSymbol: KtClassifierSymbol): Boolean = true
protected open fun KtAnalysisSession.getImportingStrategy(classifierSymbol: KtClassifierSymbol): ImportStrategy =
importStrategyDetector.detectImportStrategy(classifierSymbol)
override fun KtAnalysisSession.complete(positionContext: FirNameReferencePositionContext) {
val visibilityChecker = CompletionVisibilityChecker.create(basicContext, positionContext)
val weighingContext = createWeighingContext(null, null, emptyList(), basicContext.fakeKtFile)
when (val receiver = positionContext.explicitReceiver) {
null -> {
completeWithoutReceiver(positionContext, visibilityChecker, weighingContext)
}
else -> {
completeWithReceiver(receiver, visibilityChecker, weighingContext)
}
}
}
private fun KtAnalysisSession.completeWithReceiver(
receiver: KtExpression,
visibilityChecker: CompletionVisibilityChecker,
context: WeighingContext
) {
val reference = receiver.reference() ?: return
val scope = getStaticScope(reference) ?: return
scope
.getClassifierSymbols(scopeNameFilter)
.filter { filterClassifiers(it) }
.filter { visibilityChecker.isVisible(it) }
.forEach { addClassifierSymbolToCompletion(it, context, ImportStrategy.DoNothing) }
}
private fun KtAnalysisSession.completeWithoutReceiver(
positionContext: FirNameReferencePositionContext,
visibilityChecker: CompletionVisibilityChecker,
context: WeighingContext
) {
val availableFromScope = mutableSetOf<KtClassifierSymbol>()
getAvailableClassifiersCurrentScope(
originalKtFile,
positionContext.nameExpression,
scopeNameFilter,
visibilityChecker
)
.filter { filterClassifiers(it) }
.forEach { classifierSymbol ->
availableFromScope += classifierSymbol
addClassifierSymbolToCompletion(classifierSymbol, context, ImportStrategy.DoNothing)
}
getAvailableClassifiersFromIndex(
symbolFromIndexProvider,
scopeNameFilter,
visibilityChecker
)
.filter { it !in availableFromScope && filterClassifiers(it) }
.forEach { classifierSymbol ->
addClassifierSymbolToCompletion(classifierSymbol, context, getImportingStrategy(classifierSymbol))
}
}
}
internal class FirAnnotationCompletionContributor(
basicContext: FirBasicCompletionContext,
priority: Int
) : FirClassifierCompletionContributor(basicContext, priority) {
override fun KtAnalysisSession.filterClassifiers(classifierSymbol: KtClassifierSymbol): Boolean = when (classifierSymbol) {
is KtAnonymousObjectSymbol -> false
is KtTypeParameterSymbol -> false
is KtNamedClassOrObjectSymbol -> when (classifierSymbol.classKind) {
KtClassKind.ANNOTATION_CLASS -> true
KtClassKind.ENUM_CLASS -> false
KtClassKind.ANONYMOUS_OBJECT -> false
KtClassKind.CLASS, KtClassKind.OBJECT, KtClassKind.COMPANION_OBJECT, KtClassKind.INTERFACE -> {
// TODO show class if nested classifier is annotation class
// classifierSymbol.getDeclaredMemberScope().getClassifierSymbols().any { filterClassifiers(it) }
false
}
}
is KtTypeAliasSymbol -> {
val expendedClass = (classifierSymbol.expandedType as? KtNonErrorClassType)?.classSymbol
expendedClass?.let { filterClassifiers(it) } == true
}
}
}
internal class FirClassifierReferenceCompletionContributor(
basicContext: FirBasicCompletionContext,
priority: Int
) : FirClassifierCompletionContributor(basicContext, priority) {
override fun KtAnalysisSession.getImportingStrategy(classifierSymbol: KtClassifierSymbol): ImportStrategy =
ImportStrategy.DoNothing
}
|
apache-2.0
|
4cc2bcacea95373858502b9940c62663
| 46.05042 | 158 | 0.737275 | 5.43065 | false | false | false | false |
GunoH/intellij-community
|
plugins/grazie/src/main/kotlin/com/intellij/grazie/GrazieBundle.kt
|
2
|
1221
|
// 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.grazie
import com.intellij.AbstractBundle
import com.intellij.DynamicBundle
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.PropertyKey
import java.util.function.Supplier
object GrazieBundle {
const val DEFAULT_BUNDLE_NAME = "messages.GrazieBundle"
private const val PLUGIN_BUNDLE_NAME = "messages.GraziePluginBundle"
private val defaultBundle by lazy { DynamicBundle.getResourceBundle(javaClass.classLoader, DEFAULT_BUNDLE_NAME) }
private val pluginBundle by lazy { DynamicBundle.getResourceBundle(javaClass.classLoader, PLUGIN_BUNDLE_NAME) }
@Nls
@JvmStatic
fun message(@PropertyKey(resourceBundle = DEFAULT_BUNDLE_NAME) key: String, vararg params: Any): String {
val bundle = if (!GraziePlugin.isBundled && pluginBundle.containsKey(key)) pluginBundle else defaultBundle
return AbstractBundle.message(bundle, key, *params)
}
@JvmStatic
fun messagePointer(@PropertyKey(resourceBundle = DEFAULT_BUNDLE_NAME) key: String, vararg params: Any): Supplier<String> = Supplier {
message(key, *params)
}
}
|
apache-2.0
|
c919a8658e1df796bf0285c4df8b298c
| 42.607143 | 140 | 0.784603 | 4.360714 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/gradle/code-insight-groovy/src/org/jetbrains/kotlin/idea/groovy/GroovyGradleBuildScriptSupport.kt
|
1
|
22626
|
// 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.groovy
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.DependencyScope
import com.intellij.openapi.roots.ExternalLibraryDescriptor
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.idea.base.codeInsight.CliArgumentStringBuilder.buildArgumentString
import org.jetbrains.kotlin.idea.base.codeInsight.CliArgumentStringBuilder.replaceLanguageFeature
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.base.externalSystem.KotlinGradleFacade
import org.jetbrains.kotlin.idea.base.util.reformat
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.configuration.*
import org.jetbrains.kotlin.idea.gradleCodeInsightCommon.*
import org.jetbrains.kotlin.idea.groovy.inspections.DifferentKotlinGradleVersionInspection
import org.jetbrains.kotlin.idea.projectConfiguration.RepositoryDescription
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrApplicationStatement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner
object GroovyGradleBuildScriptSupport : GradleBuildScriptSupport {
override fun createManipulator(file: PsiFile, preferNewSyntax: Boolean): GroovyBuildScriptManipulator? {
if (file !is GroovyFile) {
return null
}
return GroovyBuildScriptManipulator(file, preferNewSyntax)
}
override fun createScriptBuilder(file: PsiFile): SettingsScriptBuilder<*>? {
return if (file is GroovyFile) GroovySettingsScriptBuilder(file) else null
}
}
class GroovyBuildScriptManipulator(
override val scriptFile: GroovyFile,
override val preferNewSyntax: Boolean
) : GradleBuildScriptManipulator<GroovyFile> {
override fun isApplicable(file: PsiFile) = file is GroovyFile
private val gradleVersion = GradleVersionProvider.fetchGradleVersion(scriptFile)
override fun isConfiguredWithOldSyntax(kotlinPluginName: String): Boolean {
val fileText = runReadAction { scriptFile.text }
return containsDirective(fileText, getApplyPluginDirective(kotlinPluginName)) &&
fileText.contains("org.jetbrains.kotlin") &&
fileText.contains("kotlin-stdlib")
}
override fun isConfigured(kotlinPluginExpression: String): Boolean {
val fileText = runReadAction { scriptFile.text }
val pluginsBlockText = runReadAction { scriptFile.getBlockByName("plugins")?.text ?: "" }
return (containsDirective(pluginsBlockText, kotlinPluginExpression)) &&
fileText.contains("org.jetbrains.kotlin") &&
fileText.contains("kotlin-stdlib")
}
override fun configureModuleBuildScript(
kotlinPluginName: String,
kotlinPluginExpression: String,
stdlibArtifactName: String,
version: IdeKotlinVersion,
jvmTarget: String?
): Boolean {
val oldText = scriptFile.text
val useNewSyntax = useNewSyntax(kotlinPluginName, gradleVersion)
if (useNewSyntax) {
scriptFile
.getPluginsBlock()
.addLastExpressionInBlockIfNeeded("$kotlinPluginExpression version '${version.artifactVersion}'")
scriptFile.getRepositoriesBlock().apply {
val repository = getRepositoryForVersion(version)
val gradleFacade = KotlinGradleFacade.instance
if (repository != null && gradleFacade != null) {
scriptFile.module?.getBuildScriptSettingsPsiFile()?.let {
with(GradleBuildScriptSupport.getManipulator(it)) {
addPluginRepository(repository)
addMavenCentralPluginRepository()
addPluginRepository(DEFAULT_GRADLE_PLUGIN_REPOSITORY)
}
}
}
}
} else {
val applyPluginDirective = getGroovyApplyPluginDirective(kotlinPluginName)
if (!containsDirective(scriptFile.text, applyPluginDirective)) {
val apply = GroovyPsiElementFactory.getInstance(scriptFile.project).createExpressionFromText(applyPluginDirective)
val applyStatement = getApplyStatement(scriptFile)
if (applyStatement != null) {
scriptFile.addAfter(apply, applyStatement)
} else {
val anchorBlock = scriptFile.getBlockByName("plugins") ?: scriptFile.getBlockByName("buildscript")
if (anchorBlock != null) {
scriptFile.addAfter(apply, anchorBlock.parent)
} else {
scriptFile.addAfter(apply, scriptFile.statements.lastOrNull() ?: scriptFile.firstChild)
}
}
}
}
scriptFile.getRepositoriesBlock().apply {
addRepository(version)
addMavenCentralIfMissing()
}
scriptFile.getDependenciesBlock().apply {
addExpressionOrStatementInBlockIfNeeded(
getGroovyDependencySnippet(stdlibArtifactName, !useNewSyntax, gradleVersion),
isStatement = false,
isFirst = false
)
}
if (jvmTarget != null) {
changeKotlinTaskParameter(scriptFile, "jvmTarget", jvmTarget, forTests = false)
changeKotlinTaskParameter(scriptFile, "jvmTarget", jvmTarget, forTests = true)
}
return scriptFile.text != oldText
}
override fun configureProjectBuildScript(kotlinPluginName: String, version: IdeKotlinVersion): Boolean {
if (useNewSyntax(kotlinPluginName, gradleVersion)) return false
val oldText = scriptFile.text
scriptFile.apply {
getBuildScriptBlock().apply {
addFirstExpressionInBlockIfNeeded(VERSION.replace(VERSION_TEMPLATE, version.rawVersion))
}
getBuildScriptRepositoriesBlock().apply {
addRepository(version)
addMavenCentralIfMissing()
}
getBuildScriptDependenciesBlock().apply {
addLastExpressionInBlockIfNeeded(CLASSPATH)
}
}
return oldText != scriptFile.text
}
override fun changeLanguageFeatureConfiguration(
feature: LanguageFeature,
state: LanguageFeature.State,
forTests: Boolean
): PsiElement? {
if (usesNewMultiplatform()) {
state.assertApplicableInMultiplatform()
val kotlinBlock = scriptFile.getKotlinBlock()
val sourceSetsBlock = kotlinBlock.getSourceSetsBlock()
val allBlock = sourceSetsBlock.getBlockOrCreate("all")
allBlock.addLastExpressionInBlockIfNeeded("languageSettings.enableLanguageFeature(\"${feature.name}\")")
return allBlock.statements.lastOrNull()
}
val kotlinVersion = DifferentKotlinGradleVersionInspection.getKotlinPluginVersion(scriptFile)
val featureArgumentString = feature.buildArgumentString(state, kotlinVersion)
val parameterName = "freeCompilerArgs"
return addOrReplaceKotlinTaskParameter(
scriptFile,
parameterName,
"[\"$featureArgumentString\"]",
forTests
) { insideKotlinOptions ->
val prefix = if (insideKotlinOptions) "kotlinOptions." else ""
val newText = text.replaceLanguageFeature(
feature,
state,
kotlinVersion,
prefix = "$prefix$parameterName = [",
postfix = "]"
)
replaceWithStatementFromText(newText)
}
}
override fun changeLanguageVersion(version: String, forTests: Boolean): PsiElement? =
changeKotlinTaskParameter(scriptFile, "languageVersion", version, forTests)
override fun changeApiVersion(version: String, forTests: Boolean): PsiElement? =
changeKotlinTaskParameter(scriptFile, "apiVersion", version, forTests)
override fun addKotlinLibraryToModuleBuildScript(
targetModule: Module?,
scope: DependencyScope,
libraryDescriptor: ExternalLibraryDescriptor
) {
val dependencyString = String.format(
"%s \"%s:%s:%s\"",
scope.toGradleCompileScope(scriptFile.isAndroidModule()),
libraryDescriptor.libraryGroupId,
libraryDescriptor.libraryArtifactId,
libraryDescriptor.maxVersion
)
if (targetModule != null && usesNewMultiplatform()) {
scriptFile
.getKotlinBlock()
.getSourceSetsBlock()
.getBlockOrCreate(targetModule.name.takeLastWhile { it != '.' })
.getDependenciesBlock()
.addLastExpressionInBlockIfNeeded(dependencyString)
} else {
scriptFile.getDependenciesBlock().apply {
addLastExpressionInBlockIfNeeded(dependencyString)
}
}
}
override fun getKotlinStdlibVersion(): String? {
val versionProperty = "\$kotlin_version"
scriptFile.getBlockByName("buildScript")?.let {
if (it.text.contains("ext.kotlin_version = ")) {
return versionProperty
}
}
val dependencies = scriptFile.getBlockByName("dependencies")?.statements
val stdlibArtifactPrefix = "org.jetbrains.kotlin:kotlin-stdlib:"
dependencies?.forEach { dependency ->
val dependencyText = dependency.text
val startIndex = dependencyText.indexOf(stdlibArtifactPrefix) + stdlibArtifactPrefix.length
val endIndex = dependencyText.length - 1
if (startIndex != -1 && endIndex != -1) {
return dependencyText.substring(startIndex, endIndex)
}
}
return null
}
private fun addPluginRepositoryExpression(expression: String) {
scriptFile
.getBlockOrPrepend("pluginManagement")
.getBlockOrCreate("repositories")
.addLastExpressionInBlockIfNeeded(expression)
}
override fun addMavenCentralPluginRepository() {
addPluginRepositoryExpression("mavenCentral()")
}
override fun addPluginRepository(repository: RepositoryDescription) {
addPluginRepositoryExpression(repository.toGroovyRepositorySnippet())
}
override fun addResolutionStrategy(pluginId: String) {
scriptFile
.getBlockOrPrepend("pluginManagement")
.getBlockOrCreate("resolutionStrategy")
.getBlockOrCreate("eachPlugin")
.addLastStatementInBlockIfNeeded(
"""
if (requested.id.id == "$pluginId") {
useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${'$'}{requested.version}")
}
""".trimIndent()
)
}
private fun GrClosableBlock.addParameterAssignment(
parameterName: String,
defaultValue: String,
replaceIt: GrStatement.(Boolean) -> GrStatement
) {
statements.firstOrNull { stmt ->
(stmt as? GrAssignmentExpression)?.lValue?.text == parameterName
}?.let { stmt ->
stmt.replaceIt(false)
} ?: addLastExpressionInBlockIfNeeded("$parameterName = $defaultValue")
}
private fun String.extractTextFromQuotes(quoteCharacter: Char): String? {
val quoteIndex = indexOf(quoteCharacter)
if (quoteIndex != -1) {
val lastQuoteIndex = lastIndexOf(quoteCharacter)
return if (lastQuoteIndex > quoteIndex) substring(quoteIndex + 1, lastQuoteIndex) else null
}
return null
}
private fun String.extractTextFromQuotes(): String = extractTextFromQuotes('\'') ?: extractTextFromQuotes('"') ?: this
private fun addOrReplaceKotlinTaskParameter(
gradleFile: GroovyFile,
parameterName: String,
defaultValue: String,
forTests: Boolean,
replaceIt: GrStatement.(Boolean) -> GrStatement
): PsiElement? {
if (usesNewMultiplatform()) {
val kotlinBlock = gradleFile.getKotlinBlock()
val kotlinTargets = kotlinBlock.getBlockOrCreate("targets")
val targetNames = mutableListOf<String>()
fun GrStatement.handleTarget(targetExpectedText: String) {
if (this is GrMethodCallExpression && invokedExpression.text == targetExpectedText) {
val targetNameArgument = argumentList.expressionArguments.getOrNull(1)?.text
if (targetNameArgument != null) {
targetNames += targetNameArgument.extractTextFromQuotes()
}
}
}
for (target in kotlinTargets.statements) {
target.handleTarget("fromPreset")
}
for (target in kotlinBlock.statements) {
target.handleTarget("targets.fromPreset")
}
val configureBlock = kotlinTargets.getBlockOrCreate("configure")
val factory = GroovyPsiElementFactory.getInstance(kotlinTargets.project)
val argumentList = factory.createArgumentListFromText(
targetNames.joinToString(prefix = "([", postfix = "])", separator = ", ")
)
configureBlock.getStrictParentOfType<GrMethodCallExpression>()!!.argumentList.replaceWithArgumentList(argumentList)
val kotlinOptions = configureBlock.getBlockOrCreate("tasks.getByName(compilations.main.compileKotlinTaskName).kotlinOptions")
kotlinOptions.addParameterAssignment(parameterName, defaultValue, replaceIt)
return kotlinOptions.parent.parent
}
val kotlinBlock: GrClosableBlock =
if (gradleFile.isAndroidModule() && gradleFile.getBlockByName("android") != null) {
gradleFile.getBlockOrCreate("tasks.withType(org.jetbrains.kotlin.gradle.tasks.${if (forTests) "KotlinTest" else "KotlinCompile"}).all")
} else {
gradleFile.getBlockOrCreate(if (forTests) "compileTestKotlin" else "compileKotlin")
}
for (stmt in kotlinBlock.statements) {
if ((stmt as? GrAssignmentExpression)?.lValue?.text == "kotlinOptions.$parameterName") {
return stmt.replaceIt(true)
}
}
kotlinBlock.getBlockOrCreate("kotlinOptions").addParameterAssignment(parameterName, defaultValue, replaceIt)
return kotlinBlock.parent
}
private fun changeKotlinTaskParameter(
gradleFile: GroovyFile,
parameterName: String,
parameterValue: String,
forTests: Boolean
): PsiElement? {
return addOrReplaceKotlinTaskParameter(
gradleFile, parameterName, "\"$parameterValue\"", forTests
) { insideKotlinOptions ->
if (insideKotlinOptions) {
replaceWithStatementFromText("kotlinOptions.$parameterName = \"$parameterValue\"")
} else {
replaceWithStatementFromText("$parameterName = \"$parameterValue\"")
}
}
}
private fun getGroovyDependencySnippet(
artifactName: String,
withVersion: Boolean,
gradleVersion: GradleVersionInfo
): String {
val configuration = gradleVersion.scope("implementation")
return "$configuration \"org.jetbrains.kotlin:$artifactName${if (withVersion) ":\$kotlin_version" else ""}\""
}
private fun getApplyPluginDirective(pluginName: String) = "apply plugin: '$pluginName'"
private fun containsDirective(fileText: String, directive: String): Boolean {
return fileText.contains(directive)
|| fileText.contains(directive.replace("\"", "'"))
|| fileText.contains(directive.replace("'", "\""))
}
private fun getApplyStatement(file: GroovyFile): GrApplicationStatement? =
file.getChildrenOfType<GrApplicationStatement>().find { it.invokedExpression.text == "apply" }
private fun GrClosableBlock.addRepository(version: IdeKotlinVersion): Boolean {
val repository = getRepositoryForVersion(version)
val snippet = when {
repository != null -> repository.toGroovyRepositorySnippet()
!isRepositoryConfigured(text) -> "$MAVEN_CENTRAL\n"
else -> return false
}
return addLastExpressionInBlockIfNeeded(snippet)
}
private fun GroovyFile.isAndroidModule() = module?.buildSystemType == BuildSystemType.AndroidGradle
private fun GrStatementOwner.getBuildScriptBlock() = getBlockOrCreate("buildscript") { newBlock ->
val pluginsBlock = getBlockByName("plugins") ?: return@getBlockOrCreate false
addBefore(newBlock, pluginsBlock.parent)
true
}
private fun GrStatementOwner.getBuildScriptRepositoriesBlock(): GrClosableBlock =
getBuildScriptBlock().getRepositoriesBlock()
private fun GrStatementOwner.getBuildScriptDependenciesBlock(): GrClosableBlock =
getBuildScriptBlock().getDependenciesBlock()
private fun GrClosableBlock.addMavenCentralIfMissing(): Boolean =
if (!isRepositoryConfigured(text)) addLastExpressionInBlockIfNeeded(MAVEN_CENTRAL) else false
private fun GrStatementOwner.getRepositoriesBlock() = getBlockOrCreate("repositories")
private fun GrStatementOwner.getDependenciesBlock(): GrClosableBlock = getBlockOrCreate("dependencies")
private fun GrStatementOwner.getKotlinBlock(): GrClosableBlock = getBlockOrCreate("kotlin")
private fun GrStatementOwner.getSourceSetsBlock(): GrClosableBlock = getBlockOrCreate("sourceSets")
private fun GrClosableBlock.addOrReplaceExpression(snippet: String, predicate: (GrStatement) -> Boolean) {
statements.firstOrNull(predicate)?.let { stmt ->
stmt.replaceWithStatementFromText(snippet)
return
}
addLastExpressionInBlockIfNeeded(snippet)
}
private fun getGroovyApplyPluginDirective(pluginName: String) = "apply plugin: '$pluginName'"
private fun GrStatement.replaceWithStatementFromText(snippet: String): GrStatement {
val newStatement = GroovyPsiElementFactory.getInstance(project).createExpressionFromText(snippet)
newStatement.reformat()
return replaceWithStatement(newStatement)
}
companion object {
private const val VERSION_TEMPLATE = "\$VERSION$"
private val VERSION = String.format("ext.kotlin_version = '%s'", VERSION_TEMPLATE)
private const val GRADLE_PLUGIN_ID = "kotlin-gradle-plugin"
private val CLASSPATH = "classpath \"$KOTLIN_GROUP_ID:$GRADLE_PLUGIN_ID:\$kotlin_version\""
private fun PsiElement.getBlockByName(name: String): GrClosableBlock? {
return getChildrenOfType<GrMethodCallExpression>()
.filter { it.closureArguments.isNotEmpty() }
.find { it.invokedExpression.text == name }
?.let { it.closureArguments[0] }
}
fun GrStatementOwner.getBlockOrCreate(
name: String,
customInsert: GrStatementOwner.(newBlock: PsiElement) -> Boolean = { false }
): GrClosableBlock {
var block = getBlockByName(name)
if (block == null) {
val factory = GroovyPsiElementFactory.getInstance(project)
val newBlock = factory.createExpressionFromText("$name{\n}\n")
if (!customInsert(newBlock)) {
addAfter(newBlock, statements.lastOrNull() ?: firstChild)
}
block = getBlockByName(name)!!
}
return block
}
fun GrStatementOwner.getBlockOrPrepend(name: String) = getBlockOrCreate(name) { newBlock ->
addAfter(newBlock, null)
true
}
fun GrStatementOwner.getPluginsBlock() = getBlockOrCreate("plugins") { newBlock ->
addAfter(newBlock, getBlockByName("buildscript"))
true
}
fun GrClosableBlock.addLastExpressionInBlockIfNeeded(expressionText: String): Boolean =
addExpressionOrStatementInBlockIfNeeded(expressionText, isStatement = false, isFirst = false)
fun GrClosableBlock.addLastStatementInBlockIfNeeded(expressionText: String): Boolean =
addExpressionOrStatementInBlockIfNeeded(expressionText, isStatement = true, isFirst = false)
private fun GrClosableBlock.addFirstExpressionInBlockIfNeeded(expressionText: String): Boolean =
addExpressionOrStatementInBlockIfNeeded(expressionText, isStatement = false, isFirst = true)
private fun GrClosableBlock.addExpressionOrStatementInBlockIfNeeded(text: String, isStatement: Boolean, isFirst: Boolean): Boolean {
if (statements.any { StringUtil.equalsIgnoreWhitespaces(it.text, text) }) return false
val psiFactory = GroovyPsiElementFactory.getInstance(project)
val newStatement = if (isStatement) psiFactory.createStatementFromText(text) else psiFactory.createExpressionFromText(text)
newStatement.reformat()
if (!isFirst && statements.isNotEmpty()) {
val lastStatement = statements[statements.size - 1]
if (lastStatement != null) {
addAfter(newStatement, lastStatement)
}
} else {
if (firstChild != null) {
addAfter(newStatement, firstChild)
}
}
return true
}
}
}
|
apache-2.0
|
87c445dfb22d9b2edabd98444c2bd290
| 43.105263 | 151 | 0.662335 | 5.982549 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/slicer/Slicer.kt
|
1
|
16393
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.slicer
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.search.SearchScope
import com.intellij.psi.util.parentOfType
import com.intellij.slicer.JavaSliceUsage
import com.intellij.slicer.SliceUsage
import com.intellij.usageView.UsageInfo
import com.intellij.util.Processor
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.cfg.pseudocode.PseudoValue
import org.jetbrains.kotlin.cfg.pseudocode.Pseudocode
import org.jetbrains.kotlin.cfg.containingDeclarationForPseudocode
import org.jetbrains.kotlin.cfg.pseudocode.getContainingPseudocode
import org.jetbrains.kotlin.cfg.pseudocode.instructions.KtElementInstruction
import org.jetbrains.kotlin.cfg.pseudocode.instructions.eval.*
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.psi.hasInlineModifier
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.getDeepestSuperDeclarations
import org.jetbrains.kotlin.idea.findUsages.KotlinFunctionFindUsagesOptions
import org.jetbrains.kotlin.idea.findUsages.KotlinPropertyFindUsagesOptions
import org.jetbrains.kotlin.idea.findUsages.processAllExactUsages
import org.jetbrains.kotlin.idea.findUsages.processAllUsages
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchOverriders
import org.jetbrains.kotlin.idea.util.actualsForExpected
import org.jetbrains.kotlin.idea.util.expectedDescriptor
import org.jetbrains.kotlin.idea.util.isExpectDeclaration
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.contains
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.utils.addIfNotNull
abstract class Slicer(
protected val element: KtElement,
protected val processor: Processor<in SliceUsage>,
protected val parentUsage: KotlinSliceUsage
) {
abstract fun processChildren(forcedExpressionMode: Boolean)
protected val analysisScope: SearchScope = parentUsage.scope.toSearchScope()
protected val mode: KotlinSliceAnalysisMode = parentUsage.mode
protected val project = element.project
protected class PseudocodeCache {
private val computedPseudocodes = HashMap<KtElement, Pseudocode>()
operator fun get(element: KtElement): Pseudocode? {
val container = element.containingDeclarationForPseudocode ?: return null
return computedPseudocodes.getOrPut(container) {
container.getContainingPseudocode(container.analyzeWithContent())?.apply { computedPseudocodes[container] = this }
?: return null
}
}
}
protected val pseudocodeCache = PseudocodeCache()
protected fun PsiElement.passToProcessor(mode: KotlinSliceAnalysisMode = [email protected]) {
processor.process(KotlinSliceUsage(this, parentUsage, mode, false))
}
protected fun PsiElement.passToProcessorAsValue(mode: KotlinSliceAnalysisMode = [email protected]) {
processor.process(KotlinSliceUsage(this, parentUsage, mode, forcedExpressionMode = true))
}
protected fun PsiElement.passToProcessorInCallMode(
callElement: KtElement,
mode: KotlinSliceAnalysisMode = [email protected],
withOverriders: Boolean = false
) {
val newMode = when (this) {
is KtNamedFunction -> this.callMode(callElement, mode)
is KtParameter -> ownerFunction.callMode(callElement, mode)
is KtTypeReference -> {
val declaration = parent
require(declaration is KtCallableDeclaration)
require(this == declaration.receiverTypeReference)
declaration.callMode(callElement, mode)
}
else -> mode
}
if (withOverriders) {
passDeclarationToProcessorWithOverriders(newMode)
} else {
passToProcessor(newMode)
}
}
protected fun PsiElement.passDeclarationToProcessorWithOverriders(mode: KotlinSliceAnalysisMode = [email protected]) {
passToProcessor(mode)
HierarchySearchRequest(this, analysisScope)
.searchOverriders()
.forEach { it.namedUnwrappedElement?.passToProcessor(mode) }
if (this is KtCallableDeclaration && isExpectDeclaration()) {
resolveToDescriptorIfAny()
?.actualsForExpected()
?.forEach {
(it as? DeclarationDescriptorWithSource)?.toPsi()?.passToProcessor(mode)
}
}
}
protected open fun processCalls(
callable: KtCallableDeclaration,
includeOverriders: Boolean,
sliceProducer: SliceProducer,
) {
if (callable is KtFunctionLiteral || callable is KtFunction && callable.name == null) {
callable.passToProcessorAsValue(mode.withBehaviour(LambdaCallsBehaviour(sliceProducer)))
return
}
val options = when (callable) {
is KtFunction -> {
KotlinFunctionFindUsagesOptions(project).apply {
isSearchForTextOccurrences = false
isSkipImportStatements = true
searchScope = analysisScope
}
}
is KtProperty -> {
KotlinPropertyFindUsagesOptions(project).apply {
isSearchForTextOccurrences = false
isSkipImportStatements = true
searchScope = analysisScope
}
}
else -> return
}
val descriptor = callable.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return
val superDescriptors = if (includeOverriders) {
descriptor.getDeepestSuperDeclarations()
} else {
mutableListOf<CallableMemberDescriptor>().apply {
add(descriptor)
addAll(DescriptorUtils.getAllOverriddenDeclarations(descriptor))
if (descriptor.isActual) {
addIfNotNull(descriptor.expectedDescriptor() as CallableMemberDescriptor?)
}
}
}
for (superDescriptor in superDescriptors) {
val declaration = superDescriptor.toPsi() ?: continue
when (declaration) {
is KtDeclaration -> {
val usageProcessor: (UsageInfo) -> Unit = processor@{ usageInfo ->
val element = usageInfo.element ?: return@processor
if (element.parentOfType<PsiComment>() != null) return@processor
val sliceUsage = KotlinSliceUsage(element, parentUsage, mode, false)
sliceProducer.produceAndProcess(sliceUsage, mode, parentUsage, processor)
}
if (includeOverriders) {
declaration.processAllUsages(options, usageProcessor)
} else {
declaration.processAllExactUsages(options, usageProcessor)
}
}
is PsiMethod -> {
val sliceUsage = JavaSliceUsage.createRootUsage(declaration, parentUsage.params)
sliceProducer.produceAndProcess(sliceUsage, mode, parentUsage, processor)
}
else -> {
val sliceUsage = KotlinSliceUsage(declaration, parentUsage, mode, false)
sliceProducer.produceAndProcess(sliceUsage, mode, parentUsage, processor)
}
}
}
}
protected enum class AccessKind {
READ_ONLY, WRITE_ONLY, WRITE_WITH_OPTIONAL_READ, READ_OR_WRITE
}
protected fun processVariableAccesses(
declaration: KtCallableDeclaration,
scope: SearchScope,
kind: AccessKind,
usageProcessor: (UsageInfo) -> Unit
) {
val options = KotlinPropertyFindUsagesOptions(project).apply {
isReadAccess = kind == AccessKind.READ_ONLY || kind == AccessKind.READ_OR_WRITE
isWriteAccess =
kind == AccessKind.WRITE_ONLY || kind == AccessKind.WRITE_WITH_OPTIONAL_READ || kind == AccessKind.READ_OR_WRITE
isReadWriteAccess = kind == AccessKind.WRITE_WITH_OPTIONAL_READ || kind == AccessKind.READ_OR_WRITE
isSearchForTextOccurrences = false
isSkipImportStatements = true
searchScope = scope
}
val allDeclarations = mutableListOf(declaration)
val descriptor = declaration.resolveToDescriptorIfAny()
if (descriptor is CallableMemberDescriptor) {
val additionalDescriptors = if (descriptor.isActual) {
listOfNotNull(descriptor.expectedDescriptor() as? CallableMemberDescriptor)
} else {
DescriptorUtils.getAllOverriddenDeclarations(descriptor)
}
additionalDescriptors.mapNotNullTo(allDeclarations) {
it.toPsi() as? KtCallableDeclaration
}
}
allDeclarations.forEach {
it.processAllExactUsages(options) { usageInfo ->
if (!shouldIgnoreVariableUsage(usageInfo)) {
usageProcessor.invoke(usageInfo)
}
}
}
}
// ignore parameter usages in function contract
private fun shouldIgnoreVariableUsage(usage: UsageInfo): Boolean {
val element = usage.element ?: return true
return element.parents.any {
it is KtCallExpression &&
(it.calleeExpression as? KtSimpleNameExpression)?.getReferencedName() == "contract" &&
it.resolveToCall()?.resultingDescriptor?.fqNameOrNull()?.asString() == "kotlin.contracts.contract"
}
}
protected fun canProcessParameter(parameter: KtParameter) = !parameter.isVarArg
protected fun processExtensionReceiverUsages(
declaration: KtCallableDeclaration,
body: KtExpression?,
mode: KotlinSliceAnalysisMode,
) {
if (body == null) return
//TODO: overriders
val resolutionFacade = declaration.getResolutionFacade()
val callableDescriptor = declaration.resolveToDescriptorIfAny(resolutionFacade) as? CallableDescriptor ?: return
val extensionReceiver = callableDescriptor.extensionReceiverParameter ?: return
body.forEachDescendantOfType<KtThisExpression> { thisExpression ->
val receiverDescriptor = thisExpression.resolveToCall(resolutionFacade)?.resultingDescriptor
if (receiverDescriptor == extensionReceiver) {
thisExpression.passToProcessor(mode)
}
}
// process implicit receiver usages
val pseudocode = pseudocodeCache[body]
if (pseudocode != null) {
for (instruction in pseudocode.instructions) {
if (instruction is MagicInstruction && instruction.kind == MagicKind.IMPLICIT_RECEIVER) {
val receiverPseudoValue = instruction.outputValue
pseudocode.getUsages(receiverPseudoValue).forEach { receiverUseInstruction ->
if (receiverUseInstruction is KtElementInstruction) {
receiverPseudoValue.processIfReceiverValue(
receiverUseInstruction,
mode,
filter = { receiverValue, resolvedCall ->
receiverValue == resolvedCall.extensionReceiver &&
(receiverValue as? ImplicitReceiver)?.declarationDescriptor == callableDescriptor
}
)
}
}
}
}
}
}
protected fun PseudoValue.processIfReceiverValue(
instruction: KtElementInstruction,
mode: KotlinSliceAnalysisMode,
filter: (ReceiverValue, ResolvedCall<out CallableDescriptor>) -> Boolean = { _, _ -> true }
): Boolean {
val receiverValue = (instruction as? InstructionWithReceivers)?.receiverValues?.get(this) ?: return false
val resolvedCall = instruction.element.resolveToCall() ?: return true
if (!filter(receiverValue, resolvedCall)) return true
val descriptor = resolvedCall.resultingDescriptor
if (descriptor.isImplicitInvokeFunction()) {
when (receiverValue) {
resolvedCall.dispatchReceiver -> {
if (mode.currentBehaviour is LambdaCallsBehaviour) {
instruction.element.passToProcessor(mode)
}
}
resolvedCall.extensionReceiver -> {
val dispatchReceiver = resolvedCall.dispatchReceiver ?: return true
val dispatchReceiverPseudoValue = instruction.receiverValues.entries
.singleOrNull { it.value == dispatchReceiver }?.key
?: return true
val createdAt = dispatchReceiverPseudoValue.createdAt
val accessedDescriptor = (createdAt as ReadValueInstruction?)?.target?.accessedDescriptor
if (accessedDescriptor is VariableDescriptor) {
accessedDescriptor.toPsi()?.passToProcessor(mode.withBehaviour(LambdaReceiverInflowBehaviour))
}
}
}
} else {
if (receiverValue == resolvedCall.extensionReceiver) {
(descriptor.toPsi() as? KtCallableDeclaration)?.receiverTypeReference
?.passToProcessorInCallMode(instruction.element, mode)
}
}
return true
}
protected fun DeclarationDescriptor.toPsi(): PsiElement? {
return descriptorToPsi(this, project, analysisScope)
}
companion object {
protected fun KtDeclaration?.callMode(callElement: KtElement, defaultMode: KotlinSliceAnalysisMode): KotlinSliceAnalysisMode {
return if (this is KtNamedFunction && hasInlineModifier())
defaultMode.withInlineFunctionCall(callElement, this)
else
defaultMode
}
fun descriptorToPsi(descriptor: DeclarationDescriptor, project: Project, analysisScope: SearchScope): PsiElement? {
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) ?: return null
if (analysisScope.contains(declaration)) return declaration.navigationElement
// we ignore access scope for inline declarations
val isInline = when (declaration) {
is KtNamedFunction -> declaration.hasInlineModifier()
is KtParameter -> declaration.ownerFunction?.hasInlineModifier() == true
else -> false
}
return if (isInline) declaration.navigationElement else null
}
}
}
fun CallableDescriptor.isImplicitInvokeFunction(): Boolean {
if (this !is FunctionDescriptor) return false
if (!isOperator) return false
if (name != OperatorNameConventions.INVOKE) return false
return source.getPsi() == null
}
|
apache-2.0
|
1a416b438f27ba449647cd2386de1cef
| 43.305405 | 158 | 0.655402 | 6.02241 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedUnaryOperatorInspection.kt
|
1
|
2779
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPrefixExpression
import org.jetbrains.kotlin.psi.prefixExpressionVisitor
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class UnusedUnaryOperatorInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = prefixExpressionVisitor(fun(prefix) {
if (prefix.baseExpression == null) return
val operationToken = prefix.operationToken
if (operationToken != KtTokens.PLUS && operationToken != KtTokens.MINUS) return
// hack to fix KTIJ-196 (unstable `USED_AS_EXPRESSION` marker for KtAnnotationEntry)
if (prefix.isInAnnotationEntry) return
val context = prefix.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
if (prefix.isUsedAsExpression(context)) return
val operatorDescriptor = prefix.operationReference.getResolvedCall(context)?.resultingDescriptor as? DeclarationDescriptor ?: return
if (!KotlinBuiltIns.isUnderKotlinPackage(operatorDescriptor)) return
holder.registerProblem(prefix, KotlinBundle.message("unused.unary.operator"), RemoveUnaryOperatorFix())
})
private class RemoveUnaryOperatorFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.unary.operator.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val prefixExpression = descriptor.psiElement as? KtPrefixExpression ?: return
val baseExpression = prefixExpression.baseExpression ?: return
prefixExpression.replace(baseExpression)
}
}
}
private val KtPrefixExpression.isInAnnotationEntry: Boolean
get() = parentsWithSelf.takeWhile { it is KtExpression }.last().parent?.parent?.parent is KtAnnotationEntry
|
apache-2.0
|
fa3288899dd9199c9b492fc9b6bab107
| 51.433962 | 158 | 0.788413 | 5.146296 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/frame/frameInlineFunCallInsideInlineFunKotlinVariables.kt
|
4
|
715
|
// SHOW_KOTLIN_VARIABLES
package frameInlineFunCallInsideInlineFunKotlinVariables
class A {
inline fun inlineFun(s: (Int) -> Unit) {
val element = 1.0
s(1)
}
val prop = 1
}
class B {
inline fun foo(s: (Int) -> Unit) {
val element = 2
val a = A()
// STEP_INTO: 1
// STEP_OVER: 1
//Breakpoint!
a.inlineFun {
val e = element
}
s(1)
}
}
class C {
fun bar() {
val element = 1f
B().foo {
val e = element
}
}
}
fun main(args: Array<String>) {
C().bar()
}
// PRINT_FRAME
// EXPRESSION: element
// RESULT: 1.0: D
// EXPRESSION: this.prop
// RESULT: 1: I
|
apache-2.0
|
a6aa116bea371c9f7fea83c7b5a116dc
| 13.895833 | 56 | 0.486713 | 3.356808 | false | false | false | false |
josecefe/Rueda
|
src/es/um/josecefe/rueda/modelo/Horario.kt
|
1
|
4627
|
/*
* Copyright (c) 2016-2017. Jose Ceferino Ortega Carretero
*
* 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 es.um.josecefe.rueda.modelo
import javafx.beans.property.*
/**
* SQL: CREATE TABLE "horario" ( "participante" INTEGER NOT NULL REFERENCES
* participante(id) ON DELETE CASCADE, "dia" INTEGER NOT NULL REFERENCES dia(id)
* ON DELETE CASCADE, "entrada" INTEGER NOT NULL, "salida" INTEGER NOT NULL,
* "coche" INTEGER NOT NULL DEFAULT (1), PRIMARY KEY (participante,dia) );
*
* @author josecefe
*/
class Horario
/**
* Crea una porción de horario que corresponde un participante y un día
* dados
*
* @param participante Participante al que pertenece esta parte del horario
* @param dia Día al que se refiere esta parte
* @param entrada Hora de entrada del participante ese dia
* @param salida Hora de salida del participante ese dia
* @param coche Indica si ese día podría compartir su coche
*/
(participante: Participante? = null, dia: Dia? = null, entrada: Int = 0, salida: Int = 0, coche: Boolean = false) : Comparable<Horario> {
private val participanteProperty: ObjectProperty<Participante>
private val diaProperty: ObjectProperty<Dia>
private val entradaProperty: IntegerProperty
private val salidaProperty: IntegerProperty
private val cocheProperty: BooleanProperty
init {
this.participanteProperty = SimpleObjectProperty(participante)
this.diaProperty = SimpleObjectProperty(dia)
this.entradaProperty = SimpleIntegerProperty(entrada)
this.salidaProperty = SimpleIntegerProperty(salida)
this.cocheProperty = SimpleBooleanProperty(coche)
}
/**
* Permite fijar el participante de esta entrada en el horario Nota: Este
* método se incluye para la persistencia
*/
var participante: Participante
get() = participanteProperty.get()
set(participante) = this.participanteProperty.set(participante)
fun participanteProperty() = participanteProperty
/**
* Permite fija el dia de esta entrada de horario. Perticipante + Dia no se
* pueden repetir Nota: Este método se incluye para la persistencia
*
*/
var dia: Dia
get() = diaProperty.get()
set(dia) = this.diaProperty.set(dia)
fun diaProperty() = diaProperty
/**
* Permite fijar la hora de entrada (entendida como un entero, usualmente
* empezando por 1 para primera hora, 2 para la segunda, etc.) Nota: Este
* método se incluye para la persistencia
*/
var entrada: Int
get() = entradaProperty.get()
set(entrada) = this.entradaProperty.set(entrada)
fun entradaProperty() = entradaProperty
/**
* Permite fijar la hora de salida (entendida como un entero, usualmente
* empezando por 1 para primera hora, 2 para la segunda, etc.) Nota: Este
* método se incluye para la persistencia
*/
var salida: Int
get() = salidaProperty.get()
set(salida) = this.salidaProperty.set(salida)
fun salidaProperty() = salidaProperty
var coche: Boolean
get() = cocheProperty.get()
set(coche) = this.cocheProperty.set(coche)
fun cocheProperty() = cocheProperty
override fun toString(): String = "Horario [participante=$participante, dia=$dia, entrada=$entrada, salida=$salida, coche=$coche]"
override fun hashCode(): Int {
val prime = 31
var result = 100
result = prime * result + dia.hashCode()
result = prime * result + participante.hashCode()
return result
}
override fun equals(other: Any?): Boolean =
(this === other) || (other != null && other is Horario && dia == other.dia && participante == other.participante)
/* (non-Javadoc)
* @see java.lang.comparable#compareTo(java.lang.Object)
*/
override fun compareTo(other: Horario): Int {
var res = dia.compareTo(other.dia)
if (res == 0) res = participante.compareTo(other.participante)
return res
}
}
|
gpl-3.0
|
8894006cdae3165834c580e4282fefbd
| 38.470085 | 242 | 0.688826 | 3.676752 | false | false | false | false |
ninjahoahong/unstoppable
|
app/src/main/java/com/ninjahoahong/unstoppable/home/HomeFragment.kt
|
1
|
2750
|
package com.ninjahoahong.unstoppable.home
import android.os.Bundle
import android.text.Html
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.ninjahoahong.unstoppable.BaseFragment
import com.ninjahoahong.unstoppable.MainActivity
import com.ninjahoahong.unstoppable.R
import com.ninjahoahong.unstoppable.home.onboarding.OnBoardingPagerAdapter
import com.ninjahoahong.unstoppable.question.QuestionViewKey
import com.ninjahoahong.unstoppable.utils.Settings
import kotlinx.android.synthetic.main.fragment_home.continueButton
import kotlinx.android.synthetic.main.fragment_home.introText
import kotlinx.android.synthetic.main.fragment_home.loadGameButton
import kotlinx.android.synthetic.main.fragment_home.onBoardingView
import kotlinx.android.synthetic.main.fragment_home.onBoardingViewsContainer
import kotlinx.android.synthetic.main.fragment_home.viewPagerIndicator
import org.jetbrains.anko.sdk15.listeners.onClick
class HomeFragment : BaseFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_home, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
showOnboardingView(Settings.isNot(view.context, Settings.FIRST_TIME_PLAY))
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
introText.text = Html.fromHtml(
getString(R.string.intro_text), Html.FROM_HTML_MODE_LEGACY)
} else {
@Suppress("DEPRECATION")
introText.text = Html.fromHtml(getString(R.string.intro_text))
}
introText.movementMethod = LinkMovementMethod.getInstance()
loadGameButton.onClick { MainActivity[view.context].navigateTo(QuestionViewKey()); }
}
private fun showOnboardingView(shouldShowed: Boolean) {
onBoardingView.adapter = OnBoardingPagerAdapter(activity as MainActivity)
viewPagerIndicator.setupWithViewPager(onBoardingView)
continueButton.setOnClickListener { inactivateOnboarding() }
return if (shouldShowed) {
(activity as MainActivity).supportActionBar!!.hide()
onBoardingViewsContainer.visibility = View.VISIBLE
} else {
inactivateOnboarding()
}
}
private fun inactivateOnboarding() {
(activity as MainActivity).supportActionBar!!.show()
onBoardingViewsContainer.visibility = View.GONE
Settings[activity as MainActivity, Settings.FIRST_TIME_PLAY] = true
}
}
|
mit
|
34aee25cec624a006aa843d1da35f260
| 43.370968 | 92 | 0.749818 | 4.464286 | false | false | false | false |
paul58914080/ff4j-spring-boot-starter-parent
|
ff4j-spring-services/src/main/kotlin/org/ff4j/services/domain/PieChartApiBean.kt
|
1
|
1365
|
/*-
* #%L
* ff4j-spring-services
* %%
* Copyright (C) 2013 - 2019 FF4J
* %%
* 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.
* #L%
*/
package org.ff4j.services.domain
import org.ff4j.audit.chart.PieChart
import org.ff4j.audit.chart.Serie
import java.io.Serializable
import java.util.*
/**
* Created by Paul
*
* @author <a href="mailto:[email protected]">Paul Williams</a>
*/
class PieChartApiBean : Serializable {
companion object {
private const val serialVersionUID = 3177966921214178831L
}
var title: String? = null
val sectors: MutableList<PieSectorApiBean> = mutableListOf()
constructor() : super()
constructor(pieChart: PieChart) {
this.title = pieChart.title
for (sector: Serie<Int> in pieChart.sectors) {
this.sectors.add(PieSectorApiBean(sector))
}
}
}
|
apache-2.0
|
7146005c0311e26c8370391f5058c772
| 26.857143 | 75 | 0.693773 | 3.709239 | false | false | false | false |
80998062/Fank
|
presentation/src/main/java/com/sinyuk/fanfou/ui/home/IndexView.kt
|
1
|
5682
|
/*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.ui.home
import android.arch.lifecycle.Observer
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.bumptech.glide.request.target.ViewTarget
import com.sinyuk.fanfou.R
import com.sinyuk.fanfou.base.AbstractFragment
import com.sinyuk.fanfou.di.Injectable
import com.sinyuk.fanfou.domain.DO.Player
import com.sinyuk.fanfou.domain.TIMELINE_HOME
import com.sinyuk.fanfou.glide.GlideApp
import com.sinyuk.fanfou.ui.timeline.TimelineView
import com.sinyuk.fanfou.util.obtainViewModelFromActivity
import com.sinyuk.fanfou.util.span.AndroidSpan
import com.sinyuk.fanfou.util.span.SpanOptions
import com.sinyuk.fanfou.viewmodel.AccountViewModel
import com.sinyuk.fanfou.viewmodel.FanfouViewModelFactory
import com.sinyuk.myutils.system.ToastUtils
import kotlinx.android.synthetic.main.index_view.*
import kotlinx.android.synthetic.main.state_layout_forbidden.view.*
import javax.inject.Inject
/**
* Created by sinyuk on 2018/1/30.
*
*/
@Deprecated("废物")
class IndexView : AbstractFragment(), Injectable {
override fun layoutId() = R.layout.index_view
@Inject
lateinit var factory: FanfouViewModelFactory
@Inject
lateinit var toastUtils: ToastUtils
private val accountViewModel by lazy { obtainViewModelFromActivity(factory, AccountViewModel::class.java) }
override fun onLazyInitView(savedInstanceState: Bundle?) {
super.onLazyInitView(savedInstanceState)
accountViewModel.profile.observe(this@IndexView, Observer { render(it) })
}
private fun render(data: Player?) {
viewAnimator.displayedChildId = when {
data == null -> {
setup401View()
R.id.layout401
}
data.friendsCount == 0 -> {
setupNoFriendsView(data)
R.id.layoutEmpty
}
else -> {
setupTimelineView(data)
R.id.pullRefreshLayout
}
}
}
private fun setup401View() {
if (layout401.title.text.isNullOrEmpty()) {
layout401.title.text = getString(R.string.state_title_401)
val span = AndroidSpan().drawRelativeSizeSpan(getString(R.string.state_description_401), 1f)
.drawWithOptions("Sign in", SpanOptions().addTextAppearanceSpan(context!!, R.style.text_bold_primary).addSpan(object : ClickableSpan() {
override fun onClick(v: View?) {
toastUtils.toastLong("haha")
}
})).spanText
layout401.description.movementMethod = LinkMovementMethod.getInstance()
layout401.description.text = span
val target = GlideApp.with(this).load(R.drawable.state_layout_forbidden).transition(withCrossFade()).into(layout401.image)
setStateDrawableTarget(target)
}
}
private var stateDrawableTarget: ViewTarget<ImageView, Drawable>? = null
private fun setupNoFriendsView(data: Player) {
if (layoutEmpty.title.text.isNullOrEmpty()) {
layoutEmpty.title.text = getString(R.string.state_title_nofriends)
val span = AndroidSpan().drawRelativeSizeSpan(getString(R.string.state_description_nofriends), 1f)
.drawWithOptions("Look around", SpanOptions().addTextAppearanceSpan(context!!, R.style.text_bold_primary).addSpan(object : ClickableSpan() {
override fun onClick(v: View?) {
toastUtils.toastLong("haha")
}
})).spanText
layoutEmpty.description.movementMethod = LinkMovementMethod.getInstance()
layoutEmpty.description.text = span
val target = GlideApp.with(this).load(R.drawable.state_layout_empty).transition(withCrossFade()).into(layoutEmpty.image)
setStateDrawableTarget(target)
}
}
private fun setupTimelineView(data: Player) {
setStateDrawableTarget(null)
if (findChildFragment(TimelineView::class.java) == null) {
val fragment = TimelineView.playerTimeline(TIMELINE_HOME, data)
loadRootFragment(R.id.homeTimelineViewContainer, fragment)
} else {
showHideFragment(findChildFragment(TimelineView::class.java))
}
pullRefreshLayout.setOnRefreshListener { (findChildFragment(TimelineView::class.java) as TimelineView).refresh() }
}
/**
* 清除正在加载的图片目标
*
* @param target 加载图片目标
*/
private fun setStateDrawableTarget(target: ViewTarget<ImageView, Drawable>?) {
if (stateDrawableTarget != null) stateDrawableTarget!!.request?.clear()
stateDrawableTarget = target
}
}
|
mit
|
892a0de2243a8305d1b63dca9943b175
| 38.201389 | 160 | 0.677356 | 4.426667 | false | false | false | false |
Waboodoo/HTTP-Shortcuts
|
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/main/MainViewState.kt
|
1
|
1639
|
package ch.rmy.android.http_shortcuts.activities.main
import ch.rmy.android.framework.extensions.indexOfFirstOrNull
import ch.rmy.android.framework.extensions.takeUnlessEmpty
import ch.rmy.android.framework.extensions.toLocalizable
import ch.rmy.android.framework.utils.localization.Localizable
import ch.rmy.android.framework.utils.localization.StringResLocalizable
import ch.rmy.android.framework.viewmodel.viewstate.DialogState
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.activities.main.models.CategoryTabItem
import ch.rmy.android.http_shortcuts.data.domains.categories.CategoryId
import ch.rmy.android.http_shortcuts.data.enums.SelectionMode
data class MainViewState(
val toolbarTitle: String = "",
val isLocked: Boolean,
val categoryTabItems: List<CategoryTabItem>,
val selectionMode: SelectionMode,
val isInMovingMode: Boolean,
val activeCategoryId: CategoryId,
val dialogState: DialogState? = null,
) {
val isRegularMenuButtonVisible
get() = !isLocked
val isUnlockButtonVisible
get() = isLocked
val isCreateButtonVisible
get() = !isLocked && !isInMovingMode
val isTabBarVisible
get() = categoryTabItems.size > 1
val isToolbarScrollable
get() = categoryTabItems.size > 1
val toolbarTitleLocalizable: Localizable
get() = toolbarTitle.takeUnlessEmpty()?.toLocalizable() ?: StringResLocalizable(R.string.app_name)
val activeCategoryIndex: Int
get() = categoryTabItems.indexOfFirstOrNull { category ->
category.categoryId == activeCategoryId
}
?: 0
}
|
mit
|
e069f4948822a93ece6e95ceb051f9a4
| 34.630435 | 106 | 0.751678 | 4.41779 | false | false | false | false |
ThiagoGarciaAlves/intellij-community
|
python/openapi/src/com/jetbrains/python/packaging/requirement/PyRequirementVersion.kt
|
3
|
1754
|
// Copyright 2000-2017 JetBrains s.r.o.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.jetbrains.python.packaging.requirement
@Deprecated(message = "Use com.jetbrains.python.packaging.PyRequirement instead. This class will be removed in 2018.2.")
data class PyRequirementVersion(val epoch: String? = null,
val release: String,
val pre: String? = null,
val post: String? = null,
val dev: String? = null,
val local: String? = null) {
companion object {
@JvmStatic
fun release(release: String): PyRequirementVersion = PyRequirementVersion(release = release)
}
val presentableText: String
get() =
sequenceOf(epochPresentable(), release, pre, postPresentable(), devPresentable(), localPresentable())
.filterNotNull()
.joinToString(separator = "") { it }
private fun epochPresentable() = if (epoch == null) null else "$epoch!"
private fun postPresentable() = if (post == null) null else ".$post"
private fun devPresentable() = if (dev == null) null else ".$dev"
private fun localPresentable() = if (local == null) null else "+$local"
}
|
apache-2.0
|
cc8244307a4f7e7b58039a97fba0d559
| 44 | 120 | 0.656784 | 4.567708 | false | false | false | false |
sky-map-team/stardroid
|
app/src/main/java/com/google/android/stardroid/math/MathUtils.kt
|
1
|
2360
|
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.stardroid.math
/**
* Basic methods for doing mathematical operations with floats.
*
* @author Brent Bryan
*/
const val PI = Math.PI.toFloat()
const val TWO_PI = 2f * PI
const val DEGREES_TO_RADIANS = PI / 180.0f
const val RADIANS_TO_DEGREES = 180.0f / PI
fun flooredMod(a: Float, n: Float) = (if (a < 0) a % n + n else a) % n
/**
* Returns the modulo the given value by 2\pi. Returns an angle in the range 0
* to 2\pi radians.
*/
fun mod2pi(x: Float) = positiveMod(x, TWO_PI)
/**
* Calculates x modulus y, but ensures that the result lies in [0, y)
*/
fun positiveMod(x: Double, y: Double): Double {
var remainder = x % y
if (remainder < 0) remainder += y
return remainder
}
/**
* Calculates x modulus y, but ensures that the result lies in [0, y)
*/
// Sadly we can't use generics for this.
private fun positiveMod(x: Float, y: Float): Float {
var remainder = x % y
if (remainder < 0) remainder += y
return remainder
}
/** Calculates the length of the vector [x, y, z] */
fun norm(x: Float, y: Float, z: Float) = kotlin.math.sqrt(x * x + y * y + z * z)
// TODO(jontayler): eliminate this class if we can eliminate floats.
object MathUtils {
// TODO(jontayler): just inline these when everything is Kotlin
@JvmStatic
fun abs(x: Float) = kotlin.math.abs(x)
@JvmStatic
fun sqrt(x: Float) = kotlin.math.sqrt(x)
@JvmStatic
fun sin(x: Float) = kotlin.math.sin(x)
@JvmStatic
fun cos(x: Float) = kotlin.math.cos(x)
@JvmStatic
fun tan(x: Float) = kotlin.math.tan(x)
@JvmStatic
fun asin(x: Float) = kotlin.math.asin(x)
@JvmStatic
fun acos(x: Float) = kotlin.math.acos(x)
@JvmStatic
fun atan2(y: Float, x: Float) = kotlin.math.atan2(y, x)
}
|
apache-2.0
|
ac1288f7628bfbea1100ef09c5a76278
| 27.107143 | 80 | 0.669915 | 3.296089 | false | false | false | false |
cmcpasserby/MayaCharm
|
src/main/kotlin/actions/SendSelectionAction.kt
|
1
|
1284
|
package actions
import MayaBundle as Loc
import mayacomms.MayaCommandInterface
import resources.MayaNotifications
import settings.ProjectSettings
import com.intellij.notification.Notifications
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.LangDataKeys
class SendSelectionAction : BaseSendAction(
Loc.message("mayacharm.action.SendSelectionText"),
Loc.message("mayacharm.action.SendSelectionDescription"), null
) {
override fun actionPerformed(e: AnActionEvent) {
val sdk = ProjectSettings.getInstance(e.project!!).selectedSdk
if (sdk == null) {
Notifications.Bus.notify(MayaNotifications.NO_SDK_SELECTED)
return
}
val selectionModel = e.getData(LangDataKeys.EDITOR)?.selectionModel ?: return
val selectedText: String?
if (selectionModel.hasSelection()) {
selectedText = selectionModel.selectedText
} else {
selectionModel.selectLineAtCaret()
if (selectionModel.hasSelection()) {
selectedText = selectionModel.selectedText
selectionModel.removeSelection()
} else return
}
MayaCommandInterface(sdk.port).sendCodeToMaya(selectedText!!)
}
}
|
mit
|
5d1cb4f85bfe9bd947f306403a4d361f
| 33.702703 | 85 | 0.70405 | 5.240816 | false | false | false | false |
InflationX/ViewPump
|
viewpump/src/main/java/io/github/inflationx/viewpump/internal/-ViewPumpLayoutInflater.kt
|
1
|
13975
|
@file:JvmName("-ViewPumpLayoutInflater")
package io.github.inflationx.viewpump.internal
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.BuildCompat
import io.github.inflationx.viewpump.FallbackViewCreator
import io.github.inflationx.viewpump.InflateRequest
import io.github.inflationx.viewpump.R.id
import io.github.inflationx.viewpump.ViewPump
import org.xmlpull.v1.XmlPullParser
import java.lang.reflect.Field
@Suppress("ClassName")
internal class `-ViewPumpLayoutInflater`(
original: LayoutInflater,
newContext: Context,
cloned: Boolean
) : LayoutInflater(original, newContext), `-ViewPumpActivityFactory` {
private val IS_AT_LEAST_Q = Build.VERSION.SDK_INT > Build.VERSION_CODES.P || BuildCompat.isAtLeastQ()
private val nameAndAttrsViewCreator: FallbackViewCreator = NameAndAttrsViewCreator(this)
private val parentAndNameAndAttrsViewCreator: FallbackViewCreator = ParentAndNameAndAttrsViewCreator(this)
// Reflection Hax
private var setPrivateFactory = false
private var storeLayoutResId = ViewPump.get().isStoreLayoutResId
init {
setUpLayoutFactories(cloned)
}
override fun cloneInContext(newContext: Context): LayoutInflater {
return `-ViewPumpLayoutInflater`(this, newContext, true)
}
// ===
// Wrapping goodies
// ===
override fun inflate(resource: Int, root: ViewGroup?, attachToRoot: Boolean): View? {
val view = super.inflate(resource, root, attachToRoot)
if (view != null && storeLayoutResId) {
view.setTag(id.viewpump_layout_res, resource)
}
return view
}
override fun inflate(parser: XmlPullParser, root: ViewGroup?, attachToRoot: Boolean): View {
setPrivateFactoryInternal()
return super.inflate(parser, root, attachToRoot)
}
/**
* We don't want to unnecessary create/set our factories if there are none there. We try to be
* as lazy as possible.
*/
private fun setUpLayoutFactories(cloned: Boolean) {
if (cloned) return
// If we are HC+ we get and set Factory2 otherwise we just wrap Factory1
if (factory2 != null && factory2 !is WrapperFactory2) {
// Sets both Factory/Factory2
factory2 = factory2
}
// We can do this as setFactory2 is used for both methods.
if (factory != null && factory !is WrapperFactory) {
factory = factory
}
}
override fun setFactory(factory: LayoutInflater.Factory) {
// Only set our factory and wrap calls to the Factory trying to be set!
if (factory !is WrapperFactory) {
super.setFactory(
WrapperFactory(factory))
} else {
super.setFactory(factory)
}
}
override fun setFactory2(factory2: LayoutInflater.Factory2) {
// Only set our factory and wrap calls to the Factory2 trying to be set!
if (factory2 !is WrapperFactory2) {
// LayoutInflaterCompat.setFactory(this, new WrapperFactory2(factory2, mViewPumpFactory));
super.setFactory2(
WrapperFactory2(factory2))
} else {
super.setFactory2(factory2)
}
}
private fun setPrivateFactoryInternal() {
// Already tried to set the factory.
if (setPrivateFactory) return
// Reflection (Or Old Device) skip.
if (!ViewPump.get().isReflection) return
// Skip if not attached to an activity.
if (context !is LayoutInflater.Factory2) {
setPrivateFactory = true
return
}
// TODO: we need to get this and wrap it if something has already set this
val setPrivateFactoryMethod = LayoutInflater::class.java.getAccessibleMethod("setPrivateFactory")
setPrivateFactoryMethod.invokeMethod(this, PrivateWrapperFactory2(context as Factory2, this))
setPrivateFactory = true
}
// ===
// LayoutInflater ViewCreators
// Works in order of inflation
// ===
/**
* The Activity onCreateView (PrivateFactory) is the third port of call for LayoutInflation.
* We opted to manual injection over aggressive reflection, this should be less fragile.
*/
override fun onActivityCreateView(
parent: View?,
view: View,
name: String,
context: Context,
attrs: AttributeSet?
): View? {
return ViewPump.get()
.inflate(InflateRequest(
name = name,
context = context,
attrs = attrs,
parent = parent,
fallbackViewCreator = ActivityViewCreator(
this, view)
))
.view
}
/**
* The LayoutInflater onCreateView is the fourth port of call for LayoutInflation.
* BUT only for none CustomViews.
*/
@Throws(ClassNotFoundException::class)
override fun onCreateView(parent: View?, name: String, attrs: AttributeSet?): View? {
return ViewPump.get()
.inflate(InflateRequest(
name = name,
context = context,
attrs = attrs,
parent = parent,
fallbackViewCreator = parentAndNameAndAttrsViewCreator
))
.view
}
/**
* The LayoutInflater onCreateView is the fourth port of call for LayoutInflation.
* BUT only for none CustomViews.
* Basically if this method doesn't inflate the View nothing probably will.
*/
@Throws(ClassNotFoundException::class)
override fun onCreateView(name: String, attrs: AttributeSet?): View? {
return ViewPump.get()
.inflate(InflateRequest(
name = name,
context = context,
attrs = attrs,
fallbackViewCreator = nameAndAttrsViewCreator
))
.view
}
/**
* Nasty method to inflate custom layouts that haven't been handled else where. If this fails it
* will fall back through to the PhoneLayoutInflater method of inflating custom views where
* ViewPump will NOT have a hook into.
*
* @param view view if it has been inflated by this point, if this is not null this method
* just returns this value.
* @param name name of the thing to inflate.
* @param viewContext Context to inflate by if parent is null
* @param attrs Attr for this view which we can steal fontPath from too.
* @return view or the View we inflate in here.
*/
private fun createCustomViewInternal(
view: View?,
name: String,
viewContext: Context,
attrs: AttributeSet?
): View? {
var mutableView = view
// I by no means advise anyone to do this normally, but Google have locked down access to
// the createView() method, so we never get a callback with attributes at the end of the
// createViewFromTag chain (which would solve all this unnecessary rubbish).
// We at the very least try to optimise this as much as possible.
// We only call for customViews (As they are the ones that never go through onCreateView(...)).
// We also maintain the Field reference and make it accessible which will make a pretty
// significant difference to performance on Android 4.0+.
// If CustomViewCreation is off skip this.
if (!ViewPump.get().isCustomViewCreation) return mutableView
if (mutableView == null && name.indexOf('.') > -1) {
if (IS_AT_LEAST_Q) {
mutableView = cloneInContext(viewContext).createView(name, null, attrs)
} else {
@Suppress("UNCHECKED_CAST")
val constructorArgsArr = CONSTRUCTOR_ARGS_FIELD.get(this) as Array<Any>
val lastContext = constructorArgsArr[0]
// The LayoutInflater actually finds out the correct context to use. We just need to set
// it on the mConstructor for the internal method.
// Set the constructor ars up for the createView, not sure why we can't pass these in.
constructorArgsArr[0] = viewContext
CONSTRUCTOR_ARGS_FIELD.setValueQuietly(this, constructorArgsArr)
try {
mutableView = createView(name, null, attrs)
} catch (ignored: ClassNotFoundException) {
} finally {
constructorArgsArr[0] = lastContext
CONSTRUCTOR_ARGS_FIELD.setValueQuietly(this, constructorArgsArr)
}
}
}
return mutableView
}
private fun superOnCreateView(parent: View?, name: String, attrs: AttributeSet?): View? {
return try {
super.onCreateView(parent, name, attrs)
} catch (e: ClassNotFoundException) {
null
}
}
private fun superOnCreateView(name: String, attrs: AttributeSet?): View? {
return try {
super.onCreateView(name, attrs)
} catch (e: ClassNotFoundException) {
null
}
}
// ===
// View creators
// ===
private class ActivityViewCreator(
private val inflater: `-ViewPumpLayoutInflater`,
private val view: View
) : FallbackViewCreator {
override fun onCreateView(
parent: View?,
name: String,
context: Context,
attrs: AttributeSet?
): View? {
return inflater.createCustomViewInternal(view, name, context, attrs)
}
}
private class ParentAndNameAndAttrsViewCreator(
private val inflater: `-ViewPumpLayoutInflater`) : FallbackViewCreator {
override fun onCreateView(parent: View?, name: String, context: Context,
attrs: AttributeSet?): View? {
return inflater.superOnCreateView(parent, name, attrs)
}
}
private class NameAndAttrsViewCreator(
private val inflater: `-ViewPumpLayoutInflater`
) : FallbackViewCreator {
override fun onCreateView(
parent: View?,
name: String,
context: Context,
attrs: AttributeSet?
): View? {
// This mimics the {@code PhoneLayoutInflater} in the way it tries to inflate the base
// classes, if this fails its pretty certain the app will fail at this point.
var view: View? = null
for (prefix in CLASS_PREFIX_LIST) {
try {
view = inflater.createView(name, prefix, attrs)
if (view != null) {
break
}
} catch (ignored: ClassNotFoundException) {
}
}
// In this case we want to let the base class take a crack
// at it.
if (view == null) view = inflater.superOnCreateView(name, attrs)
return view
}
}
// ===
// Wrapper Factories
// ===
/**
* Factory 1 is the first port of call for LayoutInflation
*/
private class WrapperFactory(factory: LayoutInflater.Factory) : LayoutInflater.Factory {
private val viewCreator: FallbackViewCreator = WrapperFactoryViewCreator(factory)
override fun onCreateView(name: String, context: Context, attrs: AttributeSet?): View? {
return ViewPump.get()
.inflate(InflateRequest(
name = name,
context = context,
attrs = attrs,
fallbackViewCreator = viewCreator
))
.view
}
}
private class WrapperFactoryViewCreator(
private val factory: LayoutInflater.Factory
) : FallbackViewCreator {
override fun onCreateView(
parent: View?,
name: String,
context: Context,
attrs: AttributeSet?
): View? {
return factory.onCreateView(name, context, attrs)
}
}
/**
* Factory 2 is the second port of call for LayoutInflation
*/
private open class WrapperFactory2(factory2: LayoutInflater.Factory2) : LayoutInflater.Factory2 {
private val viewCreator = WrapperFactory2ViewCreator(factory2)
override fun onCreateView(name: String, context: Context, attrs: AttributeSet?): View? {
return onCreateView(null, name, context, attrs)
}
override fun onCreateView(
parent: View?,
name: String,
context: Context,
attrs: AttributeSet?
): View? {
return ViewPump.get()
.inflate(InflateRequest(
name = name,
context = context,
attrs = attrs,
parent = parent,
fallbackViewCreator = viewCreator
))
.view
}
}
private open class WrapperFactory2ViewCreator(
protected val factory2: LayoutInflater.Factory2) : FallbackViewCreator {
override fun onCreateView(
parent: View?,
name: String,
context: Context,
attrs: AttributeSet?
): View? {
return factory2.onCreateView(parent, name, context, attrs)
}
}
/**
* Private factory is step three for Activity Inflation, this is what is attached to the Activity
*/
private class PrivateWrapperFactory2(
factory2: LayoutInflater.Factory2,
inflater: `-ViewPumpLayoutInflater`
) : WrapperFactory2(factory2) {
private val viewCreator = PrivateWrapperFactory2ViewCreator(factory2, inflater)
override fun onCreateView(
parent: View?,
name: String,
context: Context,
attrs: AttributeSet?
): View? {
return ViewPump.get()
.inflate(InflateRequest(
name = name,
context = context,
attrs = attrs,
parent = parent,
fallbackViewCreator = viewCreator
))
.view
}
}
private class PrivateWrapperFactory2ViewCreator(
factory2: LayoutInflater.Factory2,
private val inflater: `-ViewPumpLayoutInflater`
) : WrapperFactory2ViewCreator(factory2), FallbackViewCreator {
override fun onCreateView(
parent: View?,
name: String,
context: Context,
attrs: AttributeSet?
): View? {
return inflater.createCustomViewInternal(
factory2.onCreateView(parent, name, context, attrs), name, context, attrs)
}
}
companion object {
private val CLASS_PREFIX_LIST = setOf("android.widget.", "android.webkit.")
private val CONSTRUCTOR_ARGS_FIELD: Field by lazy {
requireNotNull(LayoutInflater::class.java.getDeclaredField("mConstructorArgs")) {
"No constructor arguments field found in LayoutInflater!"
}.apply { isAccessible = true }
}
}
}
|
apache-2.0
|
fab6c5e0085e4cd991e8d3a95b129abf
| 31.126437 | 108 | 0.66161 | 4.529984 | false | false | false | false |
savoirfairelinux/ring-client-android
|
ring-android/app/src/main/java/cx/ring/service/DRingService.kt
|
1
|
15835
|
/*
* Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Regis Montoya <[email protected]>
* Author: Emeric Vigier <[email protected]>
* Author: Alexandre Lision <[email protected]>
* Author: Adrien Béraud <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package cx.ring.service
import android.app.Notification
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.database.ContentObserver
import android.net.ConnectivityManager
import android.net.Uri
import android.os.*
import android.provider.ContactsContract
import android.text.TextUtils
import android.util.Log
import androidx.core.app.RemoteInput
import androidx.legacy.content.WakefulBroadcastReceiver
import cx.ring.BuildConfig
import cx.ring.application.JamiApplication
import cx.ring.client.CallActivity
import cx.ring.client.ConversationActivity
import cx.ring.tv.call.TVCallActivity
import cx.ring.utils.ConversationPath
import cx.ring.utils.DeviceUtils
import dagger.hilt.android.AndroidEntryPoint
import io.reactivex.rxjava3.disposables.CompositeDisposable
import net.jami.services.ConversationFacade
import net.jami.model.Conversation
import net.jami.model.Settings
import net.jami.services.*
import javax.inject.Inject
import javax.inject.Singleton
@AndroidEntryPoint
class DRingService : Service() {
private val contactContentObserver = ContactsContentObserver()
@Inject
@Singleton
lateinit var mDaemonService: DaemonService
@Inject
@Singleton
lateinit var mCallService: CallService
@Inject
@Singleton
lateinit var mAccountService: AccountService
@Inject
@Singleton
lateinit var mHardwareService: HardwareService
@Inject
@Singleton
lateinit var mHistoryService: HistoryService
@Inject
@Singleton
lateinit var mDeviceRuntimeService: DeviceRuntimeService
@Inject
@Singleton
lateinit var mNotificationService: NotificationService
@Inject
@Singleton
lateinit var mContactService: ContactService
@Inject
@Singleton
lateinit var mPreferencesService: PreferencesService
@Inject
@Singleton
lateinit var mConversationFacade: ConversationFacade
private val mHandler = Handler(Looper.myLooper()!!)
private val mDisposableBag = CompositeDisposable()
private val mConnectivityChecker = Runnable { updateConnectivityState() }
private val receiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (action == null) {
Log.w(TAG, "onReceive: received a null action on broadcast receiver")
return
}
Log.d(TAG, "receiver.onReceive: $action")
when (action) {
ConnectivityManager.CONNECTIVITY_ACTION -> {
updateConnectivityState()
}
PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED -> {
mConnectivityChecker.run()
mHandler.postDelayed(mConnectivityChecker, 100)
}
}
}
}
override fun onCreate() {
super.onCreate()
Log.i(TAG, "onCreate")
isRunning = true
if (mDeviceRuntimeService.hasContactPermission()) {
contentResolver.registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactContentObserver)
}
val intentFilter = IntentFilter()
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
intentFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED)
}
registerReceiver(receiver, intentFilter)
updateConnectivityState()
mDisposableBag.add(mPreferencesService.settingsSubject.subscribe { settings: Settings ->
showSystemNotification(settings)
})
JamiApplication.instance!!.apply {
bindDaemon()
bootstrapDaemon()
}
}
override fun onDestroy() {
super.onDestroy()
Log.i(TAG, "onDestroy()")
unregisterReceiver(receiver)
contentResolver.unregisterContentObserver(contactContentObserver)
mHardwareService.unregisterCameraDetectionCallback()
mDisposableBag.clear()
isRunning = false
}
private fun showSystemNotification(settings: Settings) {
if (settings.enablePermanentService) {
startForeground(NOTIFICATION_ID, mNotificationService.serviceNotification as Notification)
} else {
stopForeground(true)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
// Log.i(TAG, "onStartCommand " + (intent == null ? "null" : intent.getAction()) + " " + flags + " " + startId);
if (intent != null) {
parseIntent(intent)
WakefulBroadcastReceiver.completeWakefulIntent(intent)
}
return START_STICKY /* started and stopped explicitly */
}
private val binder: IBinder = Binder()
override fun onBind(intent: Intent): IBinder? {
return binder
}
/* ************************************
*
* Implement public interface for the service
*
* *********************************
*/
private fun updateConnectivityState() {
if (mDaemonService.isStarted) {
val isConnected = mPreferencesService.hasNetworkConnected()
mAccountService.setAccountsActive(isConnected)
// Execute connectivityChanged to reload UPnP
// and reconnect active accounts if necessary.
mHardwareService.connectivityChanged(isConnected)
}
}
private fun parseIntent(intent: Intent) {
val action = intent.action ?: return
val extras = intent.extras
when (action) {
ACTION_TRUST_REQUEST_ACCEPT, ACTION_TRUST_REQUEST_REFUSE, ACTION_TRUST_REQUEST_BLOCK ->
handleTrustRequestAction(intent.data, action)
ACTION_CALL_ACCEPT, ACTION_CALL_HOLD_ACCEPT, ACTION_CALL_END_ACCEPT, ACTION_CALL_REFUSE, ACTION_CALL_END, ACTION_CALL_VIEW -> extras?.let {
handleCallAction(action, it)
}
ACTION_CONV_READ, ACTION_CONV_ACCEPT, ACTION_CONV_DISMISS, ACTION_CONV_REPLY_INLINE ->
handleConvAction(intent, action, extras)
ACTION_FILE_ACCEPT, ACTION_FILE_CANCEL -> extras?.let {
handleFileAction(intent.data, action, it)
}
}
}
private fun handleFileAction(uri: Uri?, action: String, extras: Bundle) {
Log.w(TAG, "handleFileAction $extras")
val messageId = extras.getString(KEY_MESSAGE_ID)
val id = extras.getString(KEY_TRANSFER_ID)!!
val path = ConversationPath.fromUri(uri)!!
if (action == ACTION_FILE_ACCEPT) {
mNotificationService.removeTransferNotification(path.accountId, path.conversationUri, id)
mAccountService.acceptFileTransfer(path.accountId, path.conversationUri, messageId, id)
} else if (action == ACTION_FILE_CANCEL) {
mConversationFacade.cancelFileTransfer(path.accountId, path.conversationUri, messageId, id)
}
}
private fun handleTrustRequestAction(uri: Uri?, action: String) {
ConversationPath.fromUri(uri)?.let { path ->
mNotificationService.cancelTrustRequestNotification(path.accountId)
when (action) {
ACTION_TRUST_REQUEST_ACCEPT -> mConversationFacade.acceptRequest(path.accountId, path.conversationUri)
ACTION_TRUST_REQUEST_REFUSE -> mConversationFacade.discardRequest(path.accountId, path.conversationUri)
ACTION_TRUST_REQUEST_BLOCK -> {
mConversationFacade.discardRequest(path.accountId, path.conversationUri)
mAccountService.removeContact(path.accountId, path.conversationUri.rawRingId, true)
}
}
}
}
private fun handleCallAction(action: String, extras: Bundle) {
val callId = extras.getString(NotificationService.KEY_CALL_ID) ?: return
val accountId = extras.getString(ConversationPath.KEY_ACCOUNT_ID) ?: return
if (callId.isEmpty() || accountId.isEmpty()) {
return
}
when (action) {
ACTION_CALL_ACCEPT_AUDIO -> {
startActivity(Intent(ACTION_CALL_ACCEPT)
.putExtras(extras)
.setClass(applicationContext, CallActivity::class.java)
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK))
}
ACTION_CALL_ACCEPT -> {
startActivity(Intent(ACTION_CALL_ACCEPT)
.putExtras(extras)
.setClass(applicationContext, CallActivity::class.java)
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK))
}
ACTION_CALL_HOLD_ACCEPT -> {
val holdId = extras.getString(NotificationService.KEY_HOLD_ID)!!
mCallService.hold(accountId, holdId)
startActivity(Intent(ACTION_CALL_ACCEPT)
.putExtras(extras)
.setClass(applicationContext, CallActivity::class.java)
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK))
}
ACTION_CALL_END_ACCEPT -> {
val endId = extras.getString(NotificationService.KEY_END_ID)!!
mCallService.hangUp(accountId, endId)
startActivity(Intent(ACTION_CALL_ACCEPT)
.putExtras(extras)
.setClass(applicationContext, CallActivity::class.java)
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK))
}
ACTION_CALL_REFUSE -> {
mCallService.refuse(accountId, callId)
mHardwareService.closeAudioState()
}
ACTION_CALL_END -> {
mCallService.hangUp(accountId, callId)
mHardwareService.closeAudioState()
}
ACTION_CALL_VIEW -> {
startActivity(Intent(Intent.ACTION_VIEW)
.putExtras(extras)
.setClass(applicationContext, if (DeviceUtils.isTv(this)) TVCallActivity::class.java else CallActivity::class.java)
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK))
}
}
}
private fun handleConvAction(intent: Intent, action: String, extras: Bundle?) {
val path = ConversationPath.fromIntent(intent)
if (path == null || path.conversationId.isEmpty()) {
return
}
when (action) {
ACTION_CONV_READ -> mConversationFacade.readMessages(path.accountId, path.conversationUri)
ACTION_CONV_DISMISS -> {
extras?.getString(KEY_MESSAGE_ID)?.let { messageId ->
mConversationFacade.messageNotified(path.accountId, path.conversationUri, messageId)
}
}
ACTION_CONV_REPLY_INLINE -> {
val remoteInput = RemoteInput.getResultsFromIntent(intent)
if (remoteInput != null) {
val reply = remoteInput.getCharSequence(KEY_TEXT_REPLY)
if (!reply.isNullOrEmpty()) {
val uri = path.conversationUri
val message = reply.toString()
mConversationFacade.startConversation(path.accountId, uri)
.flatMapCompletable { c: Conversation ->
mConversationFacade.sendTextMessage(c, uri, message)
.doOnComplete { mNotificationService.showTextNotification(path.accountId, c)}
}
.subscribe()
}
}
}
ACTION_CONV_ACCEPT -> startActivity(Intent(Intent.ACTION_VIEW, path.toUri(), applicationContext, ConversationActivity::class.java)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
else -> {
}
}
}
fun refreshContacts() {
if (mAccountService.currentAccount == null) {
return
}
mContactService.loadContacts(
mAccountService.hasRingAccount(),
mAccountService.hasSipAccount(),
mAccountService.currentAccount
)
}
private class ContactsContentObserver internal constructor() : ContentObserver(null) {
override fun onChange(selfChange: Boolean, uri: Uri?) {
super.onChange(selfChange, uri)
//mContactService.loadContacts(mAccountService.hasRingAccount(), mAccountService.hasSipAccount(), mAccountService.getCurrentAccount());
}
}
companion object {
private val TAG = DRingService::class.java.simpleName
const val ACTION_TRUST_REQUEST_ACCEPT = BuildConfig.APPLICATION_ID + ".action.TRUST_REQUEST_ACCEPT"
const val ACTION_TRUST_REQUEST_REFUSE = BuildConfig.APPLICATION_ID + ".action.TRUST_REQUEST_REFUSE"
const val ACTION_TRUST_REQUEST_BLOCK = BuildConfig.APPLICATION_ID + ".action.TRUST_REQUEST_BLOCK"
const val ACTION_CALL_ACCEPT_AUDIO = BuildConfig.APPLICATION_ID + ".action.CALL_ACCEPT_AUDIO"
const val ACTION_CALL_ACCEPT = BuildConfig.APPLICATION_ID + ".action.CALL_ACCEPT"
const val ACTION_CALL_HOLD_ACCEPT = BuildConfig.APPLICATION_ID + ".action.CALL_HOLD_ACCEPT"
const val ACTION_CALL_END_ACCEPT = BuildConfig.APPLICATION_ID + ".action.CALL_END_ACCEPT"
const val ACTION_CALL_REFUSE = BuildConfig.APPLICATION_ID + ".action.CALL_REFUSE"
const val ACTION_CALL_END = BuildConfig.APPLICATION_ID + ".action.CALL_END"
const val ACTION_CALL_VIEW = BuildConfig.APPLICATION_ID + ".action.CALL_VIEW"
const val ACTION_CONV_READ = BuildConfig.APPLICATION_ID + ".action.CONV_READ"
const val ACTION_CONV_DISMISS = BuildConfig.APPLICATION_ID + ".action.CONV_DISMISS"
const val ACTION_CONV_ACCEPT = BuildConfig.APPLICATION_ID + ".action.CONV_ACCEPT"
const val ACTION_CONV_REPLY_INLINE = BuildConfig.APPLICATION_ID + ".action.CONV_REPLY"
const val ACTION_FILE_ACCEPT = BuildConfig.APPLICATION_ID + ".action.FILE_ACCEPT"
const val ACTION_FILE_CANCEL = BuildConfig.APPLICATION_ID + ".action.FILE_CANCEL"
const val KEY_MESSAGE_ID = "messageId"
const val KEY_TRANSFER_ID = "transferId"
const val KEY_TEXT_REPLY = "textReply"
private const val NOTIFICATION_ID = 1
var isRunning = false
}
}
|
gpl-3.0
|
4921c5e1019136877240fa1a22dc14fa
| 41.913279 | 151 | 0.642731 | 4.792373 | false | false | false | false |
sujeet4github/MyLangUtils
|
LangKotlin/Idiomatic/src/main/kotlin/idiomatic/FunctionalProgramming.kt
|
1
|
2150
|
package idiomaticKotlin
import com.jayway.jsonpath.JsonPath
import java.util.Locale
// # Take advantages of functional programming support in Kotlin (better support then in java due to immutability and expression)
// -> reduce side-effects (less error-prone, easier to understand, thread-safe)
// (start with an enumeration of the relevant ##-points)
// ## use immutability (val for variables and properties, immutable data classes, copy(), kotlin's collection api (read-only))
data class Person(var name: String)
//better:
data class Person2(val name: String)
//var x = "hi"
//// better:
//val y = "hallo"
// ## use pure functions (without side-effects) where ever possible (therefore, use expressions and single expression functions)
// ## use if, when, try-catch, single expression function! -> concise, expressive, stateless
// expression instead of statements (if, when) -> combine control structure with other expression concisely
// Don't:
fun getDefaultLocale(deliveryArea: String): Locale {
val deliverAreaLower = deliveryArea.toLowerCase()
if (deliverAreaLower == "germany" || deliverAreaLower == "austria") {
return Locale.GERMAN
}
if (deliverAreaLower == "usa" || deliverAreaLower == "great britain") {
return Locale.ENGLISH
}
if (deliverAreaLower == "french") {
return Locale.FRENCH
}
return Locale.ENGLISH
}
// Do:
fun getDefaultLocale2(deliveryArea: String) = when (deliveryArea.toLowerCase()) {
"germany", "austria" -> Locale.GERMAN
"usa", "great britain" -> Locale.ENGLISH
"french" -> Locale.FRENCH
else -> Locale.ENGLISH
}
//println(getDefaultLocale("germany"))
// in general: consider if an `if` can be replace with a more concise `when` expression.
//try-catch is also an expression!
val json = """{"message":"HELLO"}"""
val message: String = try {
JsonPath.parse(json).read("message")
} catch (ex: Exception) {
json
}
//println(getMessage("""{"message":"HELLO"}""")) //hello
// ## use lambda expression to pass around blocks of code.
fun main(args: Array<String>) {
println(getDefaultLocale("germany"))
println(message) //hello
}
|
gpl-3.0
|
8bebcd3763a991573f1b95115441c15a
| 33.677419 | 129 | 0.70093 | 3.944954 | false | false | false | false |
JimSeker/saveData
|
sqliteDBViewModelDemo_kt/app/src/main/java/edu/cs4730/sqlitedbviewmodeldemo_kt/MainActivity.kt
|
1
|
1642
|
package edu.cs4730.sqlitedbviewmodeldemo_kt
import android.database.Cursor
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import edu.cs4730.sqlitedbviewmodeldemo_kt.db.CursorViewModel
class MainActivity : AppCompatActivity() {
lateinit var mRecyclerView: RecyclerView
lateinit var fab: FloatingActionButton
lateinit var mAdapter: myAdapter
lateinit var mViewModel: CursorViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mViewModel = ViewModelProvider(this).get(CursorViewModel::class.java)
mRecyclerView = findViewById(R.id.list)
mRecyclerView.layoutManager = LinearLayoutManager(this)
mRecyclerView.itemAnimator = DefaultItemAnimator()
mAdapter = myAdapter(null, R.layout.recycler_row, applicationContext)
//add the adapter to the recyclerview
mRecyclerView.adapter = mAdapter
mViewModel.data.observe(this,
Observer<Cursor?> { data -> mAdapter.setCursor(data) })
fab = findViewById(R.id.floatingActionButton)
fab.setOnClickListener(View.OnClickListener {
mViewModel.add("Jim", 3012)
mViewModel.add("Danny", 312)
})
}
}
|
apache-2.0
|
d297d58e50c4315f0937c549cfff94d7
| 41.128205 | 77 | 0.760658 | 5.083591 | false | false | false | false |
gradle/gradle
|
subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/codecs/transform/DefaultTransformerCodec.kt
|
2
|
4586
|
/*
* Copyright 2020 the original author or authors.
*
* 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.gradle.configurationcache.serialization.codecs.transform
import org.gradle.api.artifacts.transform.TransformAction
import org.gradle.api.internal.artifacts.transform.ArtifactTransformActionScheme
import org.gradle.api.internal.artifacts.transform.DefaultTransformer
import org.gradle.api.internal.attributes.ImmutableAttributes
import org.gradle.api.internal.file.FileLookup
import org.gradle.configurationcache.serialization.Codec
import org.gradle.configurationcache.serialization.ReadContext
import org.gradle.configurationcache.serialization.WriteContext
import org.gradle.configurationcache.serialization.decodePreservingSharedIdentity
import org.gradle.configurationcache.serialization.encodePreservingSharedIdentityOf
import org.gradle.configurationcache.serialization.readClassOf
import org.gradle.configurationcache.serialization.readEnum
import org.gradle.configurationcache.serialization.readNonNull
import org.gradle.configurationcache.serialization.writeEnum
import org.gradle.internal.execution.model.InputNormalizer
import org.gradle.internal.fingerprint.DirectorySensitivity
import org.gradle.internal.fingerprint.LineEndingSensitivity
import org.gradle.internal.model.CalculatedValueContainer
import org.gradle.internal.service.ServiceRegistry
internal
class DefaultTransformerCodec(
private val fileLookup: FileLookup,
private val actionScheme: ArtifactTransformActionScheme
) : Codec<DefaultTransformer> {
override suspend fun WriteContext.encode(value: DefaultTransformer) {
encodePreservingSharedIdentityOf(value) {
writeClass(value.implementationClass)
write(value.fromAttributes)
writeEnum(value.inputArtifactNormalizer as InputNormalizer)
writeEnum(value.inputArtifactDependenciesNormalizer as InputNormalizer)
writeBoolean(value.isCacheable)
writeEnum(value.inputArtifactDirectorySensitivity)
writeEnum(value.inputArtifactDependenciesDirectorySensitivity)
writeEnum(value.inputArtifactLineEndingNormalization)
writeEnum(value.inputArtifactDependenciesLineEndingNormalization)
write(value.isolatedParameters)
// TODO - isolate now and discard node, if isolation is scheduled but has no dependencies
}
}
override suspend fun ReadContext.decode(): DefaultTransformer? {
return decodePreservingSharedIdentity {
val implementationClass = readClassOf<TransformAction<*>>()
val fromAttributes = readNonNull<ImmutableAttributes>()
val inputArtifactNormalizer = readEnum<InputNormalizer>()
val inputArtifactDependenciesNormalizer = readEnum<InputNormalizer>()
val isCacheable = readBoolean()
val inputArtifactDirectorySensitivity = readEnum<DirectorySensitivity>()
val inputArtifactDependenciesDirectorySensitivity = readEnum<DirectorySensitivity>()
val inputArtifactLineEndingNormalization = readEnum<LineEndingSensitivity>()
val inputArtifactDependenciesLineEndingNormalization = readEnum<LineEndingSensitivity>()
val isolatedParameters = readNonNull<CalculatedValueContainer<DefaultTransformer.IsolatedParameters, DefaultTransformer.IsolateTransformerParameters>>()
DefaultTransformer(
implementationClass,
isolatedParameters,
fromAttributes,
inputArtifactNormalizer,
inputArtifactDependenciesNormalizer,
isCacheable,
fileLookup,
actionScheme.instantiationScheme,
isolate.owner.service(ServiceRegistry::class.java),
inputArtifactDirectorySensitivity,
inputArtifactDependenciesDirectorySensitivity,
inputArtifactLineEndingNormalization,
inputArtifactDependenciesLineEndingNormalization
)
}
}
}
|
apache-2.0
|
70eb199a9905cda14fe11fb4163f553b
| 49.395604 | 164 | 0.76014 | 5.668727 | false | true | false | false |
duftler/orca
|
orca-sql/src/main/kotlin/com/netflix/spinnaker/orca/sql/telemetry/SlowQueryLogger.kt
|
1
|
1495
|
/*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.sql.telemetry
import org.jooq.ExecuteContext
import org.jooq.impl.DefaultExecuteListener
import org.jooq.tools.StopWatch
import org.slf4j.LoggerFactory
import java.util.concurrent.TimeUnit
class SlowQueryLogger(
slowQuerySecondsThreshold: Long = 1
) : DefaultExecuteListener() {
private lateinit var watch: StopWatch
private val log = LoggerFactory.getLogger(javaClass)
private val slowQueryThreshold = TimeUnit.SECONDS.toNanos(slowQuerySecondsThreshold)
override fun executeStart(ctx: ExecuteContext) {
super.executeStart(ctx)
watch = StopWatch()
}
override fun executeEnd(ctx: ExecuteContext) {
super.executeEnd(ctx)
if (watch.split() > slowQueryThreshold) {
log.warn("Slow SQL (${watch.splitToMillis()}ms):\n${ctx.query()}")
}
}
private fun StopWatch.splitToMillis() = TimeUnit.NANOSECONDS.toMillis(split())
}
|
apache-2.0
|
03f843f21a0d39ccbbdf8f27d85c881e
| 31.5 | 86 | 0.751171 | 4.073569 | false | false | false | false |
Nandi/adventofcode
|
src/Day7/December7.kt
|
1
|
3404
|
package Day7
import java.nio.file.Files
import java.nio.file.Paths
import java.util.stream.Stream
import kotlin.text.Regex
/**
* todo: visualize
*
* This year, Santa brought little Bobby Tables a set of wires and bitwise logic gates! Unfortunately, little Bobby is
* a little under the recommended age range, and he needs help assembling the circuit.
*
* Each wire has an identifier (some lowercase letters) and can carry a 16-bit signal (a number from 0 to 65535). A
* signal is provided to each wire by a gate, another wire, or some specific value. Each wire can only get a signal
* from one source, but can provide its signal to multiple destinations. A gate provides no signal until all of its
* inputs have a signal.
*
* The included instructions booklet describes how to connect the parts together: x AND y -> z means to connect wires
* x and y to an AND gate, and then connect its output to wire z.
*
* Other possible gates include OR (bitwise OR) and RSHIFT (right-shift). If, for some reason, you'd like to emulate
* the circuit instead, almost all programming languages (for example, C, JavaScript, or Python) provide operators for
* these gates.
*
* Part 1
*
* In little Bobby's kit's instructions booklet (provided as your puzzle input), what signal is ultimately provided to
* wire a?
*
* Part 2
*
* Now, take the signal you got on wire a, override wire b to that signal, and reset the other wires (including wire a).
* What new signal is ultimately provided to wire a?
*
* Created by Simon on 07/12/2015.
*/
class December7 {
fun main() {
val lines = loadFile("src/Day7/7.dec_input.txt")
for (line in lines) {
val (input, label) = line.split(" -> ")
if (line.contains(Regex("AND|OR"))) {
val values = input.split(" ");
try {
nodes.put(label, Node(GATES.valueOf(values[1]), values[0].toInt(), arrayOf(values[2])))
} catch (e: NumberFormatException) {
nodes.put(label, Node(GATES.valueOf(values[1]), inputWire = arrayOf(values[0], values[2])))
}
} else if (line.contains("NOT")) {
nodes.put(label, Node(GATES.NOT, inputWire = arrayOf(input.substringAfter("NOT "))))
} else if (line.contains(Regex("LSHIFT|RSHIFT"))) {
val values = input.split(" ");
nodes.put(label, Node(GATES.valueOf(values[1]), values[2].toInt(), arrayOf(values[0])))
} else {
try {
nodes.put(label, Node(GATES.NONE, input.toInt(), arrayOf()))
} catch (e: NumberFormatException) {
nodes.put(label, Node(GATES.NONE, inputWire = arrayOf(input)))
}
}
}
val valueA = nodes["a"]?.getOutput()
//part 1
println("The value of wire a is $valueA")
for (entry in nodes) {
entry.value.reset()
}
nodes["b"] = Node(GATES.NONE, valueA!!, arrayOf());
//part 2
println("The value of wire a after wire b value change ${nodes["a"]?.getOutput()}")
}
fun loadFile(path: String): Stream<String> {
val input = Paths.get(path);
val reader = Files.newBufferedReader(input);
return reader.lines();
}
}
fun main(args: Array<String>) {
December7().main()
}
|
mit
|
645eba234268f6c8049c369192dd3ec8
| 37.681818 | 120 | 0.614571 | 3.95814 | false | false | false | false |
rori-dev/lunchbox
|
backend-spring-kotlin/src/test/kotlin/lunchbox/domain/resolvers/LunchResolverAokCafeteriaTest.kt
|
1
|
15706
|
package lunchbox.domain.resolvers /* ktlint-disable max-line-length */
import io.mockk.mockk
import lunchbox.domain.models.LunchOffer
import lunchbox.domain.models.LunchProvider.AOK_CAFETERIA
import lunchbox.util.date.DateValidator
import lunchbox.util.html.HtmlParser
import org.amshove.kluent.shouldContain
import org.amshove.kluent.shouldHaveSize
import org.junit.jupiter.api.Test
class LunchResolverAokCafeteriaTest {
private val htmlParser = HtmlParser(mockk())
private fun resolver() = LunchResolverAokCafeteria(DateValidator.alwaysValid(), htmlParser)
private val providerId = AOK_CAFETERIA.id
@Test
fun `resolve offers for week of 2020-08-31`() {
val url = javaClass.getResource("/menus/aok_cafeteria/2020-08-31.html")
val offers = resolver().resolve(url)
offers shouldHaveSize 23
var week = weekOf("2020-08-31")
offers shouldContain LunchOffer(0, "Gemüse-Spaghetti", "in Sahnesaue", week.monday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Fruchtige Asia-Gemüse Pfanne", "mit Hähnchen und Reis", week.monday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schnitzel", "mit Champignonrahm und Rosmarinkartoffeln", week.tuesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "vegetarische Tortellini", "mit Pilzrahm", week.tuesday, null, setOf("vegetarisch"), providerId)
offers shouldContain LunchOffer(0, "Hähnchengemüsecurry", "mit Reis, dazu Rote Beete", week.tuesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Vanille Milchreis", "mit Apfelmus", week.wednesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinebraten", "mit Sauce, Speckbohnen und Kartoffeln", week.wednesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "hausgem. Kotelett", "mit Spargelgemüse und Kartoffeln", week.wednesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hackbraten", "Buttermöhren und Kartoffeln", week.thursday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hähnchenschnitzel", "mit Blumenkohlsauce und Kartoffeln", week.thursday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Mexikanische Bohnenpfanne", "mit Süßkartoffel-Schnitte und Joghurt", week.thursday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "gebratendes Seelachs", "mit Dillsauce und Kartoffeln", week.friday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "gebrat. Seelachs", "mit Dillsoße, Kartoffeln und Rohkost", week.friday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinefilet", "mit Letscho und Bratkartoffeln", week.friday, null, emptySet(), providerId)
week = weekOf("2020-09-07")
offers shouldContain LunchOffer(0, "Boulette", "mit Blumenkohl- Erbsengemüse und Kartoffeln", week.monday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Putenfrikasse", "mit Reis und Rohkost", week.monday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gabelspaghetti", "mit Bolognesesoße", week.tuesday, null, setOf("vegetarisch"), providerId)
offers shouldContain LunchOffer(0, "Hähnchenbrustfilet", "mit Wachsbohnen und Kartoffeln", week.tuesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Eierkuchen", "mit Erdbeer- Rhabarbarsoße", week.wednesday, null, setOf("vegetarisch"), providerId)
offers shouldContain LunchOffer(0, "Kräuterbraten", "mit Soße, Rotkohl und Kartoffeln", week.wednesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Seelachs", "mit Meerettich- Petersiliensoße, Kartoffeln und Rohkost", week.thursday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hähnchencurry", "mit Wildreis und Dessert", week.thursday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Gemüseschnitzel", "mit Mischgemüse und Kartoffeln", week.friday, null, emptySet(), providerId)
}
// @Test
fun `resolve offers for week of 2020-08-31_alt`() {
val url = javaClass.getResource("/menus/aok_cafeteria/2020-08-31_alt.html")
val offers = resolver().resolve(url)
offers shouldHaveSize 29
var week = weekOf("2020-08-31")
offers shouldContain LunchOffer(0, "Gemüse-Spaghetti", "in Sahnesaue", week.monday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Fruchtige Asia-Gemüse Pfanne", "mit Hähnchen und Reis", week.monday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schnitzel", "mit Champignonrahm und Rosmarinkartoffeln", week.tuesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "vegetarische Tortellini", "mit Pilzrahm", week.tuesday, null, setOf("vegetarisch"), providerId)
offers shouldContain LunchOffer(0, "Bunter Vitaminsalat", "Ananas, Gemüsemais, Feta, Eisbergsalat, Grüne Gurke, Ei, Porree und geriebene süße Mandel, Joghurtdressing", week.tuesday, null, setOf("auf Vorbestellung"), providerId)
offers shouldContain LunchOffer(0, "Vanille Milchreis", "mit Apfelmus", week.wednesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinebraten", "mit Sauce, Speckbohnen und Kartoffeln", week.wednesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Bunter Vitaminsalat", "Ananas, Gemüsemais, Feta, Eisbergsalat, Grüne Gurke, Ei, Porree und geriebene süße Mandel, Joghurtdressing", week.wednesday, null, setOf("auf Vorbestellung"), providerId)
offers shouldContain LunchOffer(0, "Hackbraten", "Buttermöhren und Kartoffeln", week.thursday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hähnchenschnitzel", "mit Blumenkohlsauce und Kartoffeln", week.thursday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Bunter Vitaminsalat", "Ananas, Gemüsemais, Feta, Eisbergsalat, Grüne Gurke, Ei, Porree und geriebene süße Mandel, Joghurtdressing", week.thursday, null, setOf("auf Vorbestellung"), providerId)
offers shouldContain LunchOffer(0, "gebratendes Seelachs", "mit Dillsauce und Kartoffeln", week.friday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "gebrat. Seelachs", "mit Dillsoße, Kartoffeln und Rohkost", week.friday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Bunter Vitaminsalat", "Ananas, Gemüsemais, Feta, Eisbergsalat, Grüne Gurke, Ei, Porree und geriebene süße Mandel, Joghurtdressing", week.friday, null, setOf("auf Vorbestellung"), providerId)
week = weekOf("2020-09-07")
offers shouldContain LunchOffer(0, "Boulette", "mit Blumenkohl- Erbsengemüse und Kartoffeln", week.monday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Putenfrikasse", "mit Reis und Rohkost", week.monday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Griechischer Bauernsalat", "Tomate, Gurke, Rote Zwiebeln, Feta, Oliven, Joghurt Dressing", week.monday, null, setOf("auf Vorbestellung"), providerId)
offers shouldContain LunchOffer(0, "Gabelspaghetti", "mit Bolognesesoße", week.tuesday, null, setOf("vegetarisch"), providerId)
offers shouldContain LunchOffer(0, "Hähnchenbrustfilet", "mit Wachsbohnen und Kartoffeln", week.tuesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Griechischer Bauernsalat", "Tomate, Gurke, Rote Zwiebeln, Feta, Oliven, Joghurt Dressing", week.tuesday, null, setOf("auf Vorbestellung"), providerId)
offers shouldContain LunchOffer(0, "Eierkuchen", "mit Erdbeer- Rhabarbarsoße", week.wednesday, null, setOf("vegetarisch"), providerId)
offers shouldContain LunchOffer(0, "Kräuterbraten", "mit Soße, Rotkohl und Kartoffeln", week.wednesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Griechischer Bauernsalat", "Tomate, Gurke, Rote Zwiebeln, Feta, Oliven, Joghurt Dressing", week.wednesday, null, setOf("auf Vorbestellung"), providerId)
offers shouldContain LunchOffer(0, "Seelachs", "mit Meerettich- Petersiliensoße, Kartoffeln und Rohkost", week.thursday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Hähnchencurry", "mit Wildreis und Dessert", week.thursday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Griechischer Bauernsalat", "Tomate, Gurke, Rote Zwiebeln, Feta, Oliven, Joghurt Dressing", week.thursday, null, setOf("auf Vorbestellung"), providerId)
offers shouldContain LunchOffer(0, "Gemüseschnitzel", "mit Mischgemüse und Kartoffeln", week.friday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Paprika Gulasch", "mit Kartoffeln, dazu einen Joghurt", week.friday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Griechischer Bauernsalat", "Tomate, Gurke, Rote Zwiebeln, Feta, Oliven, Joghurt Dressing", week.friday, null, setOf("auf Vorbestellung"), providerId)
}
@Test
fun `resolve offers for week of 2020-09-14`() {
val url = javaClass.getResource("/menus/aok_cafeteria/2020-09-14.html")
val offers = resolver().resolve(url)
val week = weekOf("2020-09-14")
offers shouldHaveSize 10
offers shouldContain LunchOffer(0, "Minikönigsberge", "Kartoffeln mit Sauce und Roter Beete", week.monday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Makkaroni Pilzpfanne", "Champignon, Zwiebel, und Ratatouligemüse, dazu Joghurt", week.monday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Sahnegeschnetzeltes", "mit Nudeln", week.tuesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "geb. Fischfilet", "mit Rahmwirsing und Reis", week.tuesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Steckrübenmöhreneintopf", "mit Brötchen", week.wednesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kasslerkohlpfanne", "mit Kartoffeln", week.wednesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Eierragout", "und Kartoffeln", week.thursday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweineleber", "mit Kartoffelpüree und Apfel-Zwiebel-Sauce", week.thursday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Vanillemilchsuppe", "mit Nudeln und Obst", week.friday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Schweinegulasch", "mit Kartoffeln und Senfgurke", week.friday, null, emptySet(), providerId)
}
@Test
fun `resolve offers for week of 2021-11-15`() {
val url = javaClass.getResource("/menus/aok_cafeteria/2021-11-15.html")
val offers = resolver().resolve(url)
offers shouldHaveSize 30
var week = weekOf("2021-11-15")
offers shouldContain LunchOffer(0, "Gemüseschnitzel", "mit Kohlrabi- Möhrengemüse und Kartoffeln", week.monday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Chili con Carne", "Rinderhack, mit Reis, Obst", week.monday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kotelett", "120g ohne Knochen, mit Bohnengemüse und Kartoffeln", week.monday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Nudeln Bolognese", "Obst", week.tuesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Weißkohleintopf", "mit Schweinefleisch, Brötchen", week.tuesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Rinderschmorbraten", "mit Rotkohl und Klöße", week.tuesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Fischfilet", "mit Dillsoße und Kartoffeln, dazu Rohkost", week.wednesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Szegediner Gulasch", "mit Kartoffeln", week.wednesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Kaninchenkeule", "in Sahne-Zwiebel-Sauce mit Speckbohnen und Kartoffeln", week.wednesday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Mini Königsberger Klopse", "in Kapernsoße und Kartoffeln", week.thursday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Putenbrust", "mit Spinat-Käse-Sauce und Nudeln", week.thursday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "gebratene Forelle 160g", "mit Püree, Rohkost", week.thursday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Eier", "in Senfsoße und Kartoffeln, Rohkost", week.friday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Bratwurst", "mit Bayrischkraut und Kartoffeln", week.friday, null, emptySet(), providerId)
offers shouldContain LunchOffer(0, "Wildgulasch", "mit Spätzle", week.friday, null, emptySet(), providerId)
week = weekOf("2021-11-22")
offers.filter { it.day == week.monday } shouldHaveSize 3
offers.filter { it.day == week.tuesday } shouldHaveSize 3
offers.filter { it.day == week.wednesday } shouldHaveSize 3
offers.filter { it.day == week.thursday } shouldHaveSize 3
offers.filter { it.day == week.friday } shouldHaveSize 3
}
@Test
fun `resolve offers for week of 2021-12-20`() {
val url = javaClass.getResource("/menus/aok_cafeteria/2021-12-20.html")
val offers = resolver().resolve(url)
offers shouldHaveSize 33
var week = weekOf("2021-12-13")
offers.filter { it.day == week.monday } shouldHaveSize 3
offers.filter { it.day == week.tuesday } shouldHaveSize 3
offers.filter { it.day == week.wednesday } shouldHaveSize 3
offers.filter { it.day == week.thursday } shouldHaveSize 3
offers.filter { it.day == week.friday } shouldHaveSize 3
week = weekOf("2021-12-20")
offers.filter { it.day == week.monday } shouldHaveSize 2
offers.filter { it.day == week.tuesday } shouldHaveSize 2
offers.filter { it.day == week.wednesday } shouldHaveSize 2
offers.filter { it.day == week.thursday } shouldHaveSize 2
offers.filter { it.day == week.friday } shouldHaveSize 0
week = weekOf("2021-12-27")
offers.filter { it.day == week.monday } shouldHaveSize 0
offers.filter { it.day == week.tuesday } shouldHaveSize 0
offers.filter { it.day == week.wednesday } shouldHaveSize 0
offers.filter { it.day == week.thursday } shouldHaveSize 0
offers.filter { it.day == week.friday } shouldHaveSize 0
week = weekOf("2022-01-03")
offers.filter { it.day == week.monday } shouldHaveSize 2
offers.filter { it.day == week.tuesday } shouldHaveSize 2
offers.filter { it.day == week.wednesday } shouldHaveSize 2
offers.filter { it.day == week.thursday } shouldHaveSize 2
offers.filter { it.day == week.friday } shouldHaveSize 2
}
@Test
fun `resolve offers for week of 2022-06-07`() {
val url = javaClass.getResource("/menus/aok_cafeteria/2022-06-07.html")
val offers = resolver().resolve(url)
println(offers)
offers shouldHaveSize 27
var week = weekOf("2022-06-07")
offers.filter { it.day == week.monday } shouldHaveSize 0
offers.filter { it.day == week.tuesday } shouldHaveSize 3
offers.filter { it.day == week.wednesday } shouldHaveSize 3
offers.filter { it.day == week.thursday } shouldHaveSize 3
offers.filter { it.day == week.friday } shouldHaveSize 3
week = weekOf("2022-06-13")
offers.filter { it.day == week.monday } shouldHaveSize 3
offers.filter { it.day == week.tuesday } shouldHaveSize 3
offers.filter { it.day == week.wednesday } shouldHaveSize 3
offers.filter { it.day == week.thursday } shouldHaveSize 3
offers.filter { it.day == week.friday } shouldHaveSize 3
}
}
|
mit
|
fbaf3856bca3d1a2c7aefb7e7e65d0b7
| 74.516908 | 233 | 0.744051 | 3.335182 | false | false | false | false |
t-yoshi/peca-android
|
ui/src/main/java/org/peercast/core/ui/tv/GridItemPresenter.kt
|
1
|
1796
|
package org.peercast.core.ui.tv
/**
* @author (c) 2014-2021, T Yoshizawa
* @licenses Dual licensed under the MIT or GPL licenses.
*/
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.leanback.widget.Presenter
import org.peercast.core.ui.R
class GridItemPresenter : Presenter() {
override fun onCreateViewHolder(parent: ViewGroup): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val frame = object : FrameLayout(inflater.context) {
init {
isFocusable = true
isFocusableInTouchMode = true
updateGridItemBackgroundColor(this, false)
}
override fun setSelected(selected: Boolean) {
super.setSelected(selected)
updateGridItemBackgroundColor(this, selected)
}
}
val view = inflater.inflate(R.layout.grid_item, parent, false) as ImageView
frame.tag = view
frame.addView(view)
return ViewHolder(frame)
}
private fun updateGridItemBackgroundColor(view: FrameLayout, selected: Boolean) {
val r = when (selected) {
true -> R.color.tv_default_selected_background
else -> R.color.tv_default_background
}
val color = ContextCompat.getColor(view.context, r)
view.setBackgroundColor(color)
}
override fun onBindViewHolder(viewHolder: ViewHolder, item: Any) {
(viewHolder.view.tag as ImageView)
.setImageResource(item as Int)
}
override fun onUnbindViewHolder(viewHolder: ViewHolder) {
(viewHolder.view.tag as ImageView).setImageDrawable(null)
}
}
|
gpl-3.0
|
99a0e51883b05cf5f9062039d868aabd
| 32.90566 | 85 | 0.663697 | 4.738786 | false | false | false | false |
angcyo/RLibrary
|
uiview/src/main/java/com/angcyo/uiview/widget/RadarScanView.kt
|
1
|
4859
|
package com.angcyo.uiview.widget
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.Choreographer
import android.view.View
import com.angcyo.uiview.kotlin.density
import com.angcyo.uiview.skin.SkinHelper
/**
* Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved.
* 项目名称:
* 类的描述:雷达扫描效果
* 创建人员:Robi
* 创建时间:2017/06/08 11:46
* 修改人员:Robi
* 修改时间:2017/06/08 11:46
* 修改备注:
* Version: 1.0.0
*/
class RadarScanView(context: Context, attributeSet: AttributeSet? = null) : View(context, attributeSet),
Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
sweepAngle++
mChoreographer.postFrameCallback(this)
}
val paint: Paint by lazy {
Paint(Paint.ANTI_ALIAS_FLAG)
}
/**圈圈之间的距离*/
var circleSpace = 10 * density
var circleWidth = 1 * density
var scanDrawRectF = RectF()
val scanMatrix = Matrix()
var sweepAngle = 0f
set(value) {
field = value % 360
scanMatrix.reset()
scanMatrix.postRotate(field, (measuredWidth / 2).toFloat(), (measuredHeight / 2).toFloat())
postInvalidate()
}
val mChoreographer: Choreographer by lazy {
Choreographer.getInstance()
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (visibility == VISIBLE) {
postFrameCallback()
}
}
private fun postFrameCallback() {
mChoreographer.removeFrameCallback(this)
mChoreographer.postFrameCallback(this)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
mChoreographer.removeFrameCallback(this)
}
override fun onVisibilityChanged(changedView: View?, visibility: Int) {
super.onVisibilityChanged(changedView, visibility)
if (visibility == VISIBLE) {
postFrameCallback()
} else {
mChoreographer.removeFrameCallback(this)
}
}
override fun onDraw(canvas: Canvas) {
val minRadius = 10 * density
//有效的绘制直径
val size = Math.min(measuredWidth, measuredHeight)
if (isInEditMode) {
paint.color = SkinHelper.getTranColor(Color.RED, 0x40)
} else {
paint.color = SkinHelper.getTranColor(SkinHelper.getSkin().themeSubColor, 0x40)
}
//绘制圆圈
canvas.save()
canvas.translate((measuredWidth / 2).toFloat(), (measuredHeight / 2).toFloat())
paint.shader = null
paint.style = Paint.Style.STROKE
paint.strokeWidth = circleWidth //圈的厚度
var circleCount = 0
var circleRadius = circleCount * circleSpace + minRadius
while (circleRadius <= size / 2) {
canvas.drawCircle(0f, 0f, circleRadius - circleWidth, paint)
circleCount++
if (circleCount == 1 || circleCount == 2) {
canvas.drawCircle(0f, 0f, circleRadius - circleWidth + circleCount * 2 * density, paint)
}
circleRadius = circleCount * circleSpace + minRadius
}
//绘制几个无规则的圆
canvas.drawCircle(0f, 0f, 4 * density, paint)
canvas.restore()
//绘制扫描弧度
canvas.save()
circleRadius = (circleCount - 1) * circleSpace + minRadius
paint.style = Paint.Style.FILL
val arcOffset = circleWidth / 2
scanDrawRectF.set(measuredWidth / 2 - circleRadius + arcOffset, measuredHeight / 2 - circleRadius + arcOffset,
measuredWidth / 2 + circleRadius - arcOffset, measuredHeight / 2 + circleRadius - arcOffset)
val shaderColor: Int
val shaderStartColor: Int
if (isInEditMode) {
shaderStartColor = SkinHelper.getTranColor(Color.RED, 0x40)
shaderColor = SkinHelper.getTranColor(Color.RED, 0xFF)
} else {
shaderStartColor = SkinHelper.getTranColor(SkinHelper.getSkin().themeSubColor, 0x40)
shaderColor = SkinHelper.getSkin().themeSubColor// SkinHelper.getTranColor(SkinHelper.getSkin().themeSubColor, 0xFF)
}
paint.shader = object : SweepGradient((measuredWidth / 2).toFloat(), (measuredWidth / 2).toFloat(),
intArrayOf(shaderStartColor, shaderColor, shaderColor), floatArrayOf(0f, 0.3f, 1f)) {
}
if (!isInEditMode) {
canvas.concat(scanMatrix)
}
canvas.drawArc(scanDrawRectF, 0f, (36 * 6).toFloat(), true, paint)
canvas.restore()
}
}
|
apache-2.0
|
957152797c3e121b35066b7544e79945
| 30.465278 | 128 | 0.609673 | 4.383677 | false | false | false | false |
gatheringhallstudios/MHGenDatabase
|
app/src/main/java/com/ghstudios/android/data/classes/Quest.kt
|
1
|
3364
|
package com.ghstudios.android.data.classes
import com.ghstudios.android.ITintedIcon
import com.ghstudios.android.data.util.Converter
/**
* Defines an enumeration describing a Quest Hub.
* Values can be converted from the Enum to a string via toString(),
* and from a string to an Enum via QuestHub.from()
*/
enum class QuestHub {
VILLAGE,
GUILD,
EVENT,
ARENA,
PERMIT;
companion object {
private val converter = Converter(
"Village" to VILLAGE,
"Guild" to GUILD,
"Event" to EVENT,
"Arena" to ARENA,
"Permit" to PERMIT
)
@JvmStatic fun from(value: String) = converter.deserialize(value)
}
override fun toString() = converter.serialize(this)
}
/*
* Class for Quest
*/
class Quest: ITintedIcon {
companion object {
const val QUEST_GOAL_HUNT = 0
const val QUEST_GOAL_SLAY = 1
const val QUEST_GOAL_CAPTURE = 2
const val QUEST_GOAL_DELIVER = 3
const val QUEST_GOAL_HUNTATHON = 4
const val QUEST_GOAL_MARATHON = 5
const val QUEST_TYPE_NONE = 0
const val QUEST_TYPE_KEY = 1
const val QUEST_TYPE_URGENT = 2
}
/* Getters and Setters */
var id: Long = -1
var name = ""
var jpnName = ""
// Clear condition
var goal: String? = ""
// Port or village
var hub: QuestHub? = null
// 0=Normal,1=Key,2=Urgent
var type: Int = 0
var stars: String? = ""
var location: Location? = null
// 0 = Hunter / 1 = Cat
var hunterType: Int = 0
var timeLimit: Int = -1
var fee: Int = -1
// Quest reward in zenny
var reward: Int = -1
// Quest reward in Hunting rank points
var hrp: Int = -1
// Subquest Clear condition
var subGoal: String? = ""
// Subquest reward in zenny
var subReward: Int = -1
// Subquest reward in Hunting rank points
var subHrp: Int = -1
// Quest description
var flavor: String? = ""
//Quest goal -> one of the following constants: (todo: document)
var goalType: Int = 0
var rank: String? = null
var metadata: Int = 0
var permitMonsterId:Int=0
val starString:String
get(){
val sval = stars!!
val s = stars!!.toInt()
if(s<=10) return sval
else return "G"+(s-10)
}
// todo: we'll need a better way to do this that allows localization
val typeText: String
get() {
val keyText: String
if (type == 0)
keyText = ""
else if (type == 1)
keyText = "Key"
else
keyText = "Urgent"
return keyText
}
/**
* Resolves to true if the quest contains a gathering item
*/
val hasGatheringItem get() = metadata and 1 > 0
val hasHuntingRewardItem get() = metadata and 4 > 0
fun HasAcademyPointRequirement(): Boolean {
return metadata and 2 > 0
}
override fun getIconResourceString() = when {
hunterType == 1 -> "quest_cat"
goalType == Quest.QUEST_GOAL_DELIVER -> "quest_icon_green"
goalType == Quest.QUEST_GOAL_CAPTURE -> "quest_icon_grey"
else -> "quest_icon_red"
}
override fun toString(): String {
return this.name
}
}
|
mit
|
d54a51d29463e50baa2712bd49d27b96
| 22.524476 | 73 | 0.568668 | 3.911628 | false | false | false | false |
google-pay/android-quickstart
|
kotlin/app/src/main/java/com/google/android/gms/samples/wallet/viewmodel/CheckoutViewModel.kt
|
1
|
5358
|
package com.google.android.gms.samples.wallet.viewmodel
import android.app.Activity
import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.pay.Pay
import com.google.android.gms.pay.PayApiAvailabilityStatus
import com.google.android.gms.pay.PayClient
import com.google.android.gms.samples.wallet.util.PaymentsUtil
import com.google.android.gms.tasks.Task
import com.google.android.gms.wallet.*
class CheckoutViewModel(application: Application) : AndroidViewModel(application) {
// A client for interacting with the Google Pay API.
private val paymentsClient: PaymentsClient = PaymentsUtil.createPaymentsClient(application)
// A client to interact with the Google Wallet API
private val walletClient: PayClient = Pay.getClient(application)
// LiveData with the result of whether the user can pay using Google Pay
private val _canUseGooglePay: MutableLiveData<Boolean> by lazy {
MutableLiveData<Boolean>().also {
fetchCanUseGooglePay()
}
}
// LiveData with the result of whether the user can save passes to Google Wallet
private val _canSavePasses: MutableLiveData<Boolean> by lazy {
MutableLiveData<Boolean>().also {
fetchCanAddPassesToGoogleWallet()
}
}
val canUseGooglePay: LiveData<Boolean> = _canUseGooglePay
val canSavePasses: LiveData<Boolean> = _canSavePasses
/**
* Determine the user's ability to pay with a payment method supported by your app and display
* a Google Pay payment button.
*
* @return a [LiveData] object that holds the future result of the call.
* @see [](https://developers.google.com/android/reference/com/google/android/gms/wallet/PaymentsClient.html.isReadyToPay)
) */
private fun fetchCanUseGooglePay() {
val isReadyToPayJson = PaymentsUtil.isReadyToPayRequest()
if (isReadyToPayJson == null) _canUseGooglePay.value = false
val request = IsReadyToPayRequest.fromJson(isReadyToPayJson.toString())
val task = paymentsClient.isReadyToPay(request)
task.addOnCompleteListener { completedTask ->
try {
_canUseGooglePay.value = completedTask.getResult(ApiException::class.java)
} catch (exception: ApiException) {
Log.w("isReadyToPay failed", exception)
_canUseGooglePay.value = false
}
}
}
/**
* Creates a [Task] that starts the payment process with the transaction details included.
*
* @param priceCents the price to show on the payment sheet.
* @return a [Task] with the payment information.
* @see [](https://developers.google.com/android/reference/com/google/android/gms/wallet/PaymentsClient#loadPaymentData(com.google.android.gms.wallet.PaymentDataRequest)
) */
fun getLoadPaymentDataTask(priceCents: Long): Task<PaymentData> {
val paymentDataRequestJson = PaymentsUtil.getPaymentDataRequest(priceCents)
val request = PaymentDataRequest.fromJson(paymentDataRequestJson.toString())
return paymentsClient.loadPaymentData(request)
}
/**
* Determine whether the API to save passes to Google Pay is available on the device.
*/
private fun fetchCanAddPassesToGoogleWallet() {
walletClient
.getPayApiAvailabilityStatus(PayClient.RequestType.SAVE_PASSES)
.addOnSuccessListener { status ->
_canSavePasses.value = status == PayApiAvailabilityStatus.AVAILABLE
// } else {
// We recommend to either:
// 1) Hide the save button
// 2) Fall back to a different Save Passes integration (e.g. JWT link)
// Note that a user might become eligible in the future.
}
.addOnFailureListener {
// Google Play Services is too old. API availability can't be verified.
_canUseGooglePay.value = false
}
}
/**
* Exposes the `savePassesJwt` method in the wallet client
*/
val savePassesJwt: (String, Activity, Int) -> Unit = walletClient::savePassesJwt
/**
* Exposes the `savePasses` method in the wallet client
*/
val savePasses: (String, Activity, Int) -> Unit = walletClient::savePasses
// Test generic object used to be created against the API
// See https://developers.google.com/wallet/tickets/boarding-passes/web#json_web_token_jwt for more details
val genericObjectJwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiJnb29nbGUiLCJwYXlsb2FkIjp7ImdlbmVyaWNPYmplY3RzIjpbeyJpZCI6IjMzODgwMDAwMDAwMjIwOTUxNzcuZjUyZDRhZjYtMjQxMS00ZDU5LWFlNDktNzg2ZDY3N2FkOTJiIn1dfSwiaXNzIjoid2FsbGV0LWxhYi10b29sc0BhcHBzcG90LmdzZXJ2aWNlYWNjb3VudC5jb20iLCJ0eXAiOiJzYXZldG93YWxsZXQiLCJpYXQiOjE2NTA1MzI2MjN9.ZURFHaSiVe3DfgXghYKBrkPhnQy21wMR9vNp84azBSjJxENxbRBjqh3F1D9agKLOhrrflNtIicShLkH4LrFOYdnP6bvHm6IMFjqpUur0JK17ZQ3KUwQpejCgzuH4u7VJOP_LcBEnRtzZm0PyIvL3j5-eMRyRAo5Z3thGOsKjqCPotCAk4Z622XHPq5iMNVTvcQJaBVhmpmjRLGJs7qRp87sLIpYOYOkK8BD7OxLmBw9geqDJX-Y1zwxmQbzNjd9z2fuwXX66zMm7pn6GAEBmJiqollFBussu-QFEopml51_5nf4JQgSdXmlfPrVrwa6zjksctIXmJSiVpxL7awKN2w"
}
|
apache-2.0
|
dfc1d28045c2dd6b173d5ec58f3be85a
| 47.279279 | 681 | 0.728257 | 3.718251 | false | false | false | false |
RyanAndroidTaylor/Rapido
|
rapidosqlite/src/main/java/com/izeni/rapidosqlite/query/Query.kt
|
1
|
314
|
package com.izeni.rapidosqlite.query
/**
* Created by ryantaylor on 9/22/16.
*/
open class Query(val tableName: String, val columns: Array<String>? = null, val selection: String? = null, val selectionArgs: Array<String>? = null, val groupBy: String? = null, val order: String? = null, val limit: String? = null)
|
mit
|
e51ab08d9a575b4536f034613557358c
| 51.5 | 231 | 0.713376 | 3.488889 | false | false | false | false |
danrien/projectBlue
|
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/connection/libraries/GivenALibrary/AndWolDisabled/WhenRetrievingTheLibraryConnection.kt
|
2
|
3420
|
package com.lasthopesoftware.bluewater.client.connection.libraries.GivenALibrary.AndWolDisabled
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.connection.BuildingConnectionStatus
import com.lasthopesoftware.bluewater.client.connection.IConnectionProvider
import com.lasthopesoftware.bluewater.client.connection.builder.live.ProvideLiveUrl
import com.lasthopesoftware.bluewater.client.connection.libraries.LibraryConnectionProvider
import com.lasthopesoftware.bluewater.client.connection.okhttp.OkHttpFactory
import com.lasthopesoftware.bluewater.client.connection.settings.ConnectionSettings
import com.lasthopesoftware.bluewater.client.connection.settings.LookupConnectionSettings
import com.lasthopesoftware.bluewater.client.connection.settings.ValidateConnectionSettings
import com.lasthopesoftware.bluewater.client.connection.url.IUrlProvider
import com.lasthopesoftware.bluewater.shared.promises.extensions.DeferredPromise
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.BeforeClass
import org.junit.Test
import java.util.*
class WhenRetrievingTheLibraryConnection {
companion object {
private val urlProvider = mockk<IUrlProvider>()
private val statuses: MutableList<BuildingConnectionStatus> = ArrayList()
private var connectionProvider: IConnectionProvider? = null
private var isLibraryServerWoken = false
@BeforeClass
@JvmStatic
fun before() {
val validateConnectionSettings = mockk<ValidateConnectionSettings>()
every { validateConnectionSettings.isValid(any()) } returns true
val deferredConnectionSettings = DeferredPromise<ConnectionSettings?>(ConnectionSettings(accessCode = "aB5nf", isWakeOnLanEnabled = false))
val lookupConnection = mockk<LookupConnectionSettings>()
every {
lookupConnection.lookupConnectionSettings(LibraryId(3))
} returns deferredConnectionSettings
val liveUrlProvider = mockk<ProvideLiveUrl>()
every { liveUrlProvider.promiseLiveUrl(LibraryId(3)) } returns Promise(urlProvider)
val libraryConnectionProvider = LibraryConnectionProvider(
validateConnectionSettings,
lookupConnection,
{
isLibraryServerWoken = true
Unit.toPromise()
},
liveUrlProvider,
OkHttpFactory
)
val futureConnectionProvider =
libraryConnectionProvider
.promiseLibraryConnection(LibraryId(3))
.apply {
progress.then(statuses::add)
updates(statuses::add)
}
.toFuture()
deferredConnectionSettings.resolve()
connectionProvider = futureConnectionProvider.get()
}
}
@Test
fun thenTheLibraryIsNotWoken() {
assertThat(isLibraryServerWoken).isFalse
}
@Test
fun thenTheConnectionIsCorrect() {
assertThat(connectionProvider?.urlProvider).isEqualTo(urlProvider)
}
@Test
fun thenGettingLibraryIsBroadcast() {
assertThat(statuses)
.containsExactly(
BuildingConnectionStatus.GettingLibrary,
BuildingConnectionStatus.BuildingConnection,
BuildingConnectionStatus.BuildingConnectionComplete
)
}
}
|
lgpl-3.0
|
40a3b2614f879fafdb5b4df5e120d6b1
| 36.582418 | 142 | 0.791228 | 5.074184 | false | false | false | false |
jitsi/jitsi-videobridge
|
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/MediaSourceDesc.kt
|
1
|
6282
|
/*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.nlj
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
import org.jitsi.nlj.rtp.VideoRtpPacket
import org.jitsi.nlj.util.Bandwidth
import org.jitsi.nlj.util.bps
import org.jitsi.utils.ArrayUtils
import java.util.Collections
import java.util.NavigableMap
import java.util.TreeMap
/**
* Represents a collection of [RtpLayerDesc]s that encode the same
* media source. This specific implementation provides webrtc simulcast stream
* suspension detection.
*
* We take the definition of "Media Source" from RFC 7656. It takes a single
* logical source of media, which might be represented by multiple encoded streams.
*
* @author George Politis
*/
@SuppressFBWarnings(
value = ["NP_ALWAYS_NULL"],
justification = "False positives with 'lateinit'."
)
class MediaSourceDesc
@JvmOverloads constructor(
/**
* The [RtpEncodingDesc]s that this [MediaSourceDesc]
* possesses, ordered by their subjective quality from low to high.
*/
val rtpEncodings: Array<RtpEncodingDesc>,
/**
* A string which identifies the owner of this source (e.g. the endpoint
* which is the sender of the source).
*/
val owner: String,
/**
* A string which identifies this source.
*/
val sourceName: String,
/**
* The {@link VideoType} signaled for this media source (defaulting to {@code CAMERA} if nothing has been signaled).
*/
var videoType: VideoType = VideoType.CAMERA,
) {
/**
* Current single-list view of all the encodings' layers.
*/
private lateinit var layers: List<RtpLayerDesc>
/**
* Allow the lookup of a layer by the encoding id of a received packet.
*/
private val layersById: MutableMap<Long, RtpLayerDesc> = HashMap()
/**
* Allow the lookup of a layer by index.
*/
private val layersByIndex: NavigableMap<Int, RtpLayerDesc> = TreeMap()
/**
* Get a view of the source's RTP layers, in quality order.
*/
val rtpLayers: List<RtpLayerDesc>
@Synchronized
get() = layers
/**
* Update the layer cache. Should be synchronized on [this].
*/
private fun updateLayerCache() {
layersById.clear()
layersByIndex.clear()
val layers_ = ArrayList<RtpLayerDesc>()
for (encoding in rtpEncodings) {
for (layer in encoding.layers) {
layersById[encoding.encodingId(layer)] = layer
layersByIndex[layer.index] = layer
layers_.add(layer)
}
}
layers = Collections.unmodifiableList(layers_)
}
init { updateLayerCache() }
/**
* Gets the last "stable" bitrate (in bps) of the encoding of the specified
* index. The "stable" bitrate is measured on every new frame and with a
* 5000ms window.
*
* If the bitrate for the specified index is 0, return bitrate of the highest-
* index layer less than the index with a non-zero bitrate.
*
* @return the last "stable" bitrate (bps) of the encoding with a non-zero rate
* at or below the specified index.
*/
fun getBitrate(nowMs: Long, idx: Int): Bandwidth {
for (entry in layersByIndex.headMap(idx, true).descendingMap()) {
val bitrate = entry.value.getBitrate(nowMs)
if (bitrate.bps > 0) {
return bitrate
}
}
return 0.bps
}
@Synchronized
fun hasRtpLayers(): Boolean = layers.isNotEmpty()
@Synchronized
fun numRtpLayers(): Int =
layersByIndex.size
val primarySSRC: Long
get() = rtpEncodings[0].primarySSRC
@Synchronized
fun getRtpLayerByQualityIdx(idx: Int): RtpLayerDesc? =
layersByIndex[idx]
@Synchronized
fun findRtpLayerDesc(videoRtpPacket: VideoRtpPacket): RtpLayerDesc? {
if (ArrayUtils.isNullOrEmpty(rtpEncodings)) {
return null
}
val encodingId = videoRtpPacket.getEncodingId()
val desc = layersById[encodingId]
return desc
}
@Synchronized
fun findRtpEncodingDesc(ssrc: Long): RtpEncodingDesc? =
rtpEncodings.find { it.matches(ssrc) }
@Synchronized
fun setEncodingLayers(layers: Array<RtpLayerDesc>, ssrc: Long) {
val enc = findRtpEncodingDesc(ssrc) ?: return
enc.layers = layers
updateLayerCache()
}
/**
* Clone an existing media source desc, inheriting layer descs' statistics.
*/
@Synchronized
fun copy() = MediaSourceDesc(
Array(this.rtpEncodings.size) { i -> this.rtpEncodings[i].copy() }, this.owner, this.sourceName, this.videoType
)
override fun toString(): String = "MediaSourceDesc[name=$sourceName owner=$owner, videoType=$videoType, " +
"encodings=${rtpEncodings.joinToString(",")}]"
/**
* Checks whether the given SSRC matches this source's [primarySSRC].
* This is mostly useful only for determining quickly whether two source
* descriptions describe the same source; other functions should be used
* to match received media packets.
*
* @param ssrc the SSRC to match.
* @return `true` if the specified `ssrc` is the primary SSRC
* for this source.
*/
fun matches(ssrc: Long) = rtpEncodings.getOrNull(0)?.primarySSRC == ssrc
}
/**
* Clone an array of media source descriptions.
*/
fun Array<MediaSourceDesc>.copy() = Array(this.size) { i -> this[i].copy() }
fun Array<MediaSourceDesc>.findRtpLayerDesc(packet: VideoRtpPacket): RtpLayerDesc? {
for (source in this) {
source.findRtpLayerDesc(packet)?.let {
return it
}
}
return null
}
|
apache-2.0
|
84c737fb5bfaf00541a1fa826127d290
| 31.05102 | 120 | 0.657593 | 4.247465 | false | false | false | false |
Bombe/Sone
|
src/test/kotlin/net/pterodactylus/sone/web/pages/BookmarksPageTest.kt
|
1
|
2187
|
package net.pterodactylus.sone.web.pages
import net.pterodactylus.sone.data.*
import net.pterodactylus.sone.test.*
import net.pterodactylus.sone.utils.*
import net.pterodactylus.sone.web.*
import net.pterodactylus.sone.web.page.*
import org.hamcrest.MatcherAssert.*
import org.hamcrest.Matchers.*
import org.junit.*
/**
* Unit test for [BookmarksPage].
*/
class BookmarksPageTest : WebPageTest(::BookmarksPage) {
private val post1 = createLoadedPost(1000)
private val post2 = createLoadedPost(3000)
private val post3 = createLoadedPost(2000)
private fun createLoadedPost(time: Long) = mock<Post>().apply {
whenever(isLoaded).thenReturn(true)
whenever(this.time).thenReturn(time)
}
@Before
fun setupBookmarkedPostsAndPagination() {
whenever(core.bookmarkedPosts).thenReturn(setOf(post1, post2, post3))
core.preferences.newPostsPerPage = 5
}
@Test
fun `page returns correct path`() {
assertThat(page.path, equalTo("bookmarks.html"))
}
@Test
@Suppress("UNCHECKED_CAST")
fun `page sets correct posts in template context`() {
verifyNoRedirect {
assertThat(templateContext["posts"] as Collection<Post>, contains(post2, post3, post1))
assertThat((templateContext["pagination"] as Pagination<Post>).items, contains(post2, post3, post1))
assertThat(templateContext["postsNotLoaded"], equalTo<Any>(false))
}
}
@Test
@Suppress("UNCHECKED_CAST")
fun `page does not put unloaded posts in template context but sets a flag`() {
whenever(post3.isLoaded).thenReturn(false)
verifyNoRedirect {
assertThat(templateContext["posts"] as Collection<Post>, contains(post2, post1))
assertThat((templateContext["pagination"] as Pagination<Post>).items, contains(post2, post1))
assertThat(templateContext["postsNotLoaded"], equalTo<Any>(true))
}
}
@Test
fun `bookmarks page can be created by dependency injection`() {
assertThat(baseInjector.getInstance<BookmarksPage>(), notNullValue())
}
@Test
fun `page is annotated with correct menuname`() {
assertThat(page.menuName, equalTo("Bookmarks"))
}
@Test
fun `page is annotated with correct template path`() {
assertThat(page.templatePath, equalTo("/templates/bookmarks.html"))
}
}
|
gpl-3.0
|
ea999e8b89c44eb4dfeaa3c62d51999e
| 28.958904 | 103 | 0.748057 | 3.651085 | false | true | false | false |
jghoman/workshop-jb
|
src/i_introduction/_7_Data_Classes/DataClasses.kt
|
5
|
1554
|
package i_introduction._7_Data_Classes
import util.TODO
class Person1(val name: String, val age: Int)
//no 'new' keyword
fun create() = Person1("Alice", 29)
fun useFromJava() {
// property 'val name' = backing field + getter
// => from Java you access it through 'getName()'
JavaCode7().useKotlinClass(Person1("Bob", 31))
// property 'var mutable' = backing field + getter + setter
}
// It's the same as the following (getters are generated by default):
class Person2(_name: String, _age: Int) { //_name, _age are constructor parameters
val name: String = _name //property initialization is the part of constructor
get(): String {
return $name // you can access the backing field of property with '$' + property name
}
val age: Int = _age
get(): Int {
return $age
}
}
// If you add annotation 'data' for your class, some additional methods will be generated for you
// like 'equals', 'hashCode', 'toString'.
data class Person3(val name: String, val age: Int)
// This class is as good as Person4 (written in Java), 42 lines shorter. =)
fun todoTask7() = TODO(
"""
There is no task for you here.
Just make sure you're not forgetting to read carefully all code examples and comments and
ask questions if you have any. =) Then return 'true' from 'task7'.
More information about classes in kotlin can be found in syntax/classesObjectsInterfaces.kt
""",
references = { JavaCode7.Person4("???", -1) }
)
fun task7(): Boolean = todoTask7()
|
mit
|
617c91a759b1c16f1713c1fce5e82c01
| 31.395833 | 99 | 0.660232 | 3.944162 | false | false | false | false |
Magneticraft-Team/Magneticraft
|
ignore/test/block/BlockOre.kt
|
2
|
1779
|
package block
import com.teamwizardry.librarianlib.common.base.block.BlockMod
import net.minecraft.block.SoundType
import net.minecraft.block.material.Material
import net.minecraft.block.properties.PropertyEnum
import net.minecraft.block.state.BlockStateContainer
import net.minecraft.block.state.IBlockState
import net.minecraft.util.IStringSerializable
/**
* Created by cout970 on 12/05/2016.
*/
object BlockOre : BlockMod("ore_block", Material.ROCK, *OreStates.values().map { it.getName() }.toTypedArray()) {
lateinit var ORE_STATES: PropertyEnum<OreStates>
private set
init {
soundType = SoundType.STONE
setHardness(3.0F)
setResistance(5.0F)
setHarvestLevel("pickaxe", 1, defaultState.withProperty(ORE_STATES, OreStates.COPPER))
setHarvestLevel("pickaxe", 1, defaultState.withProperty(ORE_STATES, OreStates.LEAD))
setHarvestLevel("pickaxe", 2, defaultState.withProperty(ORE_STATES, OreStates.COBALT))
setHarvestLevel("pickaxe", 2, defaultState.withProperty(ORE_STATES, OreStates.TUNGSTEN))
}
override fun damageDropped(state: IBlockState) = state.getValue(ORE_STATES).ordinal
override fun createBlockState(): BlockStateContainer {
ORE_STATES = PropertyEnum.create("ore", OreStates::class.java)!!
return BlockStateContainer(this, ORE_STATES)
}
override fun getStateFromMeta(meta: Int) =
blockState.baseState.withProperty(ORE_STATES, OreStates.values()[meta])
override fun getMetaFromState(state: IBlockState?) =
state?.getValue(ORE_STATES)?.ordinal ?: 0
enum class OreStates : IStringSerializable {
COPPER,
LEAD,
COBALT,
TUNGSTEN;
override fun getName() = name.toLowerCase()
}
}
|
gpl-2.0
|
0dc581d222f9030bfa43dd6cc3fea4a8
| 33.882353 | 113 | 0.714446 | 4.118056 | false | false | false | false |
nisrulz/android-examples
|
BoundServices/app/src/main/java/github/nisrulz/example/boundservices/MyBoundService.kt
|
1
|
1326
|
package github.nisrulz.example.boundservices
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.*
import android.widget.Toast
/** Command to the service to display a message */
const val WHAT_MSG_DATA = 1
const val KEY_MSG_DATA = "data"
class MyBoundService : Service() {
private val messenger by lazy { Messenger(IncomingHandler(applicationContext)) }
override fun onBind(intent: Intent): IBinder? {
Toast.makeText(
applicationContext,
"On Bind of Service", Toast.LENGTH_SHORT
).show()
return messenger.binder
}
private class IncomingHandler(private val applicationContext: Context) :
Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
when (msg.what) {
WHAT_MSG_DATA -> {
val data = msg.data
val dataString = data.getString(KEY_MSG_DATA)
val textToDisplay = "Message received in Service : $dataString"
Toast.makeText(
applicationContext,
textToDisplay, Toast.LENGTH_SHORT
).show()
}
else -> super.handleMessage(msg)
}
}
}
}
|
apache-2.0
|
4dcb236f21a87412a938406004e94fcf
| 29.860465 | 84 | 0.589744 | 4.911111 | false | false | false | false |
robinverduijn/gradle
|
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/codegen/GradleApiExtensionsTest.kt
|
1
|
19970
|
/*
* Copyright 2018 the original author or authors.
*
* 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.gradle.kotlin.dsl.codegen
import com.nhaarman.mockito_kotlin.atMost
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions
import org.gradle.api.internal.file.pattern.PatternMatcher
import org.gradle.internal.hash.HashUtil
import org.gradle.kotlin.dsl.accessors.TestWithClassPath
import org.gradle.kotlin.dsl.fixtures.codegen.ClassAndGroovyNamedArguments
import org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass
import org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType
import org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments
import org.gradle.kotlin.dsl.support.normaliseLineSeparators
import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.CoreMatchers.equalTo
import org.junit.Assert.assertThat
import org.junit.Test
import org.slf4j.Logger
import java.io.File
import java.util.Properties
import java.util.function.Consumer
import java.util.jar.Attributes
import java.util.jar.JarEntry
import java.util.jar.JarOutputStream
import java.util.jar.Manifest
import kotlin.reflect.KClass
class GradleApiExtensionsTest : TestWithClassPath() {
@Test
fun `gradle-api-extensions generated jar is reproducible`() {
apiKotlinExtensionsGenerationFor(
ClassToKClass::class,
ClassToKClassParameterizedType::class,
GroovyNamedArguments::class,
ClassAndGroovyNamedArguments::class
) {
assertGeneratedJarHash("f327e4f70a6ee2c5171fe1b77345bc94")
}
}
@Test
fun `maps java-lang-Class to kotlin-reflect-KClass`() {
apiKotlinExtensionsGenerationFor(ClassToKClass::class) {
assertGeneratedExtensions(
"""
inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`rawClass`(`type`: kotlin.reflect.KClass<*>): Unit =
`rawClass`(`type`.java)
""",
"""
inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`unknownClass`(`type`: kotlin.reflect.KClass<*>): Unit =
`unknownClass`(`type`.java)
""",
"""
inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`invariantClass`(`type`: kotlin.reflect.KClass<kotlin.Number>): Unit =
`invariantClass`(`type`.java)
""",
"""
inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`covariantClass`(`type`: kotlin.reflect.KClass<out kotlin.Number>): Unit =
`covariantClass`(`type`.java)
""",
"""
inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`contravariantClass`(`type`: kotlin.reflect.KClass<in Int>): Unit =
`contravariantClass`(`type`.java)
""",
"""
inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`varargOfClasses`(vararg `types`: kotlin.reflect.KClass<*>): Unit =
`varargOfClasses`(*`types`.map { it.java }.toTypedArray())
""",
"""
inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`arrayOfClasses`(`types`: kotlin.Array<kotlin.reflect.KClass<*>>): Unit =
`arrayOfClasses`(`types`.map { it.java }.toTypedArray())
""",
"""
inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`collectionOfClasses`(`types`: kotlin.collections.Collection<kotlin.reflect.KClass<out kotlin.Number>>): Unit =
`collectionOfClasses`(`types`.map { it.java })
""",
"""
inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`methodParameterizedClass`(`type`: kotlin.reflect.KClass<T>): T =
`methodParameterizedClass`(`type`.java)
""",
"""
inline fun <T : kotlin.Number> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`covariantMethodParameterizedClass`(`type`: kotlin.reflect.KClass<T>): T =
`covariantMethodParameterizedClass`(`type`.java)
""",
"""
inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`methodParameterizedCovariantClass`(`type`: kotlin.reflect.KClass<out T>): T =
`methodParameterizedCovariantClass`(`type`.java)
""",
"""
inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`methodParameterizedContravariantClass`(`type`: kotlin.reflect.KClass<in T>): T =
`methodParameterizedContravariantClass`(`type`.java)
""",
"""
inline fun <T : kotlin.Number> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`covariantMethodParameterizedCovariantClass`(`type`: kotlin.reflect.KClass<out T>): T =
`covariantMethodParameterizedCovariantClass`(`type`.java)
""",
"""
inline fun <T : kotlin.Number> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`covariantMethodParameterizedContravariantClass`(`type`: kotlin.reflect.KClass<in T>): T =
`covariantMethodParameterizedContravariantClass`(`type`.java)
"""
)
assertUsageCompilation(
"""
import kotlin.reflect.*
fun classToKClass(subject: ClassToKClass) {
subject.rawClass(type = String::class)
subject.unknownClass(type = String::class)
subject.invariantClass(type = Number::class)
subject.covariantClass(type = Int::class)
subject.contravariantClass(type = Number::class)
subject.varargOfClasses(Number::class, Int::class)
subject.arrayOfClasses(types = arrayOf(Number::class, Int::class))
subject.collectionOfClasses(listOf(Number::class, Int::class))
subject.methodParameterizedClass(type = Int::class)
subject.covariantMethodParameterizedClass(type = Int::class)
subject.methodParameterizedCovariantClass(type = Int::class)
subject.methodParameterizedContravariantClass(type = Int::class)
subject.covariantMethodParameterizedCovariantClass(type = Int::class)
subject.covariantMethodParameterizedContravariantClass(type = Int::class)
}
"""
)
}
}
@Test
fun `maps Groovy named arguments to Kotlin vararg of Pair`() {
apiKotlinExtensionsGenerationFor(GroovyNamedArguments::class, Consumer::class) {
assertGeneratedExtensions(
"""
inline fun org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments.`rawMap`(vararg `args`: Pair<String, Any?>): Unit =
`rawMap`(mapOf(*`args`))
""",
"""
inline fun org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments.`stringUnknownMap`(vararg `args`: Pair<String, Any?>): Unit =
`stringUnknownMap`(mapOf(*`args`))
""",
"""
inline fun org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments.`stringObjectMap`(vararg `args`: Pair<String, Any?>): Unit =
`stringObjectMap`(mapOf(*`args`))
""",
"""
inline fun org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments.`mapWithOtherParameters`(`foo`: String, `bar`: Int, vararg `args`: Pair<String, Any?>): Unit =
`mapWithOtherParameters`(mapOf(*`args`), `foo`, `bar`)
""",
"""
inline fun org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments.`mapWithLastSamAndOtherParameters`(`foo`: String, vararg `args`: Pair<String, Any?>, `bar`: java.util.function.Consumer<String>): Unit =
`mapWithLastSamAndOtherParameters`(mapOf(*`args`), `foo`, `bar`)
"""
)
assertUsageCompilation(
"""
import java.util.function.Consumer
fun usage(subject: GroovyNamedArguments) {
subject.rawMap("foo" to 42, "bar" to 23L, "bazar" to "cathedral")
subject.stringUnknownMap("foo" to 42, "bar" to 23L, "bazar" to "cathedral")
subject.stringObjectMap("foo" to 42, "bar" to 23L, "bazar" to "cathedral")
subject.mapWithOtherParameters(foo = "foo", bar = 42)
subject.mapWithOtherParameters("foo", 42, "bar" to 23L, "bazar" to "cathedral")
subject.mapWithLastSamAndOtherParameters(foo = "foo") { println(it.toUpperCase()) }
subject.mapWithLastSamAndOtherParameters("foo", "bar" to 23L, "bazar" to "cathedral") { println(it.toUpperCase()) }
subject.mapWithLastSamAndOtherParameters("foo", *arrayOf("bar" to 23L, "bazar" to "cathedral")) { println(it.toUpperCase()) }
subject.mapWithLastSamAndOtherParameters(foo = "foo", bar = Consumer { println(it.toUpperCase()) })
subject.mapWithLastSamAndOtherParameters(foo = "foo", bar = Consumer<String> { println(it.toUpperCase()) })
}
"""
)
}
}
@Test
fun `maps mixed java-lang-Class and Groovy named arguments`() {
apiKotlinExtensionsGenerationFor(ClassAndGroovyNamedArguments::class, Consumer::class) {
assertGeneratedExtensions(
"""
inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassAndGroovyNamedArguments.`mapAndClass`(`type`: kotlin.reflect.KClass<out T>, vararg `args`: Pair<String, Any?>): Unit =
`mapAndClass`(mapOf(*`args`), `type`.java)
""",
"""
inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassAndGroovyNamedArguments.`mapAndClassAndVarargs`(`type`: kotlin.reflect.KClass<out T>, `options`: kotlin.Array<String>, vararg `args`: Pair<String, Any?>): Unit =
`mapAndClassAndVarargs`(mapOf(*`args`), `type`.java, *`options`)
""",
"""
inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassAndGroovyNamedArguments.`mapAndClassAndSAM`(`type`: kotlin.reflect.KClass<out T>, vararg `args`: Pair<String, Any?>, `action`: java.util.function.Consumer<in T>): Unit =
`mapAndClassAndSAM`(mapOf(*`args`), `type`.java, `action`)
"""
)
assertUsageCompilation(
"""
import java.util.function.Consumer
fun usage(subject: ClassAndGroovyNamedArguments) {
subject.mapAndClass<Number>(Int::class)
subject.mapAndClass<Number>(Int::class, "foo" to 42, "bar" to "bazar")
subject.mapAndClassAndVarargs<Number>(Int::class, arrayOf("foo", "bar"))
subject.mapAndClassAndVarargs<Number>(Int::class, arrayOf("foo", "bar"), "bazar" to "cathedral")
}
"""
)
}
}
@Test
fun `maps target type, mapped function and parameters generics`() {
apiKotlinExtensionsGenerationFor(ClassToKClassParameterizedType::class) {
assertGeneratedExtensions(
"""
inline fun <T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`invariantClass`(`type`: kotlin.reflect.KClass<T>, `list`: kotlin.collections.List<T>): T =
`invariantClass`(`type`.java, `list`)
""",
"""
inline fun <T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`covariantClass`(`type`: kotlin.reflect.KClass<out T>, `list`: kotlin.collections.List<T>): T =
`covariantClass`(`type`.java, `list`)
""",
"""
inline fun <T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`contravariantClass`(`type`: kotlin.reflect.KClass<in T>, `list`: kotlin.collections.List<T>): T =
`contravariantClass`(`type`.java, `list`)
""",
"""
inline fun <V : T, T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`covariantMethodParameterizedInvariantClass`(`type`: kotlin.reflect.KClass<V>, `list`: kotlin.collections.List<V>): V =
`covariantMethodParameterizedInvariantClass`(`type`.java, `list`)
""",
"""
inline fun <V : T, T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`covariantMethodParameterizedCovariantClass`(`type`: kotlin.reflect.KClass<out V>, `list`: kotlin.collections.List<out V>): V =
`covariantMethodParameterizedCovariantClass`(`type`.java, `list`)
""",
"""
inline fun <V : T, T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`covariantMethodParameterizedContravariantClass`(`type`: kotlin.reflect.KClass<in V>, `list`: kotlin.collections.List<out V>): V =
`covariantMethodParameterizedContravariantClass`(`type`.java, `list`)
"""
)
assertUsageCompilation(
"""
import java.io.Serializable
fun usage(subject: ClassToKClassParameterizedType<Number>) {
subject.invariantClass(Number::class, emptyList())
subject.covariantClass(Int::class, emptyList())
subject.contravariantClass(Serializable::class, emptyList())
subject.covariantMethodParameterizedInvariantClass(Number::class, emptyList())
subject.covariantMethodParameterizedCovariantClass(Int::class, emptyList())
subject.covariantMethodParameterizedContravariantClass(Serializable::class, emptyList())
}
"""
)
}
}
private
fun apiKotlinExtensionsGenerationFor(vararg classes: KClass<*>, action: ApiKotlinExtensionsGeneration.() -> Unit) =
ApiKotlinExtensionsGeneration(apiJarsWith(*classes), fixturesApiMetadataJar()).apply(action)
private
data class ApiKotlinExtensionsGeneration(val apiJars: List<File>, val apiMetadataJar: File) {
lateinit var generatedSourceFiles: List<File>
}
private
fun ApiKotlinExtensionsGeneration.assertGeneratedExtensions(vararg expectedExtensions: String) {
generatedSourceFiles = generateKotlinDslApiExtensionsSourceTo(
file("src").also { it.mkdirs() },
"org.gradle.kotlin.dsl",
"SourceBaseName",
apiJars,
emptyList(),
PatternMatcher.MATCH_ALL,
fixtureParameterNamesSupplier
)
val generatedSourceCode = generatedSourceFiles.joinToString("") {
it.readText().substringAfter("package org.gradle.kotlin.dsl\n\n")
}
println(generatedSourceCode)
expectedExtensions.forEach { expectedExtension ->
assertThat(generatedSourceCode, containsString(expectedExtension.normaliseLineSeparators().trimIndent()))
}
}
private
fun ApiKotlinExtensionsGeneration.assertUsageCompilation(vararg extensionsUsages: String) {
val useDir = file("use").also { it.mkdirs() }
val usageFiles = extensionsUsages.mapIndexed { idx, usage ->
useDir.resolve("usage$idx.kt").also {
it.writeText("""
import org.gradle.kotlin.dsl.fixtures.codegen.*
import org.gradle.kotlin.dsl.*
$usage
""".trimIndent())
}
}
val logger = mock<Logger> {
on { isTraceEnabled } doReturn false
on { isDebugEnabled } doReturn false
}
compileKotlinApiExtensionsTo(
file("out").also { it.mkdirs() },
generatedSourceFiles + usageFiles,
apiJars,
logger
)
// Assert no warnings were emitted
verify(logger, atMost(1)).isTraceEnabled
verify(logger, atMost(1)).isDebugEnabled
verifyNoMoreInteractions(logger)
}
private
fun GradleApiExtensionsTest.ApiKotlinExtensionsGeneration.assertGeneratedJarHash(hash: String) =
file("api-extensions.jar").let { generatedJar ->
generateApiExtensionsJar(generatedJar, apiJars, apiMetadataJar) {}
assertThat(
HashUtil.createHash(generatedJar, "MD5").asZeroPaddedHexString(32),
equalTo(hash)
)
}
private
fun apiJarsWith(vararg classes: KClass<*>): List<File> =
jarClassPathWith("gradle-api.jar", *classes).asFiles
private
fun fixturesApiMetadataJar(): File =
file("gradle-api-metadata.jar").also { file ->
JarOutputStream(
file.outputStream().buffered(),
Manifest().apply { mainAttributes[Attributes.Name.MANIFEST_VERSION] = "1.0" }
).use { output ->
output.putNextEntry(JarEntry("gradle-api-declaration.properties"))
Properties().apply {
setProperty("includes", "org/gradle/kotlin/dsl/fixtures/codegen/**")
setProperty("excludes", "**/internal/**")
store(output, null)
}
}
}
}
private
val fixtureParameterNamesSupplier = { key: String ->
when {
key.startsWith("${ClassToKClass::class.qualifiedName}.") -> when {
key.contains("Class(") -> listOf("type")
key.contains("Classes(") -> listOf("types")
else -> null
}
key.startsWith("${GroovyNamedArguments::class.qualifiedName}.") -> when {
key.contains("Map(") -> listOf("args")
key.contains("Parameters(") -> listOf("args", "foo", "bar")
else -> null
}
key.startsWith("${ClassAndGroovyNamedArguments::class.qualifiedName}.") -> when {
key.contains("mapAndClass(") -> listOf("args", "type")
key.contains("mapAndClassAndVarargs(") -> listOf("args", "type", "options")
key.contains("mapAndClassAndSAM(") -> listOf("args", "type", "action")
else -> null
}
key.startsWith("${ClassToKClassParameterizedType::class.qualifiedName}.") -> when {
key.contains("Class(") -> listOf("type", "list")
else -> null
}
else -> null
}
}
|
apache-2.0
|
6a6506bb175601d8c876c32d52e6498e
| 46.099057 | 264 | 0.600801 | 5.182974 | false | false | false | false |
spark/photon-tinker-android
|
mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepEnsureCardOnFile.kt
|
1
|
2243
|
package io.particle.mesh.setup.flow.setupsteps
import io.particle.android.sdk.cloud.ParticleCloud
import io.particle.mesh.R
import io.particle.mesh.common.android.livedata.nonNull
import io.particle.mesh.common.android.livedata.runBlockOnUiThreadAndAwaitUpdate
import io.particle.mesh.setup.flow.*
import io.particle.mesh.setup.flow.DialogSpec.ResDialogSpec
import io.particle.mesh.setup.flow.ExceptionType.ERROR_FATAL
import io.particle.mesh.setup.flow.context.SetupContexts
import io.particle.mesh.setup.flow.FlowUiDelegate
import mu.KotlinLogging
class StepEnsureCardOnFile(
private val flowUi: FlowUiDelegate,
private val cloud: ParticleCloud
) : MeshSetupStep() {
private val log = KotlinLogging.logger {}
override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) {
if (ctxs.cloud.paymentCardOnFile) {
return
}
flowUi.showGlobalProgressSpinner(true)
val cardResponse = cloud.getPaymentCard()
ctxs.cloud.paymentCardOnFile = cardResponse.card?.last4 != null
if (ctxs.cloud.paymentCardOnFile) {
return
}
val dialogResult = flowUi.dialogTool.dialogResultLD
.nonNull(scopes)
.runBlockOnUiThreadAndAwaitUpdate(scopes) {
flowUi.dialogTool.newDialogRequest(
ResDialogSpec(
R.string.p_mesh_billing_please_go_to_your_browser,
android.R.string.ok,
R.string.p_mesh_action_exit_setup
)
)
}
log.info { "Result for leave network confirmation dialog: $dialogResult" }
flowUi.dialogTool.clearDialogResult()
val err = when (dialogResult) {
DialogResult.POSITIVE -> ExpectedFlowException(
"Restarting flow after user confirmed payment card"
)
DialogResult.NEGATIVE -> MeshSetupFlowException(
message = "User choosing not to enter payment card; exiting setup",
severity = ERROR_FATAL
)
null -> MeshSetupFlowException(message = "Unknown error when asking user to enter payment card")
}
throw err
}
}
|
apache-2.0
|
6bc394b66b83fabd24687b850d483e6f
| 33 | 108 | 0.651806 | 4.702306 | false | false | false | false |
facebook/litho
|
sample/src/main/java/com/facebook/samples/litho/Demos.kt
|
1
|
35051
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.samples.litho
import android.content.Context
import android.content.Intent
import com.facebook.litho.Component
import com.facebook.litho.sections.SectionContext
import com.facebook.litho.sections.widget.RecyclerCollectionComponent
import com.facebook.litho.widget.ComponentCreator
import com.facebook.samples.litho.java.animations.animatedbadge.AnimatedBadge
import com.facebook.samples.litho.java.animations.animationcallbacks.AnimationCallbacksActivity
import com.facebook.samples.litho.java.animations.animationcomposition.ComposedAnimationsComponent
import com.facebook.samples.litho.java.animations.animationcookbook.AnimationCookBookActivity
import com.facebook.samples.litho.java.animations.bounds.BoundsAnimationComponent as JavaBoundsAnimationComponent
import com.facebook.samples.litho.java.animations.commondynamicprops.CommonDynamicPropsAnimationActivity
import com.facebook.samples.litho.java.animations.docs.AlphaTransitionComponent
import com.facebook.samples.litho.java.animations.docs.AppearTransitionComponent
import com.facebook.samples.litho.java.animations.docs.ParallelTransitionWithAnimatorsComponent
import com.facebook.samples.litho.java.animations.docs.SequenceTransitionLoopComponent
import com.facebook.samples.litho.java.animations.docs.SimpleAllLayoutTransitionComponent
import com.facebook.samples.litho.java.animations.docs.StaggerTransitionComponent
import com.facebook.samples.litho.java.animations.docs.StaggerTransitionSameComponent
import com.facebook.samples.litho.java.animations.docs.StaggerTransitionWithDelayComponent
import com.facebook.samples.litho.java.animations.docs.keyscope.GlobalKeyParentComponent
import com.facebook.samples.litho.java.animations.expandableelement.ExpandableElementActivity
import com.facebook.samples.litho.java.animations.pageindicators.PageIndicatorsRootComponent
import com.facebook.samples.litho.java.animations.sharedelements.SharedElementsComponent
import com.facebook.samples.litho.java.animations.sharedelements.SharedElementsFragmentActivity
import com.facebook.samples.litho.java.animations.transitions.TransitionsActivity
import com.facebook.samples.litho.java.bordereffects.BorderEffectsComponent
import com.facebook.samples.litho.java.changesetdebug.ItemsRerenderingActivity
import com.facebook.samples.litho.java.changesetdebug.PropUpdatingActivity
import com.facebook.samples.litho.java.changesetdebug.ScrollingToBottomActivity
import com.facebook.samples.litho.java.changesetdebug.StateResettingActivity
import com.facebook.samples.litho.java.communicating.CommunicatingBetweenSiblings
import com.facebook.samples.litho.java.communicating.CommunicatingFromChildToParent
import com.facebook.samples.litho.java.communicating.CommunicatingFromParentToChild
import com.facebook.samples.litho.java.duplicatestate.DuplicateState
import com.facebook.samples.litho.java.dynamicprops.DynamicPropsActivity
import com.facebook.samples.litho.java.editor.SimpleEditorExampleActivity
import com.facebook.samples.litho.java.errors.ErrorHandlingActivity
import com.facebook.samples.litho.java.fastscroll.FastScrollHandleComponent
import com.facebook.samples.litho.java.horizontalscroll.HorizontalScrollRootComponent
import com.facebook.samples.litho.java.hscroll.HorizontalScrollWithDynamicItemHeight
import com.facebook.samples.litho.java.hscroll.HorizontalScrollWithSnapActivity
import com.facebook.samples.litho.java.identity.ComponentIdentityActivity
import com.facebook.samples.litho.java.incrementalmount.IncrementalMountWithCustomViewContainerActivity
import com.facebook.samples.litho.java.lifecycle.LifecycleDelegateActivity
import com.facebook.samples.litho.java.lifecycle.LifecycleFragmentActivity
import com.facebook.samples.litho.java.lifecycle.ViewPagerLifecycleActivity
import com.facebook.samples.litho.java.lithography.LithographyActivity
import com.facebook.samples.litho.java.onboarding.IntroducingLayoutComponent
import com.facebook.samples.litho.java.onboarding.LayoutWithImageComponent
import com.facebook.samples.litho.java.playground.PlaygroundComponent
import com.facebook.samples.litho.java.stateupdates.SectionStateUpdateFromComponentSection
import com.facebook.samples.litho.java.stateupdates.StateUpdateFromOutsideTreeActivity
import com.facebook.samples.litho.java.stats.Stats
import com.facebook.samples.litho.java.textinput.TextInputRequestAndClearFocus
import com.facebook.samples.litho.java.textinput.TextInputWithKeyboardAndFocusDemo
import com.facebook.samples.litho.java.triggers.ClearTextTriggerExampleComponent
import com.facebook.samples.litho.java.triggers.CustomEventTriggerExampleComponent
import com.facebook.samples.litho.java.triggers.TooltipTriggerExampleActivity
import com.facebook.samples.litho.java.viewpager.ViewPagerDemoComponent
import com.facebook.samples.litho.kotlin.animations.animatedapi.AnimatedComponent
import com.facebook.samples.litho.kotlin.animations.animatedbadge.AnimatedBadgeKotlin
import com.facebook.samples.litho.kotlin.animations.animatedcounter.AnimatingCounterRootComponent
import com.facebook.samples.litho.kotlin.animations.animationcomposition.ComposedAnimationsComponentKotlin
import com.facebook.samples.litho.kotlin.animations.bounds.BoundsAnimationComponent
import com.facebook.samples.litho.kotlin.animations.dynamicprops.AllCommonDynamicPropsKComponent
import com.facebook.samples.litho.kotlin.animations.dynamicprops.AnimateDynamicPropsComponent
import com.facebook.samples.litho.kotlin.animations.dynamicprops.AnimateDynamicPropsKComponent
import com.facebook.samples.litho.kotlin.animations.dynamicprops.CommonDynamicPropsComponent
import com.facebook.samples.litho.kotlin.animations.dynamicprops.CommonDynamicPropsKComponent
import com.facebook.samples.litho.kotlin.animations.dynamicprops.CustomDynamicPropsComponent
import com.facebook.samples.litho.kotlin.animations.dynamicprops.CustomDynamicPropsKComponent
import com.facebook.samples.litho.kotlin.animations.expandableelement.ExpandableElementRootKotlinKComponent
import com.facebook.samples.litho.kotlin.animations.messages.Message
import com.facebook.samples.litho.kotlin.animations.transitions.TransitionsComponent
import com.facebook.samples.litho.kotlin.bordereffects.BorderEffectsComponentKotlin
import com.facebook.samples.litho.kotlin.collection.ChangeableItemsCollectionKComponent
import com.facebook.samples.litho.kotlin.collection.CollectionKComponent
import com.facebook.samples.litho.kotlin.collection.DepsCollectionKComponent
import com.facebook.samples.litho.kotlin.collection.FriendsCollectionKComponent
import com.facebook.samples.litho.kotlin.collection.HorizontalScrollKComponent
import com.facebook.samples.litho.kotlin.collection.ModularCollectionKComponent
import com.facebook.samples.litho.kotlin.collection.MultiListCollectionKComponent
import com.facebook.samples.litho.kotlin.collection.PaginationCollectionKComponent
import com.facebook.samples.litho.kotlin.collection.PullToRefreshCollectionKComponent
import com.facebook.samples.litho.kotlin.collection.ScrollToCollectionKComponent
import com.facebook.samples.litho.kotlin.collection.SelectionCollectionKComponent
import com.facebook.samples.litho.kotlin.collection.SpanCollectionKComponent
import com.facebook.samples.litho.kotlin.collection.StaggeredGridCollectionExample
import com.facebook.samples.litho.kotlin.collection.StickyHeaderCollectionKComponent
import com.facebook.samples.litho.kotlin.collection.TabsCollectionKComponent
import com.facebook.samples.litho.kotlin.errors.ErrorHandlingKotlinActivity
import com.facebook.samples.litho.kotlin.gettingstarted.BasicList
import com.facebook.samples.litho.kotlin.gettingstarted.ClickableText
import com.facebook.samples.litho.kotlin.gettingstartedsolution.VerticalSpeller
import com.facebook.samples.litho.kotlin.lithography.LithographyKotlinActivity
import com.facebook.samples.litho.kotlin.logging.LoggingActivity
import com.facebook.samples.litho.kotlin.mountables.SimpleImageViewExampleComponent
import com.facebook.samples.litho.kotlin.mountables.SimpleImageViewWithAccessibilityExampleComponent
import com.facebook.samples.litho.kotlin.mountables.bindto.MountableBindToExampleComponent
import com.facebook.samples.litho.kotlin.mountables.controllers.ControllersExampleComponent
import com.facebook.samples.litho.kotlin.observability.UseFlowComponent
import com.facebook.samples.litho.kotlin.observability.UseLiveDataComponent
import com.facebook.samples.litho.kotlin.playground.PlaygroundKComponent
import com.facebook.samples.litho.kotlin.state.IdentityRootComponent
import com.facebook.samples.litho.kotlin.state.StateParentChildComponent
import com.facebook.samples.litho.kotlin.treeprops.TreePropsExampleComponent
import com.facebook.samples.litho.kotlin.triggers.TooltipTriggerExampleKComponent
import com.facebook.samples.litho.onboarding.FirstComponentActivity
import com.facebook.samples.litho.onboarding.HelloWorldActivity
import com.facebook.samples.litho.onboarding.PostStyledKComponent
import com.facebook.samples.litho.onboarding.PostWithActionsKComponent
import com.facebook.samples.litho.onboarding.UserFeedKComponent
import com.facebook.samples.litho.onboarding.UserFeedWithStoriesKComponent
import com.facebook.samples.litho.onboarding.model.FEED
import com.facebook.samples.litho.onboarding.model.NEBULAS_POST
import com.facebook.samples.litho.onboarding.model.USER_STORIES
class Demos {
companion object {
@kotlin.jvm.JvmField
val DEMOS =
listOf(
DemoList(
name = "Playground",
listOf(
DemoGrouping(
name = "Playground",
listOf(
SingleDemo(name = "Java API Playground") { context ->
PlaygroundComponent.create(context).build()
},
SingleDemo(
name = "Kotlin API Playground",
component = PlaygroundKComponent()))))),
// Please keep this alphabetical with consistent naming and casing!
DemoList(
name = "Kotlin API Demos",
listOf(
DemoGrouping(
name = "Animations",
listOf(
SingleDemo(name = "Animated API Demo", component = AnimatedComponent()),
SingleDemo(name = "Animated Badge", component = AnimatedBadgeKotlin()),
SingleDemo(
name = "Bounds Animation", component = BoundsAnimationComponent()),
SingleDemo(
name = "Animated Counter",
component = AnimatingCounterRootComponent()),
SingleDemo(
name = "Animations Composition",
component = ComposedAnimationsComponentKotlin()),
SingleDemo(
name = "Expandable Element",
component =
ExpandableElementRootKotlinKComponent(
initialMessages = Message.MESSAGES)),
SingleDemo(name = "Transitions", component = TransitionsComponent()),
SingleDemo(name = "[Spec] Common Dynamic Props") { context ->
CommonDynamicPropsComponent.create(context).build()
},
SingleDemo(
name = "[KComponent] Common Dynamic Props",
component = CommonDynamicPropsKComponent()),
SingleDemo(
name = "All Common Dynamic Props",
component = AllCommonDynamicPropsKComponent()),
SingleDemo(name = "[Spec] Custom Dynamic Props") { context ->
CustomDynamicPropsComponent.create(context).build()
},
SingleDemo(
name = "[KComponent] Custom Dynamic Props",
component = CustomDynamicPropsKComponent()),
SingleDemo(name = "[Spec] Animated Dynamic Props") { context ->
AnimateDynamicPropsComponent.create(context).build()
},
SingleDemo(
name = "[KComponent] Animated Dynamic Props",
component = AnimateDynamicPropsKComponent()),
)),
DemoGrouping(
name = "Getting started",
listOf(
SingleDemo(name = "Clickable Text", component = ClickableText("Litho")),
SingleDemo(name = "Basic List", component = BasicList()),
SingleDemo(
name = "Vertical Speller (Solution)",
component = VerticalSpeller("I❤️Litho")))),
DemoGrouping(
name = "Collections",
listOf(
SingleDemo(name = "Fixed Items", component = CollectionKComponent()),
SingleDemo(
name = "Changeable items",
component = ChangeableItemsCollectionKComponent()),
SingleDemo(
name = "Scroll to items",
component = ScrollToCollectionKComponent()),
SingleDemo(
name = "Pull to refresh",
component = PullToRefreshCollectionKComponent()),
SingleDemo(
name = "Sticky Header",
component = StickyHeaderCollectionKComponent()),
SingleDemo(name = "Span", component = SpanCollectionKComponent()),
SingleDemo(
name = "MultiList", component = MultiListCollectionKComponent()),
SingleDemo(
name = "Pagination", component = PaginationCollectionKComponent()),
SingleDemo(name = "Deps", component = DepsCollectionKComponent()),
SingleDemo(
name = "Selection", component = SelectionCollectionKComponent()),
SingleDemo(
name = "Modular Collection",
component = ModularCollectionKComponent()),
SingleDemo(name = "Friends", component = FriendsCollectionKComponent()),
SingleDemo(
name = "Horizontal Scroll",
component = HorizontalScrollKComponent()),
SingleDemo(name = "Tabs", component = TabsCollectionKComponent()),
SingleDemo(
name = "Staggered Grid",
component = StaggeredGridCollectionExample()),
SingleDemo(
name = "Sections Demo: Lithography",
klass = LithographyKotlinActivity::class.java))),
DemoGrouping(
name = "Mountables",
listOf(
SingleDemo(
name = "Simple ImageView Mountable Component Example",
component = SimpleImageViewExampleComponent()),
SingleDemo(
name = "Simple ImageView Mountable Component With A11Y Example",
component = SimpleImageViewWithAccessibilityExampleComponent()),
SingleDemo(
name = "BindTo - Dynamic Values API",
component = MountableBindToExampleComponent()),
SingleDemo(
name = "Controllers", component = ControllersExampleComponent()),
)),
DemoGrouping(
name = "Errors",
listOf(
SingleDemo(
name = "[KComponent] Error Boundaries",
klass = ErrorHandlingKotlinActivity::class.java))),
DemoGrouping(
name = "State",
listOf(
SingleDemo(
name = "Updating State<T> from child component",
component = StateParentChildComponent()),
SingleDemo(
name = "Component Identity", component = IdentityRootComponent()))),
DemoGrouping(
name = "Common Props",
listOf(
SingleDemo(
name = "Border Effects",
component = BorderEffectsComponentKotlin()),
SingleDemo(
name = "TreeProps", component = TreePropsExampleComponent()))),
DemoGrouping(
name = "Triggers",
listOf(
SingleDemo(
name = "Tooltip Trigger",
component = TooltipTriggerExampleKComponent()))),
DemoGrouping(
name = "Logging",
listOf(SingleDemo(name = " Logging", klass = LoggingActivity::class.java))),
DemoGrouping(
name = "Observability",
listOf(
SingleDemo(name = "useLiveData", component = UseLiveDataComponent()),
SingleDemo(name = "useFlow", component = UseFlowComponent()))))),
DemoList(
name = "Java API Demos",
listOf(
DemoGrouping(
name = "Animations",
listOf(
SingleDemo(
name = "Animations Composition",
) { context ->
ComposedAnimationsComponent.create(context).build()
},
SingleDemo(
name = "Expandable Element", ExpandableElementActivity::class.java),
SingleDemo(name = "Animated Badge") { context ->
AnimatedBadge.create(context).build()
},
SingleDemo(name = "Bounds Animation") { context ->
JavaBoundsAnimationComponent.create(context).build()
},
SingleDemo(name = "Page Indicators") { context ->
PageIndicatorsRootComponent.create(context).build()
},
SingleDemo(
name = "Common Dynamic Props Animations",
klass = CommonDynamicPropsAnimationActivity::class.java),
SingleDemo(
name = "Animation Cookbook",
klass = AnimationCookBookActivity::class.java),
SingleDemo(
name = "Animation Callbacks",
klass = AnimationCallbacksActivity::class.java),
SingleDemo(name = "Activity Transition with Shared elements") { context
->
SharedElementsComponent.create(context).build()
},
SingleDemo(
name = "Fragments Transition with Shared elements",
klass = SharedElementsFragmentActivity::class.java),
SingleDemo(
name = "Transitions", klass = TransitionsActivity::class.java),
SingleDemo(name = "All Layout Transition") { context ->
SimpleAllLayoutTransitionComponent.create(context).build()
},
SingleDemo(name = "Alpha Transition") { context ->
AlphaTransitionComponent.create(context).build()
},
SingleDemo(name = "Appear Transition") { context ->
AppearTransitionComponent.create(context).build()
},
SingleDemo(name = "Stagger Transition") { context ->
StaggerTransitionComponent.create(context).build()
},
SingleDemo(name = "Stagger Transition on same Component") { context ->
StaggerTransitionSameComponent.create(context).build()
},
SingleDemo(name = "Stagger Transition with Delay") { context ->
StaggerTransitionWithDelayComponent.create(context).build()
},
SingleDemo(name = "Parallel Transition with Animators") { context ->
ParallelTransitionWithAnimatorsComponent.create(context).build()
},
SingleDemo(name = "Sequence Transition loop") { context ->
SequenceTransitionLoopComponent.create(context).build()
},
SingleDemo(name = "Global key Transition") { context ->
GlobalKeyParentComponent.create(context).build()
})),
DemoGrouping(
name = "Collections",
listOf(
SingleDemo(name = "HorizontalScroll (non-recycling)") { context ->
HorizontalScrollRootComponent.create(context).build()
},
SingleDemo(
name = "Sections Demo: Lithography",
klass = LithographyActivity::class.java),
SingleDemo(
name = "Snapping",
klass = HorizontalScrollWithSnapActivity::class.java),
SingleDemo(name = "Dynamic Item Height") { context ->
HorizontalScrollWithDynamicItemHeight.create(context).build()
})),
DemoGrouping(
name = "Common Props",
listOf(
SingleDemo(name = "Border Effects") { context ->
BorderEffectsComponent.create(context).build()
},
SingleDemo(name = "Duplicate Parent/Child State") { context ->
DuplicateState.create(context).build()
})),
DemoGrouping(
name = "Dynamic Props",
listOf(
SingleDemo(
name = "Dynamic Props Demo",
klass = DynamicPropsActivity::class.java),
SingleDemo(name = "Fast Scroll Handle") { context ->
FastScrollHandleComponent.create(context).build()
})),
DemoGrouping(
name = "Incremental Mount",
listOf(
SingleDemo(
name = "With Custom Animating Container",
klass =
IncrementalMountWithCustomViewContainerActivity::class.java))),
DemoGrouping(
name = "Lifecycle",
listOf(
SingleDemo(
name = "Error Boundaries",
klass = ErrorHandlingActivity::class.java),
SingleDemo(
name = "Lifecycle Callbacks",
klass = LifecycleDelegateActivity::class.java),
SingleDemo(
name = "ViewPager Lifecycle Callbacks",
klass = ViewPagerLifecycleActivity::class.java),
SingleDemo(
name = "Fragment transactions lifecycle",
klass = LifecycleFragmentActivity::class.java))),
DemoGrouping(
name = "Other Widgets",
listOf(
SingleDemo(name = "ViewPager") { context ->
ViewPagerDemoComponent.create(context).build()
})),
DemoGrouping(
name = "State Updates",
listOf(
SingleDemo(
name = "State Update from Outside Litho",
klass = StateUpdateFromOutsideTreeActivity::class.java),
SingleDemo(name = "State Update in Section from Child Component") {
context ->
RecyclerCollectionComponent.create(context)
.disablePTR(true)
.section(
SectionStateUpdateFromComponentSection.create(
SectionContext(context))
.build())
.build()
},
SingleDemo(
name = "State and identity",
klass = ComponentIdentityActivity::class.java),
)),
DemoGrouping(
name = "Communicating between Components",
listOf(
SingleDemo(
name = "From child to parent",
klass = CommunicatingFromChildToParent::class.java),
SingleDemo(
name = "From parent to child",
klass = CommunicatingFromParentToChild::class.java),
SingleDemo(
name = "Between sibling components",
klass = CommunicatingBetweenSiblings::class.java),
)),
DemoGrouping(
name = "TextInput",
listOf(
SingleDemo(name = "Focus and Show Soft Keyboard on Appear") { context ->
TextInputWithKeyboardAndFocusDemo.create(context).build()
},
SingleDemo(name = "Request and Clear Focus with Keyboard") { context ->
TextInputRequestAndClearFocus.create(context).build()
})),
DemoGrouping(
name = "Triggers",
listOf(
SingleDemo(name = "Clear Text Trigger") { context ->
ClearTextTriggerExampleComponent.create(context).build()
},
SingleDemo(name = "Custom Event Trigger") { context ->
CustomEventTriggerExampleComponent.create(context).build()
},
SingleDemo(
name = "Tooltip Trigger",
klass = TooltipTriggerExampleActivity::class.java))),
DemoGrouping(
name = "Editor",
listOf(
SingleDemo(
name = "SimpleEditor for Props and State",
klass = SimpleEditorExampleActivity::class.java))))),
DemoList(
name = "Internal Debugging Samples",
listOf(
DemoGrouping(
name = "Litho Stats",
listOf(
SingleDemo(name = "LithoStats") { context ->
Stats.create(context).build()
})),
DemoGrouping(
name = "Sections Changesets",
listOf(
SingleDemo(
name = "Resetting state",
klass = StateResettingActivity::class.java),
SingleDemo(
name = "Items re-rendering",
klass = ItemsRerenderingActivity::class.java),
SingleDemo(
name = "Not updating with new props",
klass = PropUpdatingActivity::class.java),
SingleDemo(
name = "List scrolls to bottom",
klass = ScrollingToBottomActivity::class.java))))),
DemoList(
name = "Tutorial",
listOf(
DemoGrouping(
name = "Onboarding",
listOf(
SingleDemo(
name = "1. Hello World", klass = HelloWorldActivity::class.java),
SingleDemo(
name = "2. First Litho Component",
klass = FirstComponentActivity::class.java),
SingleDemo(name = "3. Introducing Layout") { context ->
IntroducingLayoutComponent.create(context).name("Linda").build()
},
SingleDemo(name = "3.1. More with Layout") { context ->
LayoutWithImageComponent.create(context).name("Linda").build()
},
SingleDemo(name = "3.2. Flexbox Styling") {
PostStyledKComponent(post = NEBULAS_POST)
},
SingleDemo(name = "4. Add State") {
PostWithActionsKComponent(post = NEBULAS_POST)
},
SingleDemo(name = "5. List") { UserFeedKComponent(posts = FEED) },
SingleDemo(name = "5.1. List within Lists") {
UserFeedWithStoriesKComponent(
posts = FEED, usersWithStories = USER_STORIES)
},
)))))
}
interface DemoItem {
val name: String
}
/**
* The reasons indices are used is so we have something parcelable to pass to the Activity (a
* ComponentCreator is not parcelable).
*/
interface NavigableDemoItem : DemoItem {
fun getIntent(context: Context?, currentIndices: IntArray?): Intent
}
interface HasChildrenDemos {
val demos: List<DemoItem>?
}
/** A DemoList has groupings of SingleDemos or DemoLists to navigate to. */
class DemoList(override val name: String, val datamodels: List<DemoGrouping>) :
NavigableDemoItem, HasChildrenDemos {
override fun getIntent(context: Context?, currentIndices: IntArray?): Intent {
val intent = Intent(context, DemoListActivity::class.java)
intent.putExtra(DemoListActivity.INDICES, currentIndices)
return intent
}
override val demos: List<DemoGrouping>?
get() = datamodels
}
/** A DemoGrouping is a list of demo items that show under a single heading. */
class DemoGrouping
internal constructor(override val name: String, val datamodels: List<NavigableDemoItem>?) :
DemoItem, HasChildrenDemos {
override val demos: List<DemoItem>?
get() = datamodels
}
class SingleDemo : NavigableDemoItem {
override val name: String
val klass: Class<*>?
val componentCreator: ComponentCreator?
val component: Component?
internal constructor(
name: String,
klass: Class<*>? = null,
component: Component? = null,
componentCreator: ComponentCreator? = null
) {
this.name = name
this.klass = klass
this.componentCreator = componentCreator
this.component = component
}
private val activityClass: Class<*>
private get() = klass ?: ComponentDemoActivity::class.java
override fun getIntent(context: Context?, currentIndices: IntArray?): Intent {
val intent = Intent(context, activityClass)
intent.putExtra(DemoListActivity.INDICES, currentIndices)
return intent
}
}
}
|
apache-2.0
|
650781443349ed5b9b5ed97cb41628c5
| 57.121061 | 113 | 0.554826 | 6.058254 | false | false | false | false |
square/leakcanary
|
leakcanary-android-core/src/main/java/leakcanary/NotificationEventListener.kt
|
2
|
3928
|
package leakcanary
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.os.Build
import com.squareup.leakcanary.core.R
import leakcanary.EventListener.Event
import leakcanary.EventListener.Event.DumpingHeap
import leakcanary.EventListener.Event.HeapAnalysisDone
import leakcanary.EventListener.Event.HeapAnalysisDone.HeapAnalysisSucceeded
import leakcanary.EventListener.Event.HeapAnalysisProgress
import leakcanary.EventListener.Event.HeapDumpFailed
import leakcanary.EventListener.Event.HeapDump
import leakcanary.internal.InternalLeakCanary
import leakcanary.internal.NotificationType.LEAKCANARY_LOW
import leakcanary.internal.NotificationType.LEAKCANARY_MAX
import leakcanary.internal.Notifications
object NotificationEventListener : EventListener {
private val appContext = InternalLeakCanary.application
private val notificationManager =
appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
override fun onEvent(event: Event) {
// TODO Unify Notifications.buildNotification vs Notifications.showNotification
// We need to bring in the retained count notifications first though.
if (!Notifications.canShowNotification) {
return
}
when (event) {
is DumpingHeap -> {
val dumpingHeap = appContext.getString(R.string.leak_canary_notification_dumping)
val builder = Notification.Builder(appContext)
.setContentTitle(dumpingHeap)
val notification = Notifications.buildNotification(appContext, builder, LEAKCANARY_LOW)
notificationManager.notify(R.id.leak_canary_notification_dumping_heap, notification)
}
is HeapDumpFailed, is HeapDump -> {
notificationManager.cancel(R.id.leak_canary_notification_dumping_heap)
}
is HeapAnalysisProgress -> {
val progress = (event.progressPercent * 100).toInt()
val builder = Notification.Builder(appContext)
.setContentTitle(appContext.getString(R.string.leak_canary_notification_analysing))
.setContentText(event.step.humanReadableName)
.setProgress(100, progress, false)
val notification =
Notifications.buildNotification(appContext, builder, LEAKCANARY_LOW)
notificationManager.notify(R.id.leak_canary_notification_analyzing_heap, notification)
}
is HeapAnalysisDone<*> -> {
notificationManager.cancel(R.id.leak_canary_notification_analyzing_heap)
val contentTitle = if (event is HeapAnalysisSucceeded) {
val heapAnalysis = event.heapAnalysis
val retainedObjectCount = heapAnalysis.allLeaks.sumBy { it.leakTraces.size }
val leakTypeCount = heapAnalysis.applicationLeaks.size + heapAnalysis.libraryLeaks.size
val unreadLeakCount = event.unreadLeakSignatures.size
appContext.getString(
R.string.leak_canary_analysis_success_notification,
retainedObjectCount,
leakTypeCount,
unreadLeakCount
)
} else {
appContext.getString(R.string.leak_canary_analysis_failed)
}
val flags = if (Build.VERSION.SDK_INT >= 23) {
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
} else {
PendingIntent.FLAG_UPDATE_CURRENT
}
val pendingIntent = PendingIntent.getActivity(appContext, 1, event.showIntent, flags)
showHeapAnalysisResultNotification(contentTitle,pendingIntent)
}
}
}
private fun showHeapAnalysisResultNotification(contentTitle: String, showIntent: PendingIntent) {
val contentText = appContext.getString(R.string.leak_canary_notification_message)
Notifications.showNotification(
appContext, contentTitle, contentText, showIntent,
R.id.leak_canary_notification_analysis_result,
LEAKCANARY_MAX
)
}
}
|
apache-2.0
|
1f8701ae1a9a7dff5aae35c89e0eca41
| 43.134831 | 99 | 0.744145 | 4.801956 | false | false | false | false |
toastkidjp/Jitte
|
app/src/main/java/jp/toastkid/yobidashi/browser/history/ViewHistory.kt
|
1
|
969
|
package jp.toastkid.yobidashi.browser.history
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.browser.UrlItem
import jp.toastkid.yobidashi.search.url_suggestion.ViewHolder
/**
* ViewHistory model.
*
* @author toastkidjp
*/
@Entity(indices = [Index(value = ["url"], unique = true)])
class ViewHistory : UrlItem {
@PrimaryKey(autoGenerate = true)
var _id: Long = 0
var title: String = ""
var url: String = ""
var favicon: String = ""
var viewCount: Int = 0
var lastViewed: Long = 0
override fun bind(holder: ViewHolder) {
holder.setTitle(title)
holder.setUrl(url)
if (favicon.isEmpty()) {
holder.setIconResource(R.drawable.ic_history_black)
return
}
holder.setIconFromPath(favicon)
holder.setTime(lastViewed)
}
override fun urlString() = url
}
|
epl-1.0
|
45f0dabbf19fa0575f3157fd342f9815
| 20.533333 | 63 | 0.662539 | 3.971311 | false | false | false | false |
Deletescape-Media/Lawnchair
|
SystemUIShared/src/com/android/systemui/unfold/progress/FixedTimingTransitionProgressProvider.kt
|
1
|
3826
|
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.unfold.progress
import android.animation.Animator
import android.animation.ObjectAnimator
import android.util.FloatProperty
import com.android.systemui.unfold.UnfoldTransitionProgressProvider
import com.android.systemui.unfold.UnfoldTransitionProgressProvider.TransitionProgressListener
import com.android.systemui.unfold.updates.FOLD_UPDATE_FINISH_CLOSED
import com.android.systemui.unfold.updates.FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE
import com.android.systemui.unfold.updates.FoldStateProvider
import com.android.systemui.unfold.updates.FoldStateProvider.FoldUpdate
/**
* Emits animation progress with fixed timing after unfolding
*/
internal class FixedTimingTransitionProgressProvider(
private val foldStateProvider: FoldStateProvider
) : UnfoldTransitionProgressProvider, FoldStateProvider.FoldUpdatesListener {
private val animatorListener = AnimatorListener()
private val animator =
ObjectAnimator.ofFloat(this, AnimationProgressProperty, 0f, 1f)
.apply {
duration = TRANSITION_TIME_MILLIS
addListener(animatorListener)
}
private var transitionProgress: Float = 0.0f
set(value) {
listeners.forEach { it.onTransitionProgress(value) }
field = value
}
private val listeners: MutableList<TransitionProgressListener> = mutableListOf()
init {
foldStateProvider.addCallback(this)
foldStateProvider.start()
}
override fun destroy() {
animator.cancel()
foldStateProvider.removeCallback(this)
foldStateProvider.stop()
}
override fun onFoldUpdate(@FoldUpdate update: Int) {
when (update) {
FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE ->
animator.start()
FOLD_UPDATE_FINISH_CLOSED ->
animator.cancel()
}
}
override fun addCallback(listener: TransitionProgressListener) {
listeners.add(listener)
}
override fun removeCallback(listener: TransitionProgressListener) {
listeners.remove(listener)
}
override fun onHingeAngleUpdate(angle: Float) {
}
private object AnimationProgressProperty :
FloatProperty<FixedTimingTransitionProgressProvider>("animation_progress") {
override fun setValue(
provider: FixedTimingTransitionProgressProvider,
value: Float
) {
provider.transitionProgress = value
}
override fun get(provider: FixedTimingTransitionProgressProvider): Float =
provider.transitionProgress
}
private inner class AnimatorListener : Animator.AnimatorListener {
override fun onAnimationStart(animator: Animator) {
listeners.forEach { it.onTransitionStarted() }
}
override fun onAnimationEnd(animator: Animator) {
listeners.forEach { it.onTransitionFinished() }
}
override fun onAnimationRepeat(animator: Animator) {
}
override fun onAnimationCancel(animator: Animator) {
}
}
private companion object {
private const val TRANSITION_TIME_MILLIS = 400L
}
}
|
gpl-3.0
|
b218e73d99fdec62b4bfe4e2af6123ec
| 31.700855 | 94 | 0.701516 | 4.886335 | false | false | false | false |
google-developer-training/android-basics-kotlin-mars-photos-app
|
app/src/main/java/com/example/android/marsphotos/overview/PhotoGridAdapter.kt
|
1
|
3024
|
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.marsphotos.overview
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.android.marsphotos.databinding.GridViewItemBinding
import com.example.android.marsphotos.network.MarsPhoto
/**
* This class implements a [RecyclerView] [ListAdapter] which uses Data Binding to present [List]
* data, including computing diffs between lists.
*/
class PhotoGridAdapter :
ListAdapter<MarsPhoto, PhotoGridAdapter.MarsPhotosViewHolder>(DiffCallback) {
/**
* The MarsPhotosViewHolder constructor takes the binding variable from the associated
* GridViewItem, which nicely gives it access to the full [MarsPhoto] information.
*/
class MarsPhotosViewHolder(
private var binding: GridViewItemBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(marsPhoto: MarsPhoto) {
binding.photo = marsPhoto
// This is important, because it forces the data binding to execute immediately,
// which allows the RecyclerView to make the correct view size measurements
binding.executePendingBindings()
}
}
/**
* Allows the RecyclerView to determine which items have changed when the [List] of
* [MarsPhoto] has been updated.
*/
companion object DiffCallback : DiffUtil.ItemCallback<MarsPhoto>() {
override fun areItemsTheSame(oldItem: MarsPhoto, newItem: MarsPhoto): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: MarsPhoto, newItem: MarsPhoto): Boolean {
return oldItem.imgSrcUrl == newItem.imgSrcUrl
}
}
/**
* Create new [RecyclerView] item views (invoked by the layout manager)
*/
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): MarsPhotosViewHolder {
return MarsPhotosViewHolder(
GridViewItemBinding.inflate(LayoutInflater.from(parent.context))
)
}
/**
* Replaces the contents of a view (invoked by the layout manager)
*/
override fun onBindViewHolder(holder: MarsPhotosViewHolder, position: Int) {
val marsPhoto = getItem(position)
holder.bind(marsPhoto)
}
}
|
apache-2.0
|
b3f8f4dec9c0505834ef02f5ab682e50
| 35.878049 | 97 | 0.709987 | 4.659476 | false | false | false | false |
SUPERCILEX/Robot-Scouter
|
library/core-data/src/main/java/com/supercilex/robotscouter/core/data/model/TeamHolder.kt
|
1
|
2637
|
package com.supercilex.robotscouter.core.data.model
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.distinctUntilChanged
import com.firebase.ui.common.ChangeEventType
import com.google.firebase.firestore.DocumentSnapshot
import com.supercilex.robotscouter.core.data.ChangeEventListenerBase
import com.supercilex.robotscouter.core.data.TEAM_KEY
import com.supercilex.robotscouter.core.data.ViewModelBase
import com.supercilex.robotscouter.core.data.isSignedIn
import com.supercilex.robotscouter.core.data.teams
import com.supercilex.robotscouter.core.data.uid
import com.supercilex.robotscouter.core.data.waitForChange
import com.supercilex.robotscouter.core.model.Team
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class TeamHolder(state: SavedStateHandle) : ViewModelBase<Team>(state), ChangeEventListenerBase {
private val _teamListener = state.getLiveData<Team?>("$TEAM_KEY:holder")
val teamListener = _teamListener.distinctUntilChanged()
override fun onCreate(args: Team) {
if (isSignedIn && args.owners.contains(uid)) {
if (args.id.isBlank()) {
GlobalScope.launch(Dispatchers.Main) {
for (potentialTeam in teams.waitForChange()) {
if (args.number == potentialTeam.number) {
_teamListener.value = potentialTeam.copy()
return@launch
}
}
args.add()
_teamListener.value = args.copy()
}
} else {
_teamListener.value = args
}
} else {
_teamListener.value = null
}
teams.keepAlive = true
teams.addChangeEventListener(this)
}
override fun onChildChanged(
type: ChangeEventType,
snapshot: DocumentSnapshot,
newIndex: Int,
oldIndex: Int
) {
if (_teamListener.value?.id != snapshot.id) return
if (type == ChangeEventType.REMOVED) {
_teamListener.value = null
return
} else if (type == ChangeEventType.MOVED) {
return
}
_teamListener.value = teams[newIndex].copy()
}
override fun onDataChanged() {
val current = _teamListener.value ?: return
if (teams.none { it.id == current.id }) _teamListener.value = null
}
override fun onCleared() {
super.onCleared()
teams.keepAlive = false
teams.removeChangeEventListener(this)
}
}
|
gpl-3.0
|
ed3592fd799cb4e0efbf90ca8ad7123c
| 33.697368 | 97 | 0.636329 | 4.777174 | false | false | false | false |
xfournet/intellij-community
|
java/java-impl/src/com/intellij/lang/java/actions/templates.kt
|
1
|
2665
|
// 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.ExpectedTypeInfo
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils
import com.intellij.codeInsight.daemon.impl.quickfix.GuessTypeParameters
import com.intellij.codeInsight.template.TemplateBuilder
import com.intellij.lang.jvm.actions.ExpectedParameters
import com.intellij.lang.jvm.actions.ExpectedTypes
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Computable
import com.intellij.psi.*
import com.intellij.psi.impl.source.PostprocessReformattingAspect
import com.intellij.psi.util.PsiUtil
internal class TemplateContext(
val project: Project,
val factory: PsiElementFactory,
val targetClass: PsiClass,
val builder: TemplateBuilder,
val guesser: GuessTypeParameters,
val guesserContext: PsiElement?
)
internal fun TemplateContext.setupParameters(method: PsiMethod, parameters: ExpectedParameters) {
if (parameters.isEmpty()) return
val postprocessReformattingAspect = PostprocessReformattingAspect.getInstance(project)
val parameterList = method.parameterList
val isInterface = targetClass.isInterface
//255 is the maximum number of method parameters
for (i in 0 until minOf(parameters.size, 255)) {
val parameterInfo = parameters[i]
val names = extractNames(parameterInfo.first) { "p" + i }
val dummyParameter = factory.createParameter(names.first(), PsiType.INT)
if (isInterface) {
PsiUtil.setModifierProperty(dummyParameter, PsiModifier.FINAL, false)
}
val parameter = postprocessReformattingAspect.postponeFormattingInside(Computable {
parameterList.add(dummyParameter)
}) as PsiParameter
setupTypeElement(parameter.typeElement, parameterInfo.second)
setupParameterName(parameter, names)
}
}
internal fun TemplateContext.setupTypeElement(typeElement: PsiTypeElement?, types: ExpectedTypes) {
setupTypeElement(typeElement ?: return, extractExpectedTypes(project, types))
}
@JvmName("setupTypeElementJ")
internal fun TemplateContext.setupTypeElement(typeElement: PsiTypeElement, types: List<ExpectedTypeInfo>): PsiTypeElement {
return guesser.setupTypeElement(typeElement, types.toTypedArray(), guesserContext, targetClass)
}
internal fun TemplateContext.setupParameterName(parameter: PsiParameter, names: Array<out String>) {
val nameIdentifier = parameter.nameIdentifier ?: return
val expression = CreateFromUsageUtils.ParameterNameExpression(names)
builder.replaceElement(nameIdentifier, expression)
}
|
apache-2.0
|
28f52e1ef536cf622fac6aa9f1dd798c
| 43.416667 | 140 | 0.809381 | 4.700176 | false | false | false | false |
walkingice/momome
|
app/src/main/java/org/zeroxlab/momome/impl/EntryActivity.kt
|
1
|
6440
|
/*
* Authored By Julian Chu <[email protected]>
*
* Copyright (c) 2012 0xlab.org - http://0xlab.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zeroxlab.momome.impl
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import android.widget.AdapterView.OnItemClickListener
import org.zeroxlab.momome.Momo
import org.zeroxlab.momome.MomoApp
import org.zeroxlab.momome.MomoModel
import org.zeroxlab.momome.R
import org.zeroxlab.momome.data.Entry
import org.zeroxlab.momome.data.Item
import org.zeroxlab.momome.widget.BasicInputDialog
import org.zeroxlab.momome.widget.EditableActivity
import org.zeroxlab.momome.widget.EditableAdapter
import org.zeroxlab.momome.widget.EntryAdapter
class EntryActivity : EditableActivity(), Momo {
lateinit var mModel: MomoModel
lateinit var mContainer: ListView
lateinit var mTitle: TextView
lateinit var mLTSwitcher: ViewSwitcher // left-top
lateinit var mRTSwitcher: ViewSwitcher // right-top
lateinit var mItem: Item
lateinit var mInflater: LayoutInflater
lateinit var mAdapter: EntryAdapter
lateinit var mEntryClickListener: EntryClickListener
lateinit var mDialogListener: DialogListener
private val DIALOG_DATA = 0x1000
private val DIALOG_COMMENT = 0x1001
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_entry)
mInflater = this.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
mModel = MomoApp.getModel()
mEntryClickListener = EntryClickListener()
mDialogListener = DialogListener()
val key = intent.getStringExtra(Momo.CROSS_ITEM_KEY)
mItem = mModel.getItem(key)
if (initViews(key)) {
mTitle.text = mItem.title
mAdapter = EntryAdapter(this, mItem)
mAdapter.setListener(EditListener())
mContainer.adapter = mAdapter
mContainer.onItemClickListener = mEntryClickListener
}
}
private fun initViews(key: String?): Boolean {
if (key == null || key == "" || mModel.status() != Momo.DataStatus.OK) {
val msg = "Not valid key"
Log.e(Momo.TAG, msg)
val t = Toast.makeText(this, msg, Toast.LENGTH_SHORT)
t.show()
finish()
return false
}
mTitle = findViewById(R.id.entry_title) as TextView
mContainer = findViewById(R.id.entry_container) as ListView
mRTSwitcher = findViewById(R.id.entry_rt_switcher) as ViewSwitcher
mLTSwitcher = findViewById(R.id.entry_lt_switcher) as ViewSwitcher
return true
}
fun onClickEditButton(v: View) {
super.toggleEditing()
}
fun onClickDoneButton(v: View) {
super.toggleEditing()
}
fun onClickAddButton(v: View) {
val entry = Entry(Entry.DEF_NAME, "")
mItem.addEntry(entry)
mAdapter.notifyDataSetChanged()
askData(entry)
}
override fun onStartEdit() {
mAdapter.setEditing(true)
mLTSwitcher.showNext()
mRTSwitcher.showNext()
mContainer.onItemClickListener = null
mContainer.invalidateViews()
}
override fun onStopEdit() {
mAdapter.setEditing(false)
mLTSwitcher.showNext()
mRTSwitcher.showNext()
mContainer.onItemClickListener = mEntryClickListener
mContainer.invalidateViews()
finishEditing()
}
private fun finishEditing() {
mAdapter.notifyDataSetChanged()
mModel.save()
}
private fun askData(entry: Entry) {
val dialog = BasicInputDialog(this, "Edit data")
dialog.setListener(DIALOG_DATA, mDialogListener)
dialog.setExtra(entry)
dialog.setDefaultText(entry.data)
dialog.show()
}
private fun askComment(entry: Entry) {
val dialog = BasicInputDialog(this, "Edit comment")
dialog.setListener(DIALOG_COMMENT, mDialogListener)
dialog.setExtra(entry)
dialog.setDefaultText(entry.comment)
dialog.show()
}
inner class DialogListener : BasicInputDialog.InputListener {
override fun onInput(id: Int, input: CharSequence, extra: Any) {
val entry = extra as Entry
if (id == DIALOG_DATA) {
mItem.updateEntry(entry, input.toString(), entry.comment)
askComment(entry)
} else if (id == DIALOG_COMMENT) {
mItem.updateEntry(entry, entry.data, input.toString())
}
mAdapter.notifyDataSetChanged()
}
override fun onCancelInput(id: Int, extra: Any) {
if (id == DIALOG_DATA) {
askComment(extra as Entry)
}
mAdapter.notifyDataSetChanged()
}
}
internal inner class EditListener : EditableAdapter.EditListener<Entry> {
override fun onEdit(entry: Entry) {
askData(entry) // askData will call askComment
}
override fun onDelete(entry: Entry) {
val success = mItem.removeEntry(entry)
if (success) {
mAdapter.notifyDataSetChanged()
}
}
}
inner class EntryClickListener : OnItemClickListener {
override fun onItemClick(a: AdapterView<*>, v: View, pos: Int, id: Long) {
val intent = Intent(this@EntryActivity, DetailActivity::class.java)
val entry = mAdapter.getItem(pos) as Entry
intent.putExtra(Momo.CROSS_ENTRY_DATA_KEY, entry.data)
intent.putExtra(Momo.CROSS_ENTRY_COMMENT_KEY, entry.comment)
intent.putExtra(Momo.CROSS_ENTRY_TIME_KEY, entry.lastModifiedTime)
startActivity(intent)
}
}
}
|
apache-2.0
|
67721fb454f4b9af1eb7a8b28c167a9a
| 32.717277 | 92 | 0.660559 | 4.41701 | false | false | false | false |
Resonious/discord-talker
|
src/main/kotlin/net/resonious/talker/Data.kt
|
1
|
2485
|
package net.resonious.talker
import com.fasterxml.jackson.module.kotlin.*
import java.io.File
import java.io.FileNotFoundException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.stream.Stream
class Data(private val directory: String) {
data class Voice(val name: String, val maryVoice: String, val maryEffects: String, val emoji: String)
data class Profile(val userId: String, var voiceName: String)
class NoTokenException(
val path: Path,
override val cause: Throwable
) : Exception("Failed to read token from $path", cause)
private val mapper = jacksonObjectMapper()
private val voiceCache = hashMapOf<String, Voice>()
private val profileCache = hashMapOf<String, Profile>()
fun getToken(): String {
val path = Paths.get(directory, "token.txt")
val file = path.toFile()
try {
val lines = file.readLines()
return lines.first()
}
catch (notFound: FileNotFoundException) {
throw NoTokenException(path, notFound)
}
}
fun getProfile(id: String): Profile = profileCache.getOrPut(id, {
val path = Paths.get(directory, "profile-$id.json")
val file = path.toFile()
try {
return mapper.readValue(file)
}
catch (notFound: FileNotFoundException) {
val newProfile = Profile(id, "default")
mapper.writeValue(file, newProfile)
return newProfile
}
})
fun getVoice(name: String): Voice? = voiceCache.getOrPut(name, {
val path = Paths.get(directory, "voice-$name.json")
val file = path.toFile()
return try {
mapper.readValue(file)
}
catch (notFound: FileNotFoundException) {
null
}
})
fun allVoices(): List<Voice> {
return File(directory)
.listFiles({ file -> file.name.contains("voice-") })
.map { mapper.readValue<Voice>(it) }
}
fun getVoiceByEmoji(emoji: String): Voice? {
for (voice in allVoices())
if (voice.emoji == emoji)
return voice
return null
}
fun saveProfile(profile: Profile) {
val path = Paths.get(directory, "profile-${profile.userId}.json")
val file = path.toFile()
mapper.writeValue(file, profile)
profileCache.put(profile.userId, profile)
}
}
|
gpl-3.0
|
ee9f48ab471d976cec6d4220f5dc09f2
| 26.932584 | 105 | 0.606036 | 4.344406 | false | false | false | false |
Kotlin/dokka
|
kotlin-analysis/src/main/kotlin/org/jetbrains/dokka/analysis/DRITargetFactory.kt
|
1
|
1889
|
package org.jetbrains.dokka.analysis
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiParameter
import com.intellij.psi.PsiTypeParameter
import org.jetbrains.dokka.links.DriTarget
import org.jetbrains.dokka.links.PointingToCallableParameters
import org.jetbrains.dokka.links.PointingToDeclaration
import org.jetbrains.dokka.links.PointingToGenericParameters
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.descriptorUtil.parentsWithSelf
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
fun DriTarget.Companion.from(descriptor: DeclarationDescriptor): DriTarget = descriptor.parentsWithSelf.run {
return when (descriptor) {
is TypeParameterDescriptor -> PointingToGenericParameters(descriptor.index)
is ValueParameterDescriptor -> PointingToCallableParameters(descriptor.index)
else -> {
val callable = firstIsInstanceOrNull<CallableDescriptor>()
val params =
callable?.let { listOfNotNull(it.extensionReceiverParameter) + it.valueParameters }.orEmpty()
val parameterDescriptor = firstIsInstanceOrNull<ParameterDescriptor>()
parameterDescriptor?.let { PointingToCallableParameters(params.indexOf(it)) }
?: PointingToDeclaration
}
}
}
fun DriTarget.Companion.from(psi: PsiElement): DriTarget = psi.parentsWithSelf.run {
return when (psi) {
is PsiTypeParameter -> PointingToGenericParameters(psi.index)
else -> firstIsInstanceOrNull<PsiParameter>()?.let {
val callable = firstIsInstanceOrNull<PsiMethod>()
val params = (callable?.parameterList?.parameters).orEmpty()
PointingToCallableParameters(params.indexOf(it))
} ?: PointingToDeclaration
}
}
|
apache-2.0
|
1bc294c09333999eb8b425fb4b9aa268
| 43.97619 | 109 | 0.753309 | 4.945026 | false | false | false | false |
HendraAnggrian/kota
|
kota/src/text/Watchers.kt
|
1
|
1873
|
@file:JvmMultifileClass
@file:JvmName("TextsKt")
@file:Suppress("NOTHING_TO_INLINE", "UNUSED")
package kota
import android.text.Editable
import android.text.SpanWatcher
import android.text.Spannable
import android.text.TextWatcher
@JvmOverloads
inline fun spanWatcherOf(
noinline onSpanChanged: ((text: Spannable, what: Any, ostart: Int, oend: Int, nstart: Int, nend: Int) -> Unit)? = null,
noinline onSpanRemoved: ((text: Spannable, what: Any, start: Int, end: Int) -> Unit)? = null,
noinline onSpanAdded: ((text: Spannable, what: Any, start: Int, end: Int) -> Unit)? = null
): SpanWatcher = object : SpanWatcher {
override fun onSpanChanged(text: Spannable, what: Any, ostart: Int, oend: Int, nstart: Int, nend: Int) {
onSpanChanged?.invoke(text, what, ostart, oend, nstart, nend)
}
override fun onSpanRemoved(text: Spannable, what: Any, start: Int, end: Int) {
onSpanRemoved?.invoke(text, what, start, end)
}
override fun onSpanAdded(text: Spannable, what: Any, start: Int, end: Int) {
onSpanAdded?.invoke(text, what, start, end)
}
}
@JvmOverloads
inline fun textWatcherOf(
noinline beforeTextChanged: ((s: CharSequence, start: Int, count: Int, after: Int) -> Unit)? = null,
noinline afterTextChanged: ((s: Editable) -> Unit)? = null,
noinline onTextChanged: ((s: CharSequence, start: Int, before: Int, count: Int) -> Unit)? = null
): TextWatcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
beforeTextChanged?.invoke(s, start, count, after)
}
override fun afterTextChanged(s: Editable) {
afterTextChanged?.invoke(s)
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
onTextChanged?.invoke(s, start, before, count)
}
}
|
apache-2.0
|
f7216089f3533efe2c8c357c869ae368
| 38.041667 | 127 | 0.674319 | 3.723658 | false | false | false | false |
NordicSemiconductor/Android-nRF-Toolbox
|
profile_gls/src/main/java/no/nordicsemi/android/gls/details/view/GLSDetailsContentView.kt
|
1
|
10879
|
/*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.gls.details.view
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import no.nordicsemi.android.gls.R
import no.nordicsemi.android.gls.data.GLSRecord
import no.nordicsemi.android.gls.main.view.toDisplayString
import no.nordicsemi.android.theme.ScreenSection
@Composable
internal fun GLSDetailsContentView(record: GLSRecord) {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
Column(modifier = Modifier.padding(16.dp)) {
ScreenSection() {
Field(
stringResource(id = R.string.gls_details_sequence_number),
record.sequenceNumber.toString()
)
record.time?.let {
Field(
stringResource(id = R.string.gls_details_date_and_time),
stringResource(R.string.gls_timestamp, it)
)
}
Divider(
color = MaterialTheme.colorScheme.secondary,
thickness = 1.dp,
modifier = Modifier.padding(vertical = 16.dp)
)
record.type?.let {
Field(stringResource(id = R.string.gls_details_type), it.toDisplayString())
Spacer(modifier = Modifier.size(4.dp))
}
record.sampleLocation?.let {
Field(stringResource(id = R.string.gls_details_location), it.toDisplayString())
Spacer(modifier = Modifier.size(4.dp))
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.Bottom
) {
Text(
text = stringResource(id = R.string.gls_details_glucose_condensation_title),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.outline
)
Text(
text = stringResource(
id = R.string.gls_details_glucose_condensation_field,
record.glucoseConcentration,
record.unit.toDisplayString()
),
style = MaterialTheme.typography.titleLarge
)
}
record.status?.let {
Divider(
color = MaterialTheme.colorScheme.secondary,
thickness = 1.dp,
modifier = Modifier.padding(vertical = 16.dp)
)
BooleanField(
stringResource(id = R.string.gls_details_battery_low),
it.deviceBatteryLow
)
Spacer(modifier = Modifier.size(4.dp))
BooleanField(
stringResource(id = R.string.gls_details_sensor_malfunction),
it.sensorMalfunction
)
Spacer(modifier = Modifier.size(4.dp))
BooleanField(
stringResource(id = R.string.gls_details_insufficient_sample),
it.sampleSizeInsufficient
)
Spacer(modifier = Modifier.size(4.dp))
BooleanField(
stringResource(id = R.string.gls_details_strip_insertion_error),
it.stripInsertionError
)
Spacer(modifier = Modifier.size(4.dp))
BooleanField(
stringResource(id = R.string.gls_details_strip_type_incorrect),
it.stripTypeIncorrect
)
Spacer(modifier = Modifier.size(4.dp))
BooleanField(
stringResource(id = R.string.gls_details_sensor_result_too_high),
it.sensorResultHigherThenDeviceCanProcess
)
Spacer(modifier = Modifier.size(4.dp))
BooleanField(
stringResource(id = R.string.gls_details_sensor_result_too_low),
it.sensorResultLowerThenDeviceCanProcess
)
Spacer(modifier = Modifier.size(4.dp))
BooleanField(
stringResource(id = R.string.gls_details_temperature_too_high),
it.sensorTemperatureTooHigh
)
Spacer(modifier = Modifier.size(4.dp))
BooleanField(
stringResource(id = R.string.gls_details_temperature_too_low),
it.sensorTemperatureTooLow
)
Spacer(modifier = Modifier.size(4.dp))
BooleanField(
stringResource(id = R.string.gls_details_strip_pulled_too_soon),
it.sensorReadInterrupted
)
Spacer(modifier = Modifier.size(4.dp))
BooleanField(
stringResource(id = R.string.gls_details_general_device_fault),
it.generalDeviceFault
)
Spacer(modifier = Modifier.size(4.dp))
BooleanField(stringResource(id = R.string.gls_details_time_fault), it.timeFault)
Spacer(modifier = Modifier.size(4.dp))
}
record.context?.let {
Divider(
color = MaterialTheme.colorScheme.secondary,
thickness = 1.dp,
modifier = Modifier.padding(vertical = 16.dp)
)
Field(
stringResource(id = R.string.gls_context_title),
stringResource(id = R.string.gls_available)
)
Spacer(modifier = Modifier.size(4.dp))
it.carbohydrate?.let {
Field(
stringResource(id = R.string.gls_context_carbohydrate),
it.toDisplayString()
)
Spacer(modifier = Modifier.size(4.dp))
}
it.meal?.let {
Field(stringResource(id = R.string.gls_context_meal), it.toDisplayString())
Spacer(modifier = Modifier.size(4.dp))
}
it.tester?.let {
Field(
stringResource(id = R.string.gls_context_tester),
it.toDisplayString()
)
Spacer(modifier = Modifier.size(4.dp))
}
it.health?.let {
Field(
stringResource(id = R.string.gls_context_health),
it.toDisplayString()
)
Spacer(modifier = Modifier.size(4.dp))
}
Field(
stringResource(id = R.string.gls_context_exercise_title),
stringResource(
id = R.string.gls_context_exercise_field,
it.exerciseDuration,
it.exerciseIntensity
)
)
Spacer(modifier = Modifier.size(4.dp))
val medicationField = String.format(
stringResource(id = R.string.gls_context_medication_field),
it.medicationQuantity,
it.medicationUnit.toDisplayString(),
it.medication?.toDisplayString()
)
Field(
stringResource(id = R.string.gls_context_medication_title),
medicationField
)
Spacer(modifier = Modifier.size(4.dp))
Field(
stringResource(id = R.string.gls_context_hba1c_title),
stringResource(id = R.string.gls_context_hba1c_field, it.HbA1c)
)
Spacer(modifier = Modifier.size(4.dp))
} ?: Field(
stringResource(id = R.string.gls_context_title),
stringResource(id = R.string.gls_unavailable)
)
}
}
}
}
|
bsd-3-clause
|
7b0de95ea3198f5920ccb641224cae45
| 44.329167 | 100 | 0.515948 | 5.469583 | false | false | false | false |
alygin/intellij-rust
|
src/main/kotlin/org/rust/ide/annotator/RsLiteralAnnotator.kt
|
2
|
2734
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator
import com.intellij.lang.ASTNode
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.RsElementTypes.*
class RsLiteralAnnotator : Annotator {
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
if (element !is RsLitExpr) return
val literal = element.kind
// Check suffix
when (literal) {
is RsLiteralKind.Integer, is RsLiteralKind.Float, is RsLiteralKind.String, is RsLiteralKind.Char -> {
literal as RsLiteralWithSuffix
val suffix = literal.suffix
val validSuffixes = literal.validSuffixes
if (!suffix.isNullOrEmpty() && suffix !in validSuffixes) {
holder.createErrorAnnotation(element, if (validSuffixes.isNotEmpty()) {
val validSuffixesStr = validSuffixes.map { "'$it'" }.joinToString()
"invalid suffix '$suffix' for ${literal.node.displayName}; " +
"the suffix must be one of: $validSuffixesStr"
} else {
"${literal.node.displayName} with a suffix is invalid"
})
}
}
is RsLiteralKind.Boolean -> {
}
}
// Check char literal length
when (literal) {
is RsLiteralKind.Char -> {
val value = literal.value
when {
value == null || value.isEmpty() -> "empty ${literal.node.displayName}"
value.codePointCount(0, value.length) > 1 -> "too many characters in ${literal.node.displayName}"
else -> null
}?.let { holder.createErrorAnnotation(element, it) }
}
}
// Check delimiters
if (literal is RsTextLiteral && literal.hasUnpairedQuotes) {
holder.createErrorAnnotation(element, "unclosed ${literal.node.displayName}")
}
}
}
private val ASTNode.displayName: String
get() = when (elementType) {
INTEGER_LITERAL -> "integer literal"
FLOAT_LITERAL -> "float literal"
CHAR_LITERAL -> "char literal"
BYTE_LITERAL -> "byte literal"
STRING_LITERAL -> "string literal"
BYTE_STRING_LITERAL -> "byte string literal"
RAW_STRING_LITERAL -> "raw string literal"
RAW_BYTE_STRING_LITERAL -> "raw byte string literal"
else -> toString()
}
|
mit
|
67cfe7b3d6a0b62ac6443e3e38fdbf49
| 35.453333 | 117 | 0.583394 | 4.87344 | false | false | false | false |
Bodo1981/swapi.co
|
app/src/main/java/com/christianbahl/swapico/list/ListFragment.kt
|
1
|
3118
|
package com.christianbahl.swapico.list
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.christianbahl.appkit.viewstate.fragment.CBFragmentMvpListRecyclerViewViewState
import com.christianbahl.swapico.App
import com.christianbahl.swapico.base.loadmore.LoadMoreScrollListener
import com.christianbahl.swapico.details.DetailsActivity
import com.christianbahl.swapico.list.model.ListItem
import com.christianbahl.swapico.list.model.ListType
import com.hannesdorfmann.fragmentargs.FragmentArgs
import com.hannesdorfmann.fragmentargs.annotation.Arg
import com.hannesdorfmann.fragmentargs.annotation.FragmentWithArgs
import com.hannesdorfmann.mosby.mvp.viewstate.lce.LceViewState
import com.hannesdorfmann.mosby.mvp.viewstate.lce.data.RetainingLceViewState
/**
* @author Christian Bahl
*/
@FragmentWithArgs
class ListFragment : CBFragmentMvpListRecyclerViewViewState<ListItem, ListView, ListPresenter, ListAdapter>(), ListView {
lateinit private var loadMoreScrollListener: LoadMoreScrollListener
lateinit private var typeComponent: TypeComponent
private var listToRestore: MutableList<ListItem>? = null
private var hasNextPage: Boolean = false;
private var nextPage: Int = 1;
@Arg lateinit var listType: ListType
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
FragmentArgs.inject(this)
val app = activity.applicationContext as App
typeComponent = DaggerTypeComponent.builder()
.typeModule(TypeModule(listType))
.netComponent(app.netComponent()).build()
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
loadMoreScrollListener = LoadMoreScrollListener(contentView.layoutManager as LinearLayoutManager) {
if (hasNextPage) {
presenter.loadData(++nextPage, true)
}
}
contentView.addOnScrollListener(loadMoreScrollListener);
}
override fun createViewState(): LceViewState<MutableList<ListItem>, ListView>? = RetainingLceViewState()
override fun getData(): MutableList<ListItem>? = listToRestore
override fun createPresenter(): ListPresenter? = typeComponent.listPresenter()
override fun createAdapter(): ListAdapter? = ListAdapter(activity) {
startActivity(DetailsActivity.getStartIntent(activity, listType, it))
}
override fun loadData(pullToRefresh: Boolean) = presenter.loadData(nextPage, pullToRefresh)
override fun setData(data: MutableList<ListItem>?) {
val itemsAlreadyInListCount = adapter.itemCount
adapter.addNewDataList(data, itemsAlreadyInListCount > 0)
this.listToRestore = adapter.getItems() as MutableList<ListItem>
var newItemsCount = data?.size ?: 0
if (itemsAlreadyInListCount == 0) {
adapter.notifyDataSetChanged()
} else {
adapter.notifyItemRangeInserted(itemsAlreadyInListCount, newItemsCount)
}
loadMoreScrollListener.isLoading = false
}
override fun setHasNextPage(hasNextPage: Boolean) {
this.hasNextPage = hasNextPage
}
}
|
apache-2.0
|
7d66f19432276313512c2752293859e2
| 34.850575 | 121 | 0.788005 | 4.933544 | false | false | false | false |
alashow/music-android
|
modules/core-downloader/src/main/java/tm/alashow/datmusic/downloader/AudioExtensions.kt
|
1
|
3353
|
/*
* Copyright (C) 2021, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.datmusic.downloader
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.media.MediaExtractor
import android.media.MediaMetadataRetriever
import android.os.Build
import androidx.documentfile.provider.DocumentFile
import java.io.FileNotFoundException
import timber.log.Timber
import tm.alashow.datmusic.domain.DownloadsSongsGrouping
import tm.alashow.datmusic.domain.entities.Audio
import tm.alashow.datmusic.domain.entities.AudioDownloadItem
import tm.alashow.datmusic.domain.entities.AudioHeader
val filenameIllegalChars = setOf('|', '/', '\\', '?', '*', '<', '>', '"', ':')
private fun String.cleanIllegalChars(chars: Set<Char> = filenameIllegalChars, replacement: Char = '_') =
map { if (it in chars) replacement else it }.joinToString("")
fun DocumentFile.getOrCreateDir(name: String) = findFile(name.cleanIllegalChars())
?: createDirectory(name.cleanIllegalChars())
?: error("Couldn't create folder:$name")
private fun Audio.createDocumentFile(parent: DocumentFile) = parent.createFile(fileMimeType(), fileDisplayName().cleanIllegalChars())
?: error("Couldn't create document file")
fun Audio.documentFile(parent: DocumentFile, songsGrouping: DownloadsSongsGrouping): DocumentFile {
if (!parent.exists())
throw FileNotFoundException("Parent folder doesn't exist")
return when (songsGrouping) {
DownloadsSongsGrouping.Flat -> createDocumentFile(parent)
DownloadsSongsGrouping.ByArtist -> {
val mainArtist = mainArtist()
val artistFolder = parent.getOrCreateDir(mainArtist)
createDocumentFile(artistFolder)
}
DownloadsSongsGrouping.ByAlbum -> {
val mainArtist = mainArtist()
val artistFolder = parent.getOrCreateDir(mainArtist)
val albumName = album ?: ""
when (albumName.isBlank()) {
true -> createDocumentFile(artistFolder)
else -> {
val albumFolder = artistFolder.getOrCreateDir(albumName)
createDocumentFile(albumFolder)
}
}
}
}
}
fun Audio.artworkFromFile(context: Context): Bitmap? {
try {
val downloadInfo = audioDownloadItem?.downloadInfo ?: return null
val metadataRetriever = MediaMetadataRetriever()
metadataRetriever.setDataSource(context, downloadInfo.fileUri)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
try {
return metadataRetriever.primaryImage
} catch (e: Exception) {
Timber.e(e)
}
}
val data = metadataRetriever.embeddedPicture
if (data != null) {
return BitmapFactory.decodeByteArray(data, 0, data.size)
}
return null
} catch (e: Exception) {
Timber.e(e)
}
return null
}
fun AudioDownloadItem.audioHeader(context: Context): AudioHeader {
try {
val mediaExtractor = MediaExtractor()
mediaExtractor.setDataSource(context, downloadInfo.fileUri, null)
return AudioHeader.from(this, mediaExtractor.getTrackFormat(0))
} catch (e: Exception) {
Timber.e(e)
}
return AudioHeader()
}
|
apache-2.0
|
f0b379a7530a1994c76cacb42e72ed3a
| 35.445652 | 133 | 0.672234 | 4.663421 | false | false | false | false |
ankidroid/Anki-Android
|
AnkiDroid/src/main/java/com/ichi2/anki/Info.kt
|
1
|
7122
|
/***************************************************************************************
* Copyright (c) 2009 Nicolas Raoul <[email protected]> *
* Copyright (c) 2009 Edu Zamora <[email protected]> *
* Copyright (c) 2015 Tim Rae <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki
import android.annotation.SuppressLint
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
import androidx.appcompat.widget.ThemeUtils
import com.ichi2.anim.ActivityTransitionAnimation
import com.ichi2.utils.IntentUtil.canOpenIntent
import com.ichi2.utils.IntentUtil.tryOpenIntent
import com.ichi2.utils.VersionUtils.appName
import com.ichi2.utils.VersionUtils.pkgVersionName
import com.ichi2.utils.ViewGroupUtils.setRenderWorkaround
import timber.log.Timber
/**
* Shows an about box, which is a small HTML page.
*/
class Info : AnkiActivity() {
private var mWebView: WebView? = null
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
if (showedActivityFailedScreen(savedInstanceState)) {
return
}
Timber.d("onCreate()")
super.onCreate(savedInstanceState)
val res = resources
val type = intent.getIntExtra(TYPE_EXTRA, TYPE_NEW_VERSION)
// If the page crashes, we do not want to display it again (#7135 maybe)
if (type == TYPE_NEW_VERSION) {
val prefs = AnkiDroidApp.getSharedPrefs(this.baseContext)
InitialActivity.setUpgradedToLatestVersion(prefs)
}
setContentView(R.layout.info)
val mainView = findViewById<View>(android.R.id.content)
enableToolbar(mainView)
findViewById<View>(R.id.info_donate).setOnClickListener { openUrl(Uri.parse(getString(R.string.link_opencollective_donate))) }
title = "$appName v$pkgVersionName"
mWebView = findViewById(R.id.info)
mWebView!!.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView, progress: Int) {
// Hide the progress indicator when the page has finished loaded
if (progress == 100) {
mainView.findViewById<View>(R.id.progress_bar).visibility = View.GONE
}
}
}
findViewById<Button>(R.id.left_button).run {
if (canOpenMarketUri()) {
setText(R.string.info_rate)
setOnClickListener {
tryOpenIntent(
this@Info,
AnkiDroidApp.getMarketIntent(this@Info)
)
}
} else {
visibility = View.GONE
}
}
// Apply Theme colors
val typedArray = theme.obtainStyledAttributes(intArrayOf(android.R.attr.colorBackground, android.R.attr.textColor))
val backgroundColor = typedArray.getColor(0, -1)
val textColor = String.format("#%06X", 0xFFFFFF and typedArray.getColor(1, -1)) // Color to hex string
val anchorTextThemeColor = ThemeUtils.getThemeAttrColor(this, R.attr.colorAccent)
val anchorTextColor = String.format("#%06X", 0xFFFFFF and anchorTextThemeColor)
mWebView!!.setBackgroundColor(backgroundColor)
setRenderWorkaround(this)
when (type) {
TYPE_NEW_VERSION -> {
findViewById<Button>(R.id.right_button).run {
text = res.getString(R.string.dialog_continue)
setOnClickListener { close() }
}
val background = String.format("#%06X", 0xFFFFFF and backgroundColor)
mWebView!!.loadUrl("file:///android_asset/changelog.html")
mWebView!!.settings.javaScriptEnabled = true
mWebView!!.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
/* The order of below javascript code must not change (this order works both in debug and release mode)
* or else it will break in any one mode.
*/
mWebView!!.loadUrl(
"javascript:document.body.style.setProperty(\"color\", \"" + textColor + "\");" +
"x=document.getElementsByTagName(\"a\"); for(i=0;i<x.length;i++){x[i].style.color=\"" + anchorTextColor + "\";}" +
"document.getElementsByTagName(\"h1\")[0].style.color=\"" + textColor + "\";" +
"x=document.getElementsByTagName(\"h2\"); for(i=0;i<x.length;i++){x[i].style.color=\"#E37068\";}" +
"document.body.style.setProperty(\"background\", \"" + background + "\");"
)
}
}
}
else -> finishWithoutAnimation()
}
}
private fun close() {
setResult(RESULT_OK)
finishWithAnimation()
}
private fun canOpenMarketUri(): Boolean {
return try {
canOpenIntent(this, AnkiDroidApp.getMarketIntent(this))
} catch (e: Exception) {
Timber.w(e)
false
}
}
private fun finishWithAnimation() {
finishWithAnimation(ActivityTransitionAnimation.Direction.START)
}
@Suppress("deprecation") // onBackPressed
override fun onBackPressed() {
if (mWebView!!.canGoBack()) {
mWebView!!.goBack()
} else {
super.onBackPressed()
}
}
companion object {
const val TYPE_EXTRA = "infoType"
const val TYPE_NEW_VERSION = 2
}
}
|
gpl-3.0
|
6267f1b076df704073e905f910adf3d5
| 44.948387 | 146 | 0.549986 | 5.036775 | false | false | false | false |
akvo/akvo-flow-mobile
|
app/src/main/java/org/akvo/flow/tracking/TrackingHelper.kt
|
1
|
5044
|
/*
* Copyright (C) 2019 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.tracking
import android.content.Context
import android.os.Bundle
import com.google.firebase.analytics.FirebaseAnalytics
import org.akvo.flow.domain.util.ImageSize
class TrackingHelper(context: Context) {
private val firebaseAnalytics: FirebaseAnalytics = FirebaseAnalytics.getInstance(context)
fun logStatsEvent(tabName: String?) {
val params = Bundle()
params.putString("from_tab", tabName)
firebaseAnalytics.logEvent("menu_stats_pressed", params)
}
fun logSortEvent() {
firebaseAnalytics.logEvent("list_menu_sort_pressed", null)
}
fun logDownloadEvent(tabName: String?) {
val params = Bundle()
params.putString("from_tab", tabName)
firebaseAnalytics.logEvent("menu_download_pressed", params)
}
fun logUploadEvent(tabName: String?) {
val params = Bundle()
params.putString("from_tab", tabName)
firebaseAnalytics.logEvent("menu_upload_pressed", params)
}
fun logSortEventChosen(orderSuffix: String) {
firebaseAnalytics.logEvent("sort_by_$orderSuffix", null)
}
fun logSearchEvent() {
firebaseAnalytics.logEvent("list_search_pressed", null)
}
fun logUploadDataEvent() {
firebaseAnalytics.logEvent("setting_send_datapoints_pressed", null)
}
fun logGpsFixesEvent() {
firebaseAnalytics.logEvent("setting_gps_fix_pressed", null)
}
fun logStorageEvent() {
firebaseAnalytics.logEvent("setting_storage_pressed", null)
}
fun logMobileDataChanged(checked: Boolean) {
val params = Bundle()
params.putBoolean("status", checked)
firebaseAnalytics.logEvent("setting_mobile_data_changed", params)
}
fun logScreenOnChanged(checked: Boolean) {
val params = Bundle()
params.putBoolean("status", checked)
firebaseAnalytics.logEvent("setting_screen_on_changed", params)
}
fun logImageSizeChanged(imageSize: Int) {
val size = when (imageSize) {
ImageSize.IMAGE_SIZE_320_240 -> "small"
ImageSize.IMAGE_SIZE_640_480 -> "medium"
ImageSize.IMAGE_SIZE_1280_960 -> "large"
else -> ""
}
val params = Bundle()
params.putString("image_size", size)
firebaseAnalytics.logEvent("setting_image_size_changed", params)
}
fun logPublishPressed() {
firebaseAnalytics.logEvent("setting_publish_data_pressed", null)
}
fun logDeleteDataPressed() {
firebaseAnalytics.logEvent("setting_delete_data_pressed", null)
}
fun logDeleteAllPressed() {
firebaseAnalytics.logEvent("setting_delete_all_pressed", null)
}
fun logDownloadFormPressed() {
firebaseAnalytics.logEvent("setting_download_form_pressed", null)
}
fun logDownloadFormsPressed() {
firebaseAnalytics.logEvent("setting_download_forms_pressed", null)
}
fun logDeleteDataConfirmed() {
firebaseAnalytics.logEvent("setting_delete_data_confirmed", null)
}
fun logDeleteAllConfirmed() {
firebaseAnalytics.logEvent("setting_delete_all_confirmed", null)
}
fun logDownloadFormConfirmed(formId: String?) {
val params = Bundle()
params.putString("form_id", formId)
firebaseAnalytics.logEvent("setting_download_form_confirmed", params)
}
fun logDownloadFormsConfirmed() {
firebaseAnalytics.logEvent("setting_download_forms_confirmed", null)
}
fun logCheckUpdatePressed() {
firebaseAnalytics.logEvent("about_check_update_pressed", null)
}
fun logViewNotesPressed() {
firebaseAnalytics.logEvent("about_view_notes_pressed", null)
}
fun logViewLegalPressed() {
firebaseAnalytics.logEvent("about_view_legal_pressed", null)
}
fun logViewTermsPressed() {
firebaseAnalytics.logEvent("about_view_terms_pressed", null)
}
fun logFormSubmissionRepeatConfirmationDialogEvent() {
firebaseAnalytics.logEvent("monitoring_form_repeat_dialog_shown", null)
}
fun logHistoryTabViewed() {
firebaseAnalytics.logEvent("history_tab_viewed", null)
}
fun logFormVersionUpdated() {
firebaseAnalytics.logEvent("draft_form_version_updated", null)
}
}
|
gpl-3.0
|
2809fbc7995ca2dd301032d51798bdac
| 30.329193 | 93 | 0.680214 | 4.424561 | false | false | false | false |
pdvrieze/ProcessManager
|
darwin/ktorSupport/src/main/kotlin/io/github/pdvrieze/darwin/ktor/support/ktoraccess.kt
|
1
|
4048
|
/*
* Copyright (c) 2021.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package io.github.pdvrieze.darwin.ktor.support
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.http.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.util.pipeline.*
import kotlinx.coroutines.runBlocking
import kotlinx.html.HtmlBlockTag
import uk.ac.bournemouth.darwin.html.RequestInfo
import uk.ac.bournemouth.darwin.html.RequestServiceContext
import uk.ac.bournemouth.darwin.html.ResponseContext
import uk.ac.bournemouth.darwin.html.darwinResponse
import uk.ac.bournemouth.darwin.sharedhtml.ContextTagConsumer
import uk.ac.bournemouth.darwin.sharedhtml.ServiceContext
import java.io.CharArrayWriter
import java.io.Writer
import java.security.Principal
public suspend fun PipelineContext<*, ApplicationCall>.darwinResponse(
windowTitle: String = "Darwin",
pageTitle: String? = null,
includeLogin: Boolean = true,
context: ServiceContext,
bodyContent: ContextTagConsumer<HtmlBlockTag>.() -> Unit
) {
val resp = KtorResponseContext(call)
val req = KtorServletRequestInfo(call)
return resp.darwinResponse(req, windowTitle, pageTitle, includeLogin, context, bodyContent)
}
public suspend fun PipelineContext<*, ApplicationCall>.darwinResponse(windowTitle: String = "Darwin",
pageTitle: String? = null,
includeLogin: Boolean = true,
bodyContent: ContextTagConsumer<HtmlBlockTag>.() -> Unit) {
val resp = KtorResponseContext(call)
val req = KtorServletRequestInfo(call)
val context = RequestServiceContext(req)
return resp.darwinResponse(req, windowTitle, pageTitle, includeLogin, context, bodyContent)
}
public class KtorResponseContext(private val call: ApplicationCall): ResponseContext {
private var pendingContentType: ContentType = ContentType.parse("text/plain")
private var pendingCode: HttpStatusCode = HttpStatusCode.OK
override fun contentType(type: String) {
pendingContentType = ContentType.parse(type)
// call.response.header("Content-Type", type)
}
override fun setStatus(code: Int) {
pendingCode = HttpStatusCode.fromValue(code)
// call.response.status(HttpStatusCode.fromValue(code))
}
override fun respondWriter(body: (Writer) -> Unit) {
val caw = CharArrayWriter().apply { use { body(it) } }
runBlocking {
call.respondTextWriter(pendingContentType, pendingCode) { caw.writeTo(this) }
}
}
}
public class KtorServletRequestInfo(private val call: ApplicationCall): RequestInfo {
override fun getHeader(name: String): String? {
return call.request.header(name)
}
override fun isUserInRole(role: String): Boolean {
return false // TODO use more extensive authentication
}
public val ktorPrincipal: UserIdPrincipal? get() {
return call.principal()
}
override val userPrincipal: Principal?
get() = ktorPrincipal?.let(::KtorPrincipal)
override val contextPath: String
get() = call.application.environment.rootPath
}
internal class KtorPrincipal(private val ktorPrincipal: UserIdPrincipal): Principal {
override fun getName(): String {
return ktorPrincipal.name
}
}
|
lgpl-3.0
|
7438a5217fb68cc98a42c95acdf05498
| 36.831776 | 129 | 0.703804 | 4.642202 | false | false | false | false |
FrogCraft-Rebirth/LaboratoriumChemiae
|
src/main/kotlin/info/tritusk/laboratoriumchemiae/library/network/NetworkChemiae.kt
|
1
|
2988
|
package info.tritusk.laboratoriumchemiae.library.network
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.DataOutputStream
import io.netty.buffer.ByteBufInputStream
import io.netty.buffer.Unpooled
import net.minecraft.client.Minecraft
import net.minecraft.client.entity.EntityPlayerSP
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.entity.player.EntityPlayerMP
import net.minecraft.network.PacketBuffer
import net.minecraft.network.NetHandlerPlayServer
import net.minecraft.util.math.BlockPos
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
import net.minecraftforge.fml.common.network.FMLEventChannel
import net.minecraftforge.fml.common.network.FMLNetworkEvent
import net.minecraftforge.fml.common.network.NetworkRegistry
import net.minecraftforge.fml.common.network.internal.FMLProxyPacket
object NetworkHandler {
const val CHANNEL_NAME = "LabChm"
private val channel: FMLEventChannel = NetworkRegistry.INSTANCE.newEventDrivenChannel(CHANNEL_NAME).also { it.register(this) }
@SubscribeEvent fun onClientPacket(packet: FMLNetworkEvent.ClientCustomPacketEvent) = resolveClientPacket(
DataInputStream(ByteBufInputStream(packet.packet.payload())),
Minecraft.getMinecraft().player
)
@SubscribeEvent fun onServerPacket(packet: FMLNetworkEvent.ServerCustomPacketEvent) = resolveServerPacket(
DataInputStream(ByteBufInputStream(packet.packet.payload())),
(packet.handler as NetHandlerPlayServer).player
)
fun sendPacketToDim(pkt: PacketChemiae, dim: Int) = channel.sendToDimension(pkt.encapsulate(), dim)
fun sendPacketAroundPos(pkt: PacketChemiae, dim: Int, pos: BlockPos, range: Double = 2.0) = channel.sendToAllAround(
pkt.encapsulate(),
NetworkRegistry.TargetPoint(dim, pos.x.toDouble(), pos.y.toDouble(), pos.z.toDouble(), range))
fun sendPacketToPlayer(pkt: PacketChemiae, player: EntityPlayerMP) = channel.sendTo(pkt.encapsulate(), player)
fun sendPacketToAll(pkt: PacketChemiae) = channel.sendToAll(pkt.encapsulate())
fun sendPacketToServer(pkt: PacketChemiae) = channel.sendToServer(pkt.encapsulate())
private fun resolveClientPacket(stream: DataInputStream, player: EntityPlayerSP) {
player.activeHand
when (stream.readByte()) {
}
}
private fun resolveServerPacket(stream: DataInputStream, player: EntityPlayerMP) {
player.activeHand
when (stream.readByte()) {
}
}
}
interface PacketChemiae {
fun writeData(stream: DataOutputStream)
fun readData(stream: DataInputStream, player: EntityPlayer)
}
internal fun PacketChemiae.encapsulate(): FMLProxyPacket = FMLProxyPacket(
PacketBuffer(Unpooled.wrappedBuffer(ByteArrayOutputStream().also {
DataOutputStream(it).use { this.writeData(it) }
}.toByteArray())), NetworkHandler.CHANNEL_NAME)
|
mit
|
6b632b2dcb0e7636c6973041b795dd46
| 39.945205 | 130 | 0.755355 | 4.387665 | false | false | false | false |
ccomeaux/boardgamegeek4android
|
app/src/main/java/com/boardgamegeek/ui/ForumsFragment.kt
|
1
|
5443
|
package com.boardgamegeek.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.DividerItemDecoration
import com.boardgamegeek.R
import com.boardgamegeek.databinding.FragmentForumsBinding
import com.boardgamegeek.entities.ForumEntity
import com.boardgamegeek.entities.Status
import com.boardgamegeek.provider.BggContract
import com.boardgamegeek.ui.adapter.ForumsRecyclerViewAdapter
import com.boardgamegeek.ui.viewmodel.ForumsViewModel
class ForumsFragment : Fragment() {
private var _binding: FragmentForumsBinding? = null
private val binding get() = _binding!!
private var forumType = ForumEntity.ForumType.REGION
private var objectId = BggContract.INVALID_ID
private var objectName = ""
private val recyclerViewAdapter: ForumsRecyclerViewAdapter by lazy {
ForumsRecyclerViewAdapter(objectId, objectName, forumType)
}
private val viewModel by activityViewModels<ForumsViewModel>()
@Suppress("RedundantNullableReturnType")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentForumsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.let {
forumType = it.getSerializable(KEY_TYPE) as? ForumEntity.ForumType? ?: ForumEntity.ForumType.REGION
objectId = it.getInt(KEY_OBJECT_ID, BggContract.INVALID_ID)
objectName = it.getString(KEY_OBJECT_NAME).orEmpty()
}
binding.recyclerView.apply {
setHasFixedSize(true)
addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
adapter = recyclerViewAdapter
if (forumType == ForumEntity.ForumType.REGION) setPadding(paddingLeft, 0, paddingRight, paddingBottom)
}
when (forumType) {
ForumEntity.ForumType.GAME -> viewModel.setGameId(objectId)
ForumEntity.ForumType.REGION -> viewModel.setRegion()
ForumEntity.ForumType.ARTIST,
ForumEntity.ForumType.DESIGNER -> viewModel.setPersonId(objectId)
ForumEntity.ForumType.PUBLISHER -> viewModel.setCompanyId(objectId)
}
viewModel.forums.observe(viewLifecycleOwner) {
it?.let {
when (it.status) {
Status.REFRESHING -> binding.progressView.show()
Status.ERROR -> {
binding.emptyView.text = it.message
binding.emptyView.isVisible = true
binding.recyclerView.isVisible = false
binding.progressView.hide()
}
Status.SUCCESS -> {
recyclerViewAdapter.forums = it.data.orEmpty()
binding.emptyView.setText(R.string.empty_forums)
binding.emptyView.isVisible = recyclerViewAdapter.itemCount == 0
binding.recyclerView.isVisible = recyclerViewAdapter.itemCount > 0
binding.progressView.hide()
}
}
}
}
}
companion object {
private const val KEY_TYPE = "TYPE"
private const val KEY_OBJECT_ID = "ID"
private const val KEY_OBJECT_NAME = "NAME"
fun newInstance(): ForumsFragment {
return ForumsFragment().apply {
arguments = bundleOf(
KEY_TYPE to ForumEntity.ForumType.REGION,
KEY_OBJECT_ID to BggContract.INVALID_ID,
KEY_OBJECT_NAME to "",
)
}
}
fun newInstanceForGame(id: Int, name: String): ForumsFragment {
return ForumsFragment().apply {
arguments = bundleOf(
KEY_TYPE to ForumEntity.ForumType.GAME,
KEY_OBJECT_ID to id,
KEY_OBJECT_NAME to name,
)
}
}
fun newInstanceForArtist(id: Int, name: String): ForumsFragment {
return ForumsFragment().apply {
arguments = bundleOf(
KEY_TYPE to ForumEntity.ForumType.ARTIST,
KEY_OBJECT_ID to id,
KEY_OBJECT_NAME to name,
)
}
}
fun newInstanceForDesigner(id: Int, name: String): ForumsFragment {
return ForumsFragment().apply {
arguments = bundleOf(
KEY_TYPE to ForumEntity.ForumType.DESIGNER,
KEY_OBJECT_ID to id,
KEY_OBJECT_NAME to name,
)
}
}
fun newInstanceForPublisher(id: Int, name: String): ForumsFragment {
return ForumsFragment().apply {
arguments = bundleOf(
KEY_TYPE to ForumEntity.ForumType.PUBLISHER,
KEY_OBJECT_ID to id,
KEY_OBJECT_NAME to name,
)
}
}
}
}
|
gpl-3.0
|
c717b35f2f8a945c1e94881da7477519
| 38.442029 | 116 | 0.603711 | 5.373149 | false | false | false | false |
Nearsoft/nearbooks-android
|
app/src/main/java/com/nearsoft/nearbooks/models/view/User.kt
|
2
|
2694
|
package com.nearsoft.nearbooks.models.view
import android.databinding.BaseObservable
import android.databinding.Bindable
import android.os.Parcel
import android.os.Parcelable
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.nearsoft.nearbooks.BR
/**
* User view model.
* Created by epool on 5/1/16.
*/
class User : BaseObservable, Parcelable {
companion object {
@JvmField val CREATOR: Parcelable.Creator<User> = object : Parcelable.Creator<User> {
override fun createFromParcel(source: Parcel): User {
return User(source)
}
override fun newArray(size: Int): Array<User?> {
return arrayOfNulls(size)
}
}
}
var id: String? = null
@Bindable get() = field
set(id) {
field = id
notifyPropertyChanged(BR.id)
}
var displayName: String? = null
@Bindable get() = field
set(displayName) {
field = displayName
notifyPropertyChanged(BR.displayName)
}
var email: String? = null
@Bindable get() = field
set(email) {
field = email
notifyPropertyChanged(BR.email)
}
var photoUrl: String? = null
@Bindable get() = field
set(photoUrl) {
field = photoUrl
notifyPropertyChanged(BR.photoUrl)
}
var idToken: String? = null
@Bindable get() = field
set(idToken) {
field = idToken
notifyPropertyChanged(BR.idToken)
}
constructor() {
}
constructor(googleSignInAccount: GoogleSignInAccount) {
id = googleSignInAccount.id
displayName = googleSignInAccount.displayName
email = googleSignInAccount.email
idToken = googleSignInAccount.idToken
photoUrl = googleSignInAccount.photoUrl?.toString()
}
constructor(user: com.nearsoft.nearbooks.models.realm.User) {
id = user.id
displayName = user.displayName
email = user.email
photoUrl = user.photoUrl
idToken = user.idToken
}
protected constructor(parcel: Parcel) {
id = parcel.readString()
displayName = parcel.readString()
email = parcel.readString()
photoUrl = parcel.readString()
idToken = parcel.readString()
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(id)
dest.writeString(displayName)
dest.writeString(email)
dest.writeString(photoUrl)
dest.writeString(idToken)
}
}
|
mit
|
e94dfa319496252dda61b32d81f61338
| 25.94 | 93 | 0.605048 | 4.810714 | false | false | false | false |
sabi0/intellij-community
|
plugins/github/src/org/jetbrains/plugins/github/util/GithubAccountsMigrationHelper.kt
|
1
|
5652
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.util
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ThrowableComputable
import git4idea.DialogManager
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubApiRequests
import org.jetbrains.plugins.github.api.GithubApiUtil
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.accounts.GithubAccountManager
import org.jetbrains.plugins.github.authentication.ui.GithubLoginDialog
import java.io.IOException
internal const val GITHUB_SETTINGS_PASSWORD_KEY = "GITHUB_SETTINGS_PASSWORD_KEY"
/**
* Temporary helper
* Will move single-account authorization data to accounts list if it was a token-based auth and clear old settings
*/
@Suppress("DEPRECATION")
class GithubAccountsMigrationHelper internal constructor(private val settings: GithubSettings,
private val passwordSafe: PasswordSafe,
private val accountManager: GithubAccountManager,
private val executorFactory: GithubApiRequestExecutor.Factory) {
private val LOG = logger<GithubAccountsMigrationHelper>()
internal fun getOldServer(): GithubServerPath? {
try {
if (hasOldAccount()) {
return GithubServerPath.from(settings.host ?: GithubServerPath.DEFAULT_HOST)
}
}
catch (ignore: Exception) {
// it could be called from AnAction.update()
}
return null
}
private fun hasOldAccount(): Boolean {
// either password-based with specified login or token based
return ((settings.authType == GithubAuthData.AuthType.BASIC && settings.login != null) ||
(settings.authType == GithubAuthData.AuthType.TOKEN))
}
/**
* @return false if process was cancelled by user, true otherwise
*/
@CalledInAwt
fun migrate(project: Project): Boolean {
LOG.debug("Migrating old auth")
val login = settings.login
val host = settings.host
val password = passwordSafe.getPassword(GithubSettings::class.java, GITHUB_SETTINGS_PASSWORD_KEY)
val authType = settings.authType
LOG.debug("Old auth data: { login: $login, host: $host, authType: $authType, password null: ${password == null} }")
val hasAnyInfo = login != null || host != null || authType != null || password != null
if (!hasAnyInfo) return true
var dialogCancelled = false
if (accountManager.accounts.isEmpty()) {
val hostToUse = host ?: GithubServerPath.DEFAULT_HOST
when (authType) {
GithubAuthData.AuthType.TOKEN -> {
LOG.debug("Migrating token auth")
if (password != null) {
try {
val server = GithubServerPath.from(hostToUse)
val progressManager = ProgressManager.getInstance()
val accountName = progressManager.runProcessWithProgressSynchronously(ThrowableComputable<String, IOException> {
executorFactory.create(password).execute(progressManager.progressIndicator,
GithubApiRequests.CurrentUser.get(server)).login
}, "Accessing Github", true, project)
val account = GithubAccountManager.createAccount(accountName, server)
registerAccount(account, password)
}
catch (e: Exception) {
LOG.debug("Failed to migrate old token-based auth. Showing dialog.", e)
val dialog = GithubLoginDialog(executorFactory, project).withServer(hostToUse, false).withToken(password).withError(e)
dialogCancelled = !registerFromDialog(dialog)
}
}
}
GithubAuthData.AuthType.BASIC -> {
LOG.debug("Migrating basic auth")
val dialog = GithubLoginDialog(executorFactory, project,
message = "Password authentication is no longer supported for Github.\n" +
"Personal access token can be acquired instead.")
.withServer(hostToUse, false).withCredentials(login, password)
dialogCancelled = !registerFromDialog(dialog)
}
else -> {
}
}
}
if (!dialogCancelled) clearOldAuth()
return !dialogCancelled
}
private fun registerFromDialog(dialog: GithubLoginDialog): Boolean {
DialogManager.show(dialog)
return if (dialog.isOK) {
registerAccount(GithubAccountManager.createAccount(dialog.getLogin(), dialog.getServer()), dialog.getToken())
true
}
else false
}
private fun registerAccount(account: GithubAccount, token: String) {
accountManager.accounts += account
accountManager.updateAccountToken(account, token)
LOG.debug("Registered account $account")
}
private fun clearOldAuth() {
settings.clearAuth()
passwordSafe.setPassword(GithubSettings::class.java, GITHUB_SETTINGS_PASSWORD_KEY, null)
}
companion object {
@JvmStatic
fun getInstance(): GithubAccountsMigrationHelper = service()
}
}
|
apache-2.0
|
edfd8e102727a3e4acce060757ab405b
| 41.818182 | 140 | 0.679582 | 5.0062 | false | false | false | false |
davidwhitman/changelogs
|
app/src/main/java/com/thunderclouddev/changelogs/ui/onboarding/AuthActivity.kt
|
1
|
6298
|
/*
* Copyright (c) 2017.
* Distributed under the GNU GPLv3 by David Whitman.
* https://www.gnu.org/licenses/gpl-3.0.en.html
*
* This source code is made available to help others learn. Please don't clone my app.
*/
package com.thunderclouddev.changelogs.ui.onboarding
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.thunderclouddev.changelogs.BaseApp
import com.thunderclouddev.changelogs.R
import com.thunderclouddev.changelogs.ResourceWrapper
import com.thunderclouddev.changelogs.auth.AuthTokenProvider
import com.thunderclouddev.changelogs.databinding.IntroViewBinding
import com.thunderclouddev.playstoreapi.AuthenticationProvider
import com.thunderclouddev.playstoreapi.PlayApiClientWrapper
import com.thunderclouddev.playstoreapi.legacyMarketApi.LegacyApiClientWrapper
import io.reactivex.Completable
import timber.log.Timber
import javax.inject.Inject
/**
* Displays information to the user on why we are going to request auth tokens,
* and then requests any tokens that are needed (as specified by `fdfeAuthState` and `legacyAuthState`).
* TODO: Too much state in here.
* @author David Whitman on 29 Mar, 2017.
*/
class AuthActivity : AppCompatActivity() {
companion object {
val RESULT_SUCCESS = 0
val RESULT_ERROR = 1
private var fdfeAuthState = AuthState.NothingNeeded
private var legacyAuthState = AuthState.NothingNeeded
fun promptUserForFdfeToken(context: Context) {
if (fdfeAuthState == AuthState.NothingNeeded) {
fdfeAuthState = AuthState.Requested
// Only launch new activity if we're not current waiting on a legacy auth token prompt
// Don't wanna end up with the activity twice
if (legacyAuthState == AuthState.NothingNeeded) {
context.startActivity(Intent(context, AuthActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) })
}
}
}
fun promptUserForLegacyToken(context: Context) {
if (legacyAuthState == AuthState.NothingNeeded) {
legacyAuthState = AuthState.Requested
// Only launch new activity if we're not current waiting on a fdfe auth token prompt
// Don't wanna end up with the activity twice
if (fdfeAuthState == AuthState.NothingNeeded) {
context.startActivity(Intent(context, AuthActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) })
}
}
}
private enum class AuthState {
Requested,
InProgress,
NothingNeeded
}
}
@Inject lateinit var authTokenProvider: AuthTokenProvider
@Inject lateinit var playApiClientWrapper: PlayApiClientWrapper
@Inject lateinit var legacyApiClientWrapper: LegacyApiClientWrapper
private lateinit var model: IntroViewModel
private var authSucceeded = false
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
authTokenProvider.onActivityResult(requestCode, resultCode, data)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
BaseApp.appInjector.inject(this)
model = IntroViewModel(ResourceWrapper(this@AuthActivity))
model.nextButtonClicks
.subscribe {
var createClientChain = Completable.complete()
if (fdfeAuthState == AuthState.Requested) {
createClientChain = createClientChain
.doOnComplete { fdfeAuthState = AuthState.InProgress }
.andThen(createPlayApiClient(this))
.doOnError { fdfeAuthState = AuthState.Requested }
.doOnComplete { fdfeAuthState = AuthState.NothingNeeded }
}
if (legacyAuthState == AuthState.Requested) {
createClientChain = createClientChain
.doOnComplete { legacyAuthState = AuthState.InProgress }
.andThen(createMarketApiClient(this))
.doOnError { legacyAuthState = AuthState.Requested }
.doOnComplete { legacyAuthState = AuthState.NothingNeeded }
}
createClientChain
.subscribe({
setResult(RESULT_SUCCESS)
authSucceeded = true
finish()
}, { error ->
Timber.e(error)
Toast.makeText(this, error.message, Toast.LENGTH_LONG).show()
})
}
setContentView(DataBindingUtil.inflate<IntroViewBinding>(layoutInflater, R.layout.intro_view, null, false)
.apply { this.model = [email protected] }
.root)
}
override fun onDestroy() {
if (!authSucceeded) {
playApiClientWrapper.notifyAuthCanceled()
legacyApiClientWrapper.notifyAuthCanceled()
}
fdfeAuthState = AuthState.NothingNeeded
legacyAuthState = AuthState.NothingNeeded
super.onDestroy()
}
private fun createPlayApiClient(activity: Activity) =
playApiClientWrapper.build(object : AuthenticationProvider {
override fun getUserAuthToken() =
authTokenProvider.getAuthToken(activity, AuthTokenProvider.TOKEN_TYPE.TOKEN_TYPE_FDFE)
})
private fun createMarketApiClient(activity: Activity) =
legacyApiClientWrapper.build(object : AuthenticationProvider {
override fun getUserAuthToken() =
authTokenProvider.getAuthToken(activity, AuthTokenProvider.TOKEN_TYPE.TOKEN_TYPE_OLD_MARKET)
})
}
|
gpl-3.0
|
513565fb944eab8478b969abb76b4041
| 41.560811 | 134 | 0.631153 | 5.448097 | false | false | false | false |
andreyfomenkov/green-cat
|
plugin/src/ru/fomenkov/plugin/task/compile/CompileTask.kt
|
1
|
13629
|
package ru.fomenkov.plugin.task.compile
import ru.fomenkov.plugin.task.Task
import ru.fomenkov.plugin.task.resolve.ProjectResolverOutput
import ru.fomenkov.plugin.util.*
import ru.fomenkov.runner.*
import java.io.File
import java.util.concurrent.*
class CompileTask(
private val greencatRoot: String,
private val androidSdkRoot: String,
private val deviceApiLevel: String,
private val mappedModules: Map<String, String>,
private val projectInfo: ProjectResolverOutput,
private val executor: ExecutorService,
private val showErrorLogs: Boolean,
) : Task<Unit> {
// For debugging purposes. Find all source files in the module and compile one by one
private val debugCompileModule = false
private val debugModuleName = ""
override fun run() {
clearDirectory(CLASS_FILES_DIR)
clearDirectory(DEX_FILES_DIR)
val orderMap = mutableMapOf<Int, MutableSet<String>>()
projectInfo.moduleCompilationOrderMap.forEach { (moduleName: String, order: Int) ->
val modules = orderMap[order] ?: mutableSetOf()
modules += moduleName
orderMap[order] = modules
}
orderMap.keys.sorted().forEach { order ->
val modules = checkNotNull(orderMap[order]) {
"No modules for compilation order $order"
}
if (debugCompileModule) {
compileModuleForDebug(debugModuleName)
} else {
Telemetry.log("Compilation round ${order + 1}/${orderMap.size}: ${modules.joinToString(separator = ", ")}")
val tasks = modules.map { moduleName -> compile(moduleName) }
tasks.forEach { task ->
val result = task.get()
if (result is CompilationResult.Error) {
if (showErrorLogs) {
result.output.forEach { line -> Telemetry.err(line) }
}
deleteClasspathForModule(result.moduleName)
error("Failed to compile module ${result.moduleName}")
}
}
}
}
if (!debugCompileModule) {
runD8()
}
}
private fun compileModuleForDebug(moduleName: String) {
var moduleClasspathFile = File("$greencatRoot/$CLASSPATH_DIR/$moduleName")
val modulePath = "$CURRENT_DIR/$moduleName"
var moduleClasspath = projectInfo.moduleClasspathMap[moduleName]
if (moduleClasspath == null) {
val mappedModuleName = mappedModules[moduleName]
moduleClasspath = projectInfo.moduleClasspathMap[mappedModuleName]
moduleClasspathFile = File("$greencatRoot/$CLASSPATH_DIR/$mappedModuleName")
checkNotNull(moduleClasspath) { "No classpath for module $moduleName" }
}
if (moduleClasspathFile.exists()) {
Telemetry.log("\n# Starting debug compilation for module $moduleName ($modulePath) #")
} else {
error("No classpath file for module $moduleName")
}
val javaFilePaths = exec("find $modulePath -name '*.java'")
.filterNot { path -> path.contains("/build/") }
val kotlinFilePaths = exec("find $modulePath -name '*.kt'")
.filterNot { path -> path.contains("/build/") }
val allSourcePaths = javaFilePaths + kotlinFilePaths
val greencatClassDirs = getGreenCatClassDirectories(greencatRoot)
val classpath = greencatClassDirs.joinToString(separator = ":") + ":$moduleClasspath"
Telemetry.log("Total: ${javaFilePaths.size} Java file(s) and ${kotlinFilePaths.size} Kotlin file(s)\n")
Telemetry.log("Classpath size = ${moduleClasspath.length}")
allSourcePaths.forEachIndexed { index, path ->
val result = when {
path.endsWith(".java") -> compileWithJavac(setOf(path), moduleName, classpath)
path.endsWith(".kt") -> compileWithKotlin(setOf(path), moduleName, classpath)
else -> null
}
when (result) {
is CompilationResult.Successful -> {
Telemetry.log("[${index + 1} / ${allSourcePaths.size}] $path is OK")
}
is CompilationResult.Error -> {
Telemetry.log("\n[${index + 1} / ${allSourcePaths.size}] $path is FAILED")
result.output.forEach { line -> Telemetry.log(" # $line") }
Telemetry.log("\n")
}
else -> Telemetry.log("[${index + 1} / ${allSourcePaths.size}] $path SKIPPED")
}
}
}
private fun compile(moduleName: String): Future<CompilationResult> {
val srcFiles = checkNotNull(projectInfo.sourceFilesMap[moduleName]) {
"No source files for module $moduleName"
}
val moduleClasspath = checkNotNull(projectInfo.moduleClasspathMap[moduleName]) {
"No classpath for module $moduleName"
}
val javaSrcFiles = srcFiles.filter { path -> path.endsWith(".java") }.toSet()
val kotlinSrcFiles = srcFiles.filter { path -> path.endsWith(".kt") }.toSet()
val greencatClassDirs = getGreenCatClassDirectories(greencatRoot)
val classpath = greencatClassDirs.joinToString(separator = ":") + ":$moduleClasspath"
return Callable {
val result = when (javaSrcFiles.isEmpty()) {
true -> CompilationResult.Successful
else -> compileWithJavac(srcFiles = javaSrcFiles, moduleName = moduleName, moduleClasspath = classpath)
}
if (result is CompilationResult.Error) {
result
} else {
when (kotlinSrcFiles.isEmpty()) {
true -> CompilationResult.Successful
else -> compileWithKotlin(srcFiles = kotlinSrcFiles, moduleName = moduleName, moduleClasspath = classpath)
}
}
}.run { executor.submit(this) }
}
private fun getGreenCatClassDirectories(greencatRoot: String): Set<String> {
val files = File("$greencatRoot/$CLASS_FILES_DIR")
.listFiles { file, _ -> file.isDirectory } ?: emptyArray()
return files.map { file -> file.absolutePath }.toSet()
}
private fun deleteClasspathForModule(moduleName: String) {
Telemetry.log("Delete classpath file for module $moduleName")
File("$greencatRoot/$CLASSPATH_DIR/$moduleName").delete()
}
private fun compileWithJavac(srcFiles: Set<String>, moduleName: String, moduleClasspath: String): CompilationResult {
val classDir = "$greencatRoot/$CLASS_FILES_DIR/$moduleName".noTilda()
val srcFilesLine = srcFiles.joinToString(separator = " ")
var javac = exec("echo \$JAVA_HOME/bin/javac").first()
if (!File(javac).exists()) {
javac = "javac"
}
Telemetry.verboseLog("Using Java compiler: $javac")
val lines = exec("$javac -source 1.8 -target 1.8 -encoding utf-8 -g -cp $moduleClasspath -d $classDir $srcFilesLine")
val inputFileNames = srcFiles.map { path -> File(path).nameWithoutExtension }.toSet()
val outputFileNames = exec("find $classDir -name '*.class'").map { path -> File(path).nameWithoutExtension }.toSet()
return when ((inputFileNames - outputFileNames).isEmpty()) {
true -> CompilationResult.Successful
else -> CompilationResult.Error(moduleName, lines)
}
}
private fun compileWithKotlin(srcFiles: Set<String>, moduleName: String, moduleClasspath: String): CompilationResult {
val kotlinDir = "$greencatRoot/$KOTLINC_DIR"
val kotlinc = "$kotlinDir/bin/kotlinc".noTilda()
if (!File(kotlinc).exists()) {
error("Kotlin compiler not found: $kotlinc")
}
val classDir = "$greencatRoot/$CLASS_FILES_DIR/$moduleName".noTilda()
val srcFilesLine = srcFiles.joinToString(separator = " ")
val moduleNameArg = "-module-name ${moduleName.replace("-", "_")}_debug"
val friendPaths = getFriendModulePaths(moduleName, moduleClasspath).joinToString(separator = ",")
val cmd = "$kotlinc -Xjvm-default=all-compatibility -Xfriend-paths=$friendPaths $moduleNameArg -d $classDir -classpath $moduleClasspath $srcFilesLine"
val lines = exec(cmd)
val inputFileNames = srcFiles.map { path -> File(path).nameWithoutExtension }.toSet()
val outputFileNames = exec("find $classDir -name '*.class'").map { path -> File(path).nameWithoutExtension }.toSet()
return when ((inputFileNames - outputFileNames).isEmpty()) {
true -> CompilationResult.Successful
else -> CompilationResult.Error(moduleName, lines)
}
}
private fun getFriendModulePaths(moduleName: String, moduleClasspath: String) =
moduleClasspath.split(":").filter { path -> path.contains("$moduleName/build") }
private fun runD8() {
val buildToolsDir = getBuildToolsDir()
val d8ToolPath = "$buildToolsDir/d8"
val dexDumpToolPath = "$buildToolsDir/dexdump"
val classDir = "$greencatRoot/$CLASS_FILES_DIR".noTilda()
val moduleDirs = File(classDir).list { file, _ -> file.isDirectory } ?: emptyArray()
val dexDir = "$greencatRoot/$DEX_FILES_DIR".noTilda()
val standardDexFileName = "classes.dex"
val dexFilePath = "$dexDir/$OUTPUT_DEX_FILE".noTilda()
val currentApiLevel = try {
deviceApiLevel.toInt()
} catch (_: Throwable) {
error("Failed to parse device API level: $deviceApiLevel")
}
val minApiLevelArg = if (currentApiLevel >= MIN_API_LEVEL) {
"--min-api $MIN_API_LEVEL"
} else {
""
}
check(moduleDirs.isNotEmpty()) { "Class directory is empty" }
Telemetry.log("Running D8 (API level: $deviceApiLevel)...")
val tasks = moduleDirs.map { moduleDir ->
val task = Callable {
val outDir = File("$dexDir/$moduleDir")
val classDirs = exec("find $classDir/$moduleDir -name '*.class'")
.map { path -> "${File(path).parentFile.absolutePath}/*.class" }
.toSet()
.joinToString(separator = " ")
if (!outDir.exists()) {
outDir.mkdir()
}
exec("$d8ToolPath $classDirs --file-per-class --output ${outDir.absolutePath} $minApiLevelArg")
.forEach { line -> Telemetry.log("[$moduleDir] D8: ${line.trim()}") }
exec("find ${outDir.absolutePath} -name '*.dex'").isNotEmpty()
}
executor.submit(task)
}
tasks.forEach { future ->
val isOk = try {
future.get()
} catch (error: Throwable) {
error("Error running D8 (message = ${error.message})")
}
if (!isOk) {
error("Error running D8")
}
}
val dexFiles = exec("find $dexDir -name '*.dex'")
if (dexFiles.isEmpty()) {
error("No DEX files found")
}
val dexFilesArg = dexFiles.joinToString(separator = " ") { path -> "'$path'" }
exec("$d8ToolPath $dexFilesArg --output $dexDir $minApiLevelArg")
.forEach { line -> Telemetry.log("Merge D8: ${line.trim()}") }
val entries = exec("$dexDumpToolPath $dexDir/$standardDexFileName | grep 'Class descriptor'")
Telemetry.log("\nOutput DEX file contains ${entries.size} class entries:\n")
entries.forEach { line ->
val startIndex = line.indexOfFirst { c -> c == '\'' }
val endIndex = line.indexOfLast { c -> c == ';' }
if (startIndex == -1 || endIndex == -1) {
error("Failed to parse dexdump output")
}
Telemetry.log(" # ${line.substring(startIndex + 1, endIndex)}")
}
Telemetry.log("")
File("$dexDir/$standardDexFileName").apply {
if (!exists()) {
error("Failed to generate output DEX file: $path")
}
if (!renameTo(File(dexFilePath))) {
error("Failed to rename: $path -> $dexFilePath")
}
}
}
private fun getBuildToolsDir() = File("$androidSdkRoot/build-tools").run {
if (!exists()) {
error("No build-tools directory in Android SDK: $absolutePath")
}
val dirs = listFiles { file -> file.isDirectory }
if (dirs.isNullOrEmpty()) {
error("No build tools installed")
}
dirs.sortedDescending()[0].absolutePath
}
private fun clearDirectory(dirName: String) {
val path = "$greencatRoot/$dirName".noTilda()
exec("rm -rf $path")
if (File(path).exists()) {
error("Failed to clear directory: $path")
}
if (!File(path).mkdir()) {
error("Failed to create directory: $path")
}
}
sealed class CompilationResult {
object Successful : CompilationResult()
data class Error(val moduleName: String, val output: List<String>) : CompilationResult()
}
private companion object {
// Min API level, when there are no warnings about missing types for desugaring. Specifying types in D8
// classpath fixes the problem, but slows down build
// TODO: need research about desugaring
const val MIN_API_LEVEL = 24
}
}
|
apache-2.0
|
dce5418e212fd0b46e606262f3957395
| 42.269841 | 158 | 0.590872 | 4.613744 | false | false | false | false |
PaulWoitaschek/Voice
|
scanner/src/main/kotlin/voice/app/scanner/BookmarkMigrator.kt
|
1
|
1737
|
package voice.app.scanner
import voice.common.BookId
import voice.data.Bookmark
import voice.data.Chapter
import voice.data.legacy.LegacyBookMetaData
import voice.data.repo.internals.dao.BookmarkDao
import voice.data.repo.internals.dao.LegacyBookDao
import voice.data.runForMaxSqlVariableNumber
import voice.data.toUri
import javax.inject.Inject
class BookmarkMigrator
@Inject constructor(
private val legacyBookDao: LegacyBookDao,
private val bookmarkDao: BookmarkDao,
) {
suspend fun migrate(migrationMetaData: LegacyBookMetaData, chapters: List<Chapter>, id: BookId) {
legacyBookDao.chapters()
.filter {
it.bookId == migrationMetaData.id
}
.map { it.file }
.runForMaxSqlVariableNumber { legacyBookDao.bookmarksByFiles(it) }
.forEach { legacyBookmark ->
val legacyChapter = legacyBookDao.chapters()
.filter {
it.bookId == migrationMetaData.id
}
.find { it.file == legacyBookmark.mediaFile }
if (legacyChapter != null) {
val matchingChapter = chapters.find {
val chapterFilePath = it.id.toUri().filePath() ?: return@find false
legacyChapter.file.absolutePath.endsWith(chapterFilePath)
}
if (matchingChapter != null) {
bookmarkDao.addBookmark(
Bookmark(
bookId = id,
addedAt = legacyBookmark.addedAt,
chapterId = matchingChapter.id,
id = Bookmark.Id.random(),
setBySleepTimer = legacyBookmark.setBySleepTimer,
time = legacyBookmark.time,
title = legacyBookmark.title,
),
)
}
}
}
}
}
|
gpl-3.0
|
038033224394240afb124eabbf33a79f
| 31.166667 | 99 | 0.633276 | 4.5 | false | false | false | false |
Geobert/radis
|
app/src/main/kotlin/fr/geobert/radis/data/Statistic.kt
|
1
|
6275
|
package fr.geobert.radis.data
import android.database.Cursor
import android.os.*
import fr.geobert.radis.R
import fr.geobert.radis.db.StatisticTable
import fr.geobert.radis.tools.*
import hirondelle.date4j.DateTime
class Statistic() : ImplParcelable {
override val parcels = hashMapOf<String, Any?>()
companion object {
val PERIOD_DAYS = 0
val PERIOD_MONTHES = 1
val PERIOD_YEARS = 2
val PERIOD_ABSOLUTE = 3
val CHART_PIE = 0
val CHART_BAR = 1
val CHART_LINE = 2
// filter spinner idx
val THIRD_PARTY = 0
val TAGS = 1
val MODE = 2
val NO_FILTER = 3
val CREATOR: Parcelable.Creator<Statistic> = object : Parcelable.Creator<Statistic> {
override fun createFromParcel(p: Parcel): Statistic {
return Statistic(p)
}
override fun newArray(size: Int): Array<Statistic?> {
return arrayOfNulls(size)
}
}
}
var id: Long by parcels
var name: String by parcels
var accountId: Long by parcels
var accountName: String by parcels
var xLast: Int by parcels
var endDate: DateTime by parcels
var date: DateTime by parcels
var startDate: DateTime by parcels
var timePeriodType: Int by parcels
var timeScaleType: Int by parcels
var chartType: Int by parcels
var filterType: Int by parcels
init {
id = 0L
name = ""
accountId = 0L
accountName = ""
xLast = 1
timePeriodType = Statistic.PERIOD_DAYS
timeScaleType = Statistic.PERIOD_DAYS
chartType = Statistic.CHART_PIE
filterType = 0
val today = DateTime.today(TIME_ZONE)
date = today.minusMonth(1)
startDate = today.minusMonth(1)
endDate = today
}
constructor(cursor: Cursor) : this() {
id = cursor.getLong(0)
name = cursor.getString(StatisticTable.STAT_COLS.indexOf(StatisticTable.KEY_STAT_NAME))
accountName = cursor.getString(StatisticTable.STAT_COLS.indexOf(StatisticTable.KEY_STAT_ACCOUNT_NAME))
accountId = cursor.getLong(StatisticTable.STAT_COLS.indexOf(StatisticTable.KEY_STAT_ACCOUNT))
chartType = cursor.getInt(StatisticTable.STAT_COLS.indexOf(StatisticTable.KEY_STAT_TYPE))
filterType = cursor.getInt(StatisticTable.STAT_COLS.indexOf(StatisticTable.KEY_STAT_FILTER))
timePeriodType = cursor.getInt(StatisticTable.STAT_COLS.indexOf(StatisticTable.KEY_STAT_PERIOD_TYPE))
timeScaleType = cursor.getInt(StatisticTable.STAT_COLS.indexOf(StatisticTable.KEY_STAT_TIMESCALE_TYPE))
if (timeScaleType < 0) // freshly added column
timeScaleType = if (timePeriodType == Statistic.PERIOD_ABSOLUTE) Statistic.PERIOD_DAYS else timePeriodType
if (isPeriodAbsolute()) {
startDate = DateTime.forInstant(cursor.getLong(StatisticTable.STAT_COLS.indexOf(StatisticTable.KEY_STAT_START_DATE)), TIME_ZONE)
endDate = DateTime.forInstant(cursor.getLong(StatisticTable.STAT_COLS.indexOf(StatisticTable.KEY_STAT_END_DATE)), TIME_ZONE)
} else {
xLast = cursor.getInt(StatisticTable.STAT_COLS.indexOf(StatisticTable.KEY_STAT_X_LAST))
}
}
constructor(p: Parcel) : this() {
readFromParcel(p)
}
fun getValue(value: String): Any =
when (value) {
StatisticTable.KEY_STAT_NAME -> name
StatisticTable.KEY_STAT_ACCOUNT_NAME -> accountName
StatisticTable.KEY_STAT_ACCOUNT -> accountId
StatisticTable.KEY_STAT_TYPE -> chartType
StatisticTable.KEY_STAT_FILTER -> filterType
StatisticTable.KEY_STAT_PERIOD_TYPE -> timePeriodType
StatisticTable.KEY_STAT_TIMESCALE_TYPE -> timeScaleType
StatisticTable.KEY_STAT_X_LAST -> xLast
StatisticTable.KEY_STAT_START_DATE -> startDate.getMilliseconds(TIME_ZONE)
StatisticTable.KEY_STAT_END_DATE -> endDate.getMilliseconds(TIME_ZONE)
else -> {
throw NoSuchFieldException()
}
}
fun isPeriodAbsolute() = timePeriodType == Statistic.PERIOD_ABSOLUTE
override fun equals(other: Any?): Boolean =
if (other is Statistic) {
this.id == other.id && this.name == other.name && this.accountId == other.accountId &&
this.chartType == other.chartType && this.filterType == other.filterType &&
this.timePeriodType == other.timePeriodType && this.timeScaleType == other.timeScaleType &&
this.isPeriodAbsolute() == other.isPeriodAbsolute() &&
if (this.isPeriodAbsolute()) {
this.startDate == other.startDate && this.endDate == other.endDate
} else {
this.xLast == other.xLast
}
} else {
false
}
/**
* create a time range according to statistic's configuration
* @return (startDate, endDate)
*/
fun createTimeRange(): Pair<DateTime, DateTime> {
fun createXLastRange(): Pair<DateTime, DateTime> {
val today = DateTime.today(TIME_ZONE)
val startDate = when (this.timePeriodType) {
Statistic.PERIOD_DAYS -> today.minusDays(this.xLast)
Statistic.PERIOD_MONTHES -> today.minusMonth(this.xLast)
Statistic.PERIOD_YEARS -> today.minusYear(this.xLast)
else -> throw NoWhenBranchMatchedException()
}
return Pair(startDate, today)
}
return when (this.timePeriodType) {
Statistic.PERIOD_ABSOLUTE -> Pair(startDate, endDate)
else -> createXLastRange()
}
}
fun getFilterStr(): Int =
when (filterType) {
Statistic.THIRD_PARTY -> R.string.third_party
Statistic.TAGS -> R.string.tag
Statistic.MODE -> R.string.mode
else -> R.string.no_filter
}
override fun hashCode(): Int {
return parcels.hashCode()
}
}
|
gpl-2.0
|
e5095586e3582277c0c5b013619002da
| 37.734568 | 140 | 0.605737 | 4.437765 | false | false | false | false |
ansman/okhttp
|
okhttp/src/main/kotlin/okhttp3/internal/io/FileSystem.kt
|
1
|
4994
|
/*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.io
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import okio.Sink
import okio.Source
import okio.appendingSink
import okio.sink
import okio.source
/**
* Access to read and write files on a hierarchical data store. Most callers should use the
* [SYSTEM] implementation, which uses the host machine's local file system. Alternate
* implementations may be used to inject faults (for testing) or to transform stored data (to add
* encryption, for example).
*
* All operations on a file system are racy. For example, guarding a call to [source] with
* [exists] does not guarantee that [FileNotFoundException] will not be thrown. The
* file may be moved between the two calls!
*
* This interface is less ambitious than [java.nio.file.FileSystem] introduced in Java 7.
* It lacks important features like file watching, metadata, permissions, and disk space
* information. In exchange for these limitations, this interface is easier to implement and works
* on all versions of Java and Android.
*/
interface FileSystem {
companion object {
/** The host machine's local file system. */
@JvmField
val SYSTEM: FileSystem = SystemFileSystem()
private class SystemFileSystem : FileSystem {
@Throws(FileNotFoundException::class)
override fun source(file: File): Source = file.source()
@Throws(FileNotFoundException::class)
override fun sink(file: File): Sink {
return try {
file.sink()
} catch (_: FileNotFoundException) {
// Maybe the parent directory doesn't exist? Try creating it first.
file.parentFile.mkdirs()
file.sink()
}
}
@Throws(FileNotFoundException::class)
override fun appendingSink(file: File): Sink {
return try {
file.appendingSink()
} catch (_: FileNotFoundException) {
// Maybe the parent directory doesn't exist? Try creating it first.
file.parentFile.mkdirs()
file.appendingSink()
}
}
@Throws(IOException::class)
override fun delete(file: File) {
// If delete() fails, make sure it's because the file didn't exist!
if (!file.delete() && file.exists()) {
throw IOException("failed to delete $file")
}
}
override fun exists(file: File): Boolean = file.exists()
override fun size(file: File): Long = file.length()
@Throws(IOException::class)
override fun rename(from: File, to: File) {
delete(to)
if (!from.renameTo(to)) {
throw IOException("failed to rename $from to $to")
}
}
@Throws(IOException::class)
override fun deleteContents(directory: File) {
val files = directory.listFiles() ?: throw IOException("not a readable directory: $directory")
for (file in files) {
if (file.isDirectory) {
deleteContents(file)
}
if (!file.delete()) {
throw IOException("failed to delete $file")
}
}
}
override fun toString() = "FileSystem.SYSTEM"
}
}
/** Reads from [file]. */
@Throws(FileNotFoundException::class)
fun source(file: File): Source
/**
* Writes to [file], discarding any data already present. Creates parent directories if
* necessary.
*/
@Throws(FileNotFoundException::class)
fun sink(file: File): Sink
/**
* Writes to [file], appending if data is already present. Creates parent directories if
* necessary.
*/
@Throws(FileNotFoundException::class)
fun appendingSink(file: File): Sink
/** Deletes [file] if it exists. Throws if the file exists and cannot be deleted. */
@Throws(IOException::class)
fun delete(file: File)
/** Returns true if [file] exists on the file system. */
fun exists(file: File): Boolean
/** Returns the number of bytes stored in [file], or 0 if it does not exist. */
fun size(file: File): Long
/** Renames [from] to [to]. Throws if the file cannot be renamed. */
@Throws(IOException::class)
fun rename(from: File, to: File)
/**
* Recursively delete the contents of [directory]. Throws an IOException if any file could
* not be deleted, or if `dir` is not a readable directory.
*/
@Throws(IOException::class)
fun deleteContents(directory: File)
}
|
apache-2.0
|
bf6c05944f01469ad8bc189982d0b4d6
| 32.516779 | 102 | 0.662795 | 4.369204 | false | false | false | false |
NextFaze/dev-fun
|
devfun-annotations/src/main/java/com/nextfaze/devfun/function/DeveloperFunction.kt
|
1
|
7976
|
package com.nextfaze.devfun.function
import com.nextfaze.devfun.DeveloperAnnotation
import com.nextfaze.devfun.category.DeveloperCategory
import com.nextfaze.devfun.category.DeveloperCategoryProperties
import kotlin.reflect.KClass
/**
* Functions/methods annotated with this will be shown on the Developer Menu (and other modules).
*
* The function and its containing class can have any visibility:
* - `public` and `internal` visibilities will call the function directly
* - `package` or `private` the function will be invoked using reflection
*
* At compile time, a [FunctionDefinition] will be generated referencing the function with this annotation.
*
* At runtime the [FunctionDefinition] will be transformed to one or more [FunctionItem] via [FunctionTransformer].
*
* - [Properties](#properties)
* - [Name](#name)
* - [Category](#category)
* - [Requires API](#requires-api)
* - [Transformer](#transformer)
* - [Contextual Vars](#contextual-vars)
* - [Limitations](#limitations)
*
* # Properties
* All properties are optional.
*
* ## Name
* When [value] is undefined, the name is derived from the function name split by camel case. (e.g. "myFunction" → "My Function").
*
* e.g.
* Change the name of a function to "A Slightly Better Name":
* ```kotlin
* class MyClass {
* @DeveloperFunction("A Slightly Better Name")
* fun A_STUPID_Name() {
* ...
* }
* }
* ```
*
* ## Category
* The [category] property allows specifying and/or overloading the category details for this function _(see [DeveloperCategory])_.
*
* e.g.
* Specify a different category:
* ```kotlin
* class MyClass {
* @DeveloperFunction(category = DeveloperCategory("My Class (Animation Utils)"))
* fun startAnimation() = Unit // category="My Class (Animation Utils)"
* }
* ```
*
* Specify a group for a function:
* ```kotlin
* class MyClass {
* @DeveloperFunction(category = DeveloperCategory(group = "Special Snow Flake"))
* fun someFunction() = Unit // category="My Class", group="Special Snow Flake"
*
* @DeveloperFunction
* fun anotherFunction() = Unit // category="My Class", group="Misc" (as one or more groups are present)
* }
* ```
*
* _(todo: add "group" value to DeveloperFunction annotation?)_
*
* ## Requires API
* When [requiresApi] is specified this function will only be visible/referenced if the device meets the requirements.
*
* _(todo: use/look for @RequiresApi instead/as well?)_
*
* e.g.
* Restrict `M` function:
* ```kotlin
* class MyClass {
* // Any device below M will not see this function and DevFun wont invoke any transformers upon it
* @RequiresApi(Build.VERSION_CODES.M)
* @DeveloperFunction(requiresApi = Build.VERSION_CODES.M)
* fun startAnimation() {
* // doing something M related
* }
* }
* ```
*
* ## Transformer
* The [transformer] tells DevFun how to generate one or more [FunctionItem] from this function's [FunctionDefinition].
*
* The default transformer is [SingleFunctionTransformer] which effectively just wraps the [FunctionDefinition] to a [FunctionItem] (1:1).
*
* Item lifecycle:
* - [DeveloperFunction] → [FunctionDefinition] → [FunctionTransformer] → [FunctionItem] → "Menu Item"
*
* For an in-depth explanation on transformers see [FunctionTransformer].
*
* e.g.
* Provide a list of items to automatically fill in and log in as a test account:
* ```kotlin
* class MyAuthenticateFragment {
* ...
*
* override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
* signInButton.apply {
* setOnClickListener { attemptLogin() }
* }
* }
*
* @DeveloperFunction(transformer = SignInFunctionTransformer::class)
* private fun signInAs(email: String, password: String) {
* emailEditText.setText(email)
* passwordEditText.setText(password)
* attemptLogin()
* }
* }
*
* private class SignInFunctionTransformer : FunctionTransformer {
* private data class TestAccount(val email: String, val password: String) {
* val title = "Authenticate as $email" // this will be the name of the item - this is effectively @DeveloperFunction("Authenticate as $email")
* }
*
* private val accounts = if (BuildConfig.DEBUG) { // BuildConfig.DEBUG for dead-code removal
* listOf(
* TestAccount("[email protected]", "hello"),
* TestAccount("[email protected]", "world")
* )
* } else {
* emptyList()
* }
*
* override fun apply(functionDefinition: FunctionDefinition, categoryDefinition: CategoryDefinition): List<SimpleFunctionItem> =
* accounts.map {
* object : SimpleFunctionItem(functionDefinition, categoryDefinition) {
* override val name = it.title
* override val args = listOf(it.email, it.password) // arguments as expected from signInAs(...)
* }
* }
* }
* ```
*
* The above transformer can also be achieved using @[DeveloperArguments].
* ```kotlin
* @DeveloperArguments(
* name = "Authenticate as %0",
* args = [
* Args(["[email protected]", "hello"]),
* Args(["[email protected]", "world"])
* ]
* )
* fun signInAs(...)
* ```
*
*
* # Contextual Vars
* _(experimental)_ At compile time the follow vars are available for use in [value] (also [DeveloperCategory.value] and [DeveloperCategory.group]):
* - `%CLASS_SN%` → The simple name of the class
* - `%CLASS_QN%` → The fully qualified name of the class
* - `%FUN_SN%` → The simple name of the annotated function
* - `%FUN_QN%` → The qualified name of the annotated function. "fun myFunction(param1: String)" becomes "myFunction(java.lang.String)"
*
* e.g.
* ```kotlin
* class MyClass {
* @DeveloperFunction("I am in %CLASS_SN%")
* fun someFun() = Unit // name="I am in MyClass"
* }
* ```
*
* # Limitations
* - Annotations on functions in interfaces is not supported at the moment due to the way Kotlin/KAPT handles default functions/args. This is
* intended to be permissible in the future.
*
* - Unfortunately the [transformer] class must be in the same source tree as the declaration site. Looking into ways to change this but it
* may not be trivial/possible by the nature of Javac and annotation processing.
*
* @param value The name that to be shown for this item. If blank the method name will be split by camel case. (e.g. "myFunction" → "My Function")
* @param category Category definition override. Unset fields will be inherited.
* @param requiresApi API required for this item to be visible/processed. Unset or values `<= 0` are ignored.
* @param transformer A transformer class to handle the [FunctionDefinition] to [FunctionItem] processing. Defaults to [SingleFunctionTransformer].
*
* @see DeveloperCategory
* @see FunctionTransformer
* @see SimpleFunctionItem
*/
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.SOURCE)
@DeveloperAnnotation(developerFunction = true)
annotation class DeveloperFunction(
val value: String = "",
val category: DeveloperCategory = DeveloperCategory(),
val requiresApi: Int = 0,
val transformer: KClass<out FunctionTransformer> = SingleFunctionTransformer::class
)
/**
* Properties interface for @[DeveloperFunction].
*
* TODO: This interface should be generated by DevFun at compile time, but as the annotations are in a separate module to the compiler
* that itself depends on the annotations module, it is non-trivial to run the DevFun processor upon it (module dependencies become cyclic).
*/
interface DeveloperFunctionProperties {
val value: String get() = ""
val category: DeveloperCategoryProperties get() = object : DeveloperCategoryProperties {}
val requiresApi: Int get() = 0
val transformer: KClass<out FunctionTransformer> get() = SingleFunctionTransformer::class
}
|
apache-2.0
|
9bdf2ab5f0b40ffd7e5722f4ad4cc31d
| 37.434783 | 151 | 0.682001 | 4.034483 | false | false | false | false |
nickthecoder/paratask
|
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/compound/TemporalAmountParameter.kt
|
1
|
2979
|
/*
ParaTask Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.paratask.parameters.compound
import uk.co.nickthecoder.paratask.parameters.*
import uk.co.nickthecoder.paratask.util.Labelled
import uk.co.nickthecoder.paratask.util.uncamel
import java.time.Duration
import java.time.Period
import java.time.temporal.TemporalAmount
import kotlin.reflect.KProperty
class TemporalAmountParameter(
name: String,
label: String = name.uncamel(),
description: String = "",
required: Boolean = true)
: GroupParameter(name, label, description) {
val amountP = IntParameter("amount", label = "", required = required)
var amount by amountP
val unitsP = ChoiceParameter("units", label = "", required = required, value = TimeUnit.DAYS).enumChoices()
var units by unitsP
override fun saveChildren(): Boolean = true
val value: TemporalAmount?
get() {
val a = amount ?: return null
return when (units) {
TimeUnit.MILLISECONDS -> Duration.ofMillis(a.toLong())
TimeUnit.SECONDS -> Duration.ofSeconds(a.toLong())
TimeUnit.MINUTES -> Duration.ofMinutes(a.toLong())
TimeUnit.HOURS -> Duration.ofHours(a.toLong())
TimeUnit.DAYS -> Period.ofDays(a)
TimeUnit.WEEKS -> Period.ofDays(a)
TimeUnit.MONTHS -> Period.ofMonths(a)
TimeUnit.YEARS -> Period.ofYears(a)
null -> null
}
}
operator fun getValue(thisRef: Any?, property: KProperty<*>): TemporalAmount? {
return value
}
init {
asHorizontal(LabelPosition.LEFT)
addParameters(amountP, unitsP)
}
override fun errorMessage(): String? {
return null
}
override fun copy(): TemporalAmountParameter {
val copy = TemporalAmountParameter(name, label, description, required = amountP.required)
copy.amount = amount
copy.units = units
copyAbstractAttributes(copy)
return copy
}
enum class TimeUnit(override val label: String) : Labelled {
MILLISECONDS("Milliseconds"),
SECONDS("Seconds"),
MINUTES("Minutes"),
HOURS("Hours"),
DAYS("Days"),
WEEKS("Weeks"),
MONTHS("Months"),
YEARS("Years");
}
}
|
gpl-3.0
|
af89750b6d86b7d62ea0c3945a5b2f02
| 30.691489 | 111 | 0.654246 | 4.63297 | false | false | false | false |
arturbosch/detekt
|
detekt-rules-performance/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/performance/ForEachOnRange.kt
|
1
|
3533
|
package io.gitlab.arturbosch.detekt.rules.performance
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault
import io.gitlab.arturbosch.detekt.rules.getIntValueForPsiElement
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtParenthesizedExpression
import org.jetbrains.kotlin.psi.psiUtil.getCallNameExpression
import org.jetbrains.kotlin.psi.psiUtil.getReceiverExpression
/**
* Using the forEach method on ranges has a heavy performance cost. Prefer using simple for loops.
*
* Benchmarks have shown that using forEach on a range can have a huge performance cost in comparison to
* simple for loops. Hence in most contexts a simple for loop should be used instead.
* See more details here: https://sites.google.com/a/athaydes.com/renato-athaydes/posts/kotlinshiddencosts-benchmarks
* To solve this CodeSmell, the forEach usage should be replaced by a for loop.
*
* <noncompliant>
* (1..10).forEach {
* println(it)
* }
* (1 until 10).forEach {
* println(it)
* }
* (10 downTo 1).forEach {
* println(it)
* }
* </noncompliant>
*
* <compliant>
* for (i in 1..10) {
* println(i)
* }
* </compliant>
*/
@ActiveByDefault(since = "1.0.0")
class ForEachOnRange(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(
"ForEachOnRange",
Severity.Performance,
"Using the forEach method on ranges has a heavy performance cost. Prefer using simple for loops.",
Debt.FIVE_MINS
)
private val minimumRangeSize = 3
private val rangeOperators = setOf("..", "downTo", "until", "step")
override fun visitCallExpression(expression: KtCallExpression) {
super.visitCallExpression(expression)
expression.getCallNameExpression()?.let {
if (!it.textMatches("forEach")) {
return
}
val parenthesizedExpression = it.getReceiverExpression() as? KtParenthesizedExpression
val binaryExpression = parenthesizedExpression?.expression as? KtBinaryExpression
if (binaryExpression != null && isRangeOperator(binaryExpression)) {
report(CodeSmell(issue, Entity.from(expression), issue.description))
}
}
}
private fun isRangeOperator(binaryExpression: KtBinaryExpression): Boolean {
val range = binaryExpression.children
if (range.size >= minimumRangeSize) {
val hasCorrectLowerValue = hasCorrectLowerValue(range[0])
val hasCorrectUpperValue = getIntValueForPsiElement(range[2]) != null
return hasCorrectLowerValue && hasCorrectUpperValue && rangeOperators.contains(range[1].text)
}
return false
}
private fun hasCorrectLowerValue(element: PsiElement): Boolean {
var lowerValue = getIntValueForPsiElement(element) != null
if (!lowerValue) {
val expression = element as? KtBinaryExpression
if (expression != null) {
lowerValue = isRangeOperator(expression)
}
}
return lowerValue
}
}
|
apache-2.0
|
c8f696686f54668a55195a1263d60827
| 36.989247 | 117 | 0.703368 | 4.38882 | false | true | false | false |
nextcloud/android
|
app/src/main/java/com/owncloud/android/ui/adapter/UnifiedSearchListAdapter.kt
|
1
|
6186
|
/*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* @author Chris Narkiewicz <[email protected]>
*
* Copyright (C) 2018 Tobias Kaminsky
* Copyright (C) 2018 Nextcloud
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* 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 AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.afollestad.sectionedrecyclerview.SectionedRecyclerViewAdapter
import com.afollestad.sectionedrecyclerview.SectionedViewHolder
import com.nextcloud.client.account.User
import com.nextcloud.client.network.ClientFactory
import com.owncloud.android.R
import com.owncloud.android.databinding.UnifiedSearchEmptyBinding
import com.owncloud.android.databinding.UnifiedSearchFooterBinding
import com.owncloud.android.databinding.UnifiedSearchHeaderBinding
import com.owncloud.android.databinding.UnifiedSearchItemBinding
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.ThumbnailsCacheManager.InitDiskCacheTask
import com.owncloud.android.ui.interfaces.UnifiedSearchListInterface
import com.owncloud.android.ui.unifiedsearch.UnifiedSearchSection
import com.owncloud.android.utils.theme.ViewThemeUtils
/**
* This Adapter populates a SectionedRecyclerView with search results by unified search
*/
@Suppress("LongParameterList")
class UnifiedSearchListAdapter(
private val storageManager: FileDataStorageManager,
private val listInterface: UnifiedSearchListInterface,
private val user: User,
private val clientFactory: ClientFactory,
private val context: Context,
private val viewThemeUtils: ViewThemeUtils
) : SectionedRecyclerViewAdapter<SectionedViewHolder>() {
companion object {
private const val VIEW_TYPE_EMPTY = Int.MAX_VALUE
}
private var sections: List<UnifiedSearchSection> = emptyList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SectionedViewHolder {
val layoutInflater = LayoutInflater.from(context)
return when (viewType) {
VIEW_TYPE_HEADER -> {
val binding = UnifiedSearchHeaderBinding.inflate(
layoutInflater,
parent,
false
)
UnifiedSearchHeaderViewHolder(binding, viewThemeUtils, context)
}
VIEW_TYPE_FOOTER -> {
val binding = UnifiedSearchFooterBinding.inflate(
layoutInflater,
parent,
false
)
UnifiedSearchFooterViewHolder(binding, context, listInterface)
}
VIEW_TYPE_ITEM -> {
val binding = UnifiedSearchItemBinding.inflate(
layoutInflater,
parent,
false
)
UnifiedSearchItemViewHolder(
binding,
user,
clientFactory,
storageManager,
listInterface,
context,
viewThemeUtils
)
}
VIEW_TYPE_EMPTY -> {
val binding = UnifiedSearchEmptyBinding.inflate(layoutInflater, parent, false)
EmptyViewHolder(binding)
}
else -> throw IllegalArgumentException("Invalid view type")
}
}
internal class EmptyViewHolder(binding: UnifiedSearchEmptyBinding) :
SectionedViewHolder(binding.getRoot())
override fun getSectionCount(): Int {
return sections.size
}
override fun getItemCount(section: Int): Int {
return sections[section].entries.size
}
override fun onBindHeaderViewHolder(holder: SectionedViewHolder, section: Int, expanded: Boolean) {
val headerViewHolder = holder as UnifiedSearchHeaderViewHolder
headerViewHolder.bind(sections[section])
}
override fun onBindFooterViewHolder(holder: SectionedViewHolder, section: Int) {
if (sections[section].hasMoreResults) {
val footerViewHolder = holder as UnifiedSearchFooterViewHolder
footerViewHolder.bind(sections[section])
}
}
override fun getFooterViewType(section: Int): Int = when {
sections[section].hasMoreResults -> VIEW_TYPE_FOOTER
else -> VIEW_TYPE_EMPTY
}
override fun onBindViewHolder(
holder: SectionedViewHolder,
section: Int,
relativePosition: Int,
absolutePosition: Int
) {
// TODO different binding (and also maybe diff UI) for non-file results
val itemViewHolder = holder as UnifiedSearchItemViewHolder
val entry = sections[section].entries[relativePosition]
itemViewHolder.bind(entry)
}
override fun onViewAttachedToWindow(holder: SectionedViewHolder) {
if (holder is UnifiedSearchItemViewHolder) {
val thumbnailShimmer = holder.binding.thumbnailShimmer
if (thumbnailShimmer.visibility == View.VISIBLE) {
thumbnailShimmer.setImageResource(R.drawable.background)
thumbnailShimmer.resetLoader()
}
}
}
fun setData(sections: List<UnifiedSearchSection>) {
this.sections = sections
notifyDataSetChanged()
}
init {
// initialise thumbnails cache on background thread
InitDiskCacheTask().execute()
}
}
|
gpl-2.0
|
11e3358af10237ad1d3374b327eedfbc
| 36.490909 | 103 | 0.677174 | 5.365134 | false | false | false | false |
ibaton/3House
|
mobile/src/main/java/treehou/se/habit/ui/inbox/InboxListFragment.kt
|
1
|
9612
|
package treehou.se.habit.ui.inbox
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import java.util.ArrayList
import java.util.Collections
import java.util.Comparator
import javax.inject.Inject
import io.realm.Realm
import kotlinx.android.synthetic.main.fragment_inbox.*
import se.treehou.ng.ohcommunicator.connector.models.OHInboxItem
import treehou.se.habit.R
import treehou.se.habit.core.db.model.ServerDB
import treehou.se.habit.ui.BaseFragment
import treehou.se.habit.ui.adapter.InboxAdapter
import treehou.se.habit.util.ConnectionFactory
import treehou.se.habit.util.RxUtil
import treehou.se.habit.util.Util
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
class InboxListFragment : BaseFragment() {
@Inject lateinit var connectionFactory: ConnectionFactory
private var relam: Realm? = null
private var server: ServerDB? = null
private var adapter: InboxAdapter? = null
private val items = ArrayList<OHInboxItem>()
private var showIgnored = false
private var actionHide: MenuItem? = null
private var actionShow: MenuItem? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Util.getApplicationComponent(this).inject(this)
relam = Realm.getDefaultInstance()
server = ServerDB.load(relam!!, arguments!!.getLong(ARG_SERVER))
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_inbox, container, false)
setupActionbar()
setHasOptionsMenu(true)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
hookupInboxList()
}
/**
* Setup inbox list.
*/
private fun hookupInboxList() {
val gridLayoutManager = GridLayoutManager(activity, 1)
listView.layoutManager = gridLayoutManager
listView.itemAnimator = DefaultItemAnimator()
val simpleItemTouchCallback = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {
override fun getSwipeDirs(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?): Int {
return if (viewHolder is InboxAdapter.IgnoreInboxHolder) ItemTouchHelper.LEFT else super.getSwipeDirs(recyclerView, viewHolder)
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, swipeDir: Int) {
if (ItemTouchHelper.RIGHT == swipeDir) {
val item = adapter!!.getItem(viewHolder.adapterPosition)
ignoreInboxItem(item)
}
if (ItemTouchHelper.LEFT == swipeDir) {
val item = adapter!!.getItem(viewHolder.adapterPosition)
unignoreInboxItem(item)
}
}
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
return false
}
}
val itemTouchHelper = ItemTouchHelper(simpleItemTouchCallback)
itemTouchHelper.attachToRecyclerView(listView)
adapter = InboxAdapter(context!!, server!!, connectionFactory)
listView.adapter = adapter
}
/**
* Set up actionbar
*/
private fun setupActionbar() {
val actionBar = (activity as AppCompatActivity).supportActionBar
actionBar?.setTitle(R.string.inbox)
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater!!.inflate(R.menu.inbox, menu)
actionHide = menu!!.findItem(R.id.action_hide)
actionHide!!.setOnMenuItemClickListener {
showIgnoredItems(false)
true
}
actionShow = menu.findItem(R.id.action_show)
actionShow!!.setOnMenuItemClickListener {
showIgnoredItems(true)
true
}
updateIgnoreButtons(showIgnored)
}
/**
* Set if ignored items should be shown.
* @param showIgnored true to show ignored items, else false.
*/
private fun showIgnoredItems(showIgnored: Boolean) {
this.showIgnored = showIgnored
setItems(items, showIgnored)
updateIgnoreButtons(showIgnored)
val rootView = view
if (rootView != null) {
Snackbar.make(rootView, if (showIgnored) getString(R.string.show_ignored) else getString(R.string.hide_ignored), Snackbar.LENGTH_SHORT).show()
}
}
/**
* Update icons for showing if viewing ignored items or not.
*
* @param showIgnored True to show ignored ignored items else false.
*/
private fun updateIgnoreButtons(showIgnored: Boolean) {
actionShow!!.isVisible = !showIgnored
actionHide!!.isVisible = showIgnored
}
/**
* Set all the items that should be displayed in list.
* Clears and updates adapter accordingly.
*
* @param items the items to show.
* @param showIgnored true to filter out ignored items.
*/
private fun setItems(items: List<OHInboxItem>, showIgnored: Boolean) {
val inboxItems = ArrayList(items)
Log.d(TAG, "Received items " + inboxItems)
Collections.sort(inboxItems, InboxItemComparator())
adapter!!.clear()
if (!showIgnored) {
val it = inboxItems.iterator()
while (it.hasNext()) {
if (it.next().isIgnored) {
it.remove()
}
}
}
adapter!!.addAll(inboxItems)
}
/**
* Ignore inbox item.
* Removes the inbox item from the list.
* Sends ignore request to the server.
*
* @param item the item to hide.
*/
private fun ignoreInboxItem(item: OHInboxItem) {
item.flag = OHInboxItem.FLAG_IGNORED
val serverHandler = connectionFactory.createServerHandler(server!!.toGeneric(), context)
serverHandler.ignoreInboxItem(item)
val rootView = view
if (rootView != null) {
Snackbar.make(rootView, R.string.hide_item, Snackbar.LENGTH_LONG)
.setAction(R.string.undo) {
unignoreInboxItem(item)
Snackbar.make(rootView, R.string.restore_item, Snackbar.LENGTH_SHORT).show()
}.show()
}
setItems(items, showIgnored)
}
/**
* Unignore inbox item.
* Removes the inbox item from the list.
* Sends unignore request to the server.
*
* @param item the item to hide.
*/
private fun unignoreInboxItem(item: OHInboxItem) {
item.flag = ""
val serverHandler = connectionFactory.createServerHandler(server!!.toGeneric(), context)
serverHandler.unignoreInboxItem(item)
setItems(items, showIgnored)
}
override fun onResume() {
super.onResume()
showErrorView(false)
val serverHandler = connectionFactory.createServerHandler(server!!.toGeneric(), context)
serverHandler.requestInboxItemsRx()
.compose(RxUtil.newToMainSchedulers())
.compose(this.bindToLifecycle())
.subscribe({ ohInboxItems ->
showErrorView(false)
setItems(ohInboxItems, showIgnored)
}) {
logger.w(TAG, "Failed to load inbox items", it)
showErrorView(true)
}
}
/**
* Updates ui to show error.
* @param showError the error to show.
*/
private fun showErrorView(showError: Boolean) {
if (showError) {
empty.visibility = View.VISIBLE
listView.visibility = View.GONE
} else {
empty.visibility = View.GONE
listView.visibility = View.VISIBLE
}
}
override fun onDestroy() {
super.onDestroy()
relam!!.close()
}
/**
* Comparator for sorting inbox item in list.
*/
private class InboxItemComparator : Comparator<OHInboxItem> {
override fun compare(lhs: OHInboxItem, rhs: OHInboxItem): Int {
val inboxCompare = lhs.label.compareTo(rhs.label)
return if (inboxCompare == 0) {
lhs.thingUID.compareTo(rhs.thingUID)
} else inboxCompare
}
}
companion object {
private val TAG = "InboxListFragment"
private val ARG_SERVER = "argServer"
/**
* Creates a new instance of inbox list fragment.
*
* @param serverId the server to connect to.
* @return new fragment instance.
*/
fun newInstance(serverId: Long): InboxListFragment {
val fragment = InboxListFragment()
val args = Bundle()
args.putLong(ARG_SERVER, serverId)
fragment.arguments = args
return fragment
}
}
}
|
epl-1.0
|
85f16d077c37c46169636dd7b717fd9f
| 31.583051 | 154 | 0.635144 | 4.803598 | false | false | false | false |
mockk/mockk
|
modules/mockk/src/jvmMain/kotlin/io/mockk/impl/log/JULLogger.kt
|
2
|
1457
|
package io.mockk.impl.log
import java.util.logging.Level
import kotlin.reflect.KClass
class JULLogger(cls: KClass<*>) : Logger {
val log: java.util.logging.Logger = java.util.logging.Logger.getLogger(cls.java.name)
override fun error(msg: () -> String) = if (log.isLoggable(Level.SEVERE)) log.severe(msg()) else Unit
override fun error(ex: Throwable, msg: () -> String) =
if (log.isLoggable(Level.SEVERE)) log.log(Level.SEVERE, msg(), ex) else Unit
override fun warn(msg: () -> String) = if (log.isLoggable(Level.WARNING)) log.warning(msg()) else Unit
override fun warn(ex: Throwable, msg: () -> String) =
if (log.isLoggable(Level.WARNING)) log.log(Level.WARNING, msg(), ex) else Unit
override fun info(msg: () -> String) = if (log.isLoggable(Level.INFO)) log.info(msg()) else Unit
override fun info(ex: Throwable, msg: () -> String) =
if (log.isLoggable(Level.INFO)) log.log(Level.INFO, msg(), ex) else Unit
override fun debug(msg: () -> String) = if (log.isLoggable(Level.FINE)) log.fine(msg()) else Unit
override fun debug(ex: Throwable, msg: () -> String) =
if (log.isLoggable(Level.FINE)) log.log(Level.FINE, msg(), ex) else Unit
override fun trace(msg: () -> String) = if (log.isLoggable(Level.FINER)) log.finer(msg()) else Unit
override fun trace(ex: Throwable, msg: () -> String) =
if (log.isLoggable(Level.FINER)) log.log(Level.FINER, msg(), ex) else Unit
}
|
apache-2.0
|
231042789d6df3a0f34edb50c25e2abf
| 51.071429 | 106 | 0.661633 | 3.412178 | false | false | false | false |
ojacquemart/spring-kotlin-euro-bets
|
src/main/kotlin/org/ojacquemart/eurobets/firebase/management/match/MatchWithFixture.kt
|
2
|
1016
|
package org.ojacquemart.eurobets.firebase.management.match
import org.ojacquemart.eurobets.firebase.management.match.crawler.Fixture
import org.ojacquemart.eurobets.firebase.support.Status
data class MatchWithFixture(val match: Match, val fixture: Fixture) {
fun getFinalMatch(): MatchResultData? {
if (fixture.result == null) {
return null
}
val result = fixture.result
val awayGoals = result.goalsAwayTeam ?: 0
val homeGoals = result.goalsHomeTeam ?: 0
val homeWinner = homeGoals > awayGoals
val awayWinner = homeGoals < awayGoals
val status = if (fixture.status == org.ojacquemart.eurobets.firebase.management.match.crawler.Status.FINISHED) Status.PLAYED.id
else Status.PLAYING.id
return MatchResultData(
number = match.number, status = status,
homeGoals = result.goalsHomeTeam ?: 0, awayGoals = awayGoals,
homeWinner = homeWinner, awayWinner = awayWinner)
}
}
|
unlicense
|
8c0bbe495594014af8db931ce0046803
| 38.115385 | 135 | 0.67815 | 4.535714 | false | false | false | false |
egenvall/NameStats
|
NameStats/app/src/main/java/com/egenvall/namestats/base/domain/ReactiveUseCase.kt
|
1
|
1063
|
package com.egenvall.namestats.base.domain
import com.egenvall.namestats.common.threading.UiExecutor
import com.egenvall.namestats.common.threading.BackgroundExecutor
import rx.Observable
import rx.subscriptions.Subscriptions
abstract class ReactiveUseCase<ObservableType> (
private val uiExecutor: UiExecutor,
private val backgroundExecutor: BackgroundExecutor) {
private var subscription = Subscriptions.empty()
protected fun executeUseCase(onNext: (ObservableType) -> Unit = {},
onError: (Throwable) -> Unit = {},
onCompleted: () -> Unit = {}) {
this.subscription = useCaseObservable()
.subscribeOn(backgroundExecutor.scheduler)
.observeOn(uiExecutor.scheduler)
.subscribe(onNext, onError, onCompleted)
}
protected abstract fun useCaseObservable(): Observable<ObservableType>
fun unsubscribe() {
if (!subscription.isUnsubscribed) {
subscription.unsubscribe()
}
}
}
|
mit
|
d16b00c955cc09b6469957a50f64688c
| 34.466667 | 74 | 0.658514 | 5.160194 | false | false | false | false |
niranjan94/show-java
|
app/src/main/kotlin/com/njlabs/showjava/utils/SingletonHolder.kt
|
1
|
751
|
package com.njlabs.showjava.utils
/*
* Code borrowed from https://medium.com/@BladeCoder/kotlin-singletons-with-argument-194ef06edd9e
* Copyright (C) 2018 Christophe Beyls
*/
open class SingletonHolder<out T, in A>(creator: (A) -> T) {
private var creator: ((A) -> T)? = creator
@Volatile private var instance: T? = null
fun getInstance(arg: A): T {
val i = instance
if (i != null) {
return i
}
return synchronized(this) {
val i2 = instance
if (i2 != null) {
i2
} else {
val created = creator!!(arg)
instance = created
creator = null
created
}
}
}
}
|
gpl-3.0
|
3364b960e923a124a4d21b46e78422fa
| 25.821429 | 97 | 0.508655 | 4.081522 | false | false | false | false |
mctoyama/PixelClient
|
src/main/kotlin/org/pixelndice/table/pixelclient/connection/lobby/client/runnable/SyncActor.kt
|
1
|
1164
|
package org.pixelndice.table.pixelclient.connection.lobby.client.runnable
import org.apache.logging.log4j.LogManager
import org.pixelndice.table.pixelclient.connection.lobby.client.Context
import org.pixelndice.table.pixelclient.ds.resource.Actor
import org.pixelndice.table.pixelclient.myAccount
import org.pixelndice.table.pixelprotocol.ChannelCanceledException
import org.pixelndice.table.pixelprotocol.Protobuf
private val logger = LogManager.getLogger(SyncActor::class.java)
/**
* Runnable for sync actor with lobby peers
* @author Marcelo Costa Toyama
*/
class SyncActor(private val ctx: Context, val actor: Actor): Runnable {
override fun run() {
val packet = Protobuf.Packet.newBuilder()
packet.updateActor = actor.updateToProtobuf().build()
packet.from = myAccount.toProtobuf().build()
packet.sender = Protobuf.SenderEnum.FROM_ACCOUNT
packet.receiver = Protobuf.ReceiverEnum.TO_ALL
try {
ctx.channel.packet = packet.build()
} catch (e: ChannelCanceledException) {
logger.trace("Channel in invalid state. It will be recycled in the next cycle.")
}
}
}
|
bsd-2-clause
|
69815f37698734c375890a29bafea39d
| 36.548387 | 92 | 0.736254 | 4.263736 | false | false | false | false |
Pixelhash/SignColors
|
src/main/kotlin/de/codehat/signcolors/SignColors.kt
|
1
|
7091
|
package de.codehat.signcolors
import de.codehat.pluginupdatechecker.UpdateChecker
import de.codehat.signcolors.command.CommandManager
import de.codehat.signcolors.command.TabCompletion
import de.codehat.signcolors.commands.HelpCommand
import de.codehat.signcolors.commands.ReloadCommand
import de.codehat.signcolors.commands.GiveSignCommand
import de.codehat.signcolors.commands.ColorcodesCommand
import de.codehat.signcolors.commands.InfoCommand
import de.codehat.signcolors.config.ConfigKey
import de.codehat.signcolors.configs.LanguageConfig
import de.codehat.signcolors.daos.SignLocationDao
import de.codehat.signcolors.database.MysqlDatabase
import de.codehat.signcolors.database.SqliteDatabase
import de.codehat.signcolors.database.abstraction.Database
import de.codehat.signcolors.dependencies.VaultDependency
import de.codehat.signcolors.listener.BlockListener
import de.codehat.signcolors.listener.PlayerListener
import de.codehat.signcolors.listener.SignListener
import de.codehat.signcolors.managers.BackupOldFilesManager
import de.codehat.signcolors.managers.ColoredSignManager
import io.sentry.Sentry
import net.milkbowl.vault.economy.Economy
import org.bukkit.entity.Player
import org.bukkit.plugin.java.JavaPlugin
import java.io.File
@Suppress("unused")
class SignColors: JavaPlugin() {
private val commandManager = CommandManager()
internal val fixSignPlayers = mutableListOf<Player>()
internal var updateAvailablePair: Pair<Boolean, String> = Pair(false, "")
lateinit var database: Database
private set
lateinit var signLocationDao: SignLocationDao
private set
lateinit var coloredSignManager: ColoredSignManager
companion object {
private const val UPDATE_CHECKER_URL = "https://pluginapi.codehat.de/plugins"
private const val UPDATE_CHECKER_PLUGIN_ID = "Syjzymgdz"
private const val SENTRY_DSN = "https://[email protected]/1322662"
internal lateinit var instance: SignColors
internal lateinit var languageConfig: LanguageConfig
internal var debug = false
private set
private var vaultDependency: VaultDependency? = null
fun isVaultAvailable(): Pair<Boolean, Economy?> {
with (vaultDependency) {
return if (this != null && this.economy != null) {
Pair(true, this.economy)
} else {
Pair(false, null)
}
}
}
}
override fun onEnable() {
instance = this
checkAndDoBackup()
saveDefaultConfig()
loadLanguage()
loadDependencies()
loadDatabase()
signLocationDao = SignLocationDao(database.connectionSource)
loadManagers()
registerCommands()
registerListener()
startUpdateCheckerIfEnabled()
logger.info("v${description.version} has been enabled.")
}
override fun onDisable() {
database.close()
logger.info("v${description.version} has been disabled.")
}
private fun checkAndDoBackup() {
BackupOldFilesManager()
}
internal fun loadLanguage() {
val language = config.getString(ConfigKey.LANGUAGE.toString())
languageConfig = LanguageConfig(language)
logger.info("Loaded language '$language'.")
}
private fun loadDependencies() {
logger.info("Looking for available dependencies...")
// Find and load Vault
try {
vaultDependency = VaultDependency(this)
} catch (e: NoClassDefFoundError) {
// Drop error silently
}
if (isVaultAvailable().first) {
logger.info("Vault found and loaded.")
} else {
logger.warning("Vault is missing! Economy features have been disabled.")
}
}
internal fun loadDatabase() {
val databaseType = config.getString(ConfigKey.DATABASE_TYPE.toString())
if (databaseType.equals("sqlite", true)) {
val sqliteDatabasePath = dataFolder.absolutePath + File.separator + "sign_locations.db"
database = SqliteDatabase(SqliteDatabase.createConnectionString(sqliteDatabasePath))
logger.info("Using SQLite to save sign locations (path to DB is '$sqliteDatabasePath').")
} else if (databaseType.equals("mysql", true)) {
database = MysqlDatabase(MysqlDatabase.createConnectionString(
config.getString(ConfigKey.DATABASE_HOST.toString()),
config.getInt(ConfigKey.DATABASE_PORT.toString()),
config.getString(ConfigKey.DATABASE_NAME.toString()),
config.getString(ConfigKey.DATABASE_USER.toString()),
config.getString(ConfigKey.DATABASE_PASSWORD.toString())
))
logger.info("Using MySQL to save sign locations.")
}
}
private fun loadManagers() {
coloredSignManager = ColoredSignManager()
}
private fun registerCommands() {
with(commandManager) {
registerCommand(CommandManager.CMD_INFO, InfoCommand())
registerCommand(CommandManager.CMD_HELP, HelpCommand())
registerCommand(CommandManager.CMD_GIVE_SIGN, GiveSignCommand())
registerCommand(CommandManager.CMD_COLOR_CODES, ColorcodesCommand())
registerCommand(CommandManager.CMD_RELOAD, ReloadCommand())
//registerCommand(CommandManager.CMD_MIGRATE_DATABASE, MigrateDatabaseCommand())
}
with(getCommand(CommandManager.CMD_PREFIX)) {
executor = commandManager
tabCompleter = TabCompletion()
}
}
private fun registerListener() {
with(server.pluginManager) {
registerEvents(BlockListener(), this@SignColors)
registerEvents(SignListener(), this@SignColors)
registerEvents(PlayerListener(), this@SignColors)
}
}
private fun startUpdateCheckerIfEnabled() {
if (config.getBoolean(ConfigKey.OTHER_UPDATE_CHECK.toString())) {
logger.info("Checking for an update...")
val updateChecker = UpdateChecker.Builder(this)
.setUrl(UPDATE_CHECKER_URL)
.setPluginId(UPDATE_CHECKER_PLUGIN_ID)
.setCurrentVersion(description.version)
.onNewVersion {
logger.info("New version (v$it) is available!")
updateAvailablePair = Pair(true, it)
}
.onLatestVersion {
logger.info("No new version available.")
}
.onError {
logger.warning("Unable to check for an update!")
}
.build()
updateChecker.check()
}
}
private fun enableErrorReporting() {
if (config.getBoolean(ConfigKey.OTHER_ERROR_REPORTING.toString())) {
Sentry.init(SENTRY_DSN)
logger.info("Error reporting has been enabled.")
}
}
}
|
gpl-3.0
|
192f06bc9330e7828d197de1f4d19c5c
| 35.178571 | 101 | 0.654774 | 4.843579 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.