repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
GunoH/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/search/KotlinSSDoubleColonExpressionTest.kt
5
1502
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.structuralsearch.search import org.jetbrains.kotlin.idea.structuralsearch.KotlinStructuralSearchTest class KotlinSSDoubleColonExpressionTest : KotlinStructuralSearchTest() { override fun getBasePath(): String = "doubleColonExpression" fun testClassLiteralExpression() { doTest("Int::class", """ fun foo(x: Any) { print(x) } class X { class Y { class Z { class Int } } } fun main() { foo(<warning descr="SSR">Int::class</warning>) foo(<warning descr="SSR">kotlin.Int::class</warning>) foo(<warning descr="SSR">X.Y.Z.Int::class</warning>) foo(<warning descr="SSR">Int::class</warning>.java) } """.trimIndent()) } fun testFqClassLiteralExpression() { doTest("kotlin.Int::class", """ fun foo(x: Any) { print(x) } class X { class Y { class Z { class Int } } } fun main() { foo(Int::class) foo(<warning descr="SSR">kotlin.Int::class</warning>) foo(X.Y.Z.Int::class) foo(Int::class.java) } """.trimIndent()) } fun testDotQualifiedExpression() { doTest("Int::class.java", """ fun foo(x: Any) { print(x) } fun main() { foo(Int::class) foo(<warning descr="SSR">Int::class.java</warning>) } """.trimIndent()) } }
apache-2.0
9b8804952324035b853638ebbc841306
33.953488
120
0.593209
4.037634
false
true
false
false
smmribeiro/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/jcef/ProcessLinksExtension.kt
2
1926
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.extensions.jcef import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.registry.Registry import com.intellij.ui.jcef.JBCefPsiNavigationUtils import org.intellij.plugins.markdown.extensions.MarkdownBrowserPreviewExtension import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanel import org.intellij.plugins.markdown.ui.preview.ResourceProvider import org.intellij.plugins.markdown.ui.preview.accessor.MarkdownLinkOpener internal class ProcessLinksExtension(private val panel: MarkdownHtmlPanel): MarkdownBrowserPreviewExtension, ResourceProvider { init { panel.browserPipe?.subscribe(openLinkEventName, ::openLink) Disposer.register(this) { panel.browserPipe?.removeSubscription(openLinkEventName, ::openLink) } } private fun openLink(link: String) { if (!Registry.`is`("markdown.open.link.in.external.browser")) { return } if (JBCefPsiNavigationUtils.navigateTo(link)) { return } MarkdownLinkOpener.getInstance().openLink(panel.project, link) } override val scripts: List<String> = listOf("processLinks/processLinks.js") override val resourceProvider: ResourceProvider = this override fun canProvide(resourceName: String): Boolean = resourceName in scripts override fun loadResource(resourceName: String): ResourceProvider.Resource? { return ResourceProvider.loadInternalResource(this::class, resourceName) } override fun dispose() = Unit class Provider: MarkdownBrowserPreviewExtension.Provider { override fun createBrowserExtension(panel: MarkdownHtmlPanel): MarkdownBrowserPreviewExtension? { return ProcessLinksExtension(panel) } } companion object { private const val openLinkEventName = "openLink" } }
apache-2.0
66ef0d263c42cbb93714cb138e1747ab
36.764706
140
0.78297
4.732187
false
false
false
false
Phakx/AdventOfCode
2017/src/main/kotlin/dayfourteen/Dayfourteen.kt
1
2582
package main.kotlin.dayfourteen import main.kotlin.dayten.Dayten import java.io.File import java.net.URLDecoder import main.kotlin.utils.* class Dayfourteen { private fun load_file(): String? { val resource = this::class.java.classLoader.getResource("dayfourteen" + File.separator + "input") return URLDecoder.decode(resource.file, "UTF-8") } fun solvePartOne() { val binaryList = generateBinaryList() var sum = 0 binaryList.forEach { sum += it.count { it == '1' } } println("Part 1: $sum") } private fun generateBinaryList(): MutableList<String> { val input = File(load_file()).readText() val inputList = mutableListOf<String>() (0..127).forEach { inputList.add("$input-$it") } val knotList = mutableListOf<String>() val knotHasher = Dayten() inputList.forEach { knotList.add(knotHasher.generateKnotHash(it.toByteArray().map { it.toInt() }.toMutableList())) } val binaryList = mutableListOf<String>() knotList.forEach { binaryList.add(hexToBinary(it)) } return binaryList } fun solvePartTwo() { val binaryList = generateBinaryList().map{ it.map{it.toString().toInt()}.toTypedArray()} var currGroup = 2 for ((indexRow, row) in binaryList.withIndex()) { for ((indexColumn, cell) in row.withIndex()) { if (cell == 1) { binaryList[indexRow][indexColumn] = currGroup val queue = mutableListOf(listOf(indexRow, indexColumn, currGroup)) while (queue.isNotEmpty()) { val (baseX, baseY, group) = queue.removeAt(0) for ((xOff, yOff) in listOf(Pair(0, -1), Pair(0, 1), Pair(-1, 0), Pair(1, 0))) { val x = baseX + xOff val y = baseY + yOff try { if (binaryList[x][y] == 1) { binaryList[x][y] = (group) queue.add(listOf(x, y, group)) } } catch (_: Exception) { } } } currGroup++ } } } println("Part 2: ${currGroup-2}") } } fun main(args: Array<String>) { val solver = Dayfourteen() solver.solvePartOne() solver.solvePartTwo() }
mit
036a60382a1299601b33fdbeb81f2fe2
33.44
106
0.499225
4.368866
false
false
false
false
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/navigation/NavigationMenuViewModel.kt
1
3005
package com.ivanovsky.passnotes.presentation.navigation import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.github.terrakok.cicerone.Router import com.ivanovsky.passnotes.BuildConfig import com.ivanovsky.passnotes.injection.GlobalInjector import com.ivanovsky.passnotes.presentation.Screens.AboutScreen import com.ivanovsky.passnotes.presentation.Screens.DebugMenuScreen import com.ivanovsky.passnotes.presentation.Screens.MainSettingsScreen import com.ivanovsky.passnotes.presentation.Screens.UnlockScreen import com.ivanovsky.passnotes.presentation.navigation.mode.NavigationItem import com.ivanovsky.passnotes.presentation.navigation.mode.NavigationItem.ABOUT import com.ivanovsky.passnotes.presentation.navigation.mode.NavigationItem.DEBUG_MENU import com.ivanovsky.passnotes.presentation.navigation.mode.NavigationItem.LOCK import com.ivanovsky.passnotes.presentation.navigation.mode.NavigationItem.SETTINGS import com.ivanovsky.passnotes.presentation.navigation.mode.NavigationItem.SELECT_FILE class NavigationMenuViewModel( private val router: Router ) : ViewModel() { val isNavigationMenuEnabled = MutableLiveData(false) val visibleItems = MutableLiveData<List<NavigationItem>>() fun setNavigationEnabled(isEnabled: Boolean) { isNavigationMenuEnabled.value = isEnabled } fun setVisibleItems(items: List<NavigationItem>) { visibleItems.value = items } fun onMenuItemSelected(item: NavigationItem) { when (item) { SELECT_FILE -> { router.backTo(UnlockScreen()) } LOCK -> { router.backTo(UnlockScreen()) } SETTINGS -> { router.navigateTo(MainSettingsScreen()) } ABOUT -> { router.navigateTo(AboutScreen()) } DEBUG_MENU -> { router.navigateTo(DebugMenuScreen()) } } } companion object { @Suppress("UNCHECKED_CAST") val FACTORY = object : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return GlobalInjector.get<NavigationMenuViewModel>() as T } } fun createNavigationItemsForBasicScreens(): List<NavigationItem> { return mutableListOf<NavigationItem>().apply { add(SELECT_FILE) add(SETTINGS) if (BuildConfig.DEBUG) { add(DEBUG_MENU) } add(ABOUT) } } fun createNavigationItemsForDbScreens(): List<NavigationItem> { return mutableListOf<NavigationItem>().apply { add(LOCK) add(SETTINGS) if (BuildConfig.DEBUG) { add(DEBUG_MENU) } add(ABOUT) } } } }
gpl-2.0
052c0dbd2c787ef9c3b9efba2eef2034
34.364706
86
0.649584
5.244328
false
false
false
false
Bambooin/trime
app/src/main/java/com/osfans/trime/ime/keyboard/InputFeedbackManager.kt
2
5143
package com.osfans.trime.ime.keyboard import android.content.Context import android.inputmethodservice.InputMethodService import android.media.AudioManager import android.os.Build import android.os.VibrationEffect import android.os.Vibrator import android.speech.tts.TextToSpeech import android.view.HapticFeedbackConstants import android.view.KeyEvent import com.osfans.trime.data.AppPrefs import java.util.Locale import kotlin.math.ln /** * Manage the key press effects, such as vibration, sound, speaking and so on. */ class InputFeedbackManager( private val ims: InputMethodService ) { private val prefs: AppPrefs = AppPrefs.defaultInstance() private var vibrator: Vibrator? = null private var audioManager: AudioManager? = null private var tts: TextToSpeech? = null init { try { vibrator = ims.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator audioManager = ims.getSystemService(Context.AUDIO_SERVICE) as? AudioManager tts = TextToSpeech(ims.applicationContext) { } } catch (e: Exception) { e.printStackTrace() } } /** * Makes a key press vibration if the user has this feature enabled in the preferences. */ fun keyPressVibrate() { if (prefs.keyboard.vibrationEnabled) { val vibrationDuration = prefs.keyboard.vibrationDuration.toLong() var vibrationAmplitude = prefs.keyboard.vibrationAmplitude val hapticsPerformed = if (vibrationDuration < 0) { ims.window?.window?.decorView?.performHapticFeedback( HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING ) } else { false } if (hapticsPerformed == true) { return } if (vibrationAmplitude > 0) { vibrationAmplitude = (vibrationAmplitude / 2.0).toInt().coerceAtLeast(1) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { vibrator?.vibrate( VibrationEffect.createOneShot( vibrationDuration, vibrationAmplitude ) ) } else { @Suppress("DEPRECATION") vibrator?.vibrate(vibrationDuration) } } } /** Text to Speech engine's language getter and setter */ var ttsLanguage: Locale? get() { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { tts?.voice?.locale } else { @Suppress("DEPRECATION") tts?.language } } set(v) { tts?.language = v } /** * Makes a key press sound if the user has this feature enabled in the preferences. */ fun keyPressSound(keyCode: Int? = null) { if (prefs.keyboard.soundEnabled) { val soundVolume = prefs.keyboard.soundVolume if (Sound.isEnable()) Sound.get().play(keyCode, soundVolume) else { if (soundVolume > 0) { val effect = when (keyCode) { KeyEvent.KEYCODE_SPACE -> AudioManager.FX_KEYPRESS_SPACEBAR KeyEvent.KEYCODE_DEL -> AudioManager.FX_KEYPRESS_DELETE KeyEvent.KEYCODE_ENTER -> AudioManager.FX_KEYPRESS_RETURN else -> AudioManager.FX_KEYPRESS_STANDARD } audioManager!!.playSoundEffect( effect, (1 - (ln((101.0 - soundVolume)) / ln(101.0))).toFloat() ) } } } } /** * Makes a key press speaking if the user has this feature enabled in the preferences. */ fun keyPressSpeak(content: Any? = null) { if (prefs.keyboard.isSpeakKey) contentSpeakInternal(content) } /** * Makes a text commit speaking if the user has this feature enabled in the preferences. */ fun textCommitSpeak(text: CharSequence? = null) { if (prefs.keyboard.isSpeakCommit) contentSpeakInternal(text) } private inline fun <reified T> contentSpeakInternal(content: T) { val text = when { 0 is T -> { KeyEvent.keyCodeToString(content as Int) .replace("KEYCODE_", "") .replace("_", " ") .lowercase(Locale.getDefault()) } "" is T -> content as String else -> null } ?: return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { tts?.speak(text, TextToSpeech.QUEUE_FLUSH, null, "TrimeTTS") } else { @Suppress("DEPRECATION") tts?.speak(text, TextToSpeech.QUEUE_FLUSH, null) } } fun destroy() { vibrator = null audioManager = null if (tts != null) { tts?.stop().also { tts = null } } } }
gpl-3.0
87571d6949369250fc309bd03b0e8431
32.396104
92
0.560568
4.833647
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/useragent/UserAgentListDialog.kt
1
3717
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.legacy.useragent import android.app.Activity.RESULT_OK import android.app.AlertDialog import android.app.Dialog import android.content.DialogInterface import android.content.Intent import android.os.Bundle import android.webkit.WebSettings import androidx.fragment.app.DialogFragment import com.squareup.moshi.Moshi import dagger.hilt.android.AndroidEntryPoint import jp.hazuki.yuzubrowser.core.USER_AGENT_PC import jp.hazuki.yuzubrowser.core.utility.extensions.getChromePcUserAgent import jp.hazuki.yuzubrowser.core.utility.extensions.getFakeChromeUserAgent import jp.hazuki.yuzubrowser.core.utility.extensions.getPcUserAgent import jp.hazuki.yuzubrowser.legacy.R import jp.hazuki.yuzubrowser.ui.settings.AppPrefs import javax.inject.Inject @AndroidEntryPoint class UserAgentListDialog : DialogFragment() { @Inject lateinit var moshi: Moshi override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val activity = activity ?: throw IllegalStateException() val mUserAgentList = UserAgentList() mUserAgentList.read(activity, moshi) val entries = arrayOfNulls<String>(mUserAgentList.size + 1) val entryValues = arrayOfNulls<String>(mUserAgentList.size + 1) var ua = requireArguments().getString(UA) val isChrome = AppPrefs.fake_chrome.get() val defaultUserAgent = if (isChrome) activity.getFakeChromeUserAgent() else WebSettings.getDefaultUserAgent(activity) val pcUserAgent = if (isChrome) activity.getChromePcUserAgent() else activity.getPcUserAgent() var pos = if (ua.isNullOrEmpty() || defaultUserAgent == ua) 0 else -1 if (ua == pcUserAgent) { ua = USER_AGENT_PC } entries[0] = activity.getString(R.string.default_text) entryValues[0] = defaultUserAgent var userAgent: UserAgent var i = 1 while (mUserAgentList.size > i - 1) { userAgent = mUserAgentList[i - 1] entries[i] = userAgent.name entryValues[i] = userAgent.useragent if (ua == userAgent.useragent) { pos = i } i++ } val builder = AlertDialog.Builder(activity) builder.setTitle(R.string.useragent) .setSingleChoiceItems(entries, pos) { _, which -> val intent = Intent() intent.putExtra(Intent.EXTRA_TEXT, if (which == 0) "" else entryValues[which]) activity.setResult(RESULT_OK, intent) dismiss() } .setNegativeButton(R.string.cancel, null) return builder.create() } override fun onDismiss(dialog: DialogInterface) { super.onDismiss(dialog) activity?.finish() } companion object { private const val UA = "ua" fun newInstance(userAgent: String): UserAgentListDialog { val dialog = UserAgentListDialog() val bundle = Bundle() bundle.putString(UA, userAgent) dialog.arguments = bundle return dialog } } }
apache-2.0
1e0d92eff339481308c368e19bd4830c
34.066038
125
0.677966
4.505455
false
false
false
false
markusfisch/BinaryEye
app/src/main/kotlin/de/markusfisch/android/binaryeye/graphics/BitmapEditor.kt
1
1980
package de.markusfisch.android.binaryeye.graphics import android.content.ContentResolver import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import android.graphics.RectF import android.net.Uri import java.io.IOException import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt fun ContentResolver.loadImageUri(uri: Uri): Bitmap? = try { val options = BitmapFactory.Options() openInputStream(uri)?.use { options.inJustDecodeBounds = true BitmapFactory.decodeStream(it, null, options) options.inSampleSize = calculateInSampleSize( options.outWidth, options.outHeight ) options.inJustDecodeBounds = false } openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, options) } } catch (e: IOException) { null } private fun calculateInSampleSize( width: Int, height: Int, reqWidth: Int = 1024, reqHeight: Int = 1024 ): Int { var inSampleSize = 1 if (height > reqHeight || width > reqWidth) { val halfHeight = height / 2 val halfWidth = width / 2 while ( halfHeight / inSampleSize >= reqHeight || halfWidth / inSampleSize >= reqWidth ) { inSampleSize *= 2 } } return inSampleSize } fun Bitmap.crop( rect: RectF, rotation: Float, pivotX: Float, pivotY: Float ) = try { val erected = erect(rotation, pivotX, pivotY) val w = erected.width val h = erected.height val x = max(0, (rect.left * w).roundToInt()) val y = max(0, (rect.top * h).roundToInt()) Bitmap.createBitmap( erected, x, y, min(w - x, (rect.right * w).roundToInt() - x), min(h - y, (rect.bottom * h).roundToInt() - y) ) } catch (e: OutOfMemoryError) { null } catch (e: IllegalArgumentException) { null } private fun Bitmap.erect( rotation: Float, pivotX: Float, pivotY: Float ): Bitmap = if ( rotation % 360f != 0f ) { Bitmap.createBitmap( this, 0, 0, width, height, Matrix().apply { setRotate(rotation, pivotX, pivotY) }, true ) } else { this }
mit
4adc0d1bdfd15bf7ebe6b7b679e5a50a
19.625
59
0.702525
3.173077
false
false
false
false
EMResearch/EvoMaster
e2e-tests/spring-rest-openapi-v3/src/main/kotlin/com/foo/rest/examples/spring/openapi/v3/wiremock/jsonmap/WmJsonMapRest.kt
1
1722
package com.foo.rest.examples.spring.openapi.v3.wiremock.jsonmap import com.google.gson.Gson import com.google.gson.JsonParseException import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import java.io.BufferedReader import java.net.URL @RestController @RequestMapping(path = ["/api/wm/jsonmap"]) class WmJsonMapRest { private val gson = Gson() @GetMapping(path=["/gson"]) fun getGsonObject() : ResponseEntity<String> { val url = URL("http://json.map:10422/api/foo") val connection = url.openConnection() connection.setRequestProperty("accept", "application/json") try { val text = BufferedReader(connection.getInputStream().reader()).readText() val tree = gson.fromJson(text, Map::class.java) if (tree.isNotEmpty()){ var msg = "not empty map and include" // not solved yet if (tree.containsKey("foo") // && tree["foo"] == "foo42" ) msg += " foo42" if (tree.containsKey("bar") //&& tree["bar"] == "bar54" ) msg += " bar54" return ResponseEntity.ok(msg) } return ResponseEntity.status(404).body("empty map") }catch (e: JsonParseException){ val msg = "The format of token is invalid. For example {\"key_foo\":\"value_foo\",\"key_bar\":\"value_bar\"}" return ResponseEntity.status(500).body(msg) } } }
lgpl-3.0
99ff7f35d55d64780ca266abca52039a
34.163265
121
0.598722
4.404092
false
false
false
false
grote/Liberario
app/src/main/java/de/grobox/transportr/networks/TransportNetwork.kt
1
2877
/* * Transportr * * Copyright (c) 2013 - 2018 Torsten Grote * * 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 de.grobox.transportr.networks import android.content.Context import androidx.annotation.DrawableRes import androidx.annotation.StringRes import com.google.common.base.Preconditions.checkArgument import de.grobox.transportr.R import de.schildbach.pte.NetworkId import de.schildbach.pte.NetworkProvider import java.lang.ref.SoftReference import javax.annotation.concurrent.Immutable @Immutable data class TransportNetwork internal constructor( val id: NetworkId, @field:StringRes private val name: Int = 0, @field:StringRes private val description: Int, @field:StringRes private val agencies: Int = 0, val status: Status = Status.STABLE, @field:DrawableRes @get:DrawableRes val logo: Int = R.drawable.network_placeholder, private val goodLineNames: Boolean = false, private val itemIdExtra: Int = 0, private val factory: () -> NetworkProvider ) : Region { enum class Status { ALPHA, BETA, STABLE } val networkProvider: NetworkProvider by lazy { networkProviderRef.get() ?: getNetworkProviderReference().get()!! } private val networkProviderRef by lazy { getNetworkProviderReference() } private fun getNetworkProviderReference() = SoftReference<NetworkProvider>(factory.invoke()) init { checkArgument(description != 0 || agencies != 0) } override fun getName(context: Context): String { return if (name == 0) { id.name } else { context.getString(name) } } fun getDescription(context: Context): String? { return if (description != 0 && agencies != 0) { context.getString(description) + " (" + context.getString(agencies) + ")" } else if (description != 0) { context.getString(description) } else if (agencies == 0) { context.getString(agencies) } else { throw IllegalArgumentException() } } fun hasGoodLineNames(): Boolean { return goodLineNames } internal fun getItem(): TransportNetworkItem { return TransportNetworkItem(this, itemIdExtra) } }
gpl-3.0
3adfa7c1541c05a5f90c499b05664fa9
32.847059
118
0.683698
4.385671
false
false
false
false
t-yoshi/peca-android
ui/src/main/java/org/peercast/core/ui/tv/yp/BookmarkManager.kt
1
1919
package org.peercast.core.ui.tv.yp /** * @author (c) 2014-2021, T Yoshizawa * @licenses Dual licensed under the MIT or GPL licenses. */ import android.content.Context import androidx.core.content.edit import org.peercast.core.lib.rpc.YpChannel import org.peercast.core.ui.tv.util.isNilId import kotlin.math.min class BookmarkManager(c: Context) { private val prefs = c.getSharedPreferences("tv-bookmark", Context.MODE_PRIVATE) operator fun plusAssign(ch: YpChannel) { if (ch.isNilId || contains(ch)) return prefs.edit { putLong(KEY_PREFIX_BOOKMARK_NAME + ch.name, 1) } } operator fun minusAssign(ch: YpChannel) { prefs.edit { remove(KEY_PREFIX_BOOKMARK_NAME + ch.name) } } operator fun contains(ch: YpChannel): Boolean { return prefs.getLong(KEY_PREFIX_BOOKMARK_NAME + ch.name, 0) > 0 } fun toggle(ch: YpChannel) { if (contains(ch)) { minusAssign(ch) } else { plusAssign(ch) } } fun incrementPlayedCount(ch: YpChannel) { val n = prefs.getLong(KEY_PREFIX_BOOKMARK_NAME + ch.name, 0) if (n > 0) { prefs.edit { putLong(KEY_PREFIX_BOOKMARK_NAME + ch.name, min(n + 1, Long.MAX_VALUE)) } } } /**ブックマーク済みを先頭にもってくる*/ fun comparator(): (YpChannel, YpChannel) -> Int { // Map<name,num_played> val m = prefs.all.keys.filter { it.startsWith(KEY_PREFIX_BOOKMARK_NAME) }.map { it.removePrefix(KEY_PREFIX_BOOKMARK_NAME) to prefs.getLong(it, 0) }.toMap() return { c1, c2 -> (m[c2.name] ?: 0).compareTo(m[c1.name] ?: 0) } } companion object { private const val KEY_PREFIX_BOOKMARK_NAME = "bookmark-name:" //value=再生回数(long) } }
gpl-3.0
81b85f99a48dfc4c8e9cff4754d2f67d
25.828571
88
0.582845
3.450368
false
false
false
false
mabels/ipaddress
kotlin/lib/src/main/kotlin/com/adviser/ipaddress/IpV4.kt
1
31924
package com.adviser.ipaddress.kotlin import java.math.BigInteger val x80000000 = BigInteger.valueOf(2147483648L) val xc0000000 = BigInteger.valueOf(3221225472L) val xe0000000 = BigInteger.valueOf(3758096384L) val is_private = arrayOf( IPAddress.parse("10.0.0.0/8").unwrap(), IPAddress.parse("169.254.0.0/16").unwrap(), IPAddress.parse("172.16.0.0/12").unwrap(), IPAddress.parse("192.168.0.0/16").unwrap() ) class IpV4 { companion object { val ipv4_is_private: VtBool = { my -> is_private.find { i -> i.includes(my) } != null } val ipv4_is_loopback: VtBool = { my -> IPAddress.parse("127.0.0.0/8").unwrap().includes(my) } val to_ipv6: VtIPAddress = { ia -> IPAddress( IpBits.V6, BigInteger.ZERO.add(ia.host_address), Prefix128.create(ia.prefix.num).unwrap(), null, IpV6.ipv6_is_private, IpV6.ipv6_is_loopback, IpV6.ipv6_to_ipv6) } fun from_u32(addr: Long, _prefix: Int): Result<IPAddress> { val prefix = Prefix32.create(_prefix) if (prefix.isErr()) { return Result.Err(prefix.unwrapErr()) } return Result.Ok(IPAddress( IpBits.V4, BigInteger.valueOf(addr), prefix.unwrap(), null, ipv4_is_private, ipv4_is_loopback, to_ipv6 )) } fun create(str: String): Result<IPAddress> { val splitted = IPAddress.split_at_slash(str) if (!IPAddress.is_valid_ipv4(splitted.addr)) { return Result.Err("Invalid IP ${str}") } var ip_prefix_num = Result.Ok(32) if (splitted.netmask !== null) { // netmask is defined ip_prefix_num = IPAddress.parse_netmask_to_prefix(splitted.netmask) if (ip_prefix_num.isErr()) { return Result.Err(ip_prefix_num.unwrapErr()) } //if ip_prefix.ip_bits.version } val ip_prefix = Prefix32.create(ip_prefix_num.unwrap()) if (ip_prefix.isErr()) { return Result.Err(ip_prefix.unwrapErr()) } val split_u32 = IPAddress.split_to_u32(splitted.addr) if (split_u32.isErr()) { return Result.Err(split_u32.unwrapErr()) } return Result.Ok(IPAddress(IpBits.V4, BigInteger.valueOf(split_u32.unwrap()), ip_prefix.unwrap(), null, ipv4_is_private, ipv4_is_loopback, to_ipv6)) } // Checks whether the ip address belongs to a // RFC 791 CLASS A network, no matter // what the subnet mask is. // // Example: // // ip = IPAddress("10.0.0.1/24") // // ip.a? // // => true // fun is_class_a(my: IPAddress): Boolean { return my.is_ipv4() && my.host_address.compareTo(x80000000) < 0 } // Checks whether the ip address belongs to a // RFC 791 CLASS B network, no matter // what the subnet mask is. // // Example: // // ip = IPAddress("172.16.10.1/24") // // ip.b? // // => true // fun is_class_b(my: IPAddress): Boolean { return my.is_ipv4() && x80000000.compareTo(my.host_address) <= 0 && my.host_address.compareTo(xc0000000) < 0 } // Checks whether the ip address belongs to a // RFC 791 CLASS C network, no matter // what the subnet mask is. // // Example: // // ip = IPAddress("192.168.1.1/30") // // ip.c? // // => true // fun is_class_c(my: IPAddress): Boolean { return my.is_ipv4() && xc0000000.compareTo(my.host_address) <= 0 && my.host_address.compareTo(xe0000000) < 0 } // pub fn is_private(my: &IPAddress) -> bool { // for i in vec![IPv4::new("10.0.0.0/8"), // IPv4::new("172.16.0.0/12"), // IPv4::new("192.168.0.0/16")] { // if my.includes(&i) { // return true // } // } // return false // } // pub fn dns_reverse(my: &IPAddress) { // let parts = self.ip_bits.parts(&my.host_address) // return String.format("{}.{}.{}.{}.in-addr.arpa", // parts.get(3), // parts.get(2), // parts.get(1), // parts.get(0)) // } // pub fn to_ipv4_str(value: u32) { // String.format("{}.{}.{}.{}", // (value >> 24) & 0xff, // (value >> 16) & 0xff, // (value >> 8) & 0xff, // value & 0xff) // } // Returns the address portion of the IPv4 object // as a string. // // ip = IPAddress("172.16.100.4/22") // // ip.address // // => "172.16.100.4" // // pub fn address(&self) { // return self.address // } // Returns the prefix portion of the IPv4 object // as a IPAddress::Prefix32 object // // ip = IPAddress("172.16.100.4/22") // // ip.prefix // // => 22 // // ip.prefix.class // // => IPAddress::Prefix32 // // pub fn prefix(&self) { // return self.prefix // } // Set a new prefix number for the object // // This is useful if you want to change the prefix // to an object created with IPv4::parse_u32 or // if the object was created using the classful // mask. // // ip = IPAddress("172.16.100.4") // // puts ip // // => 172.16.100.4/16 // // ip.prefix = 22 // // puts ip // // => 172.16.100.4/22 // // pub fn set_prefix(&mut self, num: u8) { // self.prefix = Prefix32::new(num) // } // Returns the address as an array of decimal values // // ip = IPAddress("172.16.100.4") // // ip.octets // // => [172, 16, 100, 4] // // pub fn octets(&self) { // self.octets // } // Returns a string with the address portion of // the IPv4 object // // ip = IPAddress("172.16.100.4/22") // // ip.to_s // // => "172.16.100.4" // // pub fn to_s(&self) { // self.address // } // pub fn compressed(&self) { // self.address // } // Returns a string with the IP address in canonical // form. // // ip = IPAddress("172.16.100.4/22") // // ip.to_string // // => "172.16.100.4/22" // // pub fn to_string(&self) { // String.format("{}/{}", self.address.to_s, self.prefix.to_s) // } // Returns the prefix as a string in IP format // // ip = IPAddress("172.16.100.4/22") // // ip.netmask // // => "255.255.252.0" // // pub fn netmask(&self) { // self.prefix.to_ip() // } // Like IPv4// prefix=, this method allow you to // change the prefix / netmask of an IP address // object. // // ip = IPAddress("172.16.100.4") // // puts ip // // => 172.16.100.4/16 // // ip.netmask = "255.255.252.0" // // puts ip // // => 172.16.100.4/22 // // pub fn set_netmask(&self, addr: &String) { // self.prefix = Prefix32::parse_netmask_to_prefix(addr) // } // // // Returns the address portion in unsigned // 32 bits integer format. // // This method is identical to the C function // inet_pton to create a 32 bits address family // structure. // // ip = IPAddress("10.0.0.0/8") // // ip.to_i // // => 167772160 // // pub fn u32() { // self.ip32 // } // pub fn to_i() { // self.ip32 // } // pub fn to_u32() { // self.ip32 // } // // Returns the address portion of an IPv4 object // in a network byte order format. // // ip = IPAddress("172.16.10.1/24") // // ip.data // // => "\254\020\n\001" // // It is usually used to include an IP address // in a data packet to be sent over a socket // // a = Socket.open(params) // socket details here // ip = IPAddress("10.1.1.0/24") // binary_data = ["Address: "].pack("a*") + ip.data // // // Send binary data // a.puts binary_data // // pub fn data(&self) { // self.ip32 // } // Returns the octet specified by index // // ip = IPAddress("172.16.100.50/24") // // ip[0] // // => 172 // ip[1] // // => 16 // ip[2] // // => 100 // ip[3] // // => 50 // // pub fn get(&self, index: u8) { // self.octets.get(index) // } // pub fn octet(&self, index: u8) { // self.octets.get(index) // } // Returns the address portion of an IP in binary format, // as a string containing a sequence of 0 and 1 // // ip = IPAddress("127.0.0.1") // // ip.bits // // => "01111111000000000000000000000001" // // pub fn bits(&self) { // self.ip32.to_string() // } // Returns the broadcast address for the given IP. // // ip = IPAddress("172.16.10.64/24") // // ip.broadcast.to_s // // => "172.16.10.255" // // pub fn broadcast(&self) { // IPv4::parse_u32(self.broadcast_u32, self.prefix) // } // Checks if the IP address is actually a network // // ip = IPAddress("172.16.10.64/24") // // ip.network? // // => false // // ip = IPAddress("172.16.10.64/26") // // ip.network? // // => true // // pub fn is_network() { // (self.prefix.num < 32) && (self.ip32 | self.prefix.to_u32 == self.prefix.to_u32) // } // Returns a new IPv4 object with the network number // for the given IP. // // ip = IPAddress("172.16.10.64/24") // // ip.network.to_s // // => "172.16.10.0" // // pub fn network() // self.class.parse_u32(self.network_u32, prefix) // // Returns a new IPv4 object with the // first host IP address in the range. // // Example: given the 192.168.100.0/24 network, the first // host IP address is 192.168.100.1. // // ip = IPAddress("192.168.100.0/24") // // ip.first.to_s // // => "192.168.100.1" // // The object IP doesn't need to be a network: the method // automatically gets the network number from it // // ip = IPAddress("192.168.100.50/24") // // ip.first.to_s // // => "192.168.100.1" // // pub fn first(&self) { // IPv4::parse_u32(self.network_u32+1, self.prefix) // } // Like its sibling method IPv4// first, this method // returns a new IPv4 object with the // last host IP address in the range. // // Example: given the 192.168.100.0/24 network, the last // host IP address is 192.168.100.254 // // ip = IPAddress("192.168.100.0/24") // // ip.last.to_s // // => "192.168.100.254" // // The object IP doesn't need to be a network: the method // automatically gets the network number from it // // ip = IPAddress("192.168.100.50/24") // // ip.last.to_s // // => "192.168.100.254" // // pub fn last(&self) { // IPv4::parse_u32(self.broadcast_u32-1, self.prefix) // } // // // Iterates over all the hosts IP addresses for the given // network (or IP address). // // ip = IPAddress("10.0.0.1/29") // // ip.each_host do |i| // p i.to_s // end // // => "10.0.0.1" // // => "10.0.0.2" // // => "10.0.0.3" // // => "10.0.0.4" // // => "10.0.0.5" // // => "10.0.0.6" // // pub fn each_host(&self, fn: ) { // (self.network_u32+1..self.broadcast_u32-1).each do |i| // yield self.class.parse_u32(i, @prefix) // end // } // Iterates over all the IP addresses for the given // network (or IP address). // // The object yielded is a new IPv4 object created // from the iteration. // // ip = IPAddress("10.0.0.1/29") // // ip.each do |i| // p i.address // end // // => "10.0.0.0" // // => "10.0.0.1" // // => "10.0.0.2" // // => "10.0.0.3" // // => "10.0.0.4" // // => "10.0.0.5" // // => "10.0.0.6" // // => "10.0.0.7" // // pub fn each(&self) { // (self.network_u32..self.broadcast_u32).each do |i| // yield self.class.parse_u32(i, @prefix) // end // } // Spaceship operator to compare IPv4 objects // // Comparing IPv4 addresses is useful to ordinate // them into lists that match our intuitive // perception of ordered IP addresses. // // The first comparison criteria is the u32 value. // For example, 10.100.100.1 will be considered // to be less than 172.16.0.1, because, in a ordered list, // we expect 10.100.100.1 to come before 172.16.0.1. // // The second criteria, in case two IPv4 objects // have identical addresses, is the prefix. An higher // prefix will be considered greater than a lower // prefix. This is because we expect to see // 10.100.100.0/24 come before 10.100.100.0/25. // // Example: // // ip1 = IPAddress "10.100.100.1/8" // ip2 = IPAddress "172.16.0.1/16" // ip3 = IPAddress "10.100.100.1/16" // // ip1 < ip2 // // => true // ip1 > ip3 // // => false // // [ip1,ip2,ip3].sort.map{|i| i.to_string} // // => ["10.100.100.1/8","10.100.100.1/16","172.16.0.1/16"] // // pub fn cmp(&self, oth: IPv4) { // if self.to_u32() == oth.to_u32() { // return self.prefix.num - oth.prefix.num // } // self.to_u32() - oth.to_u32() // } // Returns the number of IP addresses included // in the network. It also counts the network // address and the broadcast address. // // ip = IPAddress("10.0.0.1/29") // // ip.size // // => 8 // // pub fn size(&self) { // 2 ** self.prefix.host_prefix() // } // Returns an array with the IP addresses of // all the hosts in the network. // // ip = IPAddress("10.0.0.1/29") // // ip.hosts.map {|i| i.address} // // => ["10.0.0.1", // // => "10.0.0.2", // // => "10.0.0.3", // // => "10.0.0.4", // // => "10.0.0.5", // // => "10.0.0.6"] // // pub fn hosts(&self) { // self.to_a[1..-2] // } // Returns the network number in Unsigned 32bits format // // ip = IPAddress("10.0.0.1/29") // // ip.network_u32 // // => 167772160 // // pub fn network_u32(&self) { // self.ip32 & self.prefix.to_u32() // } // Returns the broadcast address in Unsigned 32bits format // // ip = IPaddress("10.0.0.1/29") // // ip.broadcast_u32 // // => 167772167 // // pub fn broadcast_u32(&self) { // self.network_u32 + self.size - 1 // } // Checks whether a subnet includes the given IP address. // // Accepts an IPAddress::IPv4 object. // // ip = IPAddress("192.168.10.100/24") // // addr = IPAddress("192.168.10.102/24") // // ip.include? addr // // => true // // ip.include? IPAddress("172.16.0.48/16") // // => false // // pub fn include?(&self, oth: IPv4) { // self.prefix.num <= oth.prefix.num && // self.network_u32 == (oth.to_u32() & self.prefix.to_u32()) // } // Checks whether a subnet includes all the // given IPv4 objects. // // ip = IPAddress("192.168.10.100/24") // // addr1 = IPAddress("192.168.10.102/24") // addr2 = IPAddress("192.168.10.103/24") // // ip.include_all?(addr1,addr2) // // => true // // pub fn include_all?(*others) // others.all? {|oth| include?(oth)} // end // Checks if an IPv4 address objects belongs // to a private network RFC1918 // // Example: // // ip = IPAddress "10.1.1.1/24" // ip.private? // // => true // // Returns the IP address in in-addr.arpa format // for DNS lookups // // ip = IPAddress("172.16.100.50/24") // // ip.reverse // // => "50.100.16.172.in-addr.arpa" // // pub fn reverse(&self) { // return String.format("{}.{}.{}.{}.in-addr.arpa", // self.octets.get(3), self.octets.get(2), // self.octets.get(1), self.octets.get(0)) // } // pub fn arpa(&self) { // return self.reverse() // } // Returns the IP address in in-addr.arpa format // for DNS Domain definition entries like SOA Records // // ip = IPAddress("172.17.100.50/15") // // ip.dns_rev_domains // // => ["16.172.in-addr.arpa","17.172.in-addr.arpa"] // // pub fn dns_rev_domains(&self) { // let mut net = [ self.network ] // let mut cut = 4 - (self.prefix.num/8) // if (self.prefix.num <= 8) { // edge case class a // cut = 3 // } else if (self.prefix.num > 24) { // edge case class c // cut = 1 // net = [network.supernet(24)] // } // if (self.prefix.num < 24 && (self.prefix.num % 8) != 0) { // case class less // cut = 3-(self.prefix.num/8) // net = network.subnet(self.prefix.num+1) // } // return net.map(|n| n.reverse.split('.')[cut .. -1].join('.')) // } // Splits a network into different subnets // // If the IP Address is a network, it can be divided into // multiple networks. If +self+ is not a network, this // method will calculate the network from the IP and then // subnet it. // // If +subnets+ is an power of two number, the resulting // networks will be divided evenly from the supernet. // // network = IPAddress("172.16.10.0/24") // // network / 4 // implies map{|i| i.to_string} // // => ["172.16.10.0/26", // "172.16.10.64/26", // "172.16.10.128/26", // "172.16.10.192/26"] // // If +num+ is any other number, the supernet will be // divided into some networks with a even number of hosts and // other networks with the remaining addresses. // // network = IPAddress("172.16.10.0/24") // // network / 3 // implies map{|i| i.to_string} // // => ["172.16.10.0/26", // "172.16.10.64/26", // "172.16.10.128/25"] // // Returns an array of IPv4 objects // // pub fn split(my : &IPAddress, subnets: usize) { // if subnets <= 1 || (1<<self.prefix.host_prefix()) <= subnets { // return Err(String.format("Value {} out of range", subnets)) // } // let mut networks = self.subnet(self.newprefix(subnets)) // if (networks.len() != subnets) { // networks = sum_first_found(networks) // } // return networks // } // alias_method :/, :split // Returns a new IPv4 object from the supernetting // of the instance network. // // Supernetting is similar to subnetting, except // that you getting as a result a network with a // smaller prefix (bigger host space). For example, // given the network // // ip = IPAddress("172.16.10.0/24") // // you can supernet it with a new /23 prefix // // ip.supernet(23).to_string // // => "172.16.10.0/23" // // However if you supernet it with a /22 prefix, the // network address will change: // // ip.supernet(22).to_string // // => "172.16.8.0/22" // // If +new_prefix+ is less than 1, returns 0.0.0.0/0 // // pub fn supernet(&self, new_prefix: u8) { // if (new_prefix >= self.prefix.num) { // return Err(String.format("New prefix must be smaller than existing prefix: {} >= {}", // new_prefix, self.prefix.num)) // } // if new_prefix < 1 { // return Ok(IPv4::new("0.0.0.0/0")) // } // return Ok(IPv4::new(String.format("{}/{}", self.address, self.prefix.num))) // } // This method implements the subnetting function // similar to the one described in RFC3531. // // By specifying a new prefix, the method calculates // the network number for the given IPv4 object // and calculates the subnets associated to the new // prefix. // // For example, given the following network: // // ip = IPAddress "172.16.10.0/24" // // we can calculate the subnets with a /26 prefix // // ip.subnets(26).map(&:to_string) // // => ["172.16.10.0/26", "172.16.10.64/26", // "172.16.10.128/26", "172.16.10.192/26"] // // The resulting number of subnets will of course always be // a power of two. // // pub fn subnet(&self, subprefix: u8) { // if (subprefix <= self.prefix.num || 32 <= subprefix) { // return Err(String.format("New prefix must be between {} and 32", subprefix)) // } // let mut ret = Vec::new() // for (i = 0; i < (1 << (subprefix-self.prefix.num)); ++i) { // ret.push(IPv4::parse_u32(self.network_u32+(i*(1<<(32-subprefix))), subprefix)) // } // return ret // } // Return the ip address in a format compatible // with the IPv6 Mapped IPv4 addresses // // Example: // // ip = IPAddress("172.16.10.1/24") // // ip.to_ipv6 // // => "ac10:0a01" // // pub fn to_ipv6(my: &IPAddress) { // let part_mod = BigUint::one() << 16 // return String.format("{:04x}:{:04x}", // (my.host_address >> 16).mod_floor(&part_mod).to_u16().unwrap(), // my.host_address.mod_floor(&part_mod).to_u16().unwrap()) // } // Creates a new IPv4 object from an // unsigned 32bits integer. // // ip = IPAddress::IPv4::parse_u32(167772160) // // ip.prefix = 8 // ip.to_string // // => "10.0.0.0/8" // // The +prefix+ parameter is optional: // // ip = IPAddress::IPv4::parse_u32(167772160, 8) // // ip.to_string // // => "10.0.0.0/8" // // pub fn parse_u32(ip32: u32, prefix: u8) { // IPv4::new(String.format("{}/{}", IPv4::to_ipv4_str(ip32), prefix)) // } // Creates a new IPv4 object from binary data, // like the one you get from a network stream. // // For example, on a network stream the IP 172.16.0.1 // is represented with the binary "\254\020\n\001". // // ip = IPAddress::IPv4::parse_data "\254\020\n\001" // ip.prefix = 24 // // ip.to_string // // => "172.16.10.1/24" // // pub fn self.parse_data(str, prefix=32) // self.new(str.unpack("C4").join(".")+"/// {prefix}") // end // Extract an IPv4 address from a string and // returns a new object // // Example: // // str = "foobar172.16.10.1barbaz" // ip = IPAddress::IPv4::extract str // // ip.to_s // // => "172.16.10.1" // // pub fn self.extract(str) { // let re = Regexp::new(r"((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(25[0-5]|2[0-4]\d|1 // \d\d|[1-9]\d|\d)") // IPv4::new(.match(str).to_s // } // Summarization (or aggregation) is the process when two or more // networks are taken together to check if a supernet, including all // and only these networks, exists. If it exists then this supernet // is called the summarized (or aggregated) network. // // It is very important to understand that summarization can only // occur if there are no holes in the aggregated network, or, in other // words, if the given networks fill completely the address space // of the supernet. So the two rules are: // // 1) The aggregate network must contain +all+ the IP addresses of the // original networks // 2) The aggregate network must contain +only+ the IP addresses of the // original networks // // A few examples will help clarify the above. Let's consider for // instance the following two networks: // // ip1 = IPAddress("172.16.10.0/24") // ip2 = IPAddress("172.16.11.0/24") // // These two networks can be expressed using only one IP address // network if we change the prefix. Let Ruby do the work: // // IPAddress::IPv4::summarize(ip1,ip2).to_s // // => "172.16.10.0/23" // // We note how the network "172.16.10.0/23" includes all the addresses // specified in the above networks, and (more important) includes // ONLY those addresses. // // If we summarized +ip1+ and +ip2+ with the following network: // // "172.16.0.0/16" // // we would have satisfied rule // 1 above, but not rule // 2. So "172.16.0.0/16" // is not an aggregate network for +ip1+ and +ip2+. // // If it's not possible to compute a single aggregated network for all the // original networks, the method returns an array with all the aggregate // networks found. For example, the following four networks can be // aggregated in a single /22: // // ip1 = IPAddress("10.0.0.1/24") // ip2 = IPAddress("10.0.1.1/24") // ip3 = IPAddress("10.0.2.1/24") // ip4 = IPAddress("10.0.3.1/24") // // IPAddress::IPv4::summarize(ip1,ip2,ip3,ip4).to_string // // => "10.0.0.0/22", // // But the following networks can't be summarized in a single network: // // ip1 = IPAddress("10.0.1.1/24") // ip2 = IPAddress("10.0.2.1/24") // ip3 = IPAddress("10.0.3.1/24") // ip4 = IPAddress("10.0.4.1/24") // // IPAddress::IPv4::summarize(ip1,ip2,ip3,ip4).map{|i| i.to_string} // // => ["10.0.1.0/24","10.0.2.0/23","10.0.4.0/24"] // // pub fn self.summarize(args) // IPAddress.summarize(args) // end // Creates a new IPv4 address object by parsing the // address in a classful way. // // Classful addresses have a fixed netmask based on the // class they belong to: // // * Class A, from 0.0.0.0 to 127.255.255.255 // * Class B, from 128.0.0.0 to 191.255.255.255 // * Class C, D and E, from 192.0.0.0 to 255.255.255.254 // // Example: // // ip = IPAddress::IPv4.parse_classful "10.0.0.1" // // ip.netmask // // => "255.0.0.0" // ip.a? // // => true // // Note that classes C, D and E will all have a default // prefix of /24 or 255.255.255.0 // fun parse_classful(ip_s: String): Result<IPAddress> { if (!IPAddress.is_valid_ipv4(ip_s)) { return Result.Err("Invalid IP ${ip_s}") } val o_ip = IPAddress.parse(ip_s) if (o_ip.isErr()) { return o_ip } val ip = o_ip.unwrap() if (is_class_a(ip)) { return IPAddress.parse(String.format("%s/8", ip.to_s())) } else if (is_class_b(ip)) { return IPAddress.parse(String.format("%s/16", ip.to_s())) } else if (is_class_c(ip)) { return IPAddress.parse(String.format("%s/24", ip.to_s())) } return Result.Ok(ip) } } }
mit
b16de56fcbd7ef446aa3daaa7ab3bd22
22.319211
104
0.437539
3.590193
false
false
false
false
wakingrufus/mastodon-jfx
src/main/kotlin/com/github/wakingrufus/mastodon/toot/CreateToot.kt
1
606
package com.github.wakingrufus.mastodon.toot import com.sys1yagi.mastodon4j.MastodonClient import com.sys1yagi.mastodon4j.api.entity.Status import com.sys1yagi.mastodon4j.api.method.Statuses fun createToot(client: MastodonClient, statusesClient: () -> Statuses = { Statuses(client = client) }, status: String, inReplyToId: Long?): Status { return statusesClient.invoke().postStatus( status = status, inReplyToId = inReplyToId, sensitive = false, spoilerText = null, mediaIds = null).execute() }
mit
4363da555b9ab3a47e472d9194611c00
34.647059
78
0.646865
4.122449
false
false
false
false
danrien/projectBlue
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/shared/images/DefaultImageProvider.kt
2
1288
package com.lasthopesoftware.bluewater.shared.images import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import com.lasthopesoftware.bluewater.R import com.lasthopesoftware.resources.executors.ThreadPools import com.namehillsoftware.handoff.promises.Promise import com.namehillsoftware.handoff.promises.queued.MessageWriter import com.namehillsoftware.handoff.promises.queued.QueuedPromise class DefaultImageProvider(private val context: Context) { fun promiseFileBitmap(): Promise<Bitmap> = promiseFillerBitmap(context) companion object { private lateinit var fillerBitmap: Bitmap private fun promiseFillerBitmap(context: Context) = if (::fillerBitmap.isInitialized) Promise(getBitmapCopy(fillerBitmap)) else QueuedPromise(MessageWriter { if (!::fillerBitmap.isInitialized) { fillerBitmap = BitmapFactory.decodeResource(context.resources, R.drawable.wave_background) val dm = context.resources.displayMetrics val maxSize = dm.heightPixels.coerceAtLeast(dm.widthPixels) fillerBitmap = Bitmap.createScaledBitmap(fillerBitmap, maxSize, maxSize, false) } getBitmapCopy(fillerBitmap) }, ThreadPools.compute) private fun getBitmapCopy(src: Bitmap): Bitmap = src.copy(src.config, false) } }
lgpl-3.0
dbb7b9b105c561b9b90e7b22255d8873
39.25
95
0.806677
4.293333
false
false
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/test/kotlin/org/jitsi/nlj/module_tests/EndToEndHarness.kt
1
3402
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.nlj.module_tests import org.jitsi.nlj.PacketHandler import org.jitsi.nlj.PacketInfo import org.jitsi.nlj.util.BufferPool import org.jitsi.nlj.util.safeShutdown import org.jitsi.test_utils.Pcaps import org.jitsi.utils.secs import java.time.Clock import java.util.concurrent.Executors /** * Read packets from a PCAP file and feed them through a receiver * and then to a sender to simulate an end-to-end run of packets. * * NOTE that in some places this file tries to simulate behavior * of the bridge (for example cloning the packet before sending * it to the sender) but it does not perfectly simulate the bridge * (e.g. it does not do the simulcast filter/rewriting, send * probing, or other behaviors) */ fun main() { val pcap = Pcaps.Incoming.ONE_PARTICIPANT_RTP_RTCP_SIM_RTX var numBuffersRequested = 0 fun getBuffer(size: Int): ByteArray { numBuffersRequested++ return ByteArray(size) } var numBuffersReturned = 0 fun returnBuffer(@Suppress("UNUSED_PARAMETER") buf: ByteArray) { numBuffersReturned++ } BufferPool.getBuffer = ::getBuffer BufferPool.returnBuffer = ::returnBuffer org.jitsi.rtp.util.BufferPool.getArray = ::getBuffer org.jitsi.rtp.util.BufferPool.returnArray = ::returnBuffer val producer = PcapPacketProducer(pcap.filePath) val backgroundExecutor = Executors.newSingleThreadScheduledExecutor() val executor = Executors.newSingleThreadExecutor() val sender = SenderFactory.createSender( executor, backgroundExecutor, pcap.srtpData, pcap.payloadTypes, pcap.headerExtensions, pcap.ssrcAssociations ) val receiver = ReceiverFactory.createReceiver( executor, backgroundExecutor, pcap.srtpData, pcap.payloadTypes, pcap.headerExtensions, pcap.ssrcAssociations, { rtcpPacket -> sender.processPacket(PacketInfo(rtcpPacket)) } ) producer.subscribe { pkt -> val packetInfo = PacketInfo(pkt) packetInfo.receivedTime = Clock.systemUTC().instant() receiver.enqueuePacket(packetInfo) } receiver.packetHandler = object : PacketHandler { override fun processPacket(packetInfo: PacketInfo) { sender.processPacket(packetInfo) } } sender.onOutgoingPacket(object : PacketHandler { override fun processPacket(packetInfo: PacketInfo) { BufferPool.returnBuffer(packetInfo.packet.getBuffer()) } }) producer.run() receiver.stop() sender.stop() executor.safeShutdown(10.secs) backgroundExecutor.safeShutdown(10.secs) println(receiver.getNodeStats().prettyPrint()) println(sender.getNodeStats().prettyPrint()) println("gave out $numBuffersRequested buffers, returned $numBuffersReturned") }
apache-2.0
e05066163ca6988adb6205ad3a820a33
32.683168
82
0.721634
4.210396
false
false
false
false
emce/smog
app/src/main/java/mobi/cwiklinski/smog/database/Reading.kt
1
974
package mobi.cwiklinski.smog.database import android.database.Cursor public data class Reading( val year: Int = 0, val month: Int = 0, val day: Int = 0, val hour: Int = 0, val place: Int = 0, val amount: Int = 0, val color: String? = null ) { companion object { fun fromCursor(cursor: Cursor): Reading { return Reading( CursorHelper.getInt(cursor, AppContract.Readings.YEAR), CursorHelper.getInt(cursor, AppContract.Readings.MONTH), CursorHelper.getInt(cursor, AppContract.Readings.DAY), CursorHelper.getInt(cursor, AppContract.Readings.HOUR), CursorHelper.getInt(cursor, AppContract.Readings.PLACE), CursorHelper.getInt(cursor, AppContract.Readings.AMOUNT), CursorHelper.getString(cursor, AppContract.Readings.COLOR) ) } } }
apache-2.0
6ab9911f5891ee85dbebf38653bdd802
31.5
78
0.580082
4.488479
false
false
false
false
FurhatRobotics/example-skills
JokeBot/src/main/kotlin/furhatos/app/jokebot/jokes/jokeHandler.kt
1
2759
package furhatos.app.jokebot.jokes import com.google.gson.Gson import com.google.gson.JsonSyntaxException import furhatos.util.CommonUtils val BASIC_LIST_OF_JOKES = listOf( Joke("What do robots eat as snacks", "micro-chips"), Joke("What do robots do at lunchtime", "have a mega-byte"), Joke("What happened when they shut down the robot motorway?", "Everyone had to take the R2 detour.", 1.0), Joke("Why was the robot bankrupt?", "He had used all his cache"), Joke("Why did the robot marry his partner?", "He couldn't resistor"), Joke("What does R2D2 use to open PDF files?", "Adobe. wan. kenobi."), Joke("Why do robots take holidays?", "To recharge their batteries"), Joke("Who's a robot's favourite author?", "Anne. droid."), Joke("Why was the robot tired when it got home?", "it had a hard drive!"), Joke("What is most important when telling jokes", "timing") ) data class Joke(val intro: String, val punchline: String, var score: Double? = null) object JokeHandler { /** * File to read/save jokes to. * Can be found in the user's home directory/.furhat/jokes.json when running on SDK. */ private val jokeFile = CommonUtils.getAppDataDir("jokes.json") private val gson = Gson().newBuilder().setPrettyPrinting().create() //JSON parser/serializer private val listOfJokes = getJokes() //List of jokes private lateinit var currentJoke: Joke //Will be initialized when we request the first joke. /** * Returns a joke, and saves that joke to the current joke variable. */ fun getJoke(): Joke { currentJoke = listOfJokes.random() return currentJoke } /** * Changes the current joke score with the change provided. */ fun changeJokeScore(scoreChange: Double) { if (currentJoke.score == null) { currentJoke.score = 0.0 } currentJoke.score = currentJoke.score!! + scoreChange writeToFile() } /** * Tries to read the jokes from file. If that file does not exist, or the JSON cannot be parsed, we return a basic * list of jokes. */ private fun getJokes(): List<Joke> { return if (jokeFile.exists()) { try { gson.fromJson(jokeFile.readText(), Array<Joke>::class.java).toList() } catch (_: JsonSyntaxException) { BASIC_LIST_OF_JOKES } } else { BASIC_LIST_OF_JOKES } } /** * Writes the current list of jokes to a file */ private fun writeToFile() { if (!jokeFile.exists()) { jokeFile.createNewFile() } jokeFile.writeText(gson.toJson(listOfJokes)) } }
mit
d6a11e6c86536365dba8b47305480a48
33.924051
118
0.61979
3.88045
false
false
false
false
tgirard12/kotlin-talk
android/src/main/kotlin/com/tgirard12/kotlintalk/Utils.kt
1
2192
package com.tgirard12.kotlintalk import android.app.Activity import android.support.design.widget.Snackbar import android.support.graphics.drawable.VectorDrawableCompat import android.view.View import android.widget.ImageView import android.widget.TextView import com.squareup.picasso.Picasso import retrofit2.Call import retrofit2.Callback import retrofit2.Response import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty inline fun <reified V : View> Activity.bindView(resId: Int): ReadOnlyProperty<Activity, V> = Delegate { this.findViewById(resId) as V } class Delegate<in A, out V>(val funFindView: (A) -> V) : ReadOnlyProperty<A, V> { override fun getValue(thisRef: A, property: KProperty<*>): V { return funFindView(thisRef) } } fun Activity.snackbar(idRes: Int) = Snackbar.make( this.findViewById(android.R.id.content), this.getText(idRes), Snackbar.LENGTH_LONG).show() fun Activity.createVector(idRes: Int) = VectorDrawableCompat.create(this.resources, idRes, this.theme) infix fun TextView.textIs(value: String?) { this.text = value } infix fun ImageView.loadUrl(url: String?) { url?.let { Picasso.with(this.context.applicationContext) .load(it) .into(this) } ?: this.setImageDrawable(null) } /** * */ inline fun <reified T> Call<T>.enqueue(init: RetrofitTipsCallback<T>.() -> Unit) { enqueue(RetrofitTipsCallback<T>().apply(init)) } class RetrofitTipsCallback<T> : Callback<T> { // Backing fields private lateinit var onResponse: (call: Call<T>?, response: Response<T>) -> Unit private lateinit var onFailure: (call: Call<T>, t: Throwable) -> Unit // DSL function fun onResponse(block: (call: Call<T>?, response: Response<T>) -> Unit) { onResponse = block } fun onFailure(block: (call: Call<T>, t: Throwable) -> Unit) { onFailure = block } // Retrofit method override fun onResponse(call: Call<T>?, response: Response<T>) { onResponse.invoke(call, response) } override fun onFailure(call: Call<T>, t: Throwable) { onFailure.invoke(call, t) } } /** * */ annotation class GsonClass
apache-2.0
0fa63cd659090c0d500342258b86a126
27.480519
135
0.693431
3.785838
false
false
false
false
JetBrains/resharper-unity
rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/ui/UnityUIMinimizer.kt
1
2215
package com.jetbrains.rider.plugins.unity.ui import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.wm.IdeFocusManager import com.intellij.openapi.wm.ToolWindowManager import com.intellij.util.application import com.jetbrains.rider.plugins.unity.UnityProjectDiscoverer class UnityUIMinimizer : StartupActivity { companion object { fun ensureMinimizedUI(project: Project) { application.assertIsDispatchThread() if (project.isDisposed) return val unityUiManager = UnityUIManager.getInstance(project) unityUiManager.hasMinimizedUi.value = true IdeFocusManager.getInstance(project).doWhenFocusSettlesDown { val toolWindowManager = ToolWindowManager.getInstance(project) val nuget = toolWindowManager.getToolWindow("NuGet") ?: return@doWhenFocusSettlesDown nuget.isShowStripeButton = false } } fun recoverFullUI(project: Project) { application.assertIsDispatchThread() if (project.isDisposed) return val unityUiManager = UnityUIManager.getInstance(project) unityUiManager.hasMinimizedUi.value = false IdeFocusManager.getInstance(project).doWhenFocusSettlesDown { val toolWindowManager = ToolWindowManager.getInstance(project) val toolWindow = toolWindowManager.getToolWindow("NuGet") ?: return@doWhenFocusSettlesDown toolWindow.isShowStripeButton = true } } } override fun runActivity(project: Project) { application.invokeLater { val unityUIManager = UnityUIManager.getInstance(project) // Only hide UI for generated projects, so that sidecar projects can still access nuget if (UnityProjectDiscoverer.getInstance(project).isUnityGeneratedProject) { if (unityUIManager.hasMinimizedUi.value == null || unityUIManager.hasMinimizedUi.hasTrueValue()) ensureMinimizedUI(project) } } } }
apache-2.0
815ff1fe3a9b05caaf938176de9c61a2
38.571429
112
0.664108
5.679487
false
false
false
false
ReactiveCircus/FlowBinding
flowbinding-android/src/androidTest/java/reactivecircus/flowbinding/android/testutil/TestMenuItem.kt
1
6213
package reactivecircus.flowbinding.android.testutil import android.content.Context import android.content.Intent import android.graphics.drawable.Drawable import android.view.ActionProvider import android.view.ContextMenu import android.view.LayoutInflater import android.view.MenuItem import android.view.SubMenu import android.view.View import androidx.core.content.ContextCompat class TestMenuItem(private val context: Context) : MenuItem { private var itemId: Int = 0 private var groupId: Int = 0 private var order: Int = 0 private var title: CharSequence? = null private var titleCondensed: CharSequence? = null private var icon: Drawable? = null private var intent: Intent? = null private var numericChar: Char = ' ' private var alphaChar: Char = ' ' private var checkable: Boolean = false private var checked: Boolean = false private var visible: Boolean = false private var enabled: Boolean = false private var menuItemClickListener: MenuItem.OnMenuItemClickListener? = null private var actionEnum: Int = 0 private var actionView: View? = null private var actionProvider: ActionProvider? = null private var isActionViewExpanded: Boolean = false private var actionExpandListener: MenuItem.OnActionExpandListener? = null fun performClick() { menuItemClickListener?.onMenuItemClick(this) } override fun expandActionView(): Boolean { return when { isActionViewExpanded -> true actionExpandListener != null && !actionExpandListener!!.onMenuItemActionExpand(this) -> false else -> { isActionViewExpanded = true return true } } } override fun hasSubMenu(): Boolean { return false } override fun getMenuInfo(): ContextMenu.ContextMenuInfo? { return null } override fun getItemId(): Int { return itemId } override fun getAlphabeticShortcut(): Char { return alphaChar } override fun setEnabled(enabled: Boolean): MenuItem { this.enabled = enabled return this } override fun setTitle(title: CharSequence?): MenuItem { this.title = title return this } override fun setTitle(title: Int): MenuItem { this.title = context.getText(title) return this } override fun setChecked(checked: Boolean): MenuItem { if (checkable) { this.checked = checked } return this } override fun getActionView(): View? { return actionView } override fun getTitle(): CharSequence? { return title } override fun getOrder(): Int { return order } override fun setOnActionExpandListener(listener: MenuItem.OnActionExpandListener?): MenuItem { this.actionExpandListener = listener return this } override fun getIntent(): Intent? { return intent } override fun setVisible(visible: Boolean): MenuItem { this.visible = visible return this } override fun isEnabled(): Boolean { return enabled } override fun isCheckable(): Boolean { return checkable } override fun setShowAsAction(actionEnum: Int) { this.actionEnum = actionEnum } override fun getGroupId(): Int { return groupId } override fun setActionProvider(actionProvider: ActionProvider?): MenuItem { this.actionProvider = actionProvider return this } override fun setTitleCondensed(title: CharSequence?): MenuItem { this.titleCondensed = title return this } override fun getNumericShortcut(): Char { return numericChar } override fun isActionViewExpanded(): Boolean { return isActionViewExpanded } override fun collapseActionView(): Boolean { return when { !isActionViewExpanded -> false actionExpandListener != null && !actionExpandListener!!.onMenuItemActionCollapse(this) -> false else -> { isActionViewExpanded = false return true } } } override fun isVisible(): Boolean { return visible } override fun setNumericShortcut(numericChar: Char): MenuItem { this.numericChar = numericChar return this } override fun setActionView(view: View?): MenuItem { this.actionView = view return this } override fun setActionView(resId: Int): MenuItem { this.actionView = LayoutInflater.from(context).inflate(resId, null) return this } override fun setAlphabeticShortcut(alphaChar: Char): MenuItem { this.alphaChar = alphaChar return this } override fun setIcon(icon: Drawable?): MenuItem { this.icon = icon return this } override fun setIcon(iconRes: Int): MenuItem { this.icon = ContextCompat.getDrawable(context, iconRes) return this } override fun isChecked(): Boolean { return checked } override fun setIntent(intent: Intent?): MenuItem { this.intent = intent return this } override fun setShortcut(numericChar: Char, alphaChar: Char): MenuItem { this.numericChar = numericChar this.alphaChar = alphaChar return this } override fun getIcon(): Drawable? { return icon } override fun setShowAsActionFlags(actionEnum: Int): MenuItem { this.actionEnum = actionEnum return this } override fun setOnMenuItemClickListener(menuItemClickListener: MenuItem.OnMenuItemClickListener?): MenuItem { this.menuItemClickListener = menuItemClickListener return this } override fun getActionProvider(): ActionProvider? { return actionProvider } override fun setCheckable(checkable: Boolean): MenuItem { this.checkable = checkable return this } override fun getSubMenu(): SubMenu? { return null } override fun getTitleCondensed(): CharSequence? { return titleCondensed } }
apache-2.0
84da7054e241154759c56985553fa297
24.995816
113
0.646226
5.251902
false
false
false
false
owncloud/android
owncloudData/src/main/java/com/owncloud/android/data/authentication/AuthenticationConstants.kt
1
1899
/** * ownCloud Android client application * * @author David González Verdugo * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * 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.owncloud.android.data.authentication const val SELECTED_ACCOUNT = "select_oc_account" /** * OAuth2 user id */ const val KEY_USER_ID = "user_id" /** * OAuth2 refresh token */ const val KEY_OAUTH2_REFRESH_TOKEN = "oc_oauth2_refresh_token" /** * OAuth2 scope */ const val KEY_OAUTH2_SCOPE = "oc_oauth2_scope" const val OAUTH2_OIDC_SCOPE = "openid offline_access email profile" /** * OIDC Client Registration */ const val KEY_CLIENT_REGISTRATION_CLIENT_ID = "client_id" const val KEY_CLIENT_REGISTRATION_CLIENT_SECRET = "client_secret" const val KEY_CLIENT_REGISTRATION_CLIENT_EXPIRATION_DATE = "client_secret_expires_at" /** Query parameters to retrieve the authorization code. More info: https://tools.ietf.org/html/rfc6749#section-4.1.1 */ const val QUERY_PARAMETER_REDIRECT_URI = "redirect_uri" const val QUERY_PARAMETER_CLIENT_ID = "client_id" const val QUERY_PARAMETER_RESPONSE_TYPE = "response_type" const val QUERY_PARAMETER_SCOPE = "scope" const val QUERY_PARAMETER_CODE_CHALLENGE = "code_challenge" const val QUERY_PARAMETER_CODE_CHALLENGE_METHOD = "code_challenge_method" const val QUERY_PARAMETER_STATE = "state" const val QUERY_PARAMETER_USERNAME = "user"
gpl-2.0
46fdc36f71d08b2315cde38ed923de80
33.509091
120
0.748683
3.636015
false
false
false
false
google/horologist
media-ui/src/main/java/com/google/android/horologist/media/ui/components/animated/AnimatedMediaControlButtons.kt
1
4692
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.media.ui.components.animated import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.wear.compose.material.ButtonColors import androidx.wear.compose.material.ButtonDefaults import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi import com.google.android.horologist.media.ui.components.ControlButtonLayout import com.google.android.horologist.media.ui.components.PlayPauseButton import com.google.android.horologist.media.ui.components.PlayPauseProgressButton import com.google.android.horologist.media.ui.components.controls.MediaButtonDefaults import com.google.android.horologist.media.ui.components.controls.SeekToNextButton import com.google.android.horologist.media.ui.components.controls.SeekToPreviousButton /** * Standard media control buttons, showing [SeekToPreviousButton], [PlayPauseProgressButton] and * [SeekToNextButton]. */ @ExperimentalHorologistMediaUiApi @Composable public fun AnimatedMediaControlButtons( onPlayButtonClick: () -> Unit, onPauseButtonClick: () -> Unit, playPauseButtonEnabled: Boolean, playing: Boolean, percent: Float, onSeekToPreviousButtonClick: () -> Unit, seekToPreviousButtonEnabled: Boolean, onSeekToNextButtonClick: () -> Unit, seekToNextButtonEnabled: Boolean, modifier: Modifier = Modifier, colors: ButtonColors = MediaButtonDefaults.mediaButtonDefaultColors ) { AnimatedMediaControlButtons( onPlayButtonClick = onPlayButtonClick, onPauseButtonClick = onPauseButtonClick, playPauseButtonEnabled = playPauseButtonEnabled, playing = playing, onSeekToPreviousButtonClick = onSeekToPreviousButtonClick, seekToPreviousButtonEnabled = seekToPreviousButtonEnabled, onSeekToNextButtonClick = onSeekToNextButtonClick, seekToNextButtonEnabled = seekToNextButtonEnabled, showProgress = true, modifier = modifier, percent = percent, colors = colors ) } @ExperimentalHorologistMediaUiApi @Composable internal fun AnimatedMediaControlButtons( onPlayButtonClick: () -> Unit, onPauseButtonClick: () -> Unit, playPauseButtonEnabled: Boolean, playing: Boolean, onSeekToPreviousButtonClick: () -> Unit, seekToPreviousButtonEnabled: Boolean, onSeekToNextButtonClick: () -> Unit, seekToNextButtonEnabled: Boolean, showProgress: Boolean, modifier: Modifier = Modifier, percent: Float? = null, colors: ButtonColors = MediaButtonDefaults.mediaButtonDefaultColors ) { ControlButtonLayout( modifier = modifier, leftButton = { AnimatedSeekToPreviousButton( onClick = onSeekToPreviousButtonClick, enabled = seekToPreviousButtonEnabled, colors = colors ) }, middleButton = { if (showProgress) { checkNotNull(percent) PlayPauseProgressButton( onPlayClick = onPlayButtonClick, onPauseClick = onPauseButtonClick, enabled = playPauseButtonEnabled, playing = playing, percent = percent, modifier = Modifier.size(ButtonDefaults.LargeButtonSize), colors = colors ) } else { PlayPauseButton( onPlayClick = onPlayButtonClick, onPauseClick = onPauseButtonClick, enabled = playPauseButtonEnabled, playing = playing, modifier = Modifier.size(ButtonDefaults.LargeButtonSize), colors = colors ) } }, rightButton = { AnimatedSeekToNextButton( onClick = onSeekToNextButtonClick, enabled = seekToNextButtonEnabled, colors = colors ) } ) }
apache-2.0
d0cd987fda91e125f1b39766ffcf3f8c
36.83871
96
0.682651
5.430556
false
false
false
false
elifarley/kotlin-examples
src/com/github/elifarley/kotlin/persistence/model/MyTable.kt
1
3030
package com.orgecc.myproj.model import javax.persistence.* import java.math.BigDecimal import java.util.Date // Insert rows via stored procedure using Spring Data /* MS-SQL: CREATE TABLE dbo.MY_TABLE ( CREATED datetime NOT NULL CONSTRAINT DF_CREATED DEFAULT CURRENT_TIMESTAMP, UPDATED datetime NOT NULL CONSTRAINT DF_UPDATED DEFAULT CURRENT_TIMESTAMP, fk_type_id int NOT NULL FOREIGN KEY REFERENCES FK_TYPE(ID), date date NOT NULL, value numeric(9,4) NOT NULL, CONSTRAINT PK_MY_TABLE PRIMARY KEY (CREATED) ); CREATE PROCEDURE [my_table_upsert] @fk_type_id int , @date date = CURRENT_TIMESTAMP , @value numeric(9,4) = 0 AS begin SET NOCOUNT ON; MERGE INTO dbo.MY_TABLE WITH (HOLDLOCK) AS t USING (SELECT @fk_type_id, @date) AS s (fk_type_id, date) ON t.fk_type_id = s.fk_type_id and t.date = s.date WHEN MATCHED THEN UPDATE SET value = @value, UPDATED = CURRENT_TIMESTAMP WHEN NOT MATCHED THEN INSERT (fk_type_id, date, value) VALUES (s.fk_type_id, s.date, @value); SET NOCOUNT OFF; end; */ // ------------ // Model // ------------ @NamedStoredProcedureQueries( NamedStoredProcedureQuery(name = "myTableUpsert", procedureName = "my_table_upsert", parameters = arrayOf( StoredProcedureParameter(mode = ParameterMode.IN, name = "fk_type_id", type = Integer::class), StoredProcedureParameter(mode = ParameterMode.IN, name = "date", type = Date::class), StoredProcedureParameter(mode = ParameterMode.IN, name = "value", type = BigDecimal::class) ) ) ) @Entity class MyTable (@Id var dummy: Serializable? = null) // ------------ // Repository // ------------ import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.query.Procedure import org.springframework.data.repository.query.Param import java.math.BigDecimal import java.util.Date interface MyTableRepository : JpaRepository<MyTable, Serializable> { @Procedure(name = "myTableUpsert") fun upsert(@Param("fk_type_id") fk_type_id: Integer, @Param("date") date: Date, @Param("value") value: BigDecimal) @Query(nativeQuery = true, value = """ select top 1 value from my_table where my_fk_id=1 and date <= :date order by date desc """) fun findValueForDate(@Param("date") date: Date): BigDecimal? } // ------------ // Service // ------------ @Service open class MyTableService @Autowired constructor(private val myTableRepository: MyTableRepository) { companion object : WithLogging() {} @Transactional open fun upsert(fk_type_id: Int, valueAtDate: MyParser.ValueAtDate) { var date = valueAtDate.date date = date.withDayOfMonth(1) LOG.info("[indexId: $indexId; $valueAtDate]") myTableRepository.upsert(fk_type_id as Integer, java.sql.Date.valueOf(date), valueAtDate.value) } open fun findValueForDate(date: Date) = myTableRepository.findValueForDate(date) ?: BigDecimal.ZERO!! }
mit
fe08d0257e9201731b9fee9cbd5c4157
27.857143
118
0.677228
3.677184
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UIBarButtonItem.kt
1
1716
package com.yy.codex.uikit import android.content.Context import com.yy.codex.foundation.NSInvocation /** * Created by cuiminghui on 2017/1/18. */ class UIBarButtonItem(val target: Any?, val action: String?) : UIBarItem() { var isSystemBackItem = false internal set var customView: UIView? = null var width = 0.0 var insets: UIEdgeInsets = UIEdgeInsets(0.0, 8.0, 0.0, 8.0) constructor(title: String?, target: Any?, action: String?) : this(target, action) { this.title = title } constructor(image: UIImage?, target: Any?, action: String?) : this(target, action) { this.image = image } override fun getContentView(context: Context): UIView? { if (customView != null) { if (width > 0.0) { customView?.frame = CGRect(0.0, 0.0, width, Math.min(44.0, (customView?.frame?.height ?: 0.0))) } customView?.marginInsets = insets return customView } else if (view == null) { val button = UIButton(context) title?.let { button.font = UIFont(17f) button.setTitle(it, UIControl.State.Normal) } image?.let { button.setImage(it, UIControl.State.Normal) } button.frame = CGRect(0.0, 0.0, button.intrinsicContentSize().width, 44.0) button.imageEdgeInsets = imageInsets if (target != null && action != null) { button.addTarget(target, action, UIControl.Event.TouchUpInside) } view = button view?.marginInsets = insets } return super.getContentView(context) } }
gpl-3.0
8274a2a7f68e4b2a214bb4eea3d1c385
30.2
111
0.568765
4.066351
false
false
false
false
Doctoror/FuckOffMusicPlayer
data/src/main/java/com/doctoror/fuckoffmusicplayer/data/playback/controller/PlaybackControllerShuffle.kt
2
2319
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.fuckoffmusicplayer.data.playback.controller import android.util.SparseIntArray import com.doctoror.fuckoffmusicplayer.data.playback.unit.PlaybackServiceUnitPlayMediaFromQueue import com.doctoror.fuckoffmusicplayer.data.util.RandomHolder import com.doctoror.fuckoffmusicplayer.domain.playback.PlaybackData import com.doctoror.fuckoffmusicplayer.domain.playback.PlaybackParams import com.doctoror.fuckoffmusicplayer.domain.queue.Media import java.util.* class PlaybackControllerShuffle( playbackData: PlaybackData, playbackParams: PlaybackParams, playMediaFromQueueUseCase: PlaybackServiceUnitPlayMediaFromQueue, stopAction: Runnable) : PlaybackControllerNormal( playbackData, playbackParams, playMediaFromQueueUseCase, stopAction) { private val shuffledPositions = SparseIntArray() override fun setQueue(queue: List<Media>?) { synchronized(lock) { rebuildShuffledPositions(queue?.size ?: 0) } super.setQueue(queue) } override fun play(list: List<Media>?, position: Int) { var shuffledPosition = 0 synchronized(lock) { shuffledPosition = shuffledPositions.get(position) } super.play(list, shuffledPosition) } private fun rebuildShuffledPositions(size: Int) { shuffledPositions.clear() if (size != 0) { val positions = ArrayList<Int>(size) for (i in 0 until size) { positions.add(i) } positions.shuffle(RandomHolder.getInstance().random) for (i in 0 until size) { shuffledPositions.put(i, positions[i]) } } } }
apache-2.0
109b2ebf924581a9daa9f8640de955ae
34.676923
95
0.699871
4.592079
false
false
false
false
LucasHelal/AerolabsMissionPlanner
Android/src/org/droidplanner/android/maps/providers/google_map/GoogleMapPrefFragment.kt
5
16025
package org.droidplanner.android.maps.providers.google_map import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.net.Uri import android.os.Bundle import android.preference.ListPreference import android.preference.Preference import android.preference.PreferenceCategory import android.preference.PreferenceManager import android.text.TextUtils import android.widget.Toast import com.google.android.gms.maps.GoogleMap import org.droidplanner.android.R import org.droidplanner.android.dialogs.EditInputDialog import org.droidplanner.android.maps.providers.DPMapProvider import org.droidplanner.android.maps.providers.MapProviderPreferences import org.droidplanner.android.maps.providers.google_map.GoogleMapPrefConstants.GOOGLE_TILE_PROVIDER import org.droidplanner.android.maps.providers.google_map.GoogleMapPrefConstants.MAPBOX_TILE_PROVIDER import org.droidplanner.android.maps.providers.google_map.GoogleMapPrefConstants.TileProvider /** * This is the google map provider preferences. It stores and handles all preferences related to google map. */ public class GoogleMapPrefFragment : MapProviderPreferences(), EditInputDialog.Listener { companion object PrefManager { private val MAPBOX_ACCESS_TOKEN_DIALOG_TAG = "Mapbox access token dialog" private val MAPBOX_ID_DIALOG_TAG = "Mapbox map credentials dialog" val DEFAULT_TILE_PROVIDER = GOOGLE_TILE_PROVIDER val MAP_TYPE_SATELLITE = "satellite" val MAP_TYPE_HYBRID = "hybrid" val MAP_TYPE_NORMAL = "normal" val MAP_TYPE_TERRAIN = "terrain" val PREF_TILE_PROVIDERS = "pref_google_map_tile_providers" val PREF_GOOGLE_TILE_PROVIDER_SETTINGS = "pref_google_tile_provider_settings" val PREF_MAP_TYPE = "pref_map_type" val DEFAULT_MAP_TYPE = MAP_TYPE_SATELLITE val PREF_MAPBOX_TILE_PROVIDER_SETTINGS = "pref_mapbox_tile_provider_settings" val PREF_MAPBOX_MAP_DOWNLOAD = "pref_mapbox_map_download" val PREF_DOWNLOAD_MENU_OPTION = "pref_download_menu_option" val DEFAULT_DOWNLOAD_MENU_OPTION = false val PREF_MAPBOX_ID = "pref_mapbox_id" val PREF_MAPBOX_ACCESS_TOKEN = "pref_mapbox_access_token" val PREF_MAPBOX_LEARN_MORE = "pref_mapbox_learn_more" val PREF_ENABLE_OFFLINE_LAYER = "pref_enable_offline_map_layer" val DEFAULT_OFFLINE_LAYER_ENABLED = false fun getMapType(context: Context?): Int { var mapType = GoogleMap.MAP_TYPE_SATELLITE context?.let { val sharedPref = PreferenceManager.getDefaultSharedPreferences(context) val selectedType = sharedPref.getString(PREF_MAP_TYPE, DEFAULT_MAP_TYPE) when(selectedType){ MAP_TYPE_HYBRID -> mapType = GoogleMap.MAP_TYPE_HYBRID MAP_TYPE_NORMAL -> mapType = GoogleMap.MAP_TYPE_NORMAL MAP_TYPE_TERRAIN -> mapType = GoogleMap.MAP_TYPE_TERRAIN MAP_TYPE_SATELLITE -> mapType = GoogleMap.MAP_TYPE_SATELLITE else -> mapType = GoogleMap.MAP_TYPE_SATELLITE } } return mapType } @TileProvider fun getMapTileProvider(context: Context?): String { var tileProvider = DEFAULT_TILE_PROVIDER context?.let { val sharedPref = PreferenceManager.getDefaultSharedPreferences(context) tileProvider = sharedPref.getString(PREF_TILE_PROVIDERS, tileProvider) } return tileProvider } fun setMapTileProvider(context: Context?, @TileProvider tileProvider: String?){ context?.let { val sharedPref = PreferenceManager.getDefaultSharedPreferences(context) sharedPref.edit().putString(PREF_TILE_PROVIDERS, tileProvider).apply() } } fun isOfflineMapLayerEnabled(context: Context?): Boolean { return if(context == null){ DEFAULT_OFFLINE_LAYER_ENABLED } else{ val sharedPref = PreferenceManager.getDefaultSharedPreferences(context) sharedPref.getBoolean(PREF_ENABLE_OFFLINE_LAYER, DEFAULT_OFFLINE_LAYER_ENABLED) } } fun addDownloadMenuOption(context: Context?): Boolean { return if(context == null) DEFAULT_DOWNLOAD_MENU_OPTION else{ val sharedPref = PreferenceManager.getDefaultSharedPreferences(context) sharedPref.getBoolean(PREF_DOWNLOAD_MENU_OPTION, DEFAULT_DOWNLOAD_MENU_OPTION) } } fun getMapboxId(context: Context?): String { return if(context == null) "" else{ val sharedPref = PreferenceManager.getDefaultSharedPreferences(context) sharedPref.getString(PREF_MAPBOX_ID, "") } } fun setMapboxId(context: Context?, mapboxId: String?){ context?.let { val sharedPref = PreferenceManager.getDefaultSharedPreferences(context) sharedPref.edit().putString(PREF_MAPBOX_ID, mapboxId).apply() } } fun getMapboxAccessToken(context: Context?): String { return if(context == null) "" else{ val sharedPref = PreferenceManager.getDefaultSharedPreferences(context) sharedPref.getString(PREF_MAPBOX_ACCESS_TOKEN, "") } } fun setMapboxAccessToken(context: Context?, mapboxToken: String?){ context?.let { val sharedPref = PreferenceManager.getDefaultSharedPreferences(context) sharedPref.edit().putString(PREF_MAPBOX_ACCESS_TOKEN, mapboxToken).apply() } } } private val accessTokenDialog = EditInputDialog.newInstance(MAPBOX_ACCESS_TOKEN_DIALOG_TAG, "Enter mapbox access token", "mapbox access token", false) private var tileProvidersPref: ListPreference? = null override fun onCreate(savedInstanceState: Bundle?) { super<MapProviderPreferences>.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.preferences_google_maps) setupPreferences() } private fun setupPreferences() { val context = activity.applicationContext val sharedPref = PreferenceManager.getDefaultSharedPreferences(context) setupTileProvidersPreferences(sharedPref) setupGoogleTileProviderPreferences(sharedPref) setupMapboxTileProviderPreferences(sharedPref) } private fun isMapboxIdSet() = !TextUtils.isEmpty(getMapboxId(getContext())) private fun isMapboxAccessTokenSet() = !TextUtils.isEmpty(getMapboxAccessToken(getContext())) private fun areMapboxCredentialsSet() = isMapboxAccessTokenSet() && isMapboxIdSet() private fun enableTileProvider(provider: String, persistPreference: Boolean){ val tileProviderPref = findPreference(PREF_TILE_PROVIDERS) as ListPreference? if(tileProviderPref != null) { enableTileProvider(tileProviderPref, provider, persistPreference) } } private fun enableTileProvider(tileProviderPref: ListPreference?, provider: String, persistPreference: Boolean){ if(persistPreference){ tileProviderPref?.value = provider setMapTileProvider(getContext(), provider) } tileProviderPref?.summary = provider toggleTileProviderPrefs(provider) } override fun onCancel(dialogTag: String) {} override fun onOk(dialogTag: String, input: CharSequence?) { val context = getContext() when (dialogTag) { MAPBOX_ID_DIALOG_TAG -> { if (TextUtils.isEmpty(input)) { Toast.makeText(context, R.string.label_invalid_mapbox_id, Toast.LENGTH_LONG) .show() } else { //Save the mapbox id to preferences updateMapboxId(input?.toString() ?: "", true) //Check if the mapbox access token is set enable the mapbox tile // provider if (isMapboxAccessTokenSet()) { enableTileProvider(tileProvidersPref, MAPBOX_TILE_PROVIDER, true) } //Check if the mapbox access token is set accessTokenDialog?.show(fragmentManager, MAPBOX_ACCESS_TOKEN_DIALOG_TAG) } } MAPBOX_ACCESS_TOKEN_DIALOG_TAG -> { if(TextUtils.isEmpty(input)){ Toast.makeText(context, R.string.label_invalid_mapbox_access_token, Toast.LENGTH_LONG).show() } else{ //Save the mapbox access token to preferences updateMapboxAccessToken(input?.toString() ?: "", true) //Check if the mapbox id is set to enable the mapbox tile provider. if(isMapboxIdSet()){ enableTileProvider(tileProvidersPref, MAPBOX_TILE_PROVIDER, true) } } } } } private fun setupTileProvidersPreferences(sharedPref: SharedPreferences) { val tileProvidersKey = PREF_TILE_PROVIDERS tileProvidersPref = findPreference(tileProvidersKey) as ListPreference? if(tileProvidersPref != null){ val tileProvider = sharedPref.getString(tileProvidersKey, DEFAULT_TILE_PROVIDER) tileProvidersPref?.summary = tileProvider tileProvidersPref?.setOnPreferenceChangeListener { preference, newValue -> val updatedTileProvider = newValue.toString() var acceptChange = true if (updatedTileProvider == MAPBOX_TILE_PROVIDER) { //Check if the mapbox id and access token are set. if (!areMapboxCredentialsSet()) { //Show a dialog requesting the user to enter its mapbox id and access token acceptChange = false val inputDialog = if(!isMapboxIdSet()){ EditInputDialog.newInstance(MAPBOX_ID_DIALOG_TAG, "Enter mapbox id", "mapbox id", false) } else{ if(!isMapboxAccessTokenSet()){ accessTokenDialog } else{ null } } inputDialog?.show(fragmentManager, MAPBOX_ID_DIALOG_TAG) } } if(acceptChange) { enableTileProvider(tileProvidersPref, updatedTileProvider, false) true } else{ false } } toggleTileProviderPrefs(tileProvider) } } private fun setupGoogleTileProviderPreferences(sharedPref: SharedPreferences) { val mapTypeKey = PREF_MAP_TYPE val mapTypePref = findPreference(mapTypeKey) mapTypePref?.let { mapTypePref.summary = sharedPref.getString(mapTypeKey, DEFAULT_MAP_TYPE) mapTypePref.setOnPreferenceChangeListener { preference, newValue -> mapTypePref.summary = newValue.toString() true } } } private fun setupMapboxTileProviderPreferences(sharedPref: SharedPreferences) { val context = getContext() //Setup mapbox map download button val downloadMapPref = findPreference(PREF_MAPBOX_MAP_DOWNLOAD) downloadMapPref?.setOnPreferenceClickListener { startActivity(Intent(getContext(), DownloadMapboxMapActivity::class.java)) true } //Setup mapbox map id val mapboxIdPref = findPreference(PREF_MAPBOX_ID) if(mapboxIdPref != null) { val mapboxId = sharedPref.getString(PREF_MAPBOX_ID, null) mapboxId?.let { mapboxIdPref.summary = mapboxId } mapboxIdPref.setOnPreferenceChangeListener { preference, newValue -> val newMapboxId = newValue.toString() if(TextUtils.isEmpty(newMapboxId)){ Toast.makeText(context, R.string.label_invalid_mapbox_id, Toast.LENGTH_LONG) .show() } updateMapboxId(newMapboxId, false) true } } //Setup mapbox access token val mapboxTokenPref = findPreference(PREF_MAPBOX_ACCESS_TOKEN) if(mapboxTokenPref != null) { val mapboxToken = sharedPref.getString(PREF_MAPBOX_ACCESS_TOKEN, null) mapboxToken?.let { mapboxTokenPref.summary = mapboxToken } mapboxTokenPref.setOnPreferenceChangeListener {preference, newValue -> val mapboxAccessToken = newValue.toString() if(TextUtils.isEmpty(mapboxAccessToken)){ Toast.makeText(context, R.string.label_invalid_mapbox_access_token, Toast.LENGTH_LONG).show() } updateMapboxAccessToken(mapboxAccessToken, false) true } } //Setup the learn more about mapbox map button val mapboxLearnMorePref = findPreference(PREF_MAPBOX_LEARN_MORE) mapboxLearnMorePref?.setOnPreferenceClickListener { startActivity(Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://www.mapbox.com/plans/"))) true } } private fun updateMapboxId(id: String, persist: Boolean){ val mapboxIdPref = findPreference(PREF_MAPBOX_ID) mapboxIdPref?.let { val summary = if (TextUtils.isEmpty(id)) { enableTileProvider(GOOGLE_TILE_PROVIDER, true) getString(R.string.pref_hint_mapbox_id) } else id mapboxIdPref.summary = summary } if(persist) setMapboxId(getContext(), id) } private fun updateMapboxAccessToken(token: String, persist: Boolean){ val mapboxTokenPref = findPreference(PREF_MAPBOX_ACCESS_TOKEN) if(mapboxTokenPref != null) { val summary = if (TextUtils.isEmpty(token)) { enableTileProvider(GOOGLE_TILE_PROVIDER, true) getString(R.string.pref_hint_mapbox_access_token) } else token mapboxTokenPref.summary = summary } if(persist) setMapboxAccessToken(getContext(), token) } private fun toggleTileProviderPrefs(tileProvider: String){ when(tileProvider){ GoogleMapPrefConstants.GOOGLE_TILE_PROVIDER -> { enableGoogleTileProviderPrefs(true) enableMapboxTileProviderPrefs(false) } GoogleMapPrefConstants.MAPBOX_TILE_PROVIDER -> { enableGoogleTileProviderPrefs(false) enableMapboxTileProviderPrefs(true) } } } private fun enableGoogleTileProviderPrefs(enable: Boolean){ enableTileProviderPrefs(PREF_GOOGLE_TILE_PROVIDER_SETTINGS, enable) } private fun enableMapboxTileProviderPrefs(enable: Boolean){ enableTileProviderPrefs(PREF_MAPBOX_TILE_PROVIDER_SETTINGS, enable) } private fun enableTileProviderPrefs(prefKey: String, enable: Boolean){ val prefCategory = findPreference(prefKey) as PreferenceCategory? prefCategory?.isEnabled = enable } override fun getMapProvider(): DPMapProvider? = DPMapProvider.GOOGLE_MAP }
gpl-3.0
73daf774d32f96032a2ecd3f9ea970b1
39.162907
154
0.612231
5.192806
false
false
false
false
toastkidjp/Yobidashi_kt
rss/src/main/java/jp/toastkid/rss/suggestion/RssAddingSuggestion.kt
1
2170
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.rss.suggestion import android.view.View import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStoreOwner import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.rss.R import jp.toastkid.rss.extractor.RssUrlValidator import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * @author toastkidjp */ class RssAddingSuggestion( private val preferenceApplier: PreferenceApplier, private val rssUrlValidator: RssUrlValidator = RssUrlValidator(), private val contentViewModelFactory: (ViewModelStoreOwner) -> ContentViewModel? = { ViewModelProvider(it).get(ContentViewModel::class.java) }, private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main, private val backgroundDispatcher: CoroutineDispatcher = Dispatchers.Default ) { operator fun invoke(view: View, url: String) { CoroutineScope(mainDispatcher).launch { val shouldShow = withContext(backgroundDispatcher) { shouldShow(url) } if (!shouldShow) { return@launch } toast(view, url) } } private fun toast(view: View, url: String) { (view.context as? ViewModelStoreOwner)?.let { contentViewModelFactory(it) ?.snackWithAction( view.context.getString(R.string.message_add_rss_target), view.context.getString(R.string.add) ) { preferenceApplier.saveNewRssReaderTargets(url) } } } private fun shouldShow(url: String) = rssUrlValidator.invoke(url) && !preferenceApplier.containsRssTarget(url) }
epl-1.0
dd8f9262c26d04020dbd66b7728755ee
35.183333
88
0.71106
4.876404
false
false
false
false
juanjcsr/FreeOTP
app/src/main/java/org/juanjcsr/newcloudotp/external/DropboxFileSearchTask.kt
1
2474
package org.juanjcsr.newcloudotp.external import android.os.AsyncTask import android.util.Log import com.dropbox.core.DbxException import com.dropbox.core.v2.DbxClientV2 import com.dropbox.core.v2.files.SearchResult /** * Created by jezz on 22/06/16. */ class DropboxFileSearchTask(private val dbxClientV2: DbxClientV2, private val delegate: DropboxFileSearchTask.DropboxFileTasksDelegate) : AsyncTask<String, Void, SearchResult>() { private var error: Exception? = null override fun doInBackground(vararg filename: String): SearchResult? { val file = filename[0] try { //Log.d("DB","OBTENIENDO...."); return dbxClientV2.files().search("", file) //Download } catch (ex: DbxException) { ex.printStackTrace() error = ex } return null } override fun onPostExecute(list: SearchResult) { super.onPostExecute(list) var e = error if (e == null) { delegate.onListResultsReceived(list) } else { delegate.onError(e) } } /*@Override protected File doInBackground(FileMetadata... fileMetadatas) { FileMetadata metadata = fileMetadatas[0]; try { File path = Environment.getDataDirectory(); File file = new File(path, metadata.getName()); if (!path.exists()) { if (!path.mkdirs()) { error = new RuntimeException("Cant create dir: " + path); } } else if (!path.isDirectory()) { error = new IllegalStateException("Downloadpath is not directory: " + path ); return null; } OutputStream os = new FileOutputStream(file); dbxClientV2.files().download(metadata.getPathLower(), metadata.getRev()) .download(os); return file; } catch (DbxException | IOException ex) { error = ex; } return null; } @Override protected void onPostExecute(File result) { super.onPostExecute(result); if (error == null ) { delegate.onFileDownloaded(result); } else { delegate.onError(error); } }*/ interface DropboxFileTasksDelegate { //void onFileDownloaded(File list); fun onListResultsReceived(list: SearchResult) fun onError(error: Exception?) } }
apache-2.0
5a9127bb6ea85894183a81ca45aea43a
27.767442
179
0.583266
4.564576
false
false
false
false
Vakosta/Chapper
app/src/main/java/org/chapper/chapper/presentation/screen/chat/ChatActivity.kt
1
7880
package org.chapper.chapper.presentation.screen.chat import android.Manifest import android.content.pm.PackageManager import android.content.res.Configuration import android.os.Bundle import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.support.v7.app.AppCompatDelegate import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.text.Editable import android.text.TextWatcher import android.view.View import android.widget.EditText import android.widget.ImageButton import android.widget.TextView import com.wang.avi.AVLoadingIndicatorView import de.hdodenhof.circleimageview.CircleImageView import kotterknife.bindView import org.chapper.chapper.R import org.chapper.chapper.data.Constants import org.chapper.chapper.data.model.Message import org.chapper.chapper.data.repository.ChatRepository import org.chapper.chapper.data.repository.ImageRepository import org.chapper.chapper.data.repository.MessageRepository import org.chapper.chapper.domain.usecase.BluetoothUseCase import org.jetbrains.anko.* import kotlin.properties.Delegates class ChatActivity : AppCompatActivity(), ChatView { override var isForeground: Boolean = false private var mPresenter: ChatPresenter by Delegates.notNull() private val mToolbar: Toolbar by bindView(R.id.toolbar) private val mTypingAnimation: AVLoadingIndicatorView by bindView(R.id.typing_animation) private val mChatName: TextView by bindView(R.id.chatName) private val mChatStatus: TextView by bindView(R.id.chatStatus) private val mChatPhotoChars: TextView by bindView(R.id.profile_image_chars) private val mChatPhoto: CircleImageView by bindView(R.id.profile_image) private val mRecyclerView: RecyclerView by bindView(R.id.recyclerView) private var mAdapter: ChatAdapter by Delegates.notNull() private val mSendButton: ImageButton by bindView(R.id.sendButton) private val mMessageEditText: EditText by bindView(R.id.messageEditText) private val mRefresher: AVLoadingIndicatorView by bindView(R.id.connecting_animation) companion object { init { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_chat) mPresenter = ChatPresenter(this) if (this.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) { window.setBackgroundDrawableResource(R.drawable.background) } else { window.setBackgroundDrawableResource(R.drawable.background_land) } mPresenter.init(applicationContext, intent) mSendButton.setOnClickListener { sendMessage() } mMessageEditText.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(p0: Editable?) {} override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { if (p0 != null && p0.isNotEmpty()) BluetoothUseCase.sendTyping() } }) } override fun onResume() { super.onResume() isForeground = true mPresenter.resume(applicationContext) } override fun onPause() { super.onPause() isForeground = false } override fun initToolbar() { setSupportActionBar(mToolbar) mChatName.text = ChatRepository.getName(mPresenter.mChat) mChatPhotoChars.text = ChatRepository.getFirstCharsName(mPresenter.mChat) val photo = ImageRepository.getImage(applicationContext, mPresenter.mChatId) if (photo != null) mChatPhoto.setImageBitmap(photo) mToolbar.navigationIcon = ContextCompat.getDrawable(this, R.drawable.arrow_left) mToolbar.setNavigationOnClickListener { finish() } } override fun showMessages() { mRecyclerView.setHasFixedSize(false) val layout = LinearLayoutManager(this) layout.stackFromEnd = true mRecyclerView.layoutManager = layout mAdapter = ChatAdapter(MessageRepository .getMessages(intent .getStringExtra(Constants.CHAT_ID_EXTRA)), object : ChatAdapter.OnItemClickListener { override fun onItemClick(message: Message) { val actions = listOf(getString(R.string.delete)) selector(getString(R.string.select_action), actions, { _, i -> when (i) { 0 -> { alert(getString(R.string.are_you_sure)) { yesButton { doAsync { message.delete() } } noButton {} }.show() } } }) } }) mRecyclerView.adapter = mAdapter } override fun changeMessageList() { runOnUiThread { val messages = MessageRepository.getMessages(mPresenter.mChatId) mAdapter.changeDataSet(messages) mRecyclerView.smoothScrollToPosition(messages.size - 1) } } override fun sendMessage() { if (isCoarseLocationPermissionDenied()) { requestCoarseLocationPermission() return } mPresenter.sendMessage(mMessageEditText.text.toString()) mMessageEditText.setText("") } override fun onDestroy() { super.onDestroy() mRecyclerView.adapter = null mPresenter.destroy(applicationContext) } override fun showRefresher() { mRefresher.visibility = View.VISIBLE } override fun hideRefresher() { mRefresher.visibility = View.GONE } override fun startRefreshing() { mTypingAnimation.visibility = View.GONE mPresenter.startDiscovery() } override fun statusTyping() { mTypingAnimation.visibility = View.VISIBLE mChatStatus.text = getString(R.string.typing) } override fun statusConnected() { mTypingAnimation.visibility = View.GONE mChatStatus.text = getString(R.string.connected) } override fun statusNearby() { mTypingAnimation.visibility = View.GONE mChatStatus.text = getString(R.string.nearby) } override fun statusOffline() { mTypingAnimation.visibility = View.GONE mChatStatus.text = mPresenter.mChat.getLastConnectionString(applicationContext) } override fun isCoarseLocationPermissionDenied(): Boolean { val status = ActivityCompat.checkSelfPermission(applicationContext, Manifest.permission.ACCESS_COARSE_LOCATION) return status == PackageManager.PERMISSION_DENIED } override fun requestCoarseLocationPermission() { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), Constants.COARSE_LOCATION_PERMISSIONS) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { when (requestCode) { Constants.COARSE_LOCATION_PERMISSIONS -> { if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { sendMessage() } else { toast(resources.getString(R.string.error)) } } } } }
gpl-2.0
064fc9f9555901d4e21c44bcfb7df170
34.178571
119
0.661548
5.070785
false
false
false
false
http4k/http4k
http4k-core/src/test/kotlin/org/http4k/lens/BiDiLensSpecTest.kt
1
8951
package org.http4k.lens import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.throws import org.http4k.base64Encode import org.http4k.core.Method import org.http4k.core.Uri import org.http4k.lens.BiDiLensContract.checkContract import org.http4k.lens.ParamMeta.StringParam import org.junit.jupiter.api.Test import java.math.BigDecimal import java.math.BigInteger import java.time.Duration import java.time.Instant import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime import java.time.YearMonth import java.time.ZoneId import java.time.ZoneOffset import java.time.ZonedDateTime import java.util.Locale import java.util.UUID class BiDiLensSpecTest { data class Container(val s: String?) private val spec = BiDiLensSpec("location", StringParam, LensGet { _: String, str: String -> if (str.isBlank()) emptyList() else listOf(str) }, LensSet { _: String, values: List<String>, str: String -> values.fold(str) { memo, next -> memo + next } }) private val oSpec = BiDiLensSpec("location", StringParam, LensGet { _: String, (s) -> s?.let(::listOf) ?: emptyList() }, LensSet { _: String, values: List<String>, str: Container -> values.fold(str) { (value), next -> Container(value + next) } }) @Test fun nonEmptyString() = checkContract( oSpec.nonEmptyString(), "123", Container("123"), Container(null), Container(""), Container("o"), Container("o123"), Container("o123123") ) @Test fun int() = checkContract(spec.int(), 123, "123", "", "invalid", "o", "o123", "o123123") @Test fun long() = checkContract(spec.long(), 123, "123", "", "invalid", "o", "o123", "o123123") @Test fun float() = checkContract(spec.float(), 123f, "123.0", "", "invalid", "o", "o123.0", "o123.0123.0") @Test fun double() = checkContract(spec.double(), 123.0, "123.0", "", "invalid", "o", "o123.0", "o123.0123.0") @Test fun bigDecimal() = checkContract(spec.bigDecimal(), BigDecimal("123.0"), "123.0", "", "invalid", "o", "o123.0", "o123.0123.0") @Test fun base64() { checkContract( spec.base64(), "unencoded", "unencoded".base64Encode(), "", "hello", "unencoded", "unencodeddW5lbmNvZGVk", "unencodeddW5lbmNvZGVkdW5lbmNvZGVk" ) } @Test fun bigInteger() = checkContract(spec.bigInteger(), BigInteger("123"), "123", "", "invalid", "o", "o123", "o123123") @Test fun `local date`() = checkContract( spec.localDate(), LocalDate.of(2001, 1, 1), "2001-01-01", "", "123", "o", "o2001-01-01", "o2001-01-012001-01-01" ) @Test fun `local time`() = checkContract( spec.localTime(), LocalTime.of(1, 1, 1), "01:01:01", "", "123", "o", "o01:01:01", "o01:01:0101:01:01" ) @Test fun `offset time`() = checkContract( spec.offsetTime(), OffsetTime.of(1, 1, 1, 0, ZoneOffset.UTC), "01:01:01Z", "", "123", "o", "o01:01:01Z", "o01:01:01Z01:01:01Z" ) @Test fun `offset date time`() = checkContract( spec.offsetDateTime(), OffsetDateTime.of(LocalDate.of(2001, 1, 1), LocalTime.of(1, 1, 1), ZoneOffset.UTC), "2001-01-01T01:01:01Z", "", "123", "o", "o2001-01-01T01:01:01Z", "o2001-01-01T01:01:01Z2001-01-01T01:01:01Z" ) @Test fun uuid() = checkContract( spec.uuid(), UUID.fromString("f5fc0a3f-ecb5-4ab3-bc75-185165dc4844"), "f5fc0a3f-ecb5-4ab3-bc75-185165dc4844", "", "123", "o", "of5fc0a3f-ecb5-4ab3-bc75-185165dc4844", "of5fc0a3f-ecb5-4ab3-bc75-185165dc4844f5fc0a3f-ecb5-4ab3-bc75-185165dc4844" ) @Test fun regex() { val requiredLens = spec.regex("v(\\d+)", 1).required("hello") assertThat(requiredLens("v123"), equalTo("123")) assertThat((spec.regex("v(\\d+)", 1).map(String::toInt).required("hello"))("v123"), equalTo(123)) assertThat( { requiredLens("hello") }, throws(lensFailureWith<String>(Invalid(requiredLens.meta), overallType = Failure.Type.Invalid)) ) } @Test fun boolean() { checkContract(spec.boolean(), true, "true", "", "123", "o", "otrue", "otruetrue") checkContract(spec.boolean(), false, "false", "", "123", "o", "ofalse", "ofalsefalse") } @Test fun datetime() = checkContract( spec.dateTime(), LocalDateTime.of(2001, 1, 1, 2, 3, 4), "2001-01-01T02:03:04", "", "123", "o", "o2001-01-01T02:03:04", "o2001-01-01T02:03:042001-01-01T02:03:04" ) @Test fun instant() = checkContract( spec.instant(), Instant.EPOCH, "1970-01-01T00:00:00Z", "", "123", "o", "o1970-01-01T00:00:00Z", "o1970-01-01T00:00:00Z1970-01-01T00:00:00Z" ) @Test fun `zoned datetime`() = checkContract( spec.zonedDateTime(), ZonedDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneId.of("UTC")), "1970-01-01T00:00:00Z[UTC]", "", "123", "o", "o1970-01-01T00:00:00Z[UTC]", "o1970-01-01T00:00:00Z[UTC]1970-01-01T00:00:00Z[UTC]" ) @Test fun duration() = checkContract(spec.duration(), Duration.ofSeconds(35), "PT35S", "", "notathing", "o", "oPT35S", "oPT35SPT35S") @Test fun zoneId() = checkContract( spec.zoneId(), ZoneId.of("America/Toronto"), "America/Toronto", "", "Nowhere", "o", "oAmerica/Toronto", "oAmerica/TorontoAmerica/Toronto" ) @Test fun zoneOffset() = checkContract( spec.zoneOffset(), ZoneOffset.of("-04:00"), "-04:00", "", "America/Toronto", "o", "o-04:00", "o-04:00-04:00" ) @Test fun uri() = checkContract( spec.uri(), Uri.of("http://localhost"), "http://localhost", "", null, "o", "ohttp://localhost", "ohttp://localhosthttp://localhost" ) @Test fun yearMonth() = checkContract( spec.yearMonth(), YearMonth.of(2000, 2), "2000-02", "", "invalid", "o", "o2000-02", "o2000-022000-02" ) @Test fun enum() = checkContract(spec.enum(), Method.DELETE, "DELETE", "", "invalid", "o", "oDELETE", "oDELETEDELETE") @Test fun value() { checkContract(spec.value(MyInt), MyInt.of(123), "123", "", "invalid", "o", "o123", "o123123") checkContract( spec.value(MyUUID), MyUUID.of(UUID(0, 0)), UUID(0, 0).toString(), "", "invalid", "o", "o" + UUID(0, 0).toString(), "o" + UUID(0, 0).toString() + UUID(0, 0).toString() ) checkContract(spec.value(MyString), MyString.of("f"), "f", "", "invalid", "o", "of", "off") } @Test fun bytes() { val requiredLens = spec.bytes().required("hello") assertThat(String(requiredLens("123")), equalTo("123")) assertThat( { requiredLens("") }, throws(lensFailureWith<String>(Missing(requiredLens.meta), overallType = Failure.Type.Missing)) ) } @Test fun locale() = checkContract( spec.locale(), Locale.CANADA, "en-CA", "", "en_CA", // java cannot parse ISO language codes "o", "oen-CA", "oen-CAen-CA" ) @Test fun `can composite object from several sources and decompose it again`() { data class CompositeObject(val number: Int, val string: String?) val lens = spec.composite( { CompositeObject(int().required("")(it), required("")(it)) }, { it + number + string } ) val expected = CompositeObject(123, "123") assertThat(lens("123"), equalTo(expected)) assertThat(lens(expected, "prefix"), equalTo("prefix123123")) } @Test fun csv() = checkContract( spec.csv(), listOf("foo", "bar", "", "baz"), "foo,bar,,baz", "", null, "bang", "bangfoo,bar,,baz", "bangfoo,bar,,bazfoo,bar,,baz" ) @Test fun `csv - custom`() = checkContract( spec.csv(";", StringBiDiMappings.int()), listOf(0, 1, 2), "0;1;2", "", "foo;bar;baz", "-1", "-10;1;2", "-10;1;20;1;2" ) }
apache-2.0
49f2eea7949301b9c4285182d6bfb077
26.206687
133
0.534242
3.416412
false
true
false
false
xiaopansky/AssemblyAdapter
sample/src/main/java/me/panpf/adapter/sample/ui/RecyclerPagedSampleFragment.kt
1
2251
package me.panpf.adapter.sample.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.fm_recycler.* import me.panpf.adapter.paged.AssemblyPagedListAdapter import me.panpf.adapter.paged.DiffableDiffCallback import me.panpf.adapter.sample.R import me.panpf.adapter.sample.item.GameItem import me.panpf.adapter.sample.item.HeaderItem import me.panpf.adapter.sample.item.LoadMoreItem import me.panpf.adapter.sample.item.UserItem import me.panpf.adapter.sample.vm.End import me.panpf.adapter.sample.vm.ListViewModel import me.panpf.arch.ktx.bindViewModel class RecyclerPagedSampleFragment : BaseFragment() { private val viewModel by bindViewModel(ListViewModel::class) private val adapter = AssemblyPagedListAdapter<Any>(DiffableDiffCallback()).apply { addHeaderItem(HeaderItem.Factory(), "我是小额头呀!") addItemFactory(UserItem.Factory()) addItemFactory(GameItem.Factory()) addFooterItem(HeaderItem.Factory(), "我是小尾巴呀!") setMoreItem(LoadMoreItem.Factory()) } override fun onUserVisibleChanged(isVisibleToUser: Boolean) { val attachActivity = activity if (isVisibleToUser && attachActivity is AppCompatActivity) { attachActivity.supportActionBar?.subtitle = "Recycler - PagedList" } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fm_recycler, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recyclerFm_recycler.layoutManager = LinearLayoutManager(activity) recyclerFm_recycler.adapter = adapter viewModel.list.observe(this, androidx.lifecycle.Observer { adapter.submitList(it) }) viewModel.listStatus.observe(this, Observer { when (it) { is End -> adapter.loadMoreFinished(true) } }) } }
apache-2.0
ec82fbbe053e276a2d2fc0e8f4b4c6b9
38.017544
116
0.747188
4.446
false
false
false
false
b95505017/android-architecture-components
PagingWithNetworkSample/app/src/main/java/com/android/example/paging/pagingwithnetwork/reddit/repository/inMemory/byPage/InMemoryByPageKeyRepository.kt
1
2706
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.example.paging.pagingwithnetwork.reddit.repository.inMemory.byPage import android.arch.lifecycle.Transformations import android.arch.paging.LivePagedListBuilder import android.support.annotation.MainThread import com.android.example.paging.pagingwithnetwork.reddit.api.RedditApi import com.android.example.paging.pagingwithnetwork.reddit.repository.Listing import com.android.example.paging.pagingwithnetwork.reddit.repository.RedditPostRepository import com.android.example.paging.pagingwithnetwork.reddit.vo.RedditPost import java.util.concurrent.Executor /** * Repository implementation that returns a Listing that loads data directly from network by using * the previous / next page keys returned in the query. */ class InMemoryByPageKeyRepository(private val redditApi: RedditApi, private val networkExecutor: Executor) : RedditPostRepository { @MainThread override fun postsOfSubreddit(subredditName: String, pageSize: Int): Listing<RedditPost> { val sourceFactory = SubRedditDataSourceFactory(redditApi, subredditName, networkExecutor) val livePagedList = LivePagedListBuilder(sourceFactory, pageSize) // provide custom executor for network requests, otherwise it will default to // Arch Components' IO pool which is also used for disk access .setBackgroundThreadExecutor(networkExecutor) .build() val refreshState = Transformations.switchMap(sourceFactory.sourceLiveData) { it.initialLoad } return Listing( pagedList = livePagedList, networkState = Transformations.switchMap(sourceFactory.sourceLiveData, { it.networkState }), retry = { sourceFactory.sourceLiveData.value?.retryAllFailed() }, refresh = { sourceFactory.sourceLiveData.value?.invalidate() }, refreshState = refreshState ) } }
apache-2.0
9f1952ec30dfce625a0d8193994cb8d1
42.645161
98
0.701404
5.125
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/widget/WidgetStatus.kt
1
5240
/*************************************************************************************** * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.widget import android.content.Context import com.ichi2.anki.AnkiDroidApp import com.ichi2.anki.CollectionHelper import com.ichi2.anki.MetaDB import com.ichi2.anki.preferences.Preferences import com.ichi2.async.BaseAsyncTask import com.ichi2.libanki.sched.Counts import com.ichi2.utils.KotlinCleanup import com.ichi2.widget.AnkiDroidWidgetSmall.UpdateService import timber.log.Timber /** * The status of the widget. */ object WidgetStatus { private var sSmallWidgetEnabled = false @Suppress("deprecation") // #7108: AsyncTask private var sUpdateDeckStatusAsyncTask: android.os.AsyncTask<Context?, Void?, Context?>? = null /** * Request the widget to update its status. * TODO Mike - we can reduce battery usage by widget users by removing updatePeriodMillis from metadata * and replacing it with an alarm we set so device doesn't wake to update the widget, see: * https://developer.android.com/guide/topics/appwidgets/#MetaData */ @Suppress("deprecation") // #7108: AsyncTask fun update(context: Context?) { val preferences = AnkiDroidApp.getSharedPrefs(context) sSmallWidgetEnabled = preferences.getBoolean("widgetSmallEnabled", false) val notificationEnabled = preferences.getString(Preferences.MINIMUM_CARDS_DUE_FOR_NOTIFICATION, "1000001")!!.toInt() < 1000000 val canExecuteTask = sUpdateDeckStatusAsyncTask == null || sUpdateDeckStatusAsyncTask!!.status == android.os.AsyncTask.Status.FINISHED if ((sSmallWidgetEnabled || notificationEnabled) && canExecuteTask) { Timber.d("WidgetStatus.update(): updating") sUpdateDeckStatusAsyncTask = UpdateDeckStatusAsyncTask() sUpdateDeckStatusAsyncTask!!.execute(context) } else { Timber.d("WidgetStatus.update(): already running or not enabled") } } /** Returns the status of each of the decks. */ fun fetchSmall(context: Context): IntArray { return MetaDB.getWidgetSmallStatus(context) } fun fetchDue(context: Context): Int { return MetaDB.getNotificationStatus(context) } private class UpdateDeckStatusAsyncTask : BaseAsyncTask<Context?, Void?, Context?>() { @Suppress("deprecation") // #7108: AsyncTask override fun doInBackground(vararg arg0: Context?): Context? { super.doInBackground(*arg0) Timber.d("WidgetStatus.UpdateDeckStatusAsyncTask.doInBackground()") val context = arg0[0] if (!AnkiDroidApp.isSdCardMounted) { return context } try { updateCounts(context!!) } catch (e: Exception) { Timber.e(e, "Could not update widget") } return context } @Suppress("deprecation") // #7108: AsyncTask @KotlinCleanup("make result non-null") override fun onPostExecute(result: Context?) { super.onPostExecute(result) Timber.d("WidgetStatus.UpdateDeckStatusAsyncTask.onPostExecute()") MetaDB.storeSmallWidgetStatus(result!!, sSmallWidgetStatus) if (sSmallWidgetEnabled) { UpdateService().doUpdate(result) } (result.applicationContext as? AnkiDroidApp)?.scheduleNotification() } private fun updateCounts(context: Context) { val total = Counts() val col = CollectionHelper.instance.getCol(context)!! // Only count the top-level decks in the total val nodes = col.sched.deckDueTree().map { it.value } for (node in nodes) { total.addNew(node.newCount) total.addLrn(node.lrnCount) total.addRev(node.revCount) } val eta = col.sched.eta(total, false) sSmallWidgetStatus = Pair(total.count(), eta) } companion object { // due, eta private var sSmallWidgetStatus = Pair(0, 0) } } }
gpl-3.0
d9b97afde60df22c4580b4281dab68ff
44.172414
142
0.592176
4.924812
false
false
false
false
pdvrieze/ProcessManager
PE-common/src/jvmMain/kotlin/nl/adaptivity/util/activation/SourceDataSource.kt
1
1437
/* * 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.util.activation import java.io.IOException import java.io.InputStream import java.io.OutputStream import javax.activation.DataSource import javax.xml.transform.Source class SourceDataSource @JvmOverloads constructor( private val contentType: String, private val content: Source, private val name: String? = null ) : DataSource { override fun getContentType() = contentType @Throws(IOException::class) override fun getInputStream(): InputStream = content.toInputStream() override fun getName() = name @Throws(IOException::class) override fun getOutputStream(): OutputStream = throw UnsupportedOperationException("Can not write to sources") }
lgpl-3.0
d799c9823d43065add8bfa04ff1ffc62
33.214286
114
0.732777
4.80602
false
false
false
false
ebraminio/DroidPersianCalendar
PersianCalendar/src/main/java/com/byagowi/persiancalendar/service/ApplicationService.kt
1
1753
package com.byagowi.persiancalendar.service import android.app.Service import android.content.Intent import android.content.IntentFilter import android.os.IBinder import android.util.Log import com.byagowi.persiancalendar.utils.loadApp import com.byagowi.persiancalendar.utils.update import com.byagowi.persiancalendar.utils.updateStoredPreference import java.lang.ref.WeakReference /** * The Calendar Service that updates widget time and clock and build/update * calendar notification. */ class ApplicationService : Service() { private val receiver = BroadcastReceivers() override fun onBind(paramIntent: Intent?): IBinder? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { instance = WeakReference(this) Log.d(ApplicationService::class.java.name, "start") val intentFilter = IntentFilter().apply { addAction(Intent.ACTION_DATE_CHANGED) addAction(Intent.ACTION_TIMEZONE_CHANGED) addAction(Intent.ACTION_TIME_CHANGED) addAction(Intent.ACTION_SCREEN_ON) // addAction(Intent.ACTION_TIME_TICK) } registerReceiver(receiver, intentFilter) updateStoredPreference(applicationContext) loadApp(this) update(applicationContext, true) return START_STICKY } override fun onDestroy() { try { unregisterReceiver(receiver) } catch (e: Exception) { // Really can't do much here e.printStackTrace() } super.onDestroy() } companion object { private var instance: WeakReference<ApplicationService>? = null fun getInstance(): ApplicationService? = instance?.get() } }
gpl-3.0
0c2413d2b5db9584d7eea7d1096bbb34
28.711864
81
0.682829
4.789617
false
false
false
false
shkschneider/android_Skeleton
core/src/main/kotlin/me/shkschneider/skeleton/ui/transforms/ZoomInTransformer.kt
1
631
package me.shkschneider.skeleton.ui.transforms import android.view.View // <https://github.com/ToxicBakery/ViewPagerTransforms> class ZoomInTransformer : BaseTransformer() { override fun onTransform(page: View, position: Float) { val scale = if (position < 0) position + 1.toFloat() else Math.abs(1.toFloat() - position) page.scaleX = scale page.scaleY = scale page.pivotX = page.width * 0.1.toFloat() page.pivotY = page.height * 0.1.toFloat() page.alpha = if (position < (-1).toFloat() || position > 1.toFloat()) 1.toFloat() else 1.toFloat() - (scale - 1.toFloat()) } }
apache-2.0
ba6f89025a138c60da248e38696d7af5
36.117647
130
0.651347
3.585227
false
false
false
false
xusx1024/AndroidSystemServiceSample
accessibilitymanagersample/src/main/java/com/shunwang/snatchredenvelope/SnatchRedEnvelopeService.kt
1
5381
/* * Copyright (C) 2017 The sxxxxxxxxxu's Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.shunwang.snatchredenvelope import android.accessibilityservice.AccessibilityService import android.accessibilityservice.AccessibilityServiceInfo import android.annotation.TargetApi import android.content.Context import android.content.Intent import android.os.Build import android.util.Log import android.view.accessibility.AccessibilityEvent import android.view.accessibility.AccessibilityManager import android.widget.Toast import com.shunwang.snatchredenvelope.job.AccessbilityJob import com.shunwang.snatchredenvelope.job.WechatAccessbilityJob import java.util.ArrayList import java.util.HashMap /** * Fun: * Created by sxx.xu on 4/21/2017. */ class SnatchRedEnvelopeService : AccessibilityService() { companion object { val TAG: String = "SnatchRedEnvelope" private val ACCESSBILITY_JOBS = arrayOf<Class<*>>(WechatAccessbilityJob::class.java) private var service: SnatchRedEnvelopeService? = null fun handeNotificationPosted(notificationService: IStatusBarNotification) { if (notificationService == null) return if (service == null || service!!.mPkgAccessbilityJobMap == null) { return } var pack: String = notificationService.getPackageName() var job: AccessbilityJob = service!!.mPkgAccessbilityJobMap!!.get(pack!!)!! job.onNotificationPosted(notificationService) } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) fun isRunning(): Boolean { if (service == null) return false var accessibilitymanager: AccessibilityManager = service!!.getSystemService( Context.ACCESSIBILITY_SERVICE) as AccessibilityManager var info: AccessibilityServiceInfo = service!!.serviceInfo if (info == null) return false var list: List<AccessibilityServiceInfo> = accessibilitymanager.getEnabledAccessibilityServiceList( AccessibilityServiceInfo.FEEDBACK_GENERIC) var iterator: Iterator<AccessibilityServiceInfo> = list.iterator() var isConnect: Boolean = false while (iterator.hasNext()) { var i: AccessibilityServiceInfo = iterator.next() if (i.id.equals(info.id)) { isConnect = true break } } return isConnect } fun isNotificationServiceRunning(): Boolean { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { return false } try { return SRENotificationService.isRunning() } catch (e: Exception) { e.printStackTrace() } return false } } private var mAccessbilityJobs: ArrayList<AccessbilityJob>? = null private var mPkgAccessbilityJobMap: HashMap<String, AccessbilityJob>? = null fun getConfig(): Config { return Config.getConfig(this) } override fun onCreate() { super.onCreate() mAccessbilityJobs = ArrayList<AccessbilityJob>() mPkgAccessbilityJobMap = HashMap<String, AccessbilityJob>() for (clazz in ACCESSBILITY_JOBS) { try { val o = clazz.newInstance() if (o is AccessbilityJob) { (o as AccessbilityJob).onCreateJob(this) mAccessbilityJobs!!.add(o) mPkgAccessbilityJobMap!!.put(o.getTargetPackageName(), o) } } catch (e: Exception) { e.printStackTrace() } } } override fun onDestroy() { super.onDestroy() Log.e(TAG, "snatch red envelope destory") if (mPkgAccessbilityJobMap != null) { mPkgAccessbilityJobMap!!.clear() } if (mAccessbilityJobs != null && mAccessbilityJobs!!.isNotEmpty()) { for (job in mAccessbilityJobs!!) { job.onStopJob() } mAccessbilityJobs!!.clear() } service = null mAccessbilityJobs = null mPkgAccessbilityJobMap = null val intent = Intent(Config.ACTION_SANTCH_RED_ENVELOP_SERVICE_DISCONNECT) sendBroadcast(intent) } override fun onInterrupt() { Log.e(TAG, "snatch red envelope service interrupt") Toast.makeText(this, "中断抢红包服务", Toast.LENGTH_SHORT).show() } override fun onServiceConnected() { super.onServiceConnected() service = this sendBroadcast(Intent(Config.ACTION_SANTCH_RED_ENVELOP_SERVICE_CONNECT)) Toast.makeText(this, "已连接抢红包服务", Toast.LENGTH_SHORT).show() } override fun onAccessibilityEvent(event: AccessibilityEvent?) { if (BuildConfig.DEBUG) { Log.d(TAG, "事件--->" + event) } val pkn = event!!.getPackageName().toString() if (mAccessbilityJobs != null && mAccessbilityJobs!!.isNotEmpty()) { if (!getConfig().isAgreement()) return for (job in mAccessbilityJobs!!) { if (pkn.equals(job.getTargetPackageName()) && job.isEnable()) { job.onReceiveJob(event) } } } } }
apache-2.0
c76065aed4c7f9933d2710f8da6f0dd1
30.458824
105
0.69179
4.053829
false
false
false
false
sys1yagi/swipe-android
core/src/main/java/com/sys1yagi/swipe/core/view/SwipeViewPager.kt
1
3715
package com.sys1yagi.swipe.core.view import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.support.v4.view.ViewPager import android.util.AttributeSet import android.view.MotionEvent import android.view.View import com.sys1yagi.swipe.core.entity.swipe.SwipeDocument class SwipeViewPager(context: Context, attrs: AttributeSet) : ViewPager(context, attrs) { internal class Offset(var container: ViewPager) { var x: Int = 0 var y: Int = 0 } internal var scrollOffset = Offset(this) lateinit internal var swipeDocument: SwipeDocument lateinit internal var swipeRenderer: SwipeRenderer init { init() } private fun init() { setPageTransformer(true, VerticalPageTransformer()) overScrollMode = View.OVER_SCROLL_NEVER addOnPageChangeListener(PageChangeListener(scrollOffset)) } fun setSwipeDocument(swipeDocument: SwipeDocument) { this.swipeDocument = swipeDocument swipeRenderer = SwipeRenderer(swipeDocument) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) swipeRenderer.displaySize = Rect(0, 0, w, h) } private fun swapXY(ev: MotionEvent): MotionEvent { val width = width.toFloat() val height = height.toFloat() val newX = ev.y / height * width val newY = ev.x / width * height ev.setLocation(newX, newY) return ev } override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { val intercepted = super.onInterceptTouchEvent(swapXY(ev)) swapXY(ev) return intercepted } override fun onTouchEvent(ev: MotionEvent): Boolean { return super.onTouchEvent(swapXY(ev)) } override fun onDraw(canvas: Canvas) { val clipBounds = canvas.clipBounds canvas.translate(clipBounds.left.toFloat(), clipBounds.top.toFloat()) swipeRenderer.draw(canvas, scrollOffset.x, scrollOffset.y) } internal class PageChangeListener(var scrollOffset: Offset) : ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { val ratio = scrollOffset.container.height.toFloat() / scrollOffset.container.width.toFloat() val offset = position * scrollOffset.container.height + (positionOffsetPixels * ratio).toInt() scrollOffset.x = 0 scrollOffset.y = offset } override fun onPageSelected(position: Int) { } override fun onPageScrollStateChanged(state: Int) { } } internal class VerticalPageTransformer : ViewPager.PageTransformer { override fun transformPage(view: View, position: Float) { if (position < -1) { view.alpha = 0f } else if (position <= 0) { view.alpha = 1f view.translationX = view.width * -position val yPosition = position * view.height view.translationY = yPosition view.scaleX = 1f view.scaleY = 1f } else if (position <= 1) { view.alpha = 1f view.translationX = view.width * -position val scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position)) view.scaleX = scaleFactor view.scaleY = scaleFactor } else { view.alpha = 0f } } companion object { private val MIN_SCALE = 0.75f } } }
mit
34b4a34a4c5160d02753fee56a9a48a6
27.79845
106
0.618035
4.702532
false
false
false
false
V2Ray-Android/Actinium
app/src/main/kotlin/com/v2ray/actinium/ui/PerAppProxyAdapter.kt
1
3011
package com.v2ray.actinium.ui import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import com.v2ray.actinium.R import com.v2ray.actinium.util.AppInfo import kotlinx.android.synthetic.main.item_recycler_bypass_list.view.* import org.jetbrains.anko.image import org.jetbrains.anko.layoutInflater import org.jetbrains.anko.textColor import java.util.* class PerAppProxyAdapter(val apps: List<AppInfo>, blacklist: MutableSet<String>?) : RecyclerView.Adapter<PerAppProxyAdapter.BaseViewHolder>() { companion object { private const val VIEW_TYPE_HEADER = 0 private const val VIEW_TYPE_ITEM = 1 } val blacklist = if (blacklist == null) HashSet<String>() else HashSet<String>(blacklist) override fun onBindViewHolder(holder: BaseViewHolder?, position: Int) { if (holder is AppViewHolder) { val appInfo = apps[position - 1] holder.bind(appInfo) } } override fun getItemCount() = apps.size + 1 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder? { val ctx = parent.context return when (viewType) { VIEW_TYPE_HEADER -> { val view = View(ctx) view.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ctx.resources.getDimensionPixelSize(R.dimen.bypass_list_header_height) * 2) BaseViewHolder(view) } VIEW_TYPE_ITEM -> AppViewHolder(ctx.layoutInflater .inflate(R.layout.item_recycler_bypass_list, parent, false)) else -> null } } override fun getItemViewType(position: Int) = if (position == 0) VIEW_TYPE_HEADER else VIEW_TYPE_ITEM open class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) inner class AppViewHolder(itemView: View) : BaseViewHolder(itemView), View.OnClickListener { private val inBlacklist: Boolean get() = blacklist.contains(appInfo.packageName) private lateinit var appInfo: AppInfo val icon = itemView.icon!! val name = itemView.name!! val checkBox = itemView.check_box!! fun bind(appInfo: AppInfo) { this.appInfo = appInfo icon.image = appInfo.appIcon name.text = appInfo.appName checkBox.isChecked = inBlacklist name.textColor = itemView.context.resources.getColor(if (appInfo.isSystemApp) R.color.color_highlight_material else R.color.abc_secondary_text_material_light) itemView.setOnClickListener(this) } override fun onClick(v: View?) { if (inBlacklist) { blacklist.remove(appInfo.packageName) checkBox.isChecked = false } else { blacklist.add(appInfo.packageName) checkBox.isChecked = true } } } }
gpl-3.0
ee885a38d527a2f5a1278a42d1de0d36
32.842697
99
0.639655
4.632308
false
false
false
false
ageery/kwicket
kwicket-wicket-core/src/main/kotlin/org/kwicket/wicket/core/markup/html/link/KPopupSettings.kt
1
520
package org.kwicket.wicket.core.markup.html.link import org.apache.wicket.markup.html.link.PopupSettings class KPopupSettings( target: String? = null, height: Int? = null, left: Int? = null, width: Int? = null, windowName: String? = null, displayFlags: Int? = null ) : PopupSettings(windowName, displayFlags?.let { it } ?: 0) { init { target?.let { setTarget(it) } height?.let { setHeight(it) } left?.let { setLeft(it) } width?.let { setWidth(it) } } }
apache-2.0
09df106d4d0da5d04270ded2e1b4c6cf
23.809524
62
0.611538
3.312102
false
false
false
false
FHannes/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/JetBrainsAccountDialog.kt
7
2906
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic import com.intellij.CommonBundle import com.intellij.credentialStore.CredentialAttributes import com.intellij.credentialStore.Credentials import com.intellij.ide.BrowserUtil import com.intellij.ide.passwordSafe.PasswordSafe import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.components.CheckBox import com.intellij.ui.components.dialog import com.intellij.ui.layout.* import com.intellij.util.io.encodeUrlQueryParameter import java.awt.Component import javax.swing.JPasswordField import javax.swing.JTextField @JvmOverloads fun showJetBrainsAccountDialog(parent: Component, project: Project? = null): DialogWrapper { val credentials = ErrorReportConfigurable.getCredentials() val userField = JTextField(credentials?.userName) val passwordField = JPasswordField(credentials?.password?.toString()) // if no user name - never stored and so, defaults to remember. if user name set, but no password, so, previously was stored without password val rememberCheckBox = CheckBox(CommonBundle.message("checkbox.remember.password"), selected = credentials?.userName == null || !credentials?.password.isNullOrEmpty()) val panel = panel { noteRow("Login to JetBrains Account to get notified when the submitted\nexceptions are fixed.") row("Username:") { userField() } row("Password:") { passwordField() } row { rememberCheckBox() right { link("Forgot password?") { BrowserUtil.browse("https://account.jetbrains.com/forgot-password?username=${userField.text.trim().encodeUrlQueryParameter()}") } } } noteRow("""Do not have an account? <a href="https://account.jetbrains.com/login?signup">Sign Up</a>""") } return dialog( title = DiagnosticBundle.message("error.report.title"), panel = panel, focusedComponent = if (credentials?.userName == null) userField else passwordField, project = project, parent = if (parent.isShowing) parent else null) { val userName = userField.text if (!userName.isNullOrBlank()) { PasswordSafe.getInstance().set(CredentialAttributes(ErrorReportConfigurable.SERVICE_NAME, userName), Credentials(userName, if (rememberCheckBox.isSelected) passwordField.password else null)) } } }
apache-2.0
059b8b02d7bdb3db2c376101f8771a54
43.045455
196
0.75499
4.436641
false
false
false
false
Devexperts/usages
server/src/main/kotlin/com/devexperts/usages/server/config/Configuration.kt
1
1610
/** * Copyright (C) 2017 Devexperts LLC * * 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/gpl-3.0.html>. */ package com.devexperts.usages.server.config import org.aeonbits.owner.Config import org.aeonbits.owner.ConfigFactory import java.io.File @Config.Sources("classpath:usages.properties") interface PropertiesConfiguration : Config { @Config.Key("usages.workDir") @Config.DefaultValue("~/.usages") fun workDir(): String } private val configuration = ConfigFactory.create(PropertiesConfiguration::class.java, System.getProperties()) object Configuration { val workDir = resolvePath(configuration.workDir()) val settingsFile = workDirFile("settings.xml") val dbFile = workDirFile("usages_db") private fun resolvePath(file: String): String { var f = file if (f.startsWith('~')) f = System.getProperty("user.home") + f.substring(1) return f } } private fun workDirFile(file: String) = Configuration.workDir + File.separator + file
gpl-3.0
ecd2f9c15e22a07b5069cfbe6662bb0e
30.568627
109
0.723602
4.107143
false
true
false
false
TeamAmaze/AmazeFileManager
app/src/main/java/com/amaze/filemanager/ui/drag/RecyclerAdapterDragListener.kt
1
12386
/* * Copyright (C) 2014-2021 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.ui.drag import android.util.Log import android.view.DragEvent import android.view.View import androidx.recyclerview.widget.RecyclerView import com.amaze.filemanager.adapters.RecyclerAdapter import com.amaze.filemanager.adapters.data.LayoutElementParcelable import com.amaze.filemanager.adapters.holders.ItemViewHolder import com.amaze.filemanager.filesystem.HybridFile import com.amaze.filemanager.filesystem.HybridFileParcelable import com.amaze.filemanager.ui.dialogs.DragAndDropDialog import com.amaze.filemanager.ui.fragments.MainFragment import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants import com.amaze.filemanager.utils.DataUtils import com.amaze.filemanager.utils.safeLet import kotlin.collections.ArrayList class RecyclerAdapterDragListener( private val adapter: RecyclerAdapter, private val holder: ItemViewHolder?, private val dragAndDropPref: Int, private val mainFragment: MainFragment ) : View.OnDragListener { private val TAG = javaClass.simpleName override fun onDrag(p0: View?, p1: DragEvent?): Boolean { return when (p1?.action) { DragEvent.ACTION_DRAG_ENDED -> { Log.d(TAG, "ENDING DRAG, DISABLE CORNERS") mainFragment.requireMainActivity().initCornersDragListener( true, dragAndDropPref != PreferencesConstants.PREFERENCE_DRAG_TO_SELECT ) if (dragAndDropPref != PreferencesConstants.PREFERENCE_DRAG_TO_SELECT ) { val dataUtils = DataUtils.getInstance() dataUtils.checkedItemsList = null mainFragment.requireMainActivity() .tabFragment.dragPlaceholder?.visibility = View.INVISIBLE } true } DragEvent.ACTION_DRAG_ENTERED -> { safeLet(holder, adapter.itemsDigested) { holder, itemsDigested -> if (itemsDigested.size != 0 && holder.adapterPosition < itemsDigested.size ) { val listItem = (itemsDigested[holder.adapterPosition]) if (dragAndDropPref == PreferencesConstants.PREFERENCE_DRAG_TO_SELECT) { if (listItem.specialType != RecyclerAdapter.TYPE_BACK && listItem.shouldToggleDragChecked ) { listItem.toggleShouldToggleDragChecked() adapter.toggleChecked( holder.adapterPosition, if (mainFragment.mainFragmentViewModel?.isList == true) { holder.checkImageView } else { holder.checkImageViewGrid } ) } } else { val currentElement = listItem.layoutElementParcelable if (currentElement != null && currentElement.isDirectory && listItem.specialType != RecyclerAdapter.TYPE_BACK ) { holder.baseItemView.isSelected = true } } } } true } DragEvent.ACTION_DRAG_EXITED -> { safeLet(holder, adapter.itemsDigested) { holder, itemsDigested -> if (itemsDigested.size != 0 && holder.adapterPosition < itemsDigested.size ) { if (dragAndDropPref != PreferencesConstants.PREFERENCE_DRAG_TO_SELECT) { val listItem = itemsDigested[holder.adapterPosition] if (listItem.specialTypeHasFile() && listItem.specialType != RecyclerAdapter.TYPE_BACK ) { val currentElement = listItem.requireLayoutElementParcelable() if (currentElement.isDirectory && !adapter.checkedItems.contains(currentElement) ) { holder.baseItemView.run { isSelected = false isFocusable = false isFocusableInTouchMode = false clearFocus() } } } } } } true } DragEvent.ACTION_DRAG_STARTED -> { return true } DragEvent.ACTION_DRAG_LOCATION -> { holder?.run { if (dragAndDropPref != PreferencesConstants.PREFERENCE_DRAG_TO_SELECT) { holder.baseItemView.run { isFocusable = true isFocusableInTouchMode = true requestFocus() } } } true } DragEvent.ACTION_DROP -> { if (dragAndDropPref != PreferencesConstants.PREFERENCE_DRAG_TO_SELECT) { var checkedItems: ArrayList<LayoutElementParcelable>? = adapter.checkedItems var currentFileParcelable: HybridFileParcelable? = null var isCurrentElementDirectory: Boolean? = null var isEmptyArea: Boolean? = null var pasteLocation: String? = if (adapter.itemsDigested?.size == 0) { mainFragment.currentPath } else { if (holder == null || holder.adapterPosition == RecyclerView.NO_POSITION) { Log.d(TAG, "Trying to drop into empty area") isEmptyArea = true mainFragment.currentPath } else { adapter.itemsDigested?.let { itemsDigested -> if (itemsDigested[holder.adapterPosition].specialType == RecyclerAdapter.TYPE_BACK ) { // dropping in goback button // hack to get the parent path val hybridFileParcelable = mainFragment .elementsList!![1].generateBaseFile() val hybridFile = HybridFile( hybridFileParcelable.mode, hybridFileParcelable.getParent(mainFragment.context) ) hybridFile.getParent(mainFragment.context) } else { val currentElement = itemsDigested[holder.adapterPosition] .layoutElementParcelable currentFileParcelable = currentElement?.generateBaseFile() isCurrentElementDirectory = currentElement?.isDirectory currentElement?.desc } } } } if (checkedItems?.size == 0) { // probably because we switched tabs and // this adapter doesn't have any checked items, get from data utils val dataUtils = DataUtils.getInstance() Log.d( TAG, "Didn't find checked items in adapter, " + "checking dataUtils size ${ dataUtils.checkedItemsList?.size ?: "null"}" ) checkedItems = dataUtils.checkedItemsList } val arrayList = ArrayList<HybridFileParcelable>() checkedItems?.forEach { val file = it.generateBaseFile() if (it.desc.equals(pasteLocation) || ( ( isCurrentElementDirectory == false && currentFileParcelable?.getParent(mainFragment.context) .equals(file.getParent(mainFragment.context)) ) || ( isEmptyArea == true && mainFragment.currentPath .equals(file.getParent(mainFragment.context)) ) ) ) { Log.d( TAG, ( "Trying to drop into one of checked items or current " + "location, not allowed ${it.desc}" ) ) holder?.baseItemView?.run { isFocusable = false isFocusableInTouchMode = false clearFocus() } return false } arrayList.add(it.generateBaseFile()) } if (isCurrentElementDirectory == false || isEmptyArea == true) { pasteLocation = mainFragment.currentPath } Log.d( TAG, ( "Trying to drop into one of checked items " + "%s" ).format(pasteLocation) ) DragAndDropDialog.showDialogOrPerformOperation( pasteLocation!!, arrayList, mainFragment.requireMainActivity() ) adapter.toggleChecked(false) holder?.baseItemView?.run { isSelected = false isFocusable = false isFocusableInTouchMode = false clearFocus() } } true } else -> false } } }
gpl-3.0
81b0db43fc1207c6f58143b1fc96a453
47.382813
107
0.447118
6.850664
false
false
false
false
pedroSG94/rtmp-streamer-java
rtmp/src/main/java/com/pedro/rtmp/utils/AuthUtil.kt
2
4249
/* * Copyright (C) 2021 pedroSG94. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pedro.rtmp.utils import android.util.Base64 import java.io.UnsupportedEncodingException import java.security.MessageDigest import java.security.NoSuchAlgorithmException import java.util.* /** * Created by pedro on 27/04/21. */ object AuthUtil { fun getAdobeAuthUserResult(user: String, password: String, salt: String, challenge: String, opaque: String): String { val challenge2 = String.format("%08x", Random().nextInt()) var response = stringToMd5Base64(user + salt + password) if (opaque.isNotEmpty()) { response += opaque } else if (challenge.isNotEmpty()) { response += challenge } response = stringToMd5Base64(response + challenge2) var result = "?authmod=adobe&user=$user&challenge=$challenge2&response=$response" if (opaque.isNotEmpty()) { result += "&opaque=$opaque" } return result } /** * Limelight auth. This auth is closely to Digest auth * http://tools.ietf.org/html/rfc2617 * http://en.wikipedia.org/wiki/Digest_access_authentication * * https://github.com/ossrs/librtmp/blob/feature/srs/librtmp/rtmp.c */ fun getLlnwAuthUserResult(user: String, password: String, nonce: String, app: String): String { val authMod = "llnw" val realm = "live" val method = "publish" val qop = "auth" val ncHex = String.format("%08x", 1) val cNonce = String.format("%08x", Random().nextInt()) var path = app //extract query parameters val queryPos = path.indexOf("?") if (queryPos >= 0) path = path.substring(0, queryPos) if (!path.contains("/")) path += "/_definst_" val hash1 = getMd5Hash("$user:$realm:$password") val hash2 = getMd5Hash("$method:/$path") val hash3 = getMd5Hash("$hash1:$nonce:$ncHex:$cNonce:$qop:$hash2") return "?authmod=$authMod&user=$user&nonce=$nonce&cnonce=$cNonce&nc=$ncHex&response=$hash3" } fun getSalt(description: String): String { var salt = "" val data = description.split("&").toTypedArray() for (s in data) { if (s.contains("salt=")) { salt = s.substring(5) break } } return salt } fun getChallenge(description: String): String { var challenge = "" val data = description.split("&").toTypedArray() for (s in data) { if (s.contains("challenge=")) { challenge = s.substring(10) break } } return challenge } fun getOpaque(description: String): String { var opaque = "" val data = description.split("&").toTypedArray() for (s in data) { if (s.contains("opaque=")) { opaque = s.substring(7) break } } return opaque } fun stringToMd5Base64(s: String): String { try { val md = MessageDigest.getInstance("MD5") md.update(s.toByteArray()) val md5hash = md.digest() return Base64.encodeToString(md5hash, Base64.NO_WRAP) } catch (ignore: Exception) { } return "" } /** * Limelight auth utils */ fun getNonce(description: String): String { var nonce = "" val data = description.split("&").toTypedArray() for (s in data) { if (s.contains("nonce=")) { nonce = s.substring(6) break } } return nonce } fun getMd5Hash(buffer: String): String { val md: MessageDigest try { md = MessageDigest.getInstance("MD5") return bytesToHex(md.digest(buffer.toByteArray())) } catch (ignore: NoSuchAlgorithmException) { } catch (ignore: UnsupportedEncodingException) { } return "" } fun bytesToHex(bytes: ByteArray): String { return bytes.joinToString("") { "%02x".format(it) } } }
apache-2.0
af66d4d405afffbc83572208e4dcbb04
28.109589
119
0.642975
3.760177
false
false
false
false
pgutkowski/KGraphQL
src/main/kotlin/com/github/pgutkowski/kgraphql/schema/structure2/LookupSchema.kt
1
2197
package com.github.pgutkowski.kgraphql.schema.structure2 import com.github.pgutkowski.kgraphql.isIterable import com.github.pgutkowski.kgraphql.request.TypeReference import com.github.pgutkowski.kgraphql.schema.Schema import com.github.pgutkowski.kgraphql.schema.introspection.TypeKind import kotlin.reflect.KClass import kotlin.reflect.KType import kotlin.reflect.jvm.jvmErasure interface LookupSchema : Schema { fun typeByKClass(kClass: KClass<*>) : Type? fun typeByKType(kType: KType) : Type? fun typeByName(name: String) : Type? fun inputTypeByKClass(kClass: KClass<*>) : Type? fun inputTypeByKType(kType: KType) : Type? fun inputTypeByName(name: String) : Type? fun typeReference(kType: KType) : TypeReference { if(kType.jvmErasure.isIterable()){ val elementKType = kType.arguments.first().type ?: throw IllegalArgumentException("Cannot transform kotlin collection type $kType to KGraphQL TypeReference") val elementKTypeErasure = elementKType.jvmErasure val kqlType = typeByKClass(elementKTypeErasure) ?: inputTypeByKClass(elementKTypeErasure) ?: throw IllegalArgumentException("$kType has not been registered in this schema") val name = kqlType.name ?: throw IllegalArgumentException("Cannot create type reference to unnamed type") return TypeReference(name, kType.isMarkedNullable, true, elementKType.isMarkedNullable) } else { val erasure = kType.jvmErasure val kqlType = typeByKClass(erasure) ?: inputTypeByKClass(erasure) ?: throw IllegalArgumentException("$kType has not been registered in this schema") val name = kqlType.name ?: throw IllegalArgumentException("Cannot create type reference to unnamed type") return TypeReference(name, kType.isMarkedNullable) } } fun typeReference(type: Type) = TypeReference( name = type.unwrapped().name!!, isNullable = type.isNullable(), isList = type.isList(), isElementNullable = type.isList() && type.unwrapList().ofType?.kind == TypeKind.NON_NULL ) }
mit
8e37fb798bf82dbad4ec017952ab2946
40.471698
128
0.696859
4.914989
false
false
false
false
yh-kim/gachi-android
Gachi/app/src/main/kotlin/com/pickth/gachi/view/signup/fragment/RegionAddFragment.kt
1
3196
/* * Copyright 2017 Yonghoon Kim * * 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.pickth.gachi.view.signup.fragment import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.pickth.gachi.R import com.pickth.gachi.base.BaseAddInfoFragment import com.pickth.gachi.net.service.UserService import com.pickth.gachi.util.UserInfoManager import kotlinx.android.synthetic.main.fragment_signup_add_region.view.* import okhttp3.ResponseBody import retrofit2.Call import retrofit2.Callback import retrofit2.Response class RegionAddFragment : BaseAddInfoFragment() { companion object { val PAGE_INDEX = 3 private val mInstance = RegionAddFragment() fun getInstance(): RegionAddFragment = mInstance } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater!!.inflate(R.layout.fragment_signup_add_region, container, false) rootView.tv_add_info_title.text = resources.getStringArray(R.array.add_info_title)[PAGE_INDEX] return rootView } override fun clickNextButton(isSkip: Boolean) { Log.d(TAG, "click next button, isSkip: $isSkip") if(isSkip) { mListener?.onChange() return } mListener?.onChange() // TODO get region } fun initialUserInfo(input: String) { Log.d(TAG, "initialUserInfo, region input: $input") var map = HashMap<String, String>() map.set("location", input) UserService() .initialUserInfo(UserInfoManager.firebaseUserToken, UserInfoManager.getUser(context)?.uid!!, NicknameAddFragment.PAGE_INDEX + 1, map) .enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>) { Log.d(TAG, "initialUserInfo onResponse, code: ${response.code()}") if (response.code() == 200) { UserInfoManager.getUser(context)?.region = input UserInfoManager.notifyDataSetChanged(context) Log.d(TAG, "user info: ${UserInfoManager.getUser(context).toString()}") mListener?.onChange() } } override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) { Log.d(TAG, "initialUserInfo on Failure ${t?.printStackTrace()}") } }) } }
apache-2.0
9f6288b3bbf4ad3a1668b794ec80e078
34.921348
149
0.647685
4.625181
false
false
false
false
MimiReader/mimi-reader
mimi-app/src/main/java/com/emogoth/android/phone/mimi/activity/TabsActivity.kt
1
20748
package com.emogoth.android.phone.mimi.activity import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.util.Log import android.view.ActionMode import android.view.Menu import android.view.View import android.widget.PopupMenu import android.widget.TextView import android.widget.Toast import androidx.preference.PreferenceManager import androidx.viewpager.widget.ViewPager import com.emogoth.android.phone.mimi.R import com.emogoth.android.phone.mimi.activity.GalleryActivity2.Companion.start import com.emogoth.android.phone.mimi.adapter.TabPagerAdapter import com.emogoth.android.phone.mimi.autorefresh.RefreshScheduler2 import com.emogoth.android.phone.mimi.db.DatabaseUtils import com.emogoth.android.phone.mimi.db.HistoryTableConnection import com.emogoth.android.phone.mimi.fragment.MimiFragmentBase import com.emogoth.android.phone.mimi.fragment.PostItemsListFragment import com.emogoth.android.phone.mimi.interfaces.* import com.emogoth.android.phone.mimi.util.Extras import com.emogoth.android.phone.mimi.util.Pages import com.emogoth.android.phone.mimi.util.RxUtil import com.google.android.material.snackbar.Snackbar import com.google.android.material.tabs.TabLayout import com.google.android.material.tabs.TabLayout.TabLayoutOnPageChangeListener import com.mimireader.chanlib.models.ChanBoard import com.mimireader.chanlib.models.ChanPost import com.novoda.simplechromecustomtabs.SimpleChromeCustomTabs import io.reactivex.disposables.Disposable import kotlinx.android.synthetic.main.activity_tabs.* import java.util.* class TabsActivity : MimiActivity(), BoardItemClickListener, View.OnClickListener, PostItemClickListener, IToolbarContainer, GalleryMenuItemClickListener, TabEventListener { private var tabPagerAdapter: TabPagerAdapter? = null private var postListFragment: MimiFragmentBase? = null private var currentFragment: MimiFragmentBase? = null private var closeTabOnBack = false override val pageName: String? = "tabs_activity" private var historyObserver: Disposable? = null companion object { const val LOG_TAG = "TabsActivity" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_tabs) val sp = PreferenceManager.getDefaultSharedPreferences(this) closeTabOnBack = sp.getBoolean(getString(R.string.close_tab_on_back_pref), false) toolbar = mimi_toolbar mimi_toolbar.setNavigationOnClickListener { toggleNavDrawer() } val tabItems: ArrayList<TabPagerAdapter.TabItem>? if (savedInstanceState != null && savedInstanceState.containsKey("tabItems")) { tabItems = savedInstanceState.getParcelableArrayList("tabItems") tabPagerAdapter = TabPagerAdapter(supportFragmentManager, tabItems) } else { tabItems = null tabPagerAdapter = TabPagerAdapter(supportFragmentManager) } tabs_pager.setAdapter(tabPagerAdapter) tabs_pager.addOnPageChangeListener(TabLayoutOnPageChangeListener(tab_layout)) tabs_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} override fun onPageSelected(position: Int) { if (currentFragment == null) { return } tabs_pager.post { if (position < tabPagerAdapter?.count ?: 0) { currentFragment = tabPagerAdapter?.instantiateItem(tabs_pager, position) as MimiFragmentBase currentFragment?.initMenu() } } setFabVisibility(currentFragment?.showFab() ?: false) } override fun onPageScrollStateChanged(state: Int) {} }) tabs_pager.post(Runnable { currentFragment = tabPagerAdapter?.instantiateItem(tabs_pager, 0) as MimiFragmentBase currentFragment?.initMenu() }) // Hack to stop crashing // https://code.google.com/p/android/issues/detail?id=201827 // TabLayout.Tab uselessTab; // for (int j = 0; j < 17; j++) { // uselessTab = tabLayout.newTab(); // } tab_layout.setTabMode(TabLayout.MODE_SCROLLABLE) tab_layout.setupWithViewPager(tabs_pager) tab_layout.setTabsFromPagerAdapter(tabPagerAdapter) if (savedInstanceState != null && tabItems != null) { val count = tab_layout.getTabCount() for (i in 1 until count) { val tab = tab_layout.getTabAt(i) if (tab != null) { val item = tabItems[i] if (i == 1 && item.tabType == TabPagerAdapter.TabType.POSTS) { tab.text = getTabTitle(item.title) } else if (i == 1 && item.tabType == TabPagerAdapter.TabType.HISTORY) { tab.text = item.title.toUpperCase() } else { val args = item.bundle if (args != null) { val threadId = args.getLong(Extras.EXTRAS_THREAD_ID, 0) val boardName = args.getString(Extras.EXTRAS_BOARD_NAME, "") val tabView = createTabView(threadId, boardName) tab.customView = tabView tab.select() } } } } } val boardsTab = tab_layout.getTabAt(0) boardsTab?.setText(R.string.boards) fab_add_content.setOnClickListener { v: View? -> if (currentFragment is ContentInterface) { (currentFragment as ContentInterface).addContent() } } initDrawers(R.id.nav_drawer, R.id.nav_drawer_container, true) createDrawers(R.id.nav_drawer) val extras = intent.extras var openPage = Pages.NONE if (extras != null && extras.containsKey(Extras.OPEN_PAGE)) { val page = extras.getString(Extras.OPEN_PAGE) ?: "" if (!TextUtils.isEmpty(page)) { openPage = Pages.valueOf(page) } } if (openPage == Pages.BOOKMARKS) { openHistoryPage(true) } } override fun onDestroy() { super.onDestroy() if (tabs_pager != null) { tabs_pager.clearOnPageChangeListeners() } } override fun onResume() { super.onResume() startDatabaseObserver() SimpleChromeCustomTabs.getInstance().connectTo(this) if (currentFragment != null) { setFabVisibility(currentFragment?.showFab() ?: false) } } override fun onPause() { RxUtil.safeUnsubscribe(historyObserver) SimpleChromeCustomTabs.getInstance().disconnectFrom(this) super.onPause() } override fun onReplyClicked(boardName: String, threadId: Long, id: Long, replies: List<String>) { if (currentFragment is ReplyClickListener) { val frag = currentFragment as ReplyClickListener frag.onReplyClicked(boardName, threadId, id, replies) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) val tabItems = ArrayList(tabPagerAdapter?.items ?: emptyList()) outState.putParcelableArrayList("tabItems", tabItems) } protected fun getTabTitle(boardName: String): String { return "/" + boardName.toUpperCase(Locale.getDefault()) + "/" } override fun onBoardItemClick(board: ChanBoard, saveBackStack: Boolean) { val arguments = Bundle() arguments.putString(Extras.EXTRAS_BOARD_NAME, board.name) arguments.putString(Extras.EXTRAS_BOARD_TITLE, board.title) arguments.putBoolean(Extras.EXTRAS_TWOPANE, false) arguments.putBoolean(Extras.EXTRAS_STICKY_AUTO_REFRESH, true) val tabItem = TabPagerAdapter.TabItem(TabPagerAdapter.TabType.POSTS, arguments, PostItemsListFragment.TAB_ID.toLong(), board.name, null) if (tabPagerAdapter?.count == 1) { val postListTab = tab_layout.newTab() postListTab.text = getTabTitle(board.name) tabPagerAdapter?.addItem(tabItem) tab_layout.addTab(postListTab) } else { val postListTab = tab_layout.getTabAt(1) if (postListTab != null) { val newTab = tab_layout.newTab() newTab.text = getTabTitle(board.name) tab_layout.removeTabAt(1) tab_layout.addTab(newTab, 1) } tabPagerAdapter?.setItemAtIndex(1, tabItem) if (postListFragment == null) { postListFragment = tabPagerAdapter?.instantiateItem(tabs_pager, 1) as PostItemsListFragment } if (postListFragment is PostItemsListFragment) { val frag = postListFragment as PostItemsListFragment frag.setBoard(board.name) frag.refreshBoard(true) } } tabs_pager.setCurrentItem(1, true) } private fun setFabVisibility(shouldShow: Boolean) { if (fab_add_content.isShown && !shouldShow) { fab_add_content.hide() } else if (!fab_add_content.isShown && shouldShow) { fab_add_content.show() } } override fun setExpandedToolbar(expanded: Boolean, animate: Boolean) { appbar.setExpanded(expanded, animate) } override fun onClick(v: View) {} override fun onBackPressed() { var handled = false val pos = tabs_pager.currentItem if (currentFragment != null) { handled = currentFragment?.onBackPressed() ?: false } if (!handled && pos > 0) { handled = true if (closeTabOnBack && pos > 1) { closeTab(pos, false) } else { tabs_pager.setCurrentItem(pos - 1, true) } } if (!handled) { super.onBackPressed() invalidateOptionsMenu() } } override fun onPostItemClick(v: View?, posts: List<ChanPost>, position: Int, boardTitle: String, boardName: String, threadId: Long) { val threadTab = tab_layout.newTab() val threadTabItem: TabPagerAdapter.TabItem val args = Bundle() args.putLong(Extras.EXTRAS_THREAD_ID, threadId) args.putString(Extras.EXTRAS_BOARD_NAME, boardName) args.putString(Extras.EXTRAS_BOARD_TITLE, boardTitle) args.putBoolean(Extras.EXTRAS_STICKY_AUTO_REFRESH, true) if (posts.size > position) { args.putParcelable(Extras.EXTRAS_THREAD_FIRST_POST, posts[position]) } val tabView = createTabView(threadId, boardName) threadTab.customView = tabView threadTab.select() threadTabItem = TabPagerAdapter.TabItem(TabPagerAdapter.TabType.THREAD, args, threadId, boardName, threadId.toString()) val itemCount = tabPagerAdapter?.count ?: 0 val pos = tabPagerAdapter?.addItem(threadTabItem) ?: 0 if (pos < 0) { return } else if (pos >= itemCount) { tab_layout.addTab(threadTab) } tabs_pager.setCurrentItem(pos, true) } private fun createTabView(threadId: Long, boardName: String): View { val tabView = View.inflate(this, R.layout.tab_default, null) val title = tabView.findViewById<View>(R.id.title) as TextView val subTitle = tabView.findViewById<View>(R.id.subtitle) as TextView tabView.setOnLongClickListener { v -> val popupMenu = PopupMenu(this@TabsActivity, v) popupMenu.inflate(R.menu.tab_popup_menu) popupMenu.setOnMenuItemClickListener { item -> try { if (item.itemId == R.id.close_tab) { closeTab(threadId, boardName, true) } else if (item.itemId == R.id.close_other_tabs) { closeOtherTabs(tabPagerAdapter?.getPositionById(threadId) ?: -1) } } catch (e: Exception) { Log.e(LOG_TAG, "Caught exception", e) } true } popupMenu.show() true } tabView.setOnClickListener { v: View? -> tabs_pager.setCurrentItem(tabPagerAdapter?.getIndex(threadId) ?: -1, false) } title.text = getTabTitle(boardName) subTitle.text = threadId.toString() return tabView } private fun closeOtherTabs(position: Int) { val size = tabPagerAdapter?.count ?: 0 for (i in size - 1 downTo 2) { if (i != position) { Log.d(LOG_TAG, "Closing tab at position $i") val t = tabPagerAdapter?.getTab(i) if (t != null) { val id = Integer.valueOf(t.subtitle) closeTab(id.toLong(), t.title.toLowerCase(Locale.getDefault()).replace("/", ""), true) } } } } private fun closeTab(threadId: Long, boardName: String, showSnackbar: Boolean) { val pos = tabPagerAdapter?.getPositionById(threadId) ?: -1 closeTab(pos, threadId, boardName, showSnackbar) } private fun closeTab(pos: Int, showSnackbar: Boolean) { closeTab(pos, -1, "", showSnackbar) } private fun closeTab(pos: Int, threadId: Long, boardName: String, showSnackbar: Boolean) { if (pos == -1) { return } try { val pagerPos = tabs_pager.currentItem val newPos: Int newPos = if (pos > pagerPos) { pagerPos } else { pagerPos - 1 } var id = threadId var name = boardName if (threadId <= 0) { val item = tabPagerAdapter?.getTabItem(pos) if (item != null) { val args = item.bundle if (args != null) { id = args.getLong(Extras.EXTRAS_THREAD_ID, -1) name = args.getString(Extras.EXTRAS_BOARD_NAME, "") ?: "" } } } if (newPos >= 0) { Log.d(LOG_TAG, "Removing tab: position=$pos") val sub = HistoryTableConnection.fetchPost(name, id) .compose(DatabaseUtils.applySingleSchedulers()) .subscribe({ RefreshScheduler2.removeThread(name, id) // if (it.watched) { // RefreshScheduler.getInstance().removeThread(name, id) // } }, { Log.e(LOG_TAG, "Caught exception", it) }) tab_layout.removeTabAt(pos) tabPagerAdapter?.removeItemAtIndex(pos) tabPagerAdapter?.notifyDataSetChanged() // tabPager.setAdapter(tabPagerAdapter); tabs_pager.setCurrentItem(newPos, false) if (showSnackbar) { Snackbar.make(tabs_pager, R.string.closing_tab, Snackbar.LENGTH_SHORT).show() } } else { Log.e(LOG_TAG, "Position is invalid: pos=$newPos") } } catch (e: Exception) { Snackbar.make(tabs_pager, R.string.error_occurred, Snackbar.LENGTH_SHORT).show() Log.e(LOG_TAG, "Error while closing tab", e) Log.e(LOG_TAG, "Caught exception", e) } } override fun onHomeButtonClicked() { tabs_pager.setCurrentItem(0, false) } override fun onHistoryItemClicked(boardName: String, threadId: Long, boardTitle: String, position: Int, watched: Boolean) { try { val board = ChanBoard() board.name = boardName board.title = boardTitle if (tabPagerAdapter?.count == 1) { onBoardItemClick(board, false) } onPostItemClick(null, emptyList(), position, boardTitle, boardName, threadId) } catch (e: Exception) { Log.e(LOG_TAG, "Caught exception", e) Toast.makeText(this@TabsActivity, R.string.error_opening_bookmark, Toast.LENGTH_SHORT).show() } } fun startDatabaseObserver() { historyObserver = HistoryTableConnection.observeHistory() .compose(DatabaseUtils.applySchedulers()) .subscribe { for (history in it) { updateTabHighlight(history.boardName, history.threadId, history.unreadCount) } } } fun updateTabHighlight(boardName: String, threadId: Long, unread: Int) { if (tabPagerAdapter != null && tab_layout != null) { val tabIndex = tabPagerAdapter?.getIndex(threadId) ?: -1 if (tabIndex >= 0) { val t = tab_layout.getTabAt(tabIndex) if (t != null) { val v = t.customView if (v != null) { val highlightView = v.findViewById<View>(R.id.highlight) if (highlightView != null) { if (unread > 0) { highlightView.visibility = View.VISIBLE } else { highlightView.visibility = View.GONE } } } } } } } override fun onTabClosed(id: Long, boardName: String, boardTitle: String, closeOthers: Boolean) { if (closeOthers && tabPagerAdapter != null) { val position = tabPagerAdapter?.getPositionById(id) ?: -1 closeOtherTabs(position) } else { closeTab(id, boardName, true) } } override fun onGalleryMenuItemClick(boardPath: String, threadId: Long) { start(this, 0, 0, boardPath, threadId, LongArray(0)) } override fun openHistoryPage(watched: Boolean) { val args = Bundle() val historyFragmentName: String if (watched) { historyFragmentName = getString(R.string.bookmarks) args.putInt(Extras.EXTRAS_HISTORY_QUERY_TYPE, HistoryTableConnection.BOOKMARKS) args.putInt(Extras.EXTRAS_VIEWING_HISTORY, VIEWING_BOOKMARKS) } else { historyFragmentName = getString(R.string.history) args.putInt(Extras.EXTRAS_HISTORY_QUERY_TYPE, HistoryTableConnection.HISTORY) args.putInt(Extras.EXTRAS_VIEWING_HISTORY, VIEWING_HISTORY) } val tabItem = TabPagerAdapter.TabItem(TabPagerAdapter.TabType.HISTORY, args, PostItemsListFragment.TAB_ID.toLong(), historyFragmentName, null) if (tabPagerAdapter?.count == 1) { val postListTab = tab_layout.newTab() postListTab.text = historyFragmentName tabPagerAdapter?.addItem(tabItem) tab_layout.addTab(postListTab) } else { val postListTab = tab_layout.getTabAt(1) if (postListTab != null) { val newTab = tab_layout.newTab() newTab.text = historyFragmentName tab_layout.removeTabAt(1) tab_layout.addTab(newTab, 1) } tabPagerAdapter?.setItemAtIndex(1, tabItem) if (postListFragment == null) { postListFragment = tabPagerAdapter?.instantiateItem(tabs_pager, 1) as MimiFragmentBase } } tabs_pager.setCurrentItem(1, false) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) val page = intent.getStringExtra(Extras.OPEN_PAGE) if (!TextUtils.isEmpty(page)) { try { val pageEnum = Pages.valueOf(page ?: "BOARDS") val watched: Boolean watched = pageEnum == Pages.BOOKMARKS openHistoryPage(watched) } catch (ignore: Exception) { // no op } } } override fun onCreateActionMode(p0: ActionMode?, p1: Menu?): Boolean { tabs_pager.isEnabled = false return true } override fun onDestroyActionMode(p0: ActionMode?) { tabs_pager.isEnabled = true } }
apache-2.0
b1df07de072c7e17b72722a3e1f780b4
40.087129
173
0.58584
4.726196
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/render/VertexInfo.kt
1
960
package com.soywiz.korge.render import com.soywiz.kmem.* import com.soywiz.korim.color.* import com.soywiz.korio.util.* import com.soywiz.korma.geom.* data class VertexInfo( var x: Float = 0f, var y: Float = 0f, var u: Float = 0f, var v: Float = 0f, var colorMul: RGBA = Colors.WHITE, var colorAdd: Int = 0 ) { var texWidth: Int = -1 var texHeight: Int = -1 val xy get() = Point(x, y) val uv get() = Point(u, v) fun read(buffer: FBuffer, n: Int) { val index = n * 6 this.x = buffer.f32[index + 0] this.y = buffer.f32[index + 1] this.u = buffer.f32[index + 2] this.v = buffer.f32[index + 3] this.colorMul = RGBA(buffer.i32[index + 4]) this.colorAdd = buffer.i32[index + 5] } fun toStringXY() = "[${x.niceStr},${y.niceStr}]" fun toStringXYUV() = "[(${x.niceStr},${y.niceStr}), (${(u * texWidth).toIntRound()}, ${(v * texHeight).toIntRound()})]" }
apache-2.0
8fe711de7be3d027eaca5d5931f4dce9
29
123
0.578125
3.028391
false
false
false
false
donald-w/Anki-Android
AnkiDroid/src/main/java/com/ichi2/libanki/backend/ModelsBackend.kt
1
4132
/* * Copyright (c) 2021 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ @file:Suppress("FunctionName") package com.ichi2.libanki.backend import BackendProto.Backend import android.content.res.Resources import com.ichi2.libanki.NoteType import com.ichi2.libanki.backend.BackendUtils.from_json_bytes import com.ichi2.libanki.backend.BackendUtils.to_json_bytes import net.ankiweb.rsdroid.BackendV1 import net.ankiweb.rsdroid.RustCleanup import java.util.* private typealias ntid = Long class NoteTypeNameID(val name: String, val id: ntid) class NoteTypeNameIDUseCount(val id: Long, val name: String, val useCount: UInt) class BackendNote(val fields: MutableList<String>) interface ModelsBackend { fun get_notetype_names(): Sequence<NoteTypeNameID> fun get_notetype_names_and_counts(): Sequence<NoteTypeNameIDUseCount> fun get_notetype_legacy(id: Long): NoteType fun get_notetype_id_by_name(name: String): Optional<Long> fun get_stock_notetype_legacy(): NoteType fun cloze_numbers_in_note(flds: List<String>): List<Int> fun remove_notetype(id: ntid) fun add_or_update_notetype(model: NoteType, preserve_usn_and_mtime: Boolean): Long @RustCleanup("This should be in col") fun after_note_updates(nids: List<Long>, mark_modified: Boolean, generate_cards: Boolean = true) @RustCleanup("This should be in col") /** "You probably want .remove_notes_by_card() instead." */ fun remove_cards_and_orphaned_notes(card_ids: List<Long>) } @Suppress("unused") class ModelsBackendImpl(private val backend: BackendV1) : ModelsBackend { override fun get_notetype_names(): Sequence<NoteTypeNameID> { return backend.notetypeNames.entriesList.map { NoteTypeNameID(it.name, it.id) }.asSequence() } override fun get_notetype_names_and_counts(): Sequence<NoteTypeNameIDUseCount> { return backend.notetypeNamesAndCounts.entriesList.map { NoteTypeNameIDUseCount(it.id, it.name, it.useCount.toUInt()) }.asSequence() } override fun get_notetype_legacy(id: Long): NoteType { return NoteType(from_json_bytes(backend.getNotetypeLegacy(id))) } override fun get_notetype_id_by_name(name: String): Optional<Long> { return try { Optional.of(backend.getNotetypeIDByName(name).ntid) } catch (ex: Resources.NotFoundException) { Optional.empty() } } override fun get_stock_notetype_legacy(): NoteType { val fromJsonBytes = from_json_bytes(backend.getStockNotetypeLegacy(Backend.StockNoteType.STOCK_NOTE_TYPE_BASIC)) return NoteType(fromJsonBytes) } override fun cloze_numbers_in_note(flds: List<String>): List<Int> { val note = Backend.Note.newBuilder().addAllFields(flds).build() return backend.clozeNumbersInNote(note).numbersList } override fun remove_notetype(id: ntid) { backend.removeNotetype(id) } override fun add_or_update_notetype(model: NoteType, preserve_usn_and_mtime: Boolean): ntid { val toJsonBytes = to_json_bytes(model) return backend.addOrUpdateNotetype(toJsonBytes, preserve_usn_and_mtime).ntid } override fun after_note_updates(nids: List<Long>, mark_modified: Boolean, generate_cards: Boolean) { backend.afterNoteUpdates(nids, mark_modified, generate_cards) } override fun remove_cards_and_orphaned_notes(card_ids: List<Long>) { backend.removeCards(card_ids) } }
gpl-3.0
926f3b53963c1e45a176f50047c39c73
38.730769
120
0.71757
3.682709
false
false
false
false
mctoyama/PixelClient
src/main/kotlin/org/pixelndice/table/pixelclient/fx/LibraryAboutController.kt
1
2385
package org.pixelndice.table.pixelclient.fx import javafx.fxml.FXML import javafx.scene.control.Hyperlink import javafx.scene.text.Font import javafx.scene.text.FontWeight import javafx.scene.text.Text import javafx.scene.text.TextFlow import org.pixelndice.table.pixelclient.ApplicationBus import org.pixelndice.table.pixelclient.PixelResourceBundle import java.awt.event.ActionEvent class LibraryAboutController{ @FXML lateinit var aboutPixelnDiceTextFlow: TextFlow @FXML lateinit var bsdLicenseTextFlow: TextFlow @FXML lateinit var otherSoftwareTextFlow: TextFlow // initialize controler fun initialize() { // about PixelnDice val aboutPixelnDiceText = Text(PixelResourceBundle.getString("key.aboutpixelndice")) aboutPixelnDiceText.font = Font(16.0) aboutPixelnDiceTextFlow.children.add(aboutPixelnDiceText) // BSD License val bsdLicenseHead = Text(PixelResourceBundle.getString("key.2clauseBSDlicenTitle")) bsdLicenseHead.font = Font.font("", FontWeight.BOLD, 16.0) val bsdLicense = Text(PixelResourceBundle.getString("key.2clauseBSDlicense")) bsdLicense.font = Font(16.0) bsdLicenseTextFlow.children.addAll(bsdLicenseHead, bsdLicense) // Other Software val otherSoftware = Text(PixelResourceBundle.getString("key.othersoftware")) otherSoftware.font = Font.font("", FontWeight.BOLD, 16.0) val protobufText = Text(PixelResourceBundle.getString("key.aboutprotobuf")) protobufText.font = Font(16.0) val guavaText = Text(PixelResourceBundle.getString("key.aboutguava")) guavaText.font = Font(16.0) val openIconicText = Text(PixelResourceBundle.getString("key.aboutopeniconic")) openIconicText.font = Font(16.0) val neutonText = Text(PixelResourceBundle.getString("key.aboutneuton")) neutonText.font = Font(16.0) otherSoftwareTextFlow.children.addAll(otherSoftware, protobufText, guavaText, openIconicText, neutonText) } @FXML fun pixelndiceURLOnAction(){ ApplicationBus.post(ApplicationBus.OpenExternalURLEvent(PixelResourceBundle.getString("key.pixelndiceurl"))) } @FXML fun toyamaEmailOnAction(){ ApplicationBus.post(ApplicationBus.OpenExternalURLEvent("mailto:" + PixelResourceBundle.getString("key.toyamamail"))) } }
bsd-2-clause
d519371b934f176c10700a86baedcdd1
36.28125
125
0.736268
4.056122
false
false
false
false
Ribesg/anko
dsl/testData/functional/percent/ViewTest.kt
2
2225
object `$$Anko$Factories$PercentViewGroup` { val PERCENT_FRAME_LAYOUT = { ctx: Context -> _PercentFrameLayout(ctx) } val PERCENT_RELATIVE_LAYOUT = { ctx: Context -> _PercentRelativeLayout(ctx) } } inline fun ViewManager.percentFrameLayout(): android.support.percent.PercentFrameLayout = percentFrameLayout({}) inline fun ViewManager.percentFrameLayout(init: _PercentFrameLayout.() -> Unit): android.support.percent.PercentFrameLayout { return ankoView(`$$Anko$Factories$PercentViewGroup`.PERCENT_FRAME_LAYOUT) { init() } } inline fun Context.percentFrameLayout(): android.support.percent.PercentFrameLayout = percentFrameLayout({}) inline fun Context.percentFrameLayout(init: _PercentFrameLayout.() -> Unit): android.support.percent.PercentFrameLayout { return ankoView(`$$Anko$Factories$PercentViewGroup`.PERCENT_FRAME_LAYOUT) { init() } } inline fun Activity.percentFrameLayout(): android.support.percent.PercentFrameLayout = percentFrameLayout({}) inline fun Activity.percentFrameLayout(init: _PercentFrameLayout.() -> Unit): android.support.percent.PercentFrameLayout { return ankoView(`$$Anko$Factories$PercentViewGroup`.PERCENT_FRAME_LAYOUT) { init() } } inline fun ViewManager.percentRelativeLayout(): android.support.percent.PercentRelativeLayout = percentRelativeLayout({}) inline fun ViewManager.percentRelativeLayout(init: _PercentRelativeLayout.() -> Unit): android.support.percent.PercentRelativeLayout { return ankoView(`$$Anko$Factories$PercentViewGroup`.PERCENT_RELATIVE_LAYOUT) { init() } } inline fun Context.percentRelativeLayout(): android.support.percent.PercentRelativeLayout = percentRelativeLayout({}) inline fun Context.percentRelativeLayout(init: _PercentRelativeLayout.() -> Unit): android.support.percent.PercentRelativeLayout { return ankoView(`$$Anko$Factories$PercentViewGroup`.PERCENT_RELATIVE_LAYOUT) { init() } } inline fun Activity.percentRelativeLayout(): android.support.percent.PercentRelativeLayout = percentRelativeLayout({}) inline fun Activity.percentRelativeLayout(init: _PercentRelativeLayout.() -> Unit): android.support.percent.PercentRelativeLayout { return ankoView(`$$Anko$Factories$PercentViewGroup`.PERCENT_RELATIVE_LAYOUT) { init() } }
apache-2.0
3a53b0f3f22bcddf526dad72dccdc6d1
64.470588
134
0.790112
4.713983
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/RxTextAutoZoom.kt
1
11038
package com.tamsiree.rxui.view import android.annotation.SuppressLint import android.annotation.TargetApi import android.app.Activity import android.content.Context import android.content.res.Resources import android.graphics.RectF import android.graphics.Typeface import android.os.Build import android.text.Layout import android.text.StaticLayout import android.text.TextPaint import android.util.AttributeSet import android.util.SparseIntArray import android.util.TypedValue import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.EditText import java.util.* /** * @author tamsiree */ @SuppressLint("AppCompatCustomView") class RxTextAutoZoom : EditText { private val availableSpaceRect = RectF() private val textCachedSizes = SparseIntArray() private var sizeTester: SizeTester? = null private var maxTextSize = 0f private var spacingMult = 1.0f private var spacingAdd = 0.0f private var minTextSize: Float? = null private var widthLimit = 0 private var maxLines = 0 private var enableSizeCache = true private var initiallized = false private var textPaint: TextPaint? = null constructor(context: Context?) : this(context, null, 0) { initView() } constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0) { initView() } constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) { initView() } constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { initView() } override fun setTypeface(tf: Typeface?) { if (textPaint == null) { textPaint = TextPaint(paint) } textPaint!!.typeface = tf super.setTypeface(tf) } override fun setTextSize(size: Float) { maxTextSize = size textCachedSizes.clear() adjustTextSize() } override fun setMaxLines(maxlines: Int) { super.setMaxLines(maxlines) maxLines = maxlines reAdjust() } override fun getMaxLines(): Int { return maxLines } override fun setSingleLine() { super.setSingleLine() maxLines = 1 reAdjust() } override fun setSingleLine(singleLine: Boolean) { super.setSingleLine(singleLine) maxLines = if (singleLine) { 1 } else { NO_LINE_LIMIT } reAdjust() } override fun setLines(lines: Int) { super.setLines(lines) maxLines = lines reAdjust() } override fun setTextSize(unit: Int, size: Float) { val c = context val r: Resources r = if (c == null) { Resources.getSystem() } else { c.resources } maxTextSize = TypedValue.applyDimension(unit, size, r.displayMetrics) textCachedSizes.clear() adjustTextSize() } override fun setLineSpacing(add: Float, mult: Float) { super.setLineSpacing(add, mult) spacingMult = mult spacingAdd = add } private fun initView() { //获得这个控件对应的属性。 // using the minimal recommended font size minTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12f, resources.displayMetrics) maxTextSize = textSize if (maxLines == 0) { // no value was assigned during construction maxLines = NO_LINE_LIMIT } // prepare size tester: sizeTester = object : SizeTester { val textRect = RectF() @TargetApi(Build.VERSION_CODES.JELLY_BEAN) override fun onTestSize(suggestedSize: Int, availableSPace: RectF): Int { textPaint!!.textSize = suggestedSize.toFloat() val text = text.toString() val singleline = getMaxLines() == 1 if (singleline) { textRect.bottom = textPaint!!.fontSpacing textRect.right = textPaint!!.measureText(text) } else { val layout = StaticLayout(text, textPaint, widthLimit, Layout.Alignment.ALIGN_NORMAL, spacingMult, spacingAdd, true) if (getMaxLines() != NO_LINE_LIMIT && layout.lineCount > getMaxLines()) { return 1 } textRect.bottom = layout.height.toFloat() var maxWidth = -1 for (i in 0 until layout.lineCount) { if (maxWidth < layout.getLineWidth(i)) { maxWidth = layout.getLineWidth(i).toInt() } } textRect.right = maxWidth.toFloat() } textRect.offsetTo(0f, 0f) return if (availableSPace.contains(textRect)) { // may be too small, don't worry we will find the best match -1 } else 1 // else, too big } } initiallized = true } fun getMinTextSize(): Float? { return minTextSize } private fun reAdjust() { adjustTextSize() } private fun adjustTextSize() { if (!initiallized) { return } val startSize = Math.round(minTextSize!!) val heightLimit = (measuredHeight - compoundPaddingBottom - compoundPaddingTop) widthLimit = (measuredWidth - compoundPaddingLeft - compoundPaddingRight) if (widthLimit <= 0) { return } availableSpaceRect.right = widthLimit.toFloat() availableSpaceRect.bottom = heightLimit.toFloat() super.setTextSize( TypedValue.COMPLEX_UNIT_PX, efficientTextSizeSearch(startSize, maxTextSize.toInt(), sizeTester, availableSpaceRect).toFloat()) } /** * Enables or disables size caching, enabling it will improve performance * where you are animating a value inside TextView. This stores the font * size against getText().length() Be careful though while enabling it as 0 * takes more space than 1 on some fonts and so on. * * @param enable enable font size caching */ fun setEnableSizeCache(enable: Boolean) { enableSizeCache = enable textCachedSizes.clear() adjustTextSize() } /** * Set the lower text size limit and invalidate the view * * @param minTextSize 最小的文字大小 */ fun setMinTextSize(minTextSize: Float?) { this.minTextSize = minTextSize reAdjust() } private fun efficientTextSizeSearch(start: Int, end: Int, sizeTester: SizeTester?, availableSpace: RectF): Int { if (!enableSizeCache) { return binarySearch(start, end, sizeTester, availableSpace) } val text = text.toString() val key = text.length var size = textCachedSizes[key] if (size != 0) { return size } size = binarySearch(start, end, sizeTester, availableSpace) textCachedSizes.put(key, size) return size } override fun onTextChanged(text: CharSequence, start: Int, before: Int, after: Int) { super.onTextChanged(text, start, before, after) reAdjust() } override fun onSizeChanged(width: Int, height: Int, oldwidth: Int, oldheight: Int) { textCachedSizes.clear() super.onSizeChanged(width, height, oldwidth, oldheight) if (width != oldwidth || height != oldheight) { reAdjust() } } private fun binarySearch(start: Int, end: Int, sizeTester: SizeTester?, availableSpace: RectF): Int { var lastBest = start var lo = start var hi = end - 1 var mid: Int while (lo <= hi) { mid = lo + hi ushr 1 val midValCmp = sizeTester!!.onTestSize(mid, availableSpace) if (midValCmp < 0) { lastBest = lo lo = mid + 1 } else if (midValCmp > 0) { hi = mid - 1 lastBest = hi } else { return mid } } // make sure to return last best // this is what should always be returned return lastBest } interface SizeTester { /** * AutoFitEditText * * @param suggestedSize Size of text to be tested * @param availableSpace available space in which text must fit * @return an integer < 0 if after applying `suggestedSize` to * text, it takes less space than `availableSpace`, > 0 * otherwise */ fun onTestSize(suggestedSize: Int, availableSpace: RectF): Int } companion object { private const val NO_LINE_LIMIT = -1 @SuppressLint("ClickableViewAccessibility") fun setNormalization(a: Activity, rootView: View, aText: RxTextAutoZoom) { // if the view is not instance of AutoFitEditText // i.e. if the user taps outside of the box if (rootView !is RxTextAutoZoom) { rootView.setOnTouchListener { v: View?, event: MotionEvent? -> hideSoftKeyboard(a) if (aText.getMinTextSize() != null && aText.textSize < aText.getMinTextSize()!!) { // you can define your minSize, in this case is 50f // trim all the new lines and set the text as it was // before aText.setText(aText.text.toString().replace("\n", "")) } false } } // If a layout container, iterate over children and seed recursion. if (rootView is ViewGroup) { for (i in 0 until rootView.childCount) { val innerView = rootView.getChildAt(i) setNormalization(a, innerView, aText) } } } fun hideSoftKeyboard(a: Activity) { val inputMethodManager = a .getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager if (a.currentFocus != null && a.currentFocus!!.windowToken != null) { Objects.requireNonNull(inputMethodManager).hideSoftInputFromWindow(a.currentFocus!!.windowToken, 0) } } } }
apache-2.0
5405f97206aae7ef47715abfd48c079c
31.741071
146
0.563091
4.950495
false
true
false
false
stripe/stripe-android
payments-core/src/test/java/com/stripe/android/EphemeralKeyFixtures.kt
1
1281
package com.stripe.android import com.stripe.android.model.parsers.EphemeralKeyJsonParser import org.json.JSONObject internal object EphemeralKeyFixtures { val FIRST_JSON = JSONObject( """ { "id": "ephkey_123", "object": "ephemeral_key", "secret": "ek_test_123", "created": 1501179335, "livemode": false, "expires": 1501199335, "associated_objects": [{ "type": "customer", "id": "cus_AQsHpvKfKwJDrF" }] } """.trimIndent() ) val SECOND_JSON = JSONObject( """ { "id": "ephkey_ABC", "object": "ephemeral_key", "secret": "ek_test_456", "created": 1601189335, "livemode": false, "expires": 1601199335, "associated_objects": [{ "type": "customer", "id": "cus_abc123" }] } """.trimIndent() ) val FIRST = EphemeralKeyJsonParser().parse(FIRST_JSON) val SECOND = EphemeralKeyJsonParser().parse(SECOND_JSON) fun create( expires: Long ): EphemeralKey { return FIRST.copy( expires = expires ) } }
mit
b6a65cedab1459485b25137fe8f3aba9
24.117647
62
0.485558
4.186275
false
false
false
false
sczerwinski/android-delegates-shared-preferences
delegates-shared-preferences/src/main/kotlin/it/czerwinski/android/delegates/sharedpreferences/_Delegates.kt
1
6956
package it.czerwinski.android.delegates.sharedpreferences import android.content.Context import android.content.SharedPreferences /** * Creates a new instance of [NullableSharedPreferenceDelegate] * for a String preference in this Context. * * @param key The name of the preference. * * @return A new instance of [NullableSharedPreferenceDelegate] for a String preference. */ fun Context.stringSharedPreference(key: String) = NullableSharedPreferenceDelegate<String>( this, key, "", SharedPreferences::getString, SharedPreferences.Editor::putString) /** * Creates a new instance of [SharedPreferenceDelegate] * for a String preference in this Context. * * @param key The name of the preference. * @param defaultValue The value to be returned if the preference does not exist. * * @return A new instance of [SharedPreferenceDelegate] for a String preference. */ fun Context.stringSharedPreference(key: String, defaultValue: String) = SharedPreferenceDelegate<String>( this, key, defaultValue, SharedPreferences::getString, SharedPreferences.Editor::putString) /** * Creates a new instance of [NullableSharedPreferenceDelegate] * for an Int preference in this Context. * * @param key The name of the preference. * * @return A new instance of [NullableSharedPreferenceDelegate] for an Int preference. */ fun Context.intSharedPreference(key: String) = NullableSharedPreferenceDelegate<Int>( this, key, 0, SharedPreferences::getInt, SharedPreferences.Editor::putInt) /** * Creates a new instance of [SharedPreferenceDelegate] * for an Int preference in this Context. * * @param key The name of the preference. * @param defaultValue The value to be returned if the preference does not exist. * * @return A new instance of [SharedPreferenceDelegate] for an Int preference. */ fun Context.intSharedPreference(key: String, defaultValue: Int) = SharedPreferenceDelegate<Int>( this, key, defaultValue, SharedPreferences::getInt, SharedPreferences.Editor::putInt) /** * Creates a new instance of [NullableSharedPreferenceDelegate] * for a Long preference in this Context. * * @param key The name of the preference. * * @return A new instance of [NullableSharedPreferenceDelegate] for a Long preference. */ fun Context.longSharedPreference(key: String) = NullableSharedPreferenceDelegate<Long>( this, key, 0L, SharedPreferences::getLong, SharedPreferences.Editor::putLong) /** * Creates a new instance of [SharedPreferenceDelegate] * for a Long preference in this Context. * * @param key The name of the preference. * @param defaultValue The value to be returned if the preference does not exist. * * @return A new instance of [SharedPreferenceDelegate] for a Long preference. */ fun Context.longSharedPreference(key: String, defaultValue: Long) = SharedPreferenceDelegate<Long>( this, key, defaultValue, SharedPreferences::getLong, SharedPreferences.Editor::putLong) /** * Creates a new instance of [NullableSharedPreferenceDelegate] * for a Float preference in this Context. * * @param key The name of the preference. * * @return A new instance of [NullableSharedPreferenceDelegate] for a Float preference. */ fun Context.floatSharedPreference(key: String) = NullableSharedPreferenceDelegate<Float>( this, key, 0f, SharedPreferences::getFloat, SharedPreferences.Editor::putFloat) /** * Creates a new instance of [SharedPreferenceDelegate] * for a Float preference in this Context. * * @param key The name of the preference. * @param defaultValue The value to be returned if the preference does not exist. * * @return A new instance of [SharedPreferenceDelegate] for a Float preference. */ fun Context.floatSharedPreference(key: String, defaultValue: Float) = SharedPreferenceDelegate<Float>( this, key, defaultValue, SharedPreferences::getFloat, SharedPreferences.Editor::putFloat) /** * Creates a new instance of [NullableSharedPreferenceDelegate] * for a Double preference in this Context. * * @param key The name of the preference. * * @return A new instance of [NullableSharedPreferenceDelegate] for a Double preference. */ fun Context.doubleSharedPreference(key: String) = NullableSharedPreferenceDelegate<Double>( this, key, 0.0, SharedPreferences::getDouble, SharedPreferences.Editor::putDouble) /** * Creates a new instance of [SharedPreferenceDelegate] * for a Double preference in this Context. * * @param key The name of the preference. * @param defaultValue The value to be returned if the preference does not exist. * * @return A new instance of [SharedPreferenceDelegate] for a Double preference. */ fun Context.doubleSharedPreference(key: String, defaultValue: Double) = SharedPreferenceDelegate<Double>( this, key, defaultValue, SharedPreferences::getDouble, SharedPreferences.Editor::putDouble) /** * Creates a new instance of [NullableSharedPreferenceDelegate] * for a Boolean preference in this Context. * * @param key The name of the preference. * * @return A new instance of [NullableSharedPreferenceDelegate] for a Boolean preference. */ fun Context.booleanSharedPreference(key: String) = NullableSharedPreferenceDelegate<Boolean>( this, key, false, SharedPreferences::getBoolean, SharedPreferences.Editor::putBoolean) /** * Creates a new instance of [SharedPreferenceDelegate] * for a Boolean preference in this Context. * * @param key The name of the preference. * @param defaultValue The value to be returned if the preference does not exist. * * @return A new instance of [SharedPreferenceDelegate] for a Boolean preference. */ fun Context.booleanSharedPreference(key: String, defaultValue: Boolean) = SharedPreferenceDelegate<Boolean>( this, key, defaultValue, SharedPreferences::getBoolean, SharedPreferences.Editor::putBoolean) /** * Creates a new instance of [NullableSharedPreferenceDelegate] * for a String Set preference in this Context. * * @param key The name of the preference. * * @return A new instance of [NullableSharedPreferenceDelegate] for a String Set preference. */ fun Context.stringSetSharedPreference(key: String) = NullableSharedPreferenceDelegate<Set<String>>( this, key, emptySet<String>(), SharedPreferences::getStringSet, SharedPreferences.Editor::putStringSet) /** * Creates a new instance of [SharedPreferenceDelegate] * for a String Set preference in this Context. * * @param key The name of the preference. * @param defaultValue The value to be returned if the preference does not exist. * * @return A new instance of [SharedPreferenceDelegate] for a String Set preference. */ fun Context.stringSetSharedPreference(key: String, defaultValue: Set<String>) = SharedPreferenceDelegate<Set<String>>( this, key, defaultValue, SharedPreferences::getStringSet, SharedPreferences.Editor::putStringSet)
apache-2.0
b440015bd83eccb981c7c0dcda1cc6c4
32.603865
92
0.755894
4.350219
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/api/screens/ScreenStackViewManager.kt
2
2285
package abi43_0_0.host.exp.exponent.modules.api.screens import android.view.View import android.view.ViewGroup import abi43_0_0.com.facebook.react.bridge.ReactApplicationContext import abi43_0_0.com.facebook.react.module.annotations.ReactModule import abi43_0_0.com.facebook.react.uimanager.LayoutShadowNode import abi43_0_0.com.facebook.react.uimanager.ThemedReactContext import abi43_0_0.com.facebook.react.uimanager.ViewGroupManager @ReactModule(name = ScreenStackViewManager.REACT_CLASS) class ScreenStackViewManager : ViewGroupManager<ScreenStack>() { override fun getName(): String { return REACT_CLASS } override fun createViewInstance(reactContext: ThemedReactContext): ScreenStack { return ScreenStack(reactContext) } override fun addView(parent: ScreenStack, child: View, index: Int) { require(child is Screen) { "Attempt attach child that is not of type RNScreen" } parent.addScreen(child, index) } override fun removeViewAt(parent: ScreenStack, index: Int) { prepareOutTransition(parent.getScreenAt(index)) parent.removeScreenAt(index) } private fun prepareOutTransition(screen: Screen?) { startTransitionRecursive(screen) } private fun startTransitionRecursive(parent: ViewGroup?) { var i = 0 parent?.let { val size = it.childCount while (i < size) { val child = it.getChildAt(i) child?.let { view -> it.startViewTransition(view) } if (child is ScreenStackHeaderConfig) { // we want to start transition on children of the toolbar too, // which is not a child of ScreenStackHeaderConfig startTransitionRecursive(child.toolbar) } if (child is ViewGroup) { startTransitionRecursive(child) } i++ } } } override fun getChildCount(parent: ScreenStack): Int { return parent.screenCount } override fun getChildAt(parent: ScreenStack, index: Int): View { return parent.getScreenAt(index) } override fun createShadowNodeInstance(context: ReactApplicationContext): LayoutShadowNode { return ScreensShadowNode(context) } override fun needsCustomLayoutForChildren(): Boolean { return true } companion object { const val REACT_CLASS = "RNSScreenStack" } }
bsd-3-clause
46cf057c05010310ce0db2a2e4dc4629
29.878378
93
0.722538
4.247212
false
false
false
false
TeamWizardry/LibrarianLib
modules/mosaic/src/main/kotlin/com/teamwizardry/librarianlib/mosaic/MosaicJson.kt
1
737
package com.teamwizardry.librarianlib.mosaic internal class MosaicJson( var width: Int, var height: Int, var blur: Boolean, var mipmap: Boolean, var sprites: List<SpriteJson>, var colors: List<ColorJson> ) internal class SpriteJson(var name: String) { var u: Int = 0 var v: Int = 0 var w: Int = 0 var h: Int = 0 var frames: IntArray = intArrayOf(0) var offsetU: Int = 0 var offsetV: Int = 0 var minUCap: Int = 0 var minVCap: Int = 0 var maxUCap: Int = 0 var maxVCap: Int = 0 var pinLeft: Boolean = true var pinTop: Boolean = true var pinRight: Boolean = true var pinBottom: Boolean = true } internal class ColorJson(var name: String, var u: Int, var v: Int)
lgpl-3.0
f2e1689425d963b79fcc9361d2cf2ed4
22.774194
66
0.647218
3.476415
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/project/workspace/FeatureGraph.kt
3
4177
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.project.workspace import org.rust.lang.utils.Node import org.rust.lang.utils.PresentableGraph import org.rust.openapiext.isUnitTestMode private typealias FeaturesGraphInner = PresentableGraph<PackageFeature, Unit> private typealias FeatureNode = Node<PackageFeature, Unit> class FeatureGraph private constructor( private val graph: FeaturesGraphInner, private val featureToNode: Map<PackageFeature, FeatureNode> ) { /** Applies the specified function [f] to a freshly created [FeaturesView] and returns its state */ fun apply(defaultState: FeatureState, f: FeaturesView.() -> Unit): Map<PackageFeature, FeatureState> = FeaturesView(defaultState).apply(f).state /** Mutable view of a [FeatureGraph] */ inner class FeaturesView(defaultState: FeatureState) { val state: MutableMap<PackageFeature, FeatureState> = hashMapOf() init { for (feature in featureToNode.keys) { state[feature] = defaultState } } fun enableAll(features: Iterable<PackageFeature>) { for (feature in features) { enable(feature) } } fun disableAll(features: Iterable<PackageFeature>) { for (feature in features) { disable(feature) } } fun enable(feature: PackageFeature) { val node = featureToNode[feature] ?: return enableFeatureTransitively(node) } fun disable(feature: PackageFeature) { val node = featureToNode[feature] ?: return disableFeatureTransitively(node) } private fun enableFeatureTransitively(node: FeatureNode) { if (state[node.data] == FeatureState.Enabled) return state[node.data] = FeatureState.Enabled for (edge in graph.incomingEdges(node)) { val dependency = edge.source enableFeatureTransitively(dependency) } } private fun disableFeatureTransitively(node: FeatureNode) { if (state[node.data] == FeatureState.Disabled) return state[node.data] = FeatureState.Disabled for (edge in graph.outgoingEdges(node)) { val dependant = edge.target disableFeatureTransitively(dependant) } } } companion object { fun buildFor(features: Map<PackageFeature, List<PackageFeature>>): FeatureGraph { val graph = FeaturesGraphInner() val featureToNode = hashMapOf<PackageFeature, FeatureNode>() fun addFeatureIfNeeded(feature: PackageFeature) { if (feature in featureToNode) return val newNode = graph.addNode(feature) featureToNode[feature] = newNode } // Add nodes for (feature in features.keys) { addFeatureIfNeeded(feature) } // Add edges for ((feature, dependencies) in features) { val targetNode = featureToNode[feature] ?: if (isUnitTestMode) error("Unknown feature $feature") else continue for (dependency in dependencies) { val sourceNode = featureToNode[dependency] ?: if (isUnitTestMode) error("Unknown feature $dependency (dependency of $feature)") else continue graph.addEdge(sourceNode, targetNode, Unit) } } return FeatureGraph(graph, featureToNode) } val Empty: FeatureGraph get() = FeatureGraph(FeaturesGraphInner(), emptyMap()) } } fun Map<PackageFeature, FeatureState>.associateByPackageRoot(): Map<PackageRoot, Map<FeatureName, FeatureState>> { val map: MutableMap<PackageRoot, MutableMap<String, FeatureState>> = hashMapOf() for ((feature, state) in this) { map.getOrPut(feature.pkg.rootDirectory) { hashMapOf() }[feature.name] = state } return map }
mit
7609205bdfe1291f653046c571223bb5
33.808333
122
0.614316
4.931523
false
false
false
false
deva666/anko
anko/library/generated/sdk15-coroutines/src/ListenersWithCoroutines.kt
2
31669
@file:JvmName("Sdk15CoroutinesListenersWithCoroutinesKt") package org.jetbrains.anko.sdk15.coroutines import kotlin.coroutines.experimental.CoroutineContext import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.CoroutineScope import kotlinx.coroutines.experimental.launch fun android.view.View.onLayoutChange( context: CoroutineContext = UI, handler: suspend CoroutineScope.(v: android.view.View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) -> Unit ) { addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom -> launch(context) { handler(v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) } } } fun android.view.View.onAttachStateChangeListener( context: CoroutineContext = UI, init: __View_OnAttachStateChangeListener.() -> Unit ) { val listener = __View_OnAttachStateChangeListener(context) listener.init() addOnAttachStateChangeListener(listener) } class __View_OnAttachStateChangeListener(private val context: CoroutineContext) : android.view.View.OnAttachStateChangeListener { private var _onViewAttachedToWindow: (suspend CoroutineScope.(android.view.View) -> Unit)? = null override fun onViewAttachedToWindow(v: android.view.View) { val handler = _onViewAttachedToWindow ?: return launch(context) { handler(v) } } fun onViewAttachedToWindow( listener: suspend CoroutineScope.(android.view.View) -> Unit ) { _onViewAttachedToWindow = listener } private var _onViewDetachedFromWindow: (suspend CoroutineScope.(android.view.View) -> Unit)? = null override fun onViewDetachedFromWindow(v: android.view.View) { val handler = _onViewDetachedFromWindow ?: return launch(context) { handler(v) } } fun onViewDetachedFromWindow( listener: suspend CoroutineScope.(android.view.View) -> Unit ) { _onViewDetachedFromWindow = listener } }fun android.widget.TextView.textChangedListener( context: CoroutineContext = UI, init: __TextWatcher.() -> Unit ) { val listener = __TextWatcher(context) listener.init() addTextChangedListener(listener) } class __TextWatcher(private val context: CoroutineContext) : android.text.TextWatcher { private var _beforeTextChanged: (suspend CoroutineScope.(CharSequence?, Int, Int, Int) -> Unit)? = null override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { val handler = _beforeTextChanged ?: return launch(context) { handler(s, start, count, after) } } fun beforeTextChanged( listener: suspend CoroutineScope.(CharSequence?, Int, Int, Int) -> Unit ) { _beforeTextChanged = listener } private var _onTextChanged: (suspend CoroutineScope.(CharSequence?, Int, Int, Int) -> Unit)? = null override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { val handler = _onTextChanged ?: return launch(context) { handler(s, start, before, count) } } fun onTextChanged( listener: suspend CoroutineScope.(CharSequence?, Int, Int, Int) -> Unit ) { _onTextChanged = listener } private var _afterTextChanged: (suspend CoroutineScope.(android.text.Editable?) -> Unit)? = null override fun afterTextChanged(s: android.text.Editable?) { val handler = _afterTextChanged ?: return launch(context) { handler(s) } } fun afterTextChanged( listener: suspend CoroutineScope.(android.text.Editable?) -> Unit ) { _afterTextChanged = listener } }fun android.gesture.GestureOverlayView.onGestureListener( context: CoroutineContext = UI, init: __GestureOverlayView_OnGestureListener.() -> Unit ) { val listener = __GestureOverlayView_OnGestureListener(context) listener.init() addOnGestureListener(listener) } class __GestureOverlayView_OnGestureListener(private val context: CoroutineContext) : android.gesture.GestureOverlayView.OnGestureListener { private var _onGestureStarted: (suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null override fun onGestureStarted(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) { val handler = _onGestureStarted ?: return launch(context) { handler(overlay, event) } } fun onGestureStarted( listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit ) { _onGestureStarted = listener } private var _onGesture: (suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null override fun onGesture(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) { val handler = _onGesture ?: return launch(context) { handler(overlay, event) } } fun onGesture( listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit ) { _onGesture = listener } private var _onGestureEnded: (suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null override fun onGestureEnded(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) { val handler = _onGestureEnded ?: return launch(context) { handler(overlay, event) } } fun onGestureEnded( listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit ) { _onGestureEnded = listener } private var _onGestureCancelled: (suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null override fun onGestureCancelled(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) { val handler = _onGestureCancelled ?: return launch(context) { handler(overlay, event) } } fun onGestureCancelled( listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit ) { _onGestureCancelled = listener } }fun android.gesture.GestureOverlayView.onGesturePerformed( context: CoroutineContext = UI, handler: suspend CoroutineScope.(overlay: android.gesture.GestureOverlayView?, gesture: android.gesture.Gesture?) -> Unit ) { addOnGesturePerformedListener { overlay, gesture -> launch(context) { handler(overlay, gesture) } } } fun android.gesture.GestureOverlayView.onGesturingListener( context: CoroutineContext = UI, init: __GestureOverlayView_OnGesturingListener.() -> Unit ) { val listener = __GestureOverlayView_OnGesturingListener(context) listener.init() addOnGesturingListener(listener) } class __GestureOverlayView_OnGesturingListener(private val context: CoroutineContext) : android.gesture.GestureOverlayView.OnGesturingListener { private var _onGesturingStarted: (suspend CoroutineScope.(android.gesture.GestureOverlayView?) -> Unit)? = null override fun onGesturingStarted(overlay: android.gesture.GestureOverlayView?) { val handler = _onGesturingStarted ?: return launch(context) { handler(overlay) } } fun onGesturingStarted( listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?) -> Unit ) { _onGesturingStarted = listener } private var _onGesturingEnded: (suspend CoroutineScope.(android.gesture.GestureOverlayView?) -> Unit)? = null override fun onGesturingEnded(overlay: android.gesture.GestureOverlayView?) { val handler = _onGesturingEnded ?: return launch(context) { handler(overlay) } } fun onGesturingEnded( listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?) -> Unit ) { _onGesturingEnded = listener } }fun android.view.View.onClick( context: CoroutineContext = UI, handler: suspend CoroutineScope.(v: android.view.View?) -> Unit ) { setOnClickListener { v -> launch(context) { handler(v) } } } fun android.view.View.onCreateContextMenu( context: CoroutineContext = UI, handler: suspend CoroutineScope.(menu: android.view.ContextMenu?, v: android.view.View?, menuInfo: android.view.ContextMenu.ContextMenuInfo?) -> Unit ) { setOnCreateContextMenuListener { menu, v, menuInfo -> launch(context) { handler(menu, v, menuInfo) } } } fun android.view.View.onDrag( context: CoroutineContext = UI, returnValue: Boolean = false, handler: suspend CoroutineScope.(v: android.view.View, event: android.view.DragEvent) -> Unit ) { setOnDragListener { v, event -> launch(context) { handler(v, event) } returnValue } } fun android.view.View.onFocusChange( context: CoroutineContext = UI, handler: suspend CoroutineScope.(v: android.view.View, hasFocus: Boolean) -> Unit ) { setOnFocusChangeListener { v, hasFocus -> launch(context) { handler(v, hasFocus) } } } fun android.view.View.onGenericMotion( context: CoroutineContext = UI, returnValue: Boolean = false, handler: suspend CoroutineScope.(v: android.view.View, event: android.view.MotionEvent) -> Unit ) { setOnGenericMotionListener { v, event -> launch(context) { handler(v, event) } returnValue } } fun android.view.View.onHover( context: CoroutineContext = UI, returnValue: Boolean = false, handler: suspend CoroutineScope.(v: android.view.View, event: android.view.MotionEvent) -> Unit ) { setOnHoverListener { v, event -> launch(context) { handler(v, event) } returnValue } } fun android.view.View.onKey( context: CoroutineContext = UI, returnValue: Boolean = false, handler: suspend CoroutineScope.(v: android.view.View, keyCode: Int, event: android.view.KeyEvent?) -> Unit ) { setOnKeyListener { v, keyCode, event -> launch(context) { handler(v, keyCode, event) } returnValue } } fun android.view.View.onLongClick( context: CoroutineContext = UI, returnValue: Boolean = false, handler: suspend CoroutineScope.(v: android.view.View?) -> Unit ) { setOnLongClickListener { v -> launch(context) { handler(v) } returnValue } } fun android.view.View.onSystemUiVisibilityChange( context: CoroutineContext = UI, handler: suspend CoroutineScope.(visibility: Int) -> Unit ) { setOnSystemUiVisibilityChangeListener { visibility -> launch(context) { handler(visibility) } } } fun android.view.View.onTouch( context: CoroutineContext = UI, returnValue: Boolean = false, handler: suspend CoroutineScope.(v: android.view.View, event: android.view.MotionEvent) -> Unit ) { setOnTouchListener { v, event -> launch(context) { handler(v, event) } returnValue } } fun android.view.ViewGroup.onHierarchyChangeListener( context: CoroutineContext = UI, init: __ViewGroup_OnHierarchyChangeListener.() -> Unit ) { val listener = __ViewGroup_OnHierarchyChangeListener(context) listener.init() setOnHierarchyChangeListener(listener) } class __ViewGroup_OnHierarchyChangeListener(private val context: CoroutineContext) : android.view.ViewGroup.OnHierarchyChangeListener { private var _onChildViewAdded: (suspend CoroutineScope.(android.view.View?, android.view.View?) -> Unit)? = null override fun onChildViewAdded(parent: android.view.View?, child: android.view.View?) { val handler = _onChildViewAdded ?: return launch(context) { handler(parent, child) } } fun onChildViewAdded( listener: suspend CoroutineScope.(android.view.View?, android.view.View?) -> Unit ) { _onChildViewAdded = listener } private var _onChildViewRemoved: (suspend CoroutineScope.(android.view.View?, android.view.View?) -> Unit)? = null override fun onChildViewRemoved(parent: android.view.View?, child: android.view.View?) { val handler = _onChildViewRemoved ?: return launch(context) { handler(parent, child) } } fun onChildViewRemoved( listener: suspend CoroutineScope.(android.view.View?, android.view.View?) -> Unit ) { _onChildViewRemoved = listener } }fun android.view.ViewStub.onInflate( context: CoroutineContext = UI, handler: suspend CoroutineScope.(stub: android.view.ViewStub?, inflated: android.view.View?) -> Unit ) { setOnInflateListener { stub, inflated -> launch(context) { handler(stub, inflated) } } } fun android.widget.AbsListView.onScrollListener( context: CoroutineContext = UI, init: __AbsListView_OnScrollListener.() -> Unit ) { val listener = __AbsListView_OnScrollListener(context) listener.init() setOnScrollListener(listener) } class __AbsListView_OnScrollListener(private val context: CoroutineContext) : android.widget.AbsListView.OnScrollListener { private var _onScrollStateChanged: (suspend CoroutineScope.(android.widget.AbsListView?, Int) -> Unit)? = null override fun onScrollStateChanged(view: android.widget.AbsListView?, scrollState: Int) { val handler = _onScrollStateChanged ?: return launch(context) { handler(view, scrollState) } } fun onScrollStateChanged( listener: suspend CoroutineScope.(android.widget.AbsListView?, Int) -> Unit ) { _onScrollStateChanged = listener } private var _onScroll: (suspend CoroutineScope.(android.widget.AbsListView?, Int, Int, Int) -> Unit)? = null override fun onScroll(view: android.widget.AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) { val handler = _onScroll ?: return launch(context) { handler(view, firstVisibleItem, visibleItemCount, totalItemCount) } } fun onScroll( listener: suspend CoroutineScope.(android.widget.AbsListView?, Int, Int, Int) -> Unit ) { _onScroll = listener } }fun android.widget.AdapterView<out android.widget.Adapter>.onItemClick( context: CoroutineContext = UI, handler: suspend CoroutineScope.(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit ) { setOnItemClickListener { p0, p1, p2, p3 -> launch(context) { handler(p0, p1, p2, p3) } } } fun android.widget.AdapterView<out android.widget.Adapter>.onItemLongClick( context: CoroutineContext = UI, returnValue: Boolean = false, handler: suspend CoroutineScope.(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit ) { setOnItemLongClickListener { p0, p1, p2, p3 -> launch(context) { handler(p0, p1, p2, p3) } returnValue } } fun android.widget.AdapterView<out android.widget.Adapter>.onItemSelectedListener( context: CoroutineContext = UI, init: __AdapterView_OnItemSelectedListener.() -> Unit ) { val listener = __AdapterView_OnItemSelectedListener(context) listener.init() setOnItemSelectedListener(listener) } class __AdapterView_OnItemSelectedListener(private val context: CoroutineContext) : android.widget.AdapterView.OnItemSelectedListener { private var _onItemSelected: (suspend CoroutineScope.(android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit)? = null override fun onItemSelected(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) { val handler = _onItemSelected ?: return launch(context) { handler(p0, p1, p2, p3) } } fun onItemSelected( listener: suspend CoroutineScope.(android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit ) { _onItemSelected = listener } private var _onNothingSelected: (suspend CoroutineScope.(android.widget.AdapterView<*>?) -> Unit)? = null override fun onNothingSelected(p0: android.widget.AdapterView<*>?) { val handler = _onNothingSelected ?: return launch(context) { handler(p0) } } fun onNothingSelected( listener: suspend CoroutineScope.(android.widget.AdapterView<*>?) -> Unit ) { _onNothingSelected = listener } }fun android.widget.CalendarView.onDateChange( context: CoroutineContext = UI, handler: suspend CoroutineScope.(view: android.widget.CalendarView?, year: Int, month: Int, dayOfMonth: Int) -> Unit ) { setOnDateChangeListener { view, year, month, dayOfMonth -> launch(context) { handler(view, year, month, dayOfMonth) } } } fun android.widget.Chronometer.onChronometerTick( context: CoroutineContext = UI, handler: suspend CoroutineScope.(chronometer: android.widget.Chronometer?) -> Unit ) { setOnChronometerTickListener { chronometer -> launch(context) { handler(chronometer) } } } fun android.widget.CompoundButton.onCheckedChange( context: CoroutineContext = UI, handler: suspend CoroutineScope.(buttonView: android.widget.CompoundButton?, isChecked: Boolean) -> Unit ) { setOnCheckedChangeListener { buttonView, isChecked -> launch(context) { handler(buttonView, isChecked) } } } fun android.widget.ExpandableListView.onChildClick( context: CoroutineContext = UI, returnValue: Boolean = false, handler: suspend CoroutineScope.(parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, childPosition: Int, id: Long) -> Unit ) { setOnChildClickListener { parent, v, groupPosition, childPosition, id -> launch(context) { handler(parent, v, groupPosition, childPosition, id) } returnValue } } fun android.widget.ExpandableListView.onGroupClick( context: CoroutineContext = UI, returnValue: Boolean = false, handler: suspend CoroutineScope.(parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, id: Long) -> Unit ) { setOnGroupClickListener { parent, v, groupPosition, id -> launch(context) { handler(parent, v, groupPosition, id) } returnValue } } fun android.widget.ExpandableListView.onGroupCollapse( context: CoroutineContext = UI, handler: suspend CoroutineScope.(groupPosition: Int) -> Unit ) { setOnGroupCollapseListener { groupPosition -> launch(context) { handler(groupPosition) } } } fun android.widget.ExpandableListView.onGroupExpand( context: CoroutineContext = UI, handler: suspend CoroutineScope.(groupPosition: Int) -> Unit ) { setOnGroupExpandListener { groupPosition -> launch(context) { handler(groupPosition) } } } fun android.widget.NumberPicker.onScroll( context: CoroutineContext = UI, handler: suspend CoroutineScope.(view: android.widget.NumberPicker?, scrollState: Int) -> Unit ) { setOnScrollListener { view, scrollState -> launch(context) { handler(view, scrollState) } } } fun android.widget.NumberPicker.onValueChanged( context: CoroutineContext = UI, handler: suspend CoroutineScope.(picker: android.widget.NumberPicker?, oldVal: Int, newVal: Int) -> Unit ) { setOnValueChangedListener { picker, oldVal, newVal -> launch(context) { handler(picker, oldVal, newVal) } } } fun android.widget.RadioGroup.onCheckedChange( context: CoroutineContext = UI, handler: suspend CoroutineScope.(group: android.widget.RadioGroup?, checkedId: Int) -> Unit ) { setOnCheckedChangeListener { group, checkedId -> launch(context) { handler(group, checkedId) } } } fun android.widget.RatingBar.onRatingBarChange( context: CoroutineContext = UI, handler: suspend CoroutineScope.(ratingBar: android.widget.RatingBar?, rating: Float, fromUser: Boolean) -> Unit ) { setOnRatingBarChangeListener { ratingBar, rating, fromUser -> launch(context) { handler(ratingBar, rating, fromUser) } } } fun android.widget.SearchView.onClose( context: CoroutineContext = UI, returnValue: Boolean = false, handler: suspend CoroutineScope.() -> Unit ) { setOnCloseListener { -> launch(context, block = handler) returnValue } } fun android.widget.SearchView.onQueryTextFocusChange( context: CoroutineContext = UI, handler: suspend CoroutineScope.(v: android.view.View, hasFocus: Boolean) -> Unit ) { setOnQueryTextFocusChangeListener { v, hasFocus -> launch(context) { handler(v, hasFocus) } } } fun android.widget.SearchView.onQueryTextListener( context: CoroutineContext = UI, init: __SearchView_OnQueryTextListener.() -> Unit ) { val listener = __SearchView_OnQueryTextListener(context) listener.init() setOnQueryTextListener(listener) } class __SearchView_OnQueryTextListener(private val context: CoroutineContext) : android.widget.SearchView.OnQueryTextListener { private var _onQueryTextSubmit: (suspend CoroutineScope.(String?) -> Boolean)? = null private var _onQueryTextSubmit_returnValue: Boolean = false override fun onQueryTextSubmit(query: String?) : Boolean { val returnValue = _onQueryTextSubmit_returnValue val handler = _onQueryTextSubmit ?: return returnValue launch(context) { handler(query) } return returnValue } fun onQueryTextSubmit( returnValue: Boolean = false, listener: suspend CoroutineScope.(String?) -> Boolean ) { _onQueryTextSubmit = listener _onQueryTextSubmit_returnValue = returnValue } private var _onQueryTextChange: (suspend CoroutineScope.(String?) -> Boolean)? = null private var _onQueryTextChange_returnValue: Boolean = false override fun onQueryTextChange(newText: String?) : Boolean { val returnValue = _onQueryTextChange_returnValue val handler = _onQueryTextChange ?: return returnValue launch(context) { handler(newText) } return returnValue } fun onQueryTextChange( returnValue: Boolean = false, listener: suspend CoroutineScope.(String?) -> Boolean ) { _onQueryTextChange = listener _onQueryTextChange_returnValue = returnValue } }fun android.widget.SearchView.onSearchClick( context: CoroutineContext = UI, handler: suspend CoroutineScope.(v: android.view.View?) -> Unit ) { setOnSearchClickListener { v -> launch(context) { handler(v) } } } fun android.widget.SearchView.onSuggestionListener( context: CoroutineContext = UI, init: __SearchView_OnSuggestionListener.() -> Unit ) { val listener = __SearchView_OnSuggestionListener(context) listener.init() setOnSuggestionListener(listener) } class __SearchView_OnSuggestionListener(private val context: CoroutineContext) : android.widget.SearchView.OnSuggestionListener { private var _onSuggestionSelect: (suspend CoroutineScope.(Int) -> Boolean)? = null private var _onSuggestionSelect_returnValue: Boolean = false override fun onSuggestionSelect(position: Int) : Boolean { val returnValue = _onSuggestionSelect_returnValue val handler = _onSuggestionSelect ?: return returnValue launch(context) { handler(position) } return returnValue } fun onSuggestionSelect( returnValue: Boolean = false, listener: suspend CoroutineScope.(Int) -> Boolean ) { _onSuggestionSelect = listener _onSuggestionSelect_returnValue = returnValue } private var _onSuggestionClick: (suspend CoroutineScope.(Int) -> Boolean)? = null private var _onSuggestionClick_returnValue: Boolean = false override fun onSuggestionClick(position: Int) : Boolean { val returnValue = _onSuggestionClick_returnValue val handler = _onSuggestionClick ?: return returnValue launch(context) { handler(position) } return returnValue } fun onSuggestionClick( returnValue: Boolean = false, listener: suspend CoroutineScope.(Int) -> Boolean ) { _onSuggestionClick = listener _onSuggestionClick_returnValue = returnValue } }fun android.widget.SeekBar.onSeekBarChangeListener( context: CoroutineContext = UI, init: __SeekBar_OnSeekBarChangeListener.() -> Unit ) { val listener = __SeekBar_OnSeekBarChangeListener(context) listener.init() setOnSeekBarChangeListener(listener) } class __SeekBar_OnSeekBarChangeListener(private val context: CoroutineContext) : android.widget.SeekBar.OnSeekBarChangeListener { private var _onProgressChanged: (suspend CoroutineScope.(android.widget.SeekBar?, Int, Boolean) -> Unit)? = null override fun onProgressChanged(seekBar: android.widget.SeekBar?, progress: Int, fromUser: Boolean) { val handler = _onProgressChanged ?: return launch(context) { handler(seekBar, progress, fromUser) } } fun onProgressChanged( listener: suspend CoroutineScope.(android.widget.SeekBar?, Int, Boolean) -> Unit ) { _onProgressChanged = listener } private var _onStartTrackingTouch: (suspend CoroutineScope.(android.widget.SeekBar?) -> Unit)? = null override fun onStartTrackingTouch(seekBar: android.widget.SeekBar?) { val handler = _onStartTrackingTouch ?: return launch(context) { handler(seekBar) } } fun onStartTrackingTouch( listener: suspend CoroutineScope.(android.widget.SeekBar?) -> Unit ) { _onStartTrackingTouch = listener } private var _onStopTrackingTouch: (suspend CoroutineScope.(android.widget.SeekBar?) -> Unit)? = null override fun onStopTrackingTouch(seekBar: android.widget.SeekBar?) { val handler = _onStopTrackingTouch ?: return launch(context) { handler(seekBar) } } fun onStopTrackingTouch( listener: suspend CoroutineScope.(android.widget.SeekBar?) -> Unit ) { _onStopTrackingTouch = listener } }fun android.widget.SlidingDrawer.onDrawerClose( context: CoroutineContext = UI, handler: suspend CoroutineScope.() -> Unit ) { setOnDrawerCloseListener { -> launch(context, block = handler) } } fun android.widget.SlidingDrawer.onDrawerOpen( context: CoroutineContext = UI, handler: suspend CoroutineScope.() -> Unit ) { setOnDrawerOpenListener { -> launch(context, block = handler) } } fun android.widget.SlidingDrawer.onDrawerScrollListener( context: CoroutineContext = UI, init: __SlidingDrawer_OnDrawerScrollListener.() -> Unit ) { val listener = __SlidingDrawer_OnDrawerScrollListener(context) listener.init() setOnDrawerScrollListener(listener) } class __SlidingDrawer_OnDrawerScrollListener(private val context: CoroutineContext) : android.widget.SlidingDrawer.OnDrawerScrollListener { private var _onScrollStarted: (suspend CoroutineScope.() -> Unit)? = null override fun onScrollStarted() { val handler = _onScrollStarted ?: return launch(context, block = handler) } fun onScrollStarted( listener: suspend CoroutineScope.() -> Unit ) { _onScrollStarted = listener } private var _onScrollEnded: (suspend CoroutineScope.() -> Unit)? = null override fun onScrollEnded() { val handler = _onScrollEnded ?: return launch(context, block = handler) } fun onScrollEnded( listener: suspend CoroutineScope.() -> Unit ) { _onScrollEnded = listener } }fun android.widget.TabHost.onTabChanged( context: CoroutineContext = UI, handler: suspend CoroutineScope.(tabId: String?) -> Unit ) { setOnTabChangedListener { tabId -> launch(context) { handler(tabId) } } } fun android.widget.TextView.onEditorAction( context: CoroutineContext = UI, returnValue: Boolean = false, handler: suspend CoroutineScope.(v: android.widget.TextView?, actionId: Int, event: android.view.KeyEvent?) -> Unit ) { setOnEditorActionListener { v, actionId, event -> launch(context) { handler(v, actionId, event) } returnValue } } fun android.widget.TimePicker.onTimeChanged( context: CoroutineContext = UI, handler: suspend CoroutineScope.(view: android.widget.TimePicker?, hourOfDay: Int, minute: Int) -> Unit ) { setOnTimeChangedListener { view, hourOfDay, minute -> launch(context) { handler(view, hourOfDay, minute) } } } fun android.widget.VideoView.onCompletion( context: CoroutineContext = UI, handler: suspend CoroutineScope.(mp: android.media.MediaPlayer?) -> Unit ) { setOnCompletionListener { mp -> launch(context) { handler(mp) } } } fun android.widget.VideoView.onError( context: CoroutineContext = UI, returnValue: Boolean = false, handler: suspend CoroutineScope.(mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Unit ) { setOnErrorListener { mp, what, extra -> launch(context) { handler(mp, what, extra) } returnValue } } fun android.widget.VideoView.onPrepared( context: CoroutineContext = UI, handler: suspend CoroutineScope.(mp: android.media.MediaPlayer?) -> Unit ) { setOnPreparedListener { mp -> launch(context) { handler(mp) } } } fun android.widget.ZoomControls.onZoomInClick( context: CoroutineContext = UI, handler: suspend CoroutineScope.(v: android.view.View?) -> Unit ) { setOnZoomInClickListener { v -> launch(context) { handler(v) } } } fun android.widget.ZoomControls.onZoomOutClick( context: CoroutineContext = UI, handler: suspend CoroutineScope.(v: android.view.View?) -> Unit ) { setOnZoomOutClickListener { v -> launch(context) { handler(v) } } }
apache-2.0
585099fb2c9f9fc1f749f5b397e11df1
30.511443
175
0.655973
4.922132
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/tasks/TeamBoardFragment.kt
1
17205
package com.habitrpg.android.habitica.ui.fragments.tasks import android.app.Activity import android.content.Intent import android.graphics.PorterDuff import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.widget.SearchView import androidx.core.content.ContextCompat import androidx.core.os.bundleOf import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.TagRepository import com.habitrpg.android.habitica.databinding.FragmentViewpagerBinding import com.habitrpg.android.habitica.extensions.getThemeColor import com.habitrpg.android.habitica.extensions.setTintWith import com.habitrpg.android.habitica.helpers.AmplitudeManager import com.habitrpg.android.habitica.helpers.AppConfigManager import com.habitrpg.android.habitica.helpers.MainNavigationController import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.helpers.TaskFilterHelper import com.habitrpg.android.habitica.models.tasks.TaskType import com.habitrpg.android.habitica.ui.activities.TaskFormActivity import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment import com.habitrpg.android.habitica.ui.views.navigation.HabiticaBottomNavigationViewListener import com.habitrpg.android.habitica.ui.views.tasks.TaskFilterDialog import io.reactivex.rxjava3.disposables.Disposable import java.util.Date import java.util.WeakHashMap import javax.inject.Inject class TeamBoardFragment : BaseMainFragment<FragmentViewpagerBinding>(), SearchView.OnQueryTextListener, HabiticaBottomNavigationViewListener { override var binding: FragmentViewpagerBinding? = null override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentViewpagerBinding { return FragmentViewpagerBinding.inflate(inflater, container, false) } var teamID: String = "" @Inject lateinit var taskFilterHelper: TaskFilterHelper @Inject lateinit var tagRepository: TagRepository @Inject lateinit var appConfigManager: AppConfigManager private var refreshItem: MenuItem? = null internal var viewFragmentsDictionary: MutableMap<Int, TaskRecyclerViewFragment>? = WeakHashMap() private var filterMenuItem: MenuItem? = null private val activeFragment: TaskRecyclerViewFragment? get() { var fragment = viewFragmentsDictionary?.get(binding?.viewPager?.currentItem) if (fragment == null) { if (isAdded) { fragment = (childFragmentManager.findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + binding?.viewPager?.currentItem) as? TaskRecyclerViewFragment) } } return fragment } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { this.usesTabLayout = false this.hidesToolbar = true this.usesBottomNavigation = true return super.onCreateView(inflater, container, savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) arguments?.let { val args = TeamBoardFragmentArgs.fromBundle(it) teamID = args.teamID } compositeSubscription.add( userRepository.getTeamPlan(teamID) .subscribe( { activity?.title = it.name }, RxErrorHandler.handleEmptyError() ) ) compositeSubscription.add(userRepository.retrieveTeamPlan(teamID).subscribe({ }, RxErrorHandler.handleEmptyError())) loadTaskLists() } override fun onResume() { super.onResume() bottomNavigation?.activeTaskType = when (binding?.viewPager?.currentItem) { 0 -> TaskType.HABIT 1 -> TaskType.DAILY 2 -> TaskType.TODO 3 -> TaskType.REWARD else -> TaskType.HABIT } bottomNavigation?.listener = this bottomNavigation?.canAddTasks = false } override fun onPause() { if (bottomNavigation?.listener == this) { bottomNavigation?.listener = null } super.onPause() } override fun onDestroy() { tagRepository.close() super.onDestroy() } override fun injectFragment(component: UserComponent) { component.inject(this) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_team_board, menu) filterMenuItem = menu.findItem(R.id.action_filter) updateFilterIcon() val item = menu.findItem(R.id.action_search) tintMenuIcon(item) val sv = item.actionView as? SearchView sv?.setOnQueryTextListener(this) sv?.setIconifiedByDefault(false) item.setOnActionExpandListener(object : MenuItem.OnActionExpandListener { override fun onMenuItemActionCollapse(item: MenuItem): Boolean { filterMenuItem?.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) return true } override fun onMenuItemActionExpand(item: MenuItem): Boolean { // Do something when expanded filterMenuItem?.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER) return true } }) } override fun onQueryTextSubmit(query: String?): Boolean { return true } override fun onQueryTextChange(newText: String?): Boolean { taskFilterHelper.searchQuery = newText viewFragmentsDictionary?.values?.forEach { values -> values.recyclerAdapter?.filter() } return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_filter -> { showFilterDialog() true } R.id.action_reload -> { refreshItem = item refresh() true } R.id.action_team_info -> { MainNavigationController.navigate(R.id.guildFragment, bundleOf(Pair("groupID", teamID))) true } else -> super.onOptionsItemSelected(item) } } private fun showFilterDialog() { context?.let { val disposable: Disposable val dialog = TaskFilterDialog(it, HabiticaBaseApplication.userComponent) disposable = tagRepository.getTags().subscribe({ tagsList -> dialog.setTags(tagsList) }, RxErrorHandler.handleEmptyError()) dialog.setActiveTags(taskFilterHelper.tags) if (activeFragment != null) { val taskType = activeFragment?.taskType if (taskType != null) { dialog.setTaskType(taskType, taskFilterHelper.getActiveFilter(taskType)) } } dialog.setListener(object : TaskFilterDialog.OnFilterCompletedListener { override fun onFilterCompleted(activeTaskFilter: String?, activeTags: MutableList<String>) { if (viewFragmentsDictionary == null) { return } taskFilterHelper.tags = activeTags if (activeTaskFilter != null) { activeFragment?.setActiveFilter(activeTaskFilter) } viewFragmentsDictionary?.values?.forEach { values -> values.recyclerAdapter?.filter() } updateFilterIcon() } }) dialog.setOnDismissListener { if (!disposable.isDisposed) { disposable.dispose() } } dialog.show() } } private fun refresh() { activeFragment?.onRefresh() } private fun loadTaskLists() { val fragmentManager = childFragmentManager binding?.viewPager?.adapter = object : FragmentStateAdapter(fragmentManager, lifecycle) { override fun createFragment(position: Int): androidx.fragment.app.Fragment { val fragment: TaskRecyclerViewFragment = when (position) { 0 -> TaskRecyclerViewFragment.newInstance(context, TaskType.HABIT) 1 -> TaskRecyclerViewFragment.newInstance(context, TaskType.DAILY) 3 -> RewardsRecyclerviewFragment.newInstance(context, TaskType.REWARD, false) else -> TaskRecyclerViewFragment.newInstance(context, TaskType.TODO) } fragment.canEditTasks = false fragment.canScoreTaks = false fragment.refreshAction = { compositeSubscription.add( userRepository.retrieveTeamPlan(teamID) .doOnTerminate { it() }.subscribe({ }, RxErrorHandler.handleEmptyError()) ) } viewFragmentsDictionary?.put(position, fragment) return fragment } override fun getItemCount(): Int = 4 } binding?.viewPager?.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { bottomNavigation?.selectedPosition = position updateFilterIcon() } }) } private fun updateFilterIcon() { if (filterMenuItem == null) { return } var filterCount = 0 if (activeFragment != null) { filterCount = taskFilterHelper.howMany(activeFragment?.taskType) } if (filterCount == 0) { filterMenuItem?.setIcon(R.drawable.ic_action_filter_list) context?.let { val filterIcon = ContextCompat.getDrawable(it, R.drawable.ic_action_filter_list) filterIcon?.setTintWith(it.getThemeColor(R.attr.headerTextColor), PorterDuff.Mode.MULTIPLY) filterMenuItem?.setIcon(filterIcon) } } else { context?.let { val filterIcon = ContextCompat.getDrawable(it, R.drawable.ic_filters_active) filterIcon?.setTintWith(it.getThemeColor(R.attr.textColorPrimaryDark), PorterDuff.Mode.MULTIPLY) filterMenuItem?.setIcon(filterIcon) } } } private fun updateBottomBarBadges() { if (bottomNavigation == null) { return } compositeSubscription.add( tutorialRepository.getTutorialSteps(listOf("habits", "dailies", "todos", "rewards")).subscribe( { tutorialSteps -> val activeTutorialFragments = ArrayList<TaskType>() for (step in tutorialSteps) { var id = -1 val taskType = when (step.identifier) { "habits" -> { id = R.id.habits_tab TaskType.HABIT } "dailies" -> { id = R.id.dailies_tab TaskType.DAILY } "todos" -> { id = R.id.todos_tab TaskType.TODO } "rewards" -> { id = R.id.rewards_tab TaskType.REWARD } else -> TaskType.HABIT } val tab = bottomNavigation?.tabWithId(id) if (step.shouldDisplay()) { tab?.badgeCount = 1 activeTutorialFragments.add(taskType) } else { tab?.badgeCount = 0 } } if (activeTutorialFragments.size == 1) { val fragment = viewFragmentsDictionary?.get(indexForTaskType(activeTutorialFragments[0])) if (fragment?.tutorialTexts != null && context != null) { val finalText = context?.getString(R.string.tutorial_tasks_complete) if (!fragment.tutorialTexts.contains(finalText) && finalText != null) { fragment.tutorialTexts.add(finalText) } } } }, RxErrorHandler.handleEmptyError() ) ) } // endregion private fun openNewTaskActivity(type: TaskType) { if (Date().time - (lastTaskFormOpen?.time ?: 0) < 2000) { return } val additionalData = HashMap<String, Any>() additionalData["created task type"] = type additionalData["viewed task type"] = when (binding?.viewPager?.currentItem) { 0 -> TaskType.HABIT 1 -> TaskType.DAILY 2 -> TaskType.TODO 3 -> TaskType.REWARD else -> "" } AmplitudeManager.sendEvent("open create task form", AmplitudeManager.EVENT_CATEGORY_BEHAVIOUR, AmplitudeManager.EVENT_HITTYPE_EVENT, additionalData) val bundle = Bundle() bundle.putString(TaskFormActivity.TASK_TYPE_KEY, type.value) bundle.putStringArrayList(TaskFormActivity.SELECTED_TAGS_KEY, ArrayList(taskFilterHelper.tags)) val intent = Intent(activity, TaskFormActivity::class.java) intent.putExtras(bundle) intent.flags = Intent.FLAG_ACTIVITY_REORDER_TO_FRONT if (this.isAdded) { lastTaskFormOpen = Date() taskCreatedResult.launch(intent) } } //endregion Events private val taskCreatedResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { onTaskCreatedResult(it.resultCode, it.data) } private fun onTaskCreatedResult(resultCode: Int, data: Intent?) { if (resultCode == Activity.RESULT_OK) { val taskTypeValue = data?.getStringExtra(TaskFormActivity.TASK_TYPE_KEY) if (taskTypeValue != null) { val taskType = TaskType.from(taskTypeValue) switchToTaskTab(taskType) val index = indexForTaskType(taskType) if (index != -1) { val fragment = viewFragmentsDictionary?.get(index) fragment?.binding?.recyclerView?.scrollToPosition(0) } } } } private fun switchToTaskTab(taskType: TaskType?) { val index = indexForTaskType(taskType) if (binding?.viewPager != null && index != -1) { binding?.viewPager?.currentItem = index updateBottomBarBadges() } } private fun indexForTaskType(taskType: TaskType?): Int { if (taskType != null) { for (index in 0 until (viewFragmentsDictionary?.size ?: 0)) { val fragment = viewFragmentsDictionary?.get(index) if (fragment != null && taskType == fragment.className) { return index } } } return -1 } override val displayedClassName: String? get() = null override fun addToBackStack(): Boolean = false companion object { var lastTaskFormOpen: Date? = null } override fun onTabSelected(taskType: TaskType, smooth: Boolean) { val newItem = when (taskType) { TaskType.HABIT -> 0 TaskType.DAILY -> 1 TaskType.TODO -> 2 TaskType.REWARD -> 3 else -> 0 } binding?.viewPager?.setCurrentItem(newItem, smooth) updateBottomBarBadges() } override fun onAdd(taskType: TaskType) { openNewTaskActivity(taskType) } }
gpl-3.0
f196451be7536677e31984ca917fd96d
36.925339
178
0.572973
5.60241
false
false
false
false
androidx/androidx
compose/material/material/src/commonMain/kotlin/androidx/compose/material/DragGestureDetectorCopy.kt
3
4420
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material // Copy-paste version of DragGestureDetector.kt. Please don't change this file without changing // DragGestureDetector.kt import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.pointer.AwaitPointerEventScope import androidx.compose.ui.input.pointer.PointerEvent import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerId import androidx.compose.ui.input.pointer.PointerInputChange import androidx.compose.ui.input.pointer.PointerType import androidx.compose.ui.input.pointer.changedToUpIgnoreConsumed import androidx.compose.ui.platform.ViewConfiguration import androidx.compose.ui.unit.dp import androidx.compose.ui.util.fastFirstOrNull import kotlin.math.abs import kotlin.math.sign internal suspend fun AwaitPointerEventScope.awaitHorizontalPointerSlopOrCancellation( pointerId: PointerId, pointerType: PointerType, onPointerSlopReached: (change: PointerInputChange, overSlop: Float) -> Unit ) = awaitPointerSlopOrCancellation( pointerId = pointerId, pointerType = pointerType, onPointerSlopReached = onPointerSlopReached, getDragDirectionValue = { it.x } ) private suspend inline fun AwaitPointerEventScope.awaitPointerSlopOrCancellation( pointerId: PointerId, pointerType: PointerType, onPointerSlopReached: (PointerInputChange, Float) -> Unit, getDragDirectionValue: (Offset) -> Float ): PointerInputChange? { if (currentEvent.isPointerUp(pointerId)) { return null // The pointer has already been lifted, so the gesture is canceled } val touchSlop = viewConfiguration.pointerSlop(pointerType) var pointer: PointerId = pointerId var totalPositionChange = 0f while (true) { val event = awaitPointerEvent() val dragEvent = event.changes.fastFirstOrNull { it.id == pointer }!! if (dragEvent.isConsumed) { return null } else if (dragEvent.changedToUpIgnoreConsumed()) { val otherDown = event.changes.fastFirstOrNull { it.pressed } if (otherDown == null) { // This is the last "up" return null } else { pointer = otherDown.id } } else { val currentPosition = dragEvent.position val previousPosition = dragEvent.previousPosition val positionChange = getDragDirectionValue(currentPosition) - getDragDirectionValue(previousPosition) totalPositionChange += positionChange val inDirection = abs(totalPositionChange) if (inDirection < touchSlop) { // verify that nothing else consumed the drag event awaitPointerEvent(PointerEventPass.Final) if (dragEvent.isConsumed) { return null } } else { onPointerSlopReached( dragEvent, totalPositionChange - (sign(totalPositionChange) * touchSlop) ) if (dragEvent.isConsumed) { return dragEvent } else { totalPositionChange = 0f } } } } } private fun PointerEvent.isPointerUp(pointerId: PointerId): Boolean = changes.fastFirstOrNull { it.id == pointerId }?.pressed != true private val mouseSlop = 0.125.dp private val defaultTouchSlop = 18.dp // The default touch slop on Android devices private val mouseToTouchSlopRatio = mouseSlop / defaultTouchSlop internal fun ViewConfiguration.pointerSlop(pointerType: PointerType): Float { return when (pointerType) { PointerType.Mouse -> touchSlop * mouseToTouchSlopRatio else -> touchSlop } }
apache-2.0
c5da066fedda37517eb670f5a771fb81
37.780702
95
0.688688
5.163551
false
false
false
false
pedroSG94/rtmp-rtsp-stream-client-java
rtplibrary/src/main/java/com/pedro/rtplibrary/view/GlStreamInterface.kt
1
7261
package com.pedro.rtplibrary.view import android.content.Context import android.graphics.Point import android.graphics.SurfaceTexture import android.graphics.SurfaceTexture.OnFrameAvailableListener import android.os.Build import android.view.Surface import androidx.annotation.RequiresApi import com.pedro.encoder.input.gl.FilterAction import com.pedro.encoder.input.gl.SurfaceManager import com.pedro.encoder.input.gl.render.MainRender import com.pedro.encoder.input.gl.render.filters.BaseFilterRender import com.pedro.encoder.input.video.CameraHelper import com.pedro.encoder.input.video.FpsLimiter import com.pedro.rtplibrary.util.Filter import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.Semaphore /** * Created by pedro on 14/3/22. */ @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2) class GlStreamInterface(private val context: Context) : Runnable, OnFrameAvailableListener { private var thread: Thread? = null private var frameAvailable = false var running = false private var initialized = false private val surfaceManager = SurfaceManager() private val surfaceManagerEncoder = SurfaceManager() private val surfaceManagerPreview = SurfaceManager() private var managerRender: MainRender? = null private val semaphore = Semaphore(0) private val sync = Object() private var encoderWidth = 0 private var encoderHeight = 0 private var streamOrientation = 0 private var previewWidth = 0 private var previewHeight = 0 private var previewOrientation = 0 private var isPortrait = false private val fpsLimiter = FpsLimiter() private val filterQueue: BlockingQueue<Filter> = LinkedBlockingQueue() private var forceRender = false fun init() { if (!initialized) managerRender = MainRender() managerRender?.setCameraFlip(false, false) initialized = true } fun setEncoderSize(width: Int, height: Int) { encoderWidth = width encoderHeight = height } fun getEncoderSize(): Point { return Point(encoderWidth, encoderHeight) } fun setFps(fps: Int) { fpsLimiter.setFPS(fps) } fun setForceRender(forceRender: Boolean) { this.forceRender = forceRender } fun getSurfaceTexture(): SurfaceTexture { return managerRender!!.getSurfaceTexture() } fun getSurface(): Surface { return managerRender!!.getSurface() } fun addMediaCodecSurface(surface: Surface) { synchronized(sync) { if (surfaceManager.isReady) { surfaceManagerEncoder.release() surfaceManagerEncoder.eglSetup(surface, surfaceManager) } } } fun removeMediaCodecSurface() { synchronized(sync) { surfaceManagerEncoder.release() } } fun start() { synchronized(sync) { thread = Thread(this) running = true thread?.start() semaphore.acquireUninterruptibly() } } fun stop() { synchronized(sync) { running = false thread?.interrupt() try { thread?.join(100) } catch (e: InterruptedException) { thread?.interrupt() } thread = null surfaceManagerEncoder.release() surfaceManager.release() } } override fun run() { surfaceManager.release() surfaceManager.eglSetup() surfaceManager.makeCurrent() managerRender?.initGl(context, encoderWidth, encoderHeight, encoderWidth, encoderHeight) managerRender?.getSurfaceTexture()?.setOnFrameAvailableListener(this) semaphore.release() try { while (running) { if (frameAvailable || forceRender) { frameAvailable = false surfaceManager.makeCurrent() managerRender?.updateFrame() managerRender?.drawOffScreen() managerRender?.drawScreen(encoderWidth, encoderHeight, false, 0, 0, false, false) surfaceManager.swapBuffer() if (!filterQueue.isEmpty()) { val filter = filterQueue.take() managerRender?.setFilterAction(filter.filterAction, filter.position, filter.baseFilterRender) } synchronized(sync) { val limitFps = fpsLimiter.limitFPS() // render VideoEncoder (stream and record) if (surfaceManagerEncoder.isReady && !limitFps) { val w = encoderWidth val h = encoderHeight surfaceManagerEncoder.makeCurrent() managerRender?.drawScreenEncoder(w, h, isPortrait, streamOrientation, false, false) surfaceManagerEncoder.swapBuffer() } // render preview if (surfaceManagerPreview.isReady && !limitFps) { val w = if (previewWidth == 0) encoderWidth else previewWidth val h = if (previewHeight == 0) encoderHeight else previewHeight surfaceManagerPreview.makeCurrent() managerRender?.drawScreenPreview(w, h, isPortrait, true, 0, previewOrientation, false, false) surfaceManagerPreview.swapBuffer() } } } } } catch (ignore: InterruptedException) { Thread.currentThread().interrupt() } finally { managerRender?.release() surfaceManagerEncoder.release() surfaceManager.release() } } override fun onFrameAvailable(surfaceTexture: SurfaceTexture?) { synchronized(sync) { frameAvailable = true sync.notifyAll() } } fun attachPreview(surface: Surface) { synchronized(sync) { if (surfaceManager.isReady) { isPortrait = CameraHelper.isPortrait(context) surfaceManagerPreview.release() surfaceManagerPreview.eglSetup(surface, surfaceManager) } } } fun deAttachPreview() { synchronized(sync) { surfaceManagerPreview.release() } } fun setStreamOrientation(orientation: Int) { this.streamOrientation = orientation } fun setPreviewResolution(width: Int, height: Int) { this.previewWidth = width this.previewHeight = height } fun setPreviewOrientation(orientation: Int) { this.previewOrientation = orientation } fun setCameraOrientation(orientation: Int) { managerRender?.setCameraRotation(orientation) } fun setFilter(filterPosition: Int, baseFilterRender: BaseFilterRender?) { filterQueue.add(Filter(FilterAction.SET_INDEX, filterPosition, baseFilterRender)) } fun addFilter(baseFilterRender: BaseFilterRender?) { filterQueue.add(Filter(FilterAction.ADD, 0, baseFilterRender)) } fun addFilter(filterPosition: Int, baseFilterRender: BaseFilterRender?) { filterQueue.add(Filter(FilterAction.ADD_INDEX, filterPosition, baseFilterRender)) } fun clearFilters() { filterQueue.add(Filter(FilterAction.CLEAR, 0, null)) } fun removeFilter(filterPosition: Int) { filterQueue.add(Filter(FilterAction.REMOVE_INDEX, filterPosition, null)) } fun removeFilter(baseFilterRender: BaseFilterRender?) { filterQueue.add(Filter(FilterAction.REMOVE, 0, baseFilterRender)) } fun filtersCount(): Int { return managerRender?.filtersCount() ?: 0 } fun setFilter(baseFilterRender: BaseFilterRender?) { filterQueue.add(Filter(FilterAction.SET, 0, baseFilterRender)) } }
apache-2.0
e572516d8db6f7a78864c1870dd683ee
28.758197
105
0.692329
4.532459
false
false
false
false
darkpaw/boss_roobot
src/org/darkpaw/ld33/mobs/PlayerBullet.kt
1
1356
package org.darkpaw.ld33.mobs import org.darkpaw.ld33.GameWorld import org.darkpaw.ld33.Vector import org.darkpaw.ld33.sprites.PlayerBulletSprite import org.darkpaw.ld33.sprites.PlayerSprite class PlayerBullet(gw : GameWorld, val sprite : PlayerBulletSprite, fired_from : Vector, fired_at : Long) { val game_world = gw val speed = 16.0 val fired_from_position = fired_from val fired_at = fired_at private fun current_position(frame_count : Long) : Vector{ val travelled = (frame_count - fired_at) * speed val current_position = Vector(fired_from_position.x + travelled, fired_from_position.y) return current_position } fun draw(frame_count : Long){ sprite.draw(current_position(frame_count)) } fun move(frame_count : Long) : Boolean { val pos = current_position(frame_count) if(pos.x > 800.0){ return false } val boss_pos = game_world.boss_mob.position val boss_size = game_world.boss_mob.sprite.size_on_screen val hit_box_TL = Vector(boss_pos.x - boss_size * 0.4, boss_pos.y - boss_size * 0.8) val hit_box_sz = Vector(boss_size * 0.6, boss_size * 0.75) if(pos.isInRect(hit_box_TL, hit_box_sz)){ game_world.register_hit_boss() return false } return true } }
agpl-3.0
f940e077e4f5294813122079711810ee
29.155556
107
0.637906
3.29927
false
false
false
false
EventFahrplan/EventFahrplan
app/src/main/java/nerd/tuxmobil/fahrplan/congress/alarms/AlarmServices.kt
1
8690
package nerd.tuxmobil.fahrplan.congress.alarms import android.annotation.SuppressLint import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import android.content.Intent import androidx.annotation.VisibleForTesting import info.metadude.android.eventfahrplan.commons.logging.Logging import info.metadude.android.eventfahrplan.commons.temporal.DateFormatter import info.metadude.android.eventfahrplan.commons.temporal.Moment import nerd.tuxmobil.fahrplan.congress.R import nerd.tuxmobil.fahrplan.congress.dataconverters.toSchedulableAlarm import nerd.tuxmobil.fahrplan.congress.extensions.getAlarmManager import nerd.tuxmobil.fahrplan.congress.models.Alarm import nerd.tuxmobil.fahrplan.congress.models.SchedulableAlarm import nerd.tuxmobil.fahrplan.congress.models.Session import nerd.tuxmobil.fahrplan.congress.repositories.AppRepository import nerd.tuxmobil.fahrplan.congress.utils.PendingIntentCompat.FLAG_IMMUTABLE import org.threeten.bp.ZoneOffset /** * Alarm related actions such as adding and deleting session alarms or directly scheduling and * discarding alarms via the [AlarmManager][alarmManager]. */ class AlarmServices @VisibleForTesting constructor( private val context: Context, private val repository: AppRepository, private val alarmManager: AlarmManager, private val alarmTimeValues: List<String>, private val logging: Logging, private val pendingIntentDelegate: PendingIntentDelegate = PendingIntentProvider, private val formattingDelegate: FormattingDelegate = DateFormatterDelegate ) { companion object { private const val LOG_TAG = "AlarmServices" /** * Factory function returning an [AlarmServices] instance with sensible defaults set. */ @JvmStatic @JvmOverloads fun newInstance( context: Context, repository: AppRepository, logging: Logging = Logging.get() ): AlarmServices { val alarmManager = context.getAlarmManager() val alarmTimesArray = context.resources.getStringArray(R.array.preference_entry_values_alarm_time) return AlarmServices( context = context, repository = repository, alarmManager = alarmManager, alarmTimesArray.toList(), logging = logging ) } } /** * Delegate to get a [PendingIntent] that will perform a broadcast. */ interface PendingIntentDelegate { fun onPendingIntentBroadcast(context: Context, intent: Intent): PendingIntent } /** * Delegate which provides a [PendingIntent] that will perform a broadcast. */ private object PendingIntentProvider : PendingIntentDelegate { const val DEFAULT_REQUEST_CODE = 0 @SuppressLint("WrongConstant") override fun onPendingIntentBroadcast(context: Context, intent: Intent): PendingIntent { return PendingIntent.getBroadcast(context, DEFAULT_REQUEST_CODE, intent, FLAG_IMMUTABLE) } } /** * Delegate to get a formatted date/time. */ interface FormattingDelegate { fun getFormattedDateTimeShort(useDeviceTimeZone: Boolean, alarmTime: Long, timeZoneOffset: ZoneOffset?): String } /** * [DateFormatter] delegate to handle calls to get a formatted date/time. * Do not introduce any business logic here because this class is not unit tested. */ private object DateFormatterDelegate : FormattingDelegate { override fun getFormattedDateTimeShort(useDeviceTimeZone: Boolean, alarmTime: Long, timeZoneOffset: ZoneOffset?): String { return DateFormatter.newInstance(useDeviceTimeZone).getFormattedDateTimeShort(alarmTime, timeZoneOffset) } } /** * Adds an alarm for the given [session] with the * [alarm time][R.array.preference_entries_alarm_time_titles] * corresponding with the given [alarmTimesIndex]. */ fun addSessionAlarm(session: Session, alarmTimesIndex: Int) { logging.d(LOG_TAG, "Add alarm for session = ${session.sessionId}, alarmTimesIndex = $alarmTimesIndex.") val alarmTimeStrings = ArrayList(alarmTimeValues) val alarmTimes = ArrayList<Int>(alarmTimeStrings.size) for (alarmTimeString in alarmTimeStrings) { alarmTimes.add(alarmTimeString.toInt()) } val sessionStartTime = session.startTimeMilliseconds val alarmTimeOffset = alarmTimes[alarmTimesIndex] * Moment.MILLISECONDS_OF_ONE_MINUTE.toLong() val alarmTime = sessionStartTime - alarmTimeOffset val moment = Moment.ofEpochMilli(alarmTime) logging.d(LOG_TAG, "Add alarm: Time = ${moment.toUtcDateTime()}, in seconds = $alarmTime.") val sessionId = session.sessionId val sessionTitle = session.title val alarmTimeInMin = alarmTimes[alarmTimesIndex] val useDeviceTimeZone = repository.readUseDeviceTimeZoneEnabled() val timeText = formattingDelegate.getFormattedDateTimeShort(useDeviceTimeZone, alarmTime, session.timeZoneOffset) val day = session.day val alarm = Alarm(alarmTimeInMin, day, sessionStartTime, sessionId, sessionTitle, alarmTime, timeText) val schedulableAlarm = alarm.toSchedulableAlarm() scheduleSessionAlarm(schedulableAlarm, true) repository.updateAlarm(alarm) session.hasAlarm = true } /** * Deletes the alarm for the given [session]. */ fun deleteSessionAlarm(session: Session) { val sessionId = session.sessionId val alarms = repository.readAlarms(sessionId) if (alarms.isNotEmpty()) { // Delete any previous alarms of this session. val alarm = alarms[0] val schedulableAlarm = alarm.toSchedulableAlarm() discardSessionAlarm(schedulableAlarm) repository.deleteAlarmForSessionId(sessionId) } session.hasAlarm = false } /** * Schedules the given [alarm] via the [AlarmManager]. * Existing alarms for the associated session are discarded if configured via [discardExisting]. */ @JvmOverloads fun scheduleSessionAlarm(alarm: SchedulableAlarm, discardExisting: Boolean = false) { val intent = AlarmReceiver.AlarmIntentFactory( context = context, sessionId = alarm.sessionId, title = alarm.sessionTitle, day = alarm.day, startTime = alarm.startTime ).getIntent(isAddAlarmIntent = true) val pendingIntent = pendingIntentDelegate.onPendingIntentBroadcast(context, intent) if (discardExisting) { alarmManager.cancel(pendingIntent) } // Alarms scheduled here are treated as inexact as of targeting Android 4.4 (API level 19). // See https://developer.android.com/training/scheduling/alarms // and https://developer.android.com/reference/android/os/Build.VERSION_CODES#KITKAT // SCHEDULE_EXACT_ALARM permission is needed when switching to exact alarms as of targeting Android 12 (API level 31). // See https://developer.android.com/about/versions/12/behavior-changes-12#exact-alarm-permission // USE_EXACT_ALARM permission is needed when switching to exact alarms as of targeting Android 13 (API level 33). // See https://developer.android.com/about/versions/13/features#use-exact-alarm-permission // and https://support.google.com/googleplay/android-developer/answer/12253906#exact_alarm_preview alarmManager.set(AlarmManager.RTC_WAKEUP, alarm.startTime, pendingIntent) } /** * Discards the given [alarm] via the [AlarmManager]. */ fun discardSessionAlarm(alarm: SchedulableAlarm) { val intent = AlarmReceiver.AlarmIntentFactory( context = context, sessionId = alarm.sessionId, title = alarm.sessionTitle, day = alarm.day, startTime = alarm.startTime ).getIntent(isAddAlarmIntent = false) discardAlarm(context, intent) } /** * Discards an internal alarm used for automatic schedule updates via the [AlarmManager]. */ fun discardAutoUpdateAlarm() { val intent = Intent(context, AlarmReceiver::class.java) intent.action = AlarmReceiver.ALARM_UPDATE discardAlarm(context, intent) } private fun discardAlarm(context: Context, intent: Intent) { val pendingIntent = pendingIntentDelegate.onPendingIntentBroadcast(context, intent) alarmManager.cancel(pendingIntent) } }
apache-2.0
f08698137039abfb7984953334d117f5
41.807882
130
0.698159
4.9375
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/CommunityChildViewHolder.kt
2
2107
package ru.fantlab.android.ui.adapter.viewholder import android.view.View import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.community_child_row_item.view.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.model.CommunityTreeChild import ru.fantlab.android.helper.getTimeAgo import ru.fantlab.android.helper.parseFullDate import ru.fantlab.android.ui.widgets.ForegroundImageView import ru.fantlab.android.ui.widgets.treeview.TreeNode import ru.fantlab.android.ui.widgets.treeview.TreeViewAdapter import ru.fantlab.android.ui.widgets.treeview.TreeViewBinder class CommunityChildViewHolder : TreeViewBinder<CommunityChildViewHolder.ViewHolder>() { override val layoutId: Int = R.layout.community_child_row_item override fun provideViewHolder(itemView: View): ViewHolder = ViewHolder(itemView) override fun bindView( holder: RecyclerView.ViewHolder , position: Int, node: TreeNode<*>, onTreeNodeListener: TreeViewAdapter.OnTreeNodeListener? ) { (holder as ViewHolder) val parentNode = node.content as CommunityTreeChild Glide.with(holder.itemView.context).load(parentNode.avatar).into(holder.communityAvatar) holder.communityTitle.text = parentNode.title holder.articleCount.text = parentNode.articleCount.toString() holder.subscriberCount.text = parentNode.subscriberCount.toString() holder.lastDate.text = parentNode.lastArticleDate.parseFullDate(true).getTimeAgo() holder.lastUsername.text = parentNode.lastUsernameLogin holder.lastArticleTitle.text = parentNode.lastArticleTitle } class ViewHolder(rootView: View) : TreeViewBinder.ViewHolder(rootView) { var communityAvatar: ForegroundImageView = rootView.communityAvatar var communityTitle: TextView = rootView.communityTitle var articleCount: TextView = rootView.articleCount var subscriberCount: TextView = rootView.subscriberCount var lastDate: TextView = rootView.lastDate var lastArticleTitle: TextView = rootView.lastArticleTitle var lastUsername: TextView = rootView.lastUsername } }
gpl-3.0
9a876fe52631af3654928cca4d21da87
42
126
0.824395
4.067568
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/forums/topic/TopicFragment.kt
2
10290
package ru.fantlab.android.ui.modules.forums.topic import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import androidx.annotation.Keep import androidx.annotation.StringRes import androidx.core.view.isVisible import com.evernote.android.state.State import kotlinx.android.synthetic.main.draft_view.* import kotlinx.android.synthetic.main.micro_grid_refresh_list.* import kotlinx.android.synthetic.main.state_layout.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.ContextMenuBuilder import ru.fantlab.android.data.dao.model.* import ru.fantlab.android.helper.ActivityHelper import ru.fantlab.android.helper.BundleConstant import ru.fantlab.android.helper.Bundler import ru.fantlab.android.helper.PrefGetter import ru.fantlab.android.provider.rest.TopicMessagesSortOption import ru.fantlab.android.provider.rest.loadmore.OnLoadMore import ru.fantlab.android.provider.scheme.LinkParserHelper import ru.fantlab.android.ui.adapter.TopicMessagesAdapter import ru.fantlab.android.ui.base.BaseFragment import ru.fantlab.android.ui.modules.editor.EditorActivity import ru.fantlab.android.ui.modules.forums.ForumsMvp import ru.fantlab.android.ui.modules.user.UserPagerActivity import ru.fantlab.android.ui.widgets.dialog.ContextMenuDialogView import ru.fantlab.android.ui.widgets.recyclerview.layoutManager.LinearManager class TopicFragment : BaseFragment<TopicMvp.View, TopicPresenter>(), TopicMvp.View { override fun fragmentLayout() = R.layout.forum_topic_layout override fun providePresenter() = TopicPresenter() @State var topicId = -1 @State var isClosed = false @State var forumId = -1 @State var topicTitle = "" //@State var replyText = "" private val onLoadMore: OnLoadMore<Int> by lazy { OnLoadMore(presenter, topicId) } private val adapter: TopicMessagesAdapter by lazy { TopicMessagesAdapter(arrayListOf()) } private var forumsCallback: ForumsMvp.View? = null override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { if (arguments != null) { if (savedInstanceState == null) { stateLayout.hideProgress() } if (PrefGetter.getTopicMessagesOrder() == TopicMessagesSortOption.BY_NEW.value) { recycler.apply { layoutManager = LinearManager(context).apply { reverseLayout = true } } } stateLayout.setEmptyText(R.string.no_results) stateLayout.setOnReloadListener(this) refresh.setOnRefreshListener(this) recycler.setEmptyView(stateLayout, refresh) adapter.listener = presenter adapter.setOnContextMenuListener(this) recycler.adapter = adapter topicId = arguments!!.getInt(BundleConstant.EXTRA) topicTitle = arguments!!.getString(BundleConstant.EXTRA_TWO) ?: getString(R.string.topic) forumId = arguments!!.getInt(BundleConstant.EXTRA_THREE) isClosed = arguments!!.getBoolean(BundleConstant.YES_NO_EXTRA) forumsCallback?.setTitle(topicTitle) getLoadMore().initialize(presenter.getCurrentPage() - 1, presenter.getPreviousTotal()) recycler.addOnScrollListener(getLoadMore()) presenter.onCallApi(1, topicId) setHasOptionsMenu(true) } } override fun onNotifyAdapter(items: ArrayList<ForumTopic.Message>, page: Int) { hideProgress() if (items.isEmpty()) { adapter.clear() return } if (page <= 1) { adapter.insertItems(items) fastScroller.attachRecyclerView(recycler) } else { adapter.addItems(items) } } override fun onAddToAdapter(items: ArrayList<ForumTopic.Message>, isNewMessage: Boolean) { hideProgress() if (isNewMessage) adapter.data.removeAt(0) adapter.addItems(items, 0) } override fun onSetPinnedMessage(message: ForumTopic.PinnedMessage?) { } override fun onMessageDraftDeleted() { draftView.isVisible = false draftMessage.text = "" deleteDraft.setOnClickListener { } confirmDraft.setOnClickListener { } } override fun getLoadMore() = onLoadMore override fun showProgress(@StringRes resId: Int, cancelable: Boolean) { refresh.isRefreshing = true stateLayout.showProgress() } override fun hideProgress() { refresh.isRefreshing = false stateLayout.hideProgress() } override fun showErrorMessage(msgRes: String?) { hideProgress() super.showErrorMessage(msgRes) } override fun showMessage(titleRes: Int, msgRes: Int) { hideProgress() super.showMessage(titleRes, msgRes) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.topic_menu, menu) menu.getItem(0).isVisible = isLoggedIn() && !isClosed super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.share -> { ActivityHelper.shareUrl(context!!, Uri.Builder().scheme(LinkParserHelper.PROTOCOL_HTTPS) .authority(LinkParserHelper.HOST_DEFAULT) .appendEncodedPath("forum/forum${forumId}page0/topic${topicId}page${presenter.getCurrentPage()}") .toString()) } R.id.message -> { onShowEditor("") } } return super.onOptionsItemSelected(item) } override fun onClick(v: View?) { onRefresh() } override fun onRefresh() { hideProgress() } override fun onItemClicked(item: ForumTopic.Message) { showTopicMenu(item) } override fun onOpenContextMenu(topicMessage: Forum.Topic) { } override fun onItemSelected(parent: String, item: ContextMenus.MenuItem, position: Int, listItem: Any) { if (listItem is ForumTopic.Message) when (item.id) { "copy_link" -> { val link = "https://fantlab.ru/forum/forum${forumId}page0/topic${topicId}page${presenter.getCurrentPage()}#msg${listItem.id}" ActivityHelper.copyToClipboard(context!!, link) } "reply" -> { val replyText = "[b]${listItem.creation.user.login}[/b], " onShowEditor(replyText) } "profile" -> { UserPagerActivity.startActivity(context!!, listItem.creation.user.login, listItem.creation.user.id.toInt(), 0) } "delete" -> { presenter.onDeleteMessage(listItem.id.toInt()) } "edit" -> { onShowEditor(listItem.text, isEditor = true, messageId = listItem.id.toInt()) } } } override fun onShowEditor(quoteText: String, isEditor: Boolean, isDraft: Boolean, messageId: Int) { if (!isLoggedIn()) { showErrorMessage(getString(R.string.unauthorized_user)) return } if (isEditor) { startActivityForResult(Intent(activity, EditorActivity::class.java) .putExtra(BundleConstant.EXTRA_TYPE, BundleConstant.EDITOR_EDIT_TOPIC_MESSAGE) .putExtra(BundleConstant.EXTRA, quoteText) .putExtra(BundleConstant.EXTRA_TWO, topicId) .putExtra(BundleConstant.ID, messageId) .putExtra(BundleConstant.YES_NO_EXTRA, isDraft), BundleConstant.EDIT_TOPIC_MESSAGE_CODE) } else { startActivityForResult(Intent(activity, EditorActivity::class.java) .putExtra(BundleConstant.EXTRA_TYPE, BundleConstant.EDITOR_NEW_TOPIC_MESSAGE) .putExtra(BundleConstant.EXTRA, quoteText) .putExtra(BundleConstant.EXTRA_TWO, topicId) .putExtra(BundleConstant.ID, topicId), BundleConstant.NEW_TOPIC_MESSAGE_CODE) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) { when (requestCode) { BundleConstant.NEW_TOPIC_MESSAGE_CODE -> { val isDraft = data?.extras?.getBoolean(BundleConstant.YES_NO_EXTRA) ?: false if (isDraft) { val myMessage = data?.extras?.getParcelable<TopicMessageDraft>(BundleConstant.ITEM) if (myMessage != null) { draftMessage.text = myMessage.messageDraft.text deleteDraft.setOnClickListener { presenter.onDeleteDraftMessage(topicId) } confirmDraft.setOnClickListener { presenter.onConfirmDraftMessage(topicId, adapter.data.first().id) } draftView.isVisible = true } } else { onMessageDraftDeleted() val myMessage = data?.extras?.getParcelable<TopicMessage>(BundleConstant.ITEM) if (myMessage != null) { recycler.scrollToPosition(0) adapter.addItem(myMessage.message, 0) presenter.refreshMessages(adapter.data.first().id, true) } } } BundleConstant.EDIT_TOPIC_MESSAGE_CODE -> { val extra = data?.extras if (data != null) { val messageId = extra?.getInt(BundleConstant.ID) val messageText = extra?.getString(BundleConstant.EXTRA) val message = adapter.data.find { it.id.toInt() == messageId } val position = adapter.data.indexOf(message) if (message != null) { adapter.getItem(position).text = messageText!! adapter.notifyItemChanged(position) presenter.refreshMessages(adapter.data.first().id, false) } } } } } } override fun onItemLongClicked(position: Int, v: View?, item: ForumTopic.Message) { showTopicMenu(item) } private fun showTopicMenu(item: ForumTopic.Message) { val dialogView = ContextMenuDialogView() dialogView.initArguments("main", ContextMenuBuilder.buildForTopicMessage(recycler.context, isLoggedIn(), item.creation.user.id.toInt() == PrefGetter.getLoggedUser()?.id), item, 0) dialogView.show(childFragmentManager, "ContextMenuDialogView") } override fun onMessageDeleted(messageId: Int) { hideProgress() val position = adapter.data.indexOf(adapter.data.find { it.id.toInt() == messageId }) adapter.data.removeAt(position) adapter.notifyItemRemoved(position) } override fun onAttach(context: Context) { super.onAttach(context) if (context is ForumsMvp.View) { forumsCallback = context } } override fun onDetach() { forumsCallback = null super.onDetach() } companion object { @Keep val TAG: String = TopicFragment::class.java.simpleName fun newInstance(topicId: Int, topicTitle: String, forumId: Int, isClosed: Boolean): TopicFragment { //TODO fix uselles code val view = TopicFragment() view.arguments = Bundler.start() .put(BundleConstant.EXTRA, topicId) .put(BundleConstant.EXTRA_TWO, topicTitle) .put(BundleConstant.EXTRA_THREE, forumId) .put(BundleConstant.YES_NO_EXTRA, isClosed) .end() return view } } }
gpl-3.0
a45c2bfb83a784442b1aa9f40457f0e4
30.959627
181
0.736832
3.735027
false
false
false
false
tasomaniac/OpenLinkWith
app/src/main/java/com/tasomaniac/openwith/resolver/ResolverUseCase.kt
1
2696
package com.tasomaniac.openwith.resolver import android.content.Intent import android.net.Uri import com.tasomaniac.openwith.data.PreferredApp import com.tasomaniac.openwith.data.PreferredAppDao import com.tasomaniac.openwith.resolver.preferred.PreferredResolver import com.tasomaniac.openwith.rx.SchedulingStrategy import io.reactivex.Completable import io.reactivex.disposables.Disposable import io.reactivex.rxkotlin.subscribeBy import timber.log.Timber import javax.inject.Inject // TODO wrap this into ViewModel to retain over config change internal class ResolverUseCase @Inject constructor( private val sourceIntent: Intent, private val preferredResolver: PreferredResolver, private val intentResolver: IntentResolver, private val history: ChooserHistory, private val dao: PreferredAppDao, private val scheduling: SchedulingStrategy ) { private var disposable: Disposable? = null private var listener: Listener? = null fun bind(listener: Listener) { this.listener = listener val uri = sourceIntent.data!! disposable = preferredResolver.resolve(uri) .compose(scheduling.forMaybe()) .subscribeBy( onSuccess = { (app, info) -> intentResolver.lastChosenComponent = app.componentName listener.onPreferredResolved(uri, app, info) intentResolver.bind(listener) }, onError = Timber::e, onComplete = { intentResolver.bind(listener) } ) } fun unbind() { intentResolver.unbind() } fun release() { intentResolver.release() disposable?.dispose() } fun resolve() { intentResolver.resolve() } fun persistSelectedIntent(intent: Intent, alwaysCheck: Boolean) { val component = intent.component ?: return val preferredApp = PreferredApp( host = intent.data!!.host!!, component = component.flattenToString(), preferred = alwaysCheck ) Completable .fromAction { dao.insert(preferredApp) } .compose(scheduling.forCompletable()) .subscribe() history.add(component.packageName) history.save() } fun deleteFailedHost(uri: Uri) { Completable.fromAction { dao.deleteHost(uri.host!!) } .compose(scheduling.forCompletable()) .subscribe() } interface Listener : IntentResolver.Listener { fun onPreferredResolved( uri: Uri, preferredApp: PreferredApp, displayActivityInfo: DisplayActivityInfo ) } }
apache-2.0
b385964b0ce76b0a8dd556fd60f553cd
29.988506
74
0.651335
4.919708
false
false
false
false
inorichi/tachiyomi-extensions
src/pt/hqnow/src/eu/kanade/tachiyomi/extension/pt/hqnow/HQNowDto.kt
1
678
package eu.kanade.tachiyomi.extension.pt.hqnow import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class HqNowComicBookDto( @SerialName("capitulos") val chapters: List<HqNowChapterDto> = emptyList(), @SerialName("hqCover") val cover: String? = "", val id: Int, val name: String, val publisherName: String? = "", val status: String? = "", val synopsis: String? = "" ) @Serializable data class HqNowChapterDto( val id: Int = 0, val name: String, val number: String, val pictures: List<HqNowPageDto> = emptyList() ) @Serializable data class HqNowPageDto( val pictureUrl: String )
apache-2.0
88a5115ce928ae385c1a6c4e1e306eb9
23.214286
79
0.70354
3.587302
false
false
false
false
Shockah/Godwit
test/src/pl/shockah/godwit/test/UiViewportTest.kt
1
1290
package pl.shockah.godwit.test import com.badlogic.gdx.utils.viewport.ScreenViewport import pl.shockah.godwit.color.RGBColor import pl.shockah.godwit.geom.ImmutableVec2 import pl.shockah.godwit.geom.Rectangle import pl.shockah.godwit.geom.vec2 import pl.shockah.godwit.node.Stage import pl.shockah.godwit.node.StageLayer import pl.shockah.godwit.node.NodeGame import pl.shockah.godwit.node.asFilledNode private val rect = Rectangle(vec2(-5000f, -5000f), vec2(10000f, 10000f)) class UiViewportTest : NodeGame({ object : Stage( StageLayer(ScreenViewport()).apply { root += rect.asFilledNode().apply { color = RGBColor(1f, 0.5f, 0f).alpha() } root += Rectangle(size = vec2(32f, 32f)).asFilledNode() }, StageLayer(ScreenViewport()).apply { root += rect.asFilledNode().apply { color = RGBColor(0.5f, 0.5f, 0.5f).alpha(0.5f) } } ) { private val uiHeight = 150 val mainLayer = stageLayers[0] val uiLayer = stageLayers[1] override fun resize(screenWidth: Int, screenHeight: Int) { super.resize(screenWidth, screenHeight) mainLayer.viewports[0].apply { val height = screenHeight - uiHeight update(screenWidth, height, true) screenY = uiHeight } uiLayer.viewports[0].apply { screenX = 0 screenY = 0 update(screenWidth, uiHeight, true) } } } })
apache-2.0
e4dfb3caf961ee4824458da5cfccc187
28.340909
87
0.732558
3.093525
false
false
false
false
firebase/snippets-android
mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/ImageLabelingActivity.kt
1
3557
package com.google.firebase.example.mlkit.kotlin import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.tasks.OnFailureListener import com.google.android.gms.tasks.OnSuccessListener import com.google.firebase.ml.vision.FirebaseVision import com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions import com.google.firebase.ml.vision.common.FirebaseVisionImage import com.google.firebase.ml.vision.label.FirebaseVisionImageLabel import com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceImageLabelerOptions class ImageLabelingActivity : AppCompatActivity() { private fun labelImages(image: FirebaseVisionImage) { // [START set_detector_options] val options = FirebaseVisionOnDeviceImageLabelerOptions.Builder() .setConfidenceThreshold(0.8f) .build() // [END set_detector_options] // [START get_detector_default] val detector = FirebaseVision.getInstance() .onDeviceImageLabeler // [END get_detector_default] /* // [START get_detector_options] // Or, to set the minimum confidence required: val detector = FirebaseVision.getInstance() .getOnDeviceImageLabeler(options) // [END get_detector_options] */ // [START fml_run_detector] val result = detector.processImage(image) .addOnSuccessListener { labels -> // Task completed successfully // [START_EXCLUDE] // [START get_labels] for (label in labels) { val text = label.text val entityId = label.entityId val confidence = label.confidence } // [END get_labels] // [END_EXCLUDE] } .addOnFailureListener { e -> // Task failed with an exception // ... } // [END fml_run_detector] } private fun labelImagesCloud(image: FirebaseVisionImage) { // [START set_detector_options_cloud] val options = FirebaseVisionCloudDetectorOptions.Builder() .setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL) .setMaxResults(30) .build() // [END set_detector_options_cloud] // [START get_detector_cloud] val detector = FirebaseVision.getInstance() .cloudImageLabeler // Or, to change the default settings: // val detector = FirebaseVision.getInstance() // .getCloudImageLabeler(options) // [END get_detector_cloud] // [START fml_run_detector_cloud] val result = detector.processImage(image) .addOnSuccessListener { labels -> // Task completed successfully // [START_EXCLUDE] // [START get_labels_cloud] for (label in labels) { val text = label.text val entityId = label.entityId val confidence = label.confidence } // [END get_labels_cloud] // [END_EXCLUDE] } .addOnFailureListener { e -> // Task failed with an exception // ... } // [END fml_run_detector_cloud] } }
apache-2.0
e3f36e02362dcc6ef6b58f55c8f489f8
38.087912
84
0.558336
5.254062
false
false
false
false
ilya-g/kotlinx.collections.experimental
kotlinx-collections-experimental/benchmarks/src/main/kotlin/TestData.kt
1
708
package kotlinx.collections.experimental.benchmarks import kotlinx.collections.experimental.grouping.groupCountBy import java.util.* data class Element(val key: String, val value: Int) fun generateElements(count: Int, keys: Int): List<Element> { val keyChars = ('a'..'z').toList() fun key(value: Int) = buildString { var v = value % keys while (v != 0) { append(keyChars[v % keyChars.size]) v /= keyChars.size } } val rnd = Random() val result = (0 until count).map { Element(key(rnd.nextInt(count)), rnd.nextInt(count)) } println(result.groupCountBy { it.key }.entries.sortedByDescending { it.value }.take(10)) return result }
apache-2.0
1c67f3035465c173ef7942b9fdbd67a2
29.826087
93
0.649718
3.786096
false
false
false
false
rhdunn/xquery-intellij-plugin
src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/xml/dom/Xml.kt
1
4994
/* * Copyright (C) 2017-2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.core.xml.dom import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.text.nullize import org.w3c.dom.* import org.xml.sax.InputSource import java.io.* import javax.xml.namespace.QName import javax.xml.transform.dom.DOMSource import javax.xml.transform.stream.StreamResult private class NodeListIterator(val nodes: NodeList) : Iterator<Node> { private var current: Int = 0 override fun hasNext(): Boolean = current != nodes.length override fun next(): Node = nodes.item(current++) } fun NodeList.asSequence(): Sequence<Node> = NodeListIterator(this).asSequence() fun <E> NodeList.elements(map: (Element) -> E): Sequence<E> = asSequence().filterIsInstance<Element>().map(map) class NamedNodeMapIterator(val nodes: NamedNodeMap) : Iterator<Node> { private var current: Int = 0 override fun hasNext(): Boolean = current != nodes.length override fun next(): Node = nodes.item(current++) } inline fun <reified E> NamedNodeMap.asSequence(): Sequence<E> { return NamedNodeMapIterator(this).asSequence().filterIsInstance<E>() } fun String.toQName(namespaces: Map<String, String>): QName = when { startsWith("*:") -> split(":").let { QName(it[0], it[1], it[0]) } contains(':') -> split(":").let { QName(namespaces[it[0]], it[1], it[0]) } else -> QName(this) } class XmlElement(val element: Element, private val namespaces: Map<String, String>) { fun children(): Sequence<XmlElement> = element.childNodes.elements { XmlElement(it, namespaces) } fun children(qname: String): Sequence<XmlElement> = children(qname.toQName(namespaces)) fun children(qname: QName): Sequence<XmlElement> = children().filter { it.`is`(qname) } fun child(qname: String): XmlElement? = children(qname).firstOrNull() fun child(qname: QName): XmlElement? = children(qname).firstOrNull() fun text(): String? = element.firstChild?.nodeValue val attributes: Sequence<Attr> get() = element.attributes.asSequence() fun attribute(qname: String): String? = attribute(qname.toQName(namespaces)) fun attribute(qname: QName): String? = when { qname.namespaceURI.isEmpty() -> element.getAttribute(qname.localPart)?.nullize() else -> element.getAttributeNS(qname.namespaceURI, qname.localPart)?.nullize() } fun appendChild(child: Node): Node? = element.appendChild(child) fun `is`(qname: String): Boolean = `is`(qname.toQName(namespaces)) fun `is`(qname: QName): Boolean = when (qname.namespaceURI) { "*" -> element.localName == qname.localPart else -> element.localName == qname.localPart && (element.namespaceURI ?: "") == qname.namespaceURI } fun xml(): String { val buffer = StringWriter() XmlFormatter.format(DOMSource(element), StreamResult(buffer), omitXmlDeclaration = true) return buffer.toString() } fun innerXml(): String { val buffer = StringWriter() val result = StreamResult(buffer) element.childNodes.asSequence().forEach { node -> XmlFormatter.format(DOMSource(node), result, omitXmlDeclaration = true) } return buffer.toString() } } class XmlDocument internal constructor(val doc: Document, namespaces: Map<String, String>) { val root: XmlElement = XmlElement(doc.documentElement, namespaces) fun save(file: File) { FileWriter(file).use { XmlFormatter.format(DOMSource(doc), StreamResult(it)) } } companion object { fun parse(xml: String, namespaces: Map<String, String>): XmlDocument { return parse(InputSource(StringReader(xml)), namespaces) } fun parse(file: VirtualFile, namespaces: Map<String, String>): XmlDocument { return parse(InputSource(file.inputStream), namespaces) } fun parse(xml: InputStream, namespaces: Map<String, String>): XmlDocument { return parse(InputSource(xml), namespaces) } fun parse(xml: InputSource, namespaces: Map<String, String>): XmlDocument { return XmlDocument(XmlBuilder.parse(xml), namespaces) } } } fun Sequence<XmlElement>.children(name: String): Sequence<XmlElement> = this.flatMap { it.children(name) } fun Sequence<XmlElement>.children(name: QName): Sequence<XmlElement> = this.flatMap { it.children(name) }
apache-2.0
a77659536988b46391bfd4b9dc332a16
35.992593
111
0.687825
4.158201
false
false
false
false
westnordost/osmagent
app/src/main/java/de/westnordost/streetcomplete/quests/LeaveNoteInsteadFragment.kt
1
1444
package de.westnordost.streetcomplete.quests import android.content.Context import android.os.Bundle import android.view.View import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osmnotes.AbstractCreateNoteFragment import kotlinx.android.synthetic.main.form_leave_note.* import kotlinx.android.synthetic.main.fragment_quest_answer.* class LeaveNoteInsteadFragment : AbstractCreateNoteFragment() { override val layoutResId = R.layout.fragment_quest_answer private val questAnswerComponent: QuestAnswerComponent = QuestAnswerComponent() private lateinit var questTitle: String override fun onCreate(inState: Bundle?) { super.onCreate(inState) questAnswerComponent.onCreate(arguments) questTitle = arguments!!.getString(ARG_QUEST_TITLE)!! } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) titleLabel.text = getString(R.string.map_btn_create_note) descriptionLabel.text = null } override fun onAttach(context: Context) { super.onAttach(context) questAnswerComponent.onAttach(context as OsmQuestAnswerListener) } override fun onLeaveNote(text: String, imagePaths: List<String>?) { questAnswerComponent.onLeaveNote(questTitle, text, imagePaths) } companion object { const val ARG_QUEST_TITLE = "questTitle" } }
gpl-3.0
fb9bb9932483576d9c9935a3c5d7352b
31.818182
83
0.747922
4.5125
false
false
false
false
jeffgbutler/mybatis-dynamic-sql
src/test/kotlin/examples/kotlin/mybatis3/joins/ExistsTest.kt
1
30270
/* * Copyright 2016-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 examples.kotlin.mybatis3.joins import examples.kotlin.mybatis3.TestUtils import examples.kotlin.mybatis3.joins.ItemMasterDynamicSQLSupport.itemMaster import examples.kotlin.mybatis3.joins.OrderLineDynamicSQLSupport.orderLine import org.apache.ibatis.session.SqlSessionFactory import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.mybatis.dynamic.sql.util.kotlin.elements.invoke import org.mybatis.dynamic.sql.util.kotlin.mybatis3.deleteFrom import org.mybatis.dynamic.sql.util.kotlin.mybatis3.select import org.mybatis.dynamic.sql.util.kotlin.mybatis3.update import org.mybatis.dynamic.sql.util.mybatis3.CommonDeleteMapper import org.mybatis.dynamic.sql.util.mybatis3.CommonSelectMapper import org.mybatis.dynamic.sql.util.mybatis3.CommonUpdateMapper @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ExistsTest { private lateinit var sqlSessionFactory: SqlSessionFactory @BeforeAll fun setup() { sqlSessionFactory = TestUtils.buildSqlSessionFactory { withInitializationScript("/examples/kotlin/mybatis3/joins/CreateJoinDB.sql") withMapper(CommonSelectMapper::class) withMapper(CommonDeleteMapper::class) withMapper(CommonUpdateMapper::class) } } @Test fun testExists() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonSelectMapper::class.java) val selectStatement = select(itemMaster.allColumns()) { from(itemMaster, "im") where { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where { orderLine.itemId isEqualTo "im"(itemMaster.itemId) } } } } orderBy(itemMaster.itemId) } val expectedStatement: String = "select im.* from ItemMaster im" + " where exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" + " order by item_id" assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) val rows = mapper.selectManyMappedRows(selectStatement) assertThat(rows).hasSize(3) with(rows[0]) { assertThat(this).containsEntry("ITEM_ID", 22) assertThat(this).containsEntry("DESCRIPTION", "Helmet") } with(rows[1]) { assertThat(this).containsEntry("ITEM_ID", 33) assertThat(this).containsEntry("DESCRIPTION", "First Base Glove") } with(rows[2]) { assertThat(this).containsEntry("ITEM_ID", 44) assertThat(this).containsEntry("DESCRIPTION", "Outfield Glove") } } } @Test fun testExistsPropagatedAliases() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonSelectMapper::class.java) val selectStatement = select(itemMaster.allColumns()) { from(itemMaster, "im") where { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where { orderLine.itemId isEqualTo itemMaster.itemId } } } } orderBy(itemMaster.itemId) } val expectedStatement: String = "select im.* from ItemMaster im" + " where exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" + " order by item_id" assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) val rows = mapper.selectManyMappedRows(selectStatement) assertThat(rows).hasSize(3) with(rows[0]) { assertThat(this).containsEntry("ITEM_ID", 22) assertThat(this).containsEntry("DESCRIPTION", "Helmet") } with(rows[1]) { assertThat(this).containsEntry("ITEM_ID", 33) assertThat(this).containsEntry("DESCRIPTION", "First Base Glove") } with(rows[2]) { assertThat(this).containsEntry("ITEM_ID", 44) assertThat(this).containsEntry("DESCRIPTION", "Outfield Glove") } } } @Test fun testNotExists() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonSelectMapper::class.java) val selectStatement = select(itemMaster.allColumns()) { from(itemMaster, "im") where { not { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where { orderLine.itemId isEqualTo "im"(itemMaster.itemId) } } } } } orderBy(itemMaster.itemId) } val expectedStatement: String = "select im.* from ItemMaster im" + " where not exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" + " order by item_id" assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) val rows = mapper.selectManyMappedRows(selectStatement) assertThat(rows).hasSize(1) with(rows[0]) { assertThat(this).containsEntry("ITEM_ID", 55) assertThat(this).containsEntry("DESCRIPTION", "Catcher Glove") } } } @Test fun testNotExistsNewNot() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonSelectMapper::class.java) val selectStatement = select(itemMaster.allColumns()) { from(itemMaster, "im") where { not { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where { orderLine.itemId isEqualTo "im"(itemMaster.itemId) } } } } } orderBy(itemMaster.itemId) } val expectedStatement: String = "select im.* from ItemMaster im" + " where not exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" + " order by item_id" assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) val rows = mapper.selectManyMappedRows(selectStatement) assertThat(rows).hasSize(1) with(rows[0]) { assertThat(this).containsEntry("ITEM_ID", 55) assertThat(this).containsEntry("DESCRIPTION", "Catcher Glove") } } } @Test fun testPropagateTableAliasToExists() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonSelectMapper::class.java) val selectStatement = select(itemMaster.allColumns()) { from(itemMaster, "im") where { not { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where { orderLine.itemId isEqualTo itemMaster.itemId } } } } } orderBy(itemMaster.itemId) } val expectedStatement: String = "select im.* from ItemMaster im" + " where not exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" + " order by item_id" assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) val rows = mapper.selectManyMappedRows(selectStatement) assertThat(rows).hasSize(1) with(rows[0]) { assertThat(this).containsEntry("ITEM_ID", 55) assertThat(this).containsEntry("DESCRIPTION", "Catcher Glove") } } } @Test fun testAndExists() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonSelectMapper::class.java) val selectStatement = select(itemMaster.allColumns()) { from(itemMaster, "im") where { itemMaster.itemId isEqualTo 22 } and { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where { orderLine.itemId isEqualTo "im"(itemMaster.itemId) } } } } orderBy(itemMaster.itemId) } val expectedStatement = "select im.* from ItemMaster im" + " where im.item_id = #{parameters.p1,jdbcType=INTEGER}" + " and exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" + " order by item_id" assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) val rows = mapper.selectManyMappedRows(selectStatement) assertThat(rows).hasSize(1) with(rows[0]) { assertThat(this).containsEntry("ITEM_ID", 22) assertThat(this).containsEntry("DESCRIPTION", "Helmet") } } } @Test fun testAndExistsAnd() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonSelectMapper::class.java) val selectStatement = select(itemMaster.allColumns()) { from(itemMaster, "im") where { itemMaster.itemId isEqualTo 22 } and { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where { orderLine.itemId isEqualTo "im"(itemMaster.itemId) } } } and { itemMaster.itemId isGreaterThan 2 } } orderBy(itemMaster.itemId) } val expectedStatement = "select im.* from ItemMaster im" + " where im.item_id = #{parameters.p1,jdbcType=INTEGER}" + " and (exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" + " and im.item_id > #{parameters.p2,jdbcType=INTEGER})" + " order by item_id" assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) val rows = mapper.selectManyMappedRows(selectStatement) assertThat(rows).hasSize(1) with(rows[0]) { assertThat(this).containsEntry("ITEM_ID", 22) assertThat(this).containsEntry("DESCRIPTION", "Helmet") } } } @Test fun testAndExistsAnd2() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonSelectMapper::class.java) val selectStatement = select(itemMaster.allColumns()) { from(itemMaster, "im") where { itemMaster.itemId isEqualTo 22 and { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where { orderLine.itemId isEqualTo "im"(itemMaster.itemId) } } } } and { itemMaster.itemId isGreaterThan 2 } } orderBy(itemMaster.itemId) } val expectedStatement = "select im.* from ItemMaster im" + " where im.item_id = #{parameters.p1,jdbcType=INTEGER}" + " and exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" + " and im.item_id > #{parameters.p2,jdbcType=INTEGER}" + " order by item_id" assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) val rows = mapper.selectManyMappedRows(selectStatement) assertThat(rows).hasSize(1) with(rows[0]) { assertThat(this).containsEntry("ITEM_ID", 22) assertThat(this).containsEntry("DESCRIPTION", "Helmet") } } } @Test fun testAndExistsAnd3() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonSelectMapper::class.java) val selectStatement = select(itemMaster.allColumns()) { from(itemMaster, "im") where { itemMaster.itemId isEqualTo 22 and { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where { orderLine.itemId isEqualTo "im"(itemMaster.itemId) } } } and { itemMaster.itemId isGreaterThan 2 } } } orderBy(itemMaster.itemId) } val expectedStatement = "select im.* from ItemMaster im" + " where im.item_id = #{parameters.p1,jdbcType=INTEGER}" + " and (exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" + " and im.item_id > #{parameters.p2,jdbcType=INTEGER})" + " order by item_id" assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) val rows = mapper.selectManyMappedRows(selectStatement) assertThat(rows).hasSize(1) with(rows[0]) { assertThat(this).containsEntry("ITEM_ID", 22) assertThat(this).containsEntry("DESCRIPTION", "Helmet") } } } @Test fun testOrExists() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonSelectMapper::class.java) val selectStatement = select(itemMaster.allColumns()) { from(itemMaster, "im") where { itemMaster.itemId isEqualTo 22 } or { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where { orderLine.itemId isEqualTo "im"(itemMaster.itemId) } } } } orderBy(itemMaster.itemId) } val expectedStatement = "select im.* from ItemMaster im" + " where im.item_id = #{parameters.p1,jdbcType=INTEGER}" + " or exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" + " order by item_id" assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) val rows = mapper.selectManyMappedRows(selectStatement) assertThat(rows).hasSize(3) with(rows[0]) { assertThat(this).containsEntry("ITEM_ID", 22) assertThat(this).containsEntry("DESCRIPTION", "Helmet") } with(rows[1]) { assertThat(this).containsEntry("ITEM_ID", 33) assertThat(this).containsEntry("DESCRIPTION", "First Base Glove") } with(rows[2]) { assertThat(this).containsEntry("ITEM_ID", 44) assertThat(this).containsEntry("DESCRIPTION", "Outfield Glove") } } } @Test fun testOrExistsAnd() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonSelectMapper::class.java) val selectStatement = select(itemMaster.allColumns()) { from(itemMaster, "im") where { itemMaster.itemId isEqualTo 22 } or { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where { orderLine.itemId isEqualTo "im"(itemMaster.itemId) } } } and { itemMaster.itemId isGreaterThan 2 } } orderBy(itemMaster.itemId) } val expectedStatement = "select im.* from ItemMaster im" + " where im.item_id = #{parameters.p1,jdbcType=INTEGER}" + " or (exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" + " and im.item_id > #{parameters.p2,jdbcType=INTEGER})" + " order by item_id" assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) val rows = mapper.selectManyMappedRows(selectStatement) assertThat(rows).hasSize(3) with(rows[0]) { assertThat(this).containsEntry("ITEM_ID", 22) assertThat(this).containsEntry("DESCRIPTION", "Helmet") } with(rows[1]) { assertThat(this).containsEntry("ITEM_ID", 33) assertThat(this).containsEntry("DESCRIPTION", "First Base Glove") } with(rows[2]) { assertThat(this).containsEntry("ITEM_ID", 44) assertThat(this).containsEntry("DESCRIPTION", "Outfield Glove") } } } @Test fun testOrExistsAnd2() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonSelectMapper::class.java) val selectStatement = select(itemMaster.allColumns()) { from(itemMaster, "im") where { itemMaster.itemId isEqualTo 22 or { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where { orderLine.itemId isEqualTo "im"(itemMaster.itemId) } } } } and { itemMaster.itemId isGreaterThan 2 } } orderBy(itemMaster.itemId) } val expectedStatement = "select im.* from ItemMaster im" + " where im.item_id = #{parameters.p1,jdbcType=INTEGER}" + " or exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" + " and im.item_id > #{parameters.p2,jdbcType=INTEGER}" + " order by item_id" assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) val rows = mapper.selectManyMappedRows(selectStatement) assertThat(rows).hasSize(3) with(rows[0]) { assertThat(this).containsEntry("ITEM_ID", 22) assertThat(this).containsEntry("DESCRIPTION", "Helmet") } with(rows[1]) { assertThat(this).containsEntry("ITEM_ID", 33) assertThat(this).containsEntry("DESCRIPTION", "First Base Glove") } with(rows[2]) { assertThat(this).containsEntry("ITEM_ID", 44) assertThat(this).containsEntry("DESCRIPTION", "Outfield Glove") } } } @Test fun testOrExistsAnd3() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonSelectMapper::class.java) val selectStatement = select(itemMaster.allColumns()) { from(itemMaster, "im") where { itemMaster.itemId isEqualTo 22 or { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where { orderLine.itemId isEqualTo "im"(itemMaster.itemId) } } } and { itemMaster.itemId isGreaterThan 2 } } } orderBy(itemMaster.itemId) } val expectedStatement = "select im.* from ItemMaster im" + " where im.item_id = #{parameters.p1,jdbcType=INTEGER}" + " or (exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" + " and im.item_id > #{parameters.p2,jdbcType=INTEGER})" + " order by item_id" assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) val rows = mapper.selectManyMappedRows(selectStatement) assertThat(rows).hasSize(3) with(rows[0]) { assertThat(this).containsEntry("ITEM_ID", 22) assertThat(this).containsEntry("DESCRIPTION", "Helmet") } with(rows[1]) { assertThat(this).containsEntry("ITEM_ID", 33) assertThat(this).containsEntry("DESCRIPTION", "First Base Glove") } with(rows[2]) { assertThat(this).containsEntry("ITEM_ID", 44) assertThat(this).containsEntry("DESCRIPTION", "Outfield Glove") } } } @Test fun testWhereExistsOr() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonSelectMapper::class.java) val selectStatement = select(itemMaster.allColumns()) { from(itemMaster, "im") where { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where { orderLine.itemId isEqualTo "im"(itemMaster.itemId) } } } or { itemMaster.itemId isEqualTo 22 } } orderBy(itemMaster.itemId) } val expectedStatement = "select im.* from ItemMaster im" + " where exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" + " or im.item_id = #{parameters.p1,jdbcType=INTEGER}" + " order by item_id" assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) val rows = mapper.selectManyMappedRows(selectStatement) assertThat(rows).hasSize(3) with(rows[0]) { assertThat(this).containsEntry("ITEM_ID", 22) assertThat(this).containsEntry("DESCRIPTION", "Helmet") } with(rows[1]) { assertThat(this).containsEntry("ITEM_ID", 33) assertThat(this).containsEntry("DESCRIPTION", "First Base Glove") } with(rows[2]) { assertThat(this).containsEntry("ITEM_ID", 44) assertThat(this).containsEntry("DESCRIPTION", "Outfield Glove") } } } @Test fun testWhereExistsAnd() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonSelectMapper::class.java) val selectStatement = select(itemMaster.allColumns()) { from(itemMaster, "im") where { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where { orderLine.itemId isEqualTo "im"(itemMaster.itemId) } } } and { itemMaster.itemId isEqualTo 22 } } orderBy(itemMaster.itemId) } val expectedStatement = "select im.* from ItemMaster im" + " where exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" + " and im.item_id = #{parameters.p1,jdbcType=INTEGER}" + " order by item_id" assertThat(selectStatement.selectStatement).isEqualTo(expectedStatement) val rows = mapper.selectManyMappedRows(selectStatement) assertThat(rows).hasSize(1) with(rows[0]) { assertThat(this).containsEntry("ITEM_ID", 22) assertThat(this).containsEntry("DESCRIPTION", "Helmet") } } } @Test fun testDeleteWithHardAlias() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonDeleteMapper::class.java) val im = itemMaster.withAlias("im") val deleteStatement = deleteFrom(im) { where { not { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where{orderLine.itemId isEqualTo im.itemId} } } } } } val expectedStatement = "delete from ItemMaster im where not exists " + "(select ol.* from OrderLine ol where ol.item_id = im.item_id)" assertThat(deleteStatement.deleteStatement).isEqualTo(expectedStatement) val rows = mapper.delete(deleteStatement) assertThat(rows).isEqualTo(1) } } @Test fun testDeleteWithSoftAlias() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonDeleteMapper::class.java) val deleteStatement = deleteFrom(itemMaster, "im") { where { not { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where{orderLine.itemId isEqualTo itemMaster.itemId} } } } } } val expectedStatement = "delete from ItemMaster im where not exists " + "(select ol.* from OrderLine ol where ol.item_id = im.item_id)" assertThat(deleteStatement.deleteStatement).isEqualTo(expectedStatement) val rows = mapper.delete(deleteStatement) assertThat(rows).isEqualTo(1) } } @Test fun testUpdateWithHardAlias() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonUpdateMapper::class.java) val im = itemMaster.withAlias("im") val updateStatement = update(im) { set(im.description) equalTo "No Orders" where { not { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where{orderLine.itemId isEqualTo im.itemId} } } } } } val expectedStatement = "update ItemMaster im " + "set im.description = #{parameters.p1,jdbcType=VARCHAR} " + "where not exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" assertThat(updateStatement.updateStatement).isEqualTo(expectedStatement) val rows = mapper.update(updateStatement) assertThat(rows).isEqualTo(1) } } @Test fun testUpdateWithSoftAlias() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(CommonUpdateMapper::class.java) val updateStatement = update(itemMaster, "im") { set(itemMaster.description) equalTo "No Orders" where { not { exists { select(orderLine.allColumns()) { from(orderLine, "ol") where{orderLine.itemId isEqualTo itemMaster.itemId} } } } } } val expectedStatement = "update ItemMaster im " + "set im.description = #{parameters.p1,jdbcType=VARCHAR} " + "where not exists (select ol.* from OrderLine ol where ol.item_id = im.item_id)" assertThat(updateStatement.updateStatement).isEqualTo(expectedStatement) val rows = mapper.update(updateStatement) assertThat(rows).isEqualTo(1) } } }
apache-2.0
7ede0e7d9140c059609292c398bb5bbc
38.362809
103
0.515824
5.155851
false
true
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/presentation/user_reviews/mapper/UserReviewsStateMapper.kt
1
11662
package org.stepik.android.presentation.user_reviews.mapper import org.stepik.android.domain.course_reviews.model.CourseReview import org.stepik.android.domain.user_reviews.model.UserCourseReviewItem import org.stepik.android.presentation.user_reviews.UserReviewsFeature import ru.nobird.android.core.model.mutate import javax.inject.Inject class UserReviewsStateMapper @Inject constructor() { /** * Operations from UserCourseReviewOperationBus */ fun mergeStateWithNewReview(state: UserReviewsFeature.State.Content, courseReview: CourseReview): UserReviewsFeature.State.Content? { val indexOfReviewedCourse = state.userCourseReviewsResult.potentialReviewItems.indexOfFirst { it.id == courseReview.course } return if (indexOfReviewedCourse == -1) { null } else { val reviewedCourse = state.userCourseReviewsResult.potentialReviewItems[indexOfReviewedCourse] val updatedReviewedItems = state.userCourseReviewsResult.reviewedReviewItems.mutate { add(0, UserCourseReviewItem.ReviewedItem(reviewedCourse.course, courseReview)) } val updatedReviewedHeader = listOf(UserCourseReviewItem.ReviewedHeader(reviewedCount = updatedReviewedItems.size)) val updatedPotentialReviews = state.userCourseReviewsResult.potentialReviewItems.mutate { removeAt(indexOfReviewedCourse) } val updatedPotentialReviewHeader = if (updatedPotentialReviews.isEmpty()) { emptyList() } else { listOf(UserCourseReviewItem.PotentialReviewHeader(potentialReviewCount = updatedPotentialReviews.size)) } state.copy( userCourseReviewsResult = state.userCourseReviewsResult.copy( userCourseReviewItems = updatedPotentialReviewHeader + updatedPotentialReviews + updatedReviewedHeader + updatedReviewedItems, potentialHeader = updatedPotentialReviewHeader, potentialReviewItems = updatedPotentialReviews, reviewedHeader = updatedReviewedHeader, reviewedReviewItems = updatedReviewedItems ) ) } } fun mergeStateWithEditedReview(state: UserReviewsFeature.State.Content, courseReview: CourseReview): UserReviewsFeature.State.Content? { val indexOfEditedReview = state.userCourseReviewsResult.reviewedReviewItems.indexOfFirst { it.id == courseReview.course } return if (indexOfEditedReview == -1) { null } else { val updatedReviewedItems = state .userCourseReviewsResult .reviewedReviewItems .mutate { val oldItem = get(indexOfEditedReview) set(indexOfEditedReview, oldItem.copy(courseReview = courseReview)) } state.copy( userCourseReviewsResult = state.userCourseReviewsResult.copy( userCourseReviewItems = with(state.userCourseReviewsResult) { potentialHeader + potentialReviewItems + reviewedHeader + updatedReviewedItems }, reviewedReviewItems = updatedReviewedItems ) ) } } fun mergeStateWithDeletedReview(state: UserReviewsFeature.State.Content, courseReview: CourseReview): UserReviewsFeature.State.Content? { val indexOfDeletedReview = state.userCourseReviewsResult.reviewedReviewItems.indexOfFirst { it.id == courseReview.course } return if (indexOfDeletedReview == -1) { null } else { val deletedReviewItem = state.userCourseReviewsResult.reviewedReviewItems[indexOfDeletedReview] val updatedReviewedItems = state.userCourseReviewsResult.reviewedReviewItems.mutate { removeAt(indexOfDeletedReview) } val updatedReviewedHeader = if (updatedReviewedItems.isEmpty()) { emptyList() } else { listOf(UserCourseReviewItem.ReviewedHeader(reviewedCount = updatedReviewedItems.size)) } val updatedPotentialItems = state.userCourseReviewsResult.potentialReviewItems.mutate { add(UserCourseReviewItem.PotentialReviewItem(deletedReviewItem.course)) } val updatedPotentialReviewHeader = listOf(UserCourseReviewItem.PotentialReviewHeader(potentialReviewCount = updatedPotentialItems.size)) state.copy( userCourseReviewsResult = state.userCourseReviewsResult.copy( userCourseReviewItems = updatedPotentialReviewHeader + updatedPotentialItems + updatedReviewedHeader + updatedReviewedItems, potentialHeader = updatedPotentialReviewHeader, potentialReviewItems = updatedPotentialItems, reviewedHeader = updatedReviewedHeader, reviewedReviewItems = updatedReviewedItems ) ) } } /** * Operations from UserReviewsFragment screen */ fun mergeStateWithDeletedReviewPlaceholder(state: UserReviewsFeature.State.Content, courseReview: CourseReview): UserReviewsFeature.State.Content? { val indexOfDeletedReview = state.userCourseReviewsResult.reviewedReviewItems.indexOfFirst { it.id == courseReview.course } return if (indexOfDeletedReview == -1) { null } else { val deletedReviewItem = state.userCourseReviewsResult.reviewedReviewItems[indexOfDeletedReview] val updatedReviewedItemsDisplay = (state.userCourseReviewsResult.reviewedReviewItems as List<UserCourseReviewItem>).mutate { set(indexOfDeletedReview, UserCourseReviewItem.Placeholder(courseId = deletedReviewItem.id, course = deletedReviewItem.course)) } state.copy( userCourseReviewsResult = state.userCourseReviewsResult.copy( userCourseReviewItems = with(state.userCourseReviewsResult) { potentialHeader + potentialReviewItems + reviewedHeader + updatedReviewedItemsDisplay } ) ) } } fun mergeStateWithDeletedReviewToSuccess(state: UserReviewsFeature.State.Content, courseReview: CourseReview): UserReviewsFeature.State.Content? { val indexOfPlaceholder = state.userCourseReviewsResult.userCourseReviewItems.indexOfFirst { it is UserCourseReviewItem.Placeholder && it.id == courseReview.course } return if (indexOfPlaceholder == -1) { null } else { val course = (state.userCourseReviewsResult.userCourseReviewItems[indexOfPlaceholder] as UserCourseReviewItem.Placeholder).course ?: return null val newPotentialReviewItem = UserCourseReviewItem.PotentialReviewItem(course = course) val updatedPotentialItems = state.userCourseReviewsResult.potentialReviewItems.mutate { add(newPotentialReviewItem) } val updatedPotentialReviewHeader = listOf(UserCourseReviewItem.PotentialReviewHeader(potentialReviewCount = updatedPotentialItems.size)) val deletedReviewedItemIndex = state.userCourseReviewsResult.reviewedReviewItems.indexOfFirst { it.id == courseReview.course } val updatedReviewedItems = if (deletedReviewedItemIndex == -1) { state.userCourseReviewsResult.reviewedReviewItems } else { state.userCourseReviewsResult.reviewedReviewItems.mutate { removeAt(deletedReviewedItemIndex) } } val updatedReviewedHeader = if (updatedReviewedItems.isEmpty()) { emptyList() } else { listOf(UserCourseReviewItem.ReviewedHeader(updatedReviewedItems.size)) } state.copy( userCourseReviewsResult = state.userCourseReviewsResult.copy( userCourseReviewItems = updatedPotentialReviewHeader + updatedPotentialItems + updatedReviewedHeader + updatedReviewedItems, potentialHeader = updatedPotentialReviewHeader, potentialReviewItems = updatedPotentialItems, reviewedHeader = updatedReviewedHeader, reviewedReviewItems = updatedReviewedItems ) ) } } fun mergeStateWithDeletedReviewToError(state: UserReviewsFeature.State.Content): UserReviewsFeature.State.Content = state.copy( userCourseReviewsResult = state.userCourseReviewsResult.copy( userCourseReviewItems = with(state.userCourseReviewsResult) { potentialHeader + potentialReviewItems + reviewedHeader + reviewedReviewItems } ) ) fun mergeStateWithDroppedCourse(state: UserReviewsFeature.State.Content, droppedCourseId: Long): UserReviewsFeature.State.Content { val (updatedPotentialItems, updatedReviewedItems) = with(state.userCourseReviewsResult) { potentialReviewItems.filterNot { it.id == droppedCourseId } to reviewedReviewItems.filterNot { it.id == droppedCourseId } } val updatedPotentialHeader = if (updatedPotentialItems.isEmpty()) { emptyList() } else { listOf(UserCourseReviewItem.PotentialReviewHeader(updatedPotentialItems.size)) } val updatedReviewedHeader = if (updatedReviewedItems.isEmpty()) { emptyList() } else { listOf(UserCourseReviewItem.ReviewedHeader(updatedReviewedItems.size)) } return state.copy( userCourseReviewsResult = state.userCourseReviewsResult.copy( userCourseReviewItems = updatedPotentialHeader + updatedPotentialItems + updatedReviewedHeader + updatedReviewedItems, potentialHeader = updatedPotentialHeader, potentialReviewItems = updatedPotentialItems, reviewedHeader = updatedReviewedHeader, reviewedReviewItems = updatedReviewedItems ) ) } fun mergeStateWithEnrolledReviewedItem(state: UserReviewsFeature.State.Content, reviewedItem: UserCourseReviewItem.ReviewedItem): UserReviewsFeature.State.Content { val updatedReviewedItems = state.userCourseReviewsResult.reviewedReviewItems.mutate { add(reviewedItem) } val updatedReviewedHeader = listOf(UserCourseReviewItem.ReviewedHeader(updatedReviewedItems.size)) return state.copy( userCourseReviewsResult = state.userCourseReviewsResult.copy( userCourseReviewItems = with(state.userCourseReviewsResult) { potentialHeader + potentialReviewItems + updatedReviewedHeader + updatedReviewedItems }, reviewedHeader = updatedReviewedHeader, reviewedReviewItems = updatedReviewedItems ) ) } fun mergeStateWithEnrolledPotentialReviewItem(state: UserReviewsFeature.State.Content, potentialReviewItem: UserCourseReviewItem.PotentialReviewItem): UserReviewsFeature.State.Content { val updatedPotentialItems = state.userCourseReviewsResult.potentialReviewItems.mutate { add(potentialReviewItem) } val updatedPotentialHeader = listOf(UserCourseReviewItem.PotentialReviewHeader(updatedPotentialItems.size)) return state.copy( userCourseReviewsResult = state.userCourseReviewsResult.copy( userCourseReviewItems = with(state.userCourseReviewsResult) { updatedPotentialHeader + updatedPotentialItems + reviewedHeader + reviewedReviewItems }, potentialHeader = updatedPotentialHeader, potentialReviewItems = updatedPotentialItems ) ) } }
apache-2.0
3cd8ebbc32d8e90c40d1ffcff48ea0aa
54.803828
189
0.697393
5.542776
false
false
false
false
artspb/php-generator
src/main/kotlin/me/artspb/php/generator/model/compound/CompoundStatement.kt
1
4890
package me.artspb.php.generator.model.compound import me.artspb.php.generator.model.* import me.artspb.php.generator.model.compound._class.Class import me.artspb.php.generator.model.compound._class.Interface import me.artspb.php.generator.model.compound._class.PropertyDeclaration import me.artspb.php.generator.model.compound._class.Trait import me.artspb.php.generator.model.compound.namespace.NamespaceDefinition import me.artspb.php.generator.model.phpdoc.PhpDoc abstract class CompoundStatementElement(val braces: Boolean = true) : ElementWithChildren() { operator fun String.unaryPlus() { children.add(ArbitraryStatement(this)) } fun comment(delimited: Boolean = false, symbol: String = "//", init: Comment.() -> Unit) = initElement(Comment(delimited, symbol), init) fun function(name: String, init: FunctionDefinition.() -> Unit) = initElement(FunctionDefinition(name), init) fun _for(expr1: String = "", expr2: String = "", expr3: String = "", init: ForStatement.() -> Unit) = initElement(ForStatement(expr1, expr2, expr3), init) fun foreach(array: String, key: String = "", value: String, init: ForeachStatement.() -> Unit) = initElement(ForeachStatement(array, key, value), init) fun _try(init: TryStatement.() -> Unit) = initElement(TryStatement(), init) fun catch(exception: String, variable: String, init: CatchStatement.() -> Unit) = initElement(CatchStatement(exception, variable), init) // TODO think how to make catch depending on _try fun finally(init: FinallyStatement.() -> Unit) = initElement(FinallyStatement(), init) // TODO think how to make finally depending on _try fun const(name: String, initializer: () -> String) = initElement(ConstantDeclaration(name, initializer = initializer), {}) fun _interface(name: String, init: Interface.() -> Unit) = initElement(Interface(name), init) fun _class(name: String, vararg modifiers: String, init: Class.() -> Unit) = initElement(Class(name, *modifiers), init) fun trait(name: String, init: Class.() -> Unit) = initElement(Trait(name), init) fun phpdoc(init: PhpDoc.() -> Unit) = initElement(PhpDoc(), init) override fun generate(builder: StringBuilder, indent: String) { builder.appendAndTrim(indent + generateHeader() + " " + (if (braces) "{" else "")).append(afterLBrace()) for (c in children) { c.generate(builder, indent + if (braces) INDENT else "") } builder.appendAndTrim(indent + (if (braces) "}" else "")).append(afterRBrace()) } protected abstract fun generateHeader(): String protected open fun afterLBrace() = "\n" protected open fun afterRBrace() = "\n" } class Php : CompoundStatementElement(false) { fun namespace(name: String = "", braces: Boolean = true, init: NamespaceDefinition.() -> Unit) = initElement(NamespaceDefinition(name, braces), init) override fun generateHeader() = "<?php" override fun afterRBrace() = "" } open class FunctionDefinition(private val name: String, braces: Boolean = true) : CompoundStatementElement(braces) { private var returnType = "" private val parameters = arrayListOf<Triple<String, String, () -> String>>() fun returnType(returnType: String) { this.returnType = returnType } fun parameter(name: String, type: String = "", defaultValue: () -> String = { "" }) = parameters.add(Triple(name, type, defaultValue)) override fun generateHeader() = "function $name(${generateParameters()})" + (if (returnType.isNotEmpty()) ": $returnType" else "") private fun generateParameters() = parameters.joinToString(", ") { (if (it.second.isNotEmpty()) "${it.second} " else "") + "\$" + it.first + if (it.third().isNotEmpty()) " = ${it.third()}" else "" } } class ForStatement(private val expr1: String, private val expr2: String, private val expr3: String) : CompoundStatementElement() { override fun generateHeader() = "for ($expr1; $expr2; $expr3)" } class ForeachStatement(private val array: String, private val key: String, private val value: String) : CompoundStatementElement() { override fun generateHeader() = "foreach ($array as ${if (key.isNotEmpty()) "$key => " else ""}$value)" } class TryStatement : CompoundStatementElement() { override fun generateHeader() = "try" } class CatchStatement(private val exception: String, private val variable: String) : CompoundStatementElement() { override fun generateHeader() = "catch ($exception $variable)" } class FinallyStatement : CompoundStatementElement() { override fun generateHeader() = "finally" } class ConstantDeclaration(name: String, vararg modifiers: String, initializer: () -> String) : PropertyDeclaration(name, *modifiers, "const", initializer = initializer)
apache-2.0
afcb6e42f9a8fe501d574b516babd866
42.274336
142
0.682618
4.095477
false
false
false
false
WangDaYeeeeee/GeometricWeather
app/src/main/java/wangdaye/com/geometricweather/common/ui/widgets/insets/FitSystemBarComposeWrappers.kt
1
4697
package wangdaye.com.geometricweather.common.ui.widgets.insets import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.material.AppBarDefaults import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.compositeOver import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import wangdaye.com.geometricweather.R import wangdaye.com.geometricweather.common.ui.widgets.getWidgetSurfaceColor import kotlin.math.ln private val topAppBarElevation = 6.dp internal fun ColorScheme.applyTonalElevation(backgroundColor: Color, elevation: Dp): Color { return if (backgroundColor == surface) { surfaceColorAtElevation(elevation) } else { backgroundColor } } internal fun ColorScheme.surfaceColorAtElevation(elevation: Dp): Color { if (elevation == 0.dp) return surface val alpha = ((4.5f * ln(elevation.value + 1)) + 2f) / 100f return surfaceTint.copy(alpha = alpha).compositeOver(surface) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun FitStatusBarTopAppBar( title: @Composable () -> Unit, modifier: Modifier = Modifier, navigationIcon: @Composable (() -> Unit) = {}, actions: @Composable RowScope.() -> Unit = {}, scrollBehavior: TopAppBarScrollBehavior? = null, ) = Column { Spacer( modifier = Modifier .background(getWidgetSurfaceColor(topAppBarElevation)) .windowInsetsTopHeight(WindowInsets.statusBars) .fillMaxWidth(), ) MediumTopAppBar( title = title, modifier = modifier, navigationIcon = navigationIcon, actions = actions, colors = TopAppBarDefaults.mediumTopAppBarColors( containerColor = MaterialTheme.colorScheme.surface, scrolledContainerColor = MaterialTheme.colorScheme.applyTonalElevation( backgroundColor = MaterialTheme.colorScheme.surface, elevation = topAppBarElevation, ), navigationIconContentColor = MaterialTheme.colorScheme.onSurface, titleContentColor = MaterialTheme.colorScheme.onSurface, actionIconContentColor = MaterialTheme.colorScheme.onSurface, ), scrollBehavior = scrollBehavior, ) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun FitStatusBarTopAppBar( title: String, onBackPressed: () -> Unit, actions: @Composable RowScope.() -> Unit = {}, scrollBehavior: TopAppBarScrollBehavior? = null, ) = FitStatusBarTopAppBar( title = { Text(text = title) }, navigationIcon = { IconButton(onClick = onBackPressed) { Icon( imageVector = Icons.Filled.ArrowBack, contentDescription = stringResource(R.string.content_desc_back), tint = MaterialTheme.colorScheme.onPrimaryContainer, ) } }, actions = actions, scrollBehavior = scrollBehavior, ) @Composable fun FitNavigationBarBottomAppBar( modifier: Modifier = Modifier, containerColor: Color = MaterialTheme.colorScheme.primaryContainer, contentColor: Color = contentColorFor(containerColor), tonalElevation: Dp = AppBarDefaults.BottomAppBarElevation, contentPadding: PaddingValues = BottomAppBarDefaults.ContentPadding, content: @Composable RowScope.() -> Unit ) { Box { Column { BottomAppBar( modifier = modifier, containerColor = containerColor, contentColor = contentColor, tonalElevation = tonalElevation, contentPadding = contentPadding, content = content, ) } Spacer( modifier = Modifier .background(containerColor) .windowInsetsBottomHeight(WindowInsets.navigationBars) .fillMaxWidth() .align(Alignment.BottomCenter), ) } } enum class BottomInsetKey { INSTANCE } fun LazyListScope.bottomInsetItem( extraHeight: Dp = 0.dp, ) = item( key = { BottomInsetKey.INSTANCE }, contentType = { BottomInsetKey.INSTANCE }, ) { Column { Spacer(modifier = Modifier.height(extraHeight)) Spacer(modifier = Modifier.windowInsetsBottomHeight(WindowInsets.navigationBars)) } }
lgpl-3.0
7d6b7aff0543abfd0532c153060ba29f
34.059701
92
0.688525
5.0397
false
false
false
false
hotpodata/common
src/main/java/com/hotpodata/common/data/Contact.kt
1
3503
package com.hotpodata.common.data import android.content.Context import android.content.Intent import android.net.Uri import com.hotpodata.common.R import com.hotpodata.common.enums.Contacts import timber.log.Timber import java.util.* /** * Created by jdrotos on 1/13/16. */ abstract open class Contact(val iconResId: Int, val name: String, val desc: String) { object Factory { fun genContacts(context: Context, appName: String): List<Contact> { var contacts = ArrayList<Contact>() for (contact in Contacts.values()) { contacts.add(createContact(context, contact, appName)) } return contacts } fun createContact(context: Context, contact: Contacts, appName: String): Contact { var icon = when (contact) { Contacts.EMAIL -> R.drawable.ic_action_mail Contacts.GITHUB -> R.drawable.ic_action_github Contacts.TWITTER -> R.drawable.ic_action_twitter Contacts.WEB -> R.drawable.ic_action_web } var title = when (contact) { Contacts.EMAIL -> context.getString(R.string.email_title) Contacts.GITHUB -> context.getString(R.string.github_title) Contacts.TWITTER -> context.getString(R.string.twitter_title) Contacts.WEB -> context.getString(R.string.visit_website) } var blurb = when (contact) { Contacts.EMAIL -> context.getString(R.string.email_addr_TEMPLATE, appName) Contacts.GITHUB -> context.getString(R.string.github_handle) Contacts.TWITTER -> context.getString(R.string.twitter_handle) Contacts.WEB -> context.getString(R.string.visit_website_blurb) } var intentData = when (contact) { Contacts.EMAIL -> context.getString(R.string.email_addr_TEMPLATE, appName) Contacts.GITHUB -> context.getString(R.string.github_url) Contacts.TWITTER -> context.getString(R.string.twitter_url) Contacts.WEB -> context.getString(R.string.visit_website_url) } return when (contact) { Contacts.EMAIL -> object : Contact(icon, title, blurb) { override fun genActionIntent(context: Context): Intent { val intent = Intent(Intent.ACTION_SEND) intent.setType("message/rfc822") intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(intentData)) return intent } } else -> object : Contact(icon, title, blurb) { override fun genActionIntent(context: Context): Intent { val intent = Intent(Intent.ACTION_VIEW) intent.setData(Uri.parse(intentData)) return intent } } } } } abstract fun genActionIntent(context: Context): Intent fun fireIntent(context: Context): Boolean { try { var intent = genActionIntent(context) if (intent.resolveActivity(context.packageManager) != null) { context.startActivity(intent) return true } } catch(ex: Exception) { Timber.e(ex, "Failure to start contact intent") } return false } }
apache-2.0
648dc2d7337d4b6add8587ece1c2123e
38.370787
90
0.566372
4.708333
false
false
false
false
maurocchi/chesslave
backend/src/main/java/io/chesslave/ears/Ears.kt
2
3481
package io.chesslave.ears import io.chesslave.model.MoveDescription import io.chesslave.model.MoveDescription.Status import io.chesslave.model.Piece.Type import org.jparsec.Parser import org.jparsec.Parsers import org.jparsec.Scanners import org.jparsec.Tokens import org.jparsec.pattern.CharPredicates import org.jparsec.pattern.Patterns typealias UtteranceParser = (String) -> MoveDescription? val parseUtterance: UtteranceParser = { utterance -> fun term(text: String): Parser<Boolean> = Parsers.token { if (it.value().toString() == text) true else null } val words = Patterns.isChar(CharPredicates.IS_ALPHA).many1().toScanner("word").source() val nums = Patterns.isChar(CharPredicates.IS_DIGIT).many1().toScanner("num").source() val tokenizer = Parsers.or( words.map { Tokens.fragment(it, "WORD") }, nums.map { Tokens.fragment(it, "NUM") }) val queenParser = Parsers.or(term("donna"), term("regina")) val kingParser = term("re") val pieceParser = Parsers.or( term("pedone").map { Type.PAWN }, term("cavallo").map { Type.KNIGHT }, term("alfiere").map { Type.BISHOP }, term("torre").map { Type.ROOK }, queenParser.map { Type.QUEEN }, kingParser.map { Type.KING }) val colParser = Parsers.or( term("a").map { 0 }, term("b").map { 1 }, term("c").map { 2 }, term("d").map { 3 }, term("e").map { 4 }, term("f").map { 5 }, term("g").map { 6 }, term("h").map { 7 }) val rowParser = Parsers.or( term("1").map { 0 }, term("2").map { 1 }, term("3").map { 2 }, term("4").map { 3 }, term("5").map { 4 }, term("6").map { 5 }, term("7").map { 6 }, term("8").map { 7 }) val squareParser = Parsers.or( Parsers.sequence( pieceParser.followedBy(term("in").optional(null)), colParser.optional(null), rowParser.optional(null), { piece, col, row -> MoveDescription.Square(piece, col, row) }), Parsers.sequence( colParser, rowParser.optional(null), { col, row -> MoveDescription.Square(null, col, row) })) val captureParser = Parsers.or(term("mangia"), term("cattura")) val statusParser = Parsers .or(Parsers.or(term("scacco").next(term("matto")), term("matto"), term("scaccomatto")).map { Status.CHECKMATE }, term("scacco").map { Status.CHECK }) .optional(Status.RELAX) val regularMoveParser = Parsers.sequence( squareParser, captureParser.optional(false), squareParser.optional(null), statusParser, { fst, isCapture, snd, status -> if (snd == null) MoveDescription.Regular(toSquare = fst, status = status) else MoveDescription.Regular(fromSquare = fst, toSquare = snd, capture = isCapture, status = status) }) val castlingParser = Parsers.sequence( term("arrocco"), Parsers.or( Parsers.or(term("corto"), term("di").next(kingParser)).map { true }, Parsers.or(term("lungo"), term("di").next(queenParser)).map { false } ).optional(null), statusParser, { _, short, status -> MoveDescription.Castling(short, status) }) val parser = Parsers.or(regularMoveParser, castlingParser) parser .from(tokenizer.lexer(Scanners.WHITESPACES.optional(null))) .parse(utterance) }
gpl-2.0
cfe4dbf4feccc74f2ebb530f8a765ff9
39.964706
120
0.599828
3.573922
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/AbstractKotlinUClass.kt
3
4513
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtDelegatedSuperTypeEntry import org.jetbrains.kotlin.psi.KtModifierListOwner import org.jetbrains.kotlin.utils.addIfNotNull import org.jetbrains.uast.* import org.jetbrains.uast.internal.acceptList import org.jetbrains.uast.visitor.UastVisitor @ApiStatus.Internal abstract class AbstractKotlinUClass( givenParent: UElement? ) : KotlinAbstractUElement(givenParent), UClass, UAnchorOwner { override val uastDeclarations by lz { mutableListOf<UDeclaration>().apply { addAll(fields) addAll(initializers) addAll(methods) addAll(innerClasses) } } protected open val ktClass: KtClassOrObject? get() = (psi as? KtLightClass)?.kotlinOrigin override val uastSuperTypes: List<UTypeReferenceExpression> get() = ktClass?.superTypeListEntries.orEmpty().mapNotNull { it.typeReference }.map { KotlinUTypeReferenceExpression(it, this) } private val delegateExpressions: List<UExpression> by lz { ktClass?.superTypeListEntries.orEmpty() .filterIsInstance<KtDelegatedSuperTypeEntry>() .map { KotlinSupertypeDelegationUExpression(it, this) } } protected fun computeMethods(): Array<UMethod> { val hasPrimaryConstructor = ktClass?.hasPrimaryConstructor() ?: false var secondaryConstructorsCount = 0 fun createUMethod(psiMethod: PsiMethod): UMethod { return if (psiMethod is KtLightMethod && psiMethod.isConstructor) { if (!hasPrimaryConstructor && secondaryConstructorsCount++ == 0) KotlinSecondaryConstructorWithInitializersUMethod(ktClass, psiMethod, this) else KotlinConstructorUMethod(ktClass, psiMethod, this) } else { languagePlugin?.convertOpt(psiMethod, this) ?: reportConvertFailure(psiMethod) } } fun isDelegatedMethod(psiMethod: PsiMethod) = psiMethod is KtLightMethod && psiMethod.isDelegated val result = ArrayList<UMethod>(javaPsi.methods.size) val handledKtDeclarations = mutableSetOf<PsiElement>() for (lightMethod in javaPsi.methods) { if (isDelegatedMethod(lightMethod)) continue val uMethod = createUMethod(lightMethod) result.add(uMethod) // Ensure we pick the main Kotlin origin, not the auxiliary one val kotlinOrigin = (lightMethod as? KtLightMethod)?.kotlinOrigin ?: uMethod.sourcePsi handledKtDeclarations.addIfNotNull(kotlinOrigin) } val ktDeclarations: List<KtDeclaration> = run ktDeclarations@{ ktClass?.let { return@ktDeclarations it.declarations } (javaPsi as? KtLightClassForFacade)?.let { facade -> return@ktDeclarations facade.files.flatMap { file -> file.declarations } } emptyList() } ktDeclarations.asSequence() .filterNot { handledKtDeclarations.contains(it) } .mapNotNullTo(result) { baseResolveProviderService.baseKotlinConverter.convertDeclaration(it, this, arrayOf(UElement::class.java)) as? UMethod } return result.toTypedArray() } override fun accept(visitor: UastVisitor) { if (visitor.visitClass(this)) return delegateExpressions.acceptList(visitor) uAnnotations.acceptList(visitor) uastDeclarations.acceptList(visitor) visitor.afterVisitClass(this) } override val uAnnotations: List<UAnnotation> by lz { (sourcePsi as? KtModifierListOwner)?.annotationEntries.orEmpty().map { baseResolveProviderService.baseKotlinConverter.convertAnnotation(it, this) } } override fun equals(other: Any?) = other is AbstractKotlinUClass && psi == other.psi override fun hashCode() = psi.hashCode() }
apache-2.0
5806b98cf4cda57a49dcb6a20a704d27
39.657658
158
0.693552
5.328217
false
false
false
false
ksmirenko/cards-toefl
app/src/main/java/io/github/ksmirenko/toeflcards/ToeflCardsDatabaseProvider.kt
1
755
package io.github.ksmirenko.toeflcards import android.content.Context /** * A singleton that provides ToeflCardsDatabase to the app. * * @author Kirill Smirenko */ object ToeflCardsDatabaseProvider { private const val dbFilename = "toeflcards.db" private var database : ToeflCardsDatabase? = null fun initIfNull(context : Context) { if (database == null) { database = ToeflCardsDatabase(context, dbFilename) } } val db : ToeflCardsDatabase get() { if (database == null) { throw IllegalStateException( "ToeflCardsDatabaseProvider must be initialized prior to usage.") } return database as ToeflCardsDatabase } }
apache-2.0
f1286516c13f9ece1fa80b8089899943
25.068966
85
0.631788
4.265537
false
false
false
false
mdaniel/intellij-community
platform/platform-impl/src/com/intellij/ui/mac/MacDockDelegate.kt
2
2886
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ui.mac import com.intellij.ide.DataManager import com.intellij.ide.RecentProjectListActionProvider import com.intellij.ide.ReopenProjectAction import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.wm.impl.SystemDock import java.awt.Menu import java.awt.MenuItem import java.awt.PopupMenu import java.lang.invoke.MethodHandles import java.lang.invoke.MethodType internal class MacDockDelegate private constructor() : SystemDock.Delegate { companion object { private val LOG = logger<MacDockDelegate>() @Suppress("SpellCheckingInspection") private val appClass by lazy { MacDockDelegate::class.java.classLoader.loadClass("com.apple.eawt.Application") } val instance: SystemDock.Delegate by lazy { val result = MacDockDelegate() try { dockMenu.add(recentProjectsMenu) val lookup = MethodHandles.lookup() val appClass = appClass val app = lookup.findStatic(appClass, "getApplication", MethodType.methodType(appClass)).invoke() lookup.findVirtual(appClass, "setDockMenu", MethodType.methodType(Void.TYPE, PopupMenu::class.java)).invoke(app, dockMenu) } catch (e: Exception) { LOG.error(e) } result } private val dockMenu = PopupMenu("DockMenu") private val recentProjectsMenu = Menu("Recent Projects") private fun activateApplication() { try { val appClass = appClass val lookup = MethodHandles.lookup() val app = lookup.findStatic(appClass, "getApplication", MethodType.methodType(appClass)).invoke() lookup.findVirtual(appClass, "requestForeground", MethodType.methodType(Void.TYPE, java.lang.Boolean.TYPE)).invoke(app, false) } catch (e: Exception) { LOG.error(e) } } } override fun updateRecentProjectsMenu() { recentProjectsMenu.removeAll() for (action in RecentProjectListActionProvider.getInstance().getActions(addClearListItem = false)) { val menuItem = MenuItem((action as ReopenProjectAction).projectNameToDisplay) menuItem.addActionListener { // Newly opened project won't become an active window, if another application is currently active. // This is not what user expects, so we activate our application explicitly. activateApplication() ActionUtil.performActionDumbAwareWithCallbacks( action, AnActionEvent.createFromAnAction(action, null, ActionPlaces.DOCK_MENU, DataManager.getInstance().getDataContext(null)) ) } recentProjectsMenu.add(menuItem) } } }
apache-2.0
16e7f57c03aa2df021b9cdebc36dbcb9
38.547945
134
0.72973
4.509375
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/card/nfcv/NFCVCard.kt
1
3340
/* * NFCVCard.kt * * Copyright 2016-2019 Michael Farrell <[email protected]> * Copyright 2019 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.card.nfcv import au.id.micolous.metrodroid.card.CardProtocol import au.id.micolous.metrodroid.card.UnauthorizedException import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.serializers.XMLListIdx import au.id.micolous.metrodroid.transit.TransitData import au.id.micolous.metrodroid.transit.TransitIdentity import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.ImmutableByteArray import au.id.micolous.metrodroid.util.hexString import kotlinx.serialization.Serializable import kotlinx.serialization.Transient /** * Utility class for reading NfcV / Vicinity / ISO 15693 * * Reference: https://www.ti.com/lit/an/sloa141/sloa141.pdf */ @Serializable data class NFCVCard constructor( val sysInfo: ImmutableByteArray?, @XMLListIdx("index") val pages: List<NFCVPage>, override val isPartialRead: Boolean = false) : CardProtocol() { @Transient override val rawData: List<ListItem> get() = listOf(ListItem(R.string.nfcv_system_info, sysInfo?.toHexDump())) +pages.mapIndexed { idx, sector -> val pageIndexString = idx.hexString if (sector.isUnauthorized) { ListItem(Localizer.localizeFormatted( R.string.unauthorized_page_title_format, pageIndexString), null) } else { ListItem(Localizer.localizeFormatted( R.string.page_title_format, pageIndexString), sector.data.toHexDump()) } } private fun findTransitFactory(): NFCVCardTransitFactory? { for (factory in NFCVTransitRegistry.allFactories) { try { if (factory.check(this)) return factory } catch (e: IndexOutOfBoundsException) { /* Not the right factory. Just continue */ } catch (e: UnauthorizedException) { } } return null } override fun parseTransitIdentity(): TransitIdentity? = findTransitFactory()?.parseTransitIdentity(this) override fun parseTransitData(): TransitData? = findTransitFactory()?.parseTransitData(this) fun getPage(index: Int): NFCVPage = pages[index] fun readPages(startPage: Int, pageCount: Int): ImmutableByteArray { var data = ImmutableByteArray.empty() for (index in startPage until startPage + pageCount) { data += getPage(index).data } return data } }
gpl-3.0
9b2c8d8df5f1466428751ca805e3ba04
36.52809
116
0.685629
4.447403
false
false
false
false
nearit/Android-SDK
sample-kotlin/src/main/java/com/nearit/sample_kotlin/MyBackgroundJIS.kt
1
924
package com.nearit.sample_kotlin import android.content.Intent import it.near.sdk.recipes.background.NearBackgroundJobIntentService /** * This is the manifest element for the IntentService * <service android:name=".MyBackgroundJIS" * android:exported="false" * android:permission="android.permission.BIND_JOB_SERVICE"> * <intent-filter> * <action android:name="it.near.sdk.permission.GEO_MESSAGE" /> * <category android:name="android.intent.category.DEFAULT" /> * </intent-filter> * <intent-filter> * <action android:name="it.near.sdk.permission.PUSH_MESSAGE" /> * <category android:name="android.intent.category.DEFAULT" /> * </intent-filter> * </service> */ class MyBackgroundJIS : NearBackgroundJobIntentService() { override fun onHandleWork(intent: Intent) { // in this sample I don't customize anything, I even call super super.onHandleWork(intent) } }
mit
128f4387981caadbf875b68ca64c3b99
30.896552
71
0.712121
3.637795
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/fe10/code-insight/src/org/jetbrains/kotlin/idea/quickfix/KotlinSuppressIntentionAction.kt
1
7833
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.FileModificationService import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview import com.intellij.codeInspection.SuppressIntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.idea.base.fe10.codeInsight.KotlinBaseFe10CodeInsightBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.highlighter.AnnotationHostKind import org.jetbrains.kotlin.idea.util.addAnnotation import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.replaceFileAnnotationList import org.jetbrains.kotlin.resolve.BindingContext class KotlinSuppressIntentionAction( suppressAt: KtElement, private val suppressionKey: String, @SafeFieldForPreview private val kind: AnnotationHostKind ) : SuppressIntentionAction() { private val pointer = suppressAt.createSmartPointer() @SafeFieldForPreview private val project = suppressAt.project override fun getFamilyName() = KotlinBaseFe10CodeInsightBundle.message("intention.suppress.family") override fun getText() = KotlinBaseFe10CodeInsightBundle.message("intention.suppress.text", suppressionKey, kind.kind, kind.name ?: "") override fun isAvailable(project: Project, editor: Editor?, element: PsiElement) = element.isValid override fun invoke(project: Project, editor: Editor?, element: PsiElement) { if (!element.isValid) return val suppressAt = pointer.element ?: return if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return val id = "\"$suppressionKey\"" when (suppressAt) { is KtModifierListOwner -> suppressAt.addAnnotation( StandardNames.FqNames.suppress, id, whiteSpaceText = if (kind.newLineNeeded) "\n" else " ", addToExistingAnnotation = { entry -> addArgumentToSuppressAnnotation( entry, id ); true }) is KtAnnotatedExpression -> suppressAtAnnotatedExpression(CaretBox(suppressAt, editor), id) is KtExpression -> suppressAtExpression(CaretBox(suppressAt, editor), id) is KtFile -> suppressAtFile(suppressAt, id) } } override fun getFileModifierForPreview(target: PsiFile): KotlinSuppressIntentionAction { return KotlinSuppressIntentionAction( PsiTreeUtil.findSameElementInCopy(pointer.element, target), suppressionKey, kind ) } private fun suppressAtFile(ktFile: KtFile, id: String) { val psiFactory = KtPsiFactory(project) val fileAnnotationList: KtFileAnnotationList? = ktFile.fileAnnotationList if (fileAnnotationList == null) { val newAnnotationList = psiFactory.createFileAnnotationListWithAnnotation(suppressAnnotationText(id, false)) val packageDirective = ktFile.packageDirective val createAnnotationList = if (packageDirective != null && PsiTreeUtil.skipWhitespacesForward(packageDirective) == ktFile.importList) { // packageDirective could be empty but suppression still should be added before it to generate consistent PSI ktFile.addBefore(newAnnotationList, packageDirective) as KtFileAnnotationList } else { replaceFileAnnotationList(ktFile, newAnnotationList) } ktFile.addAfter(psiFactory.createWhiteSpace(kind), createAnnotationList) return } val suppressAnnotation: KtAnnotationEntry? = findSuppressAnnotation(fileAnnotationList) if (suppressAnnotation == null) { val newSuppressAnnotation = psiFactory.createFileAnnotation(suppressAnnotationText(id, false)) fileAnnotationList.add(psiFactory.createWhiteSpace(kind)) fileAnnotationList.add(newSuppressAnnotation) as KtAnnotationEntry return } addArgumentToSuppressAnnotation(suppressAnnotation, id) } private fun suppressAtAnnotatedExpression(suppressAt: CaretBox<KtAnnotatedExpression>, id: String) { val entry = findSuppressAnnotation(suppressAt.expression) if (entry != null) { // already annotated with @suppress addArgumentToSuppressAnnotation(entry, id) } else { suppressAtExpression(suppressAt, id) } } private fun suppressAtExpression(caretBox: CaretBox<KtExpression>, id: String) { val suppressAt = caretBox.expression assert(suppressAt !is KtDeclaration) { "Declarations should have been checked for above" } val placeholderText = "PLACEHOLDER_ID" val annotatedExpression = KtPsiFactory(suppressAt).createExpression(suppressAnnotationText(id) + "\n" + placeholderText) val copy = suppressAt.copy()!! val afterReplace = suppressAt.replace(annotatedExpression) as KtAnnotatedExpression val toReplace = afterReplace.findElementAt(afterReplace.textLength - 2)!! assert(toReplace.text == placeholderText) val result = toReplace.replace(copy)!! caretBox.positionCaretInCopy(result) } private fun addArgumentToSuppressAnnotation(entry: KtAnnotationEntry, id: String) { // add new arguments to an existing entry val args = entry.valueArgumentList val psiFactory = KtPsiFactory(entry) val newArgList = psiFactory.createCallArguments("($id)") when { args == null -> // new argument list entry.addAfter(newArgList, entry.lastChild) args.arguments.isEmpty() -> // replace '()' with a new argument list args.replace(newArgList) else -> args.addArgument(newArgList.arguments[0]) } } private fun suppressAnnotationText(id: String, withAt: Boolean = true): String { return "${if (withAt) "@" else ""}${StandardNames.FqNames.suppress.shortName()}($id)" } private fun findSuppressAnnotation(annotated: KtAnnotated): KtAnnotationEntry? { val context = annotated.analyze() return findSuppressAnnotation(context, annotated.annotationEntries) } private fun findSuppressAnnotation(annotationList: KtFileAnnotationList): KtAnnotationEntry? { val context = annotationList.analyze() return findSuppressAnnotation(context, annotationList.annotationEntries) } private fun findSuppressAnnotation(context: BindingContext, annotationEntries: List<KtAnnotationEntry>): KtAnnotationEntry? { return annotationEntries.firstOrNull { entry -> context.get(BindingContext.ANNOTATION, entry)?.fqName == StandardNames.FqNames.suppress } } } private fun KtPsiFactory.createWhiteSpace(kind: AnnotationHostKind): PsiElement { return if (kind.newLineNeeded) createNewLine() else createWhiteSpace() } private class CaretBox<out E : KtExpression>( val expression: E, private val editor: Editor? ) { private val offsetInExpression: Int = (editor?.caretModel?.offset ?: 0) - expression.textRange!!.startOffset fun positionCaretInCopy(copy: PsiElement) { if (editor == null) return editor.caretModel.moveToOffset(copy.textOffset + offsetInExpression) } }
apache-2.0
2fc9933d8414ae254920d603ca02389b
42.516667
147
0.703562
5.583036
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/CoroutinesInfoFromJsonAndReferencesProvider.kt
4
5463
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.coroutine import com.google.gson.Gson import com.sun.jdi.ArrayReference import com.sun.jdi.ObjectReference import com.sun.jdi.StringReference import com.sun.jdi.ThreadReference import org.jetbrains.kotlin.idea.debugger.coroutine.data.CoroutineInfoData import org.jetbrains.kotlin.idea.debugger.coroutine.data.CoroutineStackTraceProvider import org.jetbrains.kotlin.idea.debugger.coroutine.data.LazyCoroutineInfoData import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.CoroutineInfoProvider import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror.DebugProbesImpl import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror.MirrorOfCoroutineContext import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger import org.jetbrains.kotlin.idea.debugger.base.util.evaluate.DefaultExecutionContext import org.jetbrains.kotlin.utils.addToStdlib.safeAs class CoroutinesInfoFromJsonAndReferencesProvider( private val executionContext: DefaultExecutionContext, private val debugProbesImpl: DebugProbesImpl ) : CoroutineInfoProvider { private val stackTraceProvider = CoroutineStackTraceProvider(executionContext) override fun dumpCoroutinesInfo(): List<CoroutineInfoData> { val array = debugProbesImpl.dumpCoroutinesInfoAsJsonAndReferences(executionContext) ?: return emptyList() if (array.length() != 4) { error("The result array of 'dumpCoroutinesInfoAsJSONAndReferences' should be of size 4") } val coroutinesInfoAsJsonString = array.getValue(0).safeAs<StringReference>()?.value() ?: error("The first element of the result array must be a string") val lastObservedThreadRefs = array.getValue(1).safeAs<ArrayReference>()?.toTypedList<ThreadReference?>() ?: error("The second element of the result array must be an array") val lastObservedFrameRefs = array.getValue(2).safeAs<ArrayReference>()?.toTypedList<ObjectReference?>() ?: error("The third element of the result array must be an array") val coroutineInfoRefs = array.getValue(3).safeAs<ArrayReference>()?.toTypedList<ObjectReference>() ?: error("The fourth element of the result array must be an array") val coroutinesInfo = Gson().fromJson(coroutinesInfoAsJsonString, Array<CoroutineInfoFromJson>::class.java) if (coroutineInfoRefs.size != lastObservedFrameRefs.size || lastObservedFrameRefs.size != coroutinesInfo.size || coroutinesInfo.size != lastObservedThreadRefs.size) { error("Arrays must have equal sizes") } return calculateCoroutineInfoData(coroutinesInfo, coroutineInfoRefs, lastObservedThreadRefs, lastObservedFrameRefs) } private fun calculateCoroutineInfoData( coroutineInfos: Array<CoroutineInfoFromJson>, coroutineInfoRefs: List<ObjectReference>, lastObservedThreadRefs: List<ThreadReference?>, lastObservedFrameRefs: List<ObjectReference?> ): List<CoroutineInfoData> { val result = mutableListOf<LazyCoroutineInfoData>() for ((i, info) in coroutineInfos.withIndex()) { result.add( getLazyCoroutineInfoData( info, coroutineInfoRefs[i], lastObservedThreadRefs[i], lastObservedFrameRefs[i], stackTraceProvider ) ) } return result } private fun getLazyCoroutineInfoData( info: CoroutineInfoFromJson, coroutineInfosRef: ObjectReference, lastObservedThreadRef: ThreadReference?, lastObservedFrameRef: ObjectReference?, stackTraceProvider: CoroutineStackTraceProvider ): LazyCoroutineInfoData { val coroutineContextMirror = MirrorOfCoroutineContext( info.name, info.id, info.dispatcher ) val coroutineInfoMirror = debugProbesImpl.getCoroutineInfo( coroutineInfosRef, executionContext, coroutineContextMirror, info.sequenceNumber, info.state, lastObservedThreadRef, lastObservedFrameRef ) return LazyCoroutineInfoData(coroutineInfoMirror, stackTraceProvider) } private data class CoroutineInfoFromJson( val name: String?, val id: Long?, val dispatcher: String?, val sequenceNumber: Long?, val state: String? ) companion object { fun instance(executionContext: DefaultExecutionContext, debugProbesImpl: DebugProbesImpl): CoroutinesInfoFromJsonAndReferencesProvider? { if (debugProbesImpl.canDumpCoroutinesInfoAsJsonAndReferences()) { return CoroutinesInfoFromJsonAndReferencesProvider(executionContext, debugProbesImpl) } return null } val log by logger } } private inline fun <reified T> ArrayReference.toTypedList(): List<T> { val result = mutableListOf<T>() for (value in values) { if (value !is T) { error("Value has type ${value::class.java}, but ${T::class.java} was expected") } result.add(value) } return result }
apache-2.0
db49ef4bc31ce0cb51c55cfcc7915d6f
42.015748
158
0.698334
5.303883
false
false
false
false
GunoH/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/TransformationContextImpl.kt
6
11884
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.groovy.transformations import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.impl.light.LightMethodBuilder import com.intellij.psi.impl.light.LightPsiClassBuilder import com.intellij.psi.util.MethodSignature import com.intellij.psi.util.PsiTypesUtil import com.intellij.util.containers.FactoryMap import com.intellij.util.containers.toArray import it.unimi.dsi.fastutil.Hash import it.unimi.dsi.fastutil.objects.ObjectOpenCustomHashSet import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition import org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary.modifiers.hasCodeModifierProperty import org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary.modifiers.hasModifierProperty import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType import org.jetbrains.plugins.groovy.lang.psi.impl.statements.typedef.GrEnumTypeDefinitionImpl import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightField import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder import org.jetbrains.plugins.groovy.lang.psi.util.GrClassImplUtil.* import org.jetbrains.plugins.groovy.transformations.dsl.MemberBuilder import java.util.* internal class TransformationContextImpl(private val myCodeClass: GrTypeDefinition) : TransformationContext { private val myProject: Project = myCodeClass.project private val myPsiManager: PsiManager = myCodeClass.manager private val myPsiFacade: JavaPsiFacade = JavaPsiFacade.getInstance(myProject) private var myHierarchyView: PsiClass? = null private val myClassType: PsiClassType = myPsiFacade.elementFactory.createType(codeClass, PsiSubstitutor.EMPTY) private val myMemberBuilder = MemberBuilder(this) private val myMethods: LinkedList<PsiMethod> by lazy(LazyThreadSafetyMode.NONE) { myCodeClass.codeMethods.flatMapTo(LinkedList(), ::expandReflectedMethods) } private val myFields: MutableList<GrField> by lazy(LazyThreadSafetyMode.NONE) { myCodeClass.codeFields.toMutableList() } private val myInnerClasses: MutableList<PsiClass> by lazy(LazyThreadSafetyMode.NONE) { myCodeClass.codeInnerClasses.toMutableList<PsiClass>() } private val myImplementsTypes: MutableList<PsiClassType> by lazy(LazyThreadSafetyMode.NONE) { getReferenceListTypes(myCodeClass.implementsClause).toMutableList() } private val myExtendsTypes: MutableList<PsiClassType> by lazy(LazyThreadSafetyMode.NONE) { getReferenceListTypes(myCodeClass.extendsClause).toMutableList() } private val myModifiers: MutableMap<GrModifierList, MutableList<String>> = mutableMapOf() private val mySignaturesCache: Map<String, MutableSet<MethodSignature>> = FactoryMap.create { name -> val result = ObjectOpenCustomHashSet(AST_TRANSFORMATION_AWARE_METHOD_PARAMETERS_ERASURE_EQUALITY) for (existingMethod in myMethods) { if (existingMethod.name == name) { result.add(existingMethod.getSignature(PsiSubstitutor.EMPTY)) } } result } private val myAnnotations: MutableList<PsiAnnotation> by lazy(LazyThreadSafetyMode.NONE) { myCodeClass.annotations.toMutableList() } // Modifiers should be processed with care in transformation context to avoid recursion issues. // This code re-creates erasures computation to properly handle modifier querying private val AST_TRANSFORMATION_AWARE_METHOD_PARAMETERS_ERASURE_EQUALITY: Hash.Strategy<MethodSignature> = object : Hash.Strategy<MethodSignature> { override fun equals(a: MethodSignature?, b: MethodSignature?): Boolean { if (a === b) return true return (a != null && b != null && a.parameterTypes.map { erase(it) } == b.parameterTypes.map { erase(it) }) } override fun hashCode(signature: MethodSignature?): Int { return signature?.name?.hashCode() ?: 0 } } private fun erase(type: PsiType): PsiType? = type.accept(object : PsiTypeVisitor<PsiType?>() { override fun visitType(type: PsiType): PsiType = type override fun visitArrayType(arrayType: PsiArrayType): PsiType? = arrayType.componentType.accept(this)?.createArrayType() override fun visitClassType(classType: PsiClassType): PsiType = eraseClassType(classType) override fun visitDisjunctionType(disjunctionType: PsiDisjunctionType): PsiType? { val lub = PsiTypesUtil.getLowestUpperBoundClassType(disjunctionType) return lub?.run { eraseClassType(this) } ?: lub } }) override fun eraseClassType(type: PsiClassType): PsiClassType { val factory = JavaPsiFacade.getElementFactory(project) val clazz: PsiClass? = type.resolve() return if (clazz != null) { val erasureSubstitutor = PsiSubstitutor.createSubstitutor(typeParameters(clazz).map { it to null }.toMap()) factory.createType(clazz, erasureSubstitutor, type.languageLevel) } else { return type } } private fun typeParameters(owner: PsiTypeParameterListOwner): List<PsiTypeParameter?> { val result: MutableList<PsiTypeParameter?> = mutableListOf() var currentOwner: PsiTypeParameterListOwner? = owner while (currentOwner != null) { val typeParameters = currentOwner.typeParameters result.addAll(typeParameters) val modifierList = currentOwner.modifierList if (modifierList is GrModifierList && hasModifierProperty(modifierList, PsiModifier.STATIC)) break else if (modifierList != null && hasCodeModifierProperty(currentOwner, PsiModifier.STATIC)) break currentOwner = currentOwner.containingClass } return result } override fun getCodeClass(): GrTypeDefinition = myCodeClass override fun getProject(): Project = myProject override fun getManager(): PsiManager = myPsiManager override fun getPsiFacade(): JavaPsiFacade = myPsiFacade override fun getHierarchyView(): PsiClass { val hierarchyView = myHierarchyView if (hierarchyView != null) { return hierarchyView } val newView = HierarchyView( myCodeClass, myExtendsTypes.toArray(PsiClassType.EMPTY_ARRAY), myImplementsTypes.toArray(PsiClassType.EMPTY_ARRAY), myPsiManager ) myHierarchyView = newView return newView } override fun getClassType(): PsiClassType = myClassType override fun getMemberBuilder(): MemberBuilder = myMemberBuilder override fun getFields(): Collection<GrField> = myFields override fun getAllFields(includeSynthetic: Boolean): Collection<PsiField> { if (!includeSynthetic) { return getAllFields(codeClass, false).toList() } val fields = myFields.toMutableSet<PsiField>() val superTypes = myExtendsTypes + myImplementsTypes for (type in superTypes) { val psiClass = type.resolve() ?: continue fields += psiClass.allFields } return fields } override fun getMethods(): Collection<PsiMethod> = myMethods override fun getInnerClasses(): Collection<PsiClass> = myInnerClasses override fun getImplementsTypes(): List<PsiClassType> = myImplementsTypes override fun getExtendsTypes(): List<PsiClassType> = myExtendsTypes override fun hasModifierProperty(list: GrModifierList, name: String): Boolean = hasModifierProperty(list, name, false) || myModifiers.getOrDefault(list, emptyList()).contains(name) override fun getClassName(): String? = myCodeClass.name override fun getSuperClass(): PsiClass? = getSuperClass(codeClass, myExtendsTypes.toTypedArray()) override fun getAnnotation(fqn: String): PsiAnnotation? = myAnnotations.find { it.qualifiedName == fqn } override fun addAnnotation(annotation: GrAnnotation) { myAnnotations.add(annotation) } override fun isInheritor(baseClass: PsiClass): Boolean { if (manager.areElementsEquivalent(codeClass, baseClass)) return true if (codeClass.isInterface && !baseClass.isInterface) return false for (superType in superTypes) { val superClass = superType.resolve() ?: continue if (manager.areElementsEquivalent(superClass, baseClass)) return true if (superClass.isInheritor(baseClass, true)) return true } return false } override fun findMethodsByName(name: String, checkBases: Boolean): Collection<PsiMethod> { val methods = myMethods.filter { name == it.name } if (checkBases) { val superMethods = superClass?.findMethodsByName(name, true) ?: PsiMethod.EMPTY_ARRAY return methods + superMethods } else { return methods } } private fun doAddMethod(method: PsiMethod, prepend: Boolean) { if (method is GrLightMethodBuilder) { method.setContainingClass(myCodeClass) } else if (method is LightMethodBuilder) { @Suppress("UsePropertyAccessSyntax") method.setContainingClass(myCodeClass) } val signature = method.getSignature(PsiSubstitutor.EMPTY) val signatures = mySignaturesCache.getValue(method.name) if (signatures.add(signature)) { if (prepend) { myMethods.addFirst(method) } else { myMethods.addLast(method) } } } override fun addMethod(method: PsiMethod, prepend: Boolean) { for (expanded in expandReflectedMethods(method)) { doAddMethod(expanded, prepend) } } override fun addMethods(methods: Array<PsiMethod>) { for (method in methods) { addMethod(method) } } override fun addMethods(methods: Collection<PsiMethod>) { for (method in methods) { addMethod(method) } } override fun removeMethod(method: PsiMethod) { val signatures = mySignaturesCache.getValue(method.name) for (expanded in expandReflectedMethods(method)) { val signature = expanded.getSignature(PsiSubstitutor.EMPTY) if (signatures.remove(signature)) { myMethods.removeIf { m -> com.intellij.psi.util.MethodSignatureUtil.areSignaturesErasureEqual(signature, m.getSignature(PsiSubstitutor.EMPTY)) } } } } override fun addField(field: GrField) { if (field is GrLightField) { field.setContainingClass(codeClass) } myFields.add(field) } override fun addInnerClass(innerClass: PsiClass) { if (innerClass is LightPsiClassBuilder) { innerClass.containingClass = codeClass } myInnerClasses.add(innerClass) } override fun setSuperType(fqn: String) = setSuperType(createType(fqn, codeClass)) override fun setSuperType(type: PsiClassType) { if (!codeClass.isInterface) { myExtendsTypes.clear() myExtendsTypes.add(type) myHierarchyView = null } } override fun addInterface(fqn: String) = addInterface(createType(fqn, codeClass)) override fun addInterface(type: PsiClassType) { (if (!codeClass.isInterface || codeClass.isTrait) myImplementsTypes else myExtendsTypes).add(type) myHierarchyView = null } override fun addModifier(modifierList: GrModifierList, modifier: String) { myModifiers.computeIfAbsent(modifierList) { mutableListOf() }.add(modifier) } internal val transformationResult: TransformationResult get() = TransformationResult( (methods + enumMethods()).toArray(PsiMethod.EMPTY_ARRAY), fields.toArray(GrField.EMPTY_ARRAY), innerClasses.toArray(PsiClass.EMPTY_ARRAY), implementsTypes.toArray(PsiClassType.EMPTY_ARRAY), extendsTypes.toArray(PsiClassType.EMPTY_ARRAY), myModifiers ) private fun enumMethods() : List<PsiMethod> { return if (myCodeClass is GrEnumTypeDefinitionImpl) myCodeClass.getDefEnumMethods(this) else emptyList() } }
apache-2.0
e2564eda86ab3cdd25aedac5ea9d828f
38.092105
152
0.750505
4.620529
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/goto/KotlinSearchEverywherePsiRenderer.kt
4
1808
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.goto import com.intellij.ide.actions.SearchEverywherePsiRenderer import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.renderer.ParameterNameRenderingPolicy @Service internal class KotlinSearchEverywherePsiRenderer(project: Project) : SearchEverywherePsiRenderer(KotlinPluginDisposable.getInstance(project)) { companion object { private val RENDERER = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withOptions { parameterNameRenderingPolicy = ParameterNameRenderingPolicy.NONE modifiers = emptySet() startFromName = false } fun getInstance(project: Project): KotlinSearchEverywherePsiRenderer = project.service() } override fun getElementText(element: PsiElement?): String { if (element !is KtNamedFunction) return super.getElementText(element) val descriptor = element.resolveToDescriptorIfAny() ?: return "" return buildString { descriptor.extensionReceiverParameter?.let { append(RENDERER.renderType(it.type)).append('.') } append(element.name) descriptor.valueParameters.joinTo(this, prefix = "(", postfix = ")") { RENDERER.renderType(it.type) } } } }
apache-2.0
8f35e1cc6c9112a0aa2df51f7971bb6e
46.578947
158
0.760509
4.980716
false
false
false
false
himikof/intellij-rust
src/main/kotlin/org/rust/ide/inspections/RsWrongTypeParametersNumberInspection.kt
1
4612
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections import com.intellij.codeInspection.ProblemsHolder import org.rust.ide.inspections.fixes.RemoveTypeParameter import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.RsCompositeElement import org.rust.lang.core.psi.ext.RsGenericDeclaration /** * Inspection that detects E0243/E0244/E0087/E0089/E0035/E0036 errors. */ class RsWrongTypeParametersNumberInspection : RsLocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitBaseType(type: RsBaseType) { // Don't apply generic declaration checks to Fn-traits and `Self` if (type.path?.valueParameterList != null) return if (type.path?.cself != null) return checkMethod(holder, type) } override fun visitCallExpr(o: RsCallExpr) = checkMethod(holder, o) override fun visitMethodCall(o: RsMethodCall) = checkMethod(holder, o) } private fun checkMethod(holder: ProblemsHolder, o: RsCompositeElement) { val (actualArguments, declaration) = when (o) { is RsMethodCall -> o.typeArgumentList to o.reference.resolve() is RsCallExpr -> (o.expr as? RsPathExpr)?.path?.typeArgumentList to (o.expr as? RsPathExpr)?.path?.reference?.resolve() is RsBaseType -> o.path?.typeArgumentList to o.path?.reference?.resolve() else -> return } if (declaration !is RsGenericDeclaration) return val nArguments = actualArguments?.typeReferenceList?.size ?: 0 val expectedRequiredParams = declaration.typeParameterList?.typeParameterList?.filter { it.eq == null }?.size ?: 0 val expectedTotalParams = declaration.typeParameterList?.typeParameterList?.size ?: 0 val data = when(o) { is RsBaseType -> checkBaseType(nArguments, expectedRequiredParams, expectedTotalParams) is RsMethodCall -> checkMethodCall(nArguments, expectedRequiredParams, expectedTotalParams) is RsCallExpr -> checkCallExpr(nArguments, expectedRequiredParams, expectedTotalParams) else -> null } ?: return val problemText = "Wrong number of type parameters: expected ${data.expectedText}, found $nArguments [${data.code}]" if (data.fix) { holder.registerProblem(o, problemText, RemoveTypeParameter(o)) } else { holder.registerProblem(o, problemText) } } data class ProblemData(val expectedText: String, val code: String, val fix: Boolean) private fun checkBaseType(actualArgs: Int, expectedRequiredParams: Int, expectedTotalParams: Int): ProblemData? { val (code, expectedText) = when { actualArgs < expectedRequiredParams -> ("E0243" to if (expectedRequiredParams != expectedTotalParams) "at least $expectedRequiredParams" else "$expectedTotalParams") actualArgs > expectedTotalParams -> ("E0244" to if (expectedRequiredParams != expectedTotalParams) "at most $expectedTotalParams" else "$expectedTotalParams") else -> null } ?: return null return ProblemData(expectedText, code, expectedTotalParams == 0) } private fun checkMethodCall(actualArgs: Int, expectedRequiredParams: Int, expectedTotalParams: Int): ProblemData? { val (code, expectedText) = when { actualArgs != 0 && expectedTotalParams == 0 -> ("E0035" to if (expectedRequiredParams != expectedTotalParams) "at most $expectedRequiredParams" else "$expectedTotalParams") actualArgs > expectedTotalParams -> ("E0036" to if (expectedRequiredParams != expectedTotalParams) "at most $expectedTotalParams" else "$expectedTotalParams") else -> null } ?: return null return ProblemData(expectedText, code, expectedTotalParams == 0) } private fun checkCallExpr(actualArgs: Int, expectedRequiredParams: Int, expectedTotalParams: Int): ProblemData? { val (code, expectedText) = when { actualArgs > expectedTotalParams -> ("E0087" to if (expectedRequiredParams != expectedTotalParams) "at most $expectedTotalParams" else "$expectedTotalParams") else -> null } ?: return null return ProblemData(expectedText, code, expectedTotalParams == 0) } }
mit
32c150fd8c6b5f089e92cd11f8d79187
45.12
142
0.664788
4.706122
false
false
false
false
codebutler/farebot
farebot-app/src/main/java/com/codebutler/farebot/app/feature/card/map/TripMapScreen.kt
1
3559
/* * TripMapScreen.kt * * This file is part of FareBot. * Learn more at: https://codebutler.github.io/farebot/ * * Copyright (C) 2017 Eric Butler <[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.codebutler.farebot.app.feature.card.map import android.content.Context import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.codebutler.farebot.R import com.codebutler.farebot.app.core.inject.ScreenScope import com.codebutler.farebot.app.core.kotlin.compact import com.codebutler.farebot.app.core.ui.ActionBarOptions import com.codebutler.farebot.app.core.ui.FareBotScreen import com.codebutler.farebot.app.feature.main.MainActivity import com.codebutler.farebot.transit.Trip class TripMapScreen(private val trip: Trip) : FareBotScreen<TripMapScreen.Component, TripMapScreenView>() { override fun getTitle(context: Context): String = context.getString(R.string.map) override fun getActionBarOptions(): ActionBarOptions = ActionBarOptions( backgroundColorRes = R.color.accent, textColorRes = R.color.white ) override fun onCreateView(context: Context): TripMapScreenView = TripMapScreenView(context, trip) override fun onShow(context: Context) { super.onShow(context) view.post { (activity as AppCompatActivity).supportActionBar?.apply { val resources = context.resources setDisplayHomeAsUpEnabled(true) title = arrayOf(trip.startStation?.shortStationName, trip.endStation?.shortStationName) .compact() .joinToString(" → ") subtitle = arrayOf(trip.getAgencyName(resources), trip.getRouteName(resources)) .compact() .joinToString(" ") } } view.onCreate(Bundle()) } override fun onHide(context: Context) { super.onHide(context) view.onDestroy() } override fun onResume(context: Context) { super.onResume(context) view.onStart() view.onResume() } override fun onPause(context: Context) { super.onPause(context) view.onPause() view.onStop() } override fun onSave(outState: Bundle?) { super.onSave(outState) } override fun onRestore(savedInstanceState: Bundle?) { super.onRestore(savedInstanceState) } override fun createComponent(parentComponent: MainActivity.MainActivityComponent): Component = DaggerTripMapScreen_Component.builder() .mainActivityComponent(parentComponent) .build() override fun inject(component: Component) { component.inject(this) } @ScreenScope @dagger.Component(dependencies = arrayOf(MainActivity.MainActivityComponent::class)) interface Component { fun inject(screen: TripMapScreen) } }
gpl-3.0
797c58dad188d90cc0750c00f0e8722d
32.87619
107
0.685409
4.548593
false
false
false
false
codebutler/farebot
farebot-app/src/main/java/com/codebutler/farebot/app/feature/main/MainActivity.kt
1
10625
/* * MainActivity.kt * * This file is part of FareBot. * Learn more at: https://codebutler.github.io/farebot/ * * Copyright (C) 2017 Eric Butler <[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.codebutler.farebot.app.feature.main import android.animation.ObjectAnimator import android.annotation.SuppressLint import android.content.Intent import android.content.SharedPreferences import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.os.Handler import com.google.android.material.appbar.AppBarLayout import androidx.core.view.ViewCompat import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import android.view.Menu import android.view.MenuItem import android.view.View import com.codebutler.farebot.R import com.codebutler.farebot.app.core.activity.ActivityOperations import com.codebutler.farebot.app.core.activity.ActivityResult import com.codebutler.farebot.app.core.activity.RequestPermissionsResult import com.codebutler.farebot.app.core.app.FareBotApplication import com.codebutler.farebot.app.core.app.FareBotApplicationComponent import com.codebutler.farebot.app.core.inject.ActivityScope import com.codebutler.farebot.app.core.kotlin.adjustAlpha import com.codebutler.farebot.app.core.kotlin.bindView import com.codebutler.farebot.app.core.kotlin.getColor import com.codebutler.farebot.app.core.nfc.NfcStream import com.codebutler.farebot.app.core.nfc.TagReaderFactory import com.codebutler.farebot.app.core.serialize.CardKeysSerializer import com.codebutler.farebot.app.core.transit.TransitFactoryRegistry import com.codebutler.farebot.app.core.ui.FareBotCrossfadeTransition import com.codebutler.farebot.app.core.ui.FareBotScreen import com.codebutler.farebot.app.core.util.ExportHelper import com.codebutler.farebot.app.feature.home.CardStream import com.codebutler.farebot.app.feature.home.HomeScreen import com.codebutler.farebot.card.serialize.CardSerializer import com.codebutler.farebot.persist.CardKeysPersister import com.codebutler.farebot.persist.CardPersister import com.jakewharton.rxrelay2.PublishRelay import com.wealthfront.magellan.ActionBarConfig import com.wealthfront.magellan.NavigationListener import com.wealthfront.magellan.Navigator import com.wealthfront.magellan.Screen import com.wealthfront.magellan.ScreenLifecycleListener import dagger.BindsInstance import dagger.Component import dagger.Module import dagger.Provides import javax.inject.Inject class MainActivity : AppCompatActivity(), ScreenLifecycleListener, NavigationListener { @Inject internal lateinit var navigator: Navigator @Inject internal lateinit var nfcStream: NfcStream private val appBarLayout by bindView<AppBarLayout>(R.id.appBarLayout) private val toolbar by bindView<Toolbar>(R.id.toolbar) private val activityResultRelay = PublishRelay.create<ActivityResult>() private val handler = Handler() private val menuItemClickRelay = PublishRelay.create<MenuItem>() private val permissionsResultRelay = PublishRelay.create<RequestPermissionsResult>() private val shortAnimationDuration: Long by lazy { resources.getInteger(android.R.integer.config_shortAnimTime).toLong() } private val toolbarElevation: Float by lazy { resources.getDimensionPixelSize(R.dimen.toolbar_elevation).toFloat() } private var animToolbarBg: ObjectAnimator? = null val component: MainActivityComponent by lazy { DaggerMainActivity_MainActivityComponent.builder() .applicationComponent((application as FareBotApplication).component) .activity(this) .mainActivityModule(MainActivityModule()) .activityOperations(ActivityOperations( this, activityResultRelay.hide(), menuItemClickRelay.hide(), permissionsResultRelay.hide())) .build() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) component.inject(this) navigator.addLifecycleListener(this) nfcStream.onCreate(this, savedInstanceState) } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) navigator.onCreate(this, savedInstanceState) } override fun onSaveInstanceState(outState: Bundle?) { super.onSaveInstanceState(outState) navigator.onSaveInstanceState(outState) } override fun onResume() { super.onResume() navigator.onResume(this) nfcStream.onResume() } override fun onPause() { super.onPause() navigator.onPause(this) nfcStream.onPause() } override fun onDestroy() { super.onDestroy() navigator.removeLifecycleListener(this) navigator.onDestroy(this) } override fun onBackPressed() { if (!navigator.handleBack()) { super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { navigator.onCreateOptionsMenu(menu) return true } override fun onPrepareOptionsMenu(menu: Menu): Boolean { navigator.onPrepareOptionsMenu(menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() return true } menuItemClickRelay.accept(item) return true } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) handler.post { activityResultRelay.accept(ActivityResult(requestCode, resultCode, data)) } } override fun onNavigate(actionBarConfig: ActionBarConfig) { toolbar.visibility = if (actionBarConfig.visible()) View.VISIBLE else View.GONE } @SuppressLint("ResourceType") // Lint bug? override fun onShow(screen: Screen<*>) { val options = (screen as FareBotScreen<*, *>).getActionBarOptions() supportActionBar?.setDisplayHomeAsUpEnabled(!navigator.atRoot()) toolbar.setTitleTextColor(getColor(options.textColorRes, Color.BLACK)) toolbar.title = screen.getTitle(this) toolbar.subtitle = null val newColor = getColor(options.backgroundColorRes, Color.TRANSPARENT) val curColor = (toolbar.background as? ColorDrawable)?.color ?: Color.TRANSPARENT val curColorForAnim = if (curColor == Color.TRANSPARENT) adjustAlpha(newColor) else curColor val newColorForAnim = if (newColor == Color.TRANSPARENT) adjustAlpha(curColor) else newColor animToolbarBg?.cancel() animToolbarBg = ObjectAnimator.ofArgb(toolbar, "backgroundColor", curColorForAnim, newColorForAnim).apply { duration = shortAnimationDuration start() } ViewCompat.setElevation(appBarLayout, if (options.shadow) toolbarElevation else 0f) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) permissionsResultRelay.accept(RequestPermissionsResult(requestCode, permissions, grantResults)) } override fun onHide(screen: Screen<*>?) { } @Module class MainActivityModule { @Provides @ActivityScope fun provideNfcTagStream(activity: MainActivity): NfcStream = NfcStream(activity) @Provides @ActivityScope fun provideCardStream( application: FareBotApplication, cardPersister: CardPersister, cardSerializer: CardSerializer, cardKeysPersister: CardKeysPersister, cardKeysSerializer: CardKeysSerializer, nfcStream: NfcStream, tagReaderFactory: TagReaderFactory ): CardStream { return CardStream( application, cardPersister, cardSerializer, cardKeysPersister, cardKeysSerializer, nfcStream, tagReaderFactory) } @Provides @ActivityScope fun provideNavigator(activity: MainActivity): Navigator = Navigator.withRoot(HomeScreen()) .transition(FareBotCrossfadeTransition(activity)) .build() } @ActivityScope @Component(dependencies = arrayOf(FareBotApplicationComponent::class), modules = arrayOf(MainActivityModule::class)) interface MainActivityComponent { fun activityOperations(): ActivityOperations fun application(): FareBotApplication fun cardPersister(): CardPersister fun cardSerializer(): CardSerializer fun cardKeysPersister(): CardKeysPersister fun cardKeysSerializer(): CardKeysSerializer fun cardStream(): CardStream fun exportHelper(): ExportHelper fun nfcStream(): NfcStream fun sharedPreferences(): SharedPreferences fun tagReaderFactory(): TagReaderFactory fun transitFactoryRegistry(): TransitFactoryRegistry fun inject(mainActivity: MainActivity) @Component.Builder interface Builder { fun applicationComponent(applicationComponent: FareBotApplicationComponent): Builder fun mainActivityModule(mainActivityModule: MainActivityModule): Builder @BindsInstance fun activity(activity: MainActivity): Builder @BindsInstance fun activityOperations(activityOperations: ActivityOperations): Builder fun build(): MainActivityComponent } } }
gpl-3.0
4d83af73cfcb3af4f2d9d29f6d4aca1e
34.774411
120
0.713224
5.142788
false
false
false
false
ktorio/ktor
ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/cipher/CipherUtils.kt
1
2521
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.tls.cipher import io.ktor.network.util.* import io.ktor.utils.io.core.* import io.ktor.utils.io.pool.* import java.nio.* import javax.crypto.* internal val CryptoBufferPool: ObjectPool<ByteBuffer> = ByteBufferPool(128, 65536) internal fun ByteReadPacket.cipherLoop(cipher: Cipher, header: BytePacketBuilder.() -> Unit = {}): ByteReadPacket { val srcBuffer = DefaultByteBufferPool.borrow() var dstBuffer = CryptoBufferPool.borrow() var dstBufferFromPool = true try { return buildPacket { srcBuffer.clear() header() while (true) { val rc = if (srcBuffer.hasRemaining()) readAvailable(srcBuffer) else 0 srcBuffer.flip() if (!srcBuffer.hasRemaining() && (rc == -1 || [email protected])) break dstBuffer.clear() if (cipher.getOutputSize(srcBuffer.remaining()) > dstBuffer.remaining()) { if (dstBufferFromPool) { CryptoBufferPool.recycle(dstBuffer) } dstBuffer = ByteBuffer.allocate(cipher.getOutputSize(srcBuffer.remaining())) dstBufferFromPool = false } cipher.update(srcBuffer, dstBuffer) dstBuffer.flip() writeFully(dstBuffer) srcBuffer.compact() } assert(!srcBuffer.hasRemaining()) { "Cipher loop completed too early: there are unprocessed bytes" } assert(!dstBuffer.hasRemaining()) { "Not all bytes were appended to the packet" } val requiredBufferSize = cipher.getOutputSize(0) if (requiredBufferSize == 0) return@buildPacket if (requiredBufferSize > dstBuffer.capacity()) { writeFully(cipher.doFinal()) return@buildPacket } dstBuffer.clear() cipher.doFinal(EmptyByteBuffer, dstBuffer) dstBuffer.flip() if (!dstBuffer.hasRemaining()) { // workaround JDK bug writeFully(cipher.doFinal()) return@buildPacket } writeFully(dstBuffer) } } finally { DefaultByteBufferPool.recycle(srcBuffer) if (dstBufferFromPool) { CryptoBufferPool.recycle(dstBuffer) } } }
apache-2.0
d0c82d392c1c75aac5a13329a693cbb8
33.067568
119
0.587862
4.848077
false
false
false
false
feiyanke/Rxk
src/main/kotlin/io/rxk/core/Context.kt
1
7350
package io.rxk.core import java.util.concurrent.* import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference import kotlin.concurrent.thread class Context<T, R> ( var signal: IMethod<T, R>, var error: IEasyMethod<Throwable>, var finish: IUnitMethod, var start: IUnitMethod, var cancel: IUnitMethod, var report: IUnitMethod ) { fun filter(predicate:(R)->Boolean): Context<T, R> = make(FilterOperator(predicate)) fun distinct(): Context<T, R> = make(DistinctOperator()) fun <E> map(tranform:(R)->E): Context<T, E> = make(MapOperator(tranform)) fun <E> map(method: IMethod<R, E>): Context<T, E> = make(method) fun <E> mapCallback(callback:(R, (E)->Unit)->Unit): Context<T, E> = make(MapCallbackOperator(callback)) fun <E> mapFuture(method:(R)->Future<E>): Context<T, E> = make(MapFutureOperator(method)) fun scan(init:R? = null, method:(R,R)->R): Context<T, R> = make(ScanOperator(init, method)) fun reduce(init:R? = null, method:(R,R)->R) = scan(init, method).last()?:init fun multiScan(vararg init:R, m:(List<R>,R)->R): Context<T, R> = make(MultiScanOperator(*init, method = m)) fun forEach(block:(R)->Unit): Context<T, R> = make(ForEachOperator(block)) fun error(block: (e:Throwable) -> Unit): Context<T, R> = make(ErrorOperator(block)) fun take(n:Int): Context<T, R> = make(TakeOperator(n)) fun takeLast(n:Int): Context<T, R> = make(TakeLastOperator(n)) fun log(block: (R) -> String): Context<T, R> = make(LogOperator(block)) fun print() = forEach(::println).finish() fun on(executor: Executor): Context<T, R> = make(ScheduleOperator(executor)) fun parallel(): Context<T, R> = on(Executors.newCachedThreadPool()) fun pack(n:Int): Context<T, R> = make(PackOperator(n)) fun serialze(): Context<T, R> = pack(1) fun buffer(count:Int) = make(BufferOperator(count)) fun <E> flatMap(transform:(R)-> Context<*, E>): Context<T, E> = make(FlatMapOperator(transform)) fun elementAt(index:Int): Context<T, R> = make(ElementAtOperator(index)) fun first(): Context<T, R> = elementAt(0) fun skip(count: Int): Context<T, R> = make(SkipOperator(count)) fun skipLast(count: Int): Context<T, R> = make(SkipLastOperator(count)) fun startWith(context: Context<*, R>): Context<*, R> = Companion.concat(context, this) fun startWith(vararg v:R): Context<*, R> = Companion.concat(just(*v), this) fun startWith(list:List<R>): Context<*, R> = Companion.concat(from(list), this) fun merge(vararg context: Context<*, R>, sync: Boolean = false): Context<*, R> = Companion.merge(this, *context, sync = sync) fun concat(vararg context: Context<*, R>): Context<*, R> = Companion.concat(this, *context) fun zip(vararg context: Context<*, R>): Context<*, List<R>> = Companion.zip(this, *context) fun timeInterval(): Context<T, Long> = make(TimeIntervalOperator()) fun timeStamp(): Context<T, TimeStamp<R>> = map { TimeStamp(it) } fun indexStamp(): Context<T, IndexStamp<R>> = make(IndexedOperator()) fun takeUntil(predicate: (R) -> Boolean): Context<T, R> = make(TakeUntilOperator(predicate)) fun takeWhile(predicate: (R) -> Boolean): Context<T, R> = make(TakeWhileOperator(predicate)) fun skipUntil(predicate: (R) -> Boolean): Context<T, R> = make(SkipUntilOperator(predicate)) fun skipWhile(predicate: (R) -> Boolean): Context<T, R> = make(SkipWhileOperator(predicate)) fun finish(block: () -> Unit) = make(FinishOperator(block)).start() fun finish() { val latch = CountDownLatch(1) finish { latch.countDown() } latch.await() } fun last(block: (R?) -> Unit) = make(LastOperator()).forEach(block).finish{} fun last() : R? { val latch = ValueLatch<R?>() last { latch.set(it) } return latch.get() } fun all(predicate: (R) -> Boolean) = map(predicate).takeUntil { !it }.last()!! fun contains(v:R) = takeUntil { it == v }.last() == v fun any(predicate: (R) -> Boolean) = map(predicate).takeUntil { it }.last()!! fun count() = (indexStamp().last()?.index?:-1) + 1 companion object { fun <T> create(block: Stream<T>.()->Unit): Context<T, T> = make(BlockStream(block)) fun fromRunable(block:()->Unit): Context<Unit, Unit> = make(RunableStream(block)) fun from(runnable: Runnable): Context<Unit, Unit> = fromRunable(runnable::run) fun <T> fromCallable(callable:()->T): Context<T, T> = make(CallableStream(callable)) fun <T> from(callable: Callable<T>): Context<T, T> = fromCallable(callable::call) fun <T> from(future: Future<T>): Context<T, T> = fromCallable(future::get) fun <T> from(iterable: Iterable<T>): Context<T, T> = make(IterableStream(iterable)) fun <T> from(array: Array<T>): Context<T, T> = make(IterableStream(array.asIterable())) fun <T> just(vararg values:T): Context<T, T> = from(values.asIterable()) fun range(n:Int, m:Int): Context<Int, Int> = from(n until m) fun interval(ms: Long): Context<Int, Int> = make(IntervalStream(ms)) fun <T> merge(vararg context: Context<*, T>, sync:Boolean = false): Context<*, T> = make(MergeStream(sync, context.asList())) fun <T> concat(vararg context: Context<*, T>): Context<*, T> = merge(*context, sync = true) fun <T> zip(vararg context: Context<*, T>): Context<*, List<T>> = make(ZipStream(context.asList())) private fun <T> make(o: Stream<T>): Context<T, T> = o.make() } fun <E> make(m: Operator<R, E>) = make(m.signal, m.error, m.finish, m.start, m.cancel, m.report) fun make(m: EasyOperator<R>) = make(m.signal, m.error, m.finish, m.start, m.cancel, m.report) fun <E> make(next : IMethod<R, E>, error : IEasyMethod<Throwable>? = null, finish : IUnitMethod? = null, start : IUnitMethod? = null, cancel : IUnitMethod? = null, report : IUnitMethod? = null ) : Context<T, E> = chainNext(next).apply { chainError(error) chainFinish(finish) chainStart(start) chainCancel(cancel) chainReport(report) } fun make(next : IEasyMethod<R>? = null, error : IEasyMethod<Throwable>? = null, finish : IUnitMethod? = null, start : IUnitMethod? = null, cancel : IUnitMethod? = null, report : IUnitMethod? = null ) : Context<T, R> = apply { chainNext(next) chainError(error) chainFinish(finish) chainStart(start) chainCancel(cancel) chainReport(report) } private fun <E> chainNext(m: IMethod<R, E>) : Context<T, E> = Context(signal.chain(m), error, finish, start, cancel, report) private fun chainNext(m: IEasyMethod<R>?) = m?.let { signal = signal.chain(m) } private fun chainError(m: IEasyMethod<Throwable>?) = m?.let { error = error.chain(m) } private fun chainFinish(m: IUnitMethod?) = m?.let { finish = finish.chain(m) } private fun chainStart(m: IUnitMethod?) = m?.let { start = it.chain(start) } private fun chainCancel(m: IUnitMethod?) = m?.let { cancel = it.chain(cancel) } private fun chainReport(m: IUnitMethod?) = m?.let { report = it.chain(report) } }
mit
ea4916f01cfcb22479b2fdec9591c3db
53.850746
133
0.626531
3.394919
false
false
false
false
dhis2/dhis2-android-sdk
core/src/test/java/org/hisp/dhis/android/core/trackedentity/search/TrackedEntityInstanceQueryCallShould.kt
1
10523
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.trackedentity.search import com.google.common.truth.Truth.assertThat import com.nhaarman.mockitokotlin2.* import java.text.ParseException import java.util.* import java.util.concurrent.Callable import javax.net.ssl.HttpsURLConnection import org.hisp.dhis.android.core.arch.api.executors.internal.APICallExecutor import org.hisp.dhis.android.core.common.AssignedUserMode import org.hisp.dhis.android.core.common.BaseCallShould import org.hisp.dhis.android.core.enrollment.EnrollmentStatus import org.hisp.dhis.android.core.event.EventStatus import org.hisp.dhis.android.core.maintenance.D2Error import org.hisp.dhis.android.core.maintenance.D2ErrorCode import org.hisp.dhis.android.core.organisationunit.OrganisationUnitMode import org.hisp.dhis.android.core.systeminfo.DHISVersion import org.hisp.dhis.android.core.systeminfo.DHISVersionManager import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstance import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityInstanceService import org.junit.Assert.fail import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.mockito.Mockito import org.mockito.stubbing.OngoingStubbing import retrofit2.Call @RunWith(JUnit4::class) class TrackedEntityInstanceQueryCallShould : BaseCallShould() { private val service: TrackedEntityInstanceService = mock() private val apiCallExecutor: APICallExecutor = mock() private val mapper: SearchGridMapper = mock() private val dhisVersionManager: DHISVersionManager = mock() private val searchGrid: SearchGrid = mock() private val searchGridCall: Call<SearchGrid> = mock() private val teis: List<TrackedEntityInstance> = mock() private val attribute: List<String> = mock() private val filter: List<String> = mock() private lateinit var query: TrackedEntityInstanceQueryOnline // object to test private lateinit var call: Callable<List<TrackedEntityInstance>> @Before override fun setUp() { super.setUp() val orgUnits = listOf("ou1", "ou2") query = TrackedEntityInstanceQueryOnline.builder() .uids(listOf("uid1", "uid2")) .orgUnits(orgUnits) .orgUnitMode(OrganisationUnitMode.ACCESSIBLE) .program("program") .programStage("progra_stage") .programStartDate(Date()) .programEndDate(Date()) .enrollmentStatus(EnrollmentStatus.ACTIVE) .followUp(true) .eventStartDate(Date()) .eventEndDate(Date()) .eventStatus(EventStatus.OVERDUE) .incidentStartDate(Date()) .incidentEndDate(Date()) .trackedEntityType("teiTypeStr") .query("queryStr") .attribute(attribute) .filter(filter) .includeDeleted(false) .lastUpdatedStartDate(Date()) .lastUpdatedEndDate(Date()) .order("lastupdated:desc") .assignedUserMode(AssignedUserMode.ANY) .paging(false) .page(2) .pageSize(33) .build() whenServiceQuery().thenReturn(searchGridCall) whenever(apiCallExecutor.executeObjectCallWithErrorCatcher(eq(searchGridCall), any())).doReturn(searchGrid) whenever(mapper.transform(any())).doReturn(teis) whenever(dhisVersionManager.isGreaterThan(DHISVersion.V2_33)).doReturn(true) // Metadata call call = TrackedEntityInstanceQueryCallFactory(service, mapper, apiCallExecutor, dhisVersionManager).getCall(query) } @Test fun succeed_when_endpoint_calls_succeed() { val teisResponse = call.call() assertThat(teisResponse).isEqualTo(teis) } @Test fun call_mapper_with_search_grid() { call.call() verify(mapper).transform(searchGrid) verifyNoMoreInteractions(mapper) } @Test fun call_service_with_query_parameters() { call.call() verifyService(query) verifyNoMoreInteractions(service) } @Test fun throw_D2CallException_when_service_call_returns_failed_response() { whenever(apiCallExecutor.executeObjectCallWithErrorCatcher(eq(searchGridCall), any())).doThrow(d2Error) whenever(d2Error.errorCode()).doReturn(D2ErrorCode.MAX_TEI_COUNT_REACHED) try { call.call() fail("D2Error was expected but was not thrown") } catch (d2e: D2Error) { assertThat(d2e.errorCode() == D2ErrorCode.MAX_TEI_COUNT_REACHED).isTrue() } } @Test fun throw_too_many_org_units_exception_when_request_was_too_long() { whenever(apiCallExecutor.executeObjectCallWithErrorCatcher(eq(searchGridCall), any())).doThrow(d2Error) whenever(d2Error.errorCode()).doReturn(D2ErrorCode.TOO_MANY_ORG_UNITS) whenever(d2Error.httpErrorCode()).doReturn(HttpsURLConnection.HTTP_REQ_TOO_LONG) try { call.call() fail("D2Error was expected but was not thrown") } catch (d2e: D2Error) { assertThat(d2e.errorCode() == D2ErrorCode.TOO_MANY_ORG_UNITS).isTrue() } } @Test(expected = D2Error::class) fun throw_D2CallException_when_mapper_throws_exception() { whenever(mapper.transform(searchGrid)).thenThrow(ParseException::class.java) call.call() } @Test fun should_not_map_active_event_status_if_greater_than_2_33() { whenever(dhisVersionManager.isGreaterThan(DHISVersion.V2_33)).doReturn(true) val activeQuery = query.toBuilder().eventStatus(EventStatus.ACTIVE).build() val activeCall = TrackedEntityInstanceQueryCallFactory( service, mapper, apiCallExecutor, dhisVersionManager ).getCall(activeQuery) activeCall.call() verifyService(activeQuery, EventStatus.ACTIVE) } @Test fun should_map_active_event_status_if_not_greater_than_2_33() { whenever(dhisVersionManager.isGreaterThan(DHISVersion.V2_33)).doReturn(false) val activeQuery = query.toBuilder().eventStatus(EventStatus.ACTIVE).build() val activeCall = TrackedEntityInstanceQueryCallFactory( service, mapper, apiCallExecutor, dhisVersionManager ).getCall(activeQuery) activeCall.call() verifyService(activeQuery, EventStatus.VISITED) val nonActiveQuery = query.toBuilder().eventStatus(EventStatus.SCHEDULE).build() val nonActiveCall = TrackedEntityInstanceQueryCallFactory( service, mapper, apiCallExecutor, dhisVersionManager ).getCall(nonActiveQuery) nonActiveCall.call() verifyService(activeQuery, EventStatus.SCHEDULE) } private fun verifyService( query: TrackedEntityInstanceQueryOnline, expectedStatus: EventStatus? = query.eventStatus() ) { Mockito.verify(service).query( eq(query.uids()!![0] + ";" + query.uids()!![1]), eq(query.orgUnits()[0] + ";" + query.orgUnits()[1]), eq(query.orgUnitMode().toString()), eq(query.program()), eq(query.programStage()), eq(query.formattedProgramStartDate()), eq(query.formattedProgramEndDate()), eq(query.enrollmentStatus().toString()), eq(query.formattedIncidentStartDate()), eq(query.formattedIncidentEndDate()), eq(query.followUp()), eq(query.formattedEventStartDate()), eq(query.formattedEventEndDate()), eq(expectedStatus.toString()), eq(query.trackedEntityType()), eq(query.query()), eq(query.attribute()), eq(query.filter()), eq(query.assignedUserMode().toString()), eq(query.formattedLastUpdatedStartDate()), eq(query.formattedLastUpdatedEndDate()), eq(query.order()), eq(query.paging()), eq(query.page()), eq(query.pageSize()) ) } private fun whenServiceQuery(): OngoingStubbing<Call<SearchGrid>?> { return whenever( service.query( any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any() ) ) } }
bsd-3-clause
d0b0f95836a3d010680c5edf29bab32e
37.545788
118
0.646013
4.541649
false
false
false
false
intellij-solidity/intellij-solidity
src/main/kotlin/me/serce/solidity/ide/inspections/NoReturnInspection.kt
1
5355
package me.serce.solidity.ide.inspections import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import me.serce.solidity.lang.psi.* import me.serce.solidity.lang.types.SolInternalTypeFactory import me.serce.solidity.lang.types.findContract class NoReturnInspection : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return object : SolVisitor() { override fun visitFunctionDefinition(o: SolFunctionDefinition) { o.inspectReturns(holder) } } } } private fun SolFunctionDefinition.inspectReturns(holder: ProblemsHolder) { val block = this.block if (block != null) { val returns = this.returns if (returns != null) { if (!block.returns) { val shouldReturn = returns.parameterDefList.any { it.name == null } if (shouldReturn) { holder.registerProblem(this, "No return statement") } else { for (returnParam in returns.parameterDefList) { if (!block.hasAssignment(returnParam)) { holder.registerProblem(returnParam, "Return variable not assigned") } } } } } } } private val SolFunctionCallExpression.revert: Boolean get() { return if (this.name == "revert") { val ref = this.reference?.resolve() ref?.isGlobal() ?: false } else { false } } private fun SolStatement.hasAssignment(el: SolNamedElement): Boolean { this.throwSt?.let { return true } this.revertStatement?.let { return true } this.variableDefinition?.let { return it.hasAssignment(el) } this.expression?.let { if (it is SolAssignmentExpression) { return it.expressionList[0].isReferenceTo(el) } else if (it is SolFunctionCallExpression && it.revert) { return true } } this.inlineAssemblyStatement.let { st -> st?.yulBlock?.let { return it.hasAssignment(el) } } this.block?.let { return it.hasAssignment(el) } this.ifStatement?.let { return it.hasAssignment(el) } this.tupleStatement?.let { st -> val declaration = st.variableDeclaration val expressions = st.expressionList if (declaration != null) { return declaration.declarationList?.declarationItemList?.any { it.hasAssignment(el) } ?: declaration.typedDeclarationList?.typedDeclarationItemList?.any { it.hasAssignment(el) } ?: false } else { expressions.firstOrNull()?.let { if (it is SolSeqExpression) { return it.expressionList.any { expr -> expr.isReferenceTo(el) } } } } } return false } private fun SolExpression.isReferenceTo(el: SolNamedElement): Boolean { if (this is SolPrimaryExpression) { this.varLiteral?.let { lit -> if (lit.reference?.resolve() == el) { return true } } } return false } private val SolStatement.returns: Boolean get() { this.expression?.let { if (it is SolFunctionCallExpression && it.revert) { return true } } this.revertStatement?.let { return true } this.inlineAssemblyStatement.let { st -> st?.yulBlock?.let { return it.returns } } this.throwSt?.let { return true } this.block?.let { return it.returns } this.ifStatement?.let { return it.returns } if (this.returnSt != null) { return true } if (this.returnTupleStatement != null) { return true } return false } private val SolYulStatement.returns: Boolean get() { yulFunctionCall?.let { return it.text.startsWith("return")//todo better } return false } private val SolYulBlock.returns: Boolean get() { return this.yulStatementList.any { it.returns } } private val SolBlock.returns: Boolean get() = this.statementList.any { it.returns } private fun SolBlock.hasAssignment(el: SolNamedElement): Boolean = this.statementList.any { it.hasAssignment(el) } private val SolIfStatement.returns: Boolean get() = if (this.statementList.size == 1) { false } else { statementList.all { it.returns } } private fun SolIfStatement.hasAssignment(el: SolNamedElement): Boolean = if (this.statementList.size == 1) { false } else { statementList.all { it.hasAssignment(el) } } private fun SolVariableDefinition.hasAssignment(el: SolNamedElement): Boolean = this.variableDeclaration.reference?.resolve() == el private fun SolYulBlock.hasAssignment(el: SolNamedElement): Boolean = this.yulStatementList.any { it.hasAssignment(el) } private fun SolYulStatement.hasAssignment(el: SolNamedElement): Boolean { this.yulAssignment?.let { if (it.children.any { identifier -> identifier.text == el.name }) {//todo better return true } } return false } private fun SolDeclarationItem.hasAssignment(el: SolNamedElement): Boolean { return this.identifier?.text == el.name } private fun SolTypedDeclarationItem.hasAssignment(el: SolNamedElement): Boolean { return this.identifier?.text == el.name } private fun SolElement.isGlobal(): Boolean { val contract = this.findContract() return contract == SolInternalTypeFactory.of(this.project).globalType.ref }
mit
e0f00b7bc0f8aae5ae154fcb93e1db86
23.791667
99
0.669281
4.066059
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/formatter/ImportSettingsPanel.kt
5
9901
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.formatter import com.intellij.application.options.CodeStyleAbstractPanel import com.intellij.openapi.application.ApplicationBundle import com.intellij.openapi.editor.colors.EditorColorsScheme import com.intellij.openapi.util.NlsContexts import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.ui.OptionGroup import com.intellij.ui.components.JBScrollPane import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings import org.jetbrains.kotlin.idea.core.formatter.KotlinPackageEntryTable import java.awt.BorderLayout import java.awt.GridBagConstraints import java.awt.GridBagLayout import java.awt.Insets import javax.swing.* import javax.swing.table.AbstractTableModel class ImportSettingsPanelWrapper(settings: CodeStyleSettings) : CodeStyleAbstractPanel(KotlinLanguage.INSTANCE, null, settings) { private val importsPanel = ImportSettingsPanel() override fun getRightMargin() = throw UnsupportedOperationException() override fun createHighlighter(scheme: EditorColorsScheme) = throw UnsupportedOperationException() override fun getFileType() = throw UnsupportedOperationException() override fun getPreviewText(): String? = null override fun apply(settings: CodeStyleSettings) = importsPanel.apply(settings.kotlinCustomSettings) override fun isModified(settings: CodeStyleSettings) = importsPanel.isModified(settings.kotlinCustomSettings) override fun getPanel() = importsPanel override fun resetImpl(settings: CodeStyleSettings) { importsPanel.reset(settings.kotlinCustomSettings) } override fun getTabTitle() = ApplicationBundle.message("title.imports") } class ImportSettingsPanel : JPanel() { private val cbImportNestedClasses = JCheckBox(KotlinBundle.message("formatter.checkbox.text.insert.imports.for.nested.classes")) private val starImportLayoutPanel = KotlinStarImportLayoutPanel() private val importOrderLayoutPanel = KotlinImportOrderLayoutPanel() private val nameCountToUseStarImportSelector = NameCountToUseStarImportSelector( KotlinBundle.message("formatter.title.top.level.symbols"), KotlinCodeStyleSettings.DEFAULT_NAME_COUNT_TO_USE_STAR_IMPORT, ) private val nameCountToUseStarImportForMembersSelector = NameCountToUseStarImportSelector( KotlinBundle.message("formatter.title.java.statics.and.enum.members"), KotlinCodeStyleSettings.DEFAULT_NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS, ) init { layout = BorderLayout() add(JBScrollPane(JPanel(GridBagLayout()).apply { val constraints = GridBagConstraints().apply { weightx = 1.0 insets = Insets(0, 10, 10, 10) fill = GridBagConstraints.HORIZONTAL gridy = 0 } add(nameCountToUseStarImportSelector.createPanel(), constraints.apply { gridy++ }) add(nameCountToUseStarImportForMembersSelector.createPanel(), constraints.apply { gridy++ }) add( OptionGroup(KotlinBundle.message("formatter.title.other")).apply { add(cbImportNestedClasses) }.createPanel(), constraints.apply { gridy++ } ) add(starImportLayoutPanel, constraints.apply { gridy++ fill = GridBagConstraints.BOTH weighty = 1.0 }) add(importOrderLayoutPanel, constraints.apply { gridy++ fill = GridBagConstraints.BOTH weighty = 1.0 }) }), BorderLayout.CENTER) } fun reset(settings: KotlinCodeStyleSettings) { nameCountToUseStarImportSelector.value = settings.NAME_COUNT_TO_USE_STAR_IMPORT nameCountToUseStarImportForMembersSelector.value = settings.NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS cbImportNestedClasses.isSelected = settings.IMPORT_NESTED_CLASSES starImportLayoutPanel.packageTable.copyFrom(settings.PACKAGES_TO_USE_STAR_IMPORTS) (starImportLayoutPanel.layoutTable.model as AbstractTableModel).fireTableDataChanged() if (starImportLayoutPanel.layoutTable.rowCount > 0) { starImportLayoutPanel.layoutTable.selectionModel.setSelectionInterval(0, 0) } importOrderLayoutPanel.packageTable.copyFrom(settings.PACKAGES_IMPORT_LAYOUT) (importOrderLayoutPanel.layoutTable.model as AbstractTableModel).fireTableDataChanged() if (importOrderLayoutPanel.layoutTable.rowCount > 0) { importOrderLayoutPanel.layoutTable.selectionModel.setSelectionInterval(0, 0) } importOrderLayoutPanel.recomputeAliasesCheckbox() } fun apply(settings: KotlinCodeStyleSettings) { settings.NAME_COUNT_TO_USE_STAR_IMPORT = nameCountToUseStarImportSelector.value settings.NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS = nameCountToUseStarImportForMembersSelector.value settings.IMPORT_NESTED_CLASSES = cbImportNestedClasses.isSelected settings.PACKAGES_TO_USE_STAR_IMPORTS.copyFrom(getCopyWithoutEmptyPackages(starImportLayoutPanel.packageTable)) settings.PACKAGES_IMPORT_LAYOUT.copyFrom(importOrderLayoutPanel.packageTable) } fun isModified(settings: KotlinCodeStyleSettings): Boolean { return with(settings) { var isModified = false isModified = isModified || nameCountToUseStarImportSelector.value != NAME_COUNT_TO_USE_STAR_IMPORT isModified = isModified || nameCountToUseStarImportForMembersSelector.value != NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS isModified = isModified || isModified(cbImportNestedClasses, IMPORT_NESTED_CLASSES) isModified = isModified || isModified(getCopyWithoutEmptyPackages(starImportLayoutPanel.packageTable), PACKAGES_TO_USE_STAR_IMPORTS) isModified = isModified || isModified(importOrderLayoutPanel.packageTable, PACKAGES_IMPORT_LAYOUT) isModified } } companion object { private fun isModified(checkBox: JCheckBox, value: Boolean): Boolean { return checkBox.isSelected != value } private fun isModified(list: KotlinPackageEntryTable, table: KotlinPackageEntryTable): Boolean { if (list.entryCount != table.entryCount) { return true } for (i in 0 until list.entryCount) { val entry1 = list.getEntryAt(i) val entry2 = table.getEntryAt(i) if (entry1 != entry2) { return true } } return false } private fun getCopyWithoutEmptyPackages(table: KotlinPackageEntryTable): KotlinPackageEntryTable { try { val copy = table.clone() copy.removeEmptyPackages() return copy } catch (ignored: CloneNotSupportedException) { throw IllegalStateException("Clone should be supported") } } } private class NameCountToUseStarImportSelector(@NlsContexts.BorderTitle title: String, default: Int) : OptionGroup(title) { private val rbUseSingleImports = JRadioButton(KotlinBundle.message("formatter.button.text.use.single.name.import")) private val rbUseStarImports = JRadioButton(KotlinBundle.message("formatter.button.text.use.import.with")) private val rbUseStarImportsIfAtLeast = JRadioButton(KotlinBundle.message("formatter.button.text.use.import.with.when.at.least")) private val starImportLimitModel = SpinnerNumberModel(default, MIN_VALUE, MAX_VALUE, 1) private val starImportLimitField = JSpinner(starImportLimitModel) init { ButtonGroup().apply { add(rbUseSingleImports) add(rbUseStarImports) add(rbUseStarImportsIfAtLeast) } add(rbUseSingleImports, true) add(rbUseStarImports, true) val jPanel = JPanel(GridBagLayout()) add(jPanel.apply { val constraints = GridBagConstraints().apply { gridx = GridBagConstraints.RELATIVE } this.add(rbUseStarImportsIfAtLeast, constraints) this.add(starImportLimitField, constraints) this.add( JLabel(KotlinBundle.message("formatter.text.names.used")), constraints.apply { fill = GridBagConstraints.HORIZONTAL; weightx = 1.0 }) }, true) fun updateEnabled() { starImportLimitField.isEnabled = rbUseStarImportsIfAtLeast.isSelected } rbUseStarImportsIfAtLeast.addChangeListener { updateEnabled() } updateEnabled() } var value: Int get() { return when { rbUseSingleImports.isSelected -> Int.MAX_VALUE rbUseStarImports.isSelected -> 1 else -> starImportLimitModel.number as Int } } set(value) { when { value > MAX_VALUE -> rbUseSingleImports.isSelected = true value < MIN_VALUE -> rbUseStarImports.isSelected = true else -> { rbUseStarImportsIfAtLeast.isSelected = true starImportLimitField.value = value } } } companion object { private const val MIN_VALUE = 2 private const val MAX_VALUE = 100 } } }
apache-2.0
b9bcc7088b193b1d64540469b6a1c14f
41.861472
158
0.67377
5.074833
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/overrideImplement/OverridenTraitDeclarations.kt
8
857
// TODO: Declarations have no implementation and should be considered as "overloaded" interface <lineMarker descr="*">First</lineMarker> { val <lineMarker descr="<html><body>Is implemented in <br/>&nbsp;&nbsp;&nbsp;&nbsp;Second</body></html>">some</lineMarker>: Int var <lineMarker descr="<html><body>Is implemented in <br/>&nbsp;&nbsp;&nbsp;&nbsp;Second</body></html>">other</lineMarker>: String get set fun <lineMarker descr="<html><body>Is implemented in <br>&nbsp;&nbsp;&nbsp;&nbsp;Second</body></html>">foo</lineMarker>() } interface Second : First { override val <lineMarker descr="Overrides property in 'First'">some</lineMarker>: Int override var <lineMarker descr="Overrides property in 'First'">other</lineMarker>: String override fun <lineMarker descr="Overrides function in 'First'">foo</lineMarker>() }
apache-2.0
bea44116470cd769f0a439985abb59a9
56.2
134
0.705951
4.263682
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/spellchecker/src/org/jetbrains/kotlin/idea/spellchecker/KotlinSpellcheckingStrategy.kt
6
1764
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.spellchecker import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.spellchecker.inspections.PlainTextSplitter import com.intellij.spellchecker.tokenizer.SpellcheckingStrategy import com.intellij.spellchecker.tokenizer.Tokenizer import com.intellij.spellchecker.tokenizer.TokenizerBase import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* class KotlinSpellcheckingStrategy : SpellcheckingStrategy() { private val plainTextTokenizer = TokenizerBase<KtLiteralStringTemplateEntry>(PlainTextSplitter.getInstance()) private val emptyTokenizer = EMPTY_TOKENIZER override fun getTokenizer(element: PsiElement?): Tokenizer<out PsiElement?> { return when (element) { is PsiComment -> super.getTokenizer(element) is KtParameter -> { val function = (element.parent as? KtParameterList)?.parent as? KtNamedFunction when { function?.hasModifier(KtTokens.OVERRIDE_KEYWORD) == true -> emptyTokenizer else -> super.getTokenizer(element) } } is PsiNameIdentifierOwner -> { when { element is KtModifierListOwner && element.hasModifier(KtTokens.OVERRIDE_KEYWORD) -> emptyTokenizer else -> super.getTokenizer(element) } } is KtLiteralStringTemplateEntry -> plainTextTokenizer else -> emptyTokenizer } } }
apache-2.0
5496e4216bdf37ba0fde95642e913677
44.230769
158
0.692177
5.297297
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/dialog/DlgAppPicker.kt
1
5119
package jp.juggler.subwaytooter.dialog import android.annotation.SuppressLint import android.app.Activity import android.app.AlertDialog import android.content.Intent import android.content.pm.PackageManager import android.content.pm.ResolveInfo import android.graphics.drawable.Drawable import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.widget.* import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.util.CustomShare import jp.juggler.subwaytooter.util.cn import jp.juggler.util.* class DlgAppPicker( val activity: Activity, val intent: Intent, val autoSelect: Boolean = false, val addCopyAction: Boolean = false, val filter: (ResolveInfo) -> Boolean = { true }, val callback: (String) -> Unit, ) { companion object { fun Char.isAlpha() = ('A' <= this && this <= 'Z') || ('a' <= this && this <= 'z') } class ListItem( val icon: Drawable?, val text: String, val componentName: String, ) val list = ArrayList<ListItem>().apply { val pm = activity.packageManager val listResolveInfo = pm.queryIntentActivitiesCompat(intent, PackageManager.MATCH_ALL) for (it in listResolveInfo) { if (!filter(it)) continue val cn = "${it.activityInfo.packageName}/${it.activityInfo.name}" val label = (it.loadLabel(pm)?.notEmpty() ?: cn).toString() add(ListItem(it.loadIcon(pm), label, cn)) } // 自動選択オフの場合、末尾にクリップボード項目を追加する if (addCopyAction && !autoSelect) { val (label, icon) = CustomShare.getInfo(activity, CustomShare.CN_CLIPBOARD.cn()) add(ListItem(icon, label.toString(), CustomShare.CN_CLIPBOARD)) } sortWith { a, b -> val a1 = a.text.firstOrNull() ?: '\u0000' val b1 = b.text.firstOrNull() ?: '\u0000' when { !a1.isAlpha() && b1.isAlpha() -> -1 a1.isAlpha() && !b1.isAlpha() -> 1 else -> a.text.compareTo(b.text, ignoreCase = true) } } } var dialog: AlertDialog? = null // returns false if fallback required @SuppressLint("InflateParams") fun show() = when { list.isEmpty() -> false autoSelect && list.size == 1 -> { callback(list.first().componentName) true } else -> { @SuppressLint("InflateParams") val listView: ListView = activity.layoutInflater.inflate(R.layout.dlg_app_picker, null, false).cast()!! val adapter = MyAdapter() listView.adapter = adapter listView.onItemClickListener = adapter this.dialog = AlertDialog.Builder(activity) .setView(listView) .setNegativeButton(R.string.cancel, null) .create() .apply { window?.setLayout( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT ) show() } true } } private inner class MyAdapter : BaseAdapter(), AdapterView.OnItemClickListener { override fun getCount(): Int = list.size override fun getItem(idx: Int) = list[idx] override fun getItemId(p0: Int) = 0L override fun getView(idx: Int, convertView: View?, parent: ViewGroup?): View { val view: View val holder: MyViewHolder if (convertView != null) { view = convertView holder = view.tag?.cast()!! } else { view = activity.layoutInflater.inflate(R.layout.lv_app_picker, parent, false) holder = MyViewHolder(view) view.tag = holder } holder.bind(list[idx]) return view } override fun onItemClick(parent: AdapterView<*>?, view: View?, idx: Int, id: Long) { dialog?.dismissSafe() callback(list[idx].componentName) } } private inner class MyViewHolder(viewRoot: View) { val ivImage: ImageView = viewRoot.findViewById(R.id.ivImage) val tvText: TextView = viewRoot.findViewById(R.id.tvText) var item: ListItem? = null fun bind(item: ListItem) { this.item = item if (item.icon != null) { ivImage.setImageDrawable(item.icon) } else { setIconDrawableId( activity, ivImage, R.drawable.ic_question, color = activity.attrColor(R.attr.colorVectorDrawable), alphaMultiplier = 1f ) } tvText.text = item.text } } }
apache-2.0
b0bdd7d2136fe46e835b2b90abeb2f18
31.322368
94
0.544324
4.64253
false
false
false
false
sreich/ore-infinium
core/src/com/ore/infinium/systems/client/BackgroundRenderSystem.kt
1
3153
/** MIT License Copyright (c) 2016 Shaun Reich <[email protected]> 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.ore.infinium.systems.client import aurelienribon.tweenengine.TweenManager import com.artemis.BaseSystem import com.artemis.annotations.Wire import com.badlogic.gdx.graphics.Camera import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.g2d.TextureAtlas import com.ore.infinium.OreSettings import com.ore.infinium.OreWorld import com.ore.infinium.components.ItemComponent import com.ore.infinium.components.SpriteComponent import com.ore.infinium.util.RenderSystemMarker import com.ore.infinium.util.mapper import ktx.assets.file @Wire class BackgroundRenderSystem(private val oreWorld: OreWorld, private val camera: Camera) : BaseSystem(), RenderSystemMarker { val backgroundAtlas: TextureAtlas = TextureAtlas(file("packed/backgrounds.atlas")) private val batch = SpriteBatch() private val mSprite by mapper<SpriteComponent>() private val mItem by mapper<ItemComponent>() // private lateinit var tagManager: TagManager private lateinit var tweenManager: TweenManager override fun initialize() { } override fun dispose() { batch.dispose() } override fun begin() { } override fun processSystem() { batch.projectionMatrix = camera.combined renderBackground() } override fun end() { } private fun renderBackground() { val skyBackground = backgroundAtlas.findRegion("background-sky") val debug = backgroundAtlas.findRegion("debug") batch.begin() batch.setColori(90, 142, 251, 255) batch.draw(debug, 0f, 0f, OreSettings.width.toFloat(), OreSettings.height.toFloat()) batch.color = Color.WHITE batch.draw(skyBackground, 0f, 0f, OreSettings.width.toFloat(), OreSettings.height.toFloat()) batch.end() } } private fun SpriteBatch.setColori(r: Int, g: Int, b: Int, a: Int) { this.setColor(r / 255f, g / 255f, b / 255f, a / 255f) }
mit
2e279a06b2fda6f545fd3a44b4180ffa
31.173469
86
0.732318
4.307377
false
false
false
false
gituser9/InvoiceManagement
app/src/main/java/com/user/invoicemanagement/model/ModelImpl.kt
1
7880
package com.user.invoicemanagement.model import com.raizlabs.android.dbflow.kotlinextensions.* import com.user.invoicemanagement.model.data.Summary import com.user.invoicemanagement.model.dto.* import io.reactivex.Observable class ModelImpl private constructor(): Model { companion object { val instance: ModelImpl by lazy { ModelImpl() } } override fun getAll(): Observable<List<ProductFactory>> { val results = (select from ProductFactory::class).list return Observable.fromArray(results) } override fun addNewFactory(name: String): ProductFactory { val newFactory = ProductFactory() newFactory.name = name newFactory.insert() return newFactory } override fun addNewProduct(factoryId: Long): Observable<Product>? { return try { val product = Product() product.factoryId = factoryId product.save() Observable.just(product) } catch (e: Exception) { e.printStackTrace() null } } override fun deleteProduct(id: Long) { val result = (select from Product::class where (Product_Table.id.eq(id))).result result?.delete() } override fun updateProduct(product: Product): Observable<Product>? { val result = (select from Product::class where (Product_Table.id.eq(product.id))).result ?: return null result.name = product.name result.weightOnStore = product.weightOnStore result.weightInFridge = product.weightInFridge result.weightInStorage = product.weightInStorage result.weight4 = product.weight4 result.weight5 = product.weight5 result.purchasePrice = product.purchasePrice result.sellingPrice = product.sellingPrice result.update() return Observable.just(result) } override fun deleteFactory(id: Long) { val products = (select from Product::class where Product_Table.factoryId.eq(id)).list for (item in products) { item.delete() } val factory = (select from ProductFactory::class where (ProductFactory_Table.id.eq(id))).result factory?.delete() } override fun updateFactory(newName: String, factoryId: Long) { val factory = (select from ProductFactory::class where (ProductFactory_Table.id.eq(factoryId))).result factory?.name = newName factory?.update() } override fun getSummary(): Observable<Summary> { var purchaseSummary = 0f var sellingSummary = 0f val factories = (select from ProductFactory::class).list for (factory in factories) { val products = (select from Product::class where Product_Table.factoryId.eq(factory.id)).list products.forEach { product: Product -> val sellingPriceSummary = (product.weightOnStore + product.weightInFridge + product.weightInStorage + product.weight4 + product.weight5) * product.sellingPrice val purchasePriceSummary = (product.weightOnStore + product.weightInFridge + product.weightInStorage + product.weight4 + product.weight5) * product.purchasePrice purchaseSummary += purchasePriceSummary sellingSummary += sellingPriceSummary } } return Observable.just(Summary(purchaseSummary, sellingSummary)) } override fun closeInvoice() { try { val factories = (select from ProductFactory::class).list val closedInvoice = ClosedInvoice() closedInvoice.savedDate = System.currentTimeMillis() closedInvoice.insert() val oldFactories = mutableListOf<OldProductFactory>() for (factory in factories) { val oldFactory = createOldFactory(factory) oldFactory.invoiceId = closedInvoice.id oldFactory.insert() oldFactories.add(oldFactory) createOldProducts(factory.products ?: emptyList(), oldFactory.id) cleanProducts(factory.products ?: emptyList()) } } catch (e: Exception) { e.printStackTrace() } } override fun getAllClosedInvoices(): Observable<List<ClosedInvoice>> { val closedInvoices = (select from ClosedInvoice::class).list return Observable.fromArray(closedInvoices) } override fun deleteInvoice(invoice: ClosedInvoice) { invoice.delete() } override fun getInvoice(invoiceId: Long): Observable<ClosedInvoice> { val result = (select from ClosedInvoice::class where (ClosedInvoice_Table.id.eq(invoiceId))).result return Observable.just(result) } override fun searchProducts(name: String): List<Product> { val products = (select from Product::class where (Product_Table.name.like("%$name%"))).list return products } override fun filterProducts(name: String): Observable<List<ProductFactory>> { val products = (select from Product::class where (Product_Table.name.like("%$name%"))).list val ids: MutableList<Long> = mutableListOf() for (product in products) { ids.add(product.factoryId) } val results = (select from ProductFactory::class where (ProductFactory_Table.id.`in`(ids))).list for (factory in results) { val filteredProducts: MutableList<Product> = mutableListOf() for (product in factory.products!!) { if (product.name.contains(name, true)) { filteredProducts.add(product) } } factory.products = filteredProducts } return Observable.fromArray(results) } override fun saveAll(products: List<Product>) { for (item in products) { item.save() } } override fun getFactory(id: Long): Observable<ProductFactory> { val result = (select from ProductFactory::class where (ProductFactory_Table.id.eq(id))).result return Observable.just(result) } private fun createOldFactory(factory: ProductFactory): OldProductFactory { val oldFactory = OldProductFactory() oldFactory.name = factory.name return oldFactory } private fun createOldProducts(products: List<Product>, factoryId: Long): List<OldProduct> { val oldProducts = mutableListOf<OldProduct>() // todo: product to data class for (product in products) { val oldProduct = OldProduct() oldProduct.factoryId = factoryId oldProduct.name = product.name oldProduct.weightOnStore = product.weightOnStore oldProduct.weightInFridge = product.weightInFridge oldProduct.weightInStorage = product.weightInStorage oldProduct.weight4 = product.weight4 oldProduct.weight5 = product.weight5 oldProduct.purchasePrice = product.purchasePrice oldProduct.sellingPrice = product.sellingPrice oldProduct.insert() oldProducts.add(oldProduct) } return oldProducts } private fun cleanProducts(products: List<Product>) { /*products.forEach { product: Product? -> if (product != null) { product.weightOnStore = 0f product.weightInFridge = 0f product.weightInStorage = 0f product.weight4 = 0f product.weight5 = 0f product.save() } }*/ for (product in products) { product.weightOnStore = 0f product.weightInFridge = 0f product.weightInStorage = 0f product.weight4 = 0f product.weight5 = 0f product.save() } } }
mit
7999aa7f428f4d8d82c05224e1f7847e
32.53617
177
0.627157
4.912718
false
false
false
false
vitaliy555/stdkotlin
src/i_introduction/_7_Nullable_Types/NullableTypes.kt
1
1171
package i_introduction._7_Nullable_Types import util.TODO import util.doc7 fun test() { val s: String = "this variable cannot store null references" val q: String? = null if (q != null) q.length // you have to check to dereference val i: Int? = q?.length // null val j: Int = q?.length ?: 0 // 0 } fun todoTask7(client: Client?, message: String?, mailer: Mailer): Nothing = TODO( """ Task 7. Rewrite JavaCode7.sendMessageToClient in Kotlin, using only one 'if' expression. Declarations of Client, PersonalInfo and Mailer are given below. """, documentation = doc7(), references = { JavaCode7().sendMessageToClient(client, message, mailer) } ) fun sendMessageToClient( client: Client?, message: String?, mailer: Mailer ) { var personalInfo=client?.personalInfo var email=personalInfo?.email if (email!=null && message!=null){ mailer.sendMessage(email, message!!)} // todoTask7(client, message, mailer) } class Client (val personalInfo: PersonalInfo?) class PersonalInfo (val email: String?) interface Mailer { fun sendMessage(email: String, message: String) }
mit
2e0ef406a582fa04f4a86e9663bf1620
26.232558
88
0.668659
3.969492
false
false
false
false