content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package ch.rmy.android.http_shortcuts.activities.editor.body.models import ch.rmy.android.framework.utils.localization.Localizable import ch.rmy.android.framework.utils.localization.StringResLocalizable import ch.rmy.android.http_shortcuts.R sealed interface ParameterListItem { data class Parameter( val id: String, val key: String, val value: String?, val label: Localizable?, ) : ParameterListItem object EmptyState : ParameterListItem { val title: Localizable get() = StringResLocalizable(R.string.empty_state_request_parameters) val instructions: Localizable get() = StringResLocalizable(R.string.empty_state_request_parameters_instructions) } }
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/body/models/ParameterListItem.kt
3184459643
package com.gallery.core.extensions import android.view.View /** 隐藏 */ fun View.hideExpand(): View = apply { if (!isGoneExpand()) visibility = View.GONE } /** 是否为隐藏GONE */ fun View.isGoneExpand(): Boolean = visibility == View.GONE /** 显示 */ fun View.showExpand(): View = apply { if (!isVisibleExpand()) visibility = View.VISIBLE } /** 是否为显示VISIBLE */ fun View.isVisibleExpand(): Boolean = visibility == View.VISIBLE
core/src/main/java/com/gallery/core/extensions/ExtensionsView.kt
2521672395
package com.twbarber.register.public.web data class ChangeDto(val bills: String)
cash-register-public/src/main/kotlin/com/twbarber/register/public/web/ChangeResponseDto.kt
3782439123
package io.sentry.kotlin import io.sentry.IHub import io.sentry.Sentry import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.ThreadContextElement /** * Sentry context element for [CoroutineContext]. */ public class SentryContext : ThreadContextElement<IHub>, AbstractCoroutineContextElement(Key) { private companion object Key : CoroutineContext.Key<SentryContext> private val hub: IHub = Sentry.getCurrentHub().clone() override fun updateThreadContext(context: CoroutineContext): IHub { val oldState = Sentry.getCurrentHub() Sentry.setCurrentHub(hub) return oldState } override fun restoreThreadContext(context: CoroutineContext, oldState: IHub) { Sentry.setCurrentHub(oldState) } }
sentry-kotlin-extensions/src/main/java/io/sentry/kotlin/SentryContext.kt
3299142569
import java.io.File import java.util.* fun main(args: Array<String>) { val input = File(args[0]).readText().split(" ").mapNotNull { it.toIntOrNull() } assert(score(9, 25) == 32L) assert(score(10, 1618) == 8317L) assert(score(13, 7999) == 146373L) assert(score(17, 1104) == 2764L) assert(score(21, 6111) == 54718L) assert(score(30, 5807) == 37305L) println(score(input[0], input[1] * 100)) } fun score(nPlayers: Int, lastMarble: Int): Long { val circle = LinkedList<Int>() val players = LongArray(nPlayers) circle.add(0) for (i in 1..lastMarble) { if (i % 23 == 0) { circle.rotate(7) players[i % nPlayers] = players[i % nPlayers] + circle.removeLast() + i circle.rotate(-1) } else { circle.rotate(-1) circle.addLast(i) } } return players.max()!! } private fun <E> LinkedList<E>.rotate(n: Int) { if(n > 0) repeat(n) { addFirst(removeLast()) } else repeat(-n) { addLast(removeFirst()) } }
advent_of_code/2018/solutions/day_9_b.kt
2620629768
package de.treichels.hott.voice import org.apache.commons.io.IOUtils import java.io.ByteArrayInputStream import java.io.IOException import java.io.InputStream import java.util.* /** * Codec to encode / decode ADPCM (VOX) audio data. * * see [http://faculty.salina.k-state.edu/tim/vox/dialogic_adpcm.pdf](http://faculty.salina.k-state.edu/tim/vox/dialogic_adpcm.pdf) for details. * * @author [email protected] */ class ADPCMCodec { /** index into step size table */ private var index = 0 /** last PCM value */ private var last = 0 /** * Decode an ADPCM encoded 4-bit sample to 16-bit signed PCM. * * @param adpcm ADPCM encoded sample (4 bit) * @return The decoded PCM value (12 bit signed) */ fun decode(adpcm: Byte): Short { // convert byte into BitSet val bits = BitSet.valueOf(byteArrayOf(adpcm)) // current step size val stepSize = STEP_SIZES[index] // calculate difference var diff = stepSize shr 3 // magnitude bit 3 if (bits[2]) diff += stepSize // magnitude bit 2 if (bits[1]) diff += stepSize shr 1 // magnitude bit 1 if (bits[0]) diff += stepSize shr 2 // sign if (bits[3]) diff = -diff // new PCM value last += diff // clipping if (last > MAX_PCM) last = MAX_PCM if (last < MIN_PCM) last = MIN_PCM // new step size index += QUANTIZER[adpcm.toInt() and 7] // clipping if (index < MIN_INDEX) index = MIN_INDEX if (index > MAX_INDEX) index = MAX_INDEX return last.toShort() } /** * Encode a 16-bit signed PCM value to 4-bit ADPCM. * * @param pcm * The PCM value (12 bit signed) * @return The ADPCM encoded sample (4 bit) */ fun encode(pcm: Short): Byte { var stepSize = STEP_SIZES[index] var diff = pcm - last val bits = BitSet(4) // sign if (diff < 0) { bits[3] = true diff = -diff } // magnitude bit 3 if (diff >= stepSize) { bits[2] = true diff -= stepSize } // magnitude bit 2 stepSize = stepSize shr 1 if (diff >= stepSize) { bits[1] = true diff -= stepSize } // magnitude bit 1 stepSize = stepSize shr 1 if (diff >= stepSize) bits[0] = true val adpcm = if (bits.isEmpty) 0 else bits.toByteArray()[0] last = decode(adpcm).toInt() return adpcm } companion object { private val QUANTIZER = intArrayOf(-1, -1, -1, -1, 2, 4, 6, 8) private val STEP_SIZES = intArrayOf(7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767) private const val MIN_PCM = -2048 // 12-bit private const val MAX_PCM = 2047 // 12-bit private const val MIN_INDEX = 0 private val MAX_INDEX = STEP_SIZES.size - 1 /** * Decode 4-bit ADPCM encoded data to 16-bit signed PCM (compression ratio 1:4). * * @param data * ADPCM encoded data. Each byte contains two 4-bit samples. * @return The PCM decoded data. * @throws IOException */ fun decode(data: ByteArray): ByteArray { return IOUtils.toByteArray(decode(ByteArrayInputStream(data))) } /** * Decode 4-bit ADPCM encoded data to 16-bit signed PCM (compression ratio 1:4). * * @param source * A stream of ADPCM encoded data. Each byte contains two 4-bit samples. * @return A stream of PCM data. * @throws IOException */ fun decode(source: InputStream): InputStream { return DecodingInputStream(source) } /** * Encode 16-bit signed PCM data to 4-bit ADPCM encoded data (compression ratio 4:1). * * @param data * The PCM data. * * @return The ADPCM encoded data. Each byte contains two 4-bit samples. * @throws IOException */ fun encode(data: ByteArray): ByteArray { return IOUtils.toByteArray(encode(ByteArrayInputStream(data))) } /** * Encode 16-bit signed PCM data to 4-bit ADPCM encoded data (compression ratio 4:1). * * @param source * A stream of PCM data. * @return A stream of ADPCM encoded data. Each byte contains two 4-bit samples. * @throws IOException */ @JvmOverloads fun encode(source: InputStream, volume: Double = 1.0): InputStream { return EncodingInputStream(source, volume) } } }
HoTT-Voice/src/main/kotlin/de/treichels/hott/voice/ADPCMCodec.kt
114254417
/** * BreadWallet * * Created by Ahsan Butt <[email protected]> on 12/09/20. * Copyright (c) 2020 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.ui.uigift import android.content.SharedPreferences import androidx.core.content.edit private const val KEY_GIFT_PREFIX = "gift-pk-" private const val KEY_GIFT_STATE_PREFIX = "gift-state-" data class GiftCopy( val address: String, val privateKey: String, val isUsed: Boolean = false ) interface GiftBackup { fun putGift(gift: GiftCopy) fun removeUnusedGift(address: String) fun markGiftIsUsed(address: String) fun getAllGifts(): List<GiftCopy> } class SharedPrefsGiftBackup( private val createStore: () -> SharedPreferences? ) : GiftBackup { private val store: SharedPreferences? by lazy { createStore() } override fun putGift(gift: GiftCopy) { checkNotNull(store).edit { putString(gift.address.giftKey(), gift.privateKey) putBoolean(gift.address.giftStateKey(), gift.isUsed) } } override fun removeUnusedGift(address: String) { val store = checkNotNull(store) if (!store.getBoolean(address.giftStateKey(), false)) { store.edit { remove(address.giftKey()) remove(address.giftStateKey()) } } } override fun markGiftIsUsed(address: String) { checkNotNull(store).edit { putBoolean(address.giftStateKey(), true) } } override fun getAllGifts(): List<GiftCopy> { val all = checkNotNull(store).all return all.keys .filter { it.startsWith(KEY_GIFT_PREFIX) } .map { key -> val address = key.substringAfter(KEY_GIFT_PREFIX) GiftCopy( address, all[key] as String, all[address.giftStateKey()] as Boolean ) } } private fun String.giftKey() = "$KEY_GIFT_PREFIX$this" private fun String.giftStateKey() = "$KEY_GIFT_STATE_PREFIX$this" }
ui/ui-gift/src/main/java/GiftBackup.kt
915606687
package link.continuum.desktop.database import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import java.util.concurrent.ConcurrentHashMap /** * save and and get newest values * update names and avatar urls in real time */ open class LatestFlowMap<K, V>( private val init: suspend (K)-> Pair<Long, V>, private val save: suspend (K, V, Long) -> Unit ){ private val scope = CoroutineScope(Dispatchers.Default) private val flows = ConcurrentHashMap<K, UpdatableValue>() /** * set latest value if newer than existing */ suspend fun update(key: K, value: V, time: Long) { getUpdatable(key).update(key, value, time) } fun receiveUpdates(key: K): Flow<V?> { val up = getUpdatable(key) return up.observable } private fun getUpdatable(key: K): UpdatableValue { return flows.computeIfAbsent(key) { UpdatableValue().also { scope.launch { val (t, v) = init(key) it.update(key, v, t) } }} } private inner class UpdatableValue() { private val mutex = Mutex() private var timestamp = 0L private val _observable = MutableStateFlow<V?>(null) val observable: StateFlow<V?> get() = _observable suspend fun update(key: K, value: V, time: Long) { mutex.withLock { if (time < timestamp) return if (timestamp == time && _observable.value == value) return timestamp = time _observable.value = value save(key, value, time) } } } }
src/main/kotlin/link/continuum/desktop/database/storeLatest.kt
3399819418
/* * Copyright 2016 lizhaotailang * * 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.marktony.zhihudaily.data import android.annotation.SuppressLint import android.arch.persistence.room.ColumnInfo import android.os.Parcelable import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** * Created by lizhaotailang on 2017/6/17. * * Immutable model class for guokr handpick content image info. See the json string for more details. * Entity class for [com.google.gson.Gson] and [android.arch.persistence.room.Room]. */ @Parcelize @SuppressLint("ParcelCreator") data class GuokrHandpickContentImageInfo( @ColumnInfo(name = "image_info_url") @Expose @SerializedName("url") val url: String, @ColumnInfo(name = "image_info_width") @Expose @SerializedName("width") val width: Int, @ColumnInfo(name = "image_info_height") @Expose @SerializedName("height") val height: Int ) : Parcelable
app/src/main/java/com/marktony/zhihudaily/data/GuokrHandpickContentImageInfo.kt
541655223
package com.orgzly.android.ui.notes import android.content.Context import android.view.MotionEvent import androidx.core.view.GestureDetectorCompat import androidx.recyclerview.widget.RecyclerView import com.orgzly.BuildConfig import com.orgzly.android.util.LogUtils class ItemGestureDetector(context: Context, private val listener: Listener) : RecyclerView.OnItemTouchListener { private val gestureDetector = GestureDetectorCompat(context, object: OnSwipeListener() { override fun onSwipe(direction: Direction, e1: MotionEvent, e2: MotionEvent): Boolean { if (direction == Direction.RIGHT) { listener.onSwipe(1, e1, e2) return true } else if (direction == Direction.LEFT) { listener.onSwipe(-1, e1, e2) return true } return false } }) override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, e.action) } override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean { // if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, e.action) return gestureDetector.onTouchEvent(e) } override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) { } interface Listener { fun onSwipe(direction: Int, e1: MotionEvent, e2: MotionEvent) } companion object { private val TAG = ItemGestureDetector::class.java.name } }
app/src/main/java/com/orgzly/android/ui/notes/ItemGestureDetector.kt
131750619
import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.* class GreetPlugin : Plugin<Project> { override fun apply(project: Project): Unit = project.run { tasks { register("greet") { group = "sample" description = "Prints a description of ${project.name}." doLast { println("I'm ${project.name}.") } } } } }
samples/buildSrc-plugin/buildSrc/src/main/kotlin/GreetPlugin.kt
1002946808
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo.issues import com.fasterxml.jackson.annotation.JsonTypeInfo import com.fasterxml.jackson.annotation.JsonTypeName import org.junit.Test import org.litote.kmongo.AllCategoriesKMongoBaseTest import kotlin.test.assertTrue @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "value") sealed class SealedClass @JsonTypeName("A") data class A(val s: String = "s") : SealedClass() @JsonTypeName("B") data class B(val i: Int = 1) : SealedClass() class Issue247SealedClassInsertMany : AllCategoriesKMongoBaseTest<SealedClass>() { @Test fun `test insert and load`() { col.insertOne(A()) col.insertOne(B()) assertTrue(col.find().toList().contains(A())) assertTrue(col.find().toList().contains(B())) } @Test fun `test insert many and load`() { col.insertMany(listOf(A(), B())) assertTrue(col.find().toList().contains(A())) assertTrue(col.find().toList().contains(B())) } }
kmongo/src/test/kotlin/org/litote/kmongo/issues/Issue247SealedClassInsertMany.kt
1783365230
/* Copyright 2015 Andreas Würl 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.blitzortung.android.map.overlay import android.graphics.Canvas import android.graphics.Paint import android.graphics.Point import org.osmdroid.api.IGeoPoint import org.osmdroid.views.MapView import org.osmdroid.views.Projection class StrikeShape(private val center: IGeoPoint) : LightningShape { override fun isPointInside(tappedGeoPoint: IGeoPoint, projection: Projection): Boolean { val shapeCenter = Point() projection.toPixels(center, shapeCenter) val tappedPoint = Point() projection.toPixels(tappedGeoPoint, tappedPoint) return tappedPoint.x >= shapeCenter.x - size / 2 && tappedPoint.x <= shapeCenter.x + size / 2 && tappedPoint.y >= shapeCenter.y - size / 2 && tappedPoint.y <= shapeCenter.y + size / 2 } private var size: Float = 0.toFloat() private var color: Int = 0 override fun draw(canvas: Canvas, mapView: MapView, paint: Paint) { mapView.projection.toPixels(center, centerPoint) //Only draw it when its visible if (canvas.quickReject( centerPoint.x - size / 2, centerPoint.y - size / 2, centerPoint.x + size / 2, centerPoint.y + size / 2, Canvas.EdgeType.BW)) { return } paint.color = color paint.style = Paint.Style.STROKE paint.strokeWidth = size / 4 canvas.drawLine( centerPoint.x - size / 2, centerPoint.y.toFloat(), centerPoint.x + size / 2, centerPoint.y.toFloat(), paint) canvas.drawLine( centerPoint.x.toFloat(), centerPoint.y - size / 2, centerPoint.x.toFloat(), centerPoint.y + size / 2, paint) } fun update(size: Float, color: Int) { this.size = size this.color = color } companion object { private val centerPoint = Point() } }
app/src/main/java/org/blitzortung/android/map/overlay/StrikeShape.kt
4234586851
package net.ketc.numeri.presentation.view.activity.ui import android.content.Context import android.support.design.widget.AppBarLayout import android.support.v7.widget.Toolbar import net.ketc.numeri.presentation.view.activity.UserInfoActivity import org.jetbrains.anko.appcompat.v7.toolbar import org.jetbrains.anko.design.appBarLayout import org.jetbrains.anko.design.collapsingToolbarLayout import org.jetbrains.anko.design.coordinatorLayout import android.support.design.widget.AppBarLayout.LayoutParams.* import android.support.design.widget.CollapsingToolbarLayout import org.jetbrains.anko.* import android.support.design.widget.CollapsingToolbarLayout.LayoutParams.* import android.support.design.widget.TabLayout import android.support.v4.view.ViewPager import android.support.v4.widget.SwipeRefreshLayout import android.text.TextUtils import android.view.Gravity import android.view.View import android.view.ViewManager import android.widget.* import net.ketc.numeri.R import net.ketc.numeri.util.android.* import org.jetbrains.anko.custom.ankoView import org.jetbrains.anko.design.tabLayout import org.jetbrains.anko.support.v4.swipeRefreshLayout import org.jetbrains.anko.support.v4.viewPager class UserInfoActivityUI : IUserInfoActivityUI { override lateinit var swipeRefresh: SwipeRefreshLayout private set override lateinit var appBar: AppBarLayout private set override lateinit var toolbar: Toolbar private set override lateinit var collapsingToolbar: CollapsingToolbarLayout private set override lateinit var headerImage: ImageView private set override lateinit var iconRelative: RelativeLayout private set override lateinit var iconImage: ImageView private set override lateinit var infoRelative: RelativeLayout private set override lateinit var userNameText: TextView private set override lateinit var screenNameText: TextView private set override lateinit var descriptionText: TextView private set override lateinit var locationText: TextView private set override lateinit var subInfoText: TextView private set override lateinit var userProfileTabLayout: TabLayout private set override lateinit var pager: ViewPager private set override lateinit var followButton: ImageButton private set override lateinit var protectedImage: ImageView private set override lateinit var relationInfoText: TextView private set override lateinit var profileEditButton: Button private set override fun createView(ui: AnkoContext<UserInfoActivity>) = with(ui) { swipeRefreshLayout { swipeRefresh = this isEnabled = false coordinatorLayout { appBarLayout { appBar = this backgroundColor = color(R.color.colorPrimaryDark) collapsingToolbarLayout { collapsingToolbar = this isTitleEnabled = false setContentScrimColor(color(R.color.transparent)) userProfileContent(this) userProfileHeader(this) userProfileIcon(this) toolbar { toolbar = this background = drawable(R.drawable.app_bar_gradation) navigationIcon = drawable(resourceId(android.R.attr.homeAsUpIndicator)) }.collapsingToolbarlparams(matchParent, dimen(R.dimen.app_bar_standard_height)) { expandedTitleGravity = Gravity.BOTTOM or Gravity.START collapseMode = COLLAPSE_MODE_PIN } }.lparams(matchParent, matchParent) { scrollFlags = SCROLL_FLAG_SCROLL or SCROLL_FLAG_EXIT_UNTIL_COLLAPSED } }.lparams(matchParent, wrapContent) coordinatorLayout { relativeLayout { tabLayout { userProfileTabLayout = this id = R.id.user_profile_tab tabMode = TabLayout.MODE_SCROLLABLE }.lparams(matchParent, wrapContent) viewPager { pager = this id = R.id.pager offscreenPageLimit = 5 }.lparams(matchParent, matchParent) { below(R.id.user_profile_tab) } }.lparams(matchParent, matchParent) }.lparams(matchParent, matchParent) { behavior = AppBarLayout.ScrollingViewBehavior() } } } } //collapsingToolbarContent private fun AnkoContext<*>.userProfileContent(manager: ViewManager) = manager.relativeLayout { infoRelative = this headerImageView { id = R.id.dummy_header visibility = View.INVISIBLE }.lparams(matchParent, wrapContent) relativeLayout { id = R.id.buttons_relative imageButton { followButton = this isClickable = false background = drawable(R.drawable.ripple_frame) scaleType = ImageView.ScaleType.CENTER_INSIDE visibility = View.INVISIBLE }.lparams(matchParent, matchParent) button { profileEditButton = this visibility = View.GONE text = string(R.string.edit_profile) }.lparams(matchParent, matchParent) }.lparams(dip(72), dip(40)) { marginTop = dimen(R.dimen.margin_medium) marginEnd = dimen(R.dimen.margin_medium) below(R.id.dummy_header) alignParentEnd() } relativeLayout { textView { userNameText = this id = R.id.user_name_text maxLines = 1 ellipsize = TextUtils.TruncateAt.END textSizeDimen = R.dimen.text_size_large textColor = color(resourceId(android.R.attr.textColorPrimary)) }.lparams(wrapContent, wrapContent) { marginBottom = dimen(R.dimen.margin_text_small) } relativeLayout { imageView { protectedImage = this backgroundColor = color(R.color.transparent) image = drawable(R.drawable.ic_lock_outline_white_24dp) scaleType = ImageView.ScaleType.CENTER_INSIDE }.lparams(dip(16), dip(16)) { centerVertically() } }.lparams(wrapContent, wrapContent) { endOf(R.id.user_name_text) sameTop(R.id.user_name_text) sameBottom((R.id.user_name_text)) alignParentEnd() marginStart = dimen(R.dimen.margin_medium) } textView { screenNameText = this id = R.id.screen_name_text maxLines = 1 ellipsize = TextUtils.TruncateAt.END textSizeDimen = R.dimen.text_size_small textColor = color(resourceId(android.R.attr.textColorSecondary)) }.lparams(wrapContent, wrapContent) { bottomOf(R.id.user_name_text) marginBottom = dimen(R.dimen.margin_text_medium) } textView { relationInfoText = this maxLines = 1 ellipsize = TextUtils.TruncateAt.END textSizeDimen = R.dimen.text_size_small textColor = color(resourceId(android.R.attr.textColorSecondary)) }.lparams(wrapContent, wrapContent) { endOf(R.id.screen_name_text) bottomOf(R.id.user_name_text) marginStart = dimen(R.dimen.margin_text_small) alignParentEnd() } textView { descriptionText = this id = R.id.description_text textSizeDimen = R.dimen.text_size_medium textColor = color(resourceId(android.R.attr.textColorPrimary)) }.lparams(wrapContent, wrapContent) { bottomOf(R.id.screen_name_text) marginBottom = dimen(R.dimen.margin_text_small) } textView { locationText = this id = R.id.location_text textSizeDimen = R.dimen.text_size_medium ellipsize = TextUtils.TruncateAt.END maxLines = 1 textColor = color(resourceId(android.R.attr.textColorPrimary)) }.lparams(wrapContent, wrapContent) { bottomOf(R.id.description_text) marginBottom = dimen(R.dimen.margin_text_small) } textView { subInfoText = this textSizeDimen = R.dimen.text_size_small textColor = color(resourceId(android.R.attr.textColorSecondary)) }.lparams(wrapContent, wrapContent) { bottomOf(R.id.location_text) } }.lparams(matchParent, matchParent) { margin = dimen(R.dimen.margin_medium) bottomOf(R.id.buttons_relative) alignParentStart() } }.collapsingToolbarlparams(matchParent, matchParent) { collapseMode = COLLAPSE_MODE_OFF } private fun AnkoContext<*>.userProfileHeader(manager: ViewManager) = manager.relativeLayout { id = R.id.header_relative headerImageView { id = R.id.header_image headerImage = this scaleType = ImageView.ScaleType.CENTER_CROP }.lparams(matchParent, wrapContent) view { this.background = drawable(R.drawable.header_image_gradation) }.lparams(matchParent, wrapContent) { sameBottom(R.id.header_image) sameTop(R.id.header_image) } }.collapsingToolbarlparams(wrapContent, wrapContent) { collapseMode = COLLAPSE_MODE_PIN } private fun AnkoContext<*>.userProfileIcon(manager: ViewManager) = manager.relativeLayout { id = R.id.icon_frame headerImageView { id = R.id.dummy_header2 visibility = View.INVISIBLE }.lparams(matchParent, wrapContent) relativeLayout { iconRelative = this imageView { iconImage = this backgroundColor = color(R.color.image_background) }.lparams(dip(53), dip(53)) { centerInParent() } view { background = drawable(R.drawable.image_frame) }.lparams(dip(56), dip(56)) }.lparams(wrapContent, wrapContent) { sameBottom(R.id.dummy_header2) marginBottom = dimen(R.dimen.margin_large) } }.collapsingToolbarlparams(wrapContent, wrapContent) { collapseMode = COLLAPSE_MODE_OFF margin = dimen(R.dimen.margin_medium) marginTop = dimen(R.dimen.app_bar_standard_height) } class HeaderImageView(ctx: Context) : ImageView(ctx) { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val widthSize = MeasureSpec.getSize(widthMeasureSpec) val heightSize = widthSize / 3 //3:1 setMeasuredDimension(widthSize, heightSize) } } private inline fun ViewManager.headerImageView(theme: Int = 0, init: HeaderImageView.() -> Unit): ImageView { return ankoView(::HeaderImageView, theme) { init() } } } interface IUserInfoActivityUI : AnkoComponent<UserInfoActivity> { val swipeRefresh: SwipeRefreshLayout val appBar: AppBarLayout val toolbar: Toolbar val collapsingToolbar: CollapsingToolbarLayout val headerImage: ImageView val iconImage: ImageView val iconRelative: RelativeLayout val infoRelative: RelativeLayout val userNameText: TextView val screenNameText: TextView val descriptionText: TextView val locationText: TextView val subInfoText: TextView val userProfileTabLayout: TabLayout val pager: ViewPager val followButton: ImageButton val protectedImage: ImageView val relationInfoText: TextView val profileEditButton: Button }
app/src/main/kotlin/net/ketc/numeri/presentation/view/activity/ui/UserInfoActivityUI.kt
1445415422
package com.bubelov.coins.editplace import androidx.lifecycle.ViewModel import com.bubelov.coins.data.Place import com.bubelov.coins.repository.place.PlacesRepository import com.bubelov.coins.util.BasicTaskState import kotlinx.coroutines.* import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import retrofit2.HttpException class EditPlaceViewModel( private val placesRepository: PlacesRepository ) : ViewModel() { fun submitChanges( originalPlace: Place?, updatedPlace: Place ): Flow<BasicTaskState> { return flow { emit(BasicTaskState.Progress) try { if (originalPlace == null) { placesRepository.addPlace(updatedPlace) } else { placesRepository.updatePlace(updatedPlace) } emit(BasicTaskState.Success) } catch (httpException: HttpException) { val message = withContext(Dispatchers.IO) { httpException.response()?.errorBody()?.string() ?: "Unknown error" } emit(BasicTaskState.Error(message)) } catch (e: Exception) { emit(BasicTaskState.Error(e.message ?: "")) } } } }
app/src/main/java/com/bubelov/coins/editplace/EditPlaceViewModel.kt
165173631
package chat.rocket.android.dynamiclinks import android.content.Context import android.content.Intent import android.net.Uri import androidx.core.net.toUri import chat.rocket.android.R import com.google.firebase.dynamiclinks.DynamicLink import com.google.firebase.dynamiclinks.FirebaseDynamicLinks import com.google.firebase.dynamiclinks.ShortDynamicLink import timber.log.Timber import javax.inject.Inject class DynamicLinksForFirebase @Inject constructor(private var context: Context) : DynamicLinks { private var deepLink: Uri? = null private var newDeepLink: String? = null override fun getDynamicLink(intent: Intent, deepLinkCallback: (Uri?) -> Unit?) { FirebaseDynamicLinks.getInstance() .getDynamicLink(intent) .addOnSuccessListener { pendingDynamicLinkData -> if (pendingDynamicLinkData != null) { deepLink = pendingDynamicLinkData.link } deepLinkCallback(deepLink) } .addOnFailureListener { Timber.e("getDynamicLink:onFailure : $it") } } override fun createDynamicLink( username: String, server: String, deepLinkCallback: (String?) -> Unit? ) { FirebaseDynamicLinks.getInstance().createDynamicLink() .setLink("$server/direct/$username".toUri()) .setDomainUriPrefix("https://" + context.getString(R.string.dynamic_link_host_url)) .setAndroidParameters( DynamicLink.AndroidParameters.Builder(context.packageName).build() ) .setSocialMetaTagParameters( DynamicLink.SocialMetaTagParameters.Builder() .setTitle(username) .setDescription( context.getString( R.string.msg_dynamic_link_description, username, server ) ) .build() ) .buildShortDynamicLink(ShortDynamicLink.Suffix.SHORT) .addOnSuccessListener { result -> Timber.i("DynamicLink created: $newDeepLink") newDeepLink = result.shortLink.toString() deepLinkCallback(newDeepLink) }.addOnFailureListener { Timber.e("Error creating dynamicLink.") deepLinkCallback(null) } } }
app/src/play/java/chat/rocket/android/dynamiclinks/DynamicLinksForFirebase.kt
814225676
/* * Copyright (C) 2014 Contentful GmbH * * 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.contentful.java.cma.lib import com.contentful.java.cma.CMACallback import retrofit.RetrofitError import java.util.concurrent.CountDownLatch class TestCallback<T>(val allowEmpty: Boolean = false) : CMACallback<T>() { val cdl: CountDownLatch var value: T = null var error: RetrofitError? = null init { cdl = CountDownLatch(1) } override fun onSuccess(result: T) { value = result cdl.countDown() } override fun onFailure(retrofitError: RetrofitError?) { super<CMACallback>.onFailure(retrofitError) error = retrofitError cdl.countDown() } throws(InterruptedException::class) public fun await() { cdl.await() } }
src/test/kotlin/com/contentful/java/cma/lib/TestCallback.kt
283309624
package me.tatarka.silentsupport.gradle import com.android.build.gradle.AppExtension import com.android.build.gradle.AppPlugin import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.Task class SilentSupportPlugin : Plugin<Project> { override fun apply(project: Project) { project.plugins.withType(AppPlugin::class.java) { plugin -> val android = project.extensions.getByType(AppExtension::class.java) val transform = SilentSupportTransform(project) val tasks = HashSet<Task>() android.registerTransform(transform, tasks) android.applicationVariants.all { variant -> transform.putVariant(variant) val task = transform.getOrCreateSupportMetadataTask(variant) if (task != null) { tasks.add(task) } } project.dependencies.add( "compile", if (isReleased) "me.tatarka.silentsupport:silent-support-lib:$version" else project.project(":silent-support-lib") ) android.lintOptions { it.disable("NewApi") it.enable("NewApiSupport") } } } private val isReleased: Boolean get() = javaClass.getPackage().implementationVersion != null private val version: String get() = javaClass.getPackage().implementationVersion }
silent-support-gradle-plugin/src/main/kotlin/me/tatarka/silentsupport/gradle/SilentSupportPlugin.kt
588782173
package com.github.prologdb.runtime.module data class ModuleReference( /** * The alias for the path pointing to the module files parent directory, * e.g. `library` or `system`. */ val pathAlias: String, val moduleName: String ) { override fun toString(): String { return "$pathAlias($moduleName)" } }
core/src/main/kotlin/com/github/prologdb/runtime/module/ModuleReference.kt
2958108911
package org.maxur.sofarc.core.service.jackson import com.fasterxml.jackson.annotation.JsonAutoDetect import com.fasterxml.jackson.annotation.PropertyAccessor import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.datatype.jdk8.Jdk8Module import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import com.fasterxml.jackson.module.kotlin.KotlinModule import com.fasterxml.jackson.module.paranamer.ParanamerModule import dk.nykredit.jackson.dataformat.hal.JacksonHALModule import org.glassfish.hk2.api.Factory class ObjectMapperProvider : Factory<ObjectMapper> { private val objectMapper: ObjectMapper = ObjectMapper() init { objectMapper.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE) .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE) .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE) .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY) .registerModule(KotlinModule()) .registerModule(Jdk8Module()) .registerModule(ParanamerModule()) .registerModule(JavaTimeModule()) .registerModule(JacksonHALModule()) } override fun dispose(instance: ObjectMapper?) { // IGNORE } override fun provide(): ObjectMapper { return objectMapper; } }
sofarc-core/src/main/kotlin/org/maxur/sofarc/core/service/jackson/ObjectMapperProvider.kt
874699821
package com.anbillon.debuggerview import android.util.TypedValue import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView /** * @author Cosouly ([email protected]) */ internal abstract class ConfigAdapter : BaseAdapter() { abstract override fun getItem(position: Int): String? override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, view: View?, container: ViewGroup): View { val ret = view ?: LayoutInflater.from(container.context) .inflate(android.R.layout.simple_spinner_item, container, false) bindView(getItem(position), ret) return ret } override fun getDropDownView(position: Int, view: View?, container: ViewGroup): View { val ret = view ?: LayoutInflater.from(container.context) .inflate(android.R.layout.simple_spinner_item, container, false) bindView(getItem(position), ret) return ret } private fun bindView(item: String?, view: View) { val holder: ViewHolder if (view.tag is ViewHolder) { holder = view.tag as ViewHolder } else { holder = ViewHolder() view.tag = holder holder.textView = view.findViewById(android.R.id.text1) as? TextView holder.textView?.let { val padding = view.resources.getDimension(R.dimen.padding).toInt() it.setPadding(padding, padding, padding, padding) it.setTextSize(TypedValue.COMPLEX_UNIT_PX, view.resources.getDimension(R.dimen.font_normal)) it.setTextColor(view.resources.getColor(R.color.text_secondary)) it.gravity = Gravity.CENTER } } holder.textView?.text = item } private class ViewHolder { internal var textView: TextView? = null } }
debugger/src/main/java/com/anbillon/debuggerview/ConfigAdapter.kt
3622266840
package edu.kit.iti.formal.automation.testtables.print import edu.kit.iti.formal.automation.testtables.GetetaFacade import edu.kit.iti.formal.automation.testtables.grammar.TestTableLanguageParser import edu.kit.iti.formal.automation.testtables.model.* import edu.kit.iti.formal.util.CodeWriter import java.util.* import kotlin.collections.set /** * @author Alexander Weigl * @version 1 (07.08.18) */ /** * */ interface TablePrinter { /** * Prints header information needed for standalone documents. * TeX-preamble or html head */ fun printPreamble() /** * Prints only the table. */ fun print() /** * Closing statements for the standalone document. */ fun printPostamble() } /** * PrintCellContent holds printing information about table cells. */ data class PrintCellContent( /** Content to be displayed */ var content: String = "", /** position in a down streaming group */ var groupPosition: Int = 0, /** signals if the cell was empty and only filled by "down streaming" */ var originalEmpty: Boolean = false, /** signals if the cell is the end of a "down streaming" */ var endGroup: Boolean = false ) { val beginGroup: Boolean get() = groupPosition == 0 val singleGroup: Boolean get() = endGroup && secondInGroup val secondInGroup: Boolean get() = groupPosition == 1 val inBetween: Boolean get() = !beginGroup && !endGroup } /** * A serializer for table cells. */ typealias CellPrinter = (TestTableLanguageParser.CellContext) -> String /** * This class helps printer with serialization of the table cell contents. */ class PrinterHelper(gtt: GeneralizedTestTable, val cellPrinter: CellPrinter) { val states = gtt.region.flat() val columns = LinkedHashMap<String, List<PrintCellContent>>() init { gtt.programVariables.forEach { columns[it.name] = calculateColumn(it) } } fun calculateColumn(column: ColumnVariable): List<PrintCellContent> { var previousContent = GetetaFacade.parseCell("-").cell()!! val seq = states.map { PrintCellContent() } var currentGroupDuration = 0 for (i in 0 until seq.size) { val v = states[i].rawFields[column] val c = seq[i] if (v != null) { previousContent = v c.content = cellPrinter(v) c.groupPosition = 0 currentGroupDuration = 0 if (i != 0) { seq[i - 1].endGroup = true } } else { c.originalEmpty = true c.content = cellPrinter(previousContent) c.groupPosition = ++currentGroupDuration } } return seq } } /** * [Counter] offers a multiple counters identified by a string */ class Counter { private val counter = LinkedHashMap<String, Int>() fun peek(s: String): Int = counter.computeIfAbsent(s) { _ -> 0 } fun getAndIncrement(s: String): Int { val peek = peek(s) counter[s] = peek + 1 return peek } } /** * Base class for TablePrinter. * * This class provides visitor functions that get called during table visialization. */ abstract class AbstractTablePrinter(protected val gtt: GeneralizedTestTable, protected val stream: CodeWriter) : TablePrinter { protected lateinit var helper: PrinterHelper protected var currentRow = 0 val input = gtt.programVariables.filter { it.isAssumption } val output = gtt.programVariables.filter { it.isAssertion } val durations = Stack<Pair<Duration, Int>>() val depth = gtt.region.depth() fun init() { helper = PrinterHelper(gtt, this::cellFormatter) } override fun printPreamble() {} override fun printPostamble() {} protected open fun contentBegin() {} protected open fun tableBegin() {} protected open fun tableEnd() {} protected open fun contentEnd() {} protected open fun regionEnd() {} protected open fun regionBegin() {} protected open fun rowBegin() {} protected open fun rowEnd() {} protected open fun printGroupDuration(dur: Duration, rowSpan: Int) {} protected open fun printCell(v: ColumnVariable, row: TableRow) { if(v is ProjectionVariable) printCell(v, row) if(v is ProgramVariable) printCell(v, row) } protected open fun printCell(v: ProgramVariable, row: TableRow) {} protected open fun printCell(v: ProjectionVariable, row: TableRow) {} protected open fun printRowDuration(duration: Duration) {} override fun print() { contentBegin() tableBegin() printRegion(gtt.region.children) tableEnd() contentEnd() } private fun printRegion(region: List<TableNode>) { region.forEach { o -> when (o) { is TableRow -> printStep(o) is Region -> { regionBegin() printRegion(o) regionEnd() } } } } private fun printRegion(b: Region) { durations.push(b.duration to b.count()) printRegion(b.children) } private fun printStep(s: TableRow) { rowBegin() input.forEach { v -> printCell(v, s) } output.forEach { v -> printCell(v, s) } printRowDuration(s.duration) while (!durations.empty()) { val (dur, rowSpan) = durations.pop() printGroupDuration(dur, rowSpan) } rowEnd() currentRow++ } abstract fun cellFormatter(c: TestTableLanguageParser.CellContext): String }
geteta/src/main/kotlin/edu/kit/iti/formal/automation/testtables/print/base.kt
1939336600
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.input import javafx.scene.input.KeyCode import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test /** * * * @author Almas Baimagambetov ([email protected]) */ class InputModifierTest { @Test fun `Convert Shift from MouseEvent`() { val e = mouseEvent(true, false, false) val modifier = InputModifier.from(e) assertThat(modifier, `is`(InputModifier.SHIFT)) } @Test fun `Convert Ctrl from MouseEvent`() { val e = mouseEvent(false, true, false) val modifier = InputModifier.from(e) assertThat(modifier, `is`(InputModifier.CTRL)) } @Test fun `Convert Alt from MouseEvent`() { val e = mouseEvent(false, false, true) val modifier = InputModifier.from(e) assertThat(modifier, `is`(InputModifier.ALT)) } @Test fun `Convert from MouseEvent`() { val e = mouseEvent(false, false, false) val modifier = InputModifier.from(e) assertThat(modifier, `is`(InputModifier.NONE)) } @Test fun `Convert Shift from KeyEvent`() { val e = keyEvent(true, false, false) val modifier = InputModifier.from(e) assertThat(modifier, `is`(InputModifier.SHIFT)) } @Test fun `Convert Ctrl from KeyEvent`() { val e = keyEvent(false, true, false) val modifier = InputModifier.from(e) assertThat(modifier, `is`(InputModifier.CTRL)) } @Test fun `Convert Alt from KeyEvent`() { val e = keyEvent(false, false, true) val modifier = InputModifier.from(e) assertThat(modifier, `is`(InputModifier.ALT)) } @Test fun `Convert from KeyEvent`() { val e = keyEvent(false, false, false) val modifier = InputModifier.from(e) assertThat(modifier, `is`(InputModifier.NONE)) } @Test fun `Is triggered mouse`() { assertTrue(InputModifier.SHIFT.isTriggered(mouseEvent(true, false, false))) assertTrue(InputModifier.CTRL.isTriggered(mouseEvent(false, true, false))) assertTrue(InputModifier.ALT.isTriggered(mouseEvent(false, false, true))) assertTrue(InputModifier.NONE.isTriggered(mouseEvent(false, false, false))) assertFalse(InputModifier.NONE.isTriggered(mouseEvent(true, false, false))) assertFalse(InputModifier.NONE.isTriggered(mouseEvent(false, true, false))) assertFalse(InputModifier.NONE.isTriggered(mouseEvent(false, false, true))) } @Test fun `Is triggered key`() { assertTrue(InputModifier.SHIFT.isTriggered(keyEvent(true, false, false))) assertTrue(InputModifier.CTRL.isTriggered(keyEvent(false, true, false))) assertTrue(InputModifier.ALT.isTriggered(keyEvent(false, false, true))) assertTrue(InputModifier.NONE.isTriggered(keyEvent(false, false, false))) assertFalse(InputModifier.NONE.isTriggered(keyEvent(true, false, false))) assertFalse(InputModifier.NONE.isTriggered(keyEvent(false, true, false))) assertFalse(InputModifier.NONE.isTriggered(keyEvent(false, false, true))) } @Test fun `To KeyCode`() { assertTrue(InputModifier.ALT.toKeyCode() == KeyCode.ALT) assertTrue(InputModifier.CTRL.toKeyCode() == KeyCode.CONTROL) assertTrue(InputModifier.SHIFT.toKeyCode() == KeyCode.SHIFT) assertTrue(InputModifier.NONE.toKeyCode() == KeyCode.ALPHANUMERIC) } // private fun mouseEvent(shift: Boolean, ctrl: Boolean, alt: Boolean): MouseEvent { // return MouseEvent(MouseEvent.ANY, 0.0, 0.0, 0.0, 0.0, MouseButton.PRIMARY, 1, // shift, ctrl, alt, // false, false, false, false, false, false, false, null) // } // // private fun keyEvent(shift: Boolean, ctrl: Boolean, alt: Boolean): KeyEvent { // return KeyEvent(KeyEvent.ANY, "", "", KeyCode.A, shift, ctrl, alt, false) // } }
fxgl-core/src/test/kotlin/com/almasb/fxgl/input/InputModifierTest.kt
2291299251
package com.binlly.fastpeak.business.demo.fragment import android.view.View import com.binlly.fastpeak.R import com.binlly.fastpeak.base.glide.progress.OnGlideImageViewListener import com.binlly.fastpeak.base.mvp.BaseMvpFragment import com.binlly.fastpeak.base.rx.RxObserver import com.binlly.fastpeak.business.demo.model.DemoModel import com.binlly.fastpeak.ext.load import com.binlly.fastpeak.ext.loadCircle import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.GlideException import kotlinx.android.synthetic.main.fragment_demo.* import org.jetbrains.anko.coroutines.experimental.bg import org.jetbrains.anko.toast /** * Created by yy on 2017/8/25. */ class DemoFragment: BaseMvpFragment<DemoFragmentPresenter>(), DemoFragmentContract.View { private var count = 0 override fun getContentViewId(): Int { return R.layout.fragment_demo } private lateinit var images: ArrayList<String> override fun initView() { // setPageEmpty() setPageSucceed() images = arrayListOf("http://www.sogoupc.com/uploads/allimg/120309/1-1203091U601.jpg", "http://pic4.bbzhi.com/fengjingbizhi/gaoqingkuanpingfengjingbizhixiazai/gaoqingkuanpingfengjingbizhixiazai_404987_10.jpg", "http://www.sogoupc.com/uploads/allimg/120309/1-1203091U525.jpg", "http://www.1tong.com/uploads/wallpaper/landscapes/404-2-1440x900.jpg", "http://pic1.win4000.com/wallpaper/b/51fb21b44fcc6.jpg") P.requestImageList(object: RxObserver<DemoFragmentModel>() { override fun onNext(result: DemoFragmentModel) { super.onNext(result) images = result.image_list } }) image_1.loadCircle(R.color.colorPrimary) image_1.setOnClickListener { Glide.get(context).clearMemory() bg { Glide.get(context).clearDiskCache() } context.toast("清空图片缓存") } image_2.load(images[0]) image_2.setOnClickListener { image_2.load(images[++count % images.size], listener = object: OnGlideImageViewListener { override fun onProgress(percent: Int, isDone: Boolean, exception: GlideException?) { println("下载中:$percent") progress.visibility = if (isDone) View.GONE else View.VISIBLE progress.progress = percent } }) } // refresh() } private fun refresh() { setPageLoading() P.requestDemo(object: RxObserver<DemoModel>() { override fun onNext(model: DemoModel) { setPageSucceed() context.toast(model.toString()) } override fun onError(e: Throwable) { super.onError(e) setPageError() e.message ?: return context.toast(e.message.toString()) } override fun onComplete() { super.onComplete() context.toast("onComplete") } }) P.requestImageList(object: RxObserver<DemoFragmentModel>() { override fun onNext(result: DemoFragmentModel) { super.onNext(result) images = result.image_list image_2.load(images[count % images.size], listener = object: OnGlideImageViewListener { override fun onProgress(percent: Int, isDone: Boolean, exception: GlideException?) { println("下载中:$percent") progress.visibility = if (isDone) View.GONE else View.VISIBLE progress.progress = percent } }) } }) } override fun onReload() { super.onReload() context.toast("reload") refresh() } }
app/src/main/java/com/binlly/fastpeak/business/demo/fragment/DemoFragment.kt
1407032539
package flavor.pie.kludge import java.io.BufferedReader import java.io.BufferedWriter import java.io.InputStream import java.io.OutputStream import java.nio.channels.SeekableByteChannel import java.nio.charset.Charset import java.nio.file.CopyOption import java.nio.file.DirectoryStream import java.nio.file.FileStore import java.nio.file.FileVisitOption import java.nio.file.FileVisitor import java.nio.file.Files import java.nio.file.LinkOption import java.nio.file.OpenOption import java.nio.file.Path import java.nio.file.attribute.BasicFileAttributes import java.nio.file.attribute.FileAttribute import java.nio.file.attribute.FileAttributeView import java.nio.file.attribute.FileTime import java.nio.file.attribute.PosixFilePermission import java.nio.file.attribute.UserPrincipal import java.util.function.BiPredicate import kotlin.streams.asSequence /** * @see Files.newInputStream */ fun Path.newInputStream(vararg options: OpenOption): InputStream = Files.newInputStream(this, *options) /** * @see Files.newOutputStream */ fun Path.newOutputStream(vararg options: OpenOption): OutputStream = Files.newOutputStream(this, *options) /** * @see Files.newByteChannel */ fun Path.newByteChannel(vararg options: OpenOption): SeekableByteChannel = Files.newByteChannel(this, *options) /** * @see Files.newByteChannel */ fun Path.newByteChannel(options: Set<OpenOption>, vararg attributes: FileAttribute<*>): SeekableByteChannel = Files.newByteChannel(this, options, *attributes) /** * @see Files.newDirectoryStream */ fun Path.newDirectoryStream(): DirectoryStream<Path> = Files.newDirectoryStream(this) /** * @see Files.newDirectoryStream */ fun Path.newDirectoryStream(glob: String): DirectoryStream<Path> = Files.newDirectoryStream(this, glob) /** * @see Files.newDirectoryStream */ fun Path.newDirectoryStream(filter: DirectoryStream.Filter<in Path>): DirectoryStream<Path> = Files.newDirectoryStream(this, filter) /** * @see Files.createFile */ fun Path.createFile(vararg attrs: FileAttribute<*>): Path = Files.createFile(this, *attrs) /** * @see Files.createDirectory */ fun Path.createDirectory(vararg attrs: FileAttribute<*>): Path = Files.createDirectory(this, *attrs) /** * @see Files.createDirectories */ fun Path.createDirectories(vararg attrs: FileAttribute<*>): Path = Files.createDirectories(this, *attrs) /** * @see Files.createTempFile */ fun Path.createTempFile(prefix: String, suffix: String, vararg attrs: FileAttribute<*>): Path = Files.createTempFile(this, prefix, suffix, *attrs) /** * @see Files.createTempDirectory */ fun Path.createTempDirectory(prefix: String, vararg attrs: FileAttribute<*>): Path = Files.createTempDirectory(this, prefix, *attrs) /** * @see Files.createSymbolicLink */ fun Path.createSymbolicLink(target: Path, vararg attrs: FileAttribute<*>): Path = Files.createSymbolicLink(this, target, *attrs) /** * @see Files.createLink */ fun Path.createLink(existing: Path): Path = Files.createLink(this, existing) /** * @see Files.delete */ fun Path.delete() = Files.delete(this) /** * @see Files.deleteIfExists */ fun Path.deleteIfExists() = Files.deleteIfExists(this) /** * @see Files.copy */ fun Path.copy(target: Path, vararg options: CopyOption): Path = Files.copy(this, target, *options) /** * @see Files.move */ fun Path.move(target: Path, vararg options: CopyOption): Path = Files.copy(this, target, *options) /** * @see Files.readSymbolicLink */ fun Path.readSymbolicLink(): Path = Files.readSymbolicLink(this) /** * @see Files.getFileStore */ fun Path.getFileStore(): FileStore = Files.getFileStore(this) /** * @see Files.isSameFile */ fun Path.isSameFile(path2: Path): Boolean = Files.isSameFile(this, path2) /** * @see Files.isHidden */ fun Path.isHidden(): Boolean = Files.isHidden(this) /** * @see Files.probeContentType */ fun Path.probeContentType(): String? = Files.probeContentType(this) /** * @see Files.getFileAttributeView */ inline fun <reified V : FileAttributeView> Path.getFileAttributeView(vararg options: LinkOption): V? = Files.getFileAttributeView(this, V::class.java, *options) /** * @see Files.readAttributes */ inline fun <reified A : BasicFileAttributes> Path.readAttributes(vararg options: LinkOption): A = Files.readAttributes(this, A::class.java, *options) /** * @see Files.setAttribute */ fun Path.setAttribute(attribute: String, value: Any, vararg options: LinkOption): Path = Files.setAttribute(this, attribute, value, *options) /** * @see Files.getAttribute */ fun Path.getAttribute(attribute: String, vararg options: LinkOption): Any = Files.getAttribute(this, attribute, *options) /** * @see Files.readAttributes */ fun Path.readAttributes(attributes: String, vararg options: LinkOption): Map<String, Any> = Files.readAttributes(this, attributes, *options) /** * @see Files.getPosixFilePermissions */ fun Path.getPosixFilePermissions(vararg options: LinkOption): Set<PosixFilePermission> = Files.getPosixFilePermissions(this, *options) /** * @see Files.getPosixFilePermissions * @see Files.setPosixFilePermissions */ var Path.posixFilePermissions: Set<PosixFilePermission> get() = Files.getPosixFilePermissions(this) set(value) { Files.setPosixFilePermissions(this, value) } /** * @see Files.getOwner */ fun Path.getOwner(vararg options: LinkOption): UserPrincipal = Files.getOwner(this, *options) /** * @see Files.getOwner * @see Files.setOwner */ var Path.owner: UserPrincipal get() = Files.getOwner(this) set(value) { Files.setOwner(this, value) } /** * @see Files.isSymbolicLink */ val Path.isSymbolicLink: Boolean get() = Files.isSymbolicLink(this) /** * @see Files.isDirectory */ val Path.isDirectory: Boolean get() = Files.isDirectory(this) /** * @see Files.isDirectory */ fun Path.isDirectory(vararg options: LinkOption): Boolean = Files.isDirectory(this, *options) /** * @see Files.isRegularFile */ val Path.isRegularFile: Boolean get() = Files.isRegularFile(this) /** * @see Files.isRegularFile */ fun Path.isRegularFile(vararg options: LinkOption): Boolean = Files.isRegularFile(this, *options) /** * @see Files.getLastModifiedTime */ fun Path.getLastModifiedTime(vararg options: LinkOption): FileTime = Files.getLastModifiedTime(this, *options) /** * @see Files.getLastModifiedTime * @see Files.setLastModifiedTime */ var Path.lastModifiedTime: FileTime get() = Files.getLastModifiedTime(this) set(value) { Files.setLastModifiedTime(this, value) } /** * @see Files.size */ val Path.size: Long get() = Files.size(this) /** * @see Files.exists */ fun Path.exists(vararg options: LinkOption): Boolean = Files.exists(this, *options) /** * @see Files.exists */ val Path.exists: Boolean get() = Files.exists(this) /** * @see Files.notExists */ fun Path.notExists(vararg options: LinkOption): Boolean = Files.notExists(this, *options) /** * @see Files.notExists */ val Path.notExists: Boolean get() = Files.notExists(this) /** * @see Files.isReadable */ val Path.isReadable: Boolean get() = Files.isReadable(this) /** * @see Files.isWritable */ val Path.isWritable: Boolean get() = Files.isWritable(this) /** * @see Files.isExecutable */ val Path.isExecutable: Boolean get() = Files.isExecutable(this) /** * @see Files.walkFileTree */ fun Path.walkFileTree(options: Set<FileVisitOption>, maxDepth: Int, visitor: FileVisitor<in Path>): Path = Files.walkFileTree(this, options, maxDepth, visitor) /** * @see Files.walkFileTree */ fun Path.walkFileTree(visitor: FileVisitor<in Path>): Path = Files.walkFileTree(this, visitor) /** * @see Files.newBufferedReader */ fun Path.newBufferedReader(cs: Charset): BufferedReader = Files.newBufferedReader(this, cs) /** * @see Files.newBufferedReader */ fun Path.newBufferedReader(): BufferedReader = Files.newBufferedReader(this) /** * @see Files.newBufferedWriter */ fun Path.newBufferedWriter(cs: Charset, vararg options: OpenOption): BufferedWriter = Files.newBufferedWriter(this, cs, *options) /** * @see Files.newBufferedWriter */ fun Path.newBufferedWriter(vararg options: OpenOption): BufferedWriter = Files.newBufferedWriter(this, *options) /** * @see Files.copy */ fun Path.copy(`in`: InputStream, vararg options: CopyOption): Long = Files.copy(`in`, this, *options) /** * @see Files.copy */ fun Path.copy(out: OutputStream): Long = Files.copy(this, out) /** * @see Files.readAllBytes */ fun Path.readAllBytes(): ByteArray = Files.readAllBytes(this) /** * @see Files.readAllLines */ fun Path.readAllLines(): List<String> = Files.readAllLines(this) /** * @see Files.readAllLines */ fun Path.readAllLines(cs: Charset): List<String> = Files.readAllLines(this, cs) /** * @see Files.write */ fun Path.write(bytes: ByteArray, vararg options: OpenOption): Path = Files.write(this, bytes, *options) /** * @see Files.write */ fun Path.write(lines: Iterable<CharSequence>, cs: Charset, vararg options: OpenOption): Path = Files.write(this, lines, cs, *options) /** * @see Files.write */ fun Path.write(lines: Iterable<CharSequence>, vararg options: OpenOption): Path = Files.write(this, lines, *options) /** * @see Files.list */ fun Path.list(): Sequence<Path> = Files.list(this).asSequence() /** * @see Files.walk */ fun Path.walk(maxDepth: Int, vararg options: FileVisitOption): Sequence<Path> = Files.walk(this, maxDepth, *options).asSequence() /** * @see Files.walk */ fun Path.walk(vararg options: FileVisitOption): Sequence<Path> = Files.walk(this, *options).asSequence() /** * @see Files.find */ fun Path.find( maxDepth: Int, matcher: (Path, BasicFileAttributes) -> Boolean, vararg options: FileVisitOption ): Sequence<Path> = Files.find(this, maxDepth, BiPredicate(matcher), *options).asSequence() /** * @see Files.lines */ fun Path.lines(cs: Charset): Sequence<String> = Files.lines(this, cs).asSequence() /** * @see Files.lines */ fun Path.lines(): Sequence<String> = Files.lines(this).asSequence()
src/main/kotlin/flavor/pie/kludge/files.kt
594838422
/******************************************************************************* * * * Copyright (C) 2017 by Max Lv <[email protected]> * * Copyright (C) 2017 by Mygod Studio <[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.github.shadowsocks import android.annotation.TargetApi import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient class AboutFragment : ToolbarFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.layout_about, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) toolbar.title = getString(R.string.about_title, BuildConfig.VERSION_NAME) val web = view.findViewById<WebView>(R.id.web_view) web.loadUrl("file:///android_asset/pages/about.html") web.webViewClient = object : WebViewClient() { @Suppress("OverridingDeprecatedMember") override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { (activity as MainActivity).launchUrl(url) return true } @TargetApi(Build.VERSION_CODES.LOLLIPOP) override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest): Boolean { (activity as MainActivity).launchUrl(request.url) return true } } } }
mobile/src/main/java/com/github/shadowsocks/AboutFragment.kt
173393846
/******************************************************************************* * * * Copyright (C) 2017 by Max Lv <[email protected]> * * Copyright (C) 2017 by Mygod Studio <[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.github.shadowsocks.database import android.util.Log import com.github.shadowsocks.App.Companion.app import com.github.shadowsocks.ProfilesFragment import com.github.shadowsocks.preference.DataStore import com.github.shadowsocks.utils.DirectBoot import java.sql.SQLException /** * SQLExceptions are not caught (and therefore will cause crash) for insert/update transactions * to ensure we are in a consistent state. */ object ProfileManager { private const val TAG = "ProfileManager" @Throws(SQLException::class) fun createProfile(p: Profile? = null): Profile { val profile = p ?: Profile() profile.id = 0 val oldProfile = app.currentProfile if (oldProfile != null) { // Copy Feature Settings from old profile profile.route = oldProfile.route profile.ipv6 = oldProfile.ipv6 profile.proxyApps = oldProfile.proxyApps profile.bypass = oldProfile.bypass profile.individual = oldProfile.individual profile.udpdns = oldProfile.udpdns } val last = PrivateDatabase.profileDao.queryRaw(PrivateDatabase.profileDao.queryBuilder() .selectRaw("MAX(userOrder)").prepareStatementString()).firstResult if (last != null && last.size == 1 && last[0] != null) profile.userOrder = last[0].toLong() + 1 PrivateDatabase.profileDao.createOrUpdate(profile) ProfilesFragment.instance?.profilesAdapter?.add(profile) return profile } /** * Note: It's caller's responsibility to update DirectBoot profile if necessary. */ @Throws(SQLException::class) fun updateProfile(profile: Profile) = PrivateDatabase.profileDao.update(profile) fun getProfile(id: Int): Profile? = try { PrivateDatabase.profileDao.queryForId(id) } catch (ex: SQLException) { Log.e(TAG, "getProfile", ex) app.track(ex) null } @Throws(SQLException::class) fun delProfile(id: Int) { PrivateDatabase.profileDao.deleteById(id) ProfilesFragment.instance?.profilesAdapter?.removeId(id) if (id == DataStore.profileId && DataStore.directBootAware) DirectBoot.clean() } fun getFirstProfile(): Profile? = try { PrivateDatabase.profileDao.query(PrivateDatabase.profileDao.queryBuilder().limit(1L).prepare()).singleOrNull() } catch (ex: SQLException) { Log.e(TAG, "getFirstProfile", ex) app.track(ex) null } fun getAllProfiles(): List<Profile>? = try { PrivateDatabase.profileDao.query(PrivateDatabase.profileDao.queryBuilder().orderBy("userOrder", true).prepare()) } catch (ex: SQLException) { Log.e(TAG, "getAllProfiles", ex) app.track(ex) null } }
mobile/src/main/java/com/github/shadowsocks/database/ProfileManager.kt
1658067784
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.essentials.bukkit.command import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.service.Services import com.rpkit.essentials.bukkit.RPKEssentialsBukkit import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import com.rpkit.tracking.bukkit.tracking.RPKTrackingService import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class ToggleTrackingCommand(private val plugin: RPKEssentialsBukkit) : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { if (sender !is Player) { sender.sendMessage(plugin.messages["not-from-console"]) return true } if (!sender.hasPermission("rpkit.essentials.command.toggletracking")) { sender.sendMessage(plugin.messages["no-permission-toggle-tracking"]) return true } val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] if (minecraftProfileService == null) { sender.sendMessage(plugin.messages["no-minecraft-profile-service"]) return true } val characterService = Services[RPKCharacterService::class.java] if (characterService == null) { sender.sendMessage(plugin.messages["no-character-service"]) return true } val trackingService = Services[RPKTrackingService::class.java] if (trackingService == null) { sender.sendMessage(plugin.messages["no-tracking-service"]) return true } val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(sender) if (minecraftProfile == null) { sender.sendMessage(plugin.messages["no-minecraft-profile"]) return true } val character = characterService.getPreloadedActiveCharacter(minecraftProfile) if (character == null) { sender.sendMessage(plugin.messages["no-character-self"]) return true } trackingService.isTrackable(character).thenAccept { isTrackable -> val newIsTrackable = !isTrackable trackingService.setTrackable(character, newIsTrackable).thenRun { if (newIsTrackable) { sender.sendMessage(plugin.messages["toggle-tracking-on-valid"]) } else { sender.sendMessage(plugin.messages["toggle-tracking-off-valid"]) } } } return true } }
bukkit/rpk-essentials-bukkit/src/main/kotlin/com/rpkit/essentials/bukkit/command/ToggleTrackingCommand.kt
1260413047
/* * ************************************************************************************************* * Copyright 2017 Universum Studios * ************************************************************************************************* * 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 universum.studios.gradle.github.release.data.model import org.gradle.api.artifacts.PublishArtifact import java.io.File /** * Simple model containing properties describing asset associated with a specific release used locally * by the GitHub plugin. * * @author Martin Albedinsky * @since 1.0 * * @property id Id of the asset. * @property name Name of the asset. * @property file File that the asset represents. * @property fileContentType Type of the content that the asset file represents. * @property baseUploadUrl Base url that should be used to build full url for upload. * @constructor Creates a new instance of Asset with the specified property values. */ data class Asset( val id: Int = 0, val name: String, val file: File, val fileContentType: String = Asset.CONTENT_TYPE, val baseUploadUrl: String = Asset.BASE_UPLOAD_URL) { /** */ companion object Contract { /** * Default content type of asset file. */ const val CONTENT_TYPE = "application/octet-stream" /** * Default value for base upload url. */ const val BASE_UPLOAD_URL = "https://uploads.github.com/" } /** * Builder which may be used to build a name for a specific [Asset] using properties of the * corresponding [PublishArtifact] and of the specified release name. * * @author Martin Albedinsky * @since 1.0 */ class NameBuilder { /** * */ private var name: String? = null /** * */ private var version: String? = null /** * */ private var classifier: String? = null /** * */ private var type: String? = null /** * Specifies a name of asset of which full name to build. * * @param name The desired name. * @return This builder to allow methods chaining. */ fun name(name: String?): NameBuilder { this.name = name return this } /** * Specifies a version name of asset of which full name to build. * * @param version The desired version name. * @return This builder to allow methods chaining. */ fun version(version: String?) : NameBuilder { this.version = version return this } /** * Specifies a classifier of asset of which full name to build. * * @param classifier The desired classifier. * @return This builder to allow methods chaining. */ fun classifier(classifier: String?): NameBuilder { this.classifier = classifier return this } /** * Specifies a type of asset of which full name to build. * * @param type The desired type. * @return This builder to allow methods chaining. */ fun type(type: String?): NameBuilder { this.type = type return this } /** * Builds name property for [Asset] from the properties specified for this builder. * * @return The appropriate asset name. */ fun build(): String { var assetName = name ?: return "" if (!version.isNullOrEmpty()) { assetName += "-$version" } if (!classifier.isNullOrEmpty()) { assetName += "-$classifier" } if (!type.isNullOrEmpty()) { assetName += ".$type" } return assetName } } }
plugin/src/releases/kotlin/universum/studios/gradle/github/release/data/model/Asset.kt
1751125813
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.locks.bukkit.database.table import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.core.location.RPKBlockLocation import com.rpkit.locks.bukkit.RPKLocksBukkit import com.rpkit.locks.bukkit.database.create import com.rpkit.locks.bukkit.database.jooq.Tables.RPKIT_LOCKED_BLOCK import com.rpkit.locks.bukkit.database.jooq.tables.records.RpkitLockedBlockRecord import com.rpkit.locks.bukkit.lock.RPKLockedBlock import java.util.concurrent.CompletableFuture import java.util.logging.Level class RPKLockedBlockTable(private val database: Database, private val plugin: RPKLocksBukkit) : Table { private data class BlockCacheKey( val worldName: String, val x: Int, val y: Int, val z: Int ) private val cache = if (plugin.config.getBoolean("caching.rpkit_locked_block.block.enabled")) { database.cacheManager.createCache("rpk-locks-bukkit.rpkit_locked_block.block", BlockCacheKey::class.javaObjectType, RPKLockedBlock::class.java, plugin.config.getLong("caching.rpkit_locked_block.block.size") ) } else { null } fun insert(entity: RPKLockedBlock): CompletableFuture<Void> { val block = entity.block val cacheKey = BlockCacheKey(block.world, block.x, block.y, block.z) return CompletableFuture.runAsync { database.create .insertInto( RPKIT_LOCKED_BLOCK, RPKIT_LOCKED_BLOCK.WORLD, RPKIT_LOCKED_BLOCK.X, RPKIT_LOCKED_BLOCK.Y, RPKIT_LOCKED_BLOCK.Z ) .values( block.world, block.x, block.y, block.z ) .execute() cache?.set(cacheKey, entity) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to insert locked block", exception) throw exception } } operator fun get(block: RPKBlockLocation): CompletableFuture<RPKLockedBlock?> { val cacheKey = BlockCacheKey(block.world, block.x, block.y, block.z) if (cache?.containsKey(cacheKey) == true) { return CompletableFuture.completedFuture(cache[cacheKey]) } return CompletableFuture.supplyAsync { database.create .select( RPKIT_LOCKED_BLOCK.WORLD, RPKIT_LOCKED_BLOCK.X, RPKIT_LOCKED_BLOCK.Y, RPKIT_LOCKED_BLOCK.Z ) .from(RPKIT_LOCKED_BLOCK) .where(RPKIT_LOCKED_BLOCK.WORLD.eq(block.world)) .and(RPKIT_LOCKED_BLOCK.X.eq(block.x)) .and(RPKIT_LOCKED_BLOCK.Y.eq(block.y)) .and(RPKIT_LOCKED_BLOCK.Z.eq(block.z)) .fetchOne() ?: return@supplyAsync null val lockedBlock = RPKLockedBlock(block) cache?.set(cacheKey, lockedBlock) return@supplyAsync lockedBlock }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to get locked block", exception) throw exception } } fun getAll(): CompletableFuture<List<RPKLockedBlock>> { return CompletableFuture.supplyAsync { return@supplyAsync database.create .selectFrom(RPKIT_LOCKED_BLOCK) .fetch() .mapNotNull { it.toDomain() } }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to get locked blocks", exception) throw exception } } private fun RpkitLockedBlockRecord.toDomain(): RPKLockedBlock { return RPKLockedBlock( block = RPKBlockLocation(world, x, y, z) ) } fun delete(entity: RPKLockedBlock): CompletableFuture<Void> { val block = entity.block val cacheKey = BlockCacheKey(block.world, block.x, block.y, block.z) return CompletableFuture.runAsync { database.create .deleteFrom(RPKIT_LOCKED_BLOCK) .where(RPKIT_LOCKED_BLOCK.WORLD.eq(block.world)) .and(RPKIT_LOCKED_BLOCK.X.eq(block.x)) .and(RPKIT_LOCKED_BLOCK.Y.eq(block.y)) .and(RPKIT_LOCKED_BLOCK.Z.eq(block.z)) .execute() cache?.remove(cacheKey) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to delete locked block", exception) throw exception } } }
bukkit/rpk-locks-bukkit/src/main/kotlin/com/rpkit/locks/bukkit/database/table/RPKLockedBlockTable.kt
922640904
/* * Copyright (c) 2020 Giorgio Antonioli * * 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.fondesa.recyclerviewdivider import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.test.ext.junit.runners.AndroidJUnit4 import com.fondesa.recyclerviewdivider.test.context import com.fondesa.recyclerviewdivider.test.gridLayoutManager import com.fondesa.recyclerviewdivider.test.linearLayoutManager import com.fondesa.recyclerviewdivider.test.rtl import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config /** * Tests of CreateGrid.kt file. */ @RunWith(AndroidJUnit4::class) class CreateGridKtTest { @Test fun `grid - vertical LinearLayoutManager`() { val layoutManager = linearLayoutManager(Orientation.VERTICAL, false) RecyclerView(context).layoutManager = layoutManager val expectedGrid = Grid( spanCount = 1, orientation = Orientation.VERTICAL, layoutDirection = LayoutDirection( horizontal = LayoutDirection.Horizontal.LEFT_TO_RIGHT, vertical = LayoutDirection.Vertical.TOP_TO_BOTTOM ), lines = listOf( Line(cells = listOf(Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1))) ) ) val actualGrid = layoutManager.grid(4) assertEquals(expectedGrid, actualGrid) } @Config(minSdk = 17) @Test fun `grid - horizontal RTL LinearLayoutManager`() { val layoutManager = linearLayoutManager(Orientation.HORIZONTAL, false) RecyclerView(context).rtl().layoutManager = layoutManager val expectedGrid = Grid( spanCount = 1, orientation = Orientation.HORIZONTAL, layoutDirection = LayoutDirection( horizontal = LayoutDirection.Horizontal.RIGHT_TO_LEFT, vertical = LayoutDirection.Vertical.TOP_TO_BOTTOM ), lines = listOf( Line(cells = listOf(Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1))) ) ) val actualGrid = layoutManager.grid(4) assertEquals(expectedGrid, actualGrid) } @Test fun `grid - vertical GridLayoutManager, 1 column`() { val layoutManager = gridLayoutManager(1, Orientation.VERTICAL, false) RecyclerView(context).layoutManager = layoutManager val expectedGrid = Grid( spanCount = 1, orientation = Orientation.VERTICAL, layoutDirection = LayoutDirection( horizontal = LayoutDirection.Horizontal.LEFT_TO_RIGHT, vertical = LayoutDirection.Vertical.TOP_TO_BOTTOM ), lines = listOf( Line(cells = listOf(Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1))) ) ) val actualGrid = layoutManager.grid(4) assertEquals(expectedGrid, actualGrid) } @Test fun `grid - horizontal reversed GridLayoutManager, 1 row`() { val layoutManager = gridLayoutManager(1, Orientation.HORIZONTAL, true) RecyclerView(context).layoutManager = layoutManager val expectedGrid = Grid( spanCount = 1, orientation = Orientation.HORIZONTAL, layoutDirection = LayoutDirection( horizontal = LayoutDirection.Horizontal.RIGHT_TO_LEFT, vertical = LayoutDirection.Vertical.TOP_TO_BOTTOM ), lines = listOf( Line(cells = listOf(Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1))) ) ) val actualGrid = layoutManager.grid(4) assertEquals(expectedGrid, actualGrid) } @Test fun `grid - vertical reversed GridLayoutManager, multiple equal columns`() { val layoutManager = gridLayoutManager(2, Orientation.VERTICAL, true) RecyclerView(context).layoutManager = layoutManager val expectedGrid = Grid( spanCount = 2, orientation = Orientation.VERTICAL, layoutDirection = LayoutDirection( horizontal = LayoutDirection.Horizontal.LEFT_TO_RIGHT, vertical = LayoutDirection.Vertical.BOTTOM_TO_TOP ), lines = listOf( Line(cells = listOf(Cell(spanSize = 1), Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1), Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1), Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1), Cell(spanSize = 1))) ) ) val actualGrid = layoutManager.grid(8) assertEquals(expectedGrid, actualGrid) } @Test fun `grid - horizontal GridLayoutManager, multiple equal columns`() { val layoutManager = gridLayoutManager(3, Orientation.HORIZONTAL, false) RecyclerView(context).layoutManager = layoutManager val expectedGrid = Grid( spanCount = 3, orientation = Orientation.HORIZONTAL, layoutDirection = LayoutDirection( horizontal = LayoutDirection.Horizontal.LEFT_TO_RIGHT, vertical = LayoutDirection.Vertical.TOP_TO_BOTTOM ), lines = listOf( Line(cells = listOf(Cell(spanSize = 1), Cell(spanSize = 1), Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1), Cell(spanSize = 1), Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1), Cell(spanSize = 1), Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1), Cell(spanSize = 1), Cell(spanSize = 1))) ) ) val actualGrid = layoutManager.grid(12) assertEquals(expectedGrid, actualGrid) } @Test fun `grid - vertical GridLayoutManager, multiple columns with different spans`() { val layoutManager = gridLayoutManager(3, Orientation.VERTICAL, false) layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int = when (position) { 0, 3, 7 -> 2 else -> 1 } } RecyclerView(context).layoutManager = layoutManager val expectedGrid = Grid( spanCount = 3, orientation = Orientation.VERTICAL, layoutDirection = LayoutDirection( horizontal = LayoutDirection.Horizontal.LEFT_TO_RIGHT, vertical = LayoutDirection.Vertical.TOP_TO_BOTTOM ), lines = listOf( Line(cells = listOf(Cell(spanSize = 2), Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 1), Cell(spanSize = 2))), Line(cells = listOf(Cell(spanSize = 1), Cell(spanSize = 1), Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 2))) ) ) val actualGrid = layoutManager.grid(8) assertEquals(expectedGrid, actualGrid) } @Test fun `grid - horizontal GridLayoutManager, multiple columns with different spans`() { val layoutManager = gridLayoutManager(3, Orientation.HORIZONTAL, false) layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int = when (position) { 3, 6 -> 3 5 -> 2 else -> 1 } } RecyclerView(context).layoutManager = layoutManager val expectedGrid = Grid( spanCount = 3, orientation = Orientation.HORIZONTAL, layoutDirection = LayoutDirection( horizontal = LayoutDirection.Horizontal.LEFT_TO_RIGHT, vertical = LayoutDirection.Vertical.TOP_TO_BOTTOM ), lines = listOf( Line(cells = listOf(Cell(spanSize = 1), Cell(spanSize = 1), Cell(spanSize = 1))), Line(cells = listOf(Cell(spanSize = 3))), Line(cells = listOf(Cell(spanSize = 1), Cell(spanSize = 2))), Line(cells = listOf(Cell(spanSize = 3))), Line(cells = listOf(Cell(spanSize = 1))) ) ) val actualGrid = layoutManager.grid(8) assertEquals(expectedGrid, actualGrid) } }
recycler-view-divider/src/test/kotlin/com/fondesa/recyclerviewdivider/CreateGridKtTest.kt
2663627796
package cn.yiiguxing.plugin.translate.action import cn.yiiguxing.plugin.translate.util.w import com.intellij.openapi.actionSystem.* import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile abstract class PsiElementTranslateAction : AnAction() { final override fun update(e: AnActionEvent) { val editor = e.editor val psiFile = e.psiFile e.presentation.isEnabledAndVisible = if (editor != null && psiFile != null && psiFile.isValid) { val dataContext = e.dataContext val element = try { pickPsiElement(editor, psiFile, dataContext) } catch (e: Throwable) { LOG.w("Failed to pick PSI element", e) null } element?.let { it.isValid && isEnabledForElement(editor, it, dataContext) } ?: false } else { false } } protected open fun pickPsiElement(editor: Editor, psiFile: PsiFile, dataContext: DataContext): PsiElement? { return dataContext.getData(LangDataKeys.PSI_ELEMENT) } protected abstract fun isEnabledForElement(editor: Editor, element: PsiElement, dataContext: DataContext): Boolean final override fun actionPerformed(e: AnActionEvent) { val editor = e.editor ?: return val psiFile = e.psiFile ?: return val dataContext = e.dataContext val element = try { pickPsiElement(editor, psiFile, dataContext) ?: return } catch (e: Throwable) { LOG.w("Failed to pick PSI element", e) return } doTranslate(editor, element, dataContext) } protected abstract fun doTranslate(editor: Editor, element: PsiElement, dataContext: DataContext) companion object { private val LOG = Logger.getInstance(PsiElementTranslateAction::class.java) private val AnActionEvent.editor: Editor? get() = getData(CommonDataKeys.EDITOR) private val AnActionEvent.psiFile: PsiFile? get() = getData(LangDataKeys.PSI_FILE) } }
src/main/kotlin/cn/yiiguxing/plugin/translate/action/PsiElementTranslateAction.kt
398556806
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2016 The IdeaVim authors * * 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 2 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/>. */ @file:JvmName("UiHelper") package com.maddyhome.idea.vim.helper import com.intellij.openapi.application.ModalityState import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.wm.IdeFocusManager import java.awt.Font import javax.swing.JComponent /** * Get focus reliably. */ fun requestFocus(component: JComponent) { IdeFocusManager.findInstance().requestFocus(component, true) } /** * Run code after getting focus on request. * * @see [requestFocus] */ fun runAfterGotFocus(runnable: Runnable) { IdeFocusManager.findInstance().doWhenFocusSettlesDown(runnable, ModalityState.defaultModalityState()) } val editorFont: Font get() { val scheme = EditorColorsManager.getInstance().globalScheme return Font(scheme.editorFontName, Font.PLAIN, scheme.editorFontSize) }
src/com/maddyhome/idea/vim/helper/UiHelper.kt
2029146441
import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import fr.free.nrw.commons.Media import fr.free.nrw.commons.category.CategoryItem import fr.free.nrw.commons.location.LatLng import fr.free.nrw.commons.nearby.Label import fr.free.nrw.commons.nearby.Place import fr.free.nrw.commons.nearby.Sitelinks import fr.free.nrw.commons.upload.structure.depictions.DepictedItem import fr.free.nrw.commons.wikidata.model.DepictSearchItem import org.wikipedia.wikidata.* import java.util.* fun depictedItem( name: String = "label", description: String = "desc", imageUrl: String = "", instanceOfs: List<String> = listOf(), commonsCategories: List<CategoryItem> = listOf(), isSelected: Boolean = false, id: String = "entityId" ) = DepictedItem( name = name, description = description, imageUrl = imageUrl, instanceOfs = instanceOfs, commonsCategories = commonsCategories, isSelected = isSelected, id = id ) fun categoryItem(name: String = "name", description: String = "desc", thumbUrl: String = "thumbUrl", selected: Boolean = false) = CategoryItem(name, description, thumbUrl, selected) fun media( thumbUrl: String? = "thumbUrl", imageUrl: String? = "imageUrl", filename: String? = "filename", fallbackDescription: String? = "fallbackDescription", dateUploaded: Date? = Date(), license: String? = "license", licenseUrl: String? = "licenseUrl", author: String? = "creator", user:String?="user", pageId: String = "pageId", categories: List<String>? = listOf("categories"), coordinates: LatLng? = LatLng(0.0, 0.0, 0.0f), captions: Map<String, String> = mapOf("en" to "caption"), descriptions: Map<String, String> = mapOf("en" to "description"), depictionIds: List<String> = listOf("depictionId") ) = Media( pageId, thumbUrl, imageUrl, filename, fallbackDescription, dateUploaded, license, licenseUrl, author, user, categories, coordinates, captions, descriptions, depictionIds ) fun depictSearchItem( id: String = "id", pageId: String = "pageid", url: String = "url", label: String = "label", description: String = "description" ) = DepictSearchItem(id, pageId, url, label, description) fun place( name: String = "name", lang: String = "en", label: Label? = null, longDescription: String = "longDescription", latLng: LatLng? = null, category: String = "category", siteLinks: Sitelinks? = null, pic: String = "pic", exists: Boolean = false ): Place { return Place(lang, name, label, longDescription, latLng, category, siteLinks, pic, exists) } fun entityId(wikiBaseEntityValue: WikiBaseEntityValue = wikiBaseEntityValue()) = DataValue.EntityId(wikiBaseEntityValue) fun wikiBaseEntityValue( entityType: String = "type", id: String = "id", numericId: Long = 0 ) = WikiBaseEntityValue(entityType, id, numericId) fun statement( mainSnak: Snak_partial = snak(), rank: String = "rank", type: String = "type" ) = Statement_partial(mainSnak, type, rank) fun snak( snakType: String = "type", property: String = "property", dataValue: DataValue = valueString("") ) = Snak_partial(snakType, property, dataValue) fun valueString(value: String) = DataValue.ValueString(value) fun entity( labels: Map<String, String> = emptyMap(), descriptions: Map<String, String> = emptyMap(), statements: Map<String, List<Statement_partial>>? = emptyMap(), id: String = "id" ) = mock<Entities.Entity>().apply { val mockedLabels = labels.mockLabels() whenever(labels()).thenReturn(mockedLabels) val mockedDescriptions = descriptions.mockLabels() whenever(descriptions()).thenReturn(mockedDescriptions) whenever(this.statements).thenReturn(statements) whenever(id()).thenReturn(id) } private fun Map<String, String>.mockLabels(): Map<String, Entities.Label> { return mapValues { entry -> mock<Entities.Label>().also { whenever(it.value()).thenReturn(entry.value) } } }
app/src/test/kotlin/fr/free/nrw/commons/ModelFunctions.kt
744211053
package com.github.paolorotolo.appintro.indicator import android.content.Context import android.graphics.PorterDuff import android.view.Gravity import android.view.Gravity.CENTER import android.view.View import android.widget.ImageView import android.widget.LinearLayout import androidx.core.content.ContextCompat import com.github.paolorotolo.appintro.R /** * An [IndicatorController] that shows a list of dots and highlight the selected dot. * Use this when the number of page you're dealing with is not too high. */ class DotIndicatorController(context: Context) : IndicatorController, LinearLayout(context) { override var selectedIndicatorColor = -1 set(value) { field = value selectPosition(currentPosition) } override var unselectedIndicatorColor = -1 set(value) { field = value selectPosition(currentPosition) } private var currentPosition = 0 private var slideCount = 0 override fun newInstance(context: Context): View { val newLayoutParams = LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT ) newLayoutParams.gravity = Gravity.CENTER_VERTICAL layoutParams = newLayoutParams orientation = HORIZONTAL gravity = CENTER return this } override fun initialize(slideCount: Int) { this.slideCount = slideCount for (i in 0 until slideCount) { val dot = ImageView(this.context) dot.setImageDrawable( ContextCompat.getDrawable( this.context, R.drawable.ic_appintro_indicator_unselected ) ) val params = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ) this.addView(dot, params) } selectPosition(0) } override fun selectPosition(index: Int) { currentPosition = index for (i in 0 until slideCount) { val drawableId = if (i == index) R.drawable.ic_appintro_indicator_selected else R.drawable.ic_appintro_indicator_unselected val drawable = ContextCompat.getDrawable(this.context, drawableId) if (selectedIndicatorColor != DEFAULT_COLOR && i == index) drawable!!.mutate().setColorFilter( selectedIndicatorColor, PorterDuff.Mode.SRC_IN ) if (unselectedIndicatorColor != DEFAULT_COLOR && i != index) drawable!!.mutate().setColorFilter( unselectedIndicatorColor, PorterDuff.Mode.SRC_IN ) (getChildAt(i) as ImageView).setImageDrawable(drawable) } } }
appintro/src/main/java/com/github/paolorotolo/appintro/indicator/DotIndicatorController.kt
4263878240
package com.example.examplescomposemotionlayout import android.content.Intent import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.compose.foundation.layout.* import androidx.compose.material.Button import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.unit.dp class MainActivity : ComponentActivity() { private val composeKey = "USE_COMPOSE" private var cmap = listOf( get("CollapsingToolbar DSL") { ToolBarExampleDsl() }, get("CollapsingToolbar JSON") { ToolBarExample() }, get("ToolBarLazyExample DSL") { ToolBarLazyExampleDsl() }, get("ToolBarLazyExample JSON") { ToolBarLazyExample() }, get("MotionInLazyColumn Dsl") { MotionInLazyColumnDsl() }, get("MotionInLazyColumn JSON") { MotionInLazyColumn() }, get("DynamicGraph") { ManyGraphs() }, get("ReactionSelector") { ReactionSelector() }, ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val extra = intent.extras var cfunc: ComposeFunc? = null if (extra != null) { val composeName = extra.getString(composeKey) for (composeFunc in cmap) { if (composeFunc.toString() == composeName) { cfunc = composeFunc break } } } val com = ComposeView(this) setContentView(com) com.setContent { Surface( modifier = Modifier.fillMaxSize(), color = Color(0xFFF0E7FC) ) { if (cfunc != null) { Log.v("MAIN", " running $cfunc") cfunc.Run() } else { ComposableMenu(map = cmap) { act -> launch(act) } } } } } private fun launch(to_run: ComposeFunc) { Log.v("MAIN", " launch $to_run") val intent = Intent(this, MainActivity::class.java) intent.putExtra(composeKey, to_run.toString()) startActivity(intent) } } @Composable fun ComposableMenu(map: List<ComposeFunc>, act: (act: ComposeFunc) -> Unit) { Column( modifier = Modifier .fillMaxWidth() .padding(10.dp) ) { for (i in 0..(map.size-1)/2) { val cFunc1 = map[i*2] val cFunc2 = if ((i*2+1 < map.size)) map[i*2+1] else null Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Button(onClick = { act(cFunc1) }) { Text(cFunc1.toString(), modifier = Modifier.padding(2.dp)) } if (cFunc2 != null) { Button(onClick = { act(cFunc2) }) { val s = cFunc2.toString().substring(cFunc2.toString().indexOf(' ')+1) Text(s, modifier = Modifier.padding(2.dp)) } } } } } } fun get(name: String, cRun: @Composable () -> Unit): ComposeFunc { return object : ComposeFunc { @Composable override fun Run() { cRun() } override fun toString(): String { return name } } } interface ComposeFunc { @Composable fun Run() override fun toString(): String }
demoProjects/ExamplesComposeMotionLayout/app/src/main/java/com/example/examplescomposemotionlayout/MainActivity.kt
3856379534
package com.github.kittinunf.reactiveandroid.support.v7.widget import android.support.v7.widget.Toolbar import android.view.MenuItem import android.view.View import com.github.kittinunf.reactiveandroid.subscription.AndroidMainThreadSubscription import io.reactivex.Observable //================================================================================ // Events //================================================================================ fun Toolbar.rx_navigationClick(): Observable<View> { return Observable.create { subscriber -> setNavigationOnClickListener { subscriber.onNext(it) } subscriber.setDisposable(AndroidMainThreadSubscription { setNavigationOnClickListener(null) }) } } fun Toolbar.rx_menuItemClick(consumed: Boolean): Observable<MenuItem> { return Observable.create { subscriber -> setOnMenuItemClickListener { subscriber.onNext(it) consumed } subscriber.setDisposable(AndroidMainThreadSubscription { setOnMenuItemClickListener(null) }) } }
reactiveandroid-appcompat-v7/src/main/kotlin/com/github/kittinunf/reactiveandroid/support/v7/widget/ToolbarEvent.kt
569419120
package net.junzz.app.ui.view import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.OvalShape /** * 圆形 Drawable */ class RoundDrawable constructor(color: Int) : ShapeDrawable(OvalShape()) { init { paint.color = color } }
ui/src/main/kotlin/net/junzz/app/ui/view/RoundDrawable.kt
1479978706
package com.bracketcove.postrainer.movement import com.bracketcove.postrainer.BaseLogic import com.bracketcove.postrainer.ERROR_GENERIC import com.bracketcove.postrainer.dependencyinjection.AndroidMovementProvider import com.wiseassblog.common.ResultWrapper import com.wiseassblog.domain.domainmodel.Movement import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.launch import kotlin.coroutines.CoroutineContext class MovementLogic( private val view: MovementContract.View, private val viewModel: MovementContract.ViewModel, private val provider: AndroidMovementProvider, dispatcher: CoroutineDispatcher ) : BaseLogic<MovementEvent>(dispatcher) { override val coroutineContext: CoroutineContext get() = main + jobTracker override fun handleEvent(eventType: MovementEvent) { when (eventType){ is MovementEvent.OnStart -> getMovement(eventType.movementId) is MovementEvent.OnImageClick -> onImageClick() } } private fun onImageClick() { val imageList = viewModel.getMovement()!!.imageResourceNames val index = viewModel.getCurrentIndex() if (imageList.lastIndex == index) updateViewImage(viewModel.getImageResource(0)) else updateViewImage(viewModel.getImageResource(index + 1)) } private fun updateViewImage(imageResource: String) { view.setParallaxImage(imageResource) } private fun getMovement(movementId: String?) = launch { if (movementId != null && movementId != ""){ val result = provider.movementRepository.getMovementById(movementId) when (result) { is ResultWrapper.Success -> { viewModel.setMovement(result.value) updateView(result.value) } is ResultWrapper.Error -> handleError() } } else { handleError() } } private fun handleError() { view.showMessage(ERROR_GENERIC) view.startMovementListView() } private fun updateView(mov: Movement) { view.setTootlbarTitle(mov.name) view.setParallaxImage(mov.imageResourceNames[0]) view.setTargets(mov.targets) view.setFrequency(mov.frequency) view.setIsTimed(mov.isTimeBased) view.setTimeOrRepetitions(mov.timeOrRepetitions) view.setDifficulty(mov.difficulty) view.setDescription(mov.description) view.setInstructions(mov.instructions) view.hideProgressBar() } }
app/src/main/java/com/bracketcove/postrainer/movement/MovementLogic.kt
1722021371
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.kotlinpoet import com.google.common.io.ByteStreams import com.google.common.truth.Truth.assertThat import java.net.URI import java.nio.charset.StandardCharsets.UTF_8 import javax.tools.JavaFileObject.Kind import kotlin.test.Test class FileReadingTest { @Test fun javaFileObjectUri() { val type = TypeSpec.classBuilder("Test").build() assertThat(FileSpec.get("", type).toJavaFileObject().toUri()) .isEqualTo(URI.create("Test.kt")) assertThat(FileSpec.get("foo", type).toJavaFileObject().toUri()) .isEqualTo(URI.create("foo/Test.kt")) assertThat(FileSpec.get("com.example", type).toJavaFileObject().toUri()) .isEqualTo(URI.create("com/example/Test.kt")) } @Test fun javaFileObjectKind() { val source = FileSpec.get("", TypeSpec.classBuilder("Test").build()) assertThat(source.toJavaFileObject().kind).isEqualTo(Kind.SOURCE) } @Test fun javaFileObjectCharacterContent() { val type = TypeSpec.classBuilder("Test") .addKdoc("Pi\u00f1ata\u00a1") .addFunction(FunSpec.builder("fooBar").build()) .build() val source = FileSpec.get("foo", type) val javaFileObject = source.toJavaFileObject() // We can never have encoding issues (everything is in process) assertThat(javaFileObject.getCharContent(true)).isEqualTo(source.toString()) assertThat(javaFileObject.getCharContent(false)).isEqualTo(source.toString()) } @Test fun javaFileObjectInputStreamIsUtf8() { val source = FileSpec.builder("foo", "Test") .addType(TypeSpec.classBuilder("Test").build()) .addFileComment("Pi\u00f1ata\u00a1") .build() val bytes = ByteStreams.toByteArray(source.toJavaFileObject().openInputStream()) // KotlinPoet always uses UTF-8. assertThat(bytes).isEqualTo(source.toString().toByteArray(UTF_8)) } }
kotlinpoet/src/test/java/com/squareup/kotlinpoet/FileReadingTest.kt
2554658320
package app.opass.ccip.extension import android.text.SpannableStringBuilder import android.text.style.ClickableSpan import android.view.View import androidx.core.text.inSpans inline fun SpannableStringBuilder.clickable( crossinline onClickAction: () -> Unit, builderAction: SpannableStringBuilder.() -> Unit ) = inSpans(object : ClickableSpan() { override fun onClick(widget: View) { onClickAction() } }, builderAction = builderAction)
app/src/main/java/app/opass/ccip/extension/SpannableStringBuilder.kt
3198406664
import com.android.build.api.dsl.ApplicationExtension import com.android.build.api.variant.AndroidComponentsExtension import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.tasks.Exec import org.gradle.kotlin.dsl.register import java.io.File import java.util.* class EspressoScreenshotsPlugin : Plugin<Project> { // This is where the androidx test files service puts saved bitmaps @Suppress("SdCardPath") private val screenshotsDeviceFolder = "/sdcard/googletest/test_outputfiles" override fun apply(project: Project) { val android: ApplicationExtension = project.extensions.getByType(ApplicationExtension::class.java) val androidComponents = project.extensions.getByType(AndroidComponentsExtension::class.java) // This is where AGP writes out connected test reports val reportsDirectoryPath = "${project.buildDir}/reports/androidTests/connected/flavors/%s" android.run { productFlavors.all { val flavorName = this.name val flavorTestReportPath = reportsDirectoryPath.format(flavorName) project.run { val adbExecutable = androidComponents.sdkComponents.adb.get().asFile.invariantSeparatorsPath tasks.register<Exec>("clear${flavorName.capitalize(Locale.ROOT)}Screenshots") { group = "reporting" description = "Removes $flavorName screenshots from connected device" executable = adbExecutable args( "shell", "rm", "-rf", screenshotsDeviceFolder ) } tasks.register<Exec>("fetch${flavorName.capitalize(Locale.ROOT)}Screenshots") { group = "reporting" description = "Fetches $flavorName espresso screenshots from the device" executable = adbExecutable args( "pull", screenshotsDeviceFolder, reportsDirectoryPath.format(flavorName) ) doFirst { File(flavorTestReportPath).mkdirs() } } tasks.register<EmbedScreenshotsInTestReport>( "embed${ flavorName.capitalize( Locale.ROOT ) }Screenshots" ) { group = "reporting" description = "Embeds the $flavorName screenshots in the test report" dependsOn("fetch${flavorName.capitalize(Locale.ROOT)}Screenshots") finalizedBy("clear${flavorName.capitalize(Locale.ROOT)}Screenshots") reportsPath = flavorTestReportPath } } } if (!org.gradle.nativeplatform.platform.internal.DefaultNativePlatform.getCurrentOperatingSystem().isWindows) { project.tasks.whenTaskAdded { when (name) { "connectedGmsDebugAndroidTest" -> finalizedBy("embedGmsScreenshots") "connectedOssDebugAndroidTest" -> finalizedBy("embedOssScreenshots") } } } } } }
project/buildSrc/src/main/kotlin/EspressoScreenshotsPlugin.kt
728821451
package com.darakeon.dfm.lib.extensions import android.view.MotionEvent import android.view.MotionEvent.ACTION_DOWN import android.view.MotionEvent.ACTION_MOVE import android.view.MotionEvent.ACTION_UP import android.view.View import android.widget.GridLayout import com.darakeon.dfm.lib.Log import kotlin.math.abs fun View.changeColSpan(size: Int) { val layoutParams = layoutParams as GridLayout.LayoutParams layoutParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, size, size.toFloat()) } fun View.swipe(direction: Direction, action: () -> Unit) { swipe(direction, 1, action) } fun View.swipe(direction: Direction, fingers: Int, action: () -> Unit) { val actions = touches .getOrAdd(this, mutableMapOf()) actions.getOrAdd( direction, mutableMapOf() )[fingers] = action setOnTouchListener { view, event -> if (event.action == ACTION_UP && event.pointerCount == 1) view.performClick() touch(view, event, actions) } } private fun <K, V> MutableMap<K, V>.getOrAdd(key: K, defaultValue: V): V { if (this[key] == null) this[key] = defaultValue return this[key]!! } private var x = mutableMapOf<View, Float>() private var y = mutableMapOf<View, Float>() private var finger = mutableMapOf<View, Int>() private var touches = mutableMapOf< View, MutableMap<Direction, MutableMap<Int, () -> Unit>> >() enum class Direction { None, Up, Left, Down, Right } private fun touch(view: View, event: MotionEvent, moves: MutableMap<Direction, MutableMap<Int, () -> Unit>>): Boolean { when(event.action) { ACTION_DOWN -> { x[view] = event.rawX y[view] = event.rawY finger[view] = event.pointerCount } ACTION_MOVE -> { if (!x.containsKey(view)) x[view] = event.rawX if (!y.containsKey(view)) y[view] = event.rawY if (!finger.containsKey(view)) finger[view] = event.pointerCount } ACTION_UP -> { val diffX = event.rawX - (x[view]?:0f) val diffY = event.rawY - (y[view]?:0f) val direction = getDirection(diffX, diffY) Log.record(direction) Log.record(finger[view]) moves[direction] ?.get(finger[view]) ?.invoke() x.remove(view) y.remove(view) finger.remove(view) } } return false } private fun getDirection(diffX: Float, diffY: Float): Direction { val absX = abs(diffX) val absY = abs(diffY) return when { absX > absY -> when { diffX > 0 -> Direction.Right diffX < 0 -> Direction.Left else -> Direction.None } absX < absY -> when { diffY > 0 -> Direction.Down diffY < 0 -> Direction.Up else -> Direction.None } else -> Direction.None } }
android/Lib/src/main/kotlin/com/darakeon/dfm/lib/extensions/View.kt
4033194071
package com.jaynewstrom.concretesample.main import android.content.Context import com.jaynewstrom.concretesample.R import com.jaynewstrom.concretesample.application.ForApplication import dagger.Module import dagger.Provides import javax.inject.Named @Module internal class MainActivityModule { @Provides @Named("title") fun provideTitle(@ForApplication applicationContext: Context): String { return applicationContext.getString(R.string.main_title) } }
concrete-sample/src/main/java/com/jaynewstrom/concretesample/main/MainActivityModule.kt
303543732
package com.rartworks.engine.rendering /** * A dimensions specification. */ data class Dimensions(val width: Float, val height: Float)
core/src/com/rartworks/engine/rendering/Dimensions.kt
4285388046
package at.cpickl.gadsu.version import at.cpickl.gadsu.global.GADSU_LATEST_VERSION_URL import at.cpickl.gadsu.global.UserEvent import com.google.inject.AbstractModule class CheckForUpdatesEvent : UserEvent() class VersionModule : AbstractModule() { override fun configure() { bind(LatestVersionFetcher::class.java).toInstance(WebLatestVersionFetcher(GADSU_LATEST_VERSION_URL)) bind(VersionChecker::class.java).to(VersionCheckerImpl::class.java) bind(VersionUpdater::class.java).to(VersionUpdaterImpl::class.java).asEagerSingleton() } }
src/main/kotlin/at/cpickl/gadsu/version/module.kt
1536088372
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vanniktech.emoji.google.category import com.vanniktech.emoji.google.GoogleEmoji internal object AnimalsAndNatureCategoryChunk0 { internal val EMOJIS: List<GoogleEmoji> = listOf( GoogleEmoji(String(intArrayOf(0x1F435), 0, 1), listOf("monkey_face"), 11, 40, false), GoogleEmoji(String(intArrayOf(0x1F412), 0, 1), listOf("monkey"), 11, 4, false), GoogleEmoji(String(intArrayOf(0x1F98D), 0, 1), listOf("gorilla"), 44, 31, false), GoogleEmoji(String(intArrayOf(0x1F9A7), 0, 1), listOf("orangutan"), 44, 57, false), GoogleEmoji(String(intArrayOf(0x1F436), 0, 1), listOf("dog"), 11, 41, false), GoogleEmoji(String(intArrayOf(0x1F415), 0, 1), listOf("dog2"), 11, 8, false), GoogleEmoji(String(intArrayOf(0x1F9AE), 0, 1), listOf("guide_dog"), 45, 3, false), GoogleEmoji(String(intArrayOf(0x1F415, 0x200D, 0x1F9BA), 0, 3), listOf("service_dog"), 11, 7, false), GoogleEmoji(String(intArrayOf(0x1F429), 0, 1), listOf("poodle"), 11, 28, false), GoogleEmoji(String(intArrayOf(0x1F43A), 0, 1), listOf("wolf"), 11, 45, false), GoogleEmoji(String(intArrayOf(0x1F98A), 0, 1), listOf("fox_face"), 44, 28, false), GoogleEmoji(String(intArrayOf(0x1F99D), 0, 1), listOf("raccoon"), 44, 47, false), GoogleEmoji(String(intArrayOf(0x1F431), 0, 1), listOf("cat"), 11, 36, false), GoogleEmoji(String(intArrayOf(0x1F408), 0, 1), listOf("cat2"), 10, 55, false), GoogleEmoji(String(intArrayOf(0x1F408, 0x200D, 0x2B1B), 0, 3), listOf("black_cat"), 10, 54, false), GoogleEmoji(String(intArrayOf(0x1F981), 0, 1), listOf("lion_face"), 44, 19, false), GoogleEmoji(String(intArrayOf(0x1F42F), 0, 1), listOf("tiger"), 11, 34, false), GoogleEmoji(String(intArrayOf(0x1F405), 0, 1), listOf("tiger2"), 10, 51, false), GoogleEmoji(String(intArrayOf(0x1F406), 0, 1), listOf("leopard"), 10, 52, false), GoogleEmoji(String(intArrayOf(0x1F434), 0, 1), listOf("horse"), 11, 39, false), GoogleEmoji(String(intArrayOf(0x1F40E), 0, 1), listOf("racehorse"), 11, 0, false), GoogleEmoji(String(intArrayOf(0x1F984), 0, 1), listOf("unicorn_face"), 44, 22, false), GoogleEmoji(String(intArrayOf(0x1F993), 0, 1), listOf("zebra_face"), 44, 37, false), GoogleEmoji(String(intArrayOf(0x1F98C), 0, 1), listOf("deer"), 44, 30, false), GoogleEmoji(String(intArrayOf(0x1F9AC), 0, 1), listOf("bison"), 45, 1, false), GoogleEmoji(String(intArrayOf(0x1F42E), 0, 1), listOf("cow"), 11, 33, false), GoogleEmoji(String(intArrayOf(0x1F402), 0, 1), listOf("ox"), 10, 48, false), GoogleEmoji(String(intArrayOf(0x1F403), 0, 1), listOf("water_buffalo"), 10, 49, false), GoogleEmoji(String(intArrayOf(0x1F404), 0, 1), listOf("cow2"), 10, 50, false), GoogleEmoji(String(intArrayOf(0x1F437), 0, 1), listOf("pig"), 11, 42, false), GoogleEmoji(String(intArrayOf(0x1F416), 0, 1), listOf("pig2"), 11, 9, false), GoogleEmoji(String(intArrayOf(0x1F417), 0, 1), listOf("boar"), 11, 10, false), GoogleEmoji(String(intArrayOf(0x1F43D), 0, 1), listOf("pig_nose"), 11, 49, false), GoogleEmoji(String(intArrayOf(0x1F40F), 0, 1), listOf("ram"), 11, 1, false), GoogleEmoji(String(intArrayOf(0x1F411), 0, 1), listOf("sheep"), 11, 3, false), GoogleEmoji(String(intArrayOf(0x1F410), 0, 1), listOf("goat"), 11, 2, false), GoogleEmoji(String(intArrayOf(0x1F42A), 0, 1), listOf("dromedary_camel"), 11, 29, false), GoogleEmoji(String(intArrayOf(0x1F42B), 0, 1), listOf("camel"), 11, 30, false), GoogleEmoji(String(intArrayOf(0x1F999), 0, 1), listOf("llama"), 44, 43, false), GoogleEmoji(String(intArrayOf(0x1F992), 0, 1), listOf("giraffe_face"), 44, 36, false), GoogleEmoji(String(intArrayOf(0x1F418), 0, 1), listOf("elephant"), 11, 11, false), GoogleEmoji(String(intArrayOf(0x1F9A3), 0, 1), listOf("mammoth"), 44, 53, false), GoogleEmoji(String(intArrayOf(0x1F98F), 0, 1), listOf("rhinoceros"), 44, 33, false), GoogleEmoji(String(intArrayOf(0x1F99B), 0, 1), listOf("hippopotamus"), 44, 45, false), GoogleEmoji(String(intArrayOf(0x1F42D), 0, 1), listOf("mouse"), 11, 32, false), GoogleEmoji(String(intArrayOf(0x1F401), 0, 1), listOf("mouse2"), 10, 47, false), GoogleEmoji(String(intArrayOf(0x1F400), 0, 1), listOf("rat"), 10, 46, false), GoogleEmoji(String(intArrayOf(0x1F439), 0, 1), listOf("hamster"), 11, 44, false), GoogleEmoji(String(intArrayOf(0x1F430), 0, 1), listOf("rabbit"), 11, 35, false), GoogleEmoji(String(intArrayOf(0x1F407), 0, 1), listOf("rabbit2"), 10, 53, false), GoogleEmoji(String(intArrayOf(0x1F43F, 0xFE0F), 0, 2), listOf("chipmunk"), 11, 51, false), GoogleEmoji(String(intArrayOf(0x1F9AB), 0, 1), listOf("beaver"), 45, 0, false), GoogleEmoji(String(intArrayOf(0x1F994), 0, 1), listOf("hedgehog"), 44, 38, false), GoogleEmoji(String(intArrayOf(0x1F987), 0, 1), listOf("bat"), 44, 25, false), GoogleEmoji(String(intArrayOf(0x1F43B), 0, 1), listOf("bear"), 11, 47, false), GoogleEmoji(String(intArrayOf(0x1F43B, 0x200D, 0x2744, 0xFE0F), 0, 4), listOf("polar_bear"), 11, 46, false), GoogleEmoji(String(intArrayOf(0x1F428), 0, 1), listOf("koala"), 11, 27, false), GoogleEmoji(String(intArrayOf(0x1F43C), 0, 1), listOf("panda_face"), 11, 48, false), GoogleEmoji(String(intArrayOf(0x1F9A5), 0, 1), listOf("sloth"), 44, 55, false), GoogleEmoji(String(intArrayOf(0x1F9A6), 0, 1), listOf("otter"), 44, 56, false), GoogleEmoji(String(intArrayOf(0x1F9A8), 0, 1), listOf("skunk"), 44, 58, false), GoogleEmoji(String(intArrayOf(0x1F998), 0, 1), listOf("kangaroo"), 44, 42, false), GoogleEmoji(String(intArrayOf(0x1F9A1), 0, 1), listOf("badger"), 44, 51, false), GoogleEmoji(String(intArrayOf(0x1F43E), 0, 1), listOf("feet", "paw_prints"), 11, 50, false), GoogleEmoji(String(intArrayOf(0x1F983), 0, 1), listOf("turkey"), 44, 21, false), GoogleEmoji(String(intArrayOf(0x1F414), 0, 1), listOf("chicken"), 11, 6, false), GoogleEmoji(String(intArrayOf(0x1F413), 0, 1), listOf("rooster"), 11, 5, false), GoogleEmoji(String(intArrayOf(0x1F423), 0, 1), listOf("hatching_chick"), 11, 22, false), GoogleEmoji(String(intArrayOf(0x1F424), 0, 1), listOf("baby_chick"), 11, 23, false), GoogleEmoji(String(intArrayOf(0x1F425), 0, 1), listOf("hatched_chick"), 11, 24, false), GoogleEmoji(String(intArrayOf(0x1F426), 0, 1), listOf("bird"), 11, 25, false), GoogleEmoji(String(intArrayOf(0x1F427), 0, 1), listOf("penguin"), 11, 26, false), GoogleEmoji(String(intArrayOf(0x1F54A, 0xFE0F), 0, 2), listOf("dove_of_peace"), 30, 27, false), GoogleEmoji(String(intArrayOf(0x1F985), 0, 1), listOf("eagle"), 44, 23, false), GoogleEmoji(String(intArrayOf(0x1F986), 0, 1), listOf("duck"), 44, 24, false), GoogleEmoji(String(intArrayOf(0x1F9A2), 0, 1), listOf("swan"), 44, 52, false), GoogleEmoji(String(intArrayOf(0x1F989), 0, 1), listOf("owl"), 44, 27, false), GoogleEmoji(String(intArrayOf(0x1F9A4), 0, 1), listOf("dodo"), 44, 54, false), GoogleEmoji(String(intArrayOf(0x1FAB6), 0, 1), listOf("feather"), 54, 37, false), GoogleEmoji(String(intArrayOf(0x1F9A9), 0, 1), listOf("flamingo"), 44, 59, false), GoogleEmoji(String(intArrayOf(0x1F99A), 0, 1), listOf("peacock"), 44, 44, false), GoogleEmoji(String(intArrayOf(0x1F99C), 0, 1), listOf("parrot"), 44, 46, false), GoogleEmoji(String(intArrayOf(0x1F438), 0, 1), listOf("frog"), 11, 43, false), GoogleEmoji(String(intArrayOf(0x1F40A), 0, 1), listOf("crocodile"), 10, 57, false), GoogleEmoji(String(intArrayOf(0x1F422), 0, 1), listOf("turtle"), 11, 21, false), GoogleEmoji(String(intArrayOf(0x1F98E), 0, 1), listOf("lizard"), 44, 32, false), GoogleEmoji(String(intArrayOf(0x1F40D), 0, 1), listOf("snake"), 10, 60, false), GoogleEmoji(String(intArrayOf(0x1F432), 0, 1), listOf("dragon_face"), 11, 37, false), GoogleEmoji(String(intArrayOf(0x1F409), 0, 1), listOf("dragon"), 10, 56, false), GoogleEmoji(String(intArrayOf(0x1F995), 0, 1), listOf("sauropod"), 44, 39, false), GoogleEmoji(String(intArrayOf(0x1F996), 0, 1), listOf("t-rex"), 44, 40, false), GoogleEmoji(String(intArrayOf(0x1F433), 0, 1), listOf("whale"), 11, 38, false), GoogleEmoji(String(intArrayOf(0x1F40B), 0, 1), listOf("whale2"), 10, 58, false), GoogleEmoji(String(intArrayOf(0x1F42C), 0, 1), listOf("dolphin", "flipper"), 11, 31, false), GoogleEmoji(String(intArrayOf(0x1F9AD), 0, 1), listOf("seal"), 45, 2, false), GoogleEmoji(String(intArrayOf(0x1F41F), 0, 1), listOf("fish"), 11, 18, false), GoogleEmoji(String(intArrayOf(0x1F420), 0, 1), listOf("tropical_fish"), 11, 19, false), GoogleEmoji(String(intArrayOf(0x1F421), 0, 1), listOf("blowfish"), 11, 20, false), GoogleEmoji(String(intArrayOf(0x1F988), 0, 1), listOf("shark"), 44, 26, false), GoogleEmoji(String(intArrayOf(0x1F419), 0, 1), listOf("octopus"), 11, 12, false), GoogleEmoji(String(intArrayOf(0x1F41A), 0, 1), listOf("shell"), 11, 13, false), GoogleEmoji(String(intArrayOf(0x1FAB8), 0, 1), listOf("coral"), 54, 39, false), GoogleEmoji(String(intArrayOf(0x1F40C), 0, 1), listOf("snail"), 10, 59, false), GoogleEmoji(String(intArrayOf(0x1F98B), 0, 1), listOf("butterfly"), 44, 29, false), GoogleEmoji(String(intArrayOf(0x1F41B), 0, 1), listOf("bug"), 11, 14, false), GoogleEmoji(String(intArrayOf(0x1F41C), 0, 1), listOf("ant"), 11, 15, false), GoogleEmoji(String(intArrayOf(0x1F41D), 0, 1), listOf("bee", "honeybee"), 11, 16, false), GoogleEmoji(String(intArrayOf(0x1FAB2), 0, 1), listOf("beetle"), 54, 33, false), GoogleEmoji(String(intArrayOf(0x1F41E), 0, 1), listOf("ladybug", "lady_beetle"), 11, 17, false), GoogleEmoji(String(intArrayOf(0x1F997), 0, 1), listOf("cricket"), 44, 41, false), GoogleEmoji(String(intArrayOf(0x1FAB3), 0, 1), listOf("cockroach"), 54, 34, false), GoogleEmoji(String(intArrayOf(0x1F577, 0xFE0F), 0, 2), listOf("spider"), 31, 23, false), GoogleEmoji(String(intArrayOf(0x1F578, 0xFE0F), 0, 2), listOf("spider_web"), 31, 24, false), GoogleEmoji(String(intArrayOf(0x1F982), 0, 1), listOf("scorpion"), 44, 20, false), GoogleEmoji(String(intArrayOf(0x1F99F), 0, 1), listOf("mosquito"), 44, 49, false), GoogleEmoji(String(intArrayOf(0x1FAB0), 0, 1), listOf("fly"), 54, 31, false), GoogleEmoji(String(intArrayOf(0x1FAB1), 0, 1), listOf("worm"), 54, 32, false), GoogleEmoji(String(intArrayOf(0x1F9A0), 0, 1), listOf("microbe"), 44, 50, false), GoogleEmoji(String(intArrayOf(0x1F490), 0, 1), listOf("bouquet"), 27, 6, false), GoogleEmoji(String(intArrayOf(0x1F338), 0, 1), listOf("cherry_blossom"), 5, 53, false), ) }
emoji-google/src/commonMain/kotlin/com/vanniktech/emoji/google/category/AnimalsAndNatureCategoryChunk0.kt
785698386
package com.github.christophpickl.kpotpourri.logback4k import ch.qos.logback.classic.Level import com.github.christophpickl.kpotpourri.common.io.Io import com.github.christophpickl.kpotpourri.test4k.hamkrest_matcher.not import com.github.christophpickl.kpotpourri.test4k.hamkrest_matcher.shouldMatchValue import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.isEmpty import mu.KLogger import mu.KotlinLogging import mu.KotlinLogging.logger import org.testng.annotations.Test import java.io.File import java.util.* @Test class FileAppenderIntegrationTest { fun `Given file appender configured When log Then file contains lines`() { val filePrefix = File(System.getProperty("java.io.tmpdir"), "logback4k-${Date().time}").canonicalPath val logFile = File("$filePrefix.log") Logback4k.reconfigure { addFileAppender(file = logFile.canonicalPath, filePattern = "$filePrefix-%d{yyyy-MM-dd}.log") { level = Level.ALL } } val log = logger {} log.info { "anyLogMessage" } assertThat(logFile.exists(), equalTo(true)) val lines = logFile.readLines() assertThat(lines, not(isEmpty)) } } @Test class ConsoleAppenderIntegrationTest { private val simplePattern = "[%level] %msg%n" fun `Given console appender When log Then stdout contains entry`() { Logback4k.reconfigure { addTestConsoleAppender(Level.ALL) } executeLogAndReadStdOut { info { "logInfo" } } shouldMatchValue "[INFO] logInfo\n" } fun `root level to warn, appender to all, Should not be logged`() { Logback4k.reconfigure { rootLevel = Level.WARN addTestConsoleAppender(Level.ALL) } executeLogAndReadStdOut { info { "logInfo" } } shouldMatchValue "" } fun `root level to WARN and appender to ALL and package to INFO, Should be logged`() { Logback4k.reconfigure { rootLevel = Level.WARN addTestConsoleAppender(Level.ALL) packageLevel(Level.INFO, "packagePrecedence") } loggerAndAssert("packagePrecedence", { info { "overrides root level" } }, "[INFO] overrides root level\n") } fun `package limitted`() { Logback4k.reconfigure { addTestConsoleAppender(Level.ALL) packageLevel(Level.WARN, "pkgLimit") } loggerAndAssert("pkgLimit", { info { "will not be displayed as INFO < WARN" } }, "") loggerAndAssert("pkgLimit", { error { "pkgLimitError" } }, "[ERROR] pkgLimitError\n") } private fun LogbackConfig.addTestConsoleAppender(appenderLevel: Level) { addConsoleAppender { appenderName = "testConsoleAppender" level = appenderLevel pattern = simplePattern } } private fun loggerAndAssert(packageName: String, withLogger: KLogger.() -> Unit, expectedStdout: String) { Io.readFromStdOut { withLogger(KotlinLogging.logger(packageName)) } shouldMatchValue expectedStdout } private fun executeLogAndReadStdOut(func: KLogger.() -> Unit): String { val log = logger {} return Io.readFromStdOut { func(log) } } }
logback4k/src/test/kotlin/com/github/christophpickl/kpotpourri/logback4k/integration_tests.kt
1402433651
package tech.pronghorn.util import java.nio.ByteBuffer import java.util.zip.Deflater internal const val GZIP_MAGIC: Short = 0x8b1f.toShort() internal const val GZIP_HEADER_SIZE = 10 internal const val GZIP_FOOTER_SIZE = 8 internal const val GZIP_EXTRA_SIZE = GZIP_HEADER_SIZE + GZIP_FOOTER_SIZE internal fun writeGzipHeader(buffer: ByteBuffer) { buffer.putShort(GZIP_MAGIC) buffer.put(Deflater.DEFLATED.toByte()) buffer.putInt(0) buffer.putShort(0) buffer.put(0) }
src/main/kotlin/tech/pronghorn/util/GzipUtils.kt
1333659908
package ee.design.gen.angular import ee.design.gen.DesignGeneratorFactory import ee.lang.StructureUnitI import ee.lang.gen.ts.prepareForTsGeneration import java.nio.file.Path open class DesignAngularGenerator(val model: StructureUnitI<*>) { fun generate(target: Path) { val generatorFactory = DesignGeneratorFactory() model.prepareForTsGeneration() val generatorContextsApiBase = generatorFactory.typeScriptApiBase("", model) val generatorApiBase = generatorContextsApiBase.generator val generatorContextsComponent = generatorFactory.angularTypeScriptComponent("", model) val generatorComponent = generatorContextsComponent.generator val generatorAngularModule = generatorFactory.angularModules("", model) val generatorModule = generatorAngularModule.generator val generatorAngularHtmlAndScss = generatorFactory.angularHtmlAndScssComponent("", model) val generatorHtmlAndScss = generatorAngularHtmlAndScss.generator generatorApiBase.delete(target, model) generatorComponent.delete(target, model) generatorModule.delete(target, model) generatorHtmlAndScss.delete(target, model) generatorApiBase.generate(target, model) generatorComponent.generate(target, model) generatorModule.generate(target, model) generatorHtmlAndScss.generate(target, model) } }
ee-design/src/main/kotlin/ee/design/gen/angular/DesignAngularGenerator.kt
943228324
package uk.co.appsbystudio.geoshare.authentication.signup class SignupPresenterImpl(private val view: SignupView, private val interactor: SignupInteractor): SignupPresenter, SignupInteractor.OnSignupFinishedListener { override fun validate(name: String, email: String, password: String, terms: Boolean) { view.showProgress() interactor.signup(name, email, password, terms, this) } override fun onTermsClick() { view.showTerms() } override fun onNameError() { view.setNameError() view.hideProgress() } override fun onEmailError() { view.setEmailError() view.hideProgress() } override fun onPasswordError() { view.setPasswordError() view.hideProgress() } override fun onTermsError() { view.setTermsError() view.hideProgress() } override fun onSuccess() { view.updateUI() } override fun onFailure(error: String) { view.hideProgress() view.showError(error) } }
mobile/src/main/java/uk/co/appsbystudio/geoshare/authentication/signup/SignupPresenterImpl.kt
3991405779
package cn.luo.yuan.maze.model.gift import cn.luo.yuan.maze.model.effect.original.SkillRateEffect import cn.luo.yuan.maze.service.InfoControlInterface /** * Created by luoyuan on 2017/9/15. */ class SkillMaster:GiftHandler { override fun handler(control: InfoControlInterface?) { val pre = SkillRateEffect() pre.skillRate = 10f pre.tag = this.javaClass.simpleName control?.hero?.effects?.add(pre) } override fun unHandler(control: InfoControlInterface?) { val e = control?.hero?.effects?.find { it.tag == this.javaClass.simpleName } if(e!=null){ control?.hero?.effects?.remove(e) } } }
dataModel/src/cn/luo/yuan/maze/model/gift/SkillMaster.kt
175984158
//package io.kotest.assertions.arrow // //import arrow.Kind //import arrow.core.Tuple2 //import arrow.data.Nel //import arrow.data.NonEmptyList //import arrow.data.Validated //import arrow.data.ValidatedPartialOf //import arrow.data.extensions.nonemptylist.semigroup.semigroup //import arrow.data.extensions.validated.applicativeError.applicativeError //import arrow.extension //import arrow.product //import arrow.typeclasses.Applicative //import arrow.validation.RefinedPredicateException //import arrow.validation.Refinement //import io.kotest.properties.Gen // ///** // * Marker [Throwable] used to generate random [arrow.core.Failure] cases // */ //object Ex : RuntimeException("BOOM") // //@product //data class Person(val id: Long, val name: String) { // companion object //} // //interface NonEmptyPerson<F> : Refinement<F, Person> { // override fun invalidValueMsg(a: Person): String = // "$a should have a name" // // override fun Person.refinement(): Boolean = // name.isNotEmpty() //} // //@extension //interface ValidatedNonEmptyPerson : // NonEmptyPerson<ValidatedPartialOf<Nel<RefinedPredicateException>>> { // override fun applicativeError() = // Validated.applicativeError(NonEmptyList.semigroup<RefinedPredicateException>()) //} // //fun Person.Companion.gen(): Gen<Person> = // map( // Gen.long(), // Gen.string(), // Tuple2<Long, String>::toPerson // ) // //fun <F> Applicative<F>.helloWorldPoly(): Kind<F, String> = just("Hello World")
kotest-assertions/kotest-assertions-arrow/src/jvmTest/kotlin/io/kotest/assertions/arrow/TestData.kt
3320889243
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.utils import android.content.Context import android.content.SharedPreferences import android.content.res.Resources import android.preference.PreferenceManager import org.mozilla.focus.R import org.mozilla.focus.fragment.FirstrunFragment import org.mozilla.focus.search.SearchEngine /** * A simple wrapper for SharedPreferences that makes reading preference a little bit easier. */ class Settings private constructor(context: Context) { companion object { private var instance: Settings? = null @JvmStatic @Synchronized fun getInstance(context: Context): Settings { if (instance == null) { instance = Settings(context.applicationContext) } return instance ?: throw AssertionError("Instance cleared") } } private val preferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) private val resources: Resources = context.resources val defaultSearchEngineName: String? get() = preferences.getString(getPreferenceKey(R.string.pref_key_search_engine), null) fun shouldBlockImages(): Boolean = // Not shipping in v1 (#188) /* preferences.getBoolean( resources.getString(R.string.pref_key_performance_block_images), false); */ false fun shouldShowFirstrun(): Boolean = !preferences.getBoolean(FirstrunFragment.FIRSTRUN_PREF, false) fun shouldUseSecureMode(): Boolean = preferences.getBoolean(getPreferenceKey(R.string.pref_key_secure), false) fun setDefaultSearchEngine(searchEngine: SearchEngine) { preferences.edit() .putString(getPreferenceKey(R.string.pref_key_search_engine), searchEngine.name) .apply() } fun shouldAutocompleteFromShippedDomainList() = preferences.getBoolean( getPreferenceKey(R.string.pref_key_autocomplete_preinstalled), true) fun shouldAutocompleteFromCustomDomainList() = preferences.getBoolean( getPreferenceKey(R.string.pref_key_autocomplete_custom), false) private fun getPreferenceKey(resourceId: Int): String = resources.getString(resourceId) }
app/src/main/java/org/mozilla/focus/utils/Settings.kt
2425861940
package com.ruuvi.station.app.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import org.kodein.di.DKodein import org.kodein.di.generic.instanceOrNull class ViewModelFactory(private val injector: DKodein) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return injector.instanceOrNull<ViewModel>(tag = modelClass.simpleName) as T? ?: modelClass.newInstance() } }
app/src/main/java/com/ruuvi/station/app/ui/ViewModelFactory.kt
3070037409
package com.baulsupp.okurl.commands import com.baulsupp.oksocial.output.OutputHandler import com.baulsupp.okurl.credentials.CredentialsStore import com.baulsupp.okurl.credentials.TokenSet import com.baulsupp.okurl.location.LocationSource import com.baulsupp.okurl.services.ServiceLibrary import okhttp3.OkHttpClient import okhttp3.Response interface ToolSession { fun close() var client: OkHttpClient var outputHandler: OutputHandler<Response> var credentialsStore: CredentialsStore var locationSource: LocationSource var serviceLibrary: ServiceLibrary val defaultTokenSet: TokenSet? }
src/main/kotlin/com/baulsupp/okurl/commands/ToolSession.kt
2259874415
/* * Copyright (c) 2017 Andrei Heidelbacher <[email protected]> * * 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.andreihh.algostorm.core.ecs import com.andreihh.algostorm.core.ecs.EntityRef.Id import org.junit.Before import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue class EntityGroupTest { private fun createGroup( entities: Map<EntityRef.Id, Collection<Component>> ): EntityGroup = EntityPool.of(entities).filter { true } private lateinit var initialEntities: Map<Id, Collection<Component>> private lateinit var group: EntityGroup private fun createInitialEntities(): Map<Id, Collection<Component>> = (1 until 1000).associate { Id(it) to setOf(ComponentMock(it)) } @Before fun initGroup() { initialEntities = createInitialEntities() group = createGroup(initialEntities) } @Test fun testGetSnapshotReturnsSameEntities() { assertEquals( expected = initialEntities, actual = group.associate { it.id to it.components.toSet() } ) } @Test fun testContainsReturnsTrue() { for (id in initialEntities.keys) { assertTrue(id in group) } } @Test fun testContainsAbsentReturnsFalse() { val maxId = initialEntities.keys.maxBy { it.value }?.value ?: 0 assertFalse(Id(maxId + 1) in group) } @Test fun testFilterGroupShouldContainFilteredEntities() { val subgroup = group.filter { it.id.value % 2 == 1 } assertEquals( expected = initialEntities.filter { it.key.value % 2 == 1 }, actual = subgroup.associate { it.id to it.components.toSet() } ) } @Test fun testChangedEntityRemovedFromSubgroup() { val subgroup = group.filter { val id = it[ComponentMock::class]?.id id != null && id % 2 == 1 } group.forEach { if (it.id in subgroup) { it.remove(ComponentMock::class) assertFalse(it.id in subgroup) } } } @Test fun testChangedEntityAddedToSubgroup() { val subgroup = group.filter { val id = it[ComponentMock::class]?.id id != null && id % 2 == 0 } group.forEach { if (it.id !in subgroup) { it.set(ComponentMock(it.id.value - it.id.value % 2)) assertTrue(it.id in subgroup) } } } }
algostorm-core/src/test/kotlin/com/andreihh/algostorm/core/ecs/EntityGroupTest.kt
2929589398
/* * Copyright 2019 Stephane Nicolas * Copyright 2019 Daniel Molinero Reguera * * 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 toothpick /** * Bridge that makes it possible to modify the injector used by Toothpick. */ fun setToothpickInjector(injector: Injector) { Toothpick.injector = injector }
ktp/src/main/kotlin/toothpick/TPInjectorReplace.kt
1774182158
/* * 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.onboarding import androidx.recyclerview.widget.RecyclerView.HORIZONTAL import com.facebook.litho.Component import com.facebook.litho.ComponentScope import com.facebook.litho.KComponent import com.facebook.litho.Row import com.facebook.litho.Style import com.facebook.litho.core.height import com.facebook.litho.core.padding import com.facebook.litho.dp import com.facebook.litho.px import com.facebook.litho.view.backgroundColor import com.facebook.litho.widget.collection.CrossAxisWrapMode import com.facebook.litho.widget.collection.LazyList import com.facebook.samples.litho.onboarding.model.Post import com.facebook.samples.litho.onboarding.model.User // start_example class UserFeedWithStoriesKComponent( private val posts: List<Post>, private val usersWithStories: List<User> ) : KComponent() { override fun ComponentScope.render(): Component { return LazyList { child( LazyList( orientation = HORIZONTAL, crossAxisWrapMode = CrossAxisWrapMode.MatchFirstChild, startPadding = 4.dp, topPadding = 4.dp, style = Style.padding(vertical = 6.dp)) { usersWithStories.forEach { user -> child(StoryKComponent(user = user)) } }) child(Row(style = Style.height(1.px).backgroundColor(0x22888888))) posts.forEach { post -> child(id = post.id, component = PostWithActionsKComponent(post = post)) } } } } // end_example
sample/src/main/java/com/facebook/samples/litho/onboarding/UserFeedWithStoriesKComponent.kt
1686514619
package leakcanary.internal.activity.db import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import org.intellij.lang.annotations.Language import shark.Leak import shark.LibraryLeak internal object LeakTable { @Language("RoomSql") const val create = """ CREATE TABLE leak ( id INTEGER PRIMARY KEY, signature TEXT UNIQUE, short_description TEXT, is_library_leak INTEGER, is_read INTEGER )""" @Language("RoomSql") const val createSignatureIndex = """ CREATE INDEX leak_signature on leak (signature) """ @Language("RoomSql") const val drop = "DROP TABLE IF EXISTS leak" fun insert( db: SQLiteDatabase, heapAnalysisId: Long, leak: Leak ): Long { val values = ContentValues() values.put("signature", leak.signature) values.put("short_description", leak.shortDescription) values.put("is_library_leak", if (leak is LibraryLeak) 1 else 0) values.put("is_read", 0) db.insertWithOnConflict("leak", null, values, SQLiteDatabase.CONFLICT_IGNORE) val leakId = db.rawQuery("SELECT id from leak WHERE signature = '${leak.signature}' LIMIT 1", null) .use { cursor -> if (cursor.moveToFirst()) cursor.getLong(0) else throw IllegalStateException( "No id found for leak with signature '${leak.signature}'" ) } leak.leakTraces.forEachIndexed { index, leakTrace -> LeakTraceTable.insert( db = db, leakId = leakId, heapAnalysisId = heapAnalysisId, leakTraceIndex = index, leakingObjectClassSimpleName = leakTrace.leakingObject.classSimpleName ) } return leakId } fun retrieveLeakReadStatuses( db: SQLiteDatabase, signatures: Set<String> ): Map<String, Boolean> { return db.rawQuery( """ SELECT signature , is_read FROM leak WHERE signature IN (${signatures.joinToString { "'$it'" }}) """, null ) .use { cursor -> val leakReadStatuses = mutableMapOf<String, Boolean>() while (cursor.moveToNext()) { val signature = cursor.getString(0) val isRead = cursor.getInt(1) == 1 leakReadStatuses[signature] = isRead } leakReadStatuses } } class AllLeaksProjection( val signature: String, val shortDescription: String, val createdAtTimeMillis: Long, val leakTraceCount: Int, val isLibraryLeak: Boolean, val isNew: Boolean ) fun retrieveAllLeaks( db: SQLiteDatabase ): List<AllLeaksProjection> { return db.rawQuery( """ SELECT l.signature , MIN(l.short_description) , MAX(h.created_at_time_millis) as created_at_time_millis , COUNT(*) as leak_trace_count , MIN(l.is_library_leak) as is_library_leak , MAX(l.is_read) as is_read FROM leak_trace lt LEFT JOIN leak l on lt.leak_id = l.id LEFT JOIN heap_analysis h ON lt.heap_analysis_id = h.id GROUP BY 1 ORDER BY leak_trace_count DESC, created_at_time_millis DESC """, null ) .use { cursor -> val all = mutableListOf<AllLeaksProjection>() while (cursor.moveToNext()) { val group = AllLeaksProjection( signature = cursor.getString(0), shortDescription = cursor.getString(1), createdAtTimeMillis = cursor.getLong(2), leakTraceCount = cursor.getInt(3), isLibraryLeak = cursor.getInt(4) == 1, isNew = cursor.getInt(5) == 0 ) all.add(group) } all } } fun markAsRead( db: SQLiteDatabase, signature: String ) { val values = ContentValues().apply { put("is_read", 1) } db.update("leak", values, "signature = ?", arrayOf(signature)) } class LeakProjection( val shortDescription: String, val isNew: Boolean, val isLibraryLeak: Boolean, val leakTraces: List<LeakTraceProjection> ) class LeakTraceProjection( val leakTraceIndex: Int, val heapAnalysisId: Long, val classSimpleName: String, val createdAtTimeMillis: Long ) fun retrieveLeakBySignature( db: SQLiteDatabase, signature: String ): LeakProjection? { return db.rawQuery( """ SELECT lt.leak_trace_index , lt.heap_analysis_id , lt.class_simple_name , h.created_at_time_millis , l.short_description , l.is_read , l.is_library_leak FROM leak_trace lt LEFT JOIN leak l on lt.leak_id = l.id LEFT JOIN heap_analysis h ON lt.heap_analysis_id = h.id WHERE l.signature = ? ORDER BY h.created_at_time_millis DESC """, arrayOf(signature) ) .use { cursor -> return if (cursor.moveToFirst()) { val leakTraces = mutableListOf<LeakTraceProjection>() val leakProjection = LeakProjection( shortDescription = cursor.getString(4), isNew = cursor.getInt(5) == 0, isLibraryLeak = cursor.getInt(6) == 1, leakTraces = leakTraces ) leakTraces.addAll(generateSequence(cursor) { if (cursor.moveToNext()) cursor else null }.map { LeakTraceProjection( leakTraceIndex = cursor.getInt(0), heapAnalysisId = cursor.getLong(1), classSimpleName = cursor.getString(2), createdAtTimeMillis = cursor.getLong(3) ) }) leakProjection } else { null } } } fun deleteByHeapAnalysisId( db: SQLiteDatabase, heapAnalysisId: Long ) { LeakTraceTable.deleteByHeapAnalysisId(db, heapAnalysisId) db.execSQL( """ DELETE FROM leak WHERE NOT EXISTS ( SELECT * FROM leak_trace lt WHERE leak.id = lt.leak_id) """ ) } }
leakcanary-android-core/src/main/java/leakcanary/internal/activity/db/LeakTable.kt
2495558602
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.camera2.slowmo.fragments import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.os.Bundle import android.widget.Toast import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.navigation.Navigation import com.example.android.camera2.slowmo.R private const val PERMISSIONS_REQUEST_CODE = 10 private val PERMISSIONS_REQUIRED = arrayOf( Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO) /** * This [Fragment] requests permissions and, once granted, it will navigate to the next fragment */ class PermissionsFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (hasPermissions(requireContext())) { // If permissions have already been granted, proceed Navigation.findNavController(requireActivity(), R.id.fragment_container).navigate( PermissionsFragmentDirections.actionPermissionsToSelector()) } else { // Request camera-related permissions requestPermissions(PERMISSIONS_REQUIRED, PERMISSIONS_REQUEST_CODE) } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == PERMISSIONS_REQUEST_CODE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Takes the user to the success fragment when permission is granted Navigation.findNavController(requireActivity(), R.id.fragment_container).navigate( PermissionsFragmentDirections.actionPermissionsToSelector()) } else { Toast.makeText(context, "Permission request denied", Toast.LENGTH_LONG).show() } } } companion object { /** Convenience method used to check if all permissions required by this app are granted */ fun hasPermissions(context: Context) = PERMISSIONS_REQUIRED.all { ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED } } }
Camera2SlowMotion/app/src/main/java/com/example/android/camera2/slowmo/fragments/PermissionsFragment.kt
55247459
package app.lawnchair.util import android.content.Context import android.content.ContextWrapper import androidx.compose.runtime.* import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner private val LocalLifecycleState = compositionLocalOf<Lifecycle.State> { error("CompositionLocal LocalLifecycleState not present") } @Composable fun lifecycleState(): Lifecycle.State = LocalLifecycleState.current @Composable fun ProvideLifecycleState(content: @Composable () -> Unit) { CompositionLocalProvider(LocalLifecycleState provides observeLifecycleState()) { content() } } @Composable private fun observeLifecycleState(): Lifecycle.State { val lifecycle = LocalLifecycleOwner.current.lifecycle var state by remember(lifecycle) { mutableStateOf(lifecycle.currentState) } DisposableEffect(lifecycle) { val observer = LifecycleEventObserver { _, event -> state = event.targetState } lifecycle.addObserver(observer) onDispose { lifecycle.removeObserver(observer) } } return state } fun Context.lookupLifecycleOwner(): LifecycleOwner? { return when (this) { is LifecycleOwner -> this is ContextWrapper -> baseContext.lookupLifecycleOwner() else -> null } }
lawnchair/src/app/lawnchair/util/lifecycle.kt
1842681461
package io.dev.temperature.verticles import io.dev.temperature.BusAddresses import io.dev.temperature.model.NextScheduledTemp import io.dev.temperature.model.Schedule import io.vertx.core.AbstractVerticle import io.vertx.core.Vertx import io.vertx.core.json.JsonArray import io.vertx.core.json.JsonObject import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.File import java.time.LocalDateTime import java.time.temporal.ChronoUnit class ScheduleVerticle(val scheduleFilePath: String = "./schedule.json") : AbstractVerticle() { val log: Logger = LoggerFactory.getLogger(ScheduleVerticle::class.java) val EMPTY_SCHEDULE = JsonObject(). put("active", false). put("days", JsonArray(). add(JsonObject(). put("name", "Mon"). put("hours", JsonArray())). add(JsonObject(). put("name", "Tue"). put("hours", JsonArray())). add(JsonObject(). put("name", "Wed"). put("hours", JsonArray())). add(JsonObject(). put("name", "Thu"). put("hours", JsonArray())). add(JsonObject(). put("name", "Fri"). put("hours", JsonArray())). add(JsonObject(). put("name", "Sat"). put("hours", JsonArray())). add(JsonObject(). put("name", "Sun"). put("hours", JsonArray())) ) var currentSchedule: JsonObject? = null var scheduleFile: File? = null var currentTimer: Long = 0 var nextTemperatureSetup: NextScheduledTemp? = null override fun start() { scheduleFile = File(scheduleFilePath) if (!scheduleFile!!.exists()) { scheduleFile!!.createNewFile() scheduleFile!!.writeText(EMPTY_SCHEDULE.encodePrettily()) } currentSchedule = JsonObject(scheduleFile!!.readText()) vertx.eventBus().consumer<JsonObject>(BusAddresses.Schedule.SCHEDULE_GET_CURRENT, { message -> message.reply(currentSchedule) }) vertx.eventBus().consumer<JsonObject>(BusAddresses.Schedule.SCHEDULE_SAVE, { message -> currentSchedule = message.body() message.reply(currentSchedule) vertx.eventBus().publish(BusAddresses.Schedule.SCHEDULE_UPDATED, currentSchedule) }) vertx.eventBus().consumer<JsonObject>(BusAddresses.Schedule.SCHEDULE_GET_NEXT_UPDATE, { message -> message.reply(nextTemperatureSetup?.toJson()) }) vertx.eventBus().consumer<JsonObject>(BusAddresses.Schedule.SCHEDULE_UPDATED, { message -> val newSchedule = message.body() if (scheduleFile == null) { scheduleFile = File(scheduleFilePath) } scheduleFile!!.writeText(newSchedule.encodePrettily()) log.info("Saved new Schedule to file [${scheduleFile?.absolutePath}]") if (!currentTimer.equals(0)) { log.info("Canceling previously scheduled temperature setup") vertx.cancelTimer(currentTimer) currentTimer = 0 nextTemperatureSetup = null } if (shouldScheduleNextJob(currentSchedule)) { currentTimer = scheduleNextJob(currentSchedule, vertx) } }) if (shouldScheduleNextJob(currentSchedule)) { currentTimer = scheduleNextJob(currentSchedule, vertx) } else { log.info("There is no Active schedule at the moment.") } log.info("Started Schedule verticle") } private fun shouldScheduleNextJob(schedule: JsonObject?): Boolean { return (schedule != null && schedule.getBoolean("active", false)) } private fun scheduleNextJob(scheduleJson: JsonObject?, vertx: Vertx): Long { val schedule = Schedule.fromJson(scheduleJson!!) val now = LocalDateTime.now() val nextScheduledTemp = schedule.nextScheduledTemp(now) ?: return 0 nextTemperatureSetup = nextScheduledTemp val delay = now.until(nextScheduledTemp.time, ChronoUnit.MILLIS) log.info("Scheduling next temperature setup [${nextScheduledTemp}]") return vertx.setTimer(delay, { vertx.eventBus().send<Float>(BusAddresses.Serial.SET_TEMPERATURE_IN_ARDUINO, nextScheduledTemp.temp, { responseMessage -> if (responseMessage.failed()) { log.error("Unable to send new temperature setup", responseMessage.cause()) } currentTimer = scheduleNextJob(currentSchedule, vertx) }) }) } }
temperature-sensor-and-rest/src/main/kotlin/io/dev/temperature/verticles/ScheduleVerticle.kt
1587326611
package com.example.jingbin.cloudreader.bean /** * Created by jingbin on 2020/12/3. */ class CoinLogBean { /** * coinCount : 12 * date : 1569468233000 * desc : 2019-09-26 11:23:53 分享文章 , 积分:10 + 2 * id : 53889 * reason : 分享文章 * type : 3 * userId : 1534 * userName : jingbin */ val coinCount = 0 val date: Long = 0 val desc: String? = null val id = 0 val reason: String? = null val type = 0 val userId = 0 val username: String? = null val nickname: String? = null }
app/src/main/java/com/example/jingbin/cloudreader/bean/CoinLogBean.kt
284605810
package com.xception.messaging.features.channels.fragments import android.app.AlertDialog import android.content.Context import android.os.Bundle import android.support.v7.widget.DividerItemDecoration import android.support.design.widget.FloatingActionButton import android.support.design.widget.TextInputEditText import android.text.InputType import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.airbnb.epoxy.EpoxyModel import com.airbnb.epoxy.EpoxyRecyclerView import com.sendbird.android.OpenChannel import com.xception.messaging.R import com.xception.messaging.features.channels.items.ChannelModel_ import com.xception.messaging.features.channels.presenters.ChannelItemData import com.xception.messaging.features.channels.presenters.ChannelListPresenter import com.xception.messaging.features.channels.presenters.ChannelListView import com.xception.messaging.features.commons.BaseFragment class ChannelListFragment : BaseFragment(), ChannelListView { lateinit var mChannelListPresenter: ChannelListPresenter lateinit var mRecyclerView: EpoxyRecyclerView lateinit var mFragmentListener: Listener override fun onAttach(context: Context?) { super.onAttach(context) if (context is Listener) { mFragmentListener = context } } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater!!.inflate(R.layout.fragment_channel_list, container, false) mChannelListPresenter = ChannelListPresenter(this) mRecyclerView = view.findViewById(R.id.channel_list_epoxy_recycler_view) mRecyclerView.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) val mCreateChannelButton : FloatingActionButton = view.findViewById(R.id.channel_list_create_channel_button) mCreateChannelButton.setOnClickListener({ mChannelListPresenter.onAskToCreateChannelClicked()}) return view } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mChannelListPresenter.onViewCreated() } override fun onResume() { super.onResume() mChannelListPresenter.onViewResumed() } override fun onDestroyView() { super.onDestroyView() mChannelListPresenter.onViewDestroyed() } // region ChannelListView override fun showContent(channels: List<ChannelItemData>) { mRecyclerView.buildModelsWith { controller -> channels.forEach { ChannelModel_() .id(it.url) .channel(it) .addTo(controller) } } } override fun updateContent(channels: List<ChannelItemData>) { // Generate the new models val channelModels = ArrayList<EpoxyModel<View>>(channels.size) channels.forEach { channelModels.add( ChannelModel_() .id(it.url) .channel(it) ) } // Update the models in the recycler view mRecyclerView.setModels(channelModels) } override fun showChannelCreationForm() { // Edit text to enter the channel name val input = TextInputEditText(activity) input.setHint(R.string.channel_creation_input_hint) input.maxLines = 1 input.inputType = InputType.TYPE_CLASS_TEXT // Dialog to let the user enter its channel name AlertDialog.Builder(activity) .setTitle(R.string.channel_creation_title) .setView(input) .setPositiveButton(R.string.channel_creation_create_button, { _, _ -> mChannelListPresenter.onCreateChannelConfirmationClicked(input.text.toString()) }) .setNegativeButton(R.string.channel_creation_cancel_button, { dialog, _ -> dialog.cancel() }) .show() } override fun goToConversation(channel: OpenChannel) { mFragmentListener.showConversation(channel) } // endregion companion object { fun newInstance() = ChannelListFragment() } interface Listener { fun showConversation(channel: OpenChannel) } }
app/src/main/java/com/xception/messaging/features/channels/fragments/ChannelListFragment.kt
499350832
package net.yslibrary.monotweety.setting.domain import io.reactivex.Observable import io.reactivex.functions.BiFunction import io.reactivex.subjects.PublishSubject import net.yslibrary.monotweety.appdata.setting.SettingDataManager import javax.inject.Inject import javax.inject.Singleton @Singleton class FooterStateManager @Inject constructor( private val settingDataManager: SettingDataManager ) { private val subject: PublishSubject<Unit> = PublishSubject.create() fun get(): Observable<State> { return subject .startWith(Unit) .switchMapSingle { Observable.zip( settingDataManager.footerEnabled(), settingDataManager.footerText(), BiFunction { enabled: Boolean, footer: String -> State(enabled, footer) } ).firstOrError() } } fun set(state: State) { settingDataManager.footerEnabled(state.enabled) settingDataManager.footerText(state.text.trim()) subject.onNext(Unit) } data class State( val enabled: Boolean, val text: String ) }
app/src/main/java/net/yslibrary/monotweety/setting/domain/FooterStateManager.kt
1667948944
package transformers import org.jetbrains.dokka.DokkaConfiguration.DokkaSourceSet import org.jetbrains.dokka.base.transformers.documentables.ModuleAndPackageDocumentationReader import org.jetbrains.dokka.links.DRI import org.jetbrains.dokka.model.doc.DocumentationNode import org.jetbrains.dokka.plugability.DokkaContext import org.jetbrains.dokka.testApi.logger.TestLogger import org.jetbrains.dokka.utilities.DokkaConsoleLogger import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import testApi.testRunner.TestDokkaConfigurationBuilder import testApi.testRunner.dModule import testApi.testRunner.dPackage class ContextModuleAndPackageDocumentationReaderTest1 : AbstractContextModuleAndPackageDocumentationReaderTest() { private val includeSourceSetA by lazy { temporaryDirectory.resolve("includeA.md").toFile() } private val includeSourceSetB by lazy { temporaryDirectory.resolve("includeB.md").toFile() } @BeforeEach fun materializeIncludes() { includeSourceSetA.writeText( """ # Module moduleA This is moduleA # Package sample.a This is package sample.a\r\n # Package noise.b This will just add some noise """.trimIndent().replace("\n", "\r\n") ) includeSourceSetB.writeText( """ # Module moduleB This is moduleB # Package sample.b This is package sample.b # Package noise.b This will just add some more noise """.trimIndent() ) } private val configurationBuilder = TestDokkaConfigurationBuilder().apply { moduleName = "moduleA" } private val sourceSetA by configurationBuilder.sourceSet { name = "sourceSetA" includes = listOf(includeSourceSetA.canonicalPath) } private val sourceSetB by configurationBuilder.sourceSet { name = "sourceSetB" includes = listOf(includeSourceSetB.canonicalPath) } private val sourceSetB2 by configurationBuilder.sourceSet { name = "sourceSetB2" includes = emptyList() } private val context by lazy { DokkaContext.create( configuration = configurationBuilder.build(), logger = TestLogger(DokkaConsoleLogger()), pluginOverrides = emptyList() ) } private val reader by lazy { ModuleAndPackageDocumentationReader(context) } @Test fun `assert moduleA with sourceSetA`() { val documentation = reader[dModule(name = "moduleA", sourceSets = setOf(sourceSetA))] assertEquals( 1, documentation.keys.size, "Expected moduleA only containing documentation in a single source set" ) assertEquals( "sourceSetA", documentation.keys.single().sourceSetID.sourceSetName, "Expected moduleA documentation coming from sourceSetA" ) assertEquals( "This is moduleA", documentation.texts.single(), "Expected moduleA documentation being present" ) } @Test fun `assert moduleA with no source sets`() { val documentation = reader[dModule("moduleA")] assertEquals( emptyMap<DokkaSourceSet, DocumentationNode>(), documentation, "Expected no documentation received for module not declaring a matching sourceSet" ) } @Test fun `assert moduleA with unknown source set`() { assertThrows<IllegalStateException>( "Expected no documentation received for module with unknown sourceSet" ) { reader[ dModule("moduleA", sourceSets = setOf(configurationBuilder.unattachedSourceSet { name = "unknown" })) ] } } @Test fun `assert moduleA with all sourceSets`() { val documentation = reader[dModule("moduleA", sourceSets = setOf(sourceSetA, sourceSetB, sourceSetB2))] assertEquals(1, documentation.entries.size, "Expected only one entry from sourceSetA") assertEquals(sourceSetA, documentation.keys.single(), "Expected only one entry from sourceSetA") assertEquals("This is moduleA", documentation.texts.single()) } @Test fun `assert moduleB with sourceSetB and sourceSetB2`() { val documentation = reader[dModule("moduleB", sourceSets = setOf(sourceSetB, sourceSetB2))] assertEquals(1, documentation.keys.size, "Expected only one entry from sourceSetB") assertEquals(sourceSetB, documentation.keys.single(), "Expected only one entry from sourceSetB") assertEquals("This is moduleB", documentation.texts.single()) } @Test fun `assert sample_A in sourceSetA`() { val documentation = reader[dPackage(DRI("sample.a"), sourceSets = setOf(sourceSetA))] assertEquals(1, documentation.keys.size, "Expected only one entry from sourceSetA") assertEquals(sourceSetA, documentation.keys.single(), "Expected only one entry from sourceSetA") assertEquals("This is package sample.a\\r\\n", documentation.texts.single()) } @Test fun `assert sample_a_sub in sourceSetA`() { val documentation = reader[dPackage(DRI("sample.a.sub"), sourceSets = setOf(sourceSetA))] assertEquals( emptyMap<DokkaSourceSet, DocumentationNode>(), documentation, "Expected no documentation found for different package" ) } @Test fun `assert sample_a in sourceSetB`() { val documentation = reader[dPackage(DRI("sample.a"), sourceSets = setOf(sourceSetB))] assertEquals( emptyMap<DokkaSourceSet, DocumentationNode>(), documentation, "Expected no documentation found for different sourceSet" ) } @Test fun `assert sample_b in sourceSetB`() { val documentation = reader[dPackage(DRI("sample.b"), sourceSets = setOf(sourceSetB))] assertEquals(1, documentation.keys.size, "Expected only one entry from sourceSetB") assertEquals(sourceSetB, documentation.keys.single(), "Expected only one entry from sourceSetB") assertEquals("This is package sample.b", documentation.texts.single()) } @Test fun `assert sample_b in sourceSetB and sourceSetB2`() { val documentation = reader[dPackage(DRI("sample.b"), sourceSets = setOf(sourceSetB, sourceSetB2))] assertEquals(1, documentation.keys.size, "Expected only one entry from sourceSetB") assertEquals(sourceSetB, documentation.keys.single(), "Expected only one entry from sourceSetB") assertEquals("This is package sample.b", documentation.texts.single()) } }
plugins/base/src/test/kotlin/transformers/ContextModuleAndPackageDocumentationReaderTest1.kt
1724338806
/* * Copyright (c) 2017. Marius Reimer * * 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 de.reimerm.splintersweets.actors.scene2d import com.badlogic.gdx.scenes.scene2d.Actor import com.badlogic.gdx.scenes.scene2d.ui.ImageButton import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener import com.badlogic.gdx.scenes.scene2d.utils.Drawable import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable import de.reimerm.splintersweets.utils.AssetsManager import de.reimerm.splintersweets.utils.AudioUtils import de.reimerm.splintersweets.utils.Resources /** * Created by Marius Reimer on 05-Oct-16. */ class AudioButton : ImageButton { private var imageOn: Drawable private var imageOff: Drawable constructor(imageUp: Drawable) : super(imageUp) { imageOn = TextureRegionDrawable(AssetsManager.textureMap[Resources.RegionNames.BUTTON_AUDIO_ON.name]) imageOff = TextureRegionDrawable(AssetsManager.textureMap[Resources.RegionNames.BUTTON_AUDIO_OFF.name]) addListener(object : ChangeListener() { override fun changed(event: ChangeEvent?, actor: Actor?) { if (AudioUtils.isMusicOn() == true) { AudioUtils.stopMusic() } AudioUtils.toggleMusicPreference() AudioUtils.playBackgroundMusic() if (AudioUtils.isMusicPreferenceTrue()) { style.imageUp = imageOn } else { style.imageUp = imageOff } } }) } }
core/src/de/reimerm/splintersweets/actors/scene2d/AudioButton.kt
359667832
package test import io.jentz.winter.Component import io.jentz.winter.Graph import io.jentz.winter.TypeKey import io.jentz.winter.inject.Factory import java.util.concurrent.atomic.AtomicBoolean import javax.annotation.Generated import kotlin.Boolean @Generated( value = ["io.jentz.winter.compiler.WinterProcessor"], date = "2019-02-10T14:52Z" ) class FactoryTypeAnnotation_WinterFactory : Factory<AtomicBoolean> { override fun invoke(graph: Graph): AtomicBoolean = FactoryTypeAnnotation() override fun register(builder: Component.Builder, override: Boolean): TypeKey<AtomicBoolean> = builder.prototype(override = override, factory = this) }
winter-compiler/src/test/resources/FactoryTypeAnnotation_WinterFactory.kt
1205055874
package baltamon.mx.pokedexmvp.type import baltamon.mx.pokedexmvp.models.NamedAPIResource /** * Created by Baltazar Rodriguez on 05/07/2017. */ interface TypesView { fun onPokemonTypes(types: ArrayList<NamedAPIResource>) }
app/src/main/java/baltamon/mx/pokedexmvp/type/TypesView.kt
881016435
/* * This file is generated by jOOQ. */ package link.kotlin.server.jooq.main.tables.records import link.kotlin.server.jooq.main.tables.Kotliner import org.jooq.Field import org.jooq.Record1 import org.jooq.Record10 import org.jooq.Row10 import org.jooq.impl.UpdatableRecordImpl /** * This class is generated by jOOQ. */ @Suppress("UNCHECKED_CAST") open class KotlinerRecord() : UpdatableRecordImpl<KotlinerRecord>(Kotliner.KOTLINER), Record10<Long?, String?, String?, String?, String?, String?, String?, String?, String?, String?> { open var id: Long? set(value): Unit = set(0, value) get(): Long? = get(0) as Long? open var avatar: String? set(value): Unit = set(1, value) get(): String? = get(1) as String? open var description: String? set(value): Unit = set(2, value) get(): String? = get(2) as String? open var normalizedEmail: String? set(value): Unit = set(3, value) get(): String? = get(3) as String? open var originalEmail: String? set(value): Unit = set(4, value) get(): String? = get(4) as String? open var firstName: String? set(value): Unit = set(5, value) get(): String? = get(5) as String? open var lastName: String? set(value): Unit = set(6, value) get(): String? = get(6) as String? open var nickname: String? set(value): Unit = set(7, value) get(): String? = get(7) as String? open var password: String? set(value): Unit = set(8, value) get(): String? = get(8) as String? open var totp: String? set(value): Unit = set(9, value) get(): String? = get(9) as String? // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- override fun key(): Record1<Long?> = super.key() as Record1<Long?> // ------------------------------------------------------------------------- // Record10 type implementation // ------------------------------------------------------------------------- override fun fieldsRow(): Row10<Long?, String?, String?, String?, String?, String?, String?, String?, String?, String?> = super.fieldsRow() as Row10<Long?, String?, String?, String?, String?, String?, String?, String?, String?, String?> override fun valuesRow(): Row10<Long?, String?, String?, String?, String?, String?, String?, String?, String?, String?> = super.valuesRow() as Row10<Long?, String?, String?, String?, String?, String?, String?, String?, String?, String?> override fun field1(): Field<Long?> = Kotliner.KOTLINER.ID override fun field2(): Field<String?> = Kotliner.KOTLINER.AVATAR override fun field3(): Field<String?> = Kotliner.KOTLINER.DESCRIPTION override fun field4(): Field<String?> = Kotliner.KOTLINER.NORMALIZED_EMAIL override fun field5(): Field<String?> = Kotliner.KOTLINER.ORIGINAL_EMAIL override fun field6(): Field<String?> = Kotliner.KOTLINER.FIRST_NAME override fun field7(): Field<String?> = Kotliner.KOTLINER.LAST_NAME override fun field8(): Field<String?> = Kotliner.KOTLINER.NICKNAME override fun field9(): Field<String?> = Kotliner.KOTLINER.PASSWORD override fun field10(): Field<String?> = Kotliner.KOTLINER.TOTP override fun component1(): Long? = id override fun component2(): String? = avatar override fun component3(): String? = description override fun component4(): String? = normalizedEmail override fun component5(): String? = originalEmail override fun component6(): String? = firstName override fun component7(): String? = lastName override fun component8(): String? = nickname override fun component9(): String? = password override fun component10(): String? = totp override fun value1(): Long? = id override fun value2(): String? = avatar override fun value3(): String? = description override fun value4(): String? = normalizedEmail override fun value5(): String? = originalEmail override fun value6(): String? = firstName override fun value7(): String? = lastName override fun value8(): String? = nickname override fun value9(): String? = password override fun value10(): String? = totp override fun value1(value: Long?): KotlinerRecord { this.id = value return this } override fun value2(value: String?): KotlinerRecord { this.avatar = value return this } override fun value3(value: String?): KotlinerRecord { this.description = value return this } override fun value4(value: String?): KotlinerRecord { this.normalizedEmail = value return this } override fun value5(value: String?): KotlinerRecord { this.originalEmail = value return this } override fun value6(value: String?): KotlinerRecord { this.firstName = value return this } override fun value7(value: String?): KotlinerRecord { this.lastName = value return this } override fun value8(value: String?): KotlinerRecord { this.nickname = value return this } override fun value9(value: String?): KotlinerRecord { this.password = value return this } override fun value10(value: String?): KotlinerRecord { this.totp = value return this } override fun values(value1: Long?, value2: String?, value3: String?, value4: String?, value5: String?, value6: String?, value7: String?, value8: String?, value9: String?, value10: String?): KotlinerRecord { this.value1(value1) this.value2(value2) this.value3(value3) this.value4(value4) this.value5(value5) this.value6(value6) this.value7(value7) this.value8(value8) this.value9(value9) this.value10(value10) return this } /** * Create a detached, initialised KotlinerRecord */ constructor(id: Long? = null, avatar: String? = null, description: String? = null, normalizedEmail: String? = null, originalEmail: String? = null, firstName: String? = null, lastName: String? = null, nickname: String? = null, password: String? = null, totp: String? = null): this() { this.id = id this.avatar = avatar this.description = description this.normalizedEmail = normalizedEmail this.originalEmail = originalEmail this.firstName = firstName this.lastName = lastName this.nickname = nickname this.password = password this.totp = totp } /** * Create a detached, initialised KotlinerRecord */ constructor(value: link.kotlin.server.jooq.main.tables.pojos.Kotliner?): this() { if (value != null) { this.id = value.id this.avatar = value.avatar this.description = value.description this.normalizedEmail = value.normalizedEmail this.originalEmail = value.originalEmail this.firstName = value.firstName this.lastName = value.lastName this.nickname = value.nickname this.password = value.password this.totp = value.totp } } }
app-backend/src/main/kotlin/link/kotlin/server/jooq/main/tables/records/KotlinerRecord.kt
872937243
package com.jara.kotlin_myshare.channel import android.content.Context import android.content.Intent import android.text.TextUtils import com.jara.kotlin_myshare.R import com.jara.kotlin_myshare.bean.Constant import com.jara.kotlin_myshare.bean.ShareEntity import com.jara.kotlin_myshare.interfaces.OnShareListener import com.jara.kotlin_myshare.utils.ShareUtil /** * Created by jara on 2017-9-19. */ class ShareBySystemK(context: Context) : ShareBaseK(context) { override fun share(entity: ShareEntity, listener: OnShareListener) { if (entity == null || TextUtils.isEmpty(entity.content)) { return } val content = if (TextUtils.isEmpty(entity.content)) entity.title + entity.url else entity.content + entity.url val intent = Intent(Intent.ACTION_SEND) intent.putExtra(Intent.EXTRA_TEXT, content) intent.type = "text/plain" if (ShareUtil.startActivity(context , Intent.createChooser(intent, context.getString(R.string.share_to)))) { if (null != listener) { listener.onShare(Constant.SHARE_CHANNEL_SYSTEM, Constant.SHARE_STATUS_COMPLETE) } } else { if (null != listener) { listener.onShare(Constant.SHARE_CHANNEL_SYSTEM, Constant.SHARE_STATUS_FAILED) } } } }
kotlin_myshare/src/main/java/com/jara/kotlin_myshare/channel/ShareBySystemK.kt
1073694912
package org.http4k.cloudnative.health import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.junit.jupiter.api.Test class ReadinessCheckResultTest { private val success = Completed("name") private val failure = Failed("name2", "foobar") @Test fun `simple result`() { assertThat(success.pass, equalTo(true)) assertThat(failure.pass, equalTo(false)) assertThat(success, equalTo(Completed("name"))) } @Test fun `composite result collects results`() { assertThat((success + success).pass, equalTo(true)) assertThat((failure + success).pass, equalTo(false)) } }
http4k-cloudnative/src/test/kotlin/org/http4k/cloudnative/health/ReadinessCheckResultTest.kt
2874175424
package com.v2ray.ang.ui import android.os.Bundle import android.text.TextUtils import android.view.Menu import android.view.MenuItem import com.v2ray.ang.R import com.v2ray.ang.dto.AngConfig import com.v2ray.ang.util.AngConfigManager import com.v2ray.ang.util.Utils import kotlinx.android.synthetic.main.activity_server.* import org.jetbrains.anko.* class ServerActivity : BaseActivity() { companion object { private const val REQUEST_SCAN = 1 } var del_config: MenuItem? = null var save_config: MenuItem? = null private lateinit var configs: AngConfig private var edit_index: Int = -1 //当前编辑的服务器 private var edit_guid: String = "" private var isRunning: Boolean = false private val securitys: Array<out String> by lazy { resources.getStringArray(R.array.securitys) } private val networks: Array<out String> by lazy { resources.getStringArray(R.array.networks) } private val headertypes: Array<out String> by lazy { resources.getStringArray(R.array.headertypes) } private val streamsecuritys: Array<out String> by lazy { resources.getStringArray(R.array.streamsecuritys) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_server) configs = AngConfigManager.configs edit_index = intent.getIntExtra("position", -1) isRunning = intent.getBooleanExtra("isRunning", false) title = getString(R.string.title_server) if (edit_index >= 0) { edit_guid = configs.vmess[edit_index].guid bindingServer(configs.vmess[edit_index]) } else { clearServer() } supportActionBar?.setDisplayHomeAsUpEnabled(true) } /** * bingding seleced server config */ fun bindingServer(vmess: AngConfig.VmessBean): Boolean { et_remarks.text = Utils.getEditable(vmess.remarks) et_address.text = Utils.getEditable(vmess.address) et_port.text = Utils.getEditable(vmess.port.toString()) et_id.text = Utils.getEditable(vmess.id) et_alterId.text = Utils.getEditable(vmess.alterId.toString()) val security = Utils.arrayFind(securitys, vmess.security) if (security >= 0) { sp_security.setSelection(security) } val network = Utils.arrayFind(networks, vmess.network) if (network >= 0) { sp_network.setSelection(network) } val headerType = Utils.arrayFind(headertypes, vmess.headerType) if (headerType >= 0) { sp_header_type.setSelection(headerType) } et_request_host.text = Utils.getEditable(vmess.requestHost) val streamSecurity = Utils.arrayFind(streamsecuritys, vmess.streamSecurity) if (streamSecurity >= 0) { sp_stream_security.setSelection(streamSecurity) } return true } /** * clear or init server config */ fun clearServer(): Boolean { et_remarks.text = null et_address.text = null et_port.text = Utils.getEditable("10086") et_id.text = null et_alterId.text = Utils.getEditable("64") sp_security.setSelection(0) sp_network.setSelection(0) sp_header_type.setSelection(0) et_request_host.text = null sp_stream_security.setSelection(0) return true } /** * save server config */ fun saveServer(): Boolean { val vmess: AngConfig.VmessBean = AngConfig.VmessBean() vmess.guid = edit_guid vmess.remarks = et_remarks.text.toString() vmess.address = et_address.text.toString() vmess.port = Utils.parseInt(et_port.text.toString()) vmess.id = et_id.text.toString() vmess.alterId = Utils.parseInt(et_alterId.text.toString()) vmess.security = securitys[sp_security.selectedItemPosition] vmess.network = networks[sp_network.selectedItemPosition] vmess.headerType = headertypes[sp_header_type.selectedItemPosition] vmess.requestHost = et_request_host.text.toString() vmess.streamSecurity = streamsecuritys[sp_stream_security.selectedItemPosition] if (TextUtils.isEmpty(vmess.remarks)) { toast(R.string.server_lab_remarks) return false } if (TextUtils.isEmpty(vmess.address)) { toast(R.string.server_lab_address) return false } if (TextUtils.isEmpty(vmess.port.toString()) || vmess.port <= 0) { toast(R.string.server_lab_port) return false } if (TextUtils.isEmpty(vmess.id)) { toast(R.string.server_lab_id) return false } if (TextUtils.isEmpty(vmess.alterId.toString()) || vmess.alterId < 0) { toast(R.string.server_lab_alterid) return false } if (AngConfigManager.addServer(vmess, edit_index) == 0) { toast(R.string.toast_success) finish() return true } else { toast(R.string.toast_failure) return false } } /** * save server config */ fun deleteServer(): Boolean { if (edit_index >= 0) { alert(R.string.del_config_comfirm) { positiveButton(android.R.string.ok) { if (AngConfigManager.removeServer(edit_index) == 0) { toast(R.string.toast_success) finish() } else { toast(R.string.toast_failure) } } show() } } else { } return true } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.action_server, menu) del_config = menu?.findItem(R.id.del_config) save_config = menu?.findItem(R.id.save_config) if (edit_index >= 0) { if (isRunning) { if (edit_index == configs.index) { del_config?.isVisible = false save_config?.isVisible = false } } } else { del_config?.isVisible = false } return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.del_config -> { deleteServer() true } R.id.save_config -> { saveServer() true } else -> super.onOptionsItemSelected(item) } }
V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerActivity.kt
3902177199
package com.beyondtechnicallycorrect.visitordetector.deviceproviders import com.google.gson.annotations.SerializedName class ArpTableEntry( @SerializedName("HW address") val hwAddress: String, @SerializedName("IP address") val ipAddress: String )
app/src/main/kotlin/com/beyondtechnicallycorrect/visitordetector/deviceproviders/ArpTableEntry.kt
2539581242
package com.astir_trotter.atcustom.singleton import android.content.Context import com.astir_trotter.atcustom.component.AppInfo import com.astir_trotter.atcustom.singleton.lang.base.Language import com.astir_trotter.atcustom.singleton.theme.base.Theme /** * @author - Saori Sugiyama * * * @contact - [email protected] * * * @date - 4/11/17 */ class Cache private constructor() { //////////////////////////////////////////////////////////////////////////////////////////////// var isDebug: Boolean = false var context: Context? = null get() { if (field == null) throw IllegalStateException("No context registered yet.") return field } var appInfo: AppInfo? = null get() { if (field == null) throw IllegalStateException("No app info registered yet.") return field } var language: Language = Language.English var theme: Theme = Theme.Light companion object { private val TAG = Cache::class.java.simpleName private var _instance: Cache? = null val instance: Cache get() { if (_instance == null) _instance = Cache() return _instance!! } } }
projects/AndroidCustomer/atcustom/src/main/java/com/astir_trotter/atcustom/singleton/Cache.kt
636134209
package org.droidplanner.android.fragments.widget.diagnostics import android.graphics.drawable.Drawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.o3dr.services.android.lib.drone.property.EkfStatus import com.o3dr.services.android.lib.drone.property.Vibration import org.droidplanner.android.R import kotlin.properties.Delegates /** * Created by Fredia Huya-Kouadio on 8/29/15. */ public class MiniWidgetDiagnostics : BaseWidgetDiagnostic() { private val okFlagDrawable: Drawable? by lazy(LazyThreadSafetyMode.NONE) { resources?.getDrawable(R.drawable.ic_check_box_green_500_18dp) } private val badFlagDrawable: Drawable? by lazy(LazyThreadSafetyMode.NONE) { resources?.getDrawable(R.drawable.ic_cancel_red_500_18dp) } private val warningFlagDrawable by lazy(LazyThreadSafetyMode.NONE) { resources?.getDrawable(R.drawable.ic_warning_orange_500_18dp) } private val unknownFlagDrawable: Drawable? by lazy(LazyThreadSafetyMode.NONE) { resources?.getDrawable(R.drawable.ic_help_grey_600_18dp) } private val ekfStatusView by lazy(LazyThreadSafetyMode.NONE) { view?.findViewById(R.id.ekf_status) as TextView? } private val vibrationStatus by lazy(LazyThreadSafetyMode.NONE) { view?.findViewById(R.id.vibration_status) as TextView? } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.fragment_mini_widget_ekf_status, container, false) } override fun updateEkfView(ekfStatus: EkfStatus) { val ekfVar = Math.max(ekfStatus.velocityVariance, Math.max(ekfStatus.horizontalPositionVariance, Math.max(ekfStatus.verticalPositionVariance, Math.max(ekfStatus.compassVariance, ekfStatus.terrainAltitudeVariance)))) val statusDrawable = if (ekfVar < BaseWidgetDiagnostic.GOOD_VARIANCE_THRESHOLD) okFlagDrawable else if (ekfVar < BaseWidgetDiagnostic.WARNING_VARIANCE_THRESHOLD) warningFlagDrawable else badFlagDrawable ekfStatusView?.setCompoundDrawablesWithIntrinsicBounds(null, statusDrawable, null, null) } override fun disableEkfView() { ekfStatusView?.setCompoundDrawablesWithIntrinsicBounds(null, unknownFlagDrawable, null, null) } override fun updateVibrationView(vibration: Vibration){ val vibSummary = Math.max(vibration.vibrationX, Math.max(vibration.vibrationY, vibration.vibrationZ)) val statusDrawable = if(vibSummary < BaseWidgetDiagnostic.GOOD_VIBRATION_THRESHOLD) okFlagDrawable else if(vibSummary < BaseWidgetDiagnostic.WARNING_VIBRATION_THRESHOLD) warningFlagDrawable else badFlagDrawable vibrationStatus?.setCompoundDrawablesWithIntrinsicBounds(null, statusDrawable, null, null) } override fun disableVibrationView(){ vibrationStatus?.setCompoundDrawablesWithIntrinsicBounds(null, unknownFlagDrawable, null, null) } }
Android/src/org/droidplanner/android/fragments/widget/diagnostics/MiniWidgetDiagnostics.kt
1530041592
package com.retronicgames.lis import com.badlogic.gdx.Application import com.badlogic.gdx.Game import com.badlogic.gdx.Gdx import com.retronicgames.api.gdx.PlatformSupport import com.retronicgames.lis.mission.Mission1 import com.retronicgames.lis.screen.ScreenGame class LISGame(private val platformSupport: PlatformSupport) : Game() { private companion object { val MARKER = LISGame::class.java.simpleName } override fun create() { // FIXME: Remove! Gdx.app.logLevel = Application.LOG_DEBUG Gdx.app.debug(MARKER, "${platformSupport.title} v${platformSupport.version}") setScreen(ScreenGame(Mission1(this))) } fun showErrorDialog(message: String) { throw RuntimeException(message) } }
core/src/main/kotlin/com/retronicgames/lis/LISGame.kt
4253705695
/* * Copyright 2020 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * 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 tv.dotstart.beacon.ui.util import com.mindscapehq.raygun4java.core.RaygunClient import com.mindscapehq.raygun4java.core.messages.RaygunBreadcrumbLevel import tv.dotstart.beacon.ui.BeaconUiMetadata /** * Exports error reports to an external service provider if available. * * Authentication information is provided as part of the `raygun.token` resource file in the root * of the application Class-Path. * * @author Johannes Donath * @date 02/12/2020 */ object ErrorReporter { private val logger = ErrorReporter::class.logger /** * Permanently stores the authentication token which is to be transmitted for all requests to * the error reporting backend. * * When no authentication token has been configured, null is stored within this property instead. */ private val token = System.getProperty("raygun.token") ?.takeIf(String::isNotBlank) ?: this::class.java.getResourceAsStream("/raygun.token") ?.readAllBytes() ?.toString(Charsets.UTF_8) ?.takeIf(String::isNotBlank) ?.trim() /** * Evaluates whether error reporting is available. */ val available: Boolean by lazy { token != null } /** * Caches the error reporting client once initialized. */ private val client by lazy { token?.let { RaygunClient(it) .apply { setVersion(BeaconUiMetadata.version) withData("javaVersion", System.getProperty("java.version", "unknown")) withData("javaVendor", System.getProperty("java.vendor", "unknown")) withData("javaBytecodeVersion", System.getProperty("java.class.version", "unknown")) } } } /** * Submits an application error if authentication is present within the application Class-Path. * * When no authentication is given, this method simply acts as a no-op. */ operator fun invoke(ex: Throwable) { val client = client if (client == null) { logger.error("Cannot submit error report without valid authentication", ex) return } val responseCode = client.send(ex) logger.info("Submitted error report (server responded with code $responseCode)") } /** * Records a trace of an action performed within the application. * * This information is transmitted along with error records if submitted thus providing additional * information on how to reproduce a given error within the application. */ fun trace(category: String, message: String, level: RaygunBreadcrumbLevel = RaygunBreadcrumbLevel.INFO, data: Map<String, Any?> = emptyMap()) { val client = client if (client == null) { logger.debug("Ignoring breadcrumb of level $level for category \"$category\": $message") return } client.recordBreadcrumb(message) .withLevel(level) .withCategory(category) .withCustomData(data) } }
ui/src/main/kotlin/tv/dotstart/beacon/ui/util/ErrorReporter.kt
2638555846
package com.infinum.dbinspector.domain.settings.interactors import com.infinum.dbinspector.data.Sources import com.infinum.dbinspector.data.models.local.proto.input.SettingsTask import com.infinum.dbinspector.data.sources.local.proto.settings.SettingsDataStore import com.infinum.dbinspector.shared.BaseTest import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.mockk import kotlinx.coroutines.flow.flowOf import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.koin.core.module.Module import org.koin.dsl.module import org.koin.test.get @DisplayName("RemoveIgnoredTableNameInteractor tests") internal class RemoveIgnoredTableNameInteractorTest : BaseTest() { override fun modules(): List<Module> = listOf( module { factory<Sources.Local.Settings> { mockk<SettingsDataStore>() } } ) @Test fun `Non blank table name removes entity from source`() { val given: SettingsTask = mockk { every { ignoredTableName } returns "android_metadata" } val source: Sources.Local.Settings = get() val interactor = RemoveIgnoredTableNameInteractor(source) coEvery { source.store() } returns mockk { every { data } returns flowOf( mockk { every { ignoredTableNamesList } returns listOf( mockk { every { name } returns "android_metadata" } ) } ) coEvery { updateData(any()) } returns mockk { coEvery { ignoredTableNamesList } returns listOf() } } test { interactor.invoke(given) } coVerify(exactly = 2) { source.store() } } @Test fun `Empty or blank table name should not remove in data source and throws exception`() { val given: SettingsTask = mockk { every { ignoredTableName } returns "" } val source: Sources.Local.Settings = get() val interactor = RemoveIgnoredTableNameInteractor(source) coEvery { source.store() } returns mockk { coEvery { updateData(any()) } returns mockk { coEvery { ignoredTableNamesList } returns listOf() } } test { assertThrows<IllegalStateException> { interactor.invoke(given) } } coVerify(exactly = 0) { source.store() } } }
dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/settings/interactors/RemoveIgnoredTableNameInteractorTest.kt
3211089727
/* * 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 org.jetbrains.kotlin.js.inline import org.jetbrains.kotlin.js.backend.ast.* import org.jetbrains.kotlin.js.backend.ast.metadata.isSuspend import org.jetbrains.kotlin.js.backend.ast.metadata.staticRef import org.jetbrains.kotlin.js.backend.ast.metadata.synthetic import org.jetbrains.kotlin.js.inline.clean.removeDefaultInitializers import org.jetbrains.kotlin.js.inline.context.InliningContext import org.jetbrains.kotlin.js.inline.util.* import org.jetbrains.kotlin.js.inline.util.rewriters.ReturnReplacingVisitor import org.jetbrains.kotlin.js.translate.context.Namer class FunctionInlineMutator private constructor( private val call: JsInvocation, private val inliningContext: InliningContext ) { private val invokedFunction: JsFunction private val namingContext = inliningContext.newNamingContext() private val body: JsBlock private var resultExpr: JsExpression? = null private var resultName: JsName? = null private var breakLabel: JsLabel? = null private val currentStatement = inliningContext.statementContext.currentNode init { val functionContext = inliningContext.functionContext invokedFunction = uncoverClosure(functionContext.getFunctionDefinition(call).deepCopy()) body = invokedFunction.body } private fun process() { val arguments = getArguments() val parameters = getParameters() removeDefaultInitializers(arguments, parameters, body) aliasArgumentsIfNeeded(namingContext, arguments, parameters) renameLocalNames(namingContext, invokedFunction) processReturns() namingContext.applyRenameTo(body) resultExpr = resultExpr?.let { namingContext.applyRenameTo(it) as JsExpression } } private fun uncoverClosure(invokedFunction: JsFunction): JsFunction { val innerFunction = invokedFunction.getInnerFunction() val innerCall = getInnerCall(call.qualifier) return if (innerCall != null && innerFunction != null) { innerFunction.apply { replaceThis(body) applyCapturedArgs(innerCall, this, invokedFunction) } } else { invokedFunction.apply { replaceThis(body) } } } private fun getInnerCall(qualifier: JsExpression): JsInvocation? { return when (qualifier) { is JsInvocation -> qualifier is JsNameRef -> { val callee = if (qualifier.ident == Namer.CALL_FUNCTION) qualifier.qualifier else (qualifier.name?.staticRef as? JsExpression) callee?.let { getInnerCall(it) } } else -> null } } private fun applyCapturedArgs(call: JsInvocation, inner: JsFunction, outer: JsFunction) { val namingContext = inliningContext.newNamingContext() val arguments = call.arguments val parameters = outer.parameters aliasArgumentsIfNeeded(namingContext, arguments, parameters) namingContext.applyRenameTo(inner) } private fun replaceThis(block: JsBlock) { if (!hasThisReference(block)) return var thisReplacement = getThisReplacement(call) if (thisReplacement == null || thisReplacement is JsLiteral.JsThisRef) return val thisName = namingContext.getFreshName(getThisAlias()) namingContext.newVar(thisName, thisReplacement) thisReplacement = thisName.makeRef() replaceThisReference(block, thisReplacement) } private fun processReturns() { resultExpr = getResultReference() val breakName = namingContext.getFreshName(getBreakLabel()) this.breakLabel = JsLabel(breakName).apply { synthetic = true } val visitor = ReturnReplacingVisitor(resultExpr as? JsNameRef, breakName.makeRef(), invokedFunction, call.isSuspend) visitor.accept(body) } private fun getResultReference(): JsNameRef? { if (!isResultNeeded(call)) return null val resultName = namingContext.getFreshName(getResultLabel()) this.resultName = resultName namingContext.newVar(resultName, null) return resultName.makePHPVarRef() } private fun getArguments(): List<JsExpression> { val arguments = call.arguments if (isCallInvocation(call)) { return arguments.subList(1, arguments.size) } return arguments } private fun isResultNeeded(call: JsInvocation): Boolean { return currentStatement !is JsExpressionStatement || call != currentStatement.expression } private fun getParameters(): List<JsParameter> { return invokedFunction.parameters } private fun getResultLabel(): String { return getLabelPrefix() + "result" } private fun getBreakLabel(): String { return getLabelPrefix() + "break" } private fun getThisAlias(): String { return "\$this" } fun getLabelPrefix(): String { val ident = getSimpleIdent(call) val labelPrefix = ident ?: "inline$" if (labelPrefix.endsWith("$")) { return labelPrefix } return labelPrefix + "$" } companion object { @JvmStatic fun getInlineableCallReplacement(call: JsInvocation, inliningContext: InliningContext): InlineableResult { val mutator = FunctionInlineMutator(call, inliningContext) mutator.process() var inlineableBody: JsStatement = mutator.body val breakLabel = mutator.breakLabel if (breakLabel != null) { breakLabel.statement = inlineableBody inlineableBody = breakLabel } return InlineableResult(inlineableBody, mutator.resultExpr) } @JvmStatic private fun getThisReplacement(call: JsInvocation): JsExpression? { if (isCallInvocation(call)) { return call.arguments[0] } if (hasCallerQualifier(call)) { return getCallerQualifier(call) } return null } private fun hasThisReference(body: JsBlock): Boolean { val thisRefs = collectInstances(JsLiteral.JsThisRef::class.java, body) return !thisRefs.isEmpty() } } }
k2php/src/org/jetbrains/kotlin/js/inline/FunctionInlineMutator.kt
3194546720
package pl.loziuu.ivms.presentation.user import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.ResponseEntity import org.springframework.stereotype.Service import pl.loziuu.ivms.identity.user.application.UserQueryService import pl.loziuu.ivms.identity.user.application.UserService import pl.loziuu.ivms.presentation.RestResponse import pl.loziuu.ivms.presentation.user.requests.ChangePasswordRequest import pl.loziuu.ivms.presentation.user.requests.ChangeRoleRequest import pl.loziuu.ivms.presentation.user.requests.NewUserRequest @Service class UserAdapter(@Autowired val queryService: UserQueryService, @Autowired val commandService: UserService) { fun getAll(): ResponseEntity<Any> = ResponseEntity.ok(queryService.getAll()) fun addUser(request: NewUserRequest): ResponseEntity<Any> { commandService.addUser(request.login, request.password) return RestResponse("User created", 201).toResponseEntity() } fun activate(id: Long): ResponseEntity<Any> { commandService.activate(id) return RestResponse("User activated").toResponseEntity() } fun deactivate(id: Long): ResponseEntity<Any> { commandService.deactivate(id) return RestResponse("User deactivated").toResponseEntity() } fun changePassword(id: Long, request: ChangePasswordRequest): ResponseEntity<Any> { commandService.changePassword(id, request.password) return RestResponse("Password changed").toResponseEntity() } fun changeRole(id: Long, request: ChangeRoleRequest): ResponseEntity<Any> { commandService.changeRole(id, request.role) return RestResponse("Role changed").toResponseEntity() } }
ivms/src/main/kotlin/pl/loziuu/ivms/presentation/user/UserAdapter.kt
3832694209
package com.social.com.domain.model /** * Created by igor on 3/27/17. */ data class LoginResponse(val status: String?)
domain/src/main/java/com/social/com/domain/model/LoginResponse.kt
4124497858
package `in`.yeng.user.helpers import android.animation.ObjectAnimator import android.view.View import android.view.animation.AccelerateInterpolator import android.view.animation.DecelerateInterpolator object AnimUtil { fun fadeDown(view: View, duration: Long = 1200, initialOffset: Float = 100f, scaleValue: Float = 0.9f) { val translate = ObjectAnimator.ofFloat(view, "translationY", -initialOffset, 0f) translate.duration = duration translate.interpolator = DecelerateInterpolator(2f) translate.start() val alpha = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f) alpha.duration = duration * 8 / 10 alpha.interpolator = AccelerateInterpolator(0.9f) alpha.start() val scale = ObjectAnimator.ofFloat(view, "scaleX", scaleValue, 1f) scale.duration = duration * 8 / 10 scale.interpolator = DecelerateInterpolator(2f) scale.start() } fun fadeUp(view: View, duration: Long = 1200, initialOffset: Float = 100f, scaleValue: Float = 0.9f) { val translate = ObjectAnimator.ofFloat(view, "translationY", initialOffset, 0f) translate.duration = duration translate.interpolator = DecelerateInterpolator(2f) translate.start() val alpha = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f) alpha.duration = duration * 8 / 10 alpha.interpolator = AccelerateInterpolator(0.9f) alpha.start() val scale = ObjectAnimator.ofFloat(view, "scaleX", scaleValue, 1f) scale.duration = duration * 8 / 10 scale.interpolator = DecelerateInterpolator(2f) scale.start() } fun fadeIn(view: View, duration: Long = 1200, scaleValue: Float = 0.95f) { val alpha = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f) alpha.duration = duration alpha.interpolator = AccelerateInterpolator(0.9f) alpha.start() val scale = ObjectAnimator.ofFloat(view, "scaleX", scaleValue, 1f) scale.duration = duration * 8 / 10 scale.interpolator = DecelerateInterpolator(2f) scale.start() } fun clickAnimation(view: View) { val scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1f, 0.95f, 1f) scaleX.duration = 200 scaleX.start() val scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 0.95f, 1f) scaleY.duration = 300 scaleY.start() } }
app/src/main/java/in/yeng/user/helpers/AnimUtil.kt
942038918
package fi.evident.apina import fi.evident.apina.java.reader.Classpath import fi.evident.apina.model.settings.Platform.* import fi.evident.apina.model.settings.TranslationSettings import fi.evident.apina.output.swift.SwiftGenerator import fi.evident.apina.output.ts.TypeScriptAngularGenerator import fi.evident.apina.output.ts.TypeScriptES6Generator import fi.evident.apina.spring.SpringModelReader import org.slf4j.LoggerFactory class ApinaProcessor(private val classpath: Classpath) { val settings = TranslationSettings() fun process(): String { val api = SpringModelReader.readApiDefinition(classpath, settings) log.debug("Loaded {} endpoint groups with {} endpoints.", api.endpointGroupCount, api.endpointCount) log.trace("Loaded endpoint groups: {}", api.endpointGroups) if (api.endpointCount == 0) { log.warn("Apina could not find any endpoints to process") } log.debug("Loaded {} class definitions", api.classDefinitionCount) log.trace("Loaded class definitions: {}", api.classDefinitions) log.debug("Loaded {} enum definitions", api.enumDefinitionCount) log.trace("Loaded enum definitions: {}", api.enumDefinitions) val unknownTypes = api.unknownTypeReferences if (!unknownTypes.isEmpty()) { log.warn("Writing {} unknown class definitions as black boxes: {}", unknownTypes.size, unknownTypes) } @Suppress("DEPRECATION") return when (settings.platform) { ANGULAR -> TypeScriptAngularGenerator(api, settings).run { writeApi() output } ANGULAR2 -> { log.warn("Platform.ANGULAR2 is deprecated, use Platform.ANGULAR instead") TypeScriptAngularGenerator(api, settings).run { writeApi() output } } ES6 -> TypeScriptES6Generator(api, settings).run { writeApi() output } SWIFT -> SwiftGenerator(api, settings).run { log.warn("Apina's Swift-support is incubating and will have breaking changes in minor releases") writeApi() output } } } companion object { private val log = LoggerFactory.getLogger(ApinaProcessor::class.java) } }
apina-core/src/main/kotlin/fi/evident/apina/ApinaProcessor.kt
2300196554
/* * Copyright (c) 2018. * * 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 nl.adaptivity.process.processModel.engine import kotlinx.serialization.Serializable import kotlinx.serialization.Serializer import kotlinx.serialization.* import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import nl.adaptivity.process.ProcessConsts import nl.adaptivity.process.processModel.* import nl.adaptivity.process.processModel.ProcessModel.BuildHelper import nl.adaptivity.serialutil.DelegatingSerializer import nl.adaptivity.xmlutil.serialization.XmlDefault import nl.adaptivity.xmlutil.serialization.XmlSerialName /** * Class representing an activity in a process engine. Activities are expected * to invoke one (and only one) web service. Some services are special in that * they either invoke another process (and the process engine can treat this * specially in later versions), or set interaction with the user. Services can * use the ActivityResponse soap header to indicate support for processes and * what the actual state of the task after return should be (instead of * * @author Paul de Vrieze */ class XmlActivity : ActivityBase, XmlProcessNode, CompositeActivity, MessageActivity { override var message: IXmlMessage? get() = field private set(value) { field = XmlMessage.from(value) } override val childModel: ChildProcessModel<ProcessNode>? val childId: String? private var xmlCondition: XmlCondition? = null override val condition: Condition? get() = xmlCondition constructor( builder: MessageActivity.Builder, newOwner: ProcessModel<*>, otherNodes: Iterable<ProcessNode.Builder> ) : super(builder.ensureExportable(), newOwner, otherNodes) { childModel = null childId = null message = builder.message } constructor( builder: CompositeActivity.ModelBuilder, buildHelper: BuildHelper<*, *, *, *>, otherNodes: Iterable<ProcessNode.Builder> ) : super(builder.ensureExportable(), buildHelper.newOwner, otherNodes) { childModel = buildHelper.childModel(builder) childId = builder.childId message = null } constructor( builder: CompositeActivity.ReferenceBuilder, buildHelper: BuildHelper<*, *, *, *>, otherNodes: Iterable<ProcessNode.Builder> ) : super(builder.ensureExportable(), buildHelper.newOwner, otherNodes) { val id = builder.childId childModel = id?.let { buildHelper.childModel(it) } childId = id message = null } override fun builder(): Activity.Builder = when { childId == null -> MessageActivityBase.Builder(this) else -> ReferenceActivityBuilder(this) } override fun <R> visit(visitor: ProcessNode.Visitor<R>): R = when { childModel == null -> visitor.visitActivity(messageActivity = this) else -> visitor.visitActivity(compositeActivity = this) } }
PE-common/src/commonMain/kotlin/nl/adaptivity/process/processModel/engine/XmlActivity.kt
2517109335
/* * Copyright 2019 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * 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.basinmc.faucet.math import kotlin.math.roundToInt import kotlin.math.sqrt /** * @author <a href="mailto:[email protected]">Johannes Donath</a> */ data class Vector3Int(override val x: Int = 0, override val y: Int = 0, override val z: Int = 0) : Vector3<Int> { override val length: Double by lazy { sqrt(Math.pow(this.x.toDouble(), 2.0) + Math.pow(this.y.toDouble(), 2.0) + Math.pow( this.z.toDouble(), 2.0)) } override val normalized: Vector3Int by lazy { Vector3Int((this.x / this.length).roundToInt(), (this.y / this.length).roundToInt(), (this.z / this.length).roundToInt()) } override val int: Vector3Int get() = this override fun plus(addend: Int) = Vector3Int(this.x + addend, this.y + addend, this.z + addend) override fun plus(addend: Vector2<Int>) = Vector3Int(this.x + addend.x, this.y + addend.y, this.z) override fun plus(addend: Vector3<Int>) = Vector3Int(this.x + addend.x, this.y + addend.y, this.z + addend.z) override fun minus(subtrahend: Int) = Vector3Int(this.x - subtrahend, this.y - subtrahend, this.z - subtrahend) override fun minus(subtrahend: Vector2<Int>) = Vector3Int(this.x - subtrahend.x, this.y - subtrahend.y, this.z) override fun minus(subtrahend: Vector3<Int>) = Vector3Int(this.x - subtrahend.x, this.y - subtrahend.y, this.z - subtrahend.z) override fun times(factor: Int) = Vector3Int(this.x * factor, this.y * factor, this.z * factor) override fun times(factor: Vector2<Int>) = Vector3Int(this.x * factor.x, this.y * factor.y, this.z) override fun times(factor: Vector3<Int>) = Vector3Int(this.x * factor.x, this.y * factor.y, this.z * factor.z) override fun div(divisor: Int) = Vector3Int(this.x / divisor, this.y / divisor, this.z / divisor) override fun div(divisor: Vector2<Int>) = Vector3Int(this.x / divisor.x, this.y / divisor.y, this.z) override fun div(divisor: Vector3<Int>) = Vector3Int(this.x / divisor.x, this.y / divisor.y, this.z / divisor.z) override fun rem(divisor: Int) = Vector3Int(this.x % divisor, this.y % divisor, this.z % divisor) override fun rem(divisor: Vector2<Int>) = Vector3Int(this.x % divisor.x, this.y % divisor.y, this.z) override fun rem(divisor: Vector3<Int>) = Vector3Int(this.x % divisor.x, this.y % divisor.y, this.z % divisor.z) companion object : Vector3.Definition<Int> { override val zero = Vector3Int() override val one = Vector3Int(1, 1, 1) override val up = Vector3Int(0, 1, 0) override val right = Vector3Int(1, 0, 0) override val down = Vector3Int(0, -1, 0) override val left = Vector3Int(-1, 0, 0) override val forward = Vector3Int(0, 0, 1) override val backward = Vector3Int(0, 0, -1) } }
faucet/src/main/kotlin/org/basinmc/faucet/math/Vector3Int.kt
3051808443
package me.shkschneider.skeleton.ui.widget import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Rect import android.graphics.Typeface import android.util.AttributeSet import android.view.View import android.view.ViewGroup import androidx.annotation.ColorInt import androidx.annotation.IntRange import me.shkschneider.skeleton.helperx.Logger import me.shkschneider.skeleton.helperx.Metrics import me.shkschneider.skeleton.ui.ThemeHelper // <https://github.com/IvBaranov/MaterialLetterIcon> class LetterIcon : View { private var shapePaint = Paint() private var letterPaint = Paint() private var shapeColor = Color.BLACK private var letter = DEFAULT private var letterColor = Color.WHITE private var letterSize = 26 // R.dimen.textSizeBig constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr) init { shapePaint = Paint() shapePaint.style = Paint.Style.FILL shapePaint.isAntiAlias = true letterPaint = Paint() letterPaint.isAntiAlias = true setShapeColor(ThemeHelper.accentColor()) } override fun onAttachedToWindow() { super.onAttachedToWindow() val layoutParams = layoutParams ?: run { Logger.warning("ViewGroup.LayoutParams was NULL") return } if (layoutParams.width == ViewGroup.LayoutParams.WRAP_CONTENT) { val dp = Metrics.pixelsFromDp(DP.toFloat()) layoutParams.width = dp layoutParams.height = dp invalidate() } } override fun onDraw(canvas: Canvas) { val width = measuredWidth / 2 val height = measuredHeight / 2 val radius = if (width > height) height else width shapePaint.run { color = shapeColor canvas.drawCircle(width.toFloat(), height.toFloat(), radius.toFloat(), this) } letterPaint.run { color = letterColor textSize = Metrics.pixelsFromSp(letterSize.toFloat()).toFloat() getTextBounds(letter, 0, letter.length, RECT) canvas.drawText(letter, width - RECT.exactCenterX(), height - RECT.exactCenterY(), this) } } fun setShapeColor(@ColorInt color: Int) { shapeColor = color invalidate() } fun setLetter(string: String) { letter = string.replace("\\s+".toRegex(), "").toUpperCase() letter = if (letter.isNotEmpty()) letter.first().toString() else DEFAULT invalidate() } fun setLetterColor(@ColorInt color: Int) { letterColor = color invalidate() } fun setLetterSize(@IntRange(from = 0) size: Int) { letterSize = size invalidate() } fun setLetterTypeface(typeface: Typeface) { letterPaint.typeface = typeface invalidate() } companion object { private val DEFAULT = "#" private val DP = 40 private val RECT = Rect() } }
core/src/main/kotlin/me/shkschneider/skeleton/ui/widget/LetterIcon.kt
1735419522
package com.boardgamegeek.provider import android.net.Uri import android.provider.BaseColumns._ID import com.boardgamegeek.provider.BggContract.* import com.boardgamegeek.provider.BggContract.Companion.PATH_COLLECTION import com.boardgamegeek.provider.BggContract.Companion.PATH_PUBLISHERS import com.boardgamegeek.provider.BggDatabase.Tables class PublishersIdCollectionProvider : BaseProvider() { override val path = "$PATH_PUBLISHERS/#/$PATH_COLLECTION" override fun buildSimpleSelection(uri: Uri): SelectionBuilder { val publisherId = Publishers.getPublisherId(uri) return SelectionBuilder() .mapToTable(_ID, Tables.COLLECTION) .mapToTable(Games.Columns.GAME_ID, Tables.GAMES) .table(Tables.PUBLISHER_JOIN_GAMES_JOIN_COLLECTION) .whereEquals(Publishers.Columns.PUBLISHER_ID, publisherId) } }
app/src/main/java/com/boardgamegeek/provider/PublishersIdCollectionProvider.kt
3556616632
package com.stronganizer.android.repository.impl import com.stronganizer.android.repository.MeetingRepository /** * Created by valio_stoyanov on 7/30/17. */ class MeetingRepositoryImpl : MeetingRepository
Stronganizer/app/src/main/java/com/stronganizer/android/repository/impl/MeetingRepositoryImpl.kt
1644488162
package org.benji.mifuchi.controller import io.micronaut.http.MediaType import io.micronaut.http.annotation.* import org.benji.mifuchi.command.InitGameCommand import org.benji.mifuchi.common.CommandBusMiddleware data class InitializeGame(val blueUserName: String, val orangeUserName: String) @Controller("/gameCommand") class GameCommandController(private val commandBus: CommandBusMiddleware) { @Post("/init") @Produces(MediaType.APPLICATION_JSON) fun initGame(@Body initializeGame: InitializeGame): String { val commandResponse = commandBus.dispatch(InitGameCommand(initializeGame.blueUserName, initializeGame.orangeUserName)) return """{"gameId":"${commandResponse.uuid}"}""".trimIndent() } @Get("/start") @Produces(MediaType.TEXT_PLAIN) fun startGame(): String { return "Ready !!! 🦊" } }
src/main/kotlin/org/benji/mifuchi/controller/GameCommandController.kt
942063836
package nl.hannahsten.texifyidea.action.wizard.ipsum import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo import com.intellij.ui.JBIntSpinner import com.intellij.ui.components.* import nl.hannahsten.texifyidea.util.addLabeledComponent import nl.hannahsten.texifyidea.util.hbox import nl.hannahsten.texifyidea.util.text.Ipsum import java.awt.BorderLayout import java.awt.Dimension import javax.swing.* import javax.swing.border.EmptyBorder import kotlin.random.Random /** * @author Hannah Schellekens */ open class InsertDummyTextDialogWrapper : DialogWrapper(true) { /** * What type of blind text to generate. */ private val cboxBlindType = ComboBox(DummyTextData.BlindtextType.values()).apply { selectedItem = DummyTextData.BlindtextType.PARAGRAPH addItemListener { updateUi() } } /** * The amount of repetitions of blind text. */ private val intBlindRepetitions = JBIntSpinner(1, 1, 99999) /** * The amount of paragraphs of blind text. */ private val intBlindParagraphs = JBIntSpinner(1, 1, 99999) /** * The level of the blind itemize/enumerate/description. */ private val intBlindLevel = JBIntSpinner(1, 1, 999) /** * Panel containing options for the blindtext package. */ private val panelBlindtext = JPanel().apply { border = EmptyBorder(8, 0, 8, 16) layout = BoxLayout(this, BoxLayout.Y_AXIS).apply { // Flush left. alignmentX = 0.0f } val labelWidth = 140 addLabeledComponent(cboxBlindType, "Type of text:", labelWidth) addLabeledComponent(hbox(8, intBlindParagraphs, JLabel("Repetitions:"), intBlindRepetitions), "Paragraphs:", labelWidth) addLabeledComponent(intBlindLevel, "List level:", labelWidth) add(Box.createRigidArea(Dimension(0, 28))) } /** * Contains the lipsum start paragraph number (1-150). */ private val intLipsumParagraphsMin = JBIntSpinner(1, 1, 150) /** * Contains the lipsum end paragraph number (1-150). */ private val intLipsumParagraphsMax = JBIntSpinner(7, 1, 150) /** * Contains the lipsum start sentence number. */ private val intLipsumSentencesMin = JBIntSpinner(1, 1, 999) /** * Contains the lipsum end sentence number. */ private val intLipsumSentencesMax = JBIntSpinner(999, 1, 999) /** * How to separate the lipsum paragraphs. */ private val cboxLipsumSeparator = ComboBox(DummyTextData.LipsumParagraphSeparation.values()).apply { selectedItem = DummyTextData.LipsumParagraphSeparation.PARAGRAPH } /** * Panel containing options for the lipsum package. */ private val panelLipsum = JPanel().apply { border = EmptyBorder(8, 0, 8, 16) layout = BoxLayout(this, BoxLayout.Y_AXIS).apply { // Flush left. alignmentX = 0.0f } val labelWidth = 192 addLabeledComponent(hbox(8, intLipsumParagraphsMin, JLabel("to"), intLipsumParagraphsMax), "Paragraph numbers:", labelWidth) addLabeledComponent(hbox(8, intLipsumSentencesMin, JLabel("to"), intLipsumSentencesMax), "Sentence numbers:", labelWidth) addLabeledComponent(cboxLipsumSeparator, "Paragraph separation:", labelWidth) add(Box.createRigidArea(Dimension(0, 28))) } /** * Which dummy text teplate to use. */ private val cboxRawTemplate = ComboBox(Ipsum.values()).apply { selectedItem = Ipsum.TEXIFY_IDEA_IPSUM } /** * The minimum number of raw paragraphs to generate. */ private val intRawParagraphsMin = JBIntSpinner(3, 1, 99999) /** * The maximum number of raw paragraphs to generate. */ private val intRawParagraphsMax = JBIntSpinner(7, 1, 99999) /** * The minimum number of raw sentences in a paragraph. */ private val intRawSentencesMin = JBIntSpinner(2, 1, 99999) /** * The maximum number of raw sentences in a paragraph. */ private val intRawSentencessMax = JBIntSpinner(14, 1, 99999) /** * Contains the seed to generate random numbers. */ private val txtRawSeed = JBTextField(Random.nextInt().toString()) /** * Panel containing options for raw text. */ private val panelRaw = JPanel().apply { border = EmptyBorder(8, 0, 8, 16) layout = BoxLayout(this, BoxLayout.Y_AXIS).apply { // Flush left. alignmentX = 0.0f } val labelWidth = 192 addLabeledComponent(cboxRawTemplate, "Dummy text template:", labelWidth) addLabeledComponent(hbox(8, intRawParagraphsMin, JLabel("to"), intRawParagraphsMax), "Number of paragraphs:", labelWidth) addLabeledComponent(hbox(8, intRawSentencesMin, JLabel("to"), intRawSentencessMax), "Sentences per paragraph:", labelWidth) addLabeledComponent(txtRawSeed, "Seed:", labelWidth) } private val tabPane = JBTabbedPane().apply { insertTab(DummyTextData.IpsumType.BLINDTEXT.description, null, panelBlindtext, null, 0) insertTab(DummyTextData.IpsumType.LIPSUM.description, null, panelLipsum, null, 1) insertTab(DummyTextData.IpsumType.RAW.description, null, panelRaw, null, 2) } init { super.init() title = "Insert dummy text" } /** * Get the data that has been entered into the UI. */ fun extractData() = when (tabPane.selectedIndex) { 0 -> DummyTextData( ipsumType = DummyTextData.IpsumType.BLINDTEXT, blindtextType = cboxBlindType.selectedItem as DummyTextData.BlindtextType, blindtextRepetitions = intBlindRepetitions.number, blindtextParagraphs = intBlindParagraphs.number, blindtextLevel = intBlindLevel.number ) 1 -> DummyTextData( ipsumType = DummyTextData.IpsumType.LIPSUM, lipsumParagraphs = intLipsumParagraphsMin.number..intLipsumParagraphsMax.number, lipsumSentences = intLipsumSentencesMin.number..intLipsumSentencesMax.number, lipsumParagraphSeparator = cboxLipsumSeparator.selectedItem as DummyTextData.LipsumParagraphSeparation ) else -> DummyTextData( ipsumType = DummyTextData.IpsumType.RAW, rawDummyTextType = cboxRawTemplate.selectedItem as Ipsum, rawParagraphs = intRawParagraphsMin.number..intRawParagraphsMax.number, rawSentencesPerParagraph = intRawSentencesMin.number..intRawSentencessMax.number, rawSeed = txtRawSeed.text.toInt() ) } private fun updateUi() { intBlindLevel.isEnabled = cboxBlindType.item == DummyTextData.BlindtextType.ITEMIZE || cboxBlindType.item == DummyTextData.BlindtextType.DESCRIPTION || cboxBlindType.item == DummyTextData.BlindtextType.ENUMERATE intBlindRepetitions.isEnabled = cboxBlindType.item == DummyTextData.BlindtextType.PARAGRAPH intBlindParagraphs.isEnabled = cboxBlindType.item == DummyTextData.BlindtextType.PARAGRAPH } override fun createCenterPanel() = JPanel(BorderLayout()).apply { add(tabPane, BorderLayout.CENTER) updateUi() } override fun doValidate() = if (intLipsumParagraphsMax.number < intLipsumParagraphsMin.number) { ValidationInfo("Maximum must be greater than or equal to the minimum.", intLipsumParagraphsMax) } else if (intLipsumSentencesMax.number < intLipsumSentencesMin.number) { ValidationInfo("Maximum must be greater than or equal to the minimum.", intLipsumSentencesMax) } else if (intRawParagraphsMax.number < intRawParagraphsMin.number) { ValidationInfo("Maximum must be greater than or equal to the minimum.", intRawParagraphsMax) } else if (intRawSentencessMax.number < intRawSentencesMin.number) { ValidationInfo("Maximum must be greater than or equal to the minimum.", intRawSentencessMax) } else if (txtRawSeed.text.toIntOrNull() == null) { ValidationInfo("Invalid seed: must be an integer in range -2147483648 to 2147483647.", txtRawSeed) } else null }
src/nl/hannahsten/texifyidea/action/wizard/ipsum/InsertDummyTextDialogWrapper.kt
2304283261
package io.rover.sdk.experiences.services import android.os.Handler import android.os.Looper import io.rover.sdk.core.data.graphql.safeGetString import io.rover.sdk.core.data.graphql.safeOptInt import io.rover.sdk.experiences.data.events.RoverEvent import io.rover.sdk.experiences.logging.log import io.rover.sdk.experiences.platform.LocalStorage import io.rover.sdk.experiences.platform.debugExplanation import io.rover.sdk.experiences.platform.whenNotNull import org.json.JSONObject import java.util.Date import java.util.UUID import kotlin.math.max internal class SessionTracker( private val eventEmitter: EventEmitter, private val sessionStore: SessionStore, /** * The number of seconds to leave the session open for in the event that the user leaves * temporarily. */ private val keepAliveTime: Int ) { private val timerHandler = Handler(Looper.getMainLooper()) /** * Indicate a session is opening for the given session key. The Session Key should be a value * object (a Kotlin data class, a string, etc.) that properly implements hashcode, equals, and * an exhaustive version of toString(). This value object should describe the given semantic * item the user is looking at (a given experience, a given view, etc.). * * Note that the values need to be unique amongst the different event sources in the app, so be * particularly careful with string values or data class class names. * * A [sessionEventName] must be provided so that the Session Tracker can emit session viewed * after the timeout completes. */ fun enterSession( sessionKey: Any, sessionStartEvent: RoverEvent, sessionEvent: RoverEvent ) { log.v("Entering session $sessionKey") sessionStore.enterSession(sessionKey, sessionEvent) eventEmitter.trackEvent( sessionStartEvent ) } /** * Indicate a session is being left. See [enterSession] for an explanation of session key. */ private fun updateTimer() { timerHandler.removeCallbacksAndMessages(this::timerCallback) sessionStore.soonestExpiryInSeconds(keepAliveTime).whenNotNull { soonestExpiry -> if (soonestExpiry == 0) { // execute the timer callback directly. timerCallback() } else { timerHandler.postDelayed( this::timerCallback, soonestExpiry * 1000L ) } } } private fun timerCallback() { log.v("Emitting events for expired sessions.") sessionStore.collectExpiredSessions(keepAliveTime).forEach { expiredSession -> log.v("Session closed: ${expiredSession.sessionKey}") val eventToSend: RoverEvent = when (val event = expiredSession.sessionEvent) { is RoverEvent.ScreenViewed -> { event.copy(duration = expiredSession.durationSeconds) } is RoverEvent.ExperienceViewed -> { event.copy(duration = expiredSession.durationSeconds) } else -> event } eventEmitter.trackEvent(eventToSend) } updateTimer() } fun leaveSession( sessionKey: Any, sessionEndEvent: RoverEvent ) { log.v("Leaving session $sessionKey") sessionStore.leaveSession(sessionKey) eventEmitter.trackEvent(sessionEndEvent) updateTimer() } } internal class SessionStore( localStorage: LocalStorage ) { private val store = localStorage.getKeyValueStorageFor(STORAGE_IDENTIFIER) init { gc() } /** * Enters a session. * * Returns the new session's UUID, or, if a session is already active, null. */ fun enterSession(sessionKey: Any, sessionEvent: RoverEvent) { val session = getEntry(sessionKey)?.copy( // clear closedAt to avoid expiring the session if it is being re-opened. closedAt = null ) ?: SessionEntry( UUID.randomUUID(), Date(), sessionEvent, null ) setEntry(sessionKey, session) } fun leaveSession(sessionKey: Any) { val existingEntry = getEntry(sessionKey) if (existingEntry != null) { // there is indeed a session open for the given key, mark it as expiring. setEntry( sessionKey, existingEntry.copy( closedAt = Date() ) ) } } private fun getEntry(sessionKey: Any): SessionEntry? { val entryJson = store[sessionKey.toString()].whenNotNull { JSONObject(it) } return entryJson.whenNotNull { try { SessionEntry.decodeJson(it) } catch (exception: Exception) { log.w("Invalid JSON appeared in Session Store, ignoring: ${exception.debugExplanation()}") null } } } private fun setEntry(sessionKey: Any, sessionEntry: SessionEntry) { store[sessionKey.toString()] = sessionEntry.encodeJson().toString() } /** * Returns the soonest time that a session is going to expire. */ fun soonestExpiryInSeconds(keepAliveSeconds: Int): Int? { // gather stale expiring session entries that have passed. val earliestExpiry = store.keys .mapNotNull { key -> getEntry(key) } .mapNotNull { entry -> entry.closedAt?.time } .map { closedAt -> closedAt + (keepAliveSeconds * 1000L) } // differential from current time in seconds, assuming expiry in the future. .map { expiryTimeMsEpoch -> ((expiryTimeMsEpoch - Date().time) / 1000).toInt() } .minOrNull() // if there's a negative number, return 0 because there's already expired entries that need // to be dealt with now. return earliestExpiry.whenNotNull { earliest -> max(earliest, 0) } } /** * Returns the sessions that are expired and should have their event emitted. * * Such sessions will only be returned once; they are deleted. */ fun collectExpiredSessions(keepAliveSeconds: Int): List<ExpiredSession> { val expiringEntries = store.keys .mapNotNull { key -> getEntry(key).whenNotNull { Pair(key, it) } } .filter { it.second.closedAt != null } .filter { entry -> entry.second.closedAt!!.before( Date( Date().time + keepAliveSeconds * 1000L ) ) } expiringEntries.map { it.first }.forEach { key -> log.v("Removing now expired session entry $key from store.") store.unset(key) } return expiringEntries.map { (key, entry) -> ExpiredSession( key, entry.uuid, entry.sessionEvent, ((entry.closedAt?.time!! - entry.startedAt.time) / 1000L).toInt() ) } } private fun gc() { log.v("Garbage collecting any expired sessions.") store.keys.forEach { key -> val entry = getEntry(key) if (entry == null) { log.e("GC: '$key' was missing or invalid. Deleting it.") store[key] = null return@forEach } if (entry.startedAt.before(Date(Date().time - CLEANUP_TIME))) { log.w("Cleaning up stale session store key: $key/$entry") } } } data class ExpiredSession( val sessionKey: Any, val uuid: UUID, val sessionEvent: RoverEvent, val durationSeconds: Int ) data class SessionEntry( val uuid: UUID, /** * When was this session started? */ val startedAt: Date, /** * Any other attributes to include with the session event. */ val sessionEvent: RoverEvent, /** * When was the session closed? */ val closedAt: Date? ) { fun encodeJson(): JSONObject { return JSONObject().apply { put("uuid", uuid.toString()) put("started-at", startedAt.time / 1000) put("session-attributes", sessionEvent.encodeJson()) if (closedAt != null) { put("closed-at", closedAt.time / 1000) } } } companion object { fun decodeJson(jsonObject: JSONObject): SessionEntry { return SessionEntry( UUID.fromString(jsonObject.safeGetString("uuid")), Date(jsonObject.getInt("started-at") * 1000L), RoverEvent.decodeJson(jsonObject.getJSONObject("session-attributes")), jsonObject.safeOptInt("closed-at").whenNotNull { Date(it * 1000L) } ) } } } companion object { const val STORAGE_IDENTIFIER = "session-store" const val CLEANUP_TIME = 3600 * 1000L // 1 hour. } }
experiences/src/main/kotlin/io/rover/sdk/experiences/services/SessionTracker.kt
4218450931
package com.makeevapps.simpletodolist.datasource.preferences interface IDataManager { fun getThemeId(): String fun setThemeId(id: String) fun is24HourFormat(): Boolean fun setIs24HourFormat(is24: Boolean) }
app/src/main/java/com/makeevapps/simpletodolist/datasource/preferences/IDataManager.kt
2650650752
package utils.parsertools.combinators.token import utils.parsertools.ast.AstLeaf import utils.parsertools.ast.Token /** * Created by liufengkai on 2017/4/24. */ class NumToken(clazz: Class<out AstLeaf>) : AbstractToken(clazz) { override fun tokenTest(token: Token) = token.isNumber() }
src/utils/parsertools/combinators/token/NumberToken.kt
499867376
package io.aconite data class Request ( val method: String = "", val path: Map<String, String> = emptyMap(), val query: Map<String, String> = emptyMap(), val headers: Map<String, String> = emptyMap(), val body: BodyBuffer? = null ) data class Response ( val code: Int? = null, val headers: Map<String, String> = emptyMap(), val body: BodyBuffer? = null ) { operator fun plus(other: Response) = Response( code = other.code ?: this.code, headers = this.headers + other.headers, body = other.body ?: this.body ) } data class BodyBuffer( val content: Buffer, val contentType: String ) interface Buffer { val string: String val bytes: ByteArray companion object Factory { fun wrap(string: String) = object: Buffer { override val string = string override val bytes by lazy { string.toByteArray() } } fun wrap(bytes: ByteArray) = object: Buffer { override val string by lazy { String(bytes) } override val bytes = bytes } } } fun HttpException.toResponse() = Response( code = this.code, body = BodyBuffer( content = Buffer.wrap(this.message ?: ""), contentType = "text/plain" ) )
aconite-core/src/io/aconite/Data.kt
1169308659
package com.quickblox.sample.conference.kotlin.presentation.screens.settings.video import androidx.annotation.IntDef import com.quickblox.sample.conference.kotlin.presentation.screens.settings.video.ViewState.Companion.SHOW_LOGIN_SCREEN /* * Created by Injoit in 2021-09-30. * Copyright © 2021 Quickblox. All rights reserved. */ @IntDef(SHOW_LOGIN_SCREEN) annotation class ViewState { companion object { const val SHOW_LOGIN_SCREEN = 0 } }
sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/screens/settings/video/ViewState.kt
924847580
/* * Copyright (C) 2014-2022 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager 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.amaze.filemanager.filesystem.ftpserver import com.topjohnwu.superuser.io.SuFile import com.topjohnwu.superuser.io.SuFileInputStream import com.topjohnwu.superuser.io.SuFileOutputStream import org.apache.ftpserver.ftplet.FtpFile import org.apache.ftpserver.ftplet.User import org.apache.ftpserver.usermanager.impl.WriteRequest import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.InputStream import java.io.OutputStream class RootFtpFile( private val fileName: String, private val backingFile: SuFile, private val user: User ) : FtpFile { companion object { @JvmStatic private val logger: Logger = LoggerFactory.getLogger(RootFtpFile::class.java) } override fun getAbsolutePath(): String = backingFile.absolutePath override fun getName(): String = backingFile.name override fun isHidden(): Boolean = backingFile.isHidden override fun isDirectory(): Boolean = backingFile.isDirectory override fun isFile(): Boolean = backingFile.isFile override fun doesExist(): Boolean = backingFile.exists() override fun isReadable(): Boolean = backingFile.canRead() override fun isWritable(): Boolean { logger.debug("Checking authorization for $absolutePath") if (user.authorize(WriteRequest(absolutePath)) == null) { logger.debug("Not authorized") return false } logger.debug("Checking if file exists") if (backingFile.exists()) { logger.debug("Checking can write: " + backingFile.canWrite()) return backingFile.canWrite() } logger.debug("Authorized") return true } override fun isRemovable(): Boolean { // root cannot be deleted if ("/" == fileName) { return false } val fullName = absolutePath // we check FTPServer's write permission for this file. if (user.authorize(WriteRequest(fullName)) == null) { return false } // In order to maintain consistency, when possible we delete the last '/' character in the String val indexOfSlash = fullName.lastIndexOf('/') val parentFullName: String = if (indexOfSlash == 0) { "/" } else { fullName.substring(0, indexOfSlash) } // we check if the parent FileObject is writable. return backingFile.absoluteFile.parentFile?.run { RootFtpFile( parentFullName, this, user ).isWritable } ?: false } override fun getOwnerName(): String = "user" override fun getGroupName(): String = "user" override fun getLinkCount(): Int = if (backingFile.isDirectory) 3 else 1 override fun getLastModified(): Long = backingFile.lastModified() override fun setLastModified(time: Long): Boolean = backingFile.setLastModified(time) override fun getSize(): Long = backingFile.length() override fun getPhysicalFile(): Any = backingFile override fun mkdir(): Boolean = backingFile.mkdirs() override fun delete(): Boolean = backingFile.delete() override fun move(destination: FtpFile): Boolean = backingFile.renameTo(destination.physicalFile as SuFile) override fun listFiles(): MutableList<out FtpFile> = backingFile.listFiles()?.map { RootFtpFile(it.name, it, user) }?.toMutableList() ?: emptyList<FtpFile>().toMutableList() override fun createOutputStream(offset: Long): OutputStream = SuFileOutputStream.open(backingFile.absolutePath) override fun createInputStream(offset: Long): InputStream = SuFileInputStream.open(backingFile.absolutePath) }
app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/RootFtpFile.kt
3688385815
package jp.kentan.studentportalplus.data.shibboleth import java.io.IOException import java.net.InetAddress import java.net.Socket import javax.net.ssl.SSLSocket import javax.net.ssl.SSLSocketFactory /** * Enables TLS v1.2 when creating SSLSockets. * <p/> * For some reason, android supports TLS v1.2 from API 16, but enables it by * default only from API 20. * @link https://developer.android.com/reference/javax/net/ssl/SSLSocket.html * @see SSLSocketFactory */ class Tls12SocketFactory(private val delegate: SSLSocketFactory) : SSLSocketFactory() { private companion object { val TLS_V12_ONLY = arrayOf("TLSv1.2") } override fun getDefaultCipherSuites(): Array<String> { return delegate.defaultCipherSuites } override fun getSupportedCipherSuites(): Array<String> { return delegate.supportedCipherSuites } @Throws(IOException::class) override fun createSocket(s: Socket?, host: String?, port: Int, isAutoClose: Boolean): Socket { return patch(delegate.createSocket(s, host, port, isAutoClose)) } @Throws(IOException::class) override fun createSocket(host: String?, port: Int): Socket { return patch(delegate.createSocket(host, port)) } @Throws(IOException::class) override fun createSocket(host: String?, port: Int, localHost: InetAddress?, localPort: Int): Socket { return patch(delegate.createSocket(host, port, localHost, localPort)) } @Throws(IOException::class) override fun createSocket(host: InetAddress?, port: Int): Socket { return patch(delegate.createSocket(host, port)) } @Throws(IOException::class) override fun createSocket(address: InetAddress?, port: Int, localAddress: InetAddress?, localPort: Int): Socket { return patch(delegate.createSocket(address, port, localAddress, localPort)) } private fun patch(s: Socket): Socket { if (s is SSLSocket) { s.enabledProtocols = TLS_V12_ONLY } return s } }
app/src/main/java/jp/kentan/studentportalplus/data/shibboleth/Tls12SocketFactory.kt
3130198000
package org.tasks.widget import android.appwidget.AppWidgetManager import android.content.Intent import android.os.Bundle import com.todoroo.astrid.api.Filter import dagger.hilt.android.AndroidEntryPoint import org.tasks.LocalBroadcastManager import org.tasks.dialogs.FilterPicker.Companion.EXTRA_FILTER import org.tasks.dialogs.FilterPicker.Companion.SELECT_FILTER import org.tasks.dialogs.FilterPicker.Companion.newFilterPicker import org.tasks.injection.InjectingAppCompatActivity import org.tasks.preferences.DefaultFilterProvider import org.tasks.preferences.Preferences import timber.log.Timber import javax.inject.Inject @AndroidEntryPoint class WidgetFilterSelectionActivity : InjectingAppCompatActivity() { @Inject lateinit var preferences: Preferences @Inject lateinit var defaultFilterProvider: DefaultFilterProvider @Inject lateinit var localBroadcastManager: LocalBroadcastManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) if (widgetId == -1) { Timber.e("Missing ${AppWidgetManager.EXTRA_APPWIDGET_ID}") finish() } supportFragmentManager .setFragmentResultListener(SELECT_FILTER, this) { _, result -> val filter: Filter? = result.getParcelable(EXTRA_FILTER) if (filter == null) { finish() return@setFragmentResultListener } WidgetPreferences(this, preferences, widgetId) .setFilter(defaultFilterProvider.getFilterPreferenceValue(filter)) localBroadcastManager.reconfigureWidget(widgetId) setResult(RESULT_OK, Intent().putExtras(result)) finish() } newFilterPicker(intent.getParcelableExtra(EXTRA_FILTER)) .show(supportFragmentManager, FRAG_TAG_FILTER_PICKER) } companion object { private const val FRAG_TAG_FILTER_PICKER = "frag_tag_filter_picker" } }
app/src/main/java/org/tasks/widget/WidgetFilterSelectionActivity.kt
3852345950