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
michaelkourlas/voipms-sms-client
voipms-sms/src/fdroid/kotlin/net/kourlas/voipms_sms/billing/Billing.kt
1
2463
/* * VoIP.ms SMS * Copyright (C) 2021 Michael Kourlas * * 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 net.kourlas.voipms_sms.billing import android.annotation.SuppressLint import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.net.Uri import androidx.fragment.app.FragmentActivity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import net.kourlas.voipms_sms.R import net.kourlas.voipms_sms.utils.showSnackbar class Billing(private val context: Context) { suspend fun askForCoffee(activity: FragmentActivity) = withContext(Dispatchers.Main) { try { val intent = Intent( Intent.ACTION_VIEW, Uri.parse( context.getString( R.string.coffee_url ) ) ) activity.startActivity(intent) } catch (_: ActivityNotFoundException) { showSnackbar( activity, R.id.coordinator_layout, context.getString( R.string.conversations_fail_web_browser ) ) } } companion object { // It is not a leak to store an instance to the application context, // since it has the same lifetime as the application itself. @SuppressLint("StaticFieldLeak") private var instance: Billing? = null /** * Gets the sole instance of the Billing class. Initializes the * instance if it does not already exist. */ fun getInstance(context: Context): Billing = instance ?: synchronized(this) { instance ?: Billing( context.applicationContext ).also { instance = it } } } }
apache-2.0
e35225ffce07f655c7522640f7db1023
33.704225
76
0.612261
5.088843
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/base/klib/src/org/jetbrains/kotlin/idea/klib/KlibLoadingMetadataCache.kt
3
4792
// 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.klib import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.containers.ContainerUtil import org.jetbrains.kotlin.backend.common.serialization.metadata.KlibMetadataVersion import org.jetbrains.kotlin.library.KLIB_MANIFEST_FILE_NAME import org.jetbrains.kotlin.library.KLIB_METADATA_FILE_EXTENSION import org.jetbrains.kotlin.library.KLIB_MODULE_METADATA_FILE_NAME import org.jetbrains.kotlin.library.metadata.KlibMetadataProtoBuf import org.jetbrains.kotlin.library.metadata.parseModuleHeader import org.jetbrains.kotlin.library.metadata.parsePackageFragment import org.jetbrains.kotlin.library.readKonanLibraryVersioning import org.jetbrains.kotlin.metadata.ProtoBuf import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion import java.io.IOException import java.util.* class KlibLoadingMetadataCache { // Use special CacheKey class instead of VirtualFile for cache keys. Certain types of VirtualFiles (for example, obtained from JarFileSystem) // do not compare path (url) and modification stamp in equals() method. private data class CacheKey( val url: String, val modificationStamp: Long ) { constructor(virtualFile: VirtualFile) : this(virtualFile.url, virtualFile.modificationStamp) } // ConcurrentWeakValueHashMap does not allow null values. private class CacheValue<T : Any>(val value: T?) private val packageFragmentCache = ContainerUtil.createConcurrentWeakValueMap<CacheKey, CacheValue<ProtoBuf.PackageFragment>>() private val moduleHeaderCache = ContainerUtil.createConcurrentWeakValueMap<CacheKey, CacheValue<KlibMetadataProtoBuf.Header>>() private val libraryMetadataVersionCache = ContainerUtil.createConcurrentWeakValueMap<CacheKey, CacheValue<KlibMetadataVersion>>() fun getCachedPackageFragment(packageFragmentFile: VirtualFile): ProtoBuf.PackageFragment? { check(packageFragmentFile.extension == KLIB_METADATA_FILE_EXTENSION) { "Not a package metadata file: $packageFragmentFile" } return packageFragmentCache.computeIfAbsent( CacheKey(packageFragmentFile) ) { CacheValue(computePackageFragment(packageFragmentFile)) }.value } fun getCachedModuleHeader(moduleHeaderFile: VirtualFile): KlibMetadataProtoBuf.Header? { check(moduleHeaderFile.name == KLIB_MODULE_METADATA_FILE_NAME) { "Not a module header file: $moduleHeaderFile" } return moduleHeaderCache.computeIfAbsent( CacheKey(moduleHeaderFile) ) { CacheValue(computeModuleHeader(moduleHeaderFile)) }.value } private fun isMetadataCompatible(libraryRoot: VirtualFile): Boolean { val manifestFile = libraryRoot.findChild(KLIB_MANIFEST_FILE_NAME) ?: return false val metadataVersion = libraryMetadataVersionCache.computeIfAbsent( CacheKey(manifestFile) ) { CacheValue(computeLibraryMetadataVersion(manifestFile)) }.value ?: return false return metadataVersion.isCompatible() } private fun computePackageFragment(packageFragmentFile: VirtualFile): ProtoBuf.PackageFragment? { if (!isMetadataCompatible(packageFragmentFile.parent.parent.parent)) return null return try { parsePackageFragment(packageFragmentFile.contentsToByteArray(false)) } catch (_: IOException) { null } } private fun computeModuleHeader(moduleHeaderFile: VirtualFile): KlibMetadataProtoBuf.Header? { if (!isMetadataCompatible(moduleHeaderFile.parent.parent)) return null return try { parseModuleHeader(moduleHeaderFile.contentsToByteArray(false)) } catch (_: IOException) { null } } private fun computeLibraryMetadataVersion(manifestFile: VirtualFile): KlibMetadataVersion? = try { val versioning = Properties().apply { manifestFile.inputStream.use { load(it) } }.readKonanLibraryVersioning() versioning.metadataVersion?.let(BinaryVersion.Companion::parseVersionArray)?.let(::KlibMetadataVersion) } catch (_: IOException) { // ignore and cache null value null } catch (_: IllegalArgumentException) { // ignore and cache null value null } companion object { @JvmStatic fun getInstance(): KlibLoadingMetadataCache = ApplicationManager.getApplication().getService(KlibLoadingMetadataCache::class.java) } }
apache-2.0
0b9252983fefab1518a2a1f315c00d44
41.40708
158
0.733097
5.070899
false
false
false
false
bertilxi/DC-Android
app/src/main/java/utnfrsf/dondecurso/activity/FavoritoActivity.kt
1
5810
package utnfrsf.dondecurso.activity import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.View import android.widget.AdapterView import android.widget.Spinner import io.paperdb.Paper import utnfrsf.dondecurso.R import utnfrsf.dondecurso.common.async import utnfrsf.dondecurso.common.findView import utnfrsf.dondecurso.common.onUI import utnfrsf.dondecurso.domain.* import utnfrsf.dondecurso.view.MyArrayAdapter import utnfrsf.dondecurso.view.MySpinner class FavoritoActivity : AppCompatActivity() { private val spinnerNivel: Spinner by lazy { findView<Spinner>(R.id.spinner_nivel) } private val spinnerMateria: MySpinner by lazy { findView<MySpinner>(R.id.spinner_materia) } private val spinnerComision: Spinner by lazy { findView<Spinner>(R.id.spinner_comision) } private val fab: FloatingActionButton by lazy { findView<FloatingActionButton>(R.id.fab_favorito) } private var adapterNivel: MyArrayAdapter<Nivel>? = null private var adapterMateria: MyArrayAdapter<Materia>? = null private var adapterComision: MyArrayAdapter<Comision>? = null private var niveles: ArrayList<Nivel> = ArrayList<Nivel>() private var materias: ArrayList<Materia> = ArrayList<Materia>() private var filteredMaterias: ArrayList<Materia> = ArrayList<Materia>() private var comisiones: ArrayList<Comision> = ArrayList<Comision>() private var favoritos: ArrayList<Favorito> = ArrayList<Favorito>() private var carrera: Carrera? = null private var nivel: Nivel? = null private var materia: Materia? = null private var comision: Comision? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_favorito) val toolbar = findView<Toolbar>(R.id.toolbar_favorito) setSupportActionBar(toolbar) supportActionBar!!.setDisplayHomeAsUpEnabled(true) async { carrera = Paper.book().read("carrera") niveles = Paper.book().read("niveles") materias = Paper.book().read("materias", ArrayList()) comisiones = Paper.book().read("comisiones", ArrayList()) favoritos = Paper.book().read("favoritos", ArrayList()) onUI { setupView() } } } fun setupView(){ adapterNivel = MyArrayAdapter(this@FavoritoActivity, R.layout.spinner_item_dark, niveles, true) adapterComision = MyArrayAdapter(this@FavoritoActivity, R.layout.spinner_item_dark, comisiones, true) adapterMateria = MyArrayAdapter(this@FavoritoActivity, R.layout.spinner_item_dark, filteredMaterias, true) spinnerMateria.adapter = adapterMateria spinnerNivel.adapter = adapterNivel spinnerComision.adapter = adapterComision spinnerMateria.setOnItemSelectedEvenIfUnchangedListener(object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) {} override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { materia = filteredMaterias[position] comisiones.clear() comisiones.addAll(materia!!.comisiones!!) if (comisiones.size != 1) { comisiones.add(0, Comision(0, "Todas")) } if (comisiones.size == 1) { comision = comisiones[0] } adapterComision!!.notifyDataSetChanged() spinnerComision.setSelection(adapterComision?.getPosition(comision)!!) } }) spinnerNivel.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) {} override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { nivel = niveles[position] processSubjectsLoad() } } spinnerComision.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) {} override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { comision = comisiones[position] } } fab.setOnClickListener { if(nivel == null) return@setOnClickListener if(materia == null) return@setOnClickListener if(comision == null) return@setOnClickListener async { val favorito = Favorito(carrera!!, nivel!!, materia!!, comision!!) favoritos.add(favorito) Paper.book().write("favoritos", favoritos) onUI { finish() } } } } fun processSubjectsLoad() { filteredMaterias.clear() if (carrera!!.id != 0 && nivel?.id != 0) { materias.asSequence() .filter { it.idCarrera == carrera!!.id && it.nivel == nivel?.id } .forEach { filteredMaterias.add(it) } } else if (carrera!!.id != 0 && nivel?.id == 0) { materias.asSequence() .filter { it.idCarrera == carrera!!.id } .forEach { filteredMaterias.add(it) } } if (filteredMaterias.size != 1) { filteredMaterias.add(0, Materia(0, "Todas")) } adapterMateria?.notifyDataSetChanged() if (filteredMaterias.contains(materia)) { spinnerMateria.setSelection(adapterMateria?.getPosition(materia)!!) } else { spinnerMateria.setSelection(0) } } }
mit
6b29bed7af80909e9dec0f0d425aba99
40.798561
114
0.644062
4.281503
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/inference/common/DebugPrinter.kt
3
2885
// 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.j2k.post.processing.inference.common import com.intellij.psi.PsiElement import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtTypeElement import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType class DebugPrinter(private val inferenceContext: InferenceContext) { private val namer = Namer(inferenceContext) val TypeVariable.name: String get() = namer.name(this) private fun ClassReference.asString() = when (this) { is DescriptorClassReference -> descriptor.name.toString() is TypeParameterReference -> descriptor.name.toString() is NoClassReference -> "NoClassRef" } fun BoundTypeLabel.asString(): String = when (this) { is TypeVariableLabel -> typeVariable.name + "@" + typeVariable.classReference.asString() is TypeParameterLabel -> typeParameter.name.asString() is GenericLabel -> classReference.asString() StarProjectionLabel -> "*" NullLiteralLabel -> "NULL" LiteralLabel -> "LIT" } fun State.asString() = when (this) { State.LOWER -> "L" State.UPPER -> "U" State.UNKNOWN -> "?" State.UNUSED -> "$" } fun BoundType.asString(): String = buildString { append(label.asString()) if (typeParameters.isNotEmpty()) { typeParameters.joinTo(this, ", ", "<", ">") { it.boundType.asString() } } if (this@asString is WithForcedStateBoundType) { append("!!") append(forcedState.asString()) } } fun Constraint.asString() = when (this) { is EqualsConstraint -> "${left.asString()} := ${right.asString()}" is SubtypeConstraint -> "${subtype.asString()} <: ${supertype.asString()}" } + " due to '$priority'" private fun ConstraintBound.asString(): String = when (this) { is LiteralBound -> state.toString() is TypeVariableBound -> typeVariable.name } fun PsiElement.addTypeVariablesNames() { val factory = KtPsiFactory(this) for (typeElement in collectDescendantsOfType<KtTypeElement>()) { val typeVariableName = [email protected][typeElement]?.name ?: continue val comment = factory.createComment("/*$typeVariableName@*/") typeElement.parent.addBefore(comment, typeElement) } } } private class Namer(inferenceContext: InferenceContext) { private val names = inferenceContext.typeVariables.mapIndexed { index, typeVariable -> typeVariable to "T$index" }.toMap() fun name(typeVariable: TypeVariable): String = names.getValue(typeVariable) }
apache-2.0
c5b054d274caf13f51d080274b56da29
36
158
0.662392
4.824415
false
false
false
false
byu-oit/android-byu-suite-v2
support/src/main/java/edu/byu/support/utils/Extensions.kt
1
14712
package edu.byu.support.utils import android.app.Activity import android.app.AlertDialog import android.content.Context import android.content.DialogInterface import android.content.Intent import android.content.pm.PackageManager import android.graphics.Point import android.location.Location import android.os.Build import android.os.Parcel import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.text.Html import android.text.Spanned import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Spinner import android.widget.Toast import com.google.android.gms.location.* import com.google.android.gms.tasks.Task import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.LatLngBounds import edu.byu.support.R import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit import kotlin.math.ceil import kotlin.math.floor import kotlin.math.roundToInt import java.util.regex.Pattern import kotlin.math.PI import kotlin.math.cos import kotlin.math.pow /** * Created by geogor37 on 2/27/18 */ // Words that shouldn't follow normal title case rules private val REPLACEMENTS = arrayOf("and", "for", "in", "McDonald", "McKay", "of", "the", "www", "YNews", "to") // Make the replacements case insensitive. Also check to make sure we didn't just find the string inside another word. Should be used with the strings in REPLACEMENTS private const val REPLACEMENT_REGEX = "(?i)(?<=\\b)%s(?=\\b)" // Words that should be left as all caps. This assumes that the string passed in is already all caps private val EXCEPTIONS = arrayOf("BYU", "BYUSA", "CAEDM", "CB", "CIO", "CITES", "CES", "CNA", "CTB", "DNA", "FLAS", "FM", "ICLA", "ID", "KBYU", "LDS", "MTC", "MPH", "N7BYU", "NMELRC", "OIT", "ORCA", "RB", "ROTC", "SAS", "SFH", "TEC", "TV", "WSC", "YSA") private const val RADIUS_EARTH_METERS = 6378000 /** * FIRST CAPTURING GROUP: (^|[ (/-]) * This is the list of characters that should be followed by a capital. ^ is the start of the string but if we put it inside the brackets it means not, so we have to leave it outside the brackets. * Putting it inside and escaping it doesn't work because that just makes it the literal ^ character. Then we have that or a space, opening parenthesis, slash, or dash. The dash has to be at the end * (right before the closing bracket) or else it is interpreted as all the characters between the two surrounding characters (e.g. [a-e] is a, b, c, d, and e and [ae-] is a, e, and -. * SECOND (NOT CAPTURING) GROUP: (?!(?:" + EXCEPTIONS.joinToString("|") + ")[ (/-]) * (?!example) negative lookahead - don't match if the next thing is example * (" + EXCEPTIONS.joinToString("|") + ")\\b) The exceptions are all the things that we want to stay in all caps (again, this assumes that the input string is all caps). * This ors all of them together. Then it makes sure that the exception found is not the beginning of another word by checking for a word boundary (\b). We know this is at * the start of a word because of the first capturing group, this makes sure it's not just at the start of another word * SECOND CAPTURING GROUP: ([a-zA-Z]) * Captures the first letter of the word, so we can capitalize it * THIRD CAPTURING GROUP: ([\\w'\\.]*) * Capture the rest of the word (including apostrophes, periods (for web addresses), and possibly numbers) so we can lowercase it */ private val PATTERN = Pattern.compile("(^|[ (/-])(?!(?:" + EXCEPTIONS.joinToString("|") + ")\\b)([a-zA-Z])([\\w'.]*)") fun Activity.hideKeyboard() { try { (getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(currentFocus.windowToken, 0) } catch (ignore: NullPointerException) { } } fun Activity.getDisplaySize(): Point { val display = windowManager.defaultDisplay val size = Point() display.getSize(size) return size } fun AlertDialog.Builder.setPositiveButton(callback: (DialogInterface, Int) -> Unit): AlertDialog.Builder { return this.setPositiveButton(android.R.string.ok, callback) } fun Boolean?.orFalse(): Boolean { return this == true } fun Calendar.setTime(hourOfDay: Int? = null, minutes: Int? = null, seconds: Int? = null): Calendar { hourOfDay?.let { set(Calendar.HOUR_OF_DAY, it) } minutes?.let { set(Calendar.MINUTE, it) } seconds?.let { set(Calendar.SECOND, it) } return this } fun Collection<*>?.isNullOrEmpty() = this == null || this.isEmpty() fun Context.inflate(parent: ViewGroup?, layoutResId: Int): View = LayoutInflater.from(this).inflate(layoutResId, parent, false) fun Context.showAlertDialog(title: String? = null, message: String? = null, positiveText: String = getString(android.R.string.ok), positiveListener: ((DialogInterface, Int) -> Unit)? = null, negativeText: String? = getString(android.R.string.cancel), negativeListener: ((DialogInterface, Int) -> Unit)? = null, cancelable: Boolean = true) { AlertDialog.Builder(this) .setTitle(title) .setMessage(message) .setPositiveButton(positiveText, positiveListener) .setNegativeButton(negativeText, negativeListener) .setCancelable(cancelable) .show() } fun Context.confirmCancelDialog(title: String? = null, message: String? = null, confirmListener: ((DialogInterface, Int) -> Unit)? = null, cancelListener: ((DialogInterface, Int) -> Unit)? = null) { showAlertDialog(title, message, getString(R.string.confirm), confirmListener, getString(R.string.cancel), cancelListener, false) } fun Context.isPermissionGranted(permission: String) = ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED fun Context.getColorFromRes(colorRes: Int) = ContextCompat.getColor(this, colorRes) fun Context.getDrawableFromRes(drawableRes: Int) = ContextCompat.getDrawable(this, drawableRes) fun Context.displayToast(message: String, lengthLong: Boolean = false) { Toast.makeText(this, message, if (lengthLong) Toast.LENGTH_LONG else Toast.LENGTH_SHORT).show() } fun Context.getFusedLocationClient(): FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this) fun Context.checkLocationSettings(request: LocationRequest): Task<LocationSettingsResponse> = LocationServices.getSettingsClient(this).checkLocationSettings(LocationSettingsRequest.Builder().addLocationRequest(request).build()) fun Date.isBetween(startDate: Date?, endDate: Date?): Boolean { return (startDate?.before(this).orFalse() || startDate == this) && (endDate?.after(this).orFalse() || endDate == this) } fun Date.format(pattern: String): String { return SimpleDateFormat(pattern, Locale.US).format(this) } fun Date.getDayOfWeek(): String { return format("EEEE") } fun Date?.getElapsedTimeSince(): String { fun getPluralSuffix(isPlural: Boolean): String = if (isPlural) "s" else "" if (this == null) { return "In progress" } val millis = Date().time - time val minutes = TimeUnit.MILLISECONDS.toMinutes(millis).toInt() val hours = TimeUnit.MILLISECONDS.toHours(millis).toInt() val days = TimeUnit.MILLISECONDS.toDays(millis).toInt() val months = days / 30 val years = days / 365 return when { minutes < 1 -> "moments" hours < 1 -> "$minutes minute${getPluralSuffix(minutes > 1)}" days < 1 -> "$hours hour${getPluralSuffix(hours > 1)}" months < 1 -> "$days day${getPluralSuffix(days > 1)}" years < 1 -> "$months month${getPluralSuffix(months > 1)}" else -> "$years year${getPluralSuffix(years > 1)}" } } /** * Returns an integer equivalent to the first specified number of digits. (e.g. 123.firstXDigits(2) returns 12 * * @return An integer equivalent to the first specified number of digits, null if number of digits is non-positive */ fun Int.firstXDigits(numDigits: Int): Int? { return if (numDigits > 0) { var firstDigits = this while (firstDigits >= (10 * numDigits)) { firstDigits /= 10 } firstDigits } else { null } } /** * @return Number of digits in an integer */ fun Int.numDigits(): Int { if (this == 0) { return 1 } var length = 0 var temp: Long = 1 while (temp <= Math.abs(this)) { length++ temp *= 10 } return length } fun Double.roundDown() = floor(this).roundToInt() fun Double.roundUp() = ceil(this).roundToInt() // We added this Extension because the kotlin mod function (.rem()) doesn't handle negatives correctly fun Int.modulo(other: Int) = this.rem(other).let { remainder -> if (remainder < 0) remainder + other else remainder } fun Intent.getDateExtra(name: String) = getSerializableExtra(name) as Date /** * @return the distance between the two points in meters as a float */ fun LatLng.distanceTo(other: LatLng): Float { //Results of the Location.distanceBetween is stored in the results array val results = FloatArray(1) Location.distanceBetween(latitude, longitude, other.latitude, other.longitude, results) return results[0] } /** * This returns new bounds that ensures that the zoom level passed in is not exceeded. The documentation on zoom level explains that a zoom level 1 will show * the whole Earth and that each zoom level after that shows half of the previous zoom level. Using this we can determine that the the meters shown is the result * of the function (2 * EARTH_DIAMETER) / (2^zoomLevel)). We then can ensure that at least that many meters are shown while maintaining the center of the original * bounds in the center. * * @return LatLngBounds that include the area viewable from the minimum zoom */ fun LatLngBounds.Builder.adjustToMaxZoom(bounds: LatLngBounds, zoom: Float): LatLngBounds { // This calculates the number of meters shown on the screen at a given zoom level // The equation is (2 * EARTH_DIAMETER) / (2^zoomLevel)) val meters = ((RADIUS_EARTH_METERS * 4).toFloat() / (2f.pow(zoom))).toDouble() // This calculates where the new boundary corners should be to maintain the given zoom val newLatitude1 = bounds.center.latitude + (((meters / 2) / RADIUS_EARTH_METERS) * (180 / PI)) val newLongitude1 = bounds.center.longitude + ((meters / 2) / RADIUS_EARTH_METERS) * (180 / PI) / cos(bounds.center.latitude * PI / 180) val newLatitude2 = bounds.center.latitude + (((-meters / 2) / RADIUS_EARTH_METERS) * (180 / PI)) val newLongitude2 = bounds.center.longitude + ((-meters / 2) / RADIUS_EARTH_METERS) * (180 / PI) / cos(bounds.center.latitude * PI / 180) include(LatLng(newLatitude1, newLongitude1)) include(LatLng(newLatitude2, newLongitude2)) // Include previous bounds so that if it is bigger than the zoom window it doesn't zoom in include(bounds.northeast) include(bounds.southwest) return build() } // Setting the interval to 0 and setting the priority to high accuracy will get us the user's location as quickly as possible. fun LocationRequest.fastest() = this.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(0) fun <T, S: T, R: T> MutableList<T>.replaceOrAdd(replacer: S, replacee: R) { indexOf(replacee).let { if (it > -1) this[it] = replacer else add(replacer) } } fun Parcel.writeBoolean(boolean: Boolean) = writeByte(if (boolean) 1 else 0) fun Parcel.readBoolean() = readByte().compareTo(0) != 0 fun Parcel.writeBoolean(boolean: Boolean?) = writeInt(when (boolean) { null -> 0 false -> 1 true -> 2 }) fun Parcel.readBooleanOpt() = when (readInt()) { 0 -> null 1 -> false else -> true } fun Parcel.writeDouble(double: Double?) = writeValue(double) fun Parcel.readDoubleOpt() = readValue(Double::class.java.classLoader) as? Double fun Parcel.writeInt(int: Int?) = writeValue(int) fun Parcel.readIntOpt() = readValue(Int::class.java.classLoader) as? Int fun Parcel.writeDate(date: Date?) = writeValue(date?.time) fun Parcel.readDate() = (readValue(Long::class.java.classLoader) as? Long)?.let { Date(it) } fun <DataType> Spinner.setUpAdapter(context: Context, list: List<DataType>?, onItemSelectedListener: AdapterView.OnItemSelectedListener?): ArrayAdapter<DataType> { val arrayAdapter = ArrayAdapter<DataType>(context, R.layout.byu_simple_spinner_dropdown_item, list.orEmpty()) arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) onItemSelectedListener?.let { setOnItemSelectedListener(it) } adapter = arrayAdapter return arrayAdapter } /** * This computes the next day with the given name. It should only be called on a string that represents a day in the week ("Monday", "Tuesday", etc.) * * @return Date object of the next day with the given name and null if the day is invalid */ fun String.getNextDateWithDayName(): Date? { val calendar = GregorianCalendar() calendar.time = Date() calendar.set(Calendar.HOUR_OF_DAY, 0) calendar.set(Calendar.MINUTE, 0) calendar.set(Calendar.SECOND, 0) calendar.set(Calendar.MILLISECOND, 0) return getNumDaysUntilDay()?.let { calendar.add(Calendar.DATE, it) return calendar.time } } /** * How many days in the future is the next occurrence of day. It should only be called on a string that represents a day in the week ("Monday", "Tuesday", etc.) * * @return Int of the number of days until the next occurrence of that day, null if the day is invalid */ fun String.getNumDaysUntilDay(): Int? { val today = Date().getDayOfWeek() val daysOfWeek = arrayListOf("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday") return if (daysOfWeek.contains(this.toLowerCase())) ((daysOfWeek.indexOf(this.toLowerCase()) - daysOfWeek.indexOf(today.toLowerCase()) + 7) % 7) else null } @Suppress("DEPRECATION") fun String.fromHtml() = (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY) else Html.fromHtml(this)).trim() as? Spanned /** * @return A string that has been changed to title case */ fun String.toTitleCase(): String { val matcher = PATTERN.matcher(this) val stringBuffer = StringBuffer() // Find the next match in the string while (matcher.find()) { // append everything we skipped, and then append group 1 (the delimiter that separated this match from the last word), group 2 (the first letter) uppercased, and group 3 (the rest of the word) lowercased matcher.appendReplacement(stringBuffer, matcher.group(1) + matcher.group(2).toUpperCase() + matcher.group(3).toLowerCase()) } // append the rest of the string matcher.appendTail(stringBuffer) return stringBuffer.toString().titleCaseExceptionCorrection() } private fun String.titleCaseExceptionCorrection(): String { var returnString = this REPLACEMENTS.forEach { returnString = returnString.replace(String.format(REPLACEMENT_REGEX, it).toRegex(), it) } return returnString }
apache-2.0
36c222226b567f2a8b4a11582b94bd8a
41.397695
340
0.737153
3.655155
false
false
false
false
android/play-billing-samples
ClassyTaxiAppKotlin/app/src/main/java/com/example/subscriptions/ui/TvMainActivity.kt
1
6168
/* * Copyright 2019 Google LLC. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.subscriptions.ui import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModelProvider import com.android.billingclient.api.Purchase import com.example.subscriptions.Constants import com.example.subscriptions.R import com.example.subscriptions.SubApp import com.example.subscriptions.billing.BillingClientLifecycle import com.firebase.ui.auth.AuthUI /** * TvMainActivity contains a TvMainFragment that leverages Leanback UI to build an optimized * Android TV experience for Classy Taxi. * * This Activity follows a nearly identical pattern to its sibling class MainActivity, * subscribing to the sameViewModels and providing similar business logic. * */ class TvMainActivity : FragmentActivity() { companion object { private const val TAG = "TvMainActivity" private const val RC_SIGN_IN = 0 } private lateinit var billingClientLifecycle: BillingClientLifecycle private lateinit var authenticationViewModel: FirebaseUserViewModel private lateinit var billingViewModel: BillingViewModel private lateinit var subscriptionViewModel: SubscriptionStatusViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_tv_main) authenticationViewModel = ViewModelProvider(this).get(FirebaseUserViewModel::class.java) billingViewModel = ViewModelProvider(this).get(BillingViewModel::class.java) subscriptionViewModel = ViewModelProvider(this).get(SubscriptionStatusViewModel::class.java) // Billing APIs are all handled in the this lifecycle observer. billingClientLifecycle = (application as SubApp).billingClientLifecycle lifecycle.addObserver(billingClientLifecycle) // Launch the billing flow when the user clicks a button to buy something. billingViewModel.buyEvent.observe(this) { if (it != null) { billingClientLifecycle.launchBillingFlow(this, it) } } // Open the Play Store when this event is triggered. billingViewModel.openPlayStoreSubscriptionsEvent.observe(this) { product -> Log.i(TAG, "Viewing subscriptions on the Google Play Store") val url = product?.let { // If the Product is specified, open the deeplink for this product on Google Play. String.format(Constants.PLAY_STORE_SUBSCRIPTION_DEEPLINK_URL, it, packageName) } ?: Constants.PLAY_STORE_SUBSCRIPTION_URL // Or open the Google Play subscriptions URL. val intent = Intent(Intent.ACTION_VIEW).apply { data = Uri.parse(url) } startActivity(intent) } // Update authentication UI. authenticationViewModel.firebaseUser.observe(this) { invalidateOptionsMenu() if (it == null) { triggerSignIn() } else { Log.d(TAG, "CURRENT user: ${it.email} ${it.displayName}") } } // Update subscription information when user changes. authenticationViewModel.userChangeEvent.observe(this) { subscriptionViewModel.userChanged() registerPurchases(billingClientLifecycle.purchases.value) } } /** * Register Products and purchase tokens with the server. */ private fun registerPurchases(purchaseList: List<Purchase>) { for (purchase in purchaseList) { val product = purchase.products[0] val purchaseToken = purchase.purchaseToken Log.d(TAG, "Register purchase with product: $product, token: $purchaseToken") subscriptionViewModel.registerSubscription( product = product, purchaseToken = purchaseToken ) } } /** * Sign in with FirebaseUI Auth. */ fun triggerSignIn() { Log.d(TAG, "Attempting SIGN-IN!") val providers = listOf( AuthUI.IdpConfig.EmailBuilder().build(), AuthUI.IdpConfig.GoogleBuilder().build() ) startActivityForResult( AuthUI.getInstance() .createSignInIntentBuilder() .setAvailableProviders(providers) .build(), RC_SIGN_IN ) } /** * Sign out with FirebaseUI Auth. */ fun triggerSignOut() { subscriptionViewModel.unregisterInstanceId() AuthUI.getInstance().signOut(this).addOnCompleteListener { Log.d(TAG, "User SIGNED OUT!") authenticationViewModel.updateFirebaseUser() } } /** * Receive Activity result, including sign-in result. */ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { RC_SIGN_IN -> { // If sign-in is successful, update ViewModel. if (resultCode == RESULT_OK) { Log.d(TAG, "Sign-in SUCCESS!") authenticationViewModel.updateFirebaseUser() } else { Log.d(TAG, "Sign-in FAILED!") } } else -> { Log.e(TAG, "Unrecognized request code: $requestCode") } } } }
apache-2.0
9400529573a267eea52b6b4c3d200795
35.502959
100
0.648995
5.064039
false
false
false
false
jk1/intellij-community
platform/testFramework/src/com/intellij/util/io/impl/DirectoryContentSpecImpl.kt
2
5775
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.io.impl import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.util.io.DirectoryContentBuilder import com.intellij.util.io.DirectoryContentSpec import com.intellij.util.io.ZipUtil import org.junit.Assert.* import java.io.BufferedOutputStream import java.io.File import java.io.IOException import java.util.* import java.util.zip.ZipOutputStream /** * @author nik */ sealed class DirectoryContentSpecImpl : DirectoryContentSpec { } abstract class DirectorySpecBase : DirectoryContentSpecImpl() { protected val children: LinkedHashMap<String, DirectoryContentSpecImpl> = LinkedHashMap<String, DirectoryContentSpecImpl>() fun addChild(name: String, spec: DirectoryContentSpecImpl) { if (name in children) { val existing = children[name] if (spec is DirectorySpecBase && existing is DirectorySpecBase) { existing.children += spec.children return } throw IllegalArgumentException("'$name' already exists") } children[name] = spec } protected fun generateInDirectory(target: File) { for ((name, child) in children) { child.generate(File(target, name)) } } override fun generateInTempDir(): File { val target = FileUtil.createTempDirectory("directory-by-spec", null, true) generate(target) return target } fun getChildren() : Map<String, DirectoryContentSpecImpl> = Collections.unmodifiableMap(children) } class DirectorySpec : DirectorySpecBase() { override fun generate(target: File) { if (!FileUtil.createDirectory(target)) { throw IOException("Cannot create directory $target") } generateInDirectory(target) } } class ZipSpec : DirectorySpecBase() { override fun generate(target: File) { val contentDir = FileUtil.createTempDirectory("zip-content", null, false) try { generateInDirectory(contentDir) ZipOutputStream(BufferedOutputStream(target.outputStream())).use { ZipUtil.addDirToZipRecursively(it, null, contentDir, "", null, null) } } finally { FileUtil.delete(contentDir) } } } class FileSpec(val content: ByteArray?) : DirectoryContentSpecImpl() { override fun generate(target: File) { FileUtil.writeToFile(target, content ?: ByteArray(0)) } override fun generateInTempDir(): File { val target = FileUtil.createTempFile("file-by-spec", null, true) generate(target) return target } } class DirectoryContentBuilderImpl(val result: DirectorySpecBase) : DirectoryContentBuilder() { override fun addChild(name: String, spec: DirectoryContentSpecImpl) { result.addChild(name, spec) } override fun file(name: String) { addChild(name, FileSpec(null)) } override fun file(name: String, text: String) { file(name, text.toByteArray()) } override fun file(name: String, content: ByteArray) { addChild(name, FileSpec(content)) } } fun assertDirectoryContentMatches(file: File, spec: DirectoryContentSpecImpl, relativePath: String) { when (spec) { is DirectorySpec -> { assertDirectoryMatches(file, spec, relativePath) } is ZipSpec -> { val dirForExtracted = FileUtil.createTempDirectory("extracted-${file.name}", null, false) ZipUtil.extract(file, dirForExtracted, null) assertDirectoryMatches(dirForExtracted, spec, relativePath) FileUtil.delete(dirForExtracted) } is FileSpec -> { assertTrue("$file is not a file", file.isFile) if (spec.content != null) { val actualBytes = FileUtil.loadFileBytes(file) if (!Arrays.equals(actualBytes, spec.content)) { val actualString = actualBytes.convertToText() val expectedString = spec.content.convertToText() val place = if (relativePath != "") " at $relativePath" else "" if (actualString != null && expectedString != null) { assertEquals("File content mismatch$place:", expectedString, actualString) } else { fail("Binary file content mismatch$place") } } } } } } private fun ByteArray.convertToText(): String? { val encoding = CharsetToolkit(this, Charsets.UTF_8).guessFromContent(size) val charset = when (encoding) { CharsetToolkit.GuessedEncoding.SEVEN_BIT -> Charsets.US_ASCII CharsetToolkit.GuessedEncoding.VALID_UTF8 -> Charsets.UTF_8 else -> return null } return String(this, charset) } private fun assertDirectoryMatches(file: File, spec: DirectorySpecBase, relativePath: String) { assertTrue("$file is not a directory", file.isDirectory) val actualChildrenNames = file.list().sortedWith(String.CASE_INSENSITIVE_ORDER) val children = spec.getChildren() val expectedChildrenNames = children.keys.sortedWith(String.CASE_INSENSITIVE_ORDER) assertEquals("Directory content mismatch${if (relativePath != "") " at $relativePath" else ""}:", expectedChildrenNames.joinToString("\n"), actualChildrenNames.joinToString("\n")) actualChildrenNames.forEach { child -> assertDirectoryContentMatches(File(file, child), children[child]!!, "$relativePath/$child") } }
apache-2.0
4e52bfcb1a03fb0129b92a9fd5aa05c6
32.77193
125
0.710476
4.483696
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/database/GroupCallRingDatabase.kt
2
2886
package org.thoughtcrime.securesms.database import android.content.ContentValues import android.content.Context import org.signal.core.util.CursorUtil import org.signal.core.util.SqlUtil import org.signal.ringrtc.CallManager import java.util.concurrent.TimeUnit /** * Track state of Group Call ring cancellations. */ class GroupCallRingDatabase(context: Context, databaseHelper: SignalDatabase) : Database(context, databaseHelper) { companion object { private val VALID_RING_DURATION = TimeUnit.MINUTES.toMillis(30) private const val TABLE_NAME = "group_call_ring" private const val ID = "_id" private const val RING_ID = "ring_id" private const val DATE_RECEIVED = "date_received" private const val RING_STATE = "ring_state" @JvmField val CREATE_TABLE = """ CREATE TABLE $TABLE_NAME ( $ID INTEGER PRIMARY KEY, $RING_ID INTEGER UNIQUE, $DATE_RECEIVED INTEGER, $RING_STATE INTEGER ) """.trimIndent() @JvmField val CREATE_INDEXES = arrayOf( "CREATE INDEX date_received_index on $TABLE_NAME ($DATE_RECEIVED)" ) } fun isCancelled(ringId: Long): Boolean { val db = databaseHelper.signalReadableDatabase db.query(TABLE_NAME, null, "$RING_ID = ?", SqlUtil.buildArgs(ringId), null, null, null).use { cursor -> if (cursor.moveToFirst()) { return CursorUtil.requireInt(cursor, RING_STATE) != 0 } } return false } fun insertGroupRing(ringId: Long, dateReceived: Long, ringState: CallManager.RingUpdate) { val db = databaseHelper.signalWritableDatabase val values = ContentValues().apply { put(RING_ID, ringId) put(DATE_RECEIVED, dateReceived) put(RING_STATE, ringState.toCode()) } db.insert(TABLE_NAME, null, values) removeOldRings() } fun insertOrUpdateGroupRing(ringId: Long, dateReceived: Long, ringState: CallManager.RingUpdate) { val db = databaseHelper.signalWritableDatabase val values = ContentValues().apply { put(RING_ID, ringId) put(DATE_RECEIVED, dateReceived) put(RING_STATE, ringState.toCode()) } db.insertWithOnConflict(TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_REPLACE) removeOldRings() } fun removeOldRings() { val db = databaseHelper.signalWritableDatabase db.delete(TABLE_NAME, "$DATE_RECEIVED < ?", SqlUtil.buildArgs(System.currentTimeMillis() - VALID_RING_DURATION)) } } private fun CallManager.RingUpdate.toCode(): Int { return when (this) { CallManager.RingUpdate.REQUESTED -> 0 CallManager.RingUpdate.EXPIRED_REQUEST -> 1 CallManager.RingUpdate.ACCEPTED_ON_ANOTHER_DEVICE -> 2 CallManager.RingUpdate.DECLINED_ON_ANOTHER_DEVICE -> 3 CallManager.RingUpdate.BUSY_LOCALLY -> 4 CallManager.RingUpdate.BUSY_ON_ANOTHER_DEVICE -> 5 CallManager.RingUpdate.CANCELLED_BY_RINGER -> 6 } }
gpl-3.0
cff2fd2f2ae5d7cc18f2ee91aba42bb2
29.702128
116
0.70201
3.964286
false
false
false
false
ManojMadanmohan/dlt
app/src/main/java/com/manoj/dlt/features/ProfileFeature.kt
1
1320
package com.manoj.dlt.features import android.content.Context import android.util.Log import com.google.firebase.database.DatabaseReference import com.manoj.dlt.Constants import com.manoj.dlt.interfaces.IProfileFeature import com.manoj.dlt.utils.SingletonHolder import com.manoj.dlt.utils.Utilities import java.util.* class ProfileFeature private constructor(context: Context): IProfileFeature { private val _fileSystem: FileSystem private var _userId: String? init { _fileSystem = Utilities.getOneTimeStore(context) _userId = _fileSystem.read(Constants.USER_ID_KEY) if(_userId == null) { _userId = generateUserId() _fileSystem.write(Constants.USER_ID_KEY, _userId!!) } Log.d("profile", "user id = " + _userId) } companion object: SingletonHolder<ProfileFeature, Context>(::ProfileFeature) { } override fun getUserId(): String { return _userId!! } override fun getCurrentUserFirebaseBaseRef(): DatabaseReference { val baseUserRef = Constants.getFirebaseUserRef() return baseUserRef.child(_userId) } private fun generateUserId(): String { //TODO: better implementation val rand = UUID.randomUUID().toString() return rand.substring(0, 5) } }
mit
cc4d11071e9f36336edca8bd8aff54b9
25.4
82
0.681061
4.177215
false
false
false
false
evanchooly/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/internal/JvmCompilerPlugin.kt
1
16166
package com.beust.kobalt.internal import com.beust.kobalt.IncrementalTaskInfo import com.beust.kobalt.KobaltException import com.beust.kobalt.TaskResult import com.beust.kobalt.TestConfig import com.beust.kobalt.api.* import com.beust.kobalt.api.annotation.ExportedProjectProperty import com.beust.kobalt.api.annotation.IncrementalTask import com.beust.kobalt.api.annotation.Task import com.beust.kobalt.maven.DependencyManager import com.beust.kobalt.maven.LocalRepo import com.beust.kobalt.maven.Md5 import com.beust.kobalt.misc.KFiles import com.beust.kobalt.misc.KobaltExecutors import com.beust.kobalt.misc.log import com.beust.kobalt.misc.warn import java.io.File import java.util.* import javax.inject.Inject import javax.inject.Singleton /** * This plug-in takes care of compilation: it declares a bunch of tasks ("compile", "compileTest") and * and picks up all the compiler contributors in order to run them whenever a compilation is requested. */ @Singleton open class JvmCompilerPlugin @Inject constructor( open val localRepo: LocalRepo, open val files: KFiles, open val dependencyManager: DependencyManager, open val executors: KobaltExecutors, open val taskContributor : TaskContributor) : BasePlugin(), ISourceDirectoryContributor, IProjectContributor, ITaskContributor by taskContributor { companion object { val PLUGIN_NAME = "JvmCompiler" @ExportedProjectProperty(doc = "Projects this project depends on", type = "List<ProjectDescription>") const val DEPENDENT_PROJECTS = "dependentProjects" @ExportedProjectProperty(doc = "Compiler args", type = "List<String>") const val COMPILER_ARGS = "compilerArgs" const val TASK_COMPILE = "compile" const val TASK_COMPILE_TEST = "compileTest" const val TASK_CLEAN = "clean" const val TASK_TEST = "test" const val DOCS_DIRECTORY = "docs/javadoc" const val GROUP_TEST = "test" const val GROUP_BUILD = "build" const val GROUP_DOCUMENTATION = "documentation" } override val name: String = PLUGIN_NAME override fun accept(project: Project) = true /** * Log with a project. */ protected fun lp(project: Project, s: String) { log(2, "${project.name}: $s") } override fun apply(project: Project, context: KobaltContext) { super.apply(project, context) // cleanUpActors() taskContributor.addIncrementalVariantTasks(this, project, context, "compile", GROUP_BUILD, runTask = { taskCompile(project) }) // // Add each test config as a test task. If none was specified, create a default one so that // users don't have to specify a test{} // if (project.testConfigs.isEmpty()) { project.testConfigs.add(TestConfig(project)) } project.testConfigs.forEach { config -> val taskName = if (config.name.isEmpty()) TASK_TEST else TASK_TEST + config.name taskManager.addTask(this, project, taskName, group = GROUP_TEST, dependsOn = listOf(JvmCompilerPlugin.TASK_COMPILE, JvmCompilerPlugin.TASK_COMPILE_TEST), task = { taskTest(project, config.name)} ) } } private fun taskTest(project: Project, configName: String): TaskResult { lp(project, "Running tests: $configName") val runContributor = ActorUtils.selectAffinityActor(project, context, context.pluginInfo.testRunnerContributors) if (runContributor != null && runContributor.affinity(project, context) > 0) { return runContributor.run(project, context, configName, dependencyManager.testDependencies(project, context)) } else { log(1, "Couldn't find a test runner for project ${project.name}, did you specify a dependenciesTest{}?") return TaskResult() } } @Task(name = TASK_CLEAN, description = "Clean the project", group = GROUP_BUILD) fun taskClean(project: Project): TaskResult { java.io.File(project.directory, project.buildDirectory).let { dir -> if (!dir.deleteRecursively()) { warn("Couldn't delete $dir") } } return TaskResult() } /** * Copy the resources from a source directory to the build one */ protected fun copyResources(project: Project, sourceSet: SourceSet) { var outputDir = sourceSet.outputDir val variantSourceDirs = context.variant.resourceDirectories(project, sourceSet) if (variantSourceDirs.size > 0) { lp(project, "Copying $sourceSet resources") val absOutputDir = File(KFiles.joinDir(project.directory, project.buildDirectory, outputDir)) variantSourceDirs.map { File(project.directory, it.path) }.filter { it.exists() }.forEach { log(2, "Copying from $it to $absOutputDir") KFiles.copyRecursively(it, absOutputDir, deleteFirst = false) } } else { lp(project, "No resources to copy for $sourceSet") } } protected fun compilerArgsFor(project: Project): List<String> { val result = project.projectProperties.get(COMPILER_ARGS) if (result != null) { @Suppress("UNCHECKED_CAST") return result as List<String> } else { return emptyList() } } @IncrementalTask(name = TASK_COMPILE_TEST, description = "Compile the tests", group = GROUP_BUILD, dependsOn = arrayOf(TASK_COMPILE)) fun taskCompileTest(project: Project): IncrementalTaskInfo { return IncrementalTaskInfo( inputChecksum = { Md5.toMd5Directories(context.testSourceDirectories(project).map { File(project.directory, it.path)}) }, outputChecksum = { Md5.toMd5Directories(listOf(KFiles.makeOutputTestDir(project))) }, task = { project -> doTaskCompileTest(project)}, context = context ) } private fun sourceDirectories(project: Project, context: KobaltContext) = context.variant.sourceDirectories(project, context, SourceSet.of(isTest = false)) @IncrementalTask(name = JvmCompilerPlugin.TASK_COMPILE, description = "Compile the project", group = GROUP_BUILD, runAfter = arrayOf(TASK_CLEAN)) fun taskCompile(project: Project): IncrementalTaskInfo { return IncrementalTaskInfo( inputChecksum = { Md5.toMd5Directories(context.sourceDirectories(project).map { File(project.directory, it.path) }) }, outputChecksum = { Md5.toMd5Directories(listOf(File(project.directory, project.classesDir(context)))) }, task = { project -> doTaskCompile(project) }, context = context ) } private fun doTaskCompile(project: Project) = doTaskCompile(project, isTest = false) private fun doTaskCompileTest(project: Project) = doTaskCompile(project, isTest = true) private fun doTaskCompile(project: Project, isTest: Boolean): TaskResult { val results = arrayListOf<TaskResult>() val compilerContributors = context.pluginInfo.compilerContributors ActorUtils.selectAffinityActors(project, context, context.pluginInfo.compilerContributors) var failedResult: TaskResult? = null if (compilerContributors.isEmpty()) { throw KobaltException("Couldn't find any compiler for project ${project.name}") } else { val allCompilers = compilerContributors.flatMap { it.compilersFor(project, context)}.sorted() allCompilers.forEach { compiler -> val contributedSourceDirs = if (isTest) { context.testSourceDirectories(project) } else { context.sourceDirectories(project) } val sourceFiles = KFiles.findSourceFiles(project.directory, contributedSourceDirs.map { it.path }, compiler.sourceSuffixes) if (sourceFiles.size > 0) { // TODO: createCompilerActionInfo recalculates the source files, only compute them // once and pass them val info = createCompilerActionInfo(project, context, compiler, isTest, sourceDirectories(project, context), sourceSuffixes = compiler.sourceSuffixes) val thisResult = compiler.compile(project, context, info) results.add(thisResult) if (!thisResult.success && failedResult == null) { failedResult = thisResult } } else { log(2, "Compiler $compiler not running on ${project.name} since no source files were found") } } return if (failedResult != null) failedResult!! else if (results.size > 0) results[0] else TaskResult(true) } } val allProjects = arrayListOf<ProjectDescription>() // IProjectContributor override fun projects() = allProjects override fun cleanUpActors() { allProjects.clear() } fun addDependentProjects(project: Project, dependents: List<Project>) { project.projectExtra.dependsOn.addAll(dependents) with(ProjectDescription(project, dependents)) { allProjects.add(this) } project.projectProperties.put(DEPENDENT_PROJECTS, allProjects) } @Task(name = "doc", description = "Generate the documentation for the project", group = GROUP_DOCUMENTATION) fun taskJavadoc(project: Project): TaskResult { val docGenerator = ActorUtils.selectAffinityActor(project, context, context.pluginInfo.docContributors) if (docGenerator != null) { val contributors = ActorUtils.selectAffinityActors(project, context, context.pluginInfo.compilerContributors) var result: TaskResult? = null contributors.forEach { it.compilersFor(project, context).forEach { compiler -> result = docGenerator.generateDoc(project, context, createCompilerActionInfo(project, context, compiler, isTest = false, sourceDirectories = sourceDirectories(project, context), sourceSuffixes = compiler.sourceSuffixes)) } } return result!! } else { warn("Couldn't find any doc contributor for project ${project.name}") return TaskResult() } } /** * Naïve implementation: just exclude all dependencies that start with one of the excluded dependencies. * Should probably make exclusion more generic (full on string) or allow exclusion to be specified * formally by groupId or artifactId. */ private fun isDependencyExcluded(id: IClasspathDependency, excluded: List<IClasspathDependency>) = excluded.any { id.id.startsWith(it.id) } /** * Create a CompilerActionInfo (all the information that a compiler needs to know) for the given parameters. * Runs all the contributors and interceptors relevant to that task. */ protected fun createCompilerActionInfo(project: Project, context: KobaltContext, compiler: ICompiler, isTest: Boolean, sourceDirectories: List<File>, sourceSuffixes: List<String>): CompilerActionInfo { copyResources(project, SourceSet.of(isTest)) val fullClasspath = if (isTest) dependencyManager.testDependencies(project, context) else dependencyManager.dependencies(project, context) // Remove all the excluded dependencies from the classpath val classpath = fullClasspath.filter { ! isDependencyExcluded(it, project.excludedDependencies) } val buildDirectory = if (isTest) File(project.buildDirectory, KFiles.TEST_CLASSES_DIR) else File(project.classesDir(context)) buildDirectory.mkdirs() val initialSourceDirectories = ArrayList<File>(sourceDirectories) // Source directories from the contributors val contributedSourceDirs = if (isTest) { context.pluginInfo.testSourceDirContributors.flatMap { it.testSourceDirectoriesFor(project, context) } } else { context.pluginInfo.sourceDirContributors.flatMap { it.sourceDirectoriesFor(project, context) } } initialSourceDirectories.addAll(contributedSourceDirs) // Transform them with the interceptors, if any val allSourceDirectories = if (isTest) { initialSourceDirectories } else { context.pluginInfo.sourceDirectoriesInterceptors.fold(initialSourceDirectories.toList(), { sd, interceptor -> interceptor.intercept(project, context, sd) }) }.filter { File(project.directory, it.path).exists() }.filter { ! KFiles.isResource(it.path) }.distinct() // Now that we have all the source directories, find all the source files in them val projectDirectory = File(project.directory) val sourceFiles = if (compiler.canCompileDirectories) { allSourceDirectories.map { File(projectDirectory, it.path).path } } else { files.findRecursively(projectDirectory, allSourceDirectories, { file -> sourceSuffixes.any { file.endsWith(it) } }) .map { File(projectDirectory, it).path } } // Special treatment if we are compiling Kotlin files and the project also has a java source // directory. In this case, also pass that java source directory to the Kotlin compiler as is // so that it can parse its symbols // Note: this should actually be queried on the compiler object so that this method, which // is compiler agnostic, doesn't hardcode Kotlin specific stuff val extraSourceFiles = arrayListOf<String>() if (sourceSuffixes.any { it.contains("kt")}) { project.sourceDirectories.forEach { val javaDir = KFiles.joinDir(project.directory, it) if (File(javaDir).exists()) { if (it.contains("java")) { extraSourceFiles.add(javaDir) // Add all the source directories contributed as potential Java directories too // (except our own) context.pluginInfo.sourceDirContributors.filter { it != this }.forEach { extraSourceFiles.addAll(it.sourceDirectoriesFor(project, context).map { it.path }) } } } } } val allSources = (sourceFiles + extraSourceFiles).distinct().filter { File(it).exists() } // Finally, alter the info with the compiler interceptors before returning it val initialActionInfo = CompilerActionInfo(projectDirectory.path, classpath, allSources, sourceSuffixes, buildDirectory, emptyList() /* the flags will be provided by flag contributors */) val result = context.pluginInfo.compilerInterceptors.fold(initialActionInfo, { ai, interceptor -> interceptor.intercept(project, context, ai) }) return result } // ISourceDirectoryContributor override fun sourceDirectoriesFor(project: Project, context: KobaltContext) = if (accept(project)) { sourceDirectories(project, context) } else { arrayListOf() } open val compiler: ICompilerContributor? = null }
apache-2.0
335347239fc7e83adda294ec0c9270c8
42.689189
118
0.629508
5.010849
false
true
false
false
ktorio/ktor
ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyApplicationCall.kt
1
2858
/* * 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.server.netty import io.ktor.server.application.* import io.ktor.server.engine.* import io.ktor.util.* import io.netty.buffer.* import io.netty.channel.* import io.netty.util.* import kotlinx.atomicfu.* import kotlinx.coroutines.* public abstract class NettyApplicationCall( application: Application, public val context: ChannelHandlerContext, private val requestMessage: Any, ) : BaseApplicationCall(application) { public abstract override val request: NettyApplicationRequest public abstract override val response: NettyApplicationResponse internal lateinit var previousCallFinished: ChannelPromise /** * Set success when the response is ready to read or failed if a response is cancelled */ internal lateinit var finishedEvent: ChannelPromise public val responseWriteJob: Job = Job() private val messageReleased = atomic(false) internal var isByteBufferContent = false /** * Returns http content object with [buf] content if [isByteBufferContent] is false, * [buf] otherwise. */ internal open fun prepareMessage(buf: ByteBuf, isLastContent: Boolean): Any { return buf } /** * Returns the 'end of content' http marker if [isByteBufferContent] is false, * null otherwise */ internal open fun prepareEndOfStreamMessage(lastTransformed: Boolean): Any? { return null } /** * Add [MessageToByteEncoder] to the channel handler pipeline if http upgrade is supported, * [IllegalStateException] otherwise */ internal open fun upgrade(dst: ChannelHandlerContext) { throw IllegalStateException("Already upgraded") } internal abstract fun isContextCloseRequired(): Boolean internal suspend fun finish() { try { response.ensureResponseSent() } catch (cause: Throwable) { finishedEvent.setFailure(cause) finishComplete() throw cause } if (responseWriteJob.isCompleted) { finishComplete() return } return finishSuspend() } private suspend fun finishSuspend() { try { responseWriteJob.join() } finally { finishComplete() } } private fun finishComplete() { responseWriteJob.cancel() request.close() releaseRequestMessage() } internal fun dispose() { response.close() request.close() releaseRequestMessage() } private fun releaseRequestMessage() { if (messageReleased.compareAndSet(expect = false, update = true)) { ReferenceCountUtil.release(requestMessage) } } }
apache-2.0
f8711d17a470008ff3f758d4ff1e22f8
25.962264
119
0.660602
4.936097
false
false
false
false
BlueHuskyStudios/BHToolbox
BHToolbox/src/org/bh/tools/util/MutableArrayPP.kt
1
13970
@file:Suppress("unused") package org.bh.tools.util import org.bh.tools.func.IndexedGenerator import org.bh.tools.util.ArrayPosition.END import org.bh.tools.util.ArrayPosition.START import org.bh.tools.util.SearchBehavior.* import java.util.* import java.util.function.Consumer import java.util.logging.Logger import java.util.stream.Stream /** * Would be called {@code MutableArray++} if {@code +} was a legal character for a class name. This is a mutable array * with many enhancements and conveniences. * * @param <T> The type of item to store * * @see ArrayPP * * @author Kyli of Blue Husky Programming * @version 2.3.0 <pre> * - 2016-10-01 (2.3.0) * ~ Ben added functional programming paradigms. * - 2016-04-06 (2.2.0) * ~ Kyli renamed {@code Array++} to {@code MutableArray++} * - 2015-08-30 (2.1.0) * ! Kyli simplified {@link #emptyArrayOfLength(int)} * ~ Kyli changed the log message when an object couldn't be destroyed with {@link #clear(boolean) clear(true)}. * + Kyli added {@link #remove(SearchBehavior,Object,ArrayPosition)}, * {@link #remove(int)}, and {@link #removeChunk(int,int)}. * - 2015-03-03 (2.0.0) . Kyli created this completely new ArrayPP, as a rewrite of {@link org.bh.tools.util.ArrayPP}. * </pre> * * @since 2015-03-03 */ class MutableArrayPP<T> : ArrayPP<T>, MutableIterable<T?> { constructor(vararg basis: T) : super(*basis) /** * Creates a new Array++ with the items from the given [Iterable]. * * @param basis the [Iterable] holding the items to put in this Array++ */ constructor(basis: Iterable<T>) { basis.forEach(Consumer<T> { this.append(it) }) } /** * Creates a new, empty array++ of the given size. * * @param initSize The size of the new, empty array * * @param emptySample `optional` - An empty array to use to guarantee the new, empty array++ is of the right type. * If this is not empty, its contents will be at the beginning of the new array++. */ constructor(initSize: Int, vararg emptySample: T) : super(initSize, *emptySample) /** * Creates a new, filled, mutable array++ of the given size. * * @param numberOfElements The size of the new, empty, immutable array++ * * @param generator The generator which will be used to fill this array with its contents * * @param emptySample `optional` - An non-null empty array to use to guarantee the new, empty, immutable * array++ is of the right type. If this is not empty, its contents will be at the * beginning of the new, immutable array++. */ constructor(numberOfElements: Int, generator: IndexedGenerator<T>, vararg emptySample: T) : super(numberOfElements, generator, *emptySample) /** * Adds all the given values to the end of this array++ * * @param newValues The new values to be added * * @return `this`, with the added values */ fun add(vararg newValues: T): MutableArrayPP<T> { return add(END, *newValues) } fun add(position: ArrayPosition, vararg newVals: T): MutableArrayPP<T> { when (position) { END -> return append(*newVals) START -> return prepend(*newVals) } } /** * Removes all objects from the array, with an option to destroy them as they are removed. Destruction is calling * their [.finalize] method. * * @param destructive If `true`, attempts to call [Object.finalize] on each object in this array. * If any one fails, a message is logged and that one is skipped. Either way, the array is * emptied at the end. * * * @return `this` */ @Suppress("UNCHECKED_CAST") // for some reason this complains. Seems like a compiler bug. fun clear(destructive: Boolean): MutableArrayPP<T> { if (destructive) { (array.filter { it is Finalizable } as List<Finalizable>).forEach { it.finalize() } } array = Arrays.copyOf(array, 0) return this } /** * Removes all objects from the array. * @return this */ fun clear(): MutableArrayPP<T> { return clear(false) } fun increaseSize(thisManyMoreSlots: Int): MutableArrayPP<T> { System.arraycopy(array, 0, array, 0, array.size + thisManyMoreSlots) return this } /** * Sets the value at slot `index` to be `newVal` * @param index The index of the slot to change * * * @param newVal The new value to put into the slot * * * @param increaseOK Indicates whether it's OK to increase the size of the array to accommodate the new value. If * * `false`, a [ArrayIndexOutOfBoundsException] may be thrown by passing an index that * * is too high. * * * * * @return `this` * * * * * @throws ArrayIndexOutOfBoundsException if `increaseOK` is `false` and `index` is greater than * * [length()][.length] */ @JvmOverloads fun set(index: Int, newVal: T, increaseOK: Boolean = false): MutableArrayPP<T> { if (increaseOK) { if (index > this.length()) { increaseSize(this.length() - index + 1) } } array[index] = newVal return this } /** * Sets the values at slots `fromIndex` through `newValues.length - fromIndex` to the values in * `newValues` * * @param fromIndex The index of the slot to change * @param newValues The new values to put into the slot * * @return `this` */ @Deprecated("untested!\n ") fun setAll(fromIndex: Int, newValues: Array<T>): MutableArrayPP<T> { System.arraycopy( newValues, 0, array, fromIndex, this.length() - fromIndex) return this } /** * Appends the given values to the end of this array. * * @param newValues the new values to append * * @return `this` */ @SuppressWarnings("unchecked") fun prepend(vararg newValues: T): MutableArrayPP<T> { var newArray: Array<T?> = newValues as Array<T?> newArray += array array = newArray return this } /** * Remove all instances of the given value from this array++. * * @param val The value to search for and remove * * @return `this` */ fun removeAll(value: T?): MutableArrayPP<T> { return remove(ALL, value, START) } /** * Removes the given item from the array, using the given behaviors. * * @param behavior The behavior by which to search * * * If [ANY][ArrayPP.SearchBehavior.ANY], removes the first found matching object at an index close * to `near`. If none is found, nothing is changed. * * If [ALL][ArrayPP.SearchBehavior.ALL], removes each and every found matching object. If none is * found, nothing is changed. * * If [SOLELY][ArrayPP.SearchBehavior.SOLELY], first determines if the array consists solely of * matching objects. If it does, [.clear] is called. * * @param value The value to remove * @param near Used if `behavior` is [ANY][ArrayPP.SearchBehavior.ANY]. * * @return `this` */ fun remove(behavior: SearchBehavior, value: T?, near: ArrayPosition): MutableArrayPP<T> { when (behavior) { ANY -> { val index = indexOf(near, value) if (index >= 0) { remove(index) } } ALL -> for (i in array.indices) { if (value === array[i] || value == array[i]) { remove(i) } } SOLELY -> if (contains(SOLELY, value)) { clear() } } return this } /** * Removes the item at index `index`. * * @param index The index of the item to remove * * @return `this` */ fun remove(index: Int): MutableArrayPP<T> { return removeChunk(index, index) } /** * Removes all items from `startIndex`, inclusive, to `endIndex`, inclusive. * * @param startIndex The first index whose item is to be removed * @param endIndex The last index whose item is to be removed * * @return this */ @SuppressWarnings("AssignmentToMethodParameter") fun removeChunk(startIndex: Int, endIndex: Int): MutableArrayPP<T> { var adjustedStartIndex = startIndex var adjustedEndIndex = endIndex if (adjustedStartIndex > adjustedEndIndex) { val oldStart = adjustedStartIndex adjustedStartIndex = adjustedEndIndex adjustedEndIndex = oldStart } System.arraycopy(array, adjustedStartIndex, // start writing at startIndex array, adjustedEndIndex + 1, // start writing with the object after endIndex array.size - (adjustedEndIndex - adjustedStartIndex + 1)) // shorten the array appropriately return this } /** * Remove all null values from this array++. * * @return `this` */ fun removeNulls(): MutableArrayPP<T> { return removeAll(null) } /** * @return A stream of all values in this array, which can be traversed asynchronously */ fun parallelStream(): Stream<T> { return stream().parallel() } /** * Appends the given values to the end of this array. * * @param newVals the new values to append * * @return `this` */ @SuppressWarnings("unchecked") fun append(vararg newVals: T): MutableArrayPP<T> { var length = length() var insertPoint = length var currentIndex = 0 length += newVals.size array = java.util.Arrays.copyOf(array, length) while (insertPoint < length) { array[insertPoint] = newVals[currentIndex] insertPoint++ currentIndex++ } return this } /** * Appends the values in the given Iterable to the end of this array. **The given [Iterable] * *must* be finite!** * * @param vals the values to be appended, as represented by an `Iterable` * * @return the resulting array. */ fun addAll(vals: Iterable<T>): MutableArrayPP<T> { val app = MutableArrayPP(vals) val INIT_LENGTH = length() val split = vals.spliterator() var count = split.exactSizeIfKnown if (count < 0) { // if exact size isn't known count = split.estimateSize() } if (count < 0 || count == java.lang.Long.MAX_VALUE) { // if size is still unknown split.forEachRemaining { item -> count++ } } array = Arrays.copyOf(array, INIT_LENGTH + count.toInt()) var insertPoint = INIT_LENGTH split.forEachRemaining { array[insertPoint++] = it } return this } fun addAll(newVals: Array<T>): MutableArrayPP<T> { var length = length() var insertPoint = length var currentIndex = 0 length += newVals.size array = java.util.Arrays.copyOf(array, length) while (insertPoint < length) { array[insertPoint] = newVals[currentIndex] insertPoint++ currentIndex++ } return this } //</editor-fold> companion object { val serialVersionUID = 0x30000000L //<editor-fold defaultstate="collapsed" desc="Wrapping & Unwrapping"> fun wrap(unwrapped: ByteArray?): ArrayPP<Byte>? { if (unwrapped == null) { return null } if (unwrapped.size == 0) { return ArrayPP() } return ArrayPP(unwrapped.size, { idx -> unwrapped[idx] }) } fun unwrap(wrapped: ArrayPP<Byte>?): ByteArray? { if (wrapped == null) { return null } if (wrapped.size == 0) { return ByteArray(0) } val ret = ByteArray(wrapped.size) for (i in ret.indices) { ret[i] = wrapped[i]!! // We know all elements in this are non-optional } return ret } fun wrap(unwrapped: IntArray?): Array<Int?>? { if (unwrapped == null) { return null } if (unwrapped.size == 0) { return arrayOfNulls(0) } val ret = arrayOfNulls<Int>(unwrapped.size) for (i in ret.indices) { ret[i] = unwrapped[i] } return ret } fun unwrap(wrapped: Array<Int>?): IntArray? { if (wrapped == null) { return null } if (wrapped.size == 0) { return IntArray(0) } val ret = IntArray(wrapped.size) for (i in ret.indices) { ret[i] = wrapped[i] } return ret } } override fun iterator(): MutableIterator<T?> { return object : MutableIterator<T?> { private var pos = 0 override fun hasNext(): Boolean { return pos < length() } @Throws(ArrayIndexOutOfBoundsException::class) override fun next(): T? { return get(++pos - 1) } override fun remove() { Logger.getLogger(javaClass.name).severe("remove() called on immutable array") } } } }
gpl-3.0
da0b69b1ae816aab3d565287d35fb99d
30.822323
119
0.561203
4.232051
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/openal/src/templates/kotlin/openal/templates/ALC10.kt
4
8645
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package openal.templates import org.lwjgl.generator.* import openal.* val ALC10 = "ALC10".nativeClassALC("ALC10") { documentation = "Native bindings to ALC 1.0 functionality." IntConstant( "General tokens.", "INVALID"..0xFFFFFFFF.i, "FALSE"..0x0, "TRUE"..0x1 ) val ContextAttributes = IntConstant( "Context creation attributes.", "FREQUENCY"..0x1007, "REFRESH"..0x1008, "SYNC"..0x1009 ).javaDocLinks + " #MONO_SOURCES #STEREO_SOURCES" IntConstant( "Error conditions.", "NO_ERROR"..0x0, "INVALID_DEVICE"..0xA001, "INVALID_CONTEXT"..0xA002, "INVALID_ENUM"..0xA003, "INVALID_VALUE"..0xA004, "OUT_OF_MEMORY"..0xA005 ) val StringQueries = IntConstant( "String queries.", "DEFAULT_DEVICE_SPECIFIER"..0x1004, "DEVICE_SPECIFIER"..0x1005, "EXTENSIONS"..0x1006 ).javaDocLinks + " #CAPTURE_DEFAULT_DEVICE_SPECIFIER #CAPTURE_DEVICE_SPECIFIER" val IntegerQueries = IntConstant( "Integer queries.", "MAJOR_VERSION"..0x1000, "MINOR_VERSION"..0x1001, "ATTRIBUTES_SIZE"..0x1002, "ALL_ATTRIBUTES"..0x1003 ).javaDocLinks + " #CAPTURE_SAMPLES" ALCdevice.p( "OpenDevice", """ Allows the application to connect to a device. If the function returns #NULL, then no sound driver/device has been found. The argument is a null terminated string that requests a certain device or device configuration. If #NULL is specified, the implementation will provide an implementation specific default. """, nullable..ALCcharUTF8.const.p("deviceSpecifier", "the requested device or device configuration") ) ALCboolean( "CloseDevice", """ Allows the application to disconnect from a device. The return code will be ALC_TRUE or ALC_FALSE, indicating success or failure. Failure will occur if all the device's contexts and buffers have not been destroyed. Once closed, the {@code deviceHandle} is invalid. """, ALCdevice.const.p("deviceHandle", "the device to close") ) ALCcontext.p( "CreateContext", "Creates an AL context.", ALCdevice.const.p("deviceHandle", "a valid device"), nullable..NullTerminated..ALCint.const.p( "attrList", "null or a zero terminated list of integer pairs composed of valid ALC attribute tokens and requested values", ContextAttributes ) ) ALCboolean( "MakeContextCurrent", """ Makes a context current with respect to OpenAL operation. The context parameter can be #NULL or a valid context pointer. Using #NULL results in no context being current, which is useful when shutting OpenAL down. The operation will apply to the device that the context was created for. For each OS process (usually this means for each application), only one context can be current at any given time. All AL commands apply to the current context. Commands that affect objects shared among contexts (e.g. buffers) have side effects on other contexts. """, nullable..ALCcontext.p("context", "the context to make current") ) ALCvoid( "ProcessContext", """ The current context is the only context accessible to state changes by AL commands (aside from state changes affecting shared objects). However, multiple contexts can be processed at the same time. To indicate that a context should be processed (i.e. that internal execution state such as the offset increments are to be performed), the application uses {@code alcProcessContext}. Repeated calls to alcProcessContext are legal, and do not affect a context that is already marked as processing. The default state of a context created by alcCreateContext is that it is processing. """, ALCcontext.p("context", "the context to mark for processing") ) ALCvoid( "SuspendContext", """ The application can suspend any context from processing (including the current one). To indicate that a context should be suspended from processing (i.e. that internal execution state such as offset increments are not to be changed), the application uses {@code alcSuspendContext}. Repeated calls to alcSuspendContext are legal, and do not affect a context that is already marked as suspended. """, ALCcontext.p("context", "the context to mark as suspended") ) ALCvoid( "DestroyContext", """ Destroys a context. The correct way to destroy a context is to first release it using alcMakeCurrent with a #NULL context. Applications should not attempt to destroy a current context – doing so will not work and will result in an ALC_INVALID_OPERATION error. All sources within a context will automatically be deleted during context destruction. """, ALCcontext.p("context", "the context to destroy") ) ALCcontext.p( "GetCurrentContext", "Queries for, and obtains a handle to, the current context for the application. If there is no current context, #NULL is returned.", void() ) ALCdevice.p( "GetContextsDevice", "Queries for, and obtains a handle to, the device of a given context.", ALCcontext.p("context", "the context to query") ) ALCboolean( "IsExtensionPresent", """ Verifies that a given extension is available for the current context and the device it is associated with. Invalid and unsupported string tokens return ALC_FALSE. A #NULL deviceHandle is acceptable. {@code extName} is not case sensitive – the implementation will convert the name to all upper-case internally (and will express extension names in upper-case). """, nullable..ALCdevice.const.p("deviceHandle", "the device to query"), ALCcharASCII.const.p("extName", "the extension name") ) opaque_p( "GetProcAddress", """ Retrieves extension entry points. The application is expected to verify the applicability of an extension or core function entry point before requesting it by name, by use of #IsExtensionPresent(). Entry points can be device specific, but are not context specific. Using a #NULL device handle does not guarantee that the entry point is returned, even if available for one of the available devices. """, nullable..ALCdevice.const.p("deviceHandle", "the device to query"), ALcharASCII.const.p("funcName", "the function name") ) ALCenum( "GetEnumValue", """ Returns extension enum values. Enumeration/token values are device independent, but tokens defined for extensions might not be present for a given device. Using a #NULL handle is legal, but only the tokens defined by the AL core are guaranteed. Availability of extension tokens depends on the ALC extension. """, nullable..ALCdevice.const.p("deviceHandle", "the device to query"), ALCcharASCII.const.p("enumName", "the enum name") ) ALCenum( "GetError", """ Queries ALC errors. ALC uses the same conventions and mechanisms as AL for error handling. In particular, ALC does not use conventions derived from X11 (GLX) or Windows (WGL). Error conditions are specific to the device, and (like AL) a call to alcGetError resets the error state. """, nullable..ALCdevice.p("deviceHandle", "the device to query") ) ALCcharUTF8.const.p( "GetString", """ Obtains string value(s) from ALC. <b>LWJGL note</b>: Use ALUtil#getStringList() for those tokens that return multiple values. """, nullable..ALCdevice.p("deviceHandle", "the device to query"), ALCenum("token", "the information to query", StringQueries) ) ALCvoid( "GetIntegerv", "Obtains integer value(s) from ALC.", nullable..ALCdevice.p("deviceHandle", "the device to query"), ALCenum("token", "the information to query", IntegerQueries), AutoSize("dest")..ALCsizei("size", "the size of the {@code dest} buffer"), ReturnParam..ALCint.p("dest", "the destination buffer") ) }
bsd-3-clause
173655f6898bb311c5159394b6a9df5d
35.310924
162
0.654554
4.540725
false
false
false
false
drakelord/wire
wire-compiler/src/main/java/com/squareup/wire/schema/Target.kt
1
5501
/* * Copyright 2018 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.schema import com.squareup.javapoet.JavaFile import com.squareup.kotlinpoet.FileSpec import com.squareup.wire.WireCompiler import com.squareup.wire.WireLogger import com.squareup.wire.java.JavaGenerator import com.squareup.wire.java.ProfileLoader import com.squareup.wire.kotlin.KotlinGenerator import java.io.IOException import java.nio.file.FileSystem sealed class Target { /** * Proto types to generate sources for with this target. Types included here will be generated * for this target and not for subsequent targets in the task. * * This list should contain package names (suffixed with `.*`) and type names only. It should * not contain member names. */ abstract val elements: List<String> internal abstract fun newHandler(schema: Schema, fs: FileSystem, logger: WireLogger): TypeHandler /** Generate `.java` sources. */ data class JavaTarget( override val elements: List<String> = listOf("*"), val outDirectory: String, /** True for emitted types to implement `android.os.Parcelable`. */ val android: Boolean = false, /** True to enable the `androidx.annotation.Nullable` annotation where applicable. */ val androidAnnotations: Boolean = false, /** * True to emit code that uses reflection for reading, writing, and toString methods which are * normally implemented with generated code. */ val compact: Boolean = false ): Target() { override fun newHandler(schema: Schema, fs: FileSystem, logger: WireLogger) : TypeHandler { val profileName = if (android) "android" else "java" val profile = ProfileLoader(fs, profileName) .schema(schema) .load() val javaGenerator = JavaGenerator.get(schema) .withProfile(profile) .withAndroid(android) .withAndroidAnnotations(androidAnnotations) .withCompact(compact) return object : TypeHandler { override fun handle(type: Type) { val typeSpec = javaGenerator.generateType(type) val javaTypeName = javaGenerator.generatedTypeName(type) val javaFile = JavaFile.builder(javaTypeName.packageName(), typeSpec) .addFileComment("\$L", WireCompiler.CODE_GENERATED_BY_WIRE) .apply { val location = type.location() if (location != null) { addFileComment("\nSource file: \$L", location.withPathOnly()) } }.build() val path = fs.getPath(outDirectory) logger.artifact(path, javaFile) try { javaFile.writeTo(path) } catch (e: IOException) { throw IOException("Error emitting ${javaFile.packageName}.${javaFile.typeSpec.name} " + "to $outDirectory", e) } } } } } /** Generate `.kt` sources. */ data class KotlinTarget( override val elements: List<String> = listOf("*"), val outDirectory: String, /** True for emitted types to implement `android.os.Parcelable`. */ val android: Boolean = false, /** True for emitted types to implement APIs for easier migration from the Java target. */ val javaInterop: Boolean = false ): Target() { override fun newHandler(schema: Schema, fs: FileSystem, logger: WireLogger): TypeHandler { val kotlinGenerator = KotlinGenerator(schema, android, javaInterop) return object : TypeHandler { override fun handle(type: Type) { val typeSpec = kotlinGenerator.generateType(type) val className = kotlinGenerator.generatedTypeName(type) val kotlinFile = FileSpec.builder(className.packageName, typeSpec.name!!) .addComment(WireCompiler.CODE_GENERATED_BY_WIRE) .apply { val location = type.location() if (location != null) { addComment("\nSource file: %L", location.withPathOnly()) } } .addType(typeSpec) .build() val path = fs.getPath(outDirectory) logger.artifact(path, kotlinFile) try { kotlinFile.writeTo(path) } catch (e: IOException) { throw IOException("Error emitting " + "${kotlinFile.packageName}.${className.canonicalName} to $outDirectory", e) } } } } } /** Omit code generation for these sources. Use this for a dry-run. */ data class NullTarget( override val elements: List<String> = listOf("*") ): Target() { override fun newHandler(schema: Schema, fs: FileSystem, logger: WireLogger): TypeHandler { return object : TypeHandler { override fun handle(type: Type) { logger.artifactSkipped(type.type()) } } } } interface TypeHandler { fun handle(type: Type) } }
apache-2.0
df735de0af4ab0e93992e87097f07b6e
33.816456
99
0.641702
4.661864
false
false
false
false
meik99/CoffeeList
app/src/main/java/rynkbit/tk/coffeelist/db/facade/CustomerFacade.kt
1
3473
package rynkbit.tk.coffeelist.db.facade import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import io.reactivex.schedulers.Schedulers import rynkbit.tk.coffeelist.contract.entity.Customer import rynkbit.tk.coffeelist.contract.entity.InvoiceState import rynkbit.tk.coffeelist.db.entity.DatabaseCustomer class CustomerFacade : BaseFacade<DatabaseCustomer, Customer>() { fun findAll(): LiveData<List<Customer>> { return super.findAll(Customer::class.java) } fun insert(customer: Customer): LiveData<Long> { val liveData = MutableLiveData<Long>() appDatabase .customerDao() .insert(DatabaseCustomer( customer.id, customer.name )) .subscribeOn(Schedulers.newThread()) .map { liveData.postValue(it) } .subscribe() return liveData } fun update(customer: Customer): LiveData<Unit> { return super.update(DatabaseCustomer( customer.id, customer.name ), Customer::class.java) } fun getBalance(customer: Customer): LiveData<Double>{ val liveData = MutableLiveData<Double>() appDatabase .invoiceDao() .findByCustomer(customer.id) .subscribeOn(Schedulers.newThread()) .map {invoices -> var balance = 0.toDouble() liveData.postValue(balance) invoices.forEach { if(it.state == InvoiceState.OPEN) { it.itemId?.let { id -> appDatabase .itemDao() .findById(id) .subscribeOn(Schedulers.newThread()) .map {item -> balance += item.price liveData.postValue(balance) return@map item } .subscribe() } } } } .subscribe() return liveData } fun delete(customer: Customer): LiveData<Unit> { return super.delete(DatabaseCustomer( customer.id, customer.name ), Customer::class.java) } fun replaceAll(customers: List<Customer>): LiveData<Unit> { val mutableLiveData = MutableLiveData<Unit>() appDatabase .customerDao() .deleteAll() .subscribeOn(Schedulers.newThread()) .map { for(customer in customers){ appDatabase .customerDao() .insert(DatabaseCustomer( id = customer.id, name = customer.name )) .blockingGet() } mutableLiveData.postValue(Unit) } .subscribe() return mutableLiveData } }
mit
592d87d97da019ca547d569205d14612
32.403846
76
0.445724
6.372477
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnnecessaryVariableInspection.kt
1
6748
// 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.inspections import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggestionProvider import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNewDeclarationNameValidator import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.util.isMultiLine import org.jetbrains.kotlin.idea.refactoring.inline.KotlinInlinePropertyHandler import org.jetbrains.kotlin.idea.util.nameIdentifierTextRangeInThis import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespaceAndComments import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext.DECLARATION_TO_DESCRIPTOR import org.jetbrains.kotlin.resolve.BindingContext.REFERENCE_TARGET import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.addToStdlib.safeAs class UnnecessaryVariableInspection : AbstractApplicabilityBasedInspection<KtProperty>(KtProperty::class.java), CleanupLocalInspectionTool { override fun isApplicable(element: KtProperty) = statusFor(element) != null override fun inspectionHighlightRangeInElement(element: KtProperty) = element.nameIdentifierTextRangeInThis() override fun inspectionHighlightType(element: KtProperty): ProblemHighlightType { val hasMultiLineBlock = element.initializer?.hasMultiLineBlock() == true return if (hasMultiLineBlock) ProblemHighlightType.INFORMATION else ProblemHighlightType.GENERIC_ERROR_OR_WARNING } override fun inspectionText(element: KtProperty) = when (statusFor(element)) { Status.RETURN_ONLY -> KotlinBundle.message("variable.used.only.in.following.return.and.should.be.inlined") Status.EXACT_COPY -> KotlinBundle.message( "variable.is.same.as.0.and.should.be.inlined", (element.initializer as? KtNameReferenceExpression)?.getReferencedName().toString() ) else -> "" } override val defaultFixText get() = KotlinBundle.message("inline.variable") override val startFixInWriteAction = false override fun applyTo(element: KtProperty, project: Project, editor: Editor?) { KotlinInlinePropertyHandler(withPrompt = false).inlineElement(project, editor, element) } private fun LeafPsiElement.startsMultilineBlock(): Boolean = node.elementType == KtTokens.LBRACE && parent.safeAs<KtExpression>()?.isMultiLine() == true private fun KtExpression.hasMultiLineBlock(): Boolean = anyDescendantOfType<LeafPsiElement> { it.startsMultilineBlock() } companion object { private enum class Status { RETURN_ONLY, EXACT_COPY } private fun statusFor(property: KtProperty): Status? { if (property.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return null val enclosingElement = KtPsiUtil.getEnclosingElementForLocalDeclaration(property) ?: return null val initializer = property.initializer ?: return null fun isExactCopy(): Boolean { if (!property.isVar && initializer is KtNameReferenceExpression && property.typeReference == null) { val initializerDescriptor = initializer.resolveToCall(BodyResolveMode.FULL)?.resultingDescriptor as? VariableDescriptor ?: return false if (initializerDescriptor.isVar) return false if (initializerDescriptor.containingDeclaration !is FunctionDescriptor) return false if (initializerDescriptor.safeAs<LocalVariableDescriptor>()?.isDelegated == true) return false val copyName = initializerDescriptor.name.asString() if (ReferencesSearch.search(property, LocalSearchScope(enclosingElement)).findFirst() == null) return false val containingDeclaration = property.getStrictParentOfType<KtDeclaration>() if (containingDeclaration != null) { val validator = Fe10KotlinNewDeclarationNameValidator( container = containingDeclaration, anchor = property, target = KotlinNameSuggestionProvider.ValidatorTarget.VARIABLE, excludedDeclarations = listOfNotNull( DescriptorToSourceUtils.descriptorToDeclaration(initializerDescriptor) as? KtDeclaration ) ) if (!validator(copyName)) return false if (containingDeclaration is KtClassOrObject) { val enclosingBlock = enclosingElement as? KtBlockExpression val initializerDeclaration = DescriptorToSourceUtils.descriptorToDeclaration(initializerDescriptor) if (enclosingBlock?.statements?.none { it == initializerDeclaration } == true) return false } } return true } return false } fun isReturnOnly(): Boolean { val nextStatement = property.getNextSiblingIgnoringWhitespaceAndComments() as? KtReturnExpression ?: return false val returned = nextStatement.returnedExpression as? KtNameReferenceExpression ?: return false val context = nextStatement.analyze() return context[REFERENCE_TARGET, returned] == context[DECLARATION_TO_DESCRIPTOR, property] } return when { isExactCopy() -> Status.EXACT_COPY isReturnOnly() -> Status.RETURN_ONLY else -> null } } } }
apache-2.0
8597dc462fab2ef8211c7b3124604352
52.984
140
0.70495
5.752771
false
false
false
false
dahlstrom-g/intellij-community
platform/rd-platform-community/src/com/intellij/openapi/rd/util/RdCoroutinesUtil.kt
5
6148
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.rd.util import com.jetbrains.rd.framework.util.* import com.jetbrains.rd.util.lifetime.Lifetime import kotlinx.coroutines.* import org.jetbrains.concurrency.Promise import java.util.concurrent.CompletableFuture private val applicationThreadPool get() = RdCoroutineHost.applicationThreadPool private val processIODispatcher get() = RdCoroutineHost.processIODispatcher private val nonUrgentDispatcher get() = RdCoroutineHost.nonUrgentDispatcher private val uiDispatcher get() = RdCoroutineHost.instance.uiDispatcher private val uiDispatcherAnyModality get() = RdCoroutineHost.instance.uiDispatcherAnyModality fun Lifetime.launchOnUi( start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> Unit ): Job = launch(uiDispatcher, start, action) fun Lifetime.launchOnUiAnyModality( start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> Unit ): Job = launch(uiDispatcherAnyModality, start, action) fun Lifetime.launchIOBackground( start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> Unit ): Job = launch(processIODispatcher, start, action) fun Lifetime.launchLongBackground( start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> Unit ) = launch(applicationThreadPool, start, action) fun Lifetime.launchNonUrgentBackground( start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> Unit ): Job = launch(nonUrgentDispatcher, start, action) fun <T> Lifetime.startOnUiAsync( start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> T ): Deferred<T> = startAsync(uiDispatcher, start, action) fun <T> Lifetime.startIOBackgroundAsync( start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> T ): Deferred<T> = startAsync(processIODispatcher, start, action) fun <T> Lifetime.startLongBackgroundAsync( start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> T ) = startAsync(applicationThreadPool, start, action) fun <T> Lifetime.startNonUrgentBackgroundAsync( start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> T ): Deferred<T> = startAsync(nonUrgentDispatcher, start, action) fun CoroutineScope.launchChildOnUi( lifetime: Lifetime = Lifetime.Eternal, start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> Unit ): Job = launchChild(lifetime, uiDispatcher, start, action) fun CoroutineScope.launchChildIOBackground( lifetime: Lifetime = Lifetime.Eternal, start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> Unit ): Job = launchChild(lifetime, processIODispatcher, start, action) fun CoroutineScope.launchChildLongBackground( lifetime: Lifetime = Lifetime.Eternal, start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> Unit ): Job = launchChild(lifetime, applicationThreadPool, start, action) fun CoroutineScope.launchChildNonUrgentBackground( lifetime: Lifetime = Lifetime.Eternal, start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> Unit ): Job = launchChild(lifetime, nonUrgentDispatcher, start, action) fun <T> CoroutineScope.startChildOnUiAsync( lifetime: Lifetime = Lifetime.Eternal, start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> T ): Deferred<T> = startChildAsync(lifetime, uiDispatcher, start, action) fun <T> CoroutineScope.startChildIOBackgroundAsync( lifetime: Lifetime = Lifetime.Eternal, start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> T ): Deferred<T> = startChildAsync(lifetime, processIODispatcher, start, action) fun <T> CoroutineScope.startChildLongBackgroundAsync( lifetime: Lifetime = Lifetime.Eternal, start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> T ) = startChildAsync(lifetime, applicationThreadPool, start, action) fun <T> CoroutineScope.startChildNonUrgentBackgroundAsync( lifetime: Lifetime = Lifetime.Eternal, start: CoroutineStart = CoroutineStart.DEFAULT, action: suspend CoroutineScope.() -> T ): Deferred<T> = startChildAsync(lifetime, nonUrgentDispatcher, start, action) suspend fun <T> withUiContext(lifetime: Lifetime = Lifetime.Eternal, action: suspend CoroutineScope.() -> T): T = withContext(lifetime, uiDispatcher, action) suspend fun <T> withUiAnyModalityContext(lifetime: Lifetime = Lifetime.Eternal, action: suspend CoroutineScope.() -> T): T = withContext(lifetime, uiDispatcherAnyModality, action) suspend fun <T> withIOBackgroundContext(lifetime: Lifetime = Lifetime.Eternal, action: suspend CoroutineScope.() -> T): T = withContext(lifetime, processIODispatcher, action) suspend fun <T> withLongBackgroundContext(lifetime: Lifetime = Lifetime.Eternal, action: suspend CoroutineScope.() -> T): T = withContext(lifetime, applicationThreadPool, action) suspend fun <T> withNonUrgentBackgroundContext(lifetime: Lifetime = Lifetime.Eternal, action: suspend CoroutineScope.() -> T): T = withContext(lifetime, nonUrgentDispatcher, action) @ExperimentalCoroutinesApi @Deprecated("Use the overload without `shouldLogErrors` argument", ReplaceWith("toPromise()")) fun <T> Deferred<T>.toPromise(shouldLogErrors: Boolean): Promise<T> = toPromise() @ExperimentalCoroutinesApi fun <T> Deferred<T>.toPromise(): Promise<T> = AsyncPromiseWithoutLogError<T>().also { promise -> invokeOnCompletion { throwable -> if (throwable != null) { promise.setError(throwable) } else { promise.setResult(getCompleted()) } } } fun <T> CompletableFuture<T>.toPromise(): Promise<T> = AsyncPromiseWithoutLogError<T>().also { promise -> whenComplete { result, throwable -> if (throwable != null) { promise.setError(throwable) } else { promise.setResult(result) } } }
apache-2.0
b7fa5909bf504634d80f6149f13ca11f
39.447368
158
0.772772
4.385164
false
false
false
false
kdwink/intellij-community
plugins/settings-repository/src/keychain/OSXKeychainLibrary.kt
1
6640
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.keychain import com.intellij.openapi.util.SystemInfo import com.sun.jna.Pointer import java.nio.ByteBuffer import java.nio.CharBuffer val isOSXCredentialsStoreSupported: Boolean get() = SystemInfo.isMacIntel64 && SystemInfo.isMacOSLeopard // http://developer.apple.com/mac/library/DOCUMENTATION/Security/Reference/keychainservices/Reference/reference.html // It is very, very important to use CFRelease/SecKeychainItemFreeContent You must do it, otherwise you can get "An invalid record was encountered." public interface OSXKeychainLibrary : com.sun.jna.Library { companion object { private val LIBRARY = com.sun.jna.Native.loadLibrary("Security", OSXKeychainLibrary::class.java) as OSXKeychainLibrary fun saveGenericPassword(serviceName: ByteArray, accountName: String, password: CharArray) { saveGenericPassword(serviceName, accountName, Charsets.UTF_8.encode(CharBuffer.wrap(password))) } fun saveGenericPassword(serviceName: ByteArray, accountName: String, password: String) { saveGenericPassword(serviceName, accountName, Charsets.UTF_8.encode(password)) } private fun saveGenericPassword(serviceName: ByteArray, accountName: String, passwordBuffer: ByteBuffer) { val passwordData: ByteArray val passwordDataSize = passwordBuffer.limit() if (passwordBuffer.hasArray() && passwordBuffer.arrayOffset() == 0) { passwordData = passwordBuffer.array() } else { passwordData = ByteArray(passwordDataSize) passwordBuffer.get(passwordData) } saveGenericPassword(serviceName, accountName, passwordData, passwordDataSize) } fun findGenericPassword(serviceName: ByteArray, accountName: String): String? { val accountNameBytes = accountName.toByteArray() val passwordSize = IntArray(1); val passwordData = arrayOf<Pointer?>(null); checkForError("find", LIBRARY.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, accountNameBytes.size, accountNameBytes, passwordSize, passwordData)) val pointer = passwordData[0] ?: return null val result = String(pointer.getByteArray(0, passwordSize[0])) LIBRARY.SecKeychainItemFreeContent(null, pointer) return result } private fun saveGenericPassword(serviceName: ByteArray, accountName: String, password: ByteArray, passwordSize: Int) { val accountNameBytes = accountName.toByteArray() val itemRef = arrayOf<Pointer?>(null) checkForError("find (for save)", LIBRARY.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, accountNameBytes.size, accountNameBytes, null, null, itemRef)) val pointer = itemRef[0] if (pointer == null) { checkForError("save (new)", LIBRARY.SecKeychainAddGenericPassword(null, serviceName.size, serviceName, accountNameBytes.size, accountNameBytes, passwordSize, password)) } else { checkForError("save (update)", LIBRARY.SecKeychainItemModifyContent(pointer, null, passwordSize, password)) LIBRARY.CFRelease(pointer) } } fun deleteGenericPassword(serviceName: ByteArray, accountName: String) { val itemRef = arrayOf<Pointer?>(null) val accountNameBytes = accountName.toByteArray() checkForError("find (for delete)", LIBRARY.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, accountNameBytes.size, accountNameBytes, null, null, itemRef)) val pointer = itemRef[0] if (pointer != null) { checkForError("delete", LIBRARY.SecKeychainItemDelete(pointer)) LIBRARY.CFRelease(pointer) } } fun checkForError(message: String, code: Int) { if (code != 0 && code != /* errSecItemNotFound, always returned from find it seems */-25300) { val translated = LIBRARY.SecCopyErrorMessageString(code, null); val builder = StringBuilder(message).append(": ") if (translated == null) { builder.append(code); } else { val buf = CharArray(LIBRARY.CFStringGetLength(translated).toInt()) for (i in 0..buf.size() - 1) { buf[i] = LIBRARY.CFStringGetCharacterAtIndex(translated, i.toLong()) } LIBRARY.CFRelease(translated) builder.append(buf).append(" (").append(code).append(')') } LOG.error(builder.toString()) } } } public fun SecKeychainAddGenericPassword(keychain: Pointer?, serviceNameLength: Int, serviceName: ByteArray, accountNameLength: Int, accountName: ByteArray, passwordLength: Int, passwordData: ByteArray, itemRef: Pointer? = null): Int public fun SecKeychainItemModifyContent(/*SecKeychainItemRef*/ itemRef: Pointer, /*SecKeychainAttributeList**/ attrList: Pointer?, length: Int, data: ByteArray): Int public fun SecKeychainFindGenericPassword(keychainOrArray: Pointer?, serviceNameLength: Int, serviceName: ByteArray, accountNameLength: Int, accountName: ByteArray, passwordLength: IntArray? = null, passwordData: Array<Pointer?>? = null, itemRef: Array<Pointer?/*SecKeychainItemRef*/>? = null): Int public fun SecKeychainItemDelete(itemRef: Pointer): Int public fun /*CFString*/ SecCopyErrorMessageString(status: Int, reserved: Pointer?): Pointer? // http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFStringRef/Reference/reference.html public fun /*CFIndex*/ CFStringGetLength(/*CFStringRef*/ theString: Pointer): Long public fun /*UniChar*/ CFStringGetCharacterAtIndex(/*CFStringRef*/ theString: Pointer, /*CFIndex*/ idx: Long): Char public fun CFRelease(/*CFTypeRef*/ cf: Pointer) public fun SecKeychainItemFreeContent(/*SecKeychainAttributeList*/attrList: Pointer?, data: Pointer?) }
apache-2.0
b26187cfc08b4dba73e8d786e8ca371c
47.823529
235
0.697741
4.57931
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/kendra/src/main/kotlin/com/example/kendra/QueryIndex.kt
1
1960
// snippet-sourcedescription:[QueryIndex.kt demonstrates how to query an Amazon Kendra index.] // snippet-keyword:[SDK for Kotlin] // snippet-service:[Amazon Kendra] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.example.kendra // snippet-start:[kendra.kotlin.query.index.import] import aws.sdk.kotlin.services.kendra.KendraClient import aws.sdk.kotlin.services.kendra.model.QueryRequest import aws.sdk.kotlin.services.kendra.model.QueryResultType import kotlin.system.exitProcess // snippet-end:[kendra.kotlin.query.index.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <indexId> <text> Where: indexId - The id value of the index. text - The text to use. """ if (args.size != 2) { println(usage) exitProcess(1) } val indexId = args[0] val text = args[1] querySpecificIndex(indexId, text) } // snippet-start:[kendra.kotlin.query.index.main] suspend fun querySpecificIndex(indexIdVal: String?, text: String?) { val queryRequest = QueryRequest { indexId = indexIdVal queryResultTypeFilter = QueryResultType.Document queryText = text } KendraClient { region = "us-east-1" }.use { kendra -> val response = kendra.query(queryRequest) response.resultItems?.forEach { item -> println("The document title is ${item.documentTitle}") println("Text:") println(item.documentExcerpt?.text) } } } // snippet-end:[kendra.kotlin.query.index.main]
apache-2.0
08c63f55430589b42494f9917c713e61
27.69697
94
0.658163
3.820663
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/ActAppSetting.kt
1
45367
package jp.juggler.subwaytooter import android.content.Intent import android.content.SharedPreferences import android.content.pm.ResolveInfo import android.graphics.Color import android.graphics.Typeface import android.net.Uri import android.os.Bundle import android.os.Handler import android.text.Editable import android.text.TextWatcher import android.util.JsonWriter import android.view.View import android.view.ViewGroup import android.view.Window import android.widget.* import androidx.annotation.ColorInt import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SwitchCompat import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import com.jrummyapps.android.colorpicker.ColorPickerDialog import com.jrummyapps.android.colorpicker.ColorPickerDialogListener import jp.juggler.subwaytooter.appsetting.AppDataExporter import jp.juggler.subwaytooter.appsetting.AppSettingItem import jp.juggler.subwaytooter.appsetting.SettingType import jp.juggler.subwaytooter.appsetting.appSettingRoot import jp.juggler.subwaytooter.dialog.DlgAppPicker import jp.juggler.subwaytooter.notification.restartAllWorker import jp.juggler.subwaytooter.pref.impl.BooleanPref import jp.juggler.subwaytooter.pref.impl.FloatPref import jp.juggler.subwaytooter.pref.impl.IntPref import jp.juggler.subwaytooter.pref.impl.StringPref import jp.juggler.subwaytooter.pref.pref import jp.juggler.subwaytooter.pref.put import jp.juggler.subwaytooter.pref.remove import jp.juggler.subwaytooter.table.AcctColor import jp.juggler.subwaytooter.table.SavedAccount import jp.juggler.subwaytooter.util.CustomShare import jp.juggler.subwaytooter.util.CustomShareTarget import jp.juggler.subwaytooter.util.cn import jp.juggler.subwaytooter.view.MyTextView import jp.juggler.util.* import java.io.File import java.io.FileOutputStream import java.io.InputStream import java.io.OutputStreamWriter import java.text.NumberFormat import java.util.* import java.util.concurrent.TimeUnit import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream import kotlin.math.abs class ActAppSetting : AppCompatActivity(), ColorPickerDialogListener, View.OnClickListener { companion object { internal val log = LogCategory("ActAppSetting") fun createIntent(activity: ActMain) = Intent(activity, ActAppSetting::class.java) private const val COLOR_DIALOG_ID = 1 private const val STATE_CHOOSE_INTENT_TARGET = "customShareTarget" // 他の設定子画面と重複しない値にすること // const val REQUEST_CODE_OTHER = 0 // const val REQUEST_CODE_APP_DATA_IMPORT = 1 // const val REQUEST_CODE_TIMELINE_FONT = 2 val reLinefeed = Regex("[\\x0d\\x0a]+") } private var customShareTarget: CustomShareTarget? = null lateinit var pref: SharedPreferences lateinit var handler: Handler private lateinit var lvList: ListView private lateinit var adapter: MyAdapter private lateinit var etSearch: EditText private val arNoop = ActivityResultHandler(log) { } private val arImportAppData = ActivityResultHandler(log) { r -> if (r.isNotOk) return@ActivityResultHandler r.data?.handleGetContentResult(contentResolver) ?.firstOrNull() ?.uri?.let { importAppData2(false, it) } } val arTimelineFont = ActivityResultHandler(log) { r -> if (r.isNotOk) return@ActivityResultHandler r.data?.let { handleFontResult(AppSettingItem.TIMELINE_FONT, it, "TimelineFont") } } val arTimelineFontBold = ActivityResultHandler(log) { r -> if (r.isNotOk) return@ActivityResultHandler r.data?.let { handleFontResult( AppSettingItem.TIMELINE_FONT_BOLD, it, "TimelineFontBold" ) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) backPressed { when { lastQuery != null -> load(lastSection, null) lastSection != null -> load(null, null) else -> finish() } } arNoop.register(this) arImportAppData.register(this) arTimelineFont.register(this) arTimelineFontBold.register(this) requestWindowFeature(Window.FEATURE_NO_TITLE) App1.setActivityTheme(this, noActionBar = true) this.handler = App1.getAppState(this).handler this.pref = pref() // val intent = this.intent // val layoutId = intent.getIntExtra(EXTRA_LAYOUT_ID, 0) // val titleId = intent.getIntExtra(EXTRA_TITLE_ID, 0) // this.title = getString(titleId) if (savedInstanceState != null) { try { val sv = savedInstanceState.getString(STATE_CHOOSE_INTENT_TARGET) customShareTarget = CustomShareTarget.values().firstOrNull { it.name == sv } } catch (ex: Throwable) { log.e(ex, "can't restore customShareTarget.") } } initUi() removeDefaultPref() load(null, null) } private fun initUi() { setContentView(R.layout.act_app_setting) App1.initEdgeToEdge(this) Styler.fixHorizontalPadding0(findViewById(R.id.llContent)) lvList = findViewById(R.id.lvList) adapter = MyAdapter() lvList.adapter = adapter etSearch = findViewById<EditText>(R.id.etSearch).apply { addTextChangedListener(object : TextWatcher { override fun afterTextChanged(p0: Editable?) { pendingQuery = p0?.toString() [email protected](procQuery) [email protected](procQuery, 166L) } override fun beforeTextChanged( p0: CharSequence?, p1: Int, p2: Int, p3: Int, ) { } override fun onTextChanged( p0: CharSequence?, p1: Int, p2: Int, p3: Int, ) { } }) } findViewById<View>(R.id.btnSearchReset).setOnClickListener(this@ActAppSetting) } private fun removeDefaultPref() { val e = pref.edit() var changed = false appSettingRoot.scan { if (it.pref?.removeDefault(pref, e) == true) changed = true } if (changed) e.apply() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) val sv = customShareTarget?.name if (sv != null) outState.putString(STATE_CHOOSE_INTENT_TARGET, sv) } override fun onStop() { super.onStop() // Pull通知チェック間隔を変更したかもしれないのでジョブを再設定する restartAllWorker(context = this) } override fun onClick(v: View) { when (v.id) { R.id.btnSearchReset -> { handler.removeCallbacks(procQuery) etSearch.setText("") etSearch.hideKeyboard() load(lastSection, null) } } } /////////////////////////////////////////////////////////////// private var pendingQuery: String? = null private val procQuery: Runnable = Runnable { if (pendingQuery != null) load(null, pendingQuery) } /////////////////////////////////////////////////////////////// private val divider = Any() private val list = ArrayList<Any>() private var lastSection: AppSettingItem? = null private var lastQuery: String? = null private fun load(section: AppSettingItem?, query: String?) { list.clear() var lastPath: String? = null fun addParentPath(item: AppSettingItem) { list.add(divider) val pathList = ArrayList<String>() var parent = item.parent while (parent != null) { if (parent.caption != 0) pathList.add(0, getString(parent.caption)) parent = parent.parent } val path = pathList.joinToString("/") if (path != lastPath) { lastPath = path list.add(path) list.add(divider) } } if (query?.isNotEmpty() == true) { lastQuery = query fun scanGroup(level: Int, item: AppSettingItem) { if (item.caption == 0) return if (item.type != SettingType.Section) { var match = getString(item.caption).contains(query, ignoreCase = true) if (item.type == SettingType.Group) { for (child in item.items) { if (child.caption == 0) continue if (getString(item.caption).contains(query, ignoreCase = true)) { match = true break } } if (match) { // put entire group addParentPath(item) list.add(item) for (child in item.items) { list.add(child) } } return } if (match) { addParentPath(item) list.add(item) } } for (child in item.items) { scanGroup(level + 1, child) } } scanGroup(0, appSettingRoot) if (list.isNotEmpty()) list.add(divider) } else if (section == null) { // show root page val root = appSettingRoot lastQuery = null lastSection = null for (child in root.items) { list.add(divider) list.add(child) } list.add(divider) } else { // show section page lastSection = section lastQuery = null fun scanGroup(level: Int, parent: AppSettingItem?) { parent ?: return for (item in parent.items) { list.add(divider) list.add(item) if (item.items.isNotEmpty()) { if (item.type == SettingType.Group) { for (child in item.items) { list.add(child) } } else { scanGroup(level + 1, item) } } } } scanGroup(0, section.cast()) if (list.isNotEmpty()) list.add(divider) } adapter.notifyDataSetChanged() lvList.setSelectionFromTop(0, 0) } inner class MyAdapter : BaseAdapter() { override fun getCount(): Int = list.size override fun getItemId(position: Int): Long = 0 override fun getItem(position: Int): Any = list[position] override fun getViewTypeCount(): Int = SettingType.values().maxByOrNull { it.id }!!.id + 1 override fun getItemViewType(position: Int): Int = when (val item = list[position]) { is AppSettingItem -> item.type.id is String -> SettingType.Path.id divider -> SettingType.Divider.id else -> error("can't generate view for type $item") } // true if the item at the specified position is not a separator. // (A separator is a non-selectable, non-clickable item). override fun areAllItemsEnabled(): Boolean = false override fun isEnabled(position: Int): Boolean = list[position] is AppSettingItem override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View = when (val item = list[position]) { is AppSettingItem -> getViewSettingItem(item, convertView, parent) is String -> getViewPath(item, convertView) divider -> getViewDivider(convertView) else -> error("can't generate view for type $item") } } private fun dip(dp: Float): Int = (resources.displayMetrics.density * dp + 0.5f).toInt() private fun dip(dp: Int): Int = dip(dp.toFloat()) private fun getViewDivider(convertView: View?): View = convertView ?: FrameLayout(this@ActAppSetting).apply { layoutParams = AbsListView.LayoutParams( AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT ) addView(View(this@ActAppSetting).apply { layoutParams = FrameLayout.LayoutParams( AbsListView.LayoutParams.MATCH_PARENT, dip(1) ).apply { val marginX = 0 val marginY = dip(6) setMargins(marginX, marginY, marginX, marginY) } setBackgroundColor(context.attrColor(R.attr.colorSettingDivider)) }) } private fun getViewPath(path: String, convertView: View?): View { val tv: MyTextView = convertView.cast() ?: MyTextView(this@ActAppSetting).apply { layoutParams = AbsListView.LayoutParams( AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT ) val padX = 0 val padY = dip(3) setTypeface(typeface, Typeface.BOLD) setPaddingRelative(padX, padY, padX, padY) } tv.text = path return tv } private fun getViewSettingItem( item: AppSettingItem, convertView: View?, parent: ViewGroup?, ): View { val view: View val holder: ViewHolderSettingItem if (convertView != null) { view = convertView holder = convertView.tag.cast()!! } else { view = layoutInflater.inflate(R.layout.lv_setting_item, parent, false) holder = ViewHolderSettingItem(view) view.tag = holder } holder.bind(item) return view } private var colorTarget: AppSettingItem? = null override fun onDialogDismissed(dialogId: Int) { } override fun onColorSelected(dialogId: Int, @ColorInt newColor: Int) { val colorTarget = this.colorTarget ?: return val ip: IntPref = colorTarget.pref.cast() ?: error("$colorTarget has no in pref") val c = when (colorTarget.type) { SettingType.ColorAlpha -> newColor.notZero() ?: 1 else -> newColor or Color.BLACK } pref.edit().put(ip, c).apply() findItemViewHolder(colorTarget)?.showColor() colorTarget.changed(this) } inner class ViewHolderSettingItem(viewRoot: View) : TextWatcher, AdapterView.OnItemSelectedListener, CompoundButton.OnCheckedChangeListener { private val tvCaption: TextView = viewRoot.findViewById(R.id.tvCaption) private val btnAction: Button = viewRoot.findViewById(R.id.btnAction) private val checkBox: CheckBox = viewRoot.findViewById<CheckBox>(R.id.checkBox) .also { it.setOnCheckedChangeListener(this) } private val swSwitch: SwitchCompat = viewRoot.findViewById<SwitchCompat>(R.id.swSwitch) .also { it.setOnCheckedChangeListener(this) } val llExtra: LinearLayout = viewRoot.findViewById(R.id.llExtra) val textView1: TextView = viewRoot.findViewById(R.id.textView1) private val llButtonBar: LinearLayout = viewRoot.findViewById(R.id.llButtonBar) private val vColor: View = viewRoot.findViewById(R.id.vColor) private val btnEdit: Button = viewRoot.findViewById(R.id.btnEdit) private val btnReset: Button = viewRoot.findViewById(R.id.btnReset) private val spSpinner: Spinner = viewRoot.findViewById<Spinner>(R.id.spSpinner) .also { it.onItemSelectedListener = this } private val etEditText: EditText = viewRoot.findViewById<EditText>(R.id.etEditText) .also { it.addTextChangedListener(this) } private val tvDesc: TextView = viewRoot.findViewById(R.id.tvDesc) private val tvError: TextView = viewRoot.findViewById(R.id.tvError) val activity: ActAppSetting get() = this@ActAppSetting var item: AppSettingItem? = null private var bindingBusy = false fun bind(item: AppSettingItem) { bindingBusy = true try { this.item = item tvCaption.vg(false) btnAction.vg(false) checkBox.vg(false) swSwitch.vg(false) llExtra.vg(false) textView1.vg(false) llButtonBar.vg(false) vColor.vg(false) spSpinner.vg(false) etEditText.vg(false) tvDesc.vg(false) tvError.vg(false) val name = if (item.caption == 0) "" else getString(item.caption) if (item.desc != 0) { tvDesc.vg(true) tvDesc.text = getString(item.desc) if (item.descClickSet) { tvDesc.background = ContextCompat.getDrawable( activity, R.drawable.btn_bg_transparent_round6dp ) tvDesc.setOnClickListener { item.descClick.invoke(activity) } } else { tvDesc.background = null tvDesc.setOnClickListener(null) tvDesc.isClickable = false } } when (item.type) { SettingType.Section -> { btnAction.vg(true) btnAction.text = name btnAction.isEnabledAlpha = item.enabled btnAction.setOnClickListener { load(item.cast()!!, null) } } SettingType.Action -> { btnAction.vg(true) btnAction.text = name btnAction.isEnabledAlpha = item.enabled btnAction.setOnClickListener { item.action(activity) } } SettingType.CheckBox -> { val bp: BooleanPref = item.pref.cast() ?: error("$name has no boolean pref") checkBox.vg(false) // skip animation checkBox.text = name checkBox.isEnabledAlpha = item.enabled checkBox.isChecked = bp(pref) checkBox.vg(true) } SettingType.Switch -> { val bp: BooleanPref = item.pref.cast() ?: error("$name has no boolean pref") showCaption(name) swSwitch.vg(false) // skip animation setSwitchColor(swSwitch) swSwitch.isEnabledAlpha = item.enabled swSwitch.isChecked = bp(pref) swSwitch.vg(true) } SettingType.Group -> { showCaption(name) } SettingType.Sample -> { llExtra.vg(true) llExtra.removeAllViews() layoutInflater.inflate(item.sampleLayoutId, llExtra, true) item.sampleUpdate(activity, llExtra) } SettingType.ColorAlpha, SettingType.ColorOpaque -> { val ip = item.pref.cast<IntPref>() ?: error("$name has no int pref") showCaption(name) llButtonBar.vg(true) vColor.vg(true) vColor.setBackgroundColor(ip(pref)) btnEdit.isEnabledAlpha = item.enabled btnReset.isEnabledAlpha = item.enabled btnEdit.setOnClickListener { colorTarget = item val color = ip(pref) val builder = ColorPickerDialog.newBuilder() .setDialogType(ColorPickerDialog.TYPE_CUSTOM) .setAllowPresets(true) .setShowAlphaSlider(item.type == SettingType.ColorAlpha) .setDialogId(COLOR_DIALOG_ID) if (color != 0) builder.setColor(color) builder.show(activity) } btnReset.setOnClickListener { pref.edit().remove(ip).apply() showColor() item.changed.invoke(activity) } } SettingType.Spinner -> { showCaption(name) spSpinner.vg(true) spSpinner.isEnabledAlpha = item.enabled val pi = item.pref if (pi is IntPref) { // 整数型の設定のSpinnerは全て選択肢を単純に覚える val argsInt = item.spinnerArgs if (argsInt != null) { initSpinner(spSpinner, argsInt.map { getString(it) }) } else { initSpinner(spSpinner, item.spinnerArgsProc(activity)) } spSpinner.setSelection(pi.invoke(pref)) } else { item.spinnerInitializer.invoke(activity, spSpinner) } } SettingType.EditText -> { showCaption(name) etEditText.vg(true) ?: error("EditText must have preference.") etEditText.inputType = item.inputType val text = when (val pi = item.pref) { is FloatPref -> { item.fromFloat.invoke(activity, pi(pref)) } is StringPref -> { pi(pref) } else -> error("EditText han incorrect pref $pi") } etEditText.setText(text) etEditText.setSelection(0, text.length) item.hint?.let { etEditText.hint = it } updateErrorView() } SettingType.TextWithSelector -> { showCaption(name) llButtonBar.vg(true) vColor.vg(false) textView1.vg(true) item.showTextView.invoke(activity, textView1) btnEdit.setOnClickListener { item.onClickEdit.invoke(activity) } btnReset.setOnClickListener { item.onClickReset.invoke(activity) } } else -> error("unknown type ${item.type}") } } finally { bindingBusy = false } } private fun showCaption(caption: String) { if (caption.isNotEmpty()) { tvCaption.vg(true) tvCaption.text = caption updateCaption() } } fun updateCaption() { val item = item ?: return val key = item.pref?.key ?: return val sample: TextView = tvCaption var defaultExtra = defaultLineSpacingExtra[key] if (defaultExtra == null) { defaultExtra = sample.lineSpacingExtra defaultLineSpacingExtra[key] = defaultExtra } var defaultMultiplier = defaultLineSpacingMultiplier[key] if (defaultMultiplier == null) { defaultMultiplier = sample.lineSpacingMultiplier defaultLineSpacingMultiplier[key] = defaultMultiplier } val size = item.captionFontSize.invoke(activity) if (size != null) sample.textSize = size val spacing = item.captionSpacing.invoke(activity) if (spacing == null || !spacing.isFinite()) { sample.setLineSpacing(defaultExtra, defaultMultiplier) } else { sample.setLineSpacing(0f, spacing) } } private fun updateErrorView() { val item = item ?: return val sv = etEditText.text.toString() val error = item.getError.invoke(activity, sv) tvError.vg(error != null)?.text = error } fun showColor() { val item = item ?: return val ip = item.pref.cast<IntPref>() ?: return val c = ip(pref) vColor.setBackgroundColor(c) } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun afterTextChanged(p0: Editable?) { if (bindingBusy) return val item = item ?: return val sv = item.filter.invoke(p0?.toString() ?: "") when (val pi = item.pref) { is StringPref -> { pref.edit().put(pi, sv).apply() } is FloatPref -> { val fv = item.toFloat.invoke(activity, sv) if (fv.isFinite()) { pref.edit().put(pi, fv).apply() } else { pref.edit().remove(pi.key).apply() } } else -> { error("not FloatPref or StringPref") } } item.changed.invoke(activity) updateErrorView() } override fun onNothingSelected(v: AdapterView<*>?) = Unit override fun onItemSelected( parent: AdapterView<*>?, view: View?, position: Int, id: Long, ) { if (bindingBusy) return val item = item ?: return when (val pi = item.pref) { is IntPref -> pref.edit().put(pi, spSpinner.selectedItemPosition).apply() else -> item.spinnerOnSelected.invoke(activity, spSpinner, position) } item.changed.invoke(activity) } override fun onCheckedChanged(v: CompoundButton?, isChecked: Boolean) { if (bindingBusy) return val item = item ?: return when (val pi = item.pref) { is BooleanPref -> pref.edit().put(pi, isChecked).apply() else -> error("CompoundButton has no booleanPref $pi") } item.changed.invoke(activity) } } private fun initSpinner(spinner: Spinner, captions: List<String>) { spinner.adapter = ArrayAdapter( this, android.R.layout.simple_spinner_item, captions.toTypedArray() ).apply { setDropDownViewResource(R.layout.lv_spinner_dropdown) } } /////////////////////////////////////////////////////////////// @Suppress("BlockingMethodInNonBlockingContext") fun exportAppData() { val activity = this launchProgress( "export app data", doInBackground = { val cacheDir = activity.cacheDir cacheDir.mkdir() val file = File( cacheDir, "SubwayTooter.${android.os.Process.myPid()}.${android.os.Process.myTid()}.zip" ) // ZipOutputStreamオブジェクトの作成 ZipOutputStream(FileOutputStream(file)).use { zipStream -> // アプリデータjson zipStream.putNextEntry(ZipEntry("AppData.json")) try { val jw = JsonWriter(OutputStreamWriter(zipStream, "UTF-8")) AppDataExporter.encodeAppData(activity, jw) jw.flush() } finally { zipStream.closeEntry() } // カラム背景画像 val appState = App1.getAppState(activity) for (column in appState.columnList) { AppDataExporter.saveBackgroundImage(activity, zipStream, column) } } file }, afterProc = { val uri = FileProvider.getUriForFile(activity, App1.FILE_PROVIDER_AUTHORITY, it) val intent = Intent(Intent.ACTION_SEND) intent.type = contentResolver.getType(uri) intent.putExtra(Intent.EXTRA_SUBJECT, "SubwayTooter app data") intent.putExtra(Intent.EXTRA_STREAM, uri) intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION) arNoop.launch(intent) } ) } // open data picker fun importAppData1() { try { val intent = intentOpenDocument("*/*") arImportAppData.launch(intent) } catch (ex: Throwable) { showToast(ex, "importAppData(1) failed.") } } // after data picked private fun importAppData2(bConfirm: Boolean, uri: Uri) { val type = contentResolver.getType(uri) log.d("importAppData type=$type") if (!bConfirm) { AlertDialog.Builder(this) .setMessage(getString(R.string.app_data_import_confirm)) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.ok) { _, _ -> importAppData2(true, uri) } .show() return } val data = Intent() data.data = uri setResult(ActMain.RESULT_APP_DATA_IMPORT, data) finish() } fun findItemViewHolder(item: AppSettingItem?): ViewHolderSettingItem? { if (item != null) { for (i in 0 until lvList.childCount) { val view = lvList.getChildAt(i) val holder: ViewHolderSettingItem? = view?.tag?.cast() if (holder?.item == item) return holder } } return null } fun showSample(item: AppSettingItem?) { item ?: error("showSample: missing item…") findItemViewHolder(item)?.let { item.sampleUpdate.invoke(this, it.llExtra) } } // リスト内部のSwitchCompat全ての色を更新する fun setSwitchColor() = setSwitchColor(lvList) ////////////////////////////////////////////////////// fun formatFontSize(fv: Float): String = when { fv.isFinite() -> String.format(defaultLocale(this), "%.1f", fv) else -> "" } fun parseFontSize(src: String): Float { try { if (src.isNotEmpty()) { val f = NumberFormat.getInstance(defaultLocale(this)).parse(src)?.toFloat() return when { f == null -> Float.NaN f.isNaN() -> Float.NaN f < 0f -> 0f f > 999f -> 999f else -> f } } } catch (ex: Throwable) { log.trace(ex) } return Float.NaN } private val defaultLineSpacingExtra = HashMap<String, Float>() private val defaultLineSpacingMultiplier = HashMap<String, Float>() private fun handleFontResult(item: AppSettingItem?, data: Intent, fileName: String) { item ?: error("handleFontResult : setting item is null") data.handleGetContentResult(contentResolver).firstOrNull()?.uri?.let { val file = saveTimelineFont(it, fileName) if (file != null) { pref.edit().put(item.pref.cast()!!, file.absolutePath).apply() showTimelineFont(item) } } } fun showTimelineFont(item: AppSettingItem?) { item ?: return val holder = findItemViewHolder(item) ?: return item.showTextView.invoke(this, holder.textView1) } fun showTimelineFont(item: AppSettingItem, tv: TextView) { val fontUrl = item.pref.cast<StringPref>()!!.invoke(this) try { if (fontUrl.isNotEmpty()) { tv.typeface = Typeface.DEFAULT val face = Typeface.createFromFile(fontUrl) tv.typeface = face tv.text = fontUrl return } } catch (ex: Throwable) { log.trace(ex) } // fallback tv.text = getString(R.string.not_selected) tv.typeface = Typeface.DEFAULT } private fun saveTimelineFont(uri: Uri?, fileName: String): File? { try { if (uri == null) { showToast(false, "missing uri.") return null } contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) val dir = filesDir dir.mkdir() val tmpFile = File(dir, "$fileName.tmp") val source: InputStream? = contentResolver.openInputStream(uri) if (source == null) { showToast(false, "openInputStream returns null. uri=$uri") return null } else { source.use { inStream -> FileOutputStream(tmpFile).use { outStream -> inStream.copyTo(outStream) } } } val face = Typeface.createFromFile(tmpFile) if (face == null) { showToast(false, "Typeface.createFromFile() failed.") return null } val file = File(dir, fileName) if (!tmpFile.renameTo(file)) { showToast(false, "File operation failed.") return null } return file } catch (ex: Throwable) { log.trace(ex) showToast(ex, "saveTimelineFont failed.") return null } } ////////////////////////////////////////////////////// inner class AccountAdapter internal constructor() : BaseAdapter() { internal val list = ArrayList<SavedAccount>() init { for (a in SavedAccount.loadAccountList(this@ActAppSetting)) { if (a.isPseudo) continue list.add(a) } SavedAccount.sort(list) } override fun getCount(): Int { return 1 + list.size } override fun getItem(position: Int): Any? { return if (position == 0) null else list[position - 1] } override fun getItemId(position: Int): Long { return 0 } override fun getView(position: Int, viewOld: View?, parent: ViewGroup): View { val view = viewOld ?: layoutInflater.inflate( android.R.layout.simple_spinner_item, parent, false ) view.findViewById<TextView>(android.R.id.text1).text = when (position) { 0 -> getString(R.string.ask_always) else -> AcctColor.getNickname(list[position - 1]) } return view } override fun getDropDownView(position: Int, viewOld: View?, parent: ViewGroup): View { val view = viewOld ?: layoutInflater.inflate(R.layout.lv_spinner_dropdown, parent, false) view.findViewById<TextView>(android.R.id.text1).text = when (position) { 0 -> getString(R.string.ask_always) else -> AcctColor.getNickname(list[position - 1]) } return view } // 見つからなければ0,見つかったら1以上 internal fun getIndexFromId(dbId: Long): Int = 1 + list.indexOfFirst { it.db_id == dbId } internal fun getIdFromIndex(position: Int): Long = if (position > 0) list[position - 1].db_id else -1L } private class Item( val id: String, val caption: String, val offset: Int, ) inner class TimeZoneAdapter internal constructor() : BaseAdapter() { private val list = ArrayList<Item>() init { for (id in TimeZone.getAvailableIDs()) { val tz = TimeZone.getTimeZone(id) // GMT数字を指定するタイプのタイムゾーンは無視する。ただしGMT-12:00の1項目だけは残す // 3文字のIDは曖昧な場合があるので非推奨 // '/' を含まないIDは列挙しない if (!when { !tz.id.contains('/') -> false tz.id == "Etc/GMT+12" -> true tz.id.startsWith("Etc/") -> false else -> true } ) continue var offset = tz.rawOffset.toLong() val caption = when (offset) { 0L -> "(UTC\u00B100:00) ${tz.id} ${tz.displayName}" else -> { val format = when { offset > 0 -> "(UTC+%02d:%02d) %s %s" else -> "(UTC-%02d:%02d) %s %s" } offset = abs(offset) val hours = TimeUnit.MILLISECONDS.toHours(offset) val minutes = TimeUnit.MILLISECONDS.toMinutes(offset) - TimeUnit.HOURS.toMinutes(hours) String.format(format, hours, minutes, tz.id, tz.displayName) } } if (list.none { it.caption == caption }) { list.add(Item(id, caption, tz.rawOffset)) } } list.sortWith { a, b -> (a.offset - b.offset).notZero() ?: a.caption.compareTo(b.caption) } list.add(0, Item("", getString(R.string.device_timezone), 0)) } override fun getCount(): Int { return list.size } override fun getItem(position: Int): Any { return list[position] } override fun getItemId(position: Int): Long { return 0 } override fun getView(position: Int, viewOld: View?, parent: ViewGroup): View { val view = viewOld ?: layoutInflater.inflate( android.R.layout.simple_spinner_item, parent, false ) val item = list[position] view.findViewById<TextView>(android.R.id.text1).text = item.caption return view } override fun getDropDownView(position: Int, viewOld: View?, parent: ViewGroup): View { val view = viewOld ?: layoutInflater.inflate(R.layout.lv_spinner_dropdown, parent, false) val item = list[position] view.findViewById<TextView>(android.R.id.text1).text = item.caption return view } internal fun getIndexFromId(tzId: String): Int { val index = list.indexOfFirst { it.id == tzId } return if (index == -1) 0 else index } internal fun getIdFromIndex(position: Int): String { return list[position].id } } fun openCustomShareChooser(appSettingItem: AppSettingItem, target: CustomShareTarget) { try { val rv = DlgAppPicker( this, intent = Intent().apply { action = Intent.ACTION_SEND type = "text/plain" putExtra(Intent.EXTRA_TEXT, getString(R.string.content_sample)) }, addCopyAction = true ) { setCustomShare(appSettingItem, target, it) } .show() if (!rv) showToast(true, "share target app is not installed.") } catch (ex: Throwable) { log.trace(ex) showToast(ex, "openCustomShareChooser failed.") } } fun setCustomShare(appSettingItem: AppSettingItem, target: CustomShareTarget, value: String) { val sp: StringPref = appSettingItem.pref.cast() ?: error("$target: not StringPref") pref.edit().put(sp, value).apply() showCustomShareIcon(findItemViewHolder(appSettingItem)?.textView1, target) } fun showCustomShareIcon(tv: TextView?, target: CustomShareTarget) { tv ?: return val cn = CustomShare.getCustomShareComponentName(target) val (label, icon) = CustomShare.getInfo(this, cn) tv.text = label ?: getString(R.string.not_selected) tv.setCompoundDrawablesRelativeWithIntrinsicBounds(icon, null, null, null) tv.compoundDrawablePadding = (resources.displayMetrics.density * 4f + 0.5f).toInt() } fun openWebBrowserChooser( appSettingItem: AppSettingItem, intent: Intent, filter: (ResolveInfo) -> Boolean, ) { try { val rv = DlgAppPicker( this, intent = intent, filter = filter, addCopyAction = false ) { setWebBrowser(appSettingItem, it) } .show() if (!rv) showToast(true, "share target app is not installed.") } catch (ex: Throwable) { log.trace(ex) showToast(ex, "openCustomShareChooser failed.") } } private fun setWebBrowser(appSettingItem: AppSettingItem, value: String) { val sp: StringPref = appSettingItem.pref.cast() ?: error("${getString(appSettingItem.caption)}: not StringPref") pref.edit().put(sp, value).apply() showWebBrowser(findItemViewHolder(appSettingItem)?.textView1, value) } private fun showWebBrowser(tv: TextView?, prefValue: String) { tv ?: return val cn = prefValue.cn() val (label, icon) = CustomShare.getInfo(this, cn) tv.text = label ?: getString(R.string.not_selected) tv.setCompoundDrawablesRelativeWithIntrinsicBounds(icon, null, null, null) tv.compoundDrawablePadding = (resources.displayMetrics.density * 4f + 0.5f).toInt() } }
apache-2.0
57b5ecac649ded8840077aa862b2cabb
34.581301
112
0.505767
5.072717
false
false
false
false
seratch/jslack
slack-api-model-kotlin-extension/src/main/kotlin/com/slack/api/model/kotlin_extension/block/element/ButtonElementBuilder.kt
1
4051
package com.slack.api.model.kotlin_extension.block.element import com.slack.api.model.block.composition.ConfirmationDialogObject import com.slack.api.model.block.composition.PlainTextObject import com.slack.api.model.block.element.ButtonElement import com.slack.api.model.kotlin_extension.block.BlockLayoutBuilder import com.slack.api.model.kotlin_extension.block.Builder import com.slack.api.model.kotlin_extension.block.composition.ConfirmationDialogObjectBuilder // same name with the object + "Builder" suffix @BlockLayoutBuilder class ButtonElementBuilder : Builder<ButtonElement> { private var actionId: String? = null private var text: PlainTextObject? = null private var url: String? = null private var value: String? = null private var style: String? = null private var confirm: ConfirmationDialogObject? = null /** * An identifier for this action. You can use this when you receive an interaction payload to identify the source * of the action. Should be unique among all other action_ids used elsewhere by your app. Maximum length for this * field is 255 characters. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#button">Button element documentation</a> */ fun actionId(id: String) { actionId = id } /** * Inserts a plain text object in the text field for this button. * * Defines the button's text. Maximum length for the text in this field is 75 characters. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#button">Button element documentation</a> */ fun text(text: String, emoji: Boolean? = null) { this.text = PlainTextObject(text, emoji) } /** * A URL to load in the user's browser when the button is clicked. Maximum length for this field is 3000 * characters. If you're using url, you'll still receive an interaction payload and will need to send an * acknowledgement response. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#button">Button element documentation</a> */ fun url(text: String) { url = text } /** * The value to send along with the interaction payload. Maximum length for this field is 2000 characters. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#button">Button element documentation</a> */ fun value(text: String) { value = text } /** * Decorates buttons with alternative visual color schemes. Use this option with restraint. * * This implementation uses a type safe enum value for the button style. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#button">Button element documentation</a> */ fun style(style: ButtonStyle) { this.style = style.value } /** * Decorates buttons with alternative visual color schemes. Use this option with restraint. * * This implementation uses a string for the button style. This might be used if new button styles are introduced * and the enum is insufficient. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#button">Button element documentation</a> */ fun style(style: String) { this.style = style } /** * A confirm object that defines an optional confirmation dialog after the button is clicked. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#button">Button element documentation</a> */ fun confirm(builder: ConfirmationDialogObjectBuilder.() -> Unit) { confirm = ConfirmationDialogObjectBuilder().apply(builder).build() } override fun build(): ButtonElement { return ButtonElement.builder() .actionId(actionId) .url(url) .value(value) .text(text) .style(style) .confirm(confirm) .build() } }
mit
28deb02484169ba24d95e7cbca060b41
37.961538
118
0.673167
4.268704
false
false
false
false
orauyeu/SimYukkuri
subprojects/messageutil/src/main/kotlin/shitarabatogit/ConditionUtil.kt
1
2682
package shitarabatogit import messageutil.Growth import messageutil.Love import messageutil.Condition /** 指定された属性が含まれるかを返す. */ internal fun Condition.contains(attr: String): Boolean { when (attr) { "baby" -> return growth == Growth.BABY "child" -> return growth == Growth.CHILD "adult" -> return growth == Growth.ADULT } if (attr == "rude") return isImmoral if (attr == "normal") return !isImmoral if (attr == "damage") return isDamaged if (attr == "pooSlave") return isPooSlave when (attr) { "dislikeplayer" -> return love == Love.HATE "loveplayer" -> return love == Love.LOVE } if (attr == "pants") return hasWrapper throw Exception("不正な属性名です: $attr") } /** 属性を加える. */ internal fun Condition.added(attr: String): Condition { when (attr) { "baby" -> return this.copy(growth = Growth.BABY) "child" -> return this.copy(growth = Growth.CHILD) "adult" -> return this.copy(growth = Growth.ADULT) } when (attr) { "rude" -> return this.copy(isImmoral = true) "normal" -> return this.copy(isImmoral = false) } if (attr == "rude") return this.copy(isImmoral = true) if (attr == "damage") return this.copy(isDamaged = true) if (attr == "pooSlave") return this.copy(isPooSlave = true) when (attr) { "dislikeplayer" -> return this.copy(love = Love.HATE) "loveplayer" -> return this.copy(love = Love.LOVE) } if (attr == "pants") return this.copy(hasWrapper = true) throw Exception("不正な属性名です: $attr") } /** 属性を取り除く. */ internal fun Condition.removed(attr: String): Condition { when (attr) { "baby" -> return this.copy(growth = Growth.ALL) "child" -> return this.copy(growth = Growth.ALL) "adult" -> return this.copy(growth = Growth.ALL) } if (attr == "rude") return this.copy(isImmoral = false) if (attr == "damage") return this.copy(isDamaged = false) if (attr == "pooSlave") return this.copy(isPooSlave = false) when (attr) { "dislikeplayer" -> return this.copy(love = Love.ALL) "loveplayer" -> return this.copy(love = Love.ALL) } if (attr == "pants") return this.copy(hasWrapper = false) if (attr == "normal") return this else throw Exception("不正な属性名です: $attr") }
apache-2.0
adc9d098f406655007438101e29ea382
22.642202
57
0.555124
3.434667
false
false
false
false
paplorinc/intellij-community
platform/diff-impl/src/com/intellij/diff/util/DiffLineMarkerRenderer.kt
6
4415
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.util import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.markup.LineMarkerRendererEx import com.intellij.openapi.editor.markup.RangeHighlighter import java.awt.Graphics import java.awt.Graphics2D import java.awt.Rectangle internal class DiffLineMarkerRenderer( private val myHighlighter: RangeHighlighter, private val myDiffType: TextDiffType, private val myIgnoredFoldingOutline: Boolean, private val myResolved: Boolean, private val myExcluded: Boolean, private val myHideWithoutLineNumbers: Boolean, private val myEmptyRange: Boolean, private val myFirstLine: Boolean, private val myLastLine: Boolean ) : LineMarkerRendererEx { override fun paint(editor: Editor, g: Graphics, range: Rectangle) { editor as EditorEx g as Graphics2D val gutter = editor.gutterComponentEx var x1 = 0 val x2 = x1 + gutter.width var y1: Int var y2: Int if (myEmptyRange && myLastLine) { y1 = DiffDrawUtil.lineToY(editor, DiffUtil.getLineCount(editor.document)) y2 = y1 } else { val startLine = editor.document.getLineNumber(myHighlighter.startOffset) val endLine = editor.document.getLineNumber(myHighlighter.endOffset) + 1 y1 = DiffDrawUtil.lineToY(editor, startLine) y2 = if (myEmptyRange) y1 else DiffDrawUtil.lineToY(editor, endLine) } if (myEmptyRange && myFirstLine) { y1++ y2++ } if (myHideWithoutLineNumbers && !editor.getSettings().isLineNumbersShown) { // draw only in "editor" part of the gutter (rightmost part of foldings' "[+]" ) x1 = gutter.whitespaceSeparatorOffset } else { val annotationsOffset = gutter.annotationsAreaOffset val annotationsWidth = gutter.annotationsAreaWidth if (annotationsWidth != 0) { drawMarker(editor, g, x1, annotationsOffset, y1, y2) x1 = annotationsOffset + annotationsWidth } } if (myExcluded) { val xOutline = gutter.whitespaceSeparatorOffset drawMarker(editor, g, xOutline, x2, y1, y2, paintBackground = false, paintBorder = true) // over "editor" drawMarker(editor, g, x1, xOutline, y1, y2, paintBackground = true, paintBorder = true, useIgnoredBackgroundColor = true) // over "gutter" } else if (myIgnoredFoldingOutline) { val xOutline = gutter.whitespaceSeparatorOffset drawMarker(editor, g, xOutline, x2, y1, y2, useIgnoredBackgroundColor = true) // over "editor" drawMarker(editor, g, x1, xOutline, y1, y2) // over "gutter" } else { drawMarker(editor, g, x1, x2, y1, y2) } } private fun drawMarker(editor: Editor, g: Graphics2D, x1: Int, x2: Int, y1: Int, y2: Int, paintBackground: Boolean = !myResolved, paintBorder: Boolean = myResolved, dottedLine: Boolean = myResolved, useIgnoredBackgroundColor: Boolean = false) { if (x1 >= x2) return val color = myDiffType.getColor(editor) if (y2 - y1 > 2) { if (paintBackground) { g.color = if (useIgnoredBackgroundColor) myDiffType.getIgnoredColor(editor) else color g.fillRect(x1, y1, x2 - x1, y2 - y1) } if (paintBorder) { DiffDrawUtil.drawChunkBorderLine(g, x1, x2, y1, color, false, dottedLine) DiffDrawUtil.drawChunkBorderLine(g, x1, x2, y2 - 1, color, false, dottedLine) } } else { // range is empty - insertion or deletion // Draw 2 pixel line in that case DiffDrawUtil.drawChunkBorderLine(g, x1, x2, y1 - 1, color, true, dottedLine) } } override fun getPosition(): LineMarkerRendererEx.Position = LineMarkerRendererEx.Position.CUSTOM }
apache-2.0
01e8dc13d0fa713511456fff8acdca29
36.10084
144
0.683126
3.977477
false
false
false
false
vladmm/intellij-community
platform/configuration-store-impl/src/StreamProvider.kt
8
2078
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.components.RoamingType import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import java.io.InputStream public interface StreamProvider { public open val enabled: Boolean get() = true public open fun isApplicable(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT): Boolean = true /** * @param fileSpec * @param content bytes of content, size of array is not actual size of data, you must use `size` * @param size actual size of data */ public fun write(fileSpec: String, content: ByteArray, size: Int = content.size(), roamingType: RoamingType = RoamingType.DEFAULT) public fun read(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT): InputStream? /** * You must close passed input stream. */ public fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean) /** * Delete file or directory */ public fun delete(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT) } public fun StreamProvider.write(path: String, content: String) { write(path, content.toByteArray()) } public fun StreamProvider.write(path: String, content: BufferExposingByteArrayOutputStream, roamingType: RoamingType = RoamingType.DEFAULT) { write(path, content.internalBuffer, content.size(), roamingType) }
apache-2.0
567f951b617bf50663e69a232486177f
37.5
180
0.751684
4.440171
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/BufferedSource.kt
1
3572
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Instruction2 import org.runestar.client.updater.mapper.Method2 import org.runestar.client.common.startsWith import org.objectweb.asm.Opcodes.* import org.objectweb.asm.Opcodes.PUTFIELD import org.objectweb.asm.Type.* import java.io.IOException import java.io.InputStream class BufferedSource : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.interfaces.contains(Runnable::class.type) } .and { it.superType == Any::class.type } .and { it.instanceFields.count { it.type == InputStream::class.type } == 1 } class thread : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == Thread::class.type } } class inputStream : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == InputStream::class.type } } class exception : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == IOException::class.type } } class buffer : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == ByteArray::class.type } } @MethodParameters() class close : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.instructions.any { it.isMethod && it.methodName == "join" } } } class position : OrderMapper.InConstructor.Field(BufferedSource::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class limit : OrderMapper.InConstructor.Field(BufferedSource::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class capacity : OrderMapper.InConstructor.Field(BufferedSource::class, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @MethodParameters("length") class isAvailable : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE } } @MethodParameters("dst", "dstIndex", "length") class read : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE } .and { it.arguments.startsWith(ByteArray::class.type) } } @MethodParameters() class available : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE } .and { it.arguments.size in 0..1 } .and { it.instructions.none { it.opcode == IREM } } } @MethodParameters() class readUnsignedByte : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE } .and { it.arguments.size in 0..1 } .and { it.instructions.any { it.opcode == IREM } } } }
mit
70515b6f1a956bbe9dc946e463b8055e
41.535714
112
0.694009
4.340219
false
false
false
false
apollographql/apollo-android
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/keyArgs.kt
1
1872
package com.apollographql.apollo3.compiler.codegen import com.apollographql.apollo3.annotations.ApolloExperimental import com.apollographql.apollo3.ast.GQLField import com.apollographql.apollo3.ast.GQLInterfaceTypeDefinition import com.apollographql.apollo3.ast.GQLObjectTypeDefinition import com.apollographql.apollo3.ast.GQLStringValue import com.apollographql.apollo3.ast.GQLTypeDefinition import com.apollographql.apollo3.ast.Schema import com.apollographql.apollo3.ast.SourceAwareException import com.apollographql.apollo3.ast.parseAsGQLSelections import okio.Buffer internal fun GQLTypeDefinition.keyArgs(fieldName: String): Set<String> { val directives = when (this) { is GQLObjectTypeDefinition -> directives is GQLInterfaceTypeDefinition -> directives else -> emptyList() } return directives.filter { it.name == Schema.FIELD_POLICY }.filter { (it.arguments?.arguments?.single { it.name == Schema.FIELD_POLICY_FOR_FIELD }?.value as GQLStringValue).value == fieldName }.flatMap { val keyArgsValue = it.arguments?.arguments?.single { it.name == Schema.FIELD_POLICY_KEY_ARGS }?.value if (keyArgsValue !is GQLStringValue) { throw SourceAwareException("Apollo: no keyArgs found or wrong keyArgs type", it.sourceLocation) } @OptIn(ApolloExperimental::class) Buffer().writeUtf8(keyArgsValue.value) .parseAsGQLSelections() .value ?.map { if (it !is GQLField) { throw SourceAwareException("Apollo: fragments are not supported in keyArgs", it.sourceLocation) } if (it.selectionSet != null) { throw SourceAwareException("Apollo: composite fields are not supported in keyArgs", it.sourceLocation) } it.name } ?: throw SourceAwareException("Apollo: keyArgs should be a selectionSet", it.sourceLocation) }.toSet() }
mit
c25e376d5c29e6a0b92cb999bee25fef
41.568182
126
0.739316
4.303448
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/collect/CharMap.kt
1
4649
package com.nibado.projects.advent.collect import com.nibado.projects.advent.Point import com.nibado.projects.advent.Rectangle import javax.swing.text.html.HTML.Attribute.N class CharMap private constructor( val width: Int, val height: Int, var pen: Char = '#', private val chars: CharArray) { constructor(width: Int, height: Int, fill: Char = ' ', pen: Char = '#') : this( width, height, pen, CharArray(width * height) { fill }) private fun toIndex(p: Point) = toIndex(p.x, p.y) private fun toIndex(x: Int, y: Int) = x + y * width operator fun get(p: Point) = chars[toIndex(p)] operator fun get(x: Int, y: Int) = chars[toIndex(x, y)] operator fun set(p: Point, c: Char) { chars[toIndex(p)] = c } operator fun set(x: Int, y: Int, c: Char) { chars[toIndex(x, y)] = c } fun isEq(p: Point, c: Char) = if (!inBounds(p)) { false } else this[p] == c fun count(c: Char) = chars.count { it == c } fun count(set: Set<Char>) = chars.count { it in set } fun count(f: (Char) -> Boolean) = chars.count { f(it) } fun drawHorizontal(p: Point, amount: Int, c: Char = pen) { for (i in 0 until amount) { this[p.x + i, p.y] = c } } fun drawHorizontal(y: Int, xRange: IntRange, c: Char = pen) { for (x in xRange) { this[x, y] = c } } fun drawVertical(p: Point, amount: Int, c: Char = pen) { for (i in 0 until amount) { this[p.x, p.y + i] = c } } fun drawVertical(x: Int, yRange: IntRange, c: Char = pen) { for (y in yRange) { this[x, y] = c } } fun toString(rectangle: Rectangle) = toString(rectangle.left, rectangle.right) fun toString(topLeft: Point) = toString(topLeft, Point(width - 1, height - 1)) fun toString(topLeft: Point, bottomRight: Point): String { val builder = StringBuilder() for (y in topLeft.y..bottomRight.y) { for (x in topLeft.x..bottomRight.x) { builder.append(this[x, y]) } builder.append('\n') } return builder.toString() } fun points(f: (Char) -> Boolean = { true }) = (0 until height) .flatMap { y -> (0 until width).map { x -> Point(x, y) }} .filter { f(this[it]) } fun inBounds(p: Point) = inBounds(p.x, p.y) fun inBounds(x: Int, y: Int) = x in 0 until width && y in 0 until height override fun toString() = toString(Point(0, 0), Point(width - 1, height - 1)) fun clone() = CharMap(width, height, pen, chars.clone()) fun rotate90() : CharMap { val newMap = clone() for (i in 0 until width) { for (j in 0 until width) { newMap[j, width - i - 1] = this[i, j] } } return newMap } fun row(row: Int) : List<Char> = (0 until width).map { this[it, row] } fun rowFirst() = row(0) fun rowLast() = row(height - 1) fun column(column: Int) : List<Char> = (0 until height).map { this[column, it] } fun columnFirst() = column(0) fun columnLast() = column(width - 1) fun flipH() : CharMap { val new = clone() for(y in 0 until height) { for(x in 0 until width) { new[x, y] = this[width - x - 1, y] } } return new } fun flipV() : CharMap { val new = clone() for(y in 0 until height) { for(x in 0 until width) { new[x, y] = this[x, height - y - 1] } } return new } companion object { fun from(lines: List<String>) : CharMap { val input = lines.map { it.trim() }.filterNot { it.isEmpty() } if(input.isEmpty()) { throw IllegalArgumentException("List is empty") } val height = input.size val width = input.first().length if(input.any { it.length != width }) { throw IllegalArgumentException("All lines in input should be width $width") } val map = CharMap(width, height) input.indices.forEach { y -> input[y].indices.forEach { x -> map[x, y] = input[y][x] } } return map } fun from(s: String) = from(s.split('\n').map { it.trim() }) fun withSize(charMap: CharMap) = CharMap(charMap.width, charMap.height) } }
mit
81a5bc85ae8e6f926f45f6bef11ae6d0
27.175758
91
0.508281
3.623539
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/y2020/Day23.kt
1
1322
package com.nibado.projects.advent.y2020 import com.nibado.projects.advent.Day import com.nibado.projects.advent.collect.Link object Day23 : Day { private val input = "589174263".map { it - '0' } override fun part1() : Int { val game = runGame(input, 100) return game.linkSequence().first { it.value == 1 }.drop(1) .joinToString("") { it.toString() }.toInt() } override fun part2() : Long { val game = runGame(input + (10 .. 1_000_000), 10_000_000) val one = game.linkSequence().first { it.value == 1 } return one.next().value.toLong() * one.next().next().value.toLong() } private fun runGame(input: List<Int>, repeats: Int) : Link<Int> { var selected = Link.of(input) selected.lastLink().next = selected val index = selected.linkSequence().map { it.value to it }.toMap() val max = index.keys.maxOrNull()!! repeat(repeats) { move -> val removed = selected.remove(3) val next = selected.next() var dest = selected.value do { dest-- if(dest < 1) dest = max } while(dest in removed) index[dest]!!.addNext(removed) selected = next } return selected } }
mit
f19d2e272fdf59d60331533c2da7ef6d
26.5625
75
0.55295
3.888235
false
false
false
false
StepicOrg/stepik-android
app/src/stageDebuggable/java/org/stepik/android/view/debug/ui/adapter/delegate/InAppPurchaseAdapterDelegate.kt
1
2294
package org.stepik.android.view.debug.ui.adapter.delegate import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import com.android.billingclient.api.Purchase import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.stageDebuggable.item_in_app_purchase.* import org.stepic.droid.R import org.stepic.droid.util.DateTimeHelper import org.stepic.droid.util.toObject import org.stepik.android.domain.course.model.CoursePurchasePayload import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder import java.util.Date import java.util.TimeZone class InAppPurchaseAdapterDelegate( private val onItemClick: (Purchase) -> Unit ) : AdapterDelegate<Purchase, DelegateViewHolder<Purchase>>() { override fun isForViewType(position: Int, data: Purchase): Boolean = true override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<Purchase> = ViewHolder(createView(parent, R.layout.item_in_app_purchase)) private inner class ViewHolder(override val containerView: View) : DelegateViewHolder<Purchase>(containerView), LayoutContainer { init { inAppPurchaseConsumeAction.setOnClickListener { itemData?.let(onItemClick) } } override fun onBind(data: Purchase) { inAppPurchaseSku.text = data.skus.first() inAppPurchaseTime.text = context.getString(R.string.debug_purchase_date, DateTimeHelper.getPrintableDate(Date(data.purchaseTime), DateTimeHelper.DISPLAY_DATETIME_PATTERN, TimeZone.getDefault())) inAppPurchaseStatus.text = context.getString(R.string.debug_purchase_status, data.purchaseState.toString()) inAppPurchaseCourse.isVisible = data.developerPayload.isNotEmpty() inAppPurchaseUser.isVisible = data.developerPayload.isNotEmpty() if (data.developerPayload.isNotEmpty()) { data.developerPayload.toObject<CoursePurchasePayload>().let { inAppPurchaseCourse.text = context.getString(R.string.debug_purchase_course, it.courseId) inAppPurchaseUser.text = context.getString(R.string.debug_purchase_profile, it.profileId) } } } } }
apache-2.0
7f5bc2ac6e241c88078896bd617950cf
48.891304
206
0.746295
4.606426
false
false
false
false
allotria/intellij-community
plugins/git4idea/src/git4idea/log/GitBrowseRepoAtRevisionAction.kt
3
1596
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.log import com.intellij.dvcs.repo.AbstractRepositoryManager import com.intellij.dvcs.ui.VcsLogAction import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.impl.showRepositoryBrowser import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.containers.MultiMap import com.intellij.vcs.log.Hash import com.intellij.vcs.log.VcsFullCommitDetails import git4idea.i18n.GitBundle import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager class GitBrowseRepoAtRevisionAction : VcsLogAction<GitRepository>() { override fun actionPerformed(project: Project, grouped: MultiMap<GitRepository, VcsFullCommitDetails>) { val repo = grouped.keySet().single() val commit = grouped.values().single() val root = GitDirectoryVirtualFile(repo, null, "", commit) showRepositoryBrowser(project, root, repo.root, GitBundle.message("tab.title.repo.root.name.at.revision", repo.root.name, commit.id.toShortString())) } override fun isEnabled(grouped: MultiMap<GitRepository, Hash>): Boolean { return grouped.values().size == 1 } override fun getRepositoryManager(project: Project): AbstractRepositoryManager<GitRepository> { return GitRepositoryManager.getInstance(project) } override fun getRepositoryForRoot(project: Project, root: VirtualFile): GitRepository? { return getRepositoryManager(project).getRepositoryForRootQuick(root) } }
apache-2.0
01791c3b59dd824d4c638e2ee8ac820e
43.361111
140
0.785088
4.384615
false
false
false
false
Lomeli12/MCSlack
src/main/kotlin/net/lomeli/mcslack/KotlinAdapter.kt
1
3451
package net.lomeli.mcslack import net.minecraftforge.fml.common.ILanguageAdapter import net.minecraftforge.fml.common.FMLModContainer import net.minecraftforge.fml.common.ModContainer import net.minecraftforge.fml.relauncher.Side import org.apache.logging.log4j.LogManager import java.lang.reflect.Field import java.lang.reflect.Method /** * Kotlin implementation of FML's ILanguageAdapter. * * Use by setting <pre>modLanguageAdapter = "net.lomeli.mcslack.KotlinAdapter"</pre> in the Mod annotation. * Your Kotlin @Mod implementation <b>must</b> be an <pre>object</pre> type. * (Forge 1.8-11.14.1.1371 and Kotlin RC1 or above required) * * @author Arkan <[email protected]> * @author Carrot <[email protected]> */ @Suppress("UNUSED") class KotlinAdapter : ILanguageAdapter { private val logger = LogManager.getLogger("ILanguageAdapter/Kotlin") override fun setProxy(target: Field, proxyTarget: Class<*>, proxy: Any) { logger.debug("Setting proxy on target: {}.{} -> {}", target.declaringClass.simpleName, target.name, proxy) val instanceField = findInstanceFieldOrThrow(proxyTarget) val modObject = findModObjectOrThrow(instanceField) target.set(modObject, proxy) } override fun getNewInstance(container: FMLModContainer?, objectClass: Class<*>, classLoader: ClassLoader, factoryMarkedAnnotation: Method?): Any? { logger.debug("Constructing new instance of {}", objectClass.simpleName) val instanceField = findInstanceFieldOrThrow(objectClass) val modObject = findModObjectOrThrow(instanceField) return modObject } override fun supportsStatics() = false override fun setInternalProxies(mod: ModContainer?, side: Side?, loader: ClassLoader?) = Unit private fun findInstanceFieldOrThrow(targetClass: Class<*>): Field { val instanceField: Field = try { targetClass.getField("INSTANCE") } catch (exception: NoSuchFieldException) { throw noInstanceFieldException(exception) } catch (exception: SecurityException) { throw instanceSecurityException(exception) } return instanceField } private fun findModObjectOrThrow(instanceField: Field): Any { val modObject = try { instanceField.get(null) } catch (exception: IllegalArgumentException) { throw unexpectedInitializerSignatureException(exception) } catch (exception: IllegalAccessException) { throw wrongVisibilityOnInitializerException(exception) } return modObject } private fun noInstanceFieldException(exception: Exception) = KotlinAdapterException("Couldn't find INSTANCE singleton on Kotlin @Mod container", exception) private fun instanceSecurityException(exception: Exception) = KotlinAdapterException("Security violation accessing INSTANCE singleton on Kotlin @Mod container", exception) private fun unexpectedInitializerSignatureException(exception: Exception) = KotlinAdapterException("Kotlin @Mod object has an unexpected initializer signature, somehow?", exception) private fun wrongVisibilityOnInitializerException(exception: Exception) = KotlinAdapterException("Initializer on Kotlin @Mod object isn't `public`", exception) private class KotlinAdapterException(message: String, exception: Exception): RuntimeException("Kotlin adapter error - do not report to Forge! " + message, exception) }
lgpl-3.0
4065f1ae0e21c8d0d1766496a25f9fe6
43.25641
185
0.739496
4.682497
false
false
false
false
genonbeta/TrebleShot
app/src/main/java/org/monora/uprotocol/client/android/database/model/TransferDetail.kt
1
2109
/* * Copyright (C) 2021 Veli Tasalı * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.monora.uprotocol.client.android.database.model import androidx.room.DatabaseView import org.monora.uprotocol.client.android.model.ListItem import org.monora.uprotocol.core.protocol.Direction import org.monora.uprotocol.core.transfer.TransferItem.State.Constants.DONE @DatabaseView( viewName = "transferDetail", value = "SELECT transfer.id, transfer.location, transfer.clientUid, transfer.direction, transfer.dateCreated, " + "transfer.accepted, client.nickname AS clientNickname, COUNT(items.id) AS itemsCount, " + "COUNT(CASE WHEN items.state == '$DONE' THEN items.id END) as itemsDoneCount, SUM(items.size) AS size, " + "SUM(CASE WHEN items.state == '$DONE' THEN items.size END) as sizeOfDone FROM transfer " + "INNER JOIN client ON client.uid = transfer.clientUid " + "INNER JOIN transferItem items ON items.groupId = transfer.id GROUP BY items.groupId" ) data class TransferDetail( val id: Long, val clientUid: String, val clientNickname: String, val location: String, val direction: Direction, val size: Long, val accepted: Boolean, val sizeOfDone: Long, val itemsCount: Int, val itemsDoneCount: Int, val dateCreated: Long, ) : ListItem { override val listId: Long get() = id + javaClass.hashCode() }
gpl-2.0
a1983f44d7e6a6300cf2840e7efd9459
41.16
118
0.719639
4.101167
false
false
false
false
Lauwenmark/amanogawa
server/src/main/kotlin/eu/lauwenmark/amanogawa/server/auth/Auth.kt
1
2189
package eu.lauwenmark.amanogawa.server.eu.lauwenmark.amanogawa.server.auth import java.math.BigInteger import java.security.SecureRandom import javax.crypto.SecretKeyFactory import javax.crypto.spec.PBEKeySpec class User constructor(val name: String, val email: String, clearPassword: String? = null, hashPassword: String? = null) { val password: String init { if (clearPassword != null) { password = hash(clearPassword) } else if (hashPassword != null) { password = hashPassword } else { password = "" throw IllegalArgumentException("Empty password") } } } //Encryption from example at https://howtodoinjava.com/security/how-to-generate-secure-password-hash-md5-sha-pbkdf2-bcrypt-examples/ private fun salt() : ByteArray { val secureRandom = SecureRandom.getInstance("SHA1PRNG") val salt = ByteArray(16) secureRandom.nextBytes(salt) return salt } private fun hash(password: String, iterations: Int = 1000) : String { val chars = password.toCharArray() val salt = salt() val spec = PBEKeySpec(chars, salt, iterations, 64 * 8) val keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1") val hash = keyFactory.generateSecret(spec).encoded return "$iterations:${toHex(salt)}:${toHex(hash)}" } private fun toHex(array: ByteArray): String { val hex = BigInteger(1, array).toString(16) val paddingLength = (array.size * 2) - hex.length if (paddingLength > 0) { return String.format("%0"+paddingLength+"d", 0) + hex } else { return hex } } private fun fromHex(hex: String) : ByteArray { return BigInteger(hex, 16).toByteArray() } fun validate(password: String, key: String) : Boolean { val keyParts = key.split(":") val iterations = Integer.parseInt(keyParts[0]) val salt = fromHex(keyParts[1]) val hash = fromHex(keyParts[2]) val spec = PBEKeySpec(password.toCharArray(), salt, iterations, 64 * 8) val keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1") val testHash = keyFactory.generateSecret(spec).encoded return BigInteger(hash) == BigInteger(testHash) }
gpl-3.0
4b29bd1eaf2984081f6a29a316e80570
31.686567
132
0.686158
3.958409
false
false
false
false
android/compose-samples
Jetcaster/app/src/main/java/com/example/jetcaster/Graph.kt
1
3720
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetcaster import android.content.Context import androidx.room.Room import com.example.jetcaster.data.CategoryStore import com.example.jetcaster.data.EpisodeStore import com.example.jetcaster.data.PodcastStore import com.example.jetcaster.data.PodcastsFetcher import com.example.jetcaster.data.PodcastsRepository import com.example.jetcaster.data.room.JetcasterDatabase import com.example.jetcaster.data.room.TransactionRunner import com.rometools.rome.io.SyndFeedInput import java.io.File import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import okhttp3.Cache import okhttp3.OkHttpClient import okhttp3.logging.LoggingEventListener /** * A very simple global singleton dependency graph. * * For a real app, you would use something like Hilt/Dagger instead. */ object Graph { lateinit var okHttpClient: OkHttpClient lateinit var database: JetcasterDatabase private set private val transactionRunner: TransactionRunner get() = database.transactionRunnerDao() private val syndFeedInput by lazy { SyndFeedInput() } val podcastRepository by lazy { PodcastsRepository( podcastsFetcher = podcastFetcher, podcastStore = podcastStore, episodeStore = episodeStore, categoryStore = categoryStore, transactionRunner = transactionRunner, mainDispatcher = mainDispatcher ) } private val podcastFetcher by lazy { PodcastsFetcher( okHttpClient = okHttpClient, syndFeedInput = syndFeedInput, ioDispatcher = ioDispatcher ) } val podcastStore by lazy { PodcastStore( podcastDao = database.podcastsDao(), podcastFollowedEntryDao = database.podcastFollowedEntryDao(), transactionRunner = transactionRunner ) } val episodeStore by lazy { EpisodeStore( episodesDao = database.episodesDao() ) } val categoryStore by lazy { CategoryStore( categoriesDao = database.categoriesDao(), categoryEntryDao = database.podcastCategoryEntryDao(), episodesDao = database.episodesDao(), podcastsDao = database.podcastsDao() ) } private val mainDispatcher: CoroutineDispatcher get() = Dispatchers.Main private val ioDispatcher: CoroutineDispatcher get() = Dispatchers.IO fun provide(context: Context) { okHttpClient = OkHttpClient.Builder() .cache(Cache(File(context.cacheDir, "http_cache"), (20 * 1024 * 1024).toLong())) .apply { if (BuildConfig.DEBUG) eventListenerFactory(LoggingEventListener.Factory()) } .build() database = Room.databaseBuilder(context, JetcasterDatabase::class.java, "data.db") // This is not recommended for normal apps, but the goal of this sample isn't to // showcase all of Room. .fallbackToDestructiveMigration() .build() } }
apache-2.0
3d19bf0d3eab91ccc65303145a0a142a
31.631579
92
0.687903
4.856397
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetEditorGeneralTab.kt
1
20466
// 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.facet import com.intellij.facet.ui.* import com.intellij.ide.actions.ShowSettingsUtilImpl import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.util.NlsSafe import com.intellij.ui.HoverHyperlinkLabel import com.intellij.util.ui.FormBuilder import com.intellij.util.ui.ThreeStateCheckBox import org.jetbrains.kotlin.cli.common.arguments.* import org.jetbrains.kotlin.config.* import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.compiler.configuration.* import org.jetbrains.kotlin.idea.core.util.onTextChange import org.jetbrains.kotlin.idea.roots.invalidateProjectRoots import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.platform.* import org.jetbrains.kotlin.platform.js.isJs import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.platform.jvm.isJvm import java.awt.BorderLayout import java.awt.Component import javax.swing.* import javax.swing.border.EmptyBorder import kotlin.reflect.full.findAnnotation class KotlinFacetEditorGeneralTab( private val configuration: KotlinFacetConfiguration, private val editorContext: FacetEditorContext, private val validatorsManager: FacetValidatorsManager ) : FacetEditorTab() { //TODO(auskov): remove this hack as far as inconsistent equals in JdkPlatform is removed // what it actually does: if version of JVM target platform changed the TargetPlatform will // return true because equals in JvmPlatform is declared in the following way: // override fun equals(other: Any?): Boolean = other is JdkPlatform class TargetPlatformWrapper(val targetPlatform: TargetPlatform) { override fun equals(other: Any?): Boolean { if (other is TargetPlatformWrapper) { if (this.targetPlatform == other.targetPlatform) { return if (this.targetPlatform.size == 1) { this.targetPlatform.componentPlatforms.singleOrNull() === other.targetPlatform.componentPlatforms.singleOrNull() } else { true } } } return false } } class EditorComponent( private val project: Project, private val configuration: KotlinFacetConfiguration? ) : JPanel(BorderLayout()) { private val isMultiEditor: Boolean get() = configuration == null private lateinit var editableCommonArguments: CommonCompilerArguments private lateinit var editableJvmArguments: K2JVMCompilerArguments private lateinit var editableJsArguments: K2JSCompilerArguments private lateinit var editableCompilerSettings: CompilerSettings lateinit var compilerConfigurable: KotlinCompilerConfigurableTab private set lateinit var useProjectSettingsCheckBox: ThreeStateCheckBox // UI components related to MPP target platforms lateinit var targetPlatformSelectSingleCombobox: ComboBox<TargetPlatformWrapper> lateinit var dependsOnLabel: JLabel lateinit var targetPlatformWrappers: List<TargetPlatformWrapper> lateinit var targetPlatformLabel: JLabel //JTextField? var targetPlatformsCurrentlySelected: TargetPlatform? = null private lateinit var projectSettingsLink: HoverHyperlinkLabel private fun FormBuilder.addTargetPlatformComponents(): FormBuilder { return if (configuration?.settings?.mppVersion?.isHmpp == true) { targetPlatformLabel.toolTipText = KotlinBundle.message("facet.label.text.the.project.is.imported.from.external.build.system.and.could.not.be.edited") this.addLabeledComponent( KotlinBundle.message("facet.label.text.selected.target.platforms"), targetPlatformLabel) } else { this.addLabeledComponent( KotlinBundle.message("facet.label.text.target.platform"), targetPlatformSelectSingleCombobox) } } // Fixes sorting of JVM versions. // JVM 1.6, ... JVM 1.8 -> unchanged // JVM 9 -> JVM 1.9 // JVM 11.. -> unchanged // As result JVM 1.8 < JVM 1.9 < JVM 11 in UI representation private fun unifyJvmVersion(version: String) = if (version.equals("JVM 9")) "JVM 1.9" else version // Returns maxRowsCount for combobox. // Try to show whole the list at one, but do not show more than 15 elements at once. 10 elements returned otherwise private fun targetPlatformsComboboxRowsCount(targetPlatforms: Int) = if (targetPlatforms <= 15) { targetPlatforms } else { 10 } fun initialize() { if (isMultiEditor) { editableCommonArguments = object : CommonCompilerArguments() {} editableJvmArguments = K2JVMCompilerArguments() editableJsArguments = K2JSCompilerArguments() editableCompilerSettings = CompilerSettings() } else { editableCommonArguments = configuration!!.settings.compilerArguments!! editableJvmArguments = editableCommonArguments as? K2JVMCompilerArguments ?: Kotlin2JvmCompilerArgumentsHolder.getInstance(project).settings.unfrozen() editableJsArguments = editableCommonArguments as? K2JSCompilerArguments ?: Kotlin2JsCompilerArgumentsHolder.getInstance(project).settings.unfrozen() editableCompilerSettings = configuration.settings.compilerSettings!! } compilerConfigurable = KotlinCompilerConfigurableTab( project, editableCommonArguments, editableJsArguments, editableJvmArguments, editableCompilerSettings, null, false, isMultiEditor ) useProjectSettingsCheckBox = ThreeStateCheckBox(KotlinBundle.message("facet.checkbox.text.use.project.settings")).apply { isThirdStateEnabled = isMultiEditor } dependsOnLabel = JLabel() targetPlatformWrappers = CommonPlatforms.allDefaultTargetPlatforms.sortedBy { unifyJvmVersion(it.oldFashionedDescription) } .map { TargetPlatformWrapper(it) } targetPlatformLabel = JLabel() //JTextField()? targetPlatformLabel.isEditable = false targetPlatformSelectSingleCombobox = ComboBox(targetPlatformWrappers.toTypedArray()).apply { setRenderer(object : DefaultListCellRenderer() { override fun getListCellRendererComponent( list: JList<*>?, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean ): Component { return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus).apply { text = (value as? TargetPlatformWrapper)?.targetPlatform?.componentPlatforms?.singleOrNull() ?.oldFashionedDescription ?: KotlinBundle.message("facet.text.multiplatform") } } }) } targetPlatformSelectSingleCombobox.maximumRowCount = targetPlatformsComboboxRowsCount(targetPlatformWrappers.size) projectSettingsLink = HoverHyperlinkLabel(KotlinBundle.message("facet.link.text.edit.project.settings")).apply { addHyperlinkListener { ShowSettingsUtilImpl.showSettingsDialog(project, compilerConfigurable.id, "") if (useProjectSettingsCheckBox.isSelected) { updateCompilerConfigurable() } } } val contentPanel = FormBuilder .createFormBuilder() .addComponent(JPanel(BorderLayout()).apply { add(useProjectSettingsCheckBox, BorderLayout.WEST) add(projectSettingsLink, BorderLayout.EAST) }).addTargetPlatformComponents() .addComponent(dependsOnLabel) .addComponent(compilerConfigurable.createComponent()!!.apply { border = null }) .panel .apply { border = EmptyBorder(10, 10, 10, 10) } add(contentPanel, BorderLayout.NORTH) useProjectSettingsCheckBox.addActionListener { updateCompilerConfigurable() } targetPlatformSelectSingleCombobox.addActionListener { updateCompilerConfigurable() } } internal fun updateCompilerConfigurable() { val useProjectSettings = useProjectSettingsCheckBox.isSelected compilerConfigurable.setTargetPlatform(getChosenPlatform()?.idePlatformKind) compilerConfigurable.setEnabled(!useProjectSettings) if (useProjectSettings) { compilerConfigurable.commonCompilerArguments = KotlinCommonCompilerArgumentsHolder.getInstance(project).settings.unfrozen() compilerConfigurable.k2jvmCompilerArguments = Kotlin2JvmCompilerArgumentsHolder.getInstance(project).settings.unfrozen() compilerConfigurable.k2jsCompilerArguments = Kotlin2JsCompilerArgumentsHolder.getInstance(project).settings.unfrozen() compilerConfigurable.compilerSettings = KotlinCompilerSettings.getInstance(project).settings.unfrozen() } else { compilerConfigurable.commonCompilerArguments = editableCommonArguments compilerConfigurable.k2jvmCompilerArguments = editableJvmArguments compilerConfigurable.k2jsCompilerArguments = editableJsArguments compilerConfigurable.compilerSettings = editableCompilerSettings } compilerConfigurable.reset() } fun getChosenPlatform(): TargetPlatform? { return if (configuration?.settings?.mppVersion?.isHmpp == true) { targetPlatformsCurrentlySelected } else { targetPlatformSelectSingleCombobox.selectedItemTyped?.targetPlatform } } } inner class ArgumentConsistencyValidator : FacetEditorValidator() { override fun check(): ValidationResult { val platform = editor.getChosenPlatform() ?: return ValidationResult( KotlinBundle.message("facet.error.text.at.least.one.target.platform.should.be.selected")) val primaryArguments = platform.createArguments { editor.compilerConfigurable.applyTo( this, this as? K2JVMCompilerArguments ?: K2JVMCompilerArguments(), this as? K2JSCompilerArguments ?: K2JSCompilerArguments(), CompilerSettings() ) } val argumentClass = primaryArguments.javaClass val additionalArguments = argumentClass.newInstance().apply { parseCommandLineArguments(splitArgumentString(editor.compilerConfigurable.additionalArgsOptionsField.text), this) validateArguments(errors)?.let { message -> return ValidationResult(message) } } val emptyArguments = argumentClass.newInstance() val fieldNamesToCheck = when { platform.isJvm() -> jvmUIExposedFields platform.isJs() -> jsUIExposedFields platform.isCommon() -> metadataUIExposedFields else -> commonUIExposedFields } val propertiesToCheck = collectProperties(argumentClass.kotlin, false).filter { it.name in fieldNamesToCheck } val overridingArguments = ArrayList<String>() val redundantArguments = ArrayList<String>() for (property in propertiesToCheck) { val additionalValue = property.get(additionalArguments) if (additionalValue != property.get(emptyArguments)) { val argumentInfo = property.findAnnotation<Argument>() ?: continue val addTo = if (additionalValue != property.get(primaryArguments)) overridingArguments else redundantArguments addTo += "<strong>" + argumentInfo.value.first() + "</strong>" } } if (overridingArguments.isNotEmpty() || redundantArguments.isNotEmpty()) { @NlsSafe val message = buildString { if (overridingArguments.isNotEmpty()) { append( KotlinBundle.message( "facet.text.following.arguments.override.facet.settings", overridingArguments.joinToString() ) ) } if (redundantArguments.isNotEmpty()) { if (isNotEmpty()) { append("<br/>") } append( KotlinBundle.message("facet.text.following.arguments.are.redundant", redundantArguments.joinToString())) } } return ValidationResult(message) } return ValidationResult.OK } } private var isInitialized = false val editor by lazy { EditorComponent(editorContext.project, configuration) } private var enableValidation = false private fun onLanguageLevelChanged() { with(editor.compilerConfigurable) { onLanguageLevelChanged(selectedLanguageVersionView) } } private fun JTextField.validateOnChange() { onTextChange { doValidate() } } private fun AbstractButton.validateOnChange() { addChangeListener { doValidate() } } private fun JComboBox<*>.validateOnChange() { addActionListener { doValidate() } } private fun validateOnce(body: () -> Unit) { enableValidation = false body() enableValidation = true doValidate() } private fun doValidate() { if (enableValidation) { validatorsManager.validate() } } fun initializeIfNeeded() { if (isInitialized) return editor.initialize() for (creator in KotlinFacetValidatorCreator.EP_NAME.getExtensions()) { validatorsManager.registerValidator(creator.create(editor, validatorsManager, editorContext)) } validatorsManager.registerValidator(ArgumentConsistencyValidator()) with(editor.compilerConfigurable) { reportWarningsCheckBox.validateOnChange() additionalArgsOptionsField.textField.validateOnChange() generateSourceMapsCheckBox.validateOnChange() outputPrefixFile.textField.validateOnChange() outputPostfixFile.textField.validateOnChange() outputDirectory.textField.validateOnChange() copyRuntimeFilesCheckBox.validateOnChange() moduleKindComboBox.validateOnChange() languageVersionComboBox.addActionListener { onLanguageLevelChanged() doValidate() } apiVersionComboBox.validateOnChange() } editor.targetPlatformSelectSingleCombobox.validateOnChange() editor.updateCompilerConfigurable() isInitialized = true reset() } override fun onTabEntering() { initializeIfNeeded() } override fun isModified(): Boolean { if (!isInitialized) return false if (editor.useProjectSettingsCheckBox.isSelected != configuration.settings.useProjectSettings) return true val chosenPlatform = editor.getChosenPlatform() if (chosenPlatform != configuration.settings.targetPlatform) return true // work-around for hacked equals in JvmPlatform if (!configuration.settings.mppVersion.isHmpp) { if (configuration.settings.targetPlatform?.let { TargetPlatformWrapper(it) } != editor.targetPlatformSelectSingleCombobox .selectedItemTyped) { return true } } val chosenSingle = chosenPlatform?.componentPlatforms?.singleOrNull() if (chosenSingle != null && chosenSingle == JvmPlatforms.defaultJvmPlatform) { if (chosenSingle !== configuration.settings.targetPlatform) { return true } } return !editor.useProjectSettingsCheckBox.isSelected && editor.compilerConfigurable.isModified } override fun reset() { if (!isInitialized) return validateOnce { editor.useProjectSettingsCheckBox.isSelected = configuration.settings.useProjectSettings editor.targetPlatformsCurrentlySelected = configuration.settings.targetPlatform editor.targetPlatformLabel.text = editor.targetPlatformsCurrentlySelected?.componentPlatforms?.map { it.oldFashionedDescription.trim() }?.joinToString(", ") ?: "<none>" editor.dependsOnLabel.isVisible = configuration.settings.dependsOnModuleNames.isNotEmpty() editor.dependsOnLabel.text = KotlinBundle.message("facets.editor.general.tab.label.depends.on.0", configuration.settings.dependsOnModuleNames.joinToString()) editor.targetPlatformSelectSingleCombobox.selectedItem = configuration.settings.targetPlatform?.let { val index = editor.targetPlatformWrappers.indexOf(TargetPlatformWrapper(it)) if (index >= 0) { editor.targetPlatformWrappers[index] } else { null } } editor.compilerConfigurable.reset() editor.updateCompilerConfigurable() } } override fun apply() { initializeIfNeeded() validateOnce { editor.compilerConfigurable.apply() with(configuration.settings) { useProjectSettings = editor.useProjectSettingsCheckBox.isSelected editor.getChosenPlatform()?.let { if (it != targetPlatform || isModified // work-around due to hacked equals ) { val platformArguments = when { it.isJvm() -> editor.compilerConfigurable.k2jvmCompilerArguments it.isJs() -> editor.compilerConfigurable.k2jsCompilerArguments else -> null } compilerArguments = it.createArguments { if (platformArguments != null) { mergeBeans(platformArguments, this) } copyInheritedFields(compilerArguments!!, this) } } } configuration.settings.targetPlatform = editor.getChosenPlatform() updateMergedArguments() // Force code analysis with modified settings runWriteAction { editorContext.project.invalidateProjectRoots() } } } } override fun getDisplayName() = KotlinBundle.message("facet.name.general") override fun createComponent(): JComponent { return editor } override fun disposeUIResources() { if (isInitialized) { editor.compilerConfigurable.disposeUIResources() } } } @Suppress("UNCHECKED_CAST") val <T> ComboBox<T>.selectedItemTyped: T? get() = selectedItem as T?
apache-2.0
59702b5d50ec91bd29042590c22be156
44.178808
171
0.621567
6.112903
false
true
false
false
cout970/Modeler
src/main/kotlin/com/cout970/reactive/nodes/RComponent.kt
1
997
package com.cout970.reactive.nodes import com.cout970.reactive.core.* import org.liquidengine.legui.component.Component import java.lang.reflect.Modifier import kotlin.reflect.KClass class RComponentDescriptor<P : RProps, T : RComponent<P, *>>(val clazz: Class<T>, val props: P) : RDescriptor { init { require(!Modifier.isAbstract(clazz.modifiers)) { "Invalid class $clazz, It must not be abstract" } } override fun mapToComponent(): Component = throw IllegalStateException("This descriptor needs a special treatment!") } fun <P : RProps, T : RComponent<P, *>> RBuilder.child(clazz: KClass<T>, props: P, key: String? = null) = child(clazz.java, props, key) fun <T : RComponent<EmptyProps, *>> RBuilder.child(clazz: KClass<T>, key: String? = null) = child(clazz.java, EmptyProps, key) fun <P : RProps, T : RComponent<P, *>> RBuilder.child(clazz: Class<T>, props: P, key: String? = null) = +RNode(key, RComponentDescriptor(clazz, props))
gpl-3.0
435aa5b6adad1c91c7a7804465426956
34.607143
120
0.691073
3.548043
false
false
false
false
MilosKozak/AndroidAPS
app/src/main/java/info/nightscout/androidaps/utils/TirCalculator.kt
3
3600
package info.nightscout.androidaps.utils import android.text.Spanned import android.util.LongSparseArray import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile object TirCalculator { fun calculate(days: Long, lowMgdl: Double, highMgdl: Double): LongSparseArray<TIR> { if (lowMgdl < 39) throw RuntimeException("Low below 39") if (lowMgdl > highMgdl) throw RuntimeException("Low > High") val startTime = MidnightTime.calc(DateUtil.now()) - T.days(days).msecs() val endTime = MidnightTime.calc(DateUtil.now()) val bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime(startTime, endTime, true) val result = LongSparseArray<TIR>() for (bg in bgReadings) { val midnight = MidnightTime.calc(bg.date) var tir = result[midnight] if (tir == null) { tir = TIR(midnight, lowMgdl, highMgdl) result.append(midnight, tir) } if (bg.value < 39) tir.error() if (bg.value >= 39 && bg.value < lowMgdl) tir.below() if (bg.value in lowMgdl..highMgdl) tir.inRange() if (bg.value > highMgdl) tir.above() } return result } fun averageTIR(tirs: LongSparseArray<TIR>): TIR { val totalTir = if (tirs.size() > 0) { TIR(tirs.valueAt(0).date, tirs.valueAt(0).lowThreshold, tirs.valueAt(0).highThreshold) } else { TIR(7, 70.0, 180.0) } for (i in 0 until tirs.size()) { val tir = tirs.valueAt(i) totalTir.below += tir.below totalTir.inRange += tir.inRange totalTir.above += tir.above totalTir.error += tir.error totalTir.count += tir.count } return totalTir } fun stats(): Spanned { val lowTirMgdl = Constants.STATS_RANGE_LOW_MMOL * Constants.MMOLL_TO_MGDL val highTirMgdl = Constants.STATS_RANGE_HIGH_MMOL * Constants.MMOLL_TO_MGDL val lowTitMgdl = Constants.STATS_TARGET_LOW_MMOL * Constants.MMOLL_TO_MGDL val highTitMgdl = Constants.STATS_TARGET_HIGH_MMOL * Constants.MMOLL_TO_MGDL val tir7 = calculate(7, lowTirMgdl, highTirMgdl) val averageTir7 = averageTIR(tir7) val tir30 = calculate(30, lowTirMgdl, highTirMgdl) val averageTir30 = averageTIR(tir30) val tit7 = calculate(7, lowTitMgdl, highTitMgdl) val averageTit7 = averageTIR(tit7) val tit30 = calculate(30, lowTitMgdl, highTitMgdl) val averageTit30 = averageTIR(tit30) return HtmlHelper.fromHtml( "<br><b>" + MainApp.gs(R.string.tir) + ":</b><br>" + toText(tir7) + "<br><b>" + MainApp.gs(R.string.average) + " (" + Profile.toCurrentUnitsString(lowTirMgdl) + "-" + Profile.toCurrentUnitsString(highTirMgdl) + "):</b><br>" + averageTir7.toText(tir7.size()) + "<br>" + averageTir30.toText(tir30.size()) + "<br><b>" + MainApp.gs(R.string.average) + " (" + Profile.toCurrentUnitsString(lowTitMgdl) + "-" + Profile.toCurrentUnitsString(highTitMgdl) + "):</b><br>" + averageTit7.toText(tit7.size()) + "<br>" + averageTit30.toText(tit30.size()) ) } fun toText(tirs: LongSparseArray<TIR>): String { var t = "" for (i in 0 until tirs.size()) { t += "${tirs.valueAt(i).toText()}<br>" } return t } }
agpl-3.0
0314c59f8270943f350f2be7742e03c0
41.364706
173
0.599167
3.488372
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/inlineUtils.kt
1
4686
// 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.refactoring.inline import com.intellij.codeInsight.TargetElementUtil import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.NlsContexts import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.util.CommonRefactoringUtil import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.codeInliner.CodeToInline import org.jetbrains.kotlin.idea.codeInliner.CodeToInlineBuilder import org.jetbrains.kotlin.idea.intentions.ConvertReferenceToLambdaIntention import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull internal fun buildCodeToInline( declaration: KtDeclaration, bodyOrInitializer: KtExpression, isBlockBody: Boolean, editor: Editor?, fallbackToSuperCall: Boolean, ): CodeToInline? { val descriptor = declaration.unsafeResolveToDescriptor() val builder = CodeToInlineBuilder( targetCallable = descriptor as CallableDescriptor, resolutionFacade = declaration.getResolutionFacade(), originalDeclaration = declaration, fallbackToSuperCall = fallbackToSuperCall, ) val expressionMapper: (KtExpression) -> Pair<KtExpression?, List<KtExpression>>? = if (isBlockBody) { fun(bodyOrInitializer: KtExpression): Pair<KtExpression?, List<KtExpression>>? { bodyOrInitializer as KtBlockExpression val statements = bodyOrInitializer.statements val returnStatements = bodyOrInitializer.collectDescendantsOfType<KtReturnExpression> { val function = it.getStrictParentOfType<KtFunction>() if (function != null && function != declaration) return@collectDescendantsOfType false it.getLabelName().let { label -> label == null || label == declaration.name } } val lastReturn = statements.lastOrNull() as? KtReturnExpression if (returnStatements.any { it != lastReturn }) { val message = RefactoringBundle.getCannotRefactorMessage( if (returnStatements.size > 1) KotlinBundle.message("error.text.inline.function.is.not.supported.for.functions.with.multiple.return.statements") else KotlinBundle.message("error.text.inline.function.is.not.supported.for.functions.with.return.statements.not.at.the.end.of.the.body") ) CommonRefactoringUtil.showErrorHint( declaration.project, editor, message, KotlinBundle.message("title.inline.function"), null ) return null } return lastReturn?.returnedExpression to statements.dropLast(returnStatements.size) } } else { { it to emptyList() } } return builder.prepareCodeToInlineWithAdvancedResolution( bodyOrExpression = bodyOrInitializer, expressionMapper = expressionMapper, ) } fun Editor.findSimpleNameReference(): PsiReference? { val reference = TargetElementUtil.findReference(this, caretModel.offset) ?: return null return when { reference.element.language != KotlinLanguage.INSTANCE -> reference reference is KtSimpleNameReference -> reference reference is PsiMultiReference -> reference.references.firstIsInstanceOrNull<KtSimpleNameReference>() else -> null } } fun findCallableConflictForUsage(usage: PsiElement): @NlsContexts.DialogMessage String? { val usageParent = usage.parent as? KtCallableReferenceExpression ?: return null if (usageParent.callableReference != usage) return null if (ConvertReferenceToLambdaIntention.isApplicableTo(usageParent)) return null return KotlinBundle.message("text.reference.cannot.be.converted.to.a.lambda") }
apache-2.0
59d3b8b4e1f31153c37514d8bd67494f
45.39604
158
0.727059
5.288939
false
false
false
false
MikeOrtiz/TouchImageView
touchview/src/main/java/com/ortiz/touchview/TouchImageView.kt
1
51931
package com.ortiz.touchview import android.content.Context import android.content.res.Configuration import android.graphics.* import android.graphics.drawable.Drawable import android.net.Uri import android.os.Bundle import android.os.Parcelable import android.util.AttributeSet import android.view.GestureDetector import android.view.GestureDetector.OnDoubleTapListener import android.view.GestureDetector.SimpleOnGestureListener import android.view.MotionEvent import android.view.ScaleGestureDetector import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener import android.view.View import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.LinearInterpolator import android.widget.OverScroller import androidx.appcompat.widget.AppCompatImageView import kotlin.math.abs import kotlin.math.max import kotlin.math.min @Suppress("unused") open class TouchImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : AppCompatImageView(context, attrs, defStyle) { /** * Get the current zoom. This is the zoom relative to the initial * scale, not the original resource. * * @return current zoom multiplier. */ // Scale of image ranges from minScale to maxScale, where minScale == 1 // when the image is stretched to fit view. var currentZoom = 0f private set // Matrix applied to image. MSCALE_X and MSCALE_Y should always be equal. // MTRANS_X and MTRANS_Y are the other values used. prevMatrix is the matrix saved prior to the screen rotating. private var touchMatrix: Matrix private var prevMatrix: Matrix var isZoomEnabled = false private var isRotateImageToFitScreen = false var orientationChangeFixedPixel: FixedPixel? = FixedPixel.CENTER var viewSizeChangeFixedPixel: FixedPixel? = FixedPixel.CENTER private var orientationJustChanged = false private var imageActionState: ImageActionState? = null private var userSpecifiedMinScale = 0f private var minScale = 0f private var maxScaleIsSetByMultiplier = false private var maxScaleMultiplier = 0f private var maxScale = 0f private var superMinScale = 0f private var superMaxScale = 0f private var floatMatrix: FloatArray /** * Set custom zoom multiplier for double tap. * By default maxScale will be used as value for double tap zoom multiplier. * */ var doubleTapScale = 0f private var fling: Fling? = null private var orientation = 0 private var touchScaleType: ScaleType? = null private var imageRenderedAtLeastOnce = false private var onDrawReady = false private var delayedZoomVariables: ZoomVariables? = null // Size of view and previous view size (ie before rotation) private var viewWidth = 0 private var viewHeight = 0 private var prevViewWidth = 0 private var prevViewHeight = 0 // Size of image when it is stretched to fit view. Before and After rotation. private var matchViewWidth = 0f private var matchViewHeight = 0f private var prevMatchViewWidth = 0f private var prevMatchViewHeight = 0f private var scaleDetector: ScaleGestureDetector private var gestureDetector: GestureDetector private var touchCoordinatesListener: OnTouchCoordinatesListener? = null private var doubleTapListener: OnDoubleTapListener? = null private var userTouchListener: OnTouchListener? = null private var touchImageViewListener: OnTouchImageViewListener? = null init { super.setClickable(true) orientation = resources.configuration.orientation scaleDetector = ScaleGestureDetector(context, ScaleListener()) gestureDetector = GestureDetector(context, GestureListener()) touchMatrix = Matrix() prevMatrix = Matrix() floatMatrix = FloatArray(9) currentZoom = 1f if (touchScaleType == null) { touchScaleType = ScaleType.FIT_CENTER } minScale = 1f maxScale = 3f superMinScale = SUPER_MIN_MULTIPLIER * minScale superMaxScale = SUPER_MAX_MULTIPLIER * maxScale imageMatrix = touchMatrix scaleType = ScaleType.MATRIX setState(ImageActionState.NONE) onDrawReady = false super.setOnTouchListener(PrivateOnTouchListener()) val attributes = context.theme.obtainStyledAttributes(attrs, R.styleable.TouchImageView, defStyle, 0) try { if (!isInEditMode) { isZoomEnabled = attributes.getBoolean(R.styleable.TouchImageView_zoom_enabled, true) } } finally { // release the TypedArray so that it can be reused. attributes.recycle() } } fun setRotateImageToFitScreen(rotateImageToFitScreen: Boolean) { isRotateImageToFitScreen = rotateImageToFitScreen } override fun setOnTouchListener(onTouchListener: OnTouchListener?) { userTouchListener = onTouchListener } fun setOnTouchImageViewListener(onTouchImageViewListener: OnTouchImageViewListener) { touchImageViewListener = onTouchImageViewListener } fun setOnDoubleTapListener(onDoubleTapListener: OnDoubleTapListener) { doubleTapListener = onDoubleTapListener } fun setOnTouchCoordinatesListener(onTouchCoordinatesListener: OnTouchCoordinatesListener) { touchCoordinatesListener = onTouchCoordinatesListener } override fun setImageResource(resId: Int) { imageRenderedAtLeastOnce = false super.setImageResource(resId) savePreviousImageValues() fitImageToView() } override fun setImageBitmap(bm: Bitmap?) { imageRenderedAtLeastOnce = false super.setImageBitmap(bm) savePreviousImageValues() fitImageToView() } override fun setImageDrawable(drawable: Drawable?) { imageRenderedAtLeastOnce = false super.setImageDrawable(drawable) savePreviousImageValues() fitImageToView() } override fun setImageURI(uri: Uri?) { imageRenderedAtLeastOnce = false super.setImageURI(uri) savePreviousImageValues() fitImageToView() } override fun setScaleType(type: ScaleType) { if (type == ScaleType.MATRIX) { super.setScaleType(ScaleType.MATRIX) } else { touchScaleType = type if (onDrawReady) { // If the image is already rendered, scaleType has been called programmatically // and the TouchImageView should be updated with the new scaleType. setZoom(this) } } } override fun getScaleType() = touchScaleType!! /** * Returns false if image is in initial, unzoomed state. False, otherwise. * * @return true if image is zoomed */ val isZoomed: Boolean get() = currentZoom != 1f /** * Return a Rect representing the zoomed image. * * @return rect representing zoomed image */ val zoomedRect: RectF get() { if (touchScaleType == ScaleType.FIT_XY) { throw UnsupportedOperationException("getZoomedRect() not supported with FIT_XY") } val topLeft = transformCoordTouchToBitmap(0f, 0f, true) val bottomRight = transformCoordTouchToBitmap(viewWidth.toFloat(), viewHeight.toFloat(), true) val w = getDrawableWidth(drawable).toFloat() val h = getDrawableHeight(drawable).toFloat() return RectF(topLeft.x / w, topLeft.y / h, bottomRight.x / w, bottomRight.y / h) } /** * Save the current matrix and view dimensions * in the prevMatrix and prevView variables. */ fun savePreviousImageValues() { if (viewHeight != 0 && viewWidth != 0) { touchMatrix.getValues(floatMatrix) prevMatrix.setValues(floatMatrix) prevMatchViewHeight = matchViewHeight prevMatchViewWidth = matchViewWidth prevViewHeight = viewHeight prevViewWidth = viewWidth } } public override fun onSaveInstanceState(): Parcelable? { val bundle = Bundle() bundle.putParcelable("instanceState", super.onSaveInstanceState()) bundle.putInt("orientation", orientation) bundle.putFloat("saveScale", currentZoom) bundle.putFloat("matchViewHeight", matchViewHeight) bundle.putFloat("matchViewWidth", matchViewWidth) bundle.putInt("viewWidth", viewWidth) bundle.putInt("viewHeight", viewHeight) touchMatrix.getValues(floatMatrix) bundle.putFloatArray("matrix", floatMatrix) bundle.putBoolean("imageRendered", imageRenderedAtLeastOnce) bundle.putSerializable("viewSizeChangeFixedPixel", viewSizeChangeFixedPixel) bundle.putSerializable("orientationChangeFixedPixel", orientationChangeFixedPixel) return bundle } public override fun onRestoreInstanceState(state: Parcelable) { if (state is Bundle) { currentZoom = state.getFloat("saveScale") floatMatrix = state.getFloatArray("matrix")!! prevMatrix.setValues(floatMatrix) prevMatchViewHeight = state.getFloat("matchViewHeight") prevMatchViewWidth = state.getFloat("matchViewWidth") prevViewHeight = state.getInt("viewHeight") prevViewWidth = state.getInt("viewWidth") imageRenderedAtLeastOnce = state.getBoolean("imageRendered") viewSizeChangeFixedPixel = state.getSerializable("viewSizeChangeFixedPixel") as FixedPixel? orientationChangeFixedPixel = state.getSerializable("orientationChangeFixedPixel") as FixedPixel? val oldOrientation = state.getInt("orientation") if (orientation != oldOrientation) { orientationJustChanged = true } super.onRestoreInstanceState(state.getParcelable("instanceState")) return } super.onRestoreInstanceState(state) } override fun onDraw(canvas: Canvas) { onDrawReady = true imageRenderedAtLeastOnce = true if (delayedZoomVariables != null) { setZoom(delayedZoomVariables!!.scale, delayedZoomVariables!!.focusX, delayedZoomVariables!!.focusY, delayedZoomVariables!!.scaleType) delayedZoomVariables = null } super.onDraw(canvas) } public override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) val newOrientation = resources.configuration.orientation if (newOrientation != orientation) { orientationJustChanged = true orientation = newOrientation } savePreviousImageValues() } /** * Set the max zoom multiplier to a constant. Default value: 3. * @return max zoom multiplier. */ var maxZoom: Float get() = maxScale set(max) { maxScale = max superMaxScale = SUPER_MAX_MULTIPLIER * maxScale maxScaleIsSetByMultiplier = false } /** * Set the max zoom multiplier as a multiple of minZoom, whatever minZoom may change to. By * default, this is not done, and maxZoom has a fixed value of 3. * * @param max max zoom multiplier, as a multiple of minZoom */ fun setMaxZoomRatio(max: Float) { maxScaleMultiplier = max maxScale = minScale * maxScaleMultiplier superMaxScale = SUPER_MAX_MULTIPLIER * maxScale maxScaleIsSetByMultiplier = true } /** * Set the min zoom multiplier. Default value: 1. * @return min zoom multiplier. */ var minZoom: Float get() = minScale set(min) { userSpecifiedMinScale = min if (min == AUTOMATIC_MIN_ZOOM) { if (touchScaleType == ScaleType.CENTER || touchScaleType == ScaleType.CENTER_CROP) { val drawable = drawable val drawableWidth = getDrawableWidth(drawable) val drawableHeight = getDrawableHeight(drawable) if (drawable != null && drawableWidth > 0 && drawableHeight > 0) { val widthRatio = viewWidth.toFloat() / drawableWidth val heightRatio = viewHeight.toFloat() / drawableHeight minScale = if (touchScaleType == ScaleType.CENTER) { min(widthRatio, heightRatio) } else { // CENTER_CROP min(widthRatio, heightRatio) / max(widthRatio, heightRatio) } } } else { minScale = 1.0f } } else { minScale = userSpecifiedMinScale } if (maxScaleIsSetByMultiplier) { setMaxZoomRatio(maxScaleMultiplier) } superMinScale = SUPER_MIN_MULTIPLIER * minScale } // Reset zoom and translation to initial state. fun resetZoom() { currentZoom = 1f fitImageToView() } fun resetZoomAnimated() { setZoomAnimated(1f, 0.5f, 0.5f) } // Set zoom to the specified scale. Image will be centered by default. fun setZoom(scale: Float) { setZoom(scale, 0.5f, 0.5f) } /** * Set zoom to the specified scale. Image will be centered around the point * (focusX, focusY). These floats range from 0 to 1 and denote the focus point * as a fraction from the left and top of the view. For example, the top left * corner of the image would be (0, 0). And the bottom right corner would be (1, 1). */ fun setZoom(scale: Float, focusX: Float, focusY: Float) { setZoom(scale, focusX, focusY, touchScaleType) } /** * Set zoom to the specified scale. Image will be centered around the point * (focusX, focusY). These floats range from 0 to 1 and denote the focus point * as a fraction from the left and top of the view. For example, the top left * corner of the image would be (0, 0). And the bottom right corner would be (1, 1). */ fun setZoom(scale: Float, focusX: Float, focusY: Float, scaleType: ScaleType?) { // setZoom can be called before the image is on the screen, but at this point, // image and view sizes have not yet been calculated in onMeasure. Thus, we should // delay calling setZoom until the view has been measured. if (!onDrawReady) { delayedZoomVariables = ZoomVariables(scale, focusX, focusY, scaleType) return } if (userSpecifiedMinScale == AUTOMATIC_MIN_ZOOM) { minZoom = AUTOMATIC_MIN_ZOOM if (currentZoom < minScale) { currentZoom = minScale } } if (scaleType != touchScaleType) { setScaleType(scaleType!!) } resetZoom() scaleImage(scale.toDouble(), viewWidth / 2.toFloat(), viewHeight / 2.toFloat(), true) touchMatrix.getValues(floatMatrix) floatMatrix[Matrix.MTRANS_X] = (viewWidth - matchViewWidth) / 2 - focusX * (scale - 1) * matchViewWidth floatMatrix[Matrix.MTRANS_Y] = (viewHeight - matchViewHeight) / 2 - focusY * (scale - 1) * matchViewHeight touchMatrix.setValues(floatMatrix) fixTrans() savePreviousImageValues() imageMatrix = touchMatrix } /** * Set zoom parameters equal to another TouchImageView. Including scale, position and ScaleType. */ fun setZoom(imageSource: TouchImageView) { val center = imageSource.scrollPosition setZoom(imageSource.currentZoom, center.x, center.y, imageSource.scaleType) } /** * Return the point at the center of the zoomed image. The PointF coordinates range * in value between 0 and 1 and the focus point is denoted as a fraction from the left * and top of the view. For example, the top left corner of the image would be (0, 0). * And the bottom right corner would be (1, 1). * * @return PointF representing the scroll position of the zoomed image. */ val scrollPosition: PointF get() { val drawable = drawable ?: return PointF(.5f, .5f) val drawableWidth = getDrawableWidth(drawable) val drawableHeight = getDrawableHeight(drawable) val point = transformCoordTouchToBitmap(viewWidth / 2.toFloat(), viewHeight / 2.toFloat(), true) point.x /= drawableWidth.toFloat() point.y /= drawableHeight.toFloat() return point } private fun orientationMismatch(drawable: Drawable?): Boolean { return viewWidth > viewHeight != drawable!!.intrinsicWidth > drawable.intrinsicHeight } private fun getDrawableWidth(drawable: Drawable?): Int { return if (orientationMismatch(drawable) && isRotateImageToFitScreen) { drawable!!.intrinsicHeight } else drawable!!.intrinsicWidth } private fun getDrawableHeight(drawable: Drawable?): Int { return if (orientationMismatch(drawable) && isRotateImageToFitScreen) { drawable!!.intrinsicWidth } else drawable!!.intrinsicHeight } /** * Set the focus point of the zoomed image. The focus points are denoted as a fraction from the * left and top of the view. The focus points can range in value between 0 and 1. */ fun setScrollPosition(focusX: Float, focusY: Float) { setZoom(currentZoom, focusX, focusY) } /** * Performs boundary checking and fixes the image matrix if it * is out of bounds. */ private fun fixTrans() { touchMatrix.getValues(floatMatrix) val transX = floatMatrix[Matrix.MTRANS_X] val transY = floatMatrix[Matrix.MTRANS_Y] var offset = 0f if (isRotateImageToFitScreen && orientationMismatch(drawable)) { offset = imageWidth } val fixTransX = getFixTrans(transX, viewWidth.toFloat(), imageWidth, offset) val fixTransY = getFixTrans(transY, viewHeight.toFloat(), imageHeight, 0f) touchMatrix.postTranslate(fixTransX, fixTransY) } /** * When transitioning from zooming from focus to zoom from center (or vice versa) * the image can become unaligned within the view. This is apparent when zooming * quickly. When the content size is less than the view size, the content will often * be centered incorrectly within the view. fixScaleTrans first calls fixTrans() and * then makes sure the image is centered correctly within the view. */ private fun fixScaleTrans() { fixTrans() touchMatrix.getValues(floatMatrix) if (imageWidth < viewWidth) { var xOffset = (viewWidth - imageWidth) / 2 if (isRotateImageToFitScreen && orientationMismatch(drawable)) { xOffset += imageWidth } floatMatrix[Matrix.MTRANS_X] = xOffset } if (imageHeight < viewHeight) { floatMatrix[Matrix.MTRANS_Y] = (viewHeight - imageHeight) / 2 } touchMatrix.setValues(floatMatrix) } private fun getFixTrans(trans: Float, viewSize: Float, contentSize: Float, offset: Float): Float { val minTrans: Float val maxTrans: Float if (contentSize <= viewSize) { minTrans = offset maxTrans = offset + viewSize - contentSize } else { minTrans = offset + viewSize - contentSize maxTrans = offset } if (trans < minTrans) return -trans + minTrans return if (trans > maxTrans) -trans + maxTrans else 0f } private fun getFixDragTrans(delta: Float, viewSize: Float, contentSize: Float): Float { return if (contentSize <= viewSize) { 0f } else delta } private val imageWidth: Float get() = matchViewWidth * currentZoom private val imageHeight: Float get() = matchViewHeight * currentZoom override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val drawable = drawable if (drawable == null || drawable.intrinsicWidth == 0 || drawable.intrinsicHeight == 0) { setMeasuredDimension(0, 0) return } val drawableWidth = getDrawableWidth(drawable) val drawableHeight = getDrawableHeight(drawable) val widthSize = MeasureSpec.getSize(widthMeasureSpec) val widthMode = MeasureSpec.getMode(widthMeasureSpec) val heightSize = MeasureSpec.getSize(heightMeasureSpec) val heightMode = MeasureSpec.getMode(heightMeasureSpec) val totalViewWidth = setViewSize(widthMode, widthSize, drawableWidth) val totalViewHeight = setViewSize(heightMode, heightSize, drawableHeight) if (!orientationJustChanged) { savePreviousImageValues() } // Image view width, height must consider padding val width = totalViewWidth - paddingLeft - paddingRight val height = totalViewHeight - paddingTop - paddingBottom // Set view dimensions setMeasuredDimension(width, height) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) // Fit content within view. // // onMeasure may be called multiple times for each layout change, including orientation // changes. For example, if the TouchImageView is inside a ConstraintLayout, onMeasure may // be called with: // widthMeasureSpec == "AT_MOST 2556" and then immediately with // widthMeasureSpec == "EXACTLY 1404", then back and forth multiple times in quick // succession, as the ConstraintLayout tries to solve its constraints. // // onSizeChanged is called once after the final onMeasure is called. So we make all changes // to class members, such as fitting the image into the new shape of the TouchImageView, // here, after the final size has been determined. This helps us avoid both // repeated computations, and making irreversible changes (e.g. making the View temporarily too // big or too small, thus making the current zoom fall outside of an automatically-changing // minZoom and maxZoom). viewWidth = w viewHeight = h fitImageToView() } /** * This function can be called: * 1. When the TouchImageView is first loaded (onMeasure). * 2. When a new image is loaded (setImageResource|Bitmap|Drawable|URI). * 3. On rotation (onSaveInstanceState, then onRestoreInstanceState, then onMeasure). * 4. When the view is resized (onMeasure). * 5. When the zoom is reset (resetZoom). * * In cases 2, 3 and 4, we try to maintain the zoom state and position as directed by * orientationChangeFixedPixel or viewSizeChangeFixedPixel (if there is an existing zoom state * and position, which there might not be in case 2). * * * If the normalizedScale is equal to 1, then the image is made to fit the View. Otherwise, we * maintain zoom level and attempt to roughly put the same part of the image in the View as was * there before, paying attention to orientationChangeFixedPixel or viewSizeChangeFixedPixel. */ private fun fitImageToView() { val fixedPixel = if (orientationJustChanged) orientationChangeFixedPixel else viewSizeChangeFixedPixel orientationJustChanged = false val drawable = drawable if (drawable == null || drawable.intrinsicWidth == 0 || drawable.intrinsicHeight == 0) { return } @Suppress("SENSELESS_COMPARISON") if (touchMatrix == null || prevMatrix == null) { return } if (userSpecifiedMinScale == AUTOMATIC_MIN_ZOOM) { minZoom = AUTOMATIC_MIN_ZOOM if (currentZoom < minScale) { currentZoom = minScale } } val drawableWidth = getDrawableWidth(drawable) val drawableHeight = getDrawableHeight(drawable) // Scale image for view var scaleX = viewWidth.toFloat() / drawableWidth var scaleY = viewHeight.toFloat() / drawableHeight when (touchScaleType) { ScaleType.CENTER -> { scaleY = 1f scaleX = scaleY } ScaleType.CENTER_CROP -> { scaleY = max(scaleX, scaleY) scaleX = scaleY } ScaleType.CENTER_INSIDE -> { run { scaleY = min(1f, min(scaleX, scaleY)) scaleX = scaleY } run { scaleY = min(scaleX, scaleY) scaleX = scaleY } } ScaleType.FIT_CENTER, ScaleType.FIT_START, ScaleType.FIT_END -> { scaleY = min(scaleX, scaleY) scaleX = scaleY } ScaleType.FIT_XY -> Unit else -> Unit } // Put the image's center in the right place. val redundantXSpace = viewWidth - scaleX * drawableWidth val redundantYSpace = viewHeight - scaleY * drawableHeight matchViewWidth = viewWidth - redundantXSpace matchViewHeight = viewHeight - redundantYSpace if (!isZoomed && !imageRenderedAtLeastOnce) { // Stretch and center image to fit view if (isRotateImageToFitScreen && orientationMismatch(drawable)) { touchMatrix.setRotate(90f) touchMatrix.postTranslate(drawableWidth.toFloat(), 0f) touchMatrix.postScale(scaleX, scaleY) } else { touchMatrix.setScale(scaleX, scaleY) } when (touchScaleType) { ScaleType.FIT_START -> touchMatrix.postTranslate(0f, 0f) ScaleType.FIT_END -> touchMatrix.postTranslate(redundantXSpace, redundantYSpace) else -> touchMatrix.postTranslate(redundantXSpace / 2, redundantYSpace / 2) } currentZoom = 1f } else { // These values should never be 0 or we will set viewWidth and viewHeight // to NaN in newTranslationAfterChange. To avoid this, call savePreviousImageValues // to set them equal to the current values. if (prevMatchViewWidth == 0f || prevMatchViewHeight == 0f) { savePreviousImageValues() } // Use the previous matrix as our starting point for the new matrix. prevMatrix.getValues(floatMatrix) // Rescale Matrix if appropriate floatMatrix[Matrix.MSCALE_X] = matchViewWidth / drawableWidth * currentZoom floatMatrix[Matrix.MSCALE_Y] = matchViewHeight / drawableHeight * currentZoom // TransX and TransY from previous matrix val transX = floatMatrix[Matrix.MTRANS_X] val transY = floatMatrix[Matrix.MTRANS_Y] // X position val prevActualWidth = prevMatchViewWidth * currentZoom val actualWidth = imageWidth floatMatrix[Matrix.MTRANS_X] = newTranslationAfterChange(transX, prevActualWidth, actualWidth, prevViewWidth, viewWidth, drawableWidth, fixedPixel) // Y position val prevActualHeight = prevMatchViewHeight * currentZoom val actualHeight = imageHeight floatMatrix[Matrix.MTRANS_Y] = newTranslationAfterChange(transY, prevActualHeight, actualHeight, prevViewHeight, viewHeight, drawableHeight, fixedPixel) // Set the matrix to the adjusted scale and translation values. touchMatrix.setValues(floatMatrix) } fixTrans() imageMatrix = touchMatrix } // Set view dimensions based on layout params private fun setViewSize(mode: Int, size: Int, drawableWidth: Int): Int { return when (mode) { MeasureSpec.EXACTLY -> size MeasureSpec.AT_MOST -> min(drawableWidth, size) MeasureSpec.UNSPECIFIED -> drawableWidth else -> size } } /** * After any change described in the comments for fitImageToView, the matrix needs to be * translated. This function translates the image so that the fixed pixel in the image * stays in the same place in the View. * * @param trans the value of trans in that axis before the rotation * @param prevImageSize the width/height of the image before the rotation * @param imageSize width/height of the image after rotation * @param prevViewSize width/height of view before rotation * @param viewSize width/height of view after rotation * @param drawableSize width/height of drawable * @param sizeChangeFixedPixel how we should choose the fixed pixel */ private fun newTranslationAfterChange( trans: Float, prevImageSize: Float, imageSize: Float, prevViewSize: Int, viewSize: Int, drawableSize: Int, sizeChangeFixedPixel: FixedPixel? ): Float { return when { imageSize < viewSize -> { // The width/height of image is less than the view's width/height. Center it. (viewSize - drawableSize * floatMatrix[Matrix.MSCALE_X]) * 0.5f } trans > 0 -> { // The image is larger than the view, but was not before the view changed. Center it. -((imageSize - viewSize) * 0.5f) } else -> { // Where is the pixel in the View that we are keeping stable, as a fraction of the width/height of the View? var fixedPixelPositionInView = 0.5f // CENTER if (sizeChangeFixedPixel == FixedPixel.BOTTOM_RIGHT) { fixedPixelPositionInView = 1.0f } else if (sizeChangeFixedPixel == FixedPixel.TOP_LEFT) { fixedPixelPositionInView = 0.0f } // Where is the pixel in the Image that we are keeping stable, as a fraction of the // width/height of the Image? val fixedPixelPositionInImage = (-trans + fixedPixelPositionInView * prevViewSize) / prevImageSize // Here's what the new translation should be so that, after whatever change triggered // this function to be called, the pixel at fixedPixelPositionInView of the View is // still the pixel at fixedPixelPositionInImage of the image. -(fixedPixelPositionInImage * imageSize - viewSize * fixedPixelPositionInView) } } } private fun setState(imageActionState: ImageActionState) { this.imageActionState = imageActionState } @Deprecated("") fun canScrollHorizontallyFroyo(direction: Int): Boolean { return canScrollHorizontally(direction) } override fun canScrollHorizontally(direction: Int): Boolean { touchMatrix.getValues(floatMatrix) val x = floatMatrix[Matrix.MTRANS_X] return if (imageWidth < viewWidth) { false } else if (x >= -1 && direction < 0) { false } else abs(x) + viewWidth + 1 < imageWidth || direction <= 0 } override fun canScrollVertically(direction: Int): Boolean { touchMatrix.getValues(floatMatrix) val y = floatMatrix[Matrix.MTRANS_Y] return if (imageHeight < viewHeight) { false } else if (y >= -1 && direction < 0) { false } else abs(y) + viewHeight + 1 < imageHeight || direction <= 0 } /** * Gesture Listener detects a single click or long click and passes that on * to the view's listener. */ private inner class GestureListener : SimpleOnGestureListener() { override fun onSingleTapConfirmed(e: MotionEvent): Boolean { // Pass on to the OnDoubleTapListener if it is present, otherwise let the View handle the click. return doubleTapListener?.onSingleTapConfirmed(e) ?: performClick() } override fun onLongPress(e: MotionEvent) { performLongClick() } override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { // If a previous fling is still active, it should be cancelled so that two flings // are not run simultaneously. fling?.cancelFling() fling = Fling(velocityX.toInt(), velocityY.toInt()).also { compatPostOnAnimation(it) } return super.onFling(e1, e2, velocityX, velocityY) } override fun onDoubleTap(e: MotionEvent): Boolean { var consumed = false if (isZoomEnabled) { doubleTapListener?.let { consumed = it.onDoubleTap(e) } if (imageActionState == ImageActionState.NONE) { val maxZoomScale = if (doubleTapScale == 0f) maxScale else doubleTapScale val targetZoom = if (currentZoom == minScale) maxZoomScale else minScale val doubleTap = DoubleTapZoom(targetZoom, e.x, e.y, false) compatPostOnAnimation(doubleTap) consumed = true } } return consumed } override fun onDoubleTapEvent(e: MotionEvent): Boolean { return doubleTapListener?.onDoubleTapEvent(e) ?: false } } /** * Responsible for all touch events. Handles the heavy lifting of drag and also sends * touch events to Scale Detector and Gesture Detector. */ private inner class PrivateOnTouchListener : OnTouchListener { // Remember last point position for dragging private val last = PointF() override fun onTouch(v: View, event: MotionEvent): Boolean { if (drawable == null) { setState(ImageActionState.NONE) return false } if (isZoomEnabled) { scaleDetector.onTouchEvent(event) } gestureDetector.onTouchEvent(event) val curr = PointF(event.x, event.y) if (imageActionState == ImageActionState.NONE || imageActionState == ImageActionState.DRAG || imageActionState == ImageActionState.FLING) { when (event.action) { MotionEvent.ACTION_DOWN -> { last.set(curr) fling?.cancelFling() setState(ImageActionState.DRAG) } MotionEvent.ACTION_MOVE -> if (imageActionState == ImageActionState.DRAG) { val deltaX = curr.x - last.x val deltaY = curr.y - last.y val fixTransX = getFixDragTrans(deltaX, viewWidth.toFloat(), imageWidth) val fixTransY = getFixDragTrans(deltaY, viewHeight.toFloat(), imageHeight) touchMatrix.postTranslate(fixTransX, fixTransY) fixTrans() last[curr.x] = curr.y } MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> setState(ImageActionState.NONE) } } touchCoordinatesListener?.let { val bitmapPoint = transformCoordTouchToBitmap(event.x, event.y, true) it.onTouchCoordinate(v, event, bitmapPoint) } imageMatrix = touchMatrix // User-defined OnTouchListener userTouchListener?.onTouch(v, event) // OnTouchImageViewListener is set: TouchImageView dragged by user. touchImageViewListener?.onMove() // indicate event was handled return true } } /** * ScaleListener detects user two finger scaling and scales image. */ private inner class ScaleListener : SimpleOnScaleGestureListener() { override fun onScaleBegin(detector: ScaleGestureDetector): Boolean { setState(ImageActionState.ZOOM) return true } override fun onScale(detector: ScaleGestureDetector): Boolean { scaleImage(detector.scaleFactor.toDouble(), detector.focusX, detector.focusY, true) // OnTouchImageViewListener is set: TouchImageView pinch zoomed by user. touchImageViewListener?.onMove() return true } override fun onScaleEnd(detector: ScaleGestureDetector) { super.onScaleEnd(detector) setState(ImageActionState.NONE) var animateToZoomBoundary = false var targetZoom: Float = currentZoom if (currentZoom > maxScale) { targetZoom = maxScale animateToZoomBoundary = true } else if (currentZoom < minScale) { targetZoom = minScale animateToZoomBoundary = true } if (animateToZoomBoundary) { val doubleTap = DoubleTapZoom(targetZoom, (viewWidth / 2).toFloat(), (viewHeight / 2).toFloat(), true) compatPostOnAnimation(doubleTap) } } } private fun scaleImage(deltaScale: Double, focusX: Float, focusY: Float, stretchImageToSuper: Boolean) { var deltaScaleLocal = deltaScale val lowerScale: Float val upperScale: Float if (stretchImageToSuper) { lowerScale = superMinScale upperScale = superMaxScale } else { lowerScale = minScale upperScale = maxScale } val origScale = currentZoom currentZoom *= deltaScaleLocal.toFloat() if (currentZoom > upperScale) { currentZoom = upperScale deltaScaleLocal = upperScale / origScale.toDouble() } else if (currentZoom < lowerScale) { currentZoom = lowerScale deltaScaleLocal = lowerScale / origScale.toDouble() } touchMatrix.postScale(deltaScaleLocal.toFloat(), deltaScaleLocal.toFloat(), focusX, focusY) fixScaleTrans() } /** * DoubleTapZoom calls a series of runnables which apply * an animated zoom in/out graphic to the image. */ private inner class DoubleTapZoom(targetZoom: Float, focusX: Float, focusY: Float, stretchImageToSuper: Boolean) : Runnable { private val startTime: Long private val startZoom: Float private val targetZoom: Float private val bitmapX: Float private val bitmapY: Float private val stretchImageToSuper: Boolean private val interpolator = AccelerateDecelerateInterpolator() private val startTouch: PointF private val endTouch: PointF override fun run() { if (drawable == null) { setState(ImageActionState.NONE) return } val t = interpolate() val deltaScale = calculateDeltaScale(t) scaleImage(deltaScale, bitmapX, bitmapY, stretchImageToSuper) translateImageToCenterTouchPosition(t) fixScaleTrans() imageMatrix = touchMatrix // double tap runnable updates listener with every frame. touchImageViewListener?.onMove() if (t < 1f) { // We haven't finished zooming compatPostOnAnimation(this) } else { // Finished zooming setState(ImageActionState.NONE) } } /** * Interpolate between where the image should start and end in order to translate * the image so that the point that is touched is what ends up centered at the end * of the zoom. */ private fun translateImageToCenterTouchPosition(t: Float) { val targetX = startTouch.x + t * (endTouch.x - startTouch.x) val targetY = startTouch.y + t * (endTouch.y - startTouch.y) val curr = transformCoordBitmapToTouch(bitmapX, bitmapY) touchMatrix.postTranslate(targetX - curr.x, targetY - curr.y) } /** * Use interpolator to get t */ private fun interpolate(): Float { val currTime = System.currentTimeMillis() var elapsed = (currTime - startTime) / DEFAULT_ZOOM_TIME.toFloat() elapsed = min(1f, elapsed) return interpolator.getInterpolation(elapsed) } /** * Interpolate the current targeted zoom and get the delta * from the current zoom. */ private fun calculateDeltaScale(t: Float): Double { val zoom = startZoom + t * (targetZoom - startZoom).toDouble() return zoom / currentZoom } init { setState(ImageActionState.ANIMATE_ZOOM) startTime = System.currentTimeMillis() startZoom = currentZoom this.targetZoom = targetZoom this.stretchImageToSuper = stretchImageToSuper val bitmapPoint = transformCoordTouchToBitmap(focusX, focusY, false) bitmapX = bitmapPoint.x bitmapY = bitmapPoint.y // Used for translating image during scaling startTouch = transformCoordBitmapToTouch(bitmapX, bitmapY) endTouch = PointF((viewWidth / 2).toFloat(), (viewHeight / 2).toFloat()) } } /** * This function will transform the coordinates in the touch event to the coordinate * system of the drawable that the imageview contain * * @param x x-coordinate of touch event * @param y y-coordinate of touch event * @param clipToBitmap Touch event may occur within view, but outside image content. True, to clip return value * to the bounds of the bitmap size. * @return Coordinates of the point touched, in the coordinate system of the original drawable. */ protected fun transformCoordTouchToBitmap(x: Float, y: Float, clipToBitmap: Boolean): PointF { touchMatrix.getValues(floatMatrix) val origW = drawable.intrinsicWidth.toFloat() val origH = drawable.intrinsicHeight.toFloat() val transX = floatMatrix[Matrix.MTRANS_X] val transY = floatMatrix[Matrix.MTRANS_Y] var finalX = (x - transX) * origW / imageWidth var finalY = (y - transY) * origH / imageHeight if (clipToBitmap) { finalX = min(max(finalX, 0f), origW) finalY = min(max(finalY, 0f), origH) } return PointF(finalX, finalY) } /** * Inverse of transformCoordTouchToBitmap. This function will transform the coordinates in the * drawable's coordinate system to the view's coordinate system. * * @param bx x-coordinate in original bitmap coordinate system * @param by y-coordinate in original bitmap coordinate system * @return Coordinates of the point in the view's coordinate system. */ protected fun transformCoordBitmapToTouch(bx: Float, by: Float): PointF { touchMatrix.getValues(floatMatrix) val origW = drawable.intrinsicWidth.toFloat() val origH = drawable.intrinsicHeight.toFloat() val px = bx / origW val py = by / origH val finalX = floatMatrix[Matrix.MTRANS_X] + imageWidth * px val finalY = floatMatrix[Matrix.MTRANS_Y] + imageHeight * py return PointF(finalX, finalY) } /** * Fling launches sequential runnables which apply * the fling graphic to the image. The values for the translation * are interpolated by the Scroller. */ private inner class Fling(velocityX: Int, velocityY: Int) : Runnable { var scroller: CompatScroller var currX: Int var currY: Int init { setState(ImageActionState.FLING) scroller = CompatScroller(context) touchMatrix.getValues(floatMatrix) var startX = floatMatrix[Matrix.MTRANS_X].toInt() val startY = floatMatrix[Matrix.MTRANS_Y].toInt() val minX: Int val maxX: Int val minY: Int val maxY: Int if (isRotateImageToFitScreen && orientationMismatch(drawable)) { startX -= imageWidth.toInt() } if (imageWidth > viewWidth) { minX = viewWidth - imageWidth.toInt() maxX = 0 } else { maxX = startX minX = maxX } if (imageHeight > viewHeight) { minY = viewHeight - imageHeight.toInt() maxY = 0 } else { maxY = startY minY = maxY } scroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY) currX = startX currY = startY } fun cancelFling() { setState(ImageActionState.NONE) scroller.forceFinished(true) } override fun run() { // OnTouchImageViewListener is set: TouchImageView listener has been flung by user. // Listener runnable updated with each frame of fling animation. touchImageViewListener?.onMove() if (scroller.isFinished) { return } if (scroller.computeScrollOffset()) { val newX = scroller.currX val newY = scroller.currY val transX = newX - currX val transY = newY - currY currX = newX currY = newY touchMatrix.postTranslate(transX.toFloat(), transY.toFloat()) fixTrans() imageMatrix = touchMatrix compatPostOnAnimation(this) } } } private inner class CompatScroller(context: Context?) { var overScroller: OverScroller = OverScroller(context) fun fling(startX: Int, startY: Int, velocityX: Int, velocityY: Int, minX: Int, maxX: Int, minY: Int, maxY: Int) { overScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY) } fun forceFinished(finished: Boolean) { overScroller.forceFinished(finished) } val isFinished: Boolean get() = overScroller.isFinished fun computeScrollOffset(): Boolean { overScroller.computeScrollOffset() return overScroller.computeScrollOffset() } val currX: Int get() = overScroller.currX val currY: Int get() = overScroller.currY } private fun compatPostOnAnimation(runnable: Runnable) { postOnAnimation(runnable) } /** * Set zoom to the specified scale with a linearly interpolated animation. Image will be * centered around the point (focusX, focusY). These floats range from 0 to 1 and denote the * focus point as a fraction from the left and top of the view. For example, the top left * corner of the image would be (0, 0). And the bottom right corner would be (1, 1). */ fun setZoomAnimated(scale: Float, focusX: Float, focusY: Float) { setZoomAnimated(scale, focusX, focusY, DEFAULT_ZOOM_TIME) } fun setZoomAnimated(scale: Float, focusX: Float, focusY: Float, zoomTimeMs: Int) { val animation = AnimatedZoom(scale, PointF(focusX, focusY), zoomTimeMs) compatPostOnAnimation(animation) } /** * Set zoom to the specified scale with a linearly interpolated animation. Image will be * centered around the point (focusX, focusY). These floats range from 0 to 1 and denote the * focus point as a fraction from the left and top of the view. For example, the top left * corner of the image would be (0, 0). And the bottom right corner would be (1, 1). * * @param listener the listener, which will be notified, once the animation ended */ fun setZoomAnimated(scale: Float, focusX: Float, focusY: Float, zoomTimeMs: Int, listener: OnZoomFinishedListener?) { val animation = AnimatedZoom(scale, PointF(focusX, focusY), zoomTimeMs) animation.setListener(listener) compatPostOnAnimation(animation) } fun setZoomAnimated(scale: Float, focusX: Float, focusY: Float, listener: OnZoomFinishedListener?) { val animation = AnimatedZoom(scale, PointF(focusX, focusY), DEFAULT_ZOOM_TIME) animation.setListener(listener) compatPostOnAnimation(animation) } /** * AnimatedZoom calls a series of runnables which apply * an animated zoom to the specified target focus at the specified zoom level. */ private inner class AnimatedZoom(targetZoom: Float, focus: PointF, zoomTimeMillis: Int) : Runnable { private val zoomTimeMillis: Int private val startTime: Long private val startZoom: Float private val targetZoom: Float private val startFocus: PointF private val targetFocus: PointF private val interpolator = LinearInterpolator() private var zoomFinishedListener: OnZoomFinishedListener? = null init { setState(ImageActionState.ANIMATE_ZOOM) startTime = System.currentTimeMillis() startZoom = currentZoom this.targetZoom = targetZoom this.zoomTimeMillis = zoomTimeMillis // Used for translating image during zooming startFocus = scrollPosition targetFocus = focus } override fun run() { val t = interpolate() // Calculate the next focus and zoom based on the progress of the interpolation val nextZoom = startZoom + (targetZoom - startZoom) * t val nextX = startFocus.x + (targetFocus.x - startFocus.x) * t val nextY = startFocus.y + (targetFocus.y - startFocus.y) * t setZoom(nextZoom, nextX, nextY) if (t < 1f) { // We haven't finished zooming compatPostOnAnimation(this) } else { // Finished zooming setState(ImageActionState.NONE) zoomFinishedListener?.onZoomFinished() } } /** * Use interpolator to get t * * @return progress of the interpolation */ private fun interpolate(): Float { var elapsed = (System.currentTimeMillis() - startTime) / zoomTimeMillis.toFloat() elapsed = min(1f, elapsed) return interpolator.getInterpolation(elapsed) } fun setListener(listener: OnZoomFinishedListener?) { this.zoomFinishedListener = listener } } companion object { // SuperMin and SuperMax multipliers. Determine how much the image can be zoomed below or above the zoom boundaries, // before animating back to the min/max zoom boundary. private const val SUPER_MIN_MULTIPLIER = .75f private const val SUPER_MAX_MULTIPLIER = 1.25f private const val DEFAULT_ZOOM_TIME = 500 // If setMinZoom(AUTOMATIC_MIN_ZOOM), then we'll set the min scale to include the whole image. const val AUTOMATIC_MIN_ZOOM = -1.0f } }
mit
68be684639e413d5e3b970cc53fd3ff6
39.381804
151
0.622846
4.919572
false
false
false
false
jwren/intellij-community
platform/execution-impl/src/com/intellij/execution/runToolbar/RunWidgetResizeController.kt
2
957
// 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.execution.runToolbar import java.awt.Dimension import java.awt.Point class RunWidgetResizeController private constructor() : DraggablePane.DragListener { companion object { private val controller = RunWidgetResizeController() fun getInstance(): RunWidgetResizeController { return controller } } private var startWidth: Int? = null override fun dragStarted(locationOnScreen: Point) { startWidth = FixWidthSegmentedActionToolbarComponent.RUN_CONFIG_WIDTH } override fun dragged(locationOnScreen: Point, offset: Dimension) { startWidth?.let { FixWidthSegmentedActionToolbarComponent.RUN_CONFIG_WIDTH = it - offset.width } } override fun dragStopped(locationOnScreen: Point, offset: Dimension) { dragged(locationOnScreen, offset) startWidth = null } }
apache-2.0
1f363cbc722cc6aa8e342055e705b0e1
29.903226
120
0.757576
4.785
false
true
false
false
JetBrains/kotlin-native
tools/performance-server/shared/src/main/kotlin/org/jetbrains/buildInfo/BuildInfo.kt
4
2522
/* * Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.buildInfo import org.jetbrains.report.* import org.jetbrains.report.json.* data class Build(val buildNumber: String, val startTime: String, val finishTime: String, val branch: String, val commits: String, val failuresNumber: Int) { companion object : EntityFromJsonFactory<Build> { override fun create(data: JsonElement): Build { if (data is JsonObject) { val buildNumber = elementToString(data.getRequiredField("buildNumber"), "buildNumber").replace("\"", "") val startTime = elementToString(data.getRequiredField("startTime"), "startTime").replace("\"", "") val finishTime = elementToString(data.getRequiredField("finishTime"), "finishTime").replace("\"", "") val branch = elementToString(data.getRequiredField("branch"), "branch").replace("\"", "") val commits = elementToString(data.getRequiredField("commits"), "commits") val failuresNumber = elementToInt(data.getRequiredField("failuresNumber"), "failuresNumber") return Build(buildNumber, startTime, finishTime, branch, commits, failuresNumber) } else { error("Top level entity is expected to be an object. Please, check origin files.") } } } private fun formatTime(time: String, targetZone: Int = 3): String { val matchResult = "^\\d{8}T(\\d{2})(\\d{2})\\d{2}((\\+|-)\\d{2})".toRegex().find(time)?.groupValues matchResult?.let { val timeZone = matchResult[3].toInt() val timeDifference = targetZone - timeZone var hours = (matchResult[1].toInt() + timeDifference) if (hours > 23) { hours -= 24 } return "${if (hours < 10) "0$hours" else "$hours"}:${matchResult[2]}" } ?: error { "Wrong format of time $startTime" } } val date: String by lazy { val matchResult = "^(\\d{4})(\\d{2})(\\d{2})".toRegex().find(startTime)?.groupValues matchResult?.let { "${matchResult[3]}/${matchResult[2]}/${matchResult[1]}" } ?: error { "Wrong format of time $startTime" } } val formattedStartTime: String by lazy { formatTime(startTime) } val formattedFinishTime: String by lazy { formatTime(finishTime) } }
apache-2.0
4f78f93f57ccdc53243689dbac224028
45.722222
120
0.605868
4.463717
false
false
false
false
matt-richardson/TeamCity.Node
agent/src/com/jonnyzzz/teamcity/plugins/node/agent/NodeDetector.kt
2
3879
/* * Copyright 2013-2015 Eugene Petrenko * * 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.jonnyzzz.teamcity.plugins.node.agent import com.jonnyzzz.teamcity.plugins.node.common.* import jetbrains.buildServer.agent.* import jetbrains.buildServer.util.EventDispatcher import com.jonnyzzz.teamcity.plugins.node.agent.processes.ProcessExecutor import com.jonnyzzz.teamcity.plugins.node.agent.processes.execution import com.jonnyzzz.teamcity.plugins.node.agent.processes.succeeded import java.io.File import com.jonnyzzz.teamcity.plugins.node.common.NVMBean import com.jonnyzzz.teamcity.plugins.node.common.NPMBean import com.jonnyzzz.teamcity.plugins.node.common.GruntBean /** * Created by Eugene Petrenko ([email protected]) * Date: 12.01.13 1:04 */ public class NodeToolsDetector(events: EventDispatcher<AgentLifeCycleListener>, val config: BuildAgentConfiguration, val exec : ProcessExecutor) { private val LOG = log4j(this.javaClass) fun detectNVMTool() { with(config.getSystemInfo()) { when { isWindows() -> { log4j(javaClass).info("Node NVM installer runner is not availabe: Windows is not supported") } !(isMac() || isUnix()) -> { log4j(javaClass).info("Node NVM installer runner is not availabe") } !File("/bin/bash").isFile() -> { log4j(javaClass).info("Node NVM installer runner is not availabe: /bin/bash not found") } else -> { val ref = NVMBean().NVMUsed with(config) { addConfigurationParameter(NPMBean().nodeJSNPMConfigurationParameter, ref) addConfigurationParameter(NodeBean().nodeJSConfigurationParameter, ref) addConfigurationParameter(NVMBean().NVMAvailable, "yes") } } } } } fun detectNodeTool(executable: String, configParameterName: String, versionPreprocess : (String) -> String = {it}) { val run = exec runProcess execution(executable, "--version") when { run.succeeded() -> { val version = versionPreprocess(run.stdOut.trim()) LOG.info("${executable} ${version} was detected") config.addConfigurationParameter(configParameterName, version) return } else -> { LOG.info("${executable} was not found or failed, exitcode: ${run.exitCode}") LOG.info("StdOut: ${run.stdOut}") LOG.info("StdErr: ${run.stdErr}") } } } init { events.addListener(object : AgentLifeCycleAdapter() { public override fun beforeAgentConfigurationLoaded(agent: BuildAgent) { detectNVMTool() detectNodeTool("node", NodeBean().nodeJSConfigurationParameter) { it trimStart "v" } detectNodeTool("npm", NPMBean().nodeJSNPMConfigurationParameter) detectNodeTool("grunt", GruntBean().gruntConfigurationParameter) { it.trimStart("grunt-cli").trim().trimStart("v") } detectNodeTool("gulp", GulpBean().gulpConfigurationParameter) { val firstLine = it.split("[\r\n]+")[0].trim() val lastSpaceIndex = firstLine.lastIndexOf(' ') if (lastSpaceIndex > 0) { firstLine.substring(lastSpaceIndex).trim() } else { firstLine } } } }) } }
apache-2.0
2ba9afd5f7c10e781f0ed88cfb9deb47
33.945946
118
0.659964
4.31
false
true
false
false
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/gamestats/GameStatsFragment.kt
1
7911
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.app.playhvz.screens.gamestats import android.graphics.Color import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import android.widget.TextView import androidx.appcompat.app.ActionBar import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.widget.ConstraintLayout import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.app.playhvz.R import com.app.playhvz.app.EspressoIdlingResource import com.app.playhvz.common.globals.CrossClientConstants.Companion.getAliveColor import com.app.playhvz.common.globals.CrossClientConstants.Companion.getDeadColor import com.app.playhvz.common.globals.SharedPreferencesConstants import com.app.playhvz.firebase.classmodels.Stat import com.app.playhvz.firebase.operations.GameDatabaseOperations import com.app.playhvz.navigation.NavigationUtil import com.github.mikephil.charting.charts.LineChart import com.github.mikephil.charting.charts.PieChart import com.github.mikephil.charting.data.* import com.github.mikephil.charting.formatter.PercentFormatter import kotlinx.coroutines.runBlocking class GameStatsFragment : Fragment() { companion object { private val TAG = GameStatsFragment::class.qualifiedName } private var gameId: String? = null private lateinit var chartContainer: ConstraintLayout private lateinit var currentPopulationChart: PieChart private lateinit var errorLabel: TextView private lateinit var populationOverTime: LineChart private lateinit var progressBar: ProgressBar private lateinit var toolbar: ActionBar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) toolbar = (activity as AppCompatActivity).supportActionBar!! val sharedPrefs = activity?.getSharedPreferences( SharedPreferencesConstants.PREFS_FILENAME, 0 )!! gameId = sharedPrefs.getString(SharedPreferencesConstants.CURRENT_GAME_ID, null) if (gameId == null) { NavigationUtil.navigateToGameList(findNavController(), requireActivity()) } setupToolbar() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_game_stats, container, false) progressBar = view.findViewById(R.id.progress_bar) errorLabel = view.findViewById(R.id.error_label) chartContainer = view.findViewById(R.id.chart_container) currentPopulationChart = view.findViewById(R.id.current_population_chart) populationOverTime = view.findViewById(R.id.population_over_time_chart) val onSuccess = { stats: Stat -> EspressoIdlingResource.decrement() progressBar.visibility = View.GONE errorLabel.visibility = View.GONE chartContainer.visibility = View.VISIBLE displayStats(stats) } val onFail = { EspressoIdlingResource.decrement() errorLabel.visibility = View.VISIBLE progressBar.visibility = View.GONE chartContainer.visibility = View.GONE } progressBar.visibility = View.VISIBLE runBlocking { EspressoIdlingResource.increment() GameDatabaseOperations.asyncGetGameStats(gameId!!, onSuccess, onFail) } return view } fun setupToolbar() { toolbar.title = getString(R.string.navigation_drawer_game_stats) } private fun displayStats(stats: Stat) { setCurrentPopulationData(stats) setPopulationOverTimeData(stats) } private fun setCurrentPopulationData(stats: Stat) { val entries: ArrayList<PieEntry> = ArrayList() entries.add( PieEntry( stats.currentHumanCount + 0.0f, resources.getString(R.string.allegiance_option_human) ) ) entries.add( PieEntry( stats.currentZombieCount + 0.0f, resources.getString(R.string.allegiance_option_zombie) ) ) val dataSet = PieDataSet(entries, "") dataSet.setDrawIcons(false) dataSet.sliceSpace = 3f dataSet.selectionShift = 5f val colors: ArrayList<Int> = ArrayList() colors.add(getAliveColor(requireContext())) colors.add(getDeadColor(requireContext())) dataSet.colors = colors val data = PieData(dataSet) data.setValueFormatter(PercentFormatter(currentPopulationChart)) data.setValueTextSize(12f) data.setValueTextColor(Color.WHITE) currentPopulationChart.setUsePercentValues(true); currentPopulationChart.data = data currentPopulationChart.description.isEnabled = false currentPopulationChart.highlightValues(null) currentPopulationChart.invalidate() } private fun setPopulationOverTimeData(stats: Stat) { val totalPlayers = stats.currentHumanCount + stats.currentZombieCount val humanValues: MutableList<Entry> = mutableListOf() val zombieValues: MutableList<Entry> = mutableListOf() for (stat in stats.statsOverTime) { humanValues.add( Entry( stat.interval.toFloat(), (totalPlayers - stat.infectionCount - stats.starterZombieCount).toFloat() ) ) zombieValues.add( Entry( stat.interval.toFloat(), (stats.starterZombieCount + stat.infectionCount).toFloat() ) ) } val humanLine = LineDataSet(humanValues, resources.getString(R.string.allegiance_option_human)) humanLine.lineWidth = 1.75f humanLine.circleRadius = 5f humanLine.circleHoleRadius = 2.5f humanLine.color = getAliveColor(requireContext()) humanLine.setCircleColor(getAliveColor(requireContext())) humanLine.highLightColor = getAliveColor(requireContext()) humanLine.setDrawValues(false) val zombieLine = LineDataSet(zombieValues, resources.getString(R.string.allegiance_option_zombie)) zombieLine.lineWidth = 1.75f zombieLine.circleRadius = 5f zombieLine.circleHoleRadius = 2.5f zombieLine.color = getDeadColor(requireContext()) zombieLine.setCircleColor(getDeadColor(requireContext())) zombieLine.highLightColor = getDeadColor(requireContext()) zombieLine.setDrawValues(false) populationOverTime.description.isEnabled = false populationOverTime.setDrawBorders(true) populationOverTime.setTouchEnabled(true) populationOverTime.isDragEnabled = true populationOverTime.setScaleEnabled(true) populationOverTime.setPinchZoom(false) populationOverTime.data = LineData(humanLine, zombieLine) populationOverTime.axisLeft.spaceTop = 40f populationOverTime.axisRight.isEnabled = false populationOverTime.xAxis.isEnabled = false populationOverTime.invalidate() } }
apache-2.0
9051e3515d1b02b7d4b79834300b2b4f
37.222222
93
0.694476
4.832621
false
false
false
false
nimakro/tornadofx
src/main/java/tornadofx/TreeView.kt
1
7806
package tornadofx import javafx.beans.property.* import javafx.scene.Node import javafx.scene.control.* import javafx.scene.input.KeyCode import javafx.scene.input.KeyEvent import javafx.util.Callback import tornadofx.FX.IgnoreParentBuilder.Once import kotlin.reflect.KClass /** * Base class for all TreeCellFragments. */ abstract class TreeCellFragment<T> : ItemFragment<T>() { val cellProperty: ObjectProperty<TreeCell<T>?> = SimpleObjectProperty() var cell by cellProperty val editingProperty = SimpleBooleanProperty(false) val editing by editingProperty open fun startEdit() { cell?.startEdit() } open fun commitEdit(newValue: T) { cell?.commitEdit(newValue) } open fun cancelEdit() { cell?.cancelEdit() } open fun onEdit(op: () -> Unit) { editingProperty.onChange { if (it) op() } } } open class SmartTreeCell<T>(val scope: Scope = DefaultScope, treeView: TreeView<T>?): TreeCell<T>() { @Suppress("UNCHECKED_CAST") private val editSupport: (TreeCell<T>.(EditEventType, T?) -> Unit)? get() = treeView.properties["tornadofx.editSupport"] as (TreeCell<T>.(EditEventType, T?) -> Unit)? @Suppress("UNCHECKED_CAST") private val cellFormat: (TreeCell<T>.(T) -> Unit)? get() = treeView.properties["tornadofx.cellFormat"] as (TreeCell<T>.(T) -> Unit)? @Suppress("UNCHECKED_CAST") private val cellCache: TreeCellCache<T>? get() = treeView.properties["tornadofx.cellCache"] as TreeCellCache<T>? private var cellFragment: TreeCellFragment<T>? = null private var fresh = true init { if (treeView != null) { treeView.properties["tornadofx.cellFormatCapable"] = true treeView.properties["tornadofx.cellCacheCapable"] = true treeView.properties["tornadofx.editCapable"] = true } indexProperty().onChange { if (it == -1) clearCellFragment() } } override fun startEdit() { super.startEdit() editSupport?.invoke(this, EditEventType.StartEdit, null) } override fun commitEdit(newValue: T) { super.commitEdit(newValue) editSupport?.invoke(this, EditEventType.CommitEdit, newValue) } override fun cancelEdit() { super.cancelEdit() editSupport?.invoke(this, EditEventType.CancelEdit, null) } override fun updateItem(item: T, empty: Boolean) { super.updateItem(item, empty) if (item == null || empty) { cleanUp() clearCellFragment() } else { FX.ignoreParentBuilder = Once try { cellCache?.apply { graphic = getOrCreateNode(item) } } finally { FX.ignoreParentBuilder = FX.IgnoreParentBuilder.No } if (fresh) { @Suppress("UNCHECKED_CAST") val cellFragmentType = treeView.properties["tornadofx.cellFragment"] as KClass<TreeCellFragment<T>>? cellFragment = if (cellFragmentType != null) find(cellFragmentType, scope) else null fresh = false } cellFragment?.apply { editingProperty.cleanBind(editingProperty()) itemProperty.value = item cellProperty.value = this@SmartTreeCell graphic = root } cellFormat?.invoke(this, item) } } private fun cleanUp() { textProperty().unbind() graphicProperty().unbind() text = null graphic = null } private fun clearCellFragment() { cellFragment?.apply { cellProperty.value = null itemProperty.value = null editingProperty.unbind() editingProperty.value = false } } } class TreeCellCache<T>(private val cacheProvider: (T) -> Node) { private val store = mutableMapOf<T, Node>() fun getOrCreateNode(value: T) = store.getOrPut(value){ cacheProvider(value) } } fun <T> TreeView<T>.bindSelected(property: Property<T>) { selectionModel.selectedItemProperty().onChange { property.value = it?.value } } /** * Binds the currently selected object of type [T] in the given [TreeView] to the corresponding [ItemViewModel]. */ fun <T> TreeView<T>.bindSelected(model: ItemViewModel<T>) = this.bindSelected(model.itemProperty) fun <T> TreeView<T>.onUserDelete(action: (T) -> Unit) { addEventFilter(KeyEvent.KEY_PRESSED) { event -> val value = selectedValue if (event.code == KeyCode.BACK_SPACE && value != null) action(value) } } fun <T> TreeView<T>.onUserSelect(action: (T) -> Unit) { selectionModel.selectedItemProperty().addListener { _, _, new -> new?.value?.let { action(it) } } } /** * <p>This method will attempt to select the first index in the control. * If clearSelection is not called first, this method * will have the result of selecting the first index, whilst retaining * the selection of any other currently selected indices.</p> * * <p>If the first index is already selected, calling this method will have * no result, and no selection event will take place.</p> * * This functions is the same as calling. * ``` * selectionModel.selectFirst() * * ``` */ fun <T> TreeView<T>.selectFirst() = selectionModel.selectFirst() fun <T> TreeView<T>.populate(itemFactory: (T) -> TreeItem<T> = { TreeItem(it) }, childFactory: (TreeItem<T>) -> Iterable<T>?) = populateTree(root, itemFactory, childFactory) /** * Registers a `Fragment` which should be used to represent a [TreeItem] for the given [TreeView]. */ fun <T, F : TreeCellFragment<T>> TreeView<T>.cellFragment(scope: Scope = DefaultScope, fragment: KClass<F>) { properties["tornadofx.cellFragment"] = fragment if (properties["tornadofx.cellFormatCapable"] != true) cellFactory = Callback { SmartTreeCell(scope, it) } } fun <S> TreeView<S>.cellFormat(scope: Scope = DefaultScope, formatter: (TreeCell<S>.(S) -> Unit)) { properties["tornadofx.cellFormat"] = formatter if (properties["tornadofx.cellFormatCapable"] != true) { cellFactory = Callback { SmartTreeCell(scope, it) } } } fun <S> TreeView<S>.cellDecorator(decorator: (TreeCell<S>.(S) -> Unit)) { val originalFactory = cellFactory if (originalFactory == null) cellFormat(formatter = decorator) else { cellFactory = Callback { treeView: TreeView<S> -> val cell = originalFactory.call(treeView) cell.itemProperty().onChange { decorator(cell, cell.item) } cell } } } // -- Properties /** * Returns the currently selected value of type [T] (which is currently the * selected value represented by the current selection model). If there * are multiple values selected, it will return the most recently selected * value. * * <p>Note that the returned value is a snapshot in time. */ val <T> TreeView<T>.selectedValue: T? get() = this.selectionModel.selectedItem?.value fun <T> TreeView<T>.multiSelect(enable: Boolean = true) { selectionModel.selectionMode = if (enable) SelectionMode.MULTIPLE else SelectionMode.SINGLE } fun <T> TreeTableView<T>.multiSelect(enable: Boolean = true) { selectionModel.selectionMode = if (enable) SelectionMode.MULTIPLE else SelectionMode.SINGLE } // -- TreeItem helpers /** * Expand this [TreeItem] and children down to `depth`. */ fun <T> TreeItem<T>.expandTo(depth: Int) { if ( depth > 0 ) { this.isExpanded = true this.children.forEach { it.expandTo(depth - 1) } } } /** * Expand this `[TreeItem] and all it's children. */ fun <T> TreeItem<T>.expandAll() = expandTo(Int.MAX_VALUE) /** * Collapse this [TreeItem] and all it's children. */ fun <T> TreeItem<T>.collapseAll() { this.isExpanded = false this.children.forEach { it.collapseAll() } }
apache-2.0
fc0461d49ddd0202713b1d2059c993bc
32.502146
198
0.653984
4.214903
false
false
false
false
MarkNenadov/k-bird
src/main/kotlin/org/pythonbyte/kbird/domain/Checklist.kt
1
1007
package org.pythonbyte.kbird.domain import org.jsoup.nodes.Element class Checklist: DomainObject() { var identifier: String = "" var personName: String = "" var location: String = "" var date: String = "" var time: String = "" var link: String = "" var speciesEntries = ArrayList<SpeciesEntry>() companion object { fun parseFromJsonTrElement( element: Element ) : Checklist { val checklist = Checklist() checklist.personName = element.select(".recent-visitor" ).text() checklist.location = element.select( ".obstable-location" ).text() checklist.time = element.select( "obstable-time").text() val linkElement = element.select( ".obstable-date" ).select( "a" ).first() checklist.link = linkElement.attr( "href" ) checklist.identifier = checklist.link.replace( "/view/checklist/", "" ) checklist.date = linkElement.text() return checklist } } }
lgpl-2.1
43a66663ed4913469b944d44d47283c4
34.964286
86
0.613704
4.321888
false
false
false
false
lnr0626/cfn-templates
base-models/src/main/kotlin/com/lloydramey/cfn/model/resources/attributes/UpdatePolicy.kt
1
2447
/* * Copyright 2017 Lloyd Ramey <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lloydramey.cfn.model.resources.attributes import com.fasterxml.jackson.databind.annotation.JsonSerialize import com.fasterxml.jackson.databind.ser.std.ToStringSerializer data class AutoScalingReplacingUpdate(@JsonSerialize(using = ToStringSerializer::class) val willReplace: Boolean? = null) sealed class ScalingProcess(val name: String) { object Launch : ScalingProcess("Launch") object Terminate : ScalingProcess("Terminate") object HealthCheck : ScalingProcess("HealthCheck") object ReplaceUnhealthy : ScalingProcess("ReplaceUnhealthy") object AZRebalance : ScalingProcess("AZRebalance") object AlarmNotification : ScalingProcess("AlarmNotification") object ScheduledActions : ScalingProcess("ScheduledActions") object AddToLoadBalancer : ScalingProcess("AddToLoadBalancer") } data class AutoScalingRollingUpdate( @JsonSerialize(using = ToStringSerializer::class) val maxBatchSize: Int? = null, @JsonSerialize(using = ToStringSerializer::class) val minInstancesInService: Int? = null, @JsonSerialize(using = ToStringSerializer::class) val minSuccessfulInstancesPercent: Int? = null, @JsonSerialize(using = ToStringSerializer::class) val pauseTime: ISO8601Duration? = null, val suspendProcesses: List<ScalingProcess> = emptyList(), @JsonSerialize(using = ToStringSerializer::class) val waitOnResourceSignals: Boolean? = null ) data class AutoScalingScheduledAction( @JsonSerialize(using = ToStringSerializer::class) val ignoreUnmodifiedGroupSizeProperties: Boolean? = null ) class UpdatePolicy( val autoScalingReplacingUpdate: AutoScalingReplacingUpdate? = null, val autoScalingRollingUpdate: AutoScalingRollingUpdate? = null, val autoScalingScheduledAction: AutoScalingScheduledAction? = null ) : ResourceDefinitionAttribute("UpdatePolicy")
apache-2.0
6b9e62162894ffb20dafa0a02ed62628
47
121
0.782591
4.473492
false
false
false
false
smmribeiro/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/api/PackageSearchApiClient.kt
1
3887
package com.jetbrains.packagesearch.intellij.plugin.api import com.jetbrains.packagesearch.api.v2.ApiPackagesResponse import com.jetbrains.packagesearch.api.v2.ApiRepositoriesResponse import com.jetbrains.packagesearch.api.v2.ApiStandardPackage import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.PluginEnvironment import com.jetbrains.packagesearch.intellij.plugin.api.http.requestString import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import org.apache.commons.httpclient.util.URIUtil internal object ServerURLs { const val base = "https://package-search.services.jetbrains.com/api" } @Suppress("unused") // Used in SearchClient but the lazy throws off the IDE code analysis private val contentType by lazy { @Suppress("MayBeConst") // False positive object { val standard = "application/vnd.jetbrains.packagesearch.standard.v2+json" } } private val emptyStandardV2PackagesWithRepos: ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion> = ApiPackagesResponse( packages = emptyList(), repositories = emptyList() ) internal class PackageSearchApiClient( private val baseUrl: String, private val timeoutInSeconds: Int = 10, private val headers: List<Pair<String, String>> = listOf( Pair("JB-Plugin-Version", PluginEnvironment.pluginVersion), Pair("JB-IDE-Version", PluginEnvironment.ideVersion) ) ) { private val maxRequestResultsCount = 25 private val maxMavenCoordinatesParts = 3 private val json = Json { ignoreUnknownKeys = true encodeDefaults = false } @Suppress("BlockingMethodInNonBlockingContext") suspend fun packagesByQuery( searchQuery: String, onlyStable: Boolean = false, onlyMpp: Boolean = false, repositoryIds: List<String> ): ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion> { if (searchQuery.isEmpty()) { return emptyStandardV2PackagesWithRepos } val joinedRepositoryIds = repositoryIds.joinToString(",") { URIUtil.encodeQuery(it) } val requestUrl = buildString { append(baseUrl) append("/package?query=") append(URIUtil.encodeQuery(searchQuery)) append("&onlyStable=") append(onlyStable.toString()) append("&onlyMpp=") append(onlyMpp.toString()) if (repositoryIds.isNotEmpty()) { append("&repositoryIds=") append(joinedRepositoryIds) } } return requestString(requestUrl, contentType.standard, timeoutInSeconds, headers) .let { json.decodeFromString(it) } } suspend fun packagesByRange(range: List<String>): ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion> { if (range.isEmpty()) { return emptyStandardV2PackagesWithRepos } require(range.size <= maxRequestResultsCount) { PackageSearchBundle.message("packagesearch.search.client.error.too.many.requests.for.range") } require(range.none { it.split(":").size >= maxMavenCoordinatesParts }) { PackageSearchBundle.message("packagesearch.search.client.error.no.versions.for.range") } val joinedRange = range.joinToString(",") { URIUtil.encodeQuery(it) } val requestUrl = "$baseUrl/package?range=$joinedRange" return requestString(requestUrl, contentType.standard, timeoutInSeconds, headers) .let { json.decodeFromString(it) } } suspend fun repositories(): ApiRepositoriesResponse = requestString("$baseUrl/repositories", contentType.standard, timeoutInSeconds, headers) .let { json.decodeFromString(it) } }
apache-2.0
6089700ebf67fdd79f37333f1af0616e
37.107843
147
0.704142
4.932741
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/KotlinShortNamesCache.kt
1
13018
// 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.caches import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiClass import com.intellij.psi.PsiField import com.intellij.psi.PsiMethod import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiShortNamesCache import com.intellij.psi.stubs.StubIndex import com.intellij.util.ArrayUtil import com.intellij.util.Processor import com.intellij.util.Processors import com.intellij.util.containers.ContainerUtil import com.intellij.util.indexing.IdFilter import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.asJava.defaultImplsChild import org.jetbrains.kotlin.asJava.finder.JavaElementFinder import org.jetbrains.kotlin.asJava.getAccessorLightMethods import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName import org.jetbrains.kotlin.idea.decompiler.builtIns.KotlinBuiltInFileType import org.jetbrains.kotlin.idea.stubindex.* import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.load.java.getPropertyNamesCandidatesByAccessorName import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtNamedFunction class KotlinShortNamesCache(private val project: Project) : PsiShortNamesCache() { companion object { private val LOG = Logger.getInstance(KotlinShortNamesCache::class.java) } //hacky way to avoid searches for Kotlin classes, when looking for Java (from Kotlin) val disableSearch: ThreadLocal<Boolean> = object : ThreadLocal<Boolean>() { override fun initialValue(): Boolean = false } //region Classes override fun processAllClassNames(processor: Processor<in String>): Boolean { if (disableSearch.get()) return true return KotlinClassShortNameIndex.getInstance().processAllKeys(project, processor) && KotlinFileFacadeShortNameIndex.INSTANCE.processAllKeys(project, processor) } override fun processAllClassNames(processor: Processor<in String>, scope: GlobalSearchScope, filter: IdFilter?): Boolean { if (disableSearch.get()) return true return processAllClassNames(processor) } /** * Return kotlin class names from project sources which should be visible from java. */ override fun getAllClassNames(): Array<String> { if (disableSearch.get()) return ArrayUtil.EMPTY_STRING_ARRAY return withArrayProcessor(ArrayUtil.EMPTY_STRING_ARRAY) { processor -> processAllClassNames(processor) } } override fun processClassesWithName( name: String, processor: Processor<in PsiClass>, scope: GlobalSearchScope, filter: IdFilter? ): Boolean { if (disableSearch.get()) return true val effectiveScope = kotlinDeclarationsVisibleFromJavaScope(scope) val fqNameProcessor = Processor<FqName> { fqName: FqName? -> if (fqName == null) return@Processor true val isInterfaceDefaultImpl = name == JvmAbi.DEFAULT_IMPLS_CLASS_NAME && fqName.shortName().asString() != name if (fqName.shortName().asString() != name && !isInterfaceDefaultImpl) { LOG.error( "A declaration obtained from index has non-matching name:" + "\nin index: $name" + "\ndeclared: ${fqName.shortName()}($fqName)" ) return@Processor true } val fqNameToSearch = if (isInterfaceDefaultImpl) fqName.defaultImplsChild() else fqName val psiClass = JavaElementFinder.getInstance(project).findClass(fqNameToSearch.asString(), effectiveScope) ?: return@Processor true return@Processor processor.process(psiClass) } val allKtClassOrObjectsProcessed = StubIndex.getInstance().processElements( KotlinClassShortNameIndex.getInstance().key, name, project, effectiveScope, filter, KtClassOrObject::class.java ) { ktClassOrObject -> fqNameProcessor.process(ktClassOrObject.fqName) } if (!allKtClassOrObjectsProcessed) { return false } return StubIndex.getInstance().processElements( KotlinFileFacadeShortNameIndex.getInstance().key, name, project, effectiveScope, filter, KtFile::class.java ) { ktFile -> fqNameProcessor.process(ktFile.javaFileFacadeFqName) } } /** * Return class names form kotlin sources in given scope which should be visible as Java classes. */ override fun getClassesByName(name: String, scope: GlobalSearchScope): Array<PsiClass> { if (disableSearch.get()) return PsiClass.EMPTY_ARRAY return withArrayProcessor(PsiClass.EMPTY_ARRAY) { processor -> processClassesWithName(name, processor, scope, null) } } private fun kotlinDeclarationsVisibleFromJavaScope(scope: GlobalSearchScope): GlobalSearchScope { val noBuiltInsScope: GlobalSearchScope = object : GlobalSearchScope(project) { override fun isSearchInModuleContent(aModule: Module) = true override fun compare(file1: VirtualFile, file2: VirtualFile) = 0 override fun isSearchInLibraries() = true override fun contains(file: VirtualFile) = !FileTypeRegistry.getInstance().isFileOfType(file, KotlinBuiltInFileType) } return KotlinSourceFilterScope.sourceAndClassFiles(scope, project).intersectWith(noBuiltInsScope) } //endregion //region Methods override fun processAllMethodNames( processor: Processor<in String>, scope: GlobalSearchScope, filter: IdFilter? ): Boolean { if (disableSearch.get()) return true return processAllMethodNames(processor) } override fun getAllMethodNames(): Array<String> { if (disableSearch.get()) ArrayUtil.EMPTY_STRING_ARRAY return withArrayProcessor(ArrayUtil.EMPTY_STRING_ARRAY) { processor -> processAllMethodNames(processor) } } private fun processAllMethodNames(processor: Processor<in String>): Boolean { if (disableSearch.get()) return true if (!KotlinFunctionShortNameIndex.getInstance().processAllKeys(project, processor)) { return false } return KotlinPropertyShortNameIndex.getInstance().processAllKeys(project) { name -> return@processAllKeys processor.process(JvmAbi.setterName(name)) && processor.process(JvmAbi.getterName(name)) } } override fun processMethodsWithName( name: String, processor: Processor<in PsiMethod>, scope: GlobalSearchScope, filter: IdFilter? ): Boolean { if (disableSearch.get()) return true val allFunctionsProcessed = StubIndex.getInstance().processElements( KotlinFunctionShortNameIndex.getInstance().key, name, project, scope, filter, KtNamedFunction::class.java ) { ktNamedFunction -> val methods = LightClassUtil.getLightClassMethodsByName(ktNamedFunction, name) return@processElements methods.all { method -> processor.process(method) } } if (!allFunctionsProcessed) { return false } for (propertyName in getPropertyNamesCandidatesByAccessorName(Name.identifier(name))) { val allProcessed = StubIndex.getInstance().processElements( KotlinPropertyShortNameIndex.getInstance().key, propertyName.asString(), project, scope, filter, KtNamedDeclaration::class.java ) { ktNamedDeclaration -> val methods: Sequence<PsiMethod> = ktNamedDeclaration.getAccessorLightMethods() .asSequence() .filter { it.name == name } return@processElements methods.all { method -> processor.process(method) } } if (!allProcessed) { return false } } return true } override fun getMethodsByName(name: String, scope: GlobalSearchScope): Array<PsiMethod> { if (disableSearch.get()) return PsiMethod.EMPTY_ARRAY return withArrayProcessor(PsiMethod.EMPTY_ARRAY) { processor -> processMethodsWithName(name, processor, scope, null) } } override fun getMethodsByNameIfNotMoreThan(name: String, scope: GlobalSearchScope, maxCount: Int): Array<PsiMethod> { if (disableSearch.get()) return PsiMethod.EMPTY_ARRAY require(maxCount >= 0) return withArrayProcessor(PsiMethod.EMPTY_ARRAY) { processor -> processMethodsWithName( name, { psiMethod -> processor.size != maxCount && processor.process(psiMethod) }, scope, null ) } } override fun processMethodsWithName( name: String, scope: GlobalSearchScope, processor: Processor<in PsiMethod> ): Boolean { if (disableSearch.get()) return true return ContainerUtil.process(getMethodsByName(name, scope), processor) } //endregion //region Fields override fun processAllFieldNames(processor: Processor<in String>, scope: GlobalSearchScope, filter: IdFilter?): Boolean { if (disableSearch.get()) return true return processAllFieldNames(processor) } override fun getAllFieldNames(): Array<String> { if (disableSearch.get()) return ArrayUtil.EMPTY_STRING_ARRAY return withArrayProcessor(ArrayUtil.EMPTY_STRING_ARRAY) { processor -> processAllFieldNames(processor) } } private fun processAllFieldNames(processor: Processor<in String>): Boolean { if (disableSearch.get()) return true return KotlinPropertyShortNameIndex.getInstance().processAllKeys(project, processor) } override fun processFieldsWithName( name: String, processor: Processor<in PsiField>, scope: GlobalSearchScope, filter: IdFilter? ): Boolean { if (disableSearch.get()) return true return StubIndex.getInstance().processElements( KotlinPropertyShortNameIndex.getInstance().key, name, project, scope, filter, KtNamedDeclaration::class.java ) { ktNamedDeclaration -> val field = LightClassUtil.getLightClassBackingField(ktNamedDeclaration) ?: return@processElements true return@processElements processor.process(field) } } override fun getFieldsByName(name: String, scope: GlobalSearchScope): Array<PsiField> { if (disableSearch.get()) return PsiField.EMPTY_ARRAY return withArrayProcessor(PsiField.EMPTY_ARRAY) { processor -> processFieldsWithName(name, processor, scope, null) } } override fun getFieldsByNameIfNotMoreThan(name: String, scope: GlobalSearchScope, maxCount: Int): Array<PsiField> { if (disableSearch.get()) return PsiField.EMPTY_ARRAY require(maxCount >= 0) return withArrayProcessor(PsiField.EMPTY_ARRAY) { processor -> processFieldsWithName( name, { psiField -> processor.size != maxCount && processor.process(psiField) }, scope, null ) } } //endregion private inline fun <T> withArrayProcessor( result: Array<T>, process: (CancelableArrayCollectProcessor<T>) -> Unit ): Array<T> { return CancelableArrayCollectProcessor<T>().also { processor -> process(processor) }.toArray(result) } private class CancelableArrayCollectProcessor<T> : Processor<T> { private val set = HashSet<T>() private val processor = Processors.cancelableCollectProcessor<T>(set) override fun process(value: T): Boolean { return processor.process(value) } val size: Int get() = set.size fun toArray(a: Array<T>): Array<T> = set.toArray(a) } }
apache-2.0
dcced5bf10bdc7091cb4cf00556d499c
36.733333
158
0.653941
5.344007
false
false
false
false
vicpinm/KPresenterAdapter
sample/src/main/java/com/vicpin/sample/model/IRepository.kt
1
591
package com.vicpin.sample.model import java.util.ArrayList interface IRepository<T> { val PAGE_SIZE: Int var items: List<T> fun getAllItems(): List<T> = items fun getItemsPage(page: Int): List<T> { val startIndex = page * PAGE_SIZE var endIndex = page * PAGE_SIZE + PAGE_SIZE val countries = getAllItems() if (startIndex >= countries.size) { return ArrayList() } if (endIndex > countries.size) { endIndex = countries.size } return countries.subList(startIndex, endIndex) } }
apache-2.0
a33e39701bcb4dcdfb3cae8cfd0ff113
20.142857
54
0.595601
4.161972
false
false
false
false
kerubistan/kerub
src/test/kotlin/com/github/kerubistan/kerub/model/config/HostConfigurationIndexTest.kt
2
756
package com.github.kerubistan.kerub.model.config import com.github.kerubistan.kerub.testHost import com.github.kerubistan.kerub.testVirtualNetwork import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class HostConfigurationIndexTest { @Test fun getOvsNetworkConfigurations() { assertEquals( mapOf(testVirtualNetwork.id to OvsNetworkConfiguration( virtualNetworkId = testVirtualNetwork.id, ports = listOf() ) ), HostConfiguration( id = testHost.id, networkConfiguration = listOf( OvsNetworkConfiguration( virtualNetworkId = testVirtualNetwork.id, ports = listOf() ) ) ).index.ovsNetworkConfigurations ) } }
apache-2.0
21f99eb4e15b8b54f81ab067984c5918
24.233333
53
0.71164
4.108696
false
true
false
false
slisson/intellij-community
platform/script-debugger/backend/src/org/jetbrains/debugger/StandaloneVmHelper.kt
14
3995
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import io.netty.buffer.ByteBuf import io.netty.channel.Channel import io.netty.channel.ChannelFuture import io.netty.channel.ChannelFutureListener import io.netty.channel.oio.OioEventLoopGroup import org.jetbrains.concurrency import org.jetbrains.jsonProtocol.Request import org.jetbrains.rpc.MessageProcessor import org.jetbrains.rpc.MessageWriter import org.jetbrains.util.concurrency.AsyncPromise import org.jetbrains.util.concurrency.Promise import org.jetbrains.util.concurrency.ResolvedPromise import org.jetbrains.util.concurrency.catchError import java.util.concurrent.TimeUnit public open class StandaloneVmHelper(private val vm: Vm, private val messageProcessor: MessageProcessor) : MessageWriter(), AttachStateManager { private volatile var channel: Channel? = null override fun write(content: ByteBuf) = write((content as Any)) public fun getChannelIfActive(): Channel? { val currentChannel = channel return if (currentChannel == null || !currentChannel.isActive()) null else currentChannel } public fun write(content: Any): Boolean { val channel = getChannelIfActive() return channel != null && !channel.writeAndFlush(content).isCancelled() } public interface VmEx : Vm { public fun createDisconnectRequest(): Request<out Any?>? } public fun setChannel(channel: Channel) { this.channel = channel channel.closeFuture().addListener(MyChannelFutureListener()) } private inner class MyChannelFutureListener : ChannelFutureListener { override fun operationComplete(future: ChannelFuture) { // don't report in case of explicit detach() if (channel != null) { messageProcessor.closed() vm.debugListener.disconnected() } } } override fun isAttached() = channel != null override fun detach(): Promise<*> { val currentChannel = channel ?: return ResolvedPromise() messageProcessor.cancelWaitingRequests() val disconnectRequest = (vm as? VmEx)?.createDisconnectRequest() val promise = AsyncPromise<Any?>() if (disconnectRequest == null) { messageProcessor.closed() channel = null closeChannel(currentChannel, promise) return promise } messageProcessor.closed() channel = null @suppress("USELESS_CAST") val p = messageProcessor.send(disconnectRequest) as concurrency.Promise<*> p.processed { promise.catchError { messageProcessor.cancelWaitingRequests() closeChannel(currentChannel, promise) } } return promise } protected open fun closeChannel(channel: Channel, promise: AsyncPromise<Any?>) { doCloseChannel(channel, promise) } } fun doCloseChannel(channel: Channel, promise: AsyncPromise<Any?>) { val eventLoop = channel.eventLoop() channel.close().addListener(object : ChannelFutureListener { override fun operationComplete(future: ChannelFuture) { try { // if NIO, so, it is shared and we don't need to release it if (eventLoop is OioEventLoopGroup) { @suppress("USELESS_CAST") (eventLoop as OioEventLoopGroup).shutdownGracefully(1L, 2L, TimeUnit.NANOSECONDS) } } finally { val error = future.cause() if (error == null) { promise.setResult(null) } else { promise.setError(error) } } } }) }
apache-2.0
facce77745ab5b12d5921ba1b2c80358
31.487805
144
0.713892
4.514124
false
false
false
false
quran/quran_android
common/networking/src/main/java/com/quran/common/networking/dns/DnsModule.kt
2
1372
package com.quran.common.networking.dns import dagger.Module import dagger.Provides import okhttp3.Cache import okhttp3.Dns import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.OkHttpClient import okhttp3.dnsoverhttps.DnsOverHttps import java.io.File import java.net.UnknownHostException @Module class DnsModule { @Provides fun providesDns(servers: List<@JvmSuppressWildcards Dns>): Dns { return MultiDns(servers) } @Provides fun provideDnsCache(cacheDirectory: File): Cache { return Cache(cacheDirectory, 5 * 1024 * 1024L) } @Provides fun provideServers(dnsCache: Cache): List<Dns> { val bootstrapClient = OkHttpClient.Builder() .cache(dnsCache) .build() // dns fallback tries the equivalent of Dns.SYSTEM first, // so no need to explicitly add Dns.SYSTEM here. val dnsFallback = DnsFallback() val cloudflareDns = provideCloudflareDns(bootstrapClient) val result = mutableListOf<Dns>() if (cloudflareDns != null) result.add(cloudflareDns) result.add(dnsFallback) return result } private fun provideCloudflareDns(bootstrapClient: OkHttpClient): Dns? { return try { DnsOverHttps.Builder() .client(bootstrapClient) .url("https://1.1.1.1/dns-query".toHttpUrl()) .build() } catch (exception: UnknownHostException) { null } } }
gpl-3.0
1b32376d2576a153ac0a8ac1b1064eda
24.886792
73
0.710641
3.965318
false
false
false
false
ilya-g/kotlinx.collections.immutable
core/commonMain/src/implementations/persistentOrderedSet/PersistentOrderedSet.kt
1
3872
/* * Copyright 2016-2019 JetBrains s.r.o. * Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file. */ package kotlinx.collections.immutable.implementations.persistentOrderedSet import kotlinx.collections.immutable.PersistentSet import kotlinx.collections.immutable.implementations.immutableMap.PersistentHashMap import kotlinx.collections.immutable.internal.EndOfChain import kotlinx.collections.immutable.mutate internal class Links(val previous: Any?, val next: Any?) { /** Constructs Links for a new single element */ constructor() : this(EndOfChain, EndOfChain) /** Constructs Links for a new last element */ constructor(previous: Any?) : this(previous, EndOfChain) fun withNext(newNext: Any?) = Links(previous, newNext) fun withPrevious(newPrevious: Any?) = Links(newPrevious, next) val hasNext get() = next !== EndOfChain val hasPrevious get() = previous !== EndOfChain } internal class PersistentOrderedSet<E>( internal val firstElement: Any?, internal val lastElement: Any?, internal val hashMap: PersistentHashMap<E, Links> ) : AbstractSet<E>(), PersistentSet<E> { override val size: Int get() = hashMap.size override fun contains(element: E): Boolean = hashMap.containsKey(element) override fun add(element: E): PersistentSet<E> { if (hashMap.containsKey(element)) { return this } if (isEmpty()) { val newMap = hashMap.put(element, Links()) return PersistentOrderedSet(element, element, newMap) } @Suppress("UNCHECKED_CAST") val lastElement = lastElement as E val lastLinks = hashMap[lastElement]!! // assert(!lastLinks.hasNext) val newMap = hashMap .put(lastElement, lastLinks.withNext(element)) .put(element, Links(previous = lastElement)) return PersistentOrderedSet(firstElement, element, newMap) } override fun addAll(elements: Collection<E>): PersistentSet<E> { return this.mutate { it.addAll(elements) } } override fun remove(element: E): PersistentSet<E> { val links = hashMap[element] ?: return this var newMap = hashMap.remove(element) if (links.hasPrevious) { val previousLinks = newMap[links.previous]!! // assert(previousLinks.next == element) @Suppress("UNCHECKED_CAST") newMap = newMap.put(links.previous as E, previousLinks.withNext(links.next)) } if (links.hasNext) { val nextLinks = newMap[links.next]!! // assert(nextLinks.previous == element) @Suppress("UNCHECKED_CAST") newMap = newMap.put(links.next as E, nextLinks.withPrevious(links.previous)) } val newFirstElement = if (!links.hasPrevious) links.next else firstElement val newLastElement = if (!links.hasNext) links.previous else lastElement return PersistentOrderedSet(newFirstElement, newLastElement, newMap) } override fun removeAll(elements: Collection<E>): PersistentSet<E> { return mutate { it.removeAll(elements) } } override fun removeAll(predicate: (E) -> Boolean): PersistentSet<E> { return mutate { it.removeAll(predicate) } } override fun clear(): PersistentSet<E> { return PersistentOrderedSet.emptyOf() } override fun iterator(): Iterator<E> { return PersistentOrderedSetIterator(firstElement, hashMap) } override fun builder(): PersistentSet.Builder<E> { return PersistentOrderedSetBuilder(this) } internal companion object { private val EMPTY = PersistentOrderedSet<Nothing>(EndOfChain, EndOfChain, PersistentHashMap.emptyOf()) internal fun <E> emptyOf(): PersistentSet<E> = EMPTY } }
apache-2.0
3a9a6341f7b70d13ff472cca956198ed
36.230769
110
0.669163
4.566038
false
false
false
false
yrsegal/CommandControl
src/main/java/wiresegal/cmdctrl/common/commands/misc/CommandMotion.kt
1
2956
package wiresegal.cmdctrl.common.commands.misc import net.minecraft.command.CommandBase import net.minecraft.command.CommandException import net.minecraft.command.ICommandSender import net.minecraft.command.NumberInvalidException import net.minecraft.entity.player.EntityPlayerMP import net.minecraft.network.play.server.SPacketEntityVelocity import net.minecraft.server.MinecraftServer import wiresegal.cmdctrl.common.CommandControl import wiresegal.cmdctrl.common.core.CTRLUsageException import wiresegal.cmdctrl.common.core.notifyCTRLListener /** * @author WireSegal * Created at 7:43 PM on 12/4/16. */ object CommandMotion : CommandBase() { @Throws(CommandException::class) override fun execute(server: MinecraftServer, sender: ICommandSender, args: Array<out String>) { if (args.size < 3) throw CTRLUsageException(getCommandUsage(sender)) val entity = if (args.size > 3) getEntity(server, sender, args[3]) else getCommandSenderAsPlayer(sender) val x = parseExpandedRelative(entity.motionX, args[0]) val y = parseExpandedRelative(entity.motionY, args[1]) val z = parseExpandedRelative(entity.motionZ, args[2]) entity.motionX = x entity.motionY = y entity.motionZ = z if (entity is EntityPlayerMP) entity.connection.sendPacket(SPacketEntityVelocity(entity)) notifyCTRLListener(sender, this, "commandcontrol.motion.success", entity.name, entity.motionX, entity.motionY, entity.motionZ) } fun parseExpandedRelative(current: Double, token: String): Double { val flag = token.startsWith("~") if (flag) { if (token.length == 1) return current else return when (token[1]) { '*' -> { val double = parseDouble(token.substring(2)) current * double } '/' -> { val double = parseDouble(token.substring(2)) current / double } '-' -> { val double = parseDouble(token.substring(2)) current - double } '+' -> { val double = parseDouble(token.substring(2)) current + double } '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.' -> { val double = parseDouble(token.substring(1)) current + double } else -> throw NumberInvalidException("commands.generic.num.invalid", token) } } return parseDouble(token) } override fun getRequiredPermissionLevel() = 2 override fun getCommandName() = "motion" override fun getCommandUsage(sender: ICommandSender?) = CommandControl.translate("commandcontrol.motion.usage") override fun isUsernameIndex(args: Array<String>, index: Int) = index == 0 }
mit
38d52fe7d36ba95c0e2ce2350c4a0442
37.894737
134
0.616373
4.519878
false
false
false
false
luks91/Team-Bucket
app/src/main/java/com/github/luks91/teambucket/persistence/RepositoriesStorage.kt
2
4437
/** * Copyright (c) 2017-present, Team Bucket Contributors. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package com.github.luks91.teambucket.persistence import com.github.luks91.teambucket.ReactiveBus import com.github.luks91.teambucket.model.Project import com.github.luks91.teambucket.model.Repository import io.reactivex.Observable import io.reactivex.disposables.Disposable import io.reactivex.functions.BiFunction import io.realm.RealmModel import io.realm.RealmQuery class RepositoriesStorage(private val eventsBus: ReactiveBus) { private val scheduler by RealmSchedulerHolder companion object { const val REPOSITORIES_REALM = "projects.realm" } fun selectedRepositories(sortColumn: String = "slug", notifyIfMissing: Boolean = true): Observable<List<Repository>> { return usingRealm(REPOSITORIES_REALM, scheduler) { realm -> realm.where(RealmRepository::class.java).findAllSorted(sortColumn).asFlowable() .map { it.toList() } .map { it.map { it.toRepository() } } .doOnNext { list -> if (list.isEmpty() && notifyIfMissing) { eventsBus.post(ReactiveBus.EventRepositoriesMissing(PullRequestsStorage::class.java.simpleName)) } } .toObservable() } } fun selectedProjects(sortColumn: String = "key"): Observable<List<Project>> { return usingRealm(REPOSITORIES_REALM, scheduler) { realm -> realm.where(RealmProject::class.java).findAllSorted(sortColumn).asFlowable() .map { it.toList() }.map { it.map { it.toProject() } }.toObservable() } } fun subscribeRepositoriesPersisting(projects: Observable<List<Project>>, repositories: Observable<List<Repository>>) : Disposable { return usingRealm(REPOSITORIES_REALM, scheduler) { realm -> Observable.zip<List<RealmProject>, List<RealmRepository>, Unit>( projects .map { projects -> projects.map { project -> RealmProject.from(project) } } .observeOn(scheduler), repositories .map { repositories -> repositories.map { repository -> RealmRepository.Factory.from(repository) } } .observeOn(scheduler), BiFunction<List<RealmProject>, List<RealmRepository>, Unit> { projects, repositories -> realm.executeTransaction { realm.where(RealmProject::class.java) .allNotExisting(projects, "key", { it.key }) .findAll().deleteAllFromRealm() realm.copyToRealmOrUpdate(projects) realm.where(RealmRepository::class.java) .allNotExisting(projects, "project.key", { it.key }) .findAll().deleteAllFromRealm() realm.where(RealmRepository::class.java) .allNotExisting(repositories, "slug", { it.slug }) .findAll().deleteAllFromRealm() realm.copyToRealmOrUpdate(repositories) } }) }.subscribe() } private inline fun <Stored: RealmModel, Compared: RealmModel> RealmQuery<Stored>.allNotExisting( comparedList: List<Compared>, storedColumn: String, getComparedColumn: (Compared) -> String): RealmQuery<Stored> { if (comparedList.isEmpty()) { return this } var query = this.beginGroup() comparedList.forEach { query = query.notEqualTo(storedColumn, getComparedColumn(it)) } return query.endGroup() } }
apache-2.0
3b6eb441d5641dd8c6d13200b3c495a8
46.202128
128
0.601082
5.135417
false
false
false
false
FirebaseExtended/make-it-so-android
app/src/main/java/com/example/makeitso/screens/splash/SplashScreen.kt
1
2290
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.splash import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import com.example.makeitso.R.string as AppText import com.example.makeitso.common.composable.BasicButton import com.example.makeitso.common.ext.basicButton import kotlinx.coroutines.delay private const val SPLASH_TIMEOUT = 1000L @Composable fun SplashScreen( openAndPopUp: (String, String) -> Unit, modifier: Modifier = Modifier, viewModel: SplashViewModel = hiltViewModel() ) { Column( modifier = modifier .fillMaxWidth() .fillMaxHeight() .background(color = MaterialTheme.colors.background) .verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { if (viewModel.showError.value) { Text(text = stringResource(AppText.generic_error)) BasicButton(AppText.try_again, Modifier.basicButton()) { viewModel.onAppStart(openAndPopUp) } } else { CircularProgressIndicator(color = MaterialTheme.colors.onBackground) } } LaunchedEffect(true) { delay(SPLASH_TIMEOUT) viewModel.onAppStart(openAndPopUp) } }
apache-2.0
e710a6b826af94570f540579de41d148
32.676471
99
0.786026
4.499018
false
false
false
false
davinkevin/Podcast-Server
backend/src/main/kotlin/com/github/davinkevin/podcastserver/service/storage/FileStorageService.kt
1
8126
package com.github.davinkevin.podcastserver.service.storage import com.github.davinkevin.podcastserver.cover.Cover import com.github.davinkevin.podcastserver.cover.DeleteCoverRequest import com.github.davinkevin.podcastserver.item.DeleteItemRequest import com.github.davinkevin.podcastserver.item.Item import com.github.davinkevin.podcastserver.podcast.DeletePodcastRequest import com.github.davinkevin.podcastserver.podcast.Podcast import org.slf4j.LoggerFactory import org.springframework.core.io.ByteArrayResource import org.springframework.http.MediaType import org.springframework.http.codec.multipart.FilePart import org.springframework.web.reactive.function.client.WebClient import reactor.core.publisher.Mono import reactor.core.scheduler.Schedulers import reactor.kotlin.core.publisher.toMono import reactor.util.retry.Retry import software.amazon.awssdk.core.async.AsyncRequestBody import software.amazon.awssdk.services.s3.S3AsyncClient import software.amazon.awssdk.services.s3.model.* import software.amazon.awssdk.services.s3.presigner.S3Presigner import java.net.URI import java.nio.file.Files import java.nio.file.Path import java.time.Duration import java.util.* import kotlin.io.path.Path import kotlin.io.path.extension /** * Created by kevin on 2019-02-09 */ class FileStorageService( private val wcb: WebClient.Builder, private val bucket: S3AsyncClient, private val preSignerBuilder: (URI) -> S3Presigner, private val properties: StorageProperties, ) { private val log = LoggerFactory.getLogger(FileStorageService::class.java) fun deletePodcast(podcast: DeletePodcastRequest) = Mono.defer { log.info("Deletion of podcast {}", podcast.title) bucket.listObjects { it.bucket(properties.bucket).prefix(podcast.title) }.toMono() .flatMapIterable { it.contents() } .flatMap { bucket.deleteObject(it.toDeleteRequest()).toMono() } .then(true.toMono()) .onErrorReturn(false) } fun deleteItem(item: DeleteItemRequest): Mono<Boolean> = Mono.defer { val path = "${item.podcastTitle}/${item.fileName}" log.info("Deletion of file {}", path) bucket.deleteObject { it.bucket(properties.bucket).key(path) }.toMono() .map { true } .onErrorReturn(false) } fun deleteCover(cover: DeleteCoverRequest): Mono<Boolean> = Mono.defer { val path = "${cover.podcast.title}/${cover.item.id}.${cover.extension}" log.info("Deletion of file {}", path) bucket.deleteObject { it.bucket(properties.bucket).key(path) }.toMono() .map { true } .onErrorReturn(false) } fun coverExists(p: Podcast): Mono<Path> = coverExists(p.title, p.id, p.cover.extension()) fun coverExists(i: Item): Mono<Path> = coverExists(i.podcast.title, i.id, i.cover.extension()) fun coverExists(podcastTitle: String, itemId: UUID, extension: String): Mono<Path> { val path = "$podcastTitle/$itemId.$extension" return bucket.headObject { it.bucket(properties.bucket).key(path) }.toMono() .map { true } .onErrorReturn(false) .filter { it } .map { path.substringAfterLast("/") } .map { Path(it) } } private fun download(url: URI) = wcb.clone() .baseUrl(url.toASCIIString()) .build() .get() .accept(MediaType.APPLICATION_OCTET_STREAM) .retrieve() .bodyToMono(ByteArrayResource::class.java) private fun upload(key: String, resource: ByteArrayResource): Mono<PutObjectResponse> { val request = PutObjectRequest.builder() .bucket(properties.bucket) .acl(ObjectCannedACL.PUBLIC_READ) .key(key) .build() return bucket.putObject(request, AsyncRequestBody.fromBytes(resource.byteArray)).toMono() } fun downloadPodcastCover(podcast: Podcast): Mono<Void> = download(podcast.cover.url) .flatMap { upload("""${podcast.title}/${podcast.id}.${podcast.cover.extension()}""", it) } .then() fun downloadItemCover(item: Item): Mono<Void> = download(item.cover.url) .flatMap { upload("""${item.podcast.title}/${item.id}.${item.cover.extension()}""", it) } .then() fun movePodcast(request: MovePodcastRequest): Mono<Void> = Mono.defer { val listRequest = ListObjectsRequest.builder() .bucket(properties.bucket) .prefix(request.from) .build() bucket.listObjects(listRequest).toMono() .flatMapIterable { it.contents() } .flatMap { bucket .copyObject(it.toCopyRequest(request.to)).toMono() .then(Mono.defer { bucket.deleteObject(it.toDeleteRequest()).toMono() }) } .then() } fun cache(filePart: FilePart, destination: Path): Mono<Path> = Mono.defer { Files.createTempDirectory("upload-temp") .toMono() .map { it.resolve(destination.fileName) } .subscribeOn(Schedulers.boundedElastic()) .publishOn(Schedulers.parallel()) .flatMap { filePart.transferTo(it) .then(it.toMono()) } } .subscribeOn(Schedulers.boundedElastic()) .publishOn(Schedulers.parallel()) fun upload(podcastTitle: String, file: Path): Mono<PutObjectResponse> { val request = PutObjectRequest.builder() .bucket(properties.bucket) .acl(ObjectCannedACL.PUBLIC_READ) .key("$podcastTitle/${file.fileName}") .build() return bucket.putObject(request, file).toMono() .retryWhen(Retry.backoff(3, Duration.ofSeconds(1))) .delayUntil { Files.deleteIfExists(file).toMono() .subscribeOn(Schedulers.boundedElastic()) .publishOn(Schedulers.parallel()) } } fun metadata(title: String, file: Path): Mono<FileMetaData> { val key = "$title/${file.fileName}" return Mono.defer { bucket.headObject { it.bucket(properties.bucket).key(key) }.toMono() } .retryWhen(Retry.backoff(3, Duration.ofSeconds(1))) .map { FileMetaData(contentType = it.contentType(), size = it.contentLength()) } } private fun S3Object.toDeleteRequest(bucket: String = properties.bucket): DeleteObjectRequest = DeleteObjectRequest.builder() .bucket(bucket) .key(this.key()) .build() private fun S3Object.toCopyRequest(key: String, bucket: String = properties.bucket): CopyObjectRequest = CopyObjectRequest.builder() .sourceBucket(bucket) .sourceKey(this.key()) .destinationBucket(bucket) .destinationKey("$key/" + this.key().substringAfterLast("/")) .build() fun initBucket(): Mono<Void> { return bucket.headBucket { it.bucket(properties.bucket) }.toMono() .doOnSuccess { log.info("🗂 Bucket already present") } .then() .onErrorResume { bucket.createBucket { it.bucket(properties.bucket) }.toMono() .doOnSuccess { log.info("✅ Bucket creation done") } .then() } } fun toExternalUrl(file: FileDescriptor, requestedHost: URI): URI { return preSignerBuilder(requestedHost).presignGetObject { sign -> sign .signatureDuration(Duration.ofDays(1)) .getObjectRequest { request -> request .bucket(properties.bucket) .key("${file.podcastTitle}/${file.fileName}") } }.url().toURI() } } private fun Cover.extension(): String = Path(url.path).extension.ifBlank { "jpg" } private fun Item.Cover.extension() = Path(url.path).extension.ifBlank { "jpg" } data class MovePodcastRequest(val id: UUID, val from: String, val to: String) data class FileMetaData(val contentType: String, val size: Long) data class FileDescriptor(val podcastTitle: String, val fileName: Path)
apache-2.0
e0fbeef2196f4ea84e2adb939c100061
38.808824
108
0.645118
4.285488
false
false
false
false
premnirmal/StockTicker
app/src/main/kotlin/com/github/premnirmal/ticker/base/BaseActivity.kt
1
2941
package com.github.premnirmal.ticker.base import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import androidx.viewbinding.ViewBinding import com.github.premnirmal.ticker.AppPreferences import com.github.premnirmal.ticker.analytics.Analytics import com.github.premnirmal.ticker.model.StocksProvider import com.github.premnirmal.ticker.model.StocksProvider.FetchState import com.github.premnirmal.ticker.showDialog import com.github.premnirmal.tickerwidget.R import com.google.android.material.color.DynamicColors import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import timber.log.Timber import javax.inject.Inject /** * Created by premnirmal on 2/26/16. */ abstract class BaseActivity<T: ViewBinding> : AppCompatActivity() { abstract val simpleName: String abstract val binding: T open val subscribeToErrorEvents = true private var isErrorDialogShowing = false @Inject lateinit var analytics: Analytics @Inject lateinit var stocksProvider: StocksProvider @Inject lateinit var appPreferences: AppPreferences override fun onCreate( savedInstanceState: Bundle? ) { super.onCreate(savedInstanceState) DynamicColors.applyToActivityIfAvailable(this) if (appPreferences.themePref == AppPreferences.JUST_BLACK_THEME) { theme.applyStyle(R.style.AppTheme_Overlay_JustBlack, true) } setContentView(binding.root) savedInstanceState?.let { isErrorDialogShowing = it.getBoolean(IS_ERROR_DIALOG_SHOWING, false) } } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) analytics.trackScreenView(simpleName, this) } override fun onResume() { super.onResume() if (subscribeToErrorEvents) { lifecycleScope.launch { stocksProvider.fetchState.collect { state -> if (state is FetchState.Failure) { if (this.isActive && !isErrorDialogShowing && !isFinishing) { isErrorDialogShowing = true showDialog(state.displayString).setOnDismissListener { isErrorDialogShowing = false } delay(500L) } } } } } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putBoolean(IS_ERROR_DIALOG_SHOWING, isErrorDialogShowing) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { try { super.onRestoreInstanceState(savedInstanceState) } catch (ex: Throwable) { // android bug Timber.w(ex) } } override fun onOptionsItemSelected(item: android.view.MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() return true } return super.onOptionsItemSelected(item) } companion object { private const val IS_ERROR_DIALOG_SHOWING = "IS_ERROR_DIALOG_SHOWING" } }
gpl-3.0
b2eee2fd347c3823149125e9caeb4eb9
30.967391
100
0.740224
4.588144
false
false
false
false
davinkevin/Podcast-Server
backend/src/main/kotlin/com/github/davinkevin/podcastserver/update/updaters/youtube/YoutubeByApiUpdater.kt
1
7437
package com.github.davinkevin.podcastserver.update.updaters.youtube import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import com.github.davinkevin.podcastserver.extension.java.util.orNull import com.github.davinkevin.podcastserver.update.updaters.ItemFromUpdate import com.github.davinkevin.podcastserver.update.updaters.PodcastToUpdate import com.github.davinkevin.podcastserver.update.updaters.Updater import com.github.davinkevin.podcastserver.update.updaters.youtube.YoutubeByApiUpdater.Companion.URL_PAGE_BASE import org.jsoup.Jsoup import org.slf4j.LoggerFactory import org.springframework.util.DigestUtils import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.bodyToMono import reactor.core.publisher.Flux import reactor.core.publisher.Mono import reactor.kotlin.core.publisher.switchIfEmpty import reactor.kotlin.core.publisher.toMono import java.net.URI import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import java.util.* import java.util.concurrent.CopyOnWriteArrayList /** * Created by kevin on 13/09/2018 */ class YoutubeByApiUpdater( private val key: String, private val youtubeClient: WebClient, private val googleApiClient: WebClient ): Updater { private val log = LoggerFactory.getLogger(YoutubeByApiUpdater::class.java) override fun findItems(podcast: PodcastToUpdate): Flux<ItemFromUpdate> { log.debug("find items of {}", podcast.url) return findPlaylistId(podcast.url).flatMapMany { id -> Flux.range(1, MAX_PAGE) .flatMap ({ pageNumber -> Mono .deferContextual { Mono.just(it) } .flatMap { c -> Mono .justOrEmpty(c.getOrEmpty<List<String>>("pageTokens")) .filter { it.isNotEmpty() } .map { it[pageNumber-2] } .flatMap { nextPageToken -> fetchPageWithToken(id, nextPageToken) } .switchIfEmpty { fetchPageWithToken(id) } .doOnNext { c.getOrEmpty<CopyOnWriteArrayList<String>>("pageTokens") .get() .add(it.nextPageToken) } } }, 1) .takeUntil { it.nextPageToken.isEmpty() } .flatMapIterable { it.items } .map { it.toItem() } .contextWrite { c -> log.debug("creation of cache") c.put("pageTokens", CopyOnWriteArrayList<YoutubeApiResponse>()) } } } override fun signatureOf(url: URI): Mono<String> { log.debug("signature of {}", url) return findPlaylistId(url).flatMap { id -> fetchPageWithToken(id) .map { it.items } .map { items -> items.joinToString { it.snippet.resourceId.videoId } } .filter { it.isNotEmpty() } .map { DigestUtils.md5DigestAsHex(it.toByteArray()) } .switchIfEmpty { "".toMono() } } } private fun fetchPageWithToken(id: String, pageToken: String = "") = googleApiClient .get() .uri { it.path("/youtube/v3/playlistItems") .queryParam("part", "snippet") .queryParam("maxResults", 50) .queryParam("playlistId", id) .queryParam("key", key) .apply { if (pageToken.isNotEmpty()) { this.queryParam("pageToken", pageToken) } } .build() } .retrieve() .bodyToMono<YoutubeApiResponse>() .onErrorResume { YoutubeApiResponse(emptyList()).toMono() } private fun findPlaylistId(url: URI): Mono<String> { if (isPlaylist(url)) return url.toASCIIString().substringAfter("list=").toMono() return youtubeClient .get() .uri(url) .retrieve() .bodyToMono<String>() .map { Jsoup.parse(it, "https://www.youtube.com") } .flatMap { it.select("meta[itemprop=channelId]").firstOrNull().toMono() } .map { it.attr("content") } .map { transformChannelIdToPlaylistId(it) } .switchIfEmpty { RuntimeException("channel id not found").toMono() } } private fun transformChannelIdToPlaylistId(channelId: String) = if (channelId.startsWith("UC")) channelId.replaceFirst("UC".toRegex(), "UU") else channelId override fun type() = type override fun compatibility(url: String): Int = youtubeCompatibility(url) companion object { private const val MAX_PAGE = 10 internal const val URL_PAGE_BASE = "https://www.youtube.com/watch?v=%s" } } @JsonIgnoreProperties(ignoreUnknown = true) internal data class YoutubeApiResponse(val items: List<YoutubeApiItem>, val nextPageToken: String = "") @JsonIgnoreProperties(ignoreUnknown = true) internal data class YoutubeApiItem(val snippet: Snippet) { fun toItem() = ItemFromUpdate( title = snippet.title, description = snippet.description, pubDate = snippet.pubDate(), url = URI(snippet.resourceId.url()), cover = snippet.cover(), mimeType = "video/webm" ) } @JsonIgnoreProperties(ignoreUnknown = true) internal data class Snippet(val title: String, val resourceId: ResourceId, val description: String, val publishedAt: String, val thumbnails: Thumbnails = Thumbnails()) { fun pubDate() = ZonedDateTime.parse(publishedAt, DateTimeFormatter.ISO_DATE_TIME)!! fun cover() = this.thumbnails .betterThumbnail() .map { ItemFromUpdate.Cover(url = URI(it.url!!), width = it.width!!, height = it.height!!) } .orNull() } @JsonIgnoreProperties(ignoreUnknown = true) internal data class ResourceId(var videoId: String) { fun url() = URL_PAGE_BASE.format(videoId) } @JsonIgnoreProperties(ignoreUnknown = true) internal data class Thumbnails( val maxres: Thumbnail? = null, val standard: Thumbnail? = null, val high: Thumbnail? = null, val medium: Thumbnail? = null, @field:JsonProperty("default") val byDefault: Thumbnail? = null ) { fun betterThumbnail(): Optional<Thumbnail> { val v = when { maxres != null -> maxres standard != null -> standard high != null -> high medium != null -> medium byDefault != null -> byDefault else -> null } return Optional.ofNullable(v) } } @JsonIgnoreProperties(ignoreUnknown = true) internal data class Thumbnail(var url: String? = null, var width: Int? = null, var height: Int? = null)
apache-2.0
237da16fa17a20b29cc64e88dd857a7d
40.316667
169
0.576308
4.954697
false
false
false
false
Minikloon/generals.io-kotlin
src/main/kotlin/net/minikloon/generals/game/world/World.kt
1
2545
package net.minikloon.generals.game.world import net.minikloon.generals.game.Game import net.minikloon.generals.game.world.position.Pos import net.minikloon.generals.game.world.terrain.Terrain import net.minikloon.generals.game.world.terrain.TerrainData import net.minikloon.generals.game.world.terrain.TerrainType import net.minikloon.generals.utils.patch import net.minikloon.generals.utils.versionLazy class World(private val game: Game) { private var terrainData = TerrainData.unknownTerrain() private var citiesData = IntArray(0) private var generalsData = IntArray(0) var updates = 0 fun update(mapPatch: IntArray, citiesPatch: IntArray, generalsState: IntArray) { if(terrainData.unknown) terrainData = TerrainData.firstPatch(mapPatch) else terrainData.patch(mapPatch) citiesData = patch(citiesData, citiesPatch) citiesData.sort() generalsData = generalsState ++updates } val width: Int get() = terrainData.width val height: Int get() = terrainData.height val tiles : Collection<Tile> get() = tilesMap.values val generalTiles: List<Tile> get() = generalsData.map { getCached(it)!! } operator fun get(pos: Pos) : Tile? { return get(pos.x, pos.y) } operator fun get(x: Int, y: Int) : Tile? { return getCached(Pos.toIndex(x, y, width)) } private fun getCached(index: Int) : Tile? { return tilesMap[index] } private val tilesMap by versionLazy({updates}) { (0 until width*height).associate { Pair(it, createTile(it)) } } private fun createTile(index: Int) : Tile { val tat = terrainData[index]!! val terrainType = TerrainType.fromId(tat.terrain) ?: throw IllegalStateException("Unknown terrain type ${tat.terrain}") val terrain: Terrain if(tat.terrain < 0) terrain = Terrain(terrainType) else { val player = game.players[tat.terrain] terrain = PlayerOwned(terrainType, player) } val isCity = citiesData.binarySearch(index) >= 0 val general: General? if(terrain is PlayerOwned) { val generalData = generalsData[terrain.owner.index] general = if(generalData == -1) null else General(Pos.fromIndex(generalData, width), terrain.owner) } else general = null return Tile(this, index, tat.troops, terrain, isCity, general) } }
mit
5215ee94e894211c817df10774e12347
33.876712
127
0.645972
3.861912
false
false
false
false
duftler/orca
orca-kayenta/src/test/kotlin/com/netflix/spinnaker/orca/kayenta/pipeline/CleanupCanaryClustersStageTest.kt
1
6821
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.kayenta.pipeline import com.netflix.spinnaker.orca.clouddriver.pipeline.cluster.DisableClusterStage import com.netflix.spinnaker.orca.clouddriver.pipeline.cluster.ShrinkClusterStage import com.netflix.spinnaker.orca.fixture.pipeline import com.netflix.spinnaker.orca.fixture.stage import com.netflix.spinnaker.orca.pipeline.WaitStage import com.netflix.spinnaker.orca.pipeline.model.Stage import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_AFTER import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import java.time.Duration internal object CleanupCanaryClustersStageTest : Spek({ val subject = CleanupCanaryClustersStage() given("a canary deployment pipeline") { val baseline = mapOf( "application" to "spindemo", "account" to "prod", "cluster" to "spindemo-prestaging" ) val controlServerGroupA = serverGroup { mapOf( "application" to "spindemo", "stack" to "prestaging", "freeFormDetails" to "baseline-a" ) } val controlServerGroupB = serverGroup { mapOf( "application" to "spindemo", "stack" to "prestaging", "freeFormDetails" to "baseline-b" ) } val experimentServerGroupA = serverGroup { mapOf( "application" to "spindemo", "stack" to "prestaging", "freeFormDetails" to "canary-a" ) } val experimentServerGroupB = serverGroup { mapOf( "application" to "spindemo", "stack" to "prestaging", "freeFormDetails" to "canary-b" ) } val delayBeforeCleanup = Duration.ofHours(3) val pipeline = pipeline { stage { refId = "1" type = KayentaCanaryStage.STAGE_TYPE context["deployments"] = mapOf( "baseline" to baseline, "serverGroupPairs" to listOf( mapOf( "control" to controlServerGroupA, "experiment" to experimentServerGroupA ), mapOf( "control" to controlServerGroupB, "experiment" to experimentServerGroupB ) ), "delayBeforeCleanup" to delayBeforeCleanup.toString() ) stage { refId = "1<1" type = DeployCanaryServerGroupsStage.STAGE_TYPE } stage { refId = "1>1" type = CleanupCanaryClustersStage.STAGE_TYPE syntheticStageOwner = STAGE_AFTER } } } val canaryCleanupStage = pipeline.stageByRef("1>1") val beforeStages = subject.beforeStages(canaryCleanupStage) it("first disables the control and experiment clusters") { beforeStages.named("Disable control cluster spindemo-prestaging-baseline-a") { assertThat(type).isEqualTo(DisableClusterStage.STAGE_TYPE) assertThat(requisiteStageRefIds).isEmpty() assertThat(context["cloudProvider"]).isEqualTo("aws") assertThat(context["credentials"]).isEqualTo(controlServerGroupA["account"]) assertThat(context["cluster"]).isEqualTo("spindemo-prestaging-baseline-a") assertThat(context["regions"]).isEqualTo(setOf("us-west-1")) assertThat(context["remainingEnabledServerGroups"]).isEqualTo(0) } beforeStages.named("Disable experiment cluster spindemo-prestaging-canary-a") { assertThat(type).isEqualTo(DisableClusterStage.STAGE_TYPE) assertThat(requisiteStageRefIds).isEmpty() assertThat(context["cloudProvider"]).isEqualTo("aws") assertThat(context["credentials"]).isEqualTo(experimentServerGroupA["account"]) assertThat(context["cluster"]).isEqualTo("spindemo-prestaging-canary-a") assertThat(context["regions"]).isEqualTo(setOf("us-west-1")) assertThat(context["remainingEnabledServerGroups"]).isEqualTo(0) } } it("waits after disabling the clusters") { beforeStages.named("Wait before cleanup") { assertThat(type).isEqualTo(WaitStage.STAGE_TYPE) assertThat( requisiteStageRefIds .map(pipeline::stageByRef) .map(Stage::getName) ).containsExactlyInAnyOrder( "Disable control cluster spindemo-prestaging-baseline-a", "Disable control cluster spindemo-prestaging-baseline-b", "Disable experiment cluster spindemo-prestaging-canary-a", "Disable experiment cluster spindemo-prestaging-canary-b" ) assertThat(context["waitTime"]).isEqualTo(delayBeforeCleanup.seconds) } } it("finally destroys the clusters") { beforeStages.named("Cleanup control cluster spindemo-prestaging-baseline-a") { assertThat(type).isEqualTo(ShrinkClusterStage.STAGE_TYPE) assertThat( requisiteStageRefIds .map(pipeline::stageByRef) .map(Stage::getName) ).containsExactly("Wait before cleanup") assertThat(context["cloudProvider"]).isEqualTo("aws") assertThat(context["credentials"]).isEqualTo(controlServerGroupA["account"]) assertThat(context["regions"]).isEqualTo(setOf("us-west-1")) assertThat(context["cluster"]).isEqualTo("spindemo-prestaging-baseline-a") assertThat(context["allowDeleteActive"]).isEqualTo(true) assertThat(context["shrinkToSize"]).isEqualTo(0) } beforeStages.named("Cleanup experiment cluster spindemo-prestaging-canary-a") { assertThat(type).isEqualTo(ShrinkClusterStage.STAGE_TYPE) assertThat( requisiteStageRefIds .map(pipeline::stageByRef) .map(Stage::getName) ).containsExactly("Wait before cleanup") assertThat(context["cloudProvider"]).isEqualTo("aws") assertThat(context["credentials"]).isEqualTo(experimentServerGroupA["account"]) assertThat(context["cluster"]).isEqualTo("spindemo-prestaging-canary-a") assertThat(context["regions"]).isEqualTo(setOf("us-west-1")) assertThat(context["allowDeleteActive"]).isEqualTo(true) assertThat(context["shrinkToSize"]).isEqualTo(0) } } } })
apache-2.0
409712d1254e7b9874ff3408a594aa1f
36.894444
87
0.673068
4.687973
false
false
false
false
Catherine22/WebServices
WebServices/app/src/main/java/com/catherine/webservices/MainActivity.kt
1
17635
package com.catherine.webservices import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.os.Handler import android.support.design.widget.TabLayout import android.support.v4.app.Fragment import android.support.v4.view.GravityCompat import android.view.KeyEvent import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.AdapterView import android.widget.ArrayAdapter import catherine.messagecenter.AsyncResponse import catherine.messagecenter.Server import com.catherine.webservices.adapters.MainViewPagerAdapter import com.catherine.webservices.components.DialogManager import com.catherine.webservices.components.MyDialogFragment import com.catherine.webservices.fragments.OkHttp3Fragment import com.catherine.webservices.fragments.cache.GalleryFragment import com.catherine.webservices.fragments.cellular_wifi.* import com.catherine.webservices.fragments.webview.FullWebViewFragment import com.catherine.webservices.fragments.webview.WebViewSettingsFragment import com.catherine.webservices.fragments.webview.WebViewHistoryFragment import com.catherine.webservices.fragments.webview.WebViewTestListFragment import com.catherine.webservices.interfaces.* import com.catherine.webservices.kotlin_sample.KotlinTemplate import com.catherine.webservices.kotlin_sample.player.Player import com.catherine.webservices.network.NetworkHealthListener import com.catherine.webservices.network.NetworkHelper import com.catherine.webservices.toolkits.CLog import com.catherine.webservices.xml.DOMParser import com.catherine.webservices.xml.SAXParser import com.catherine.webservices.xml.XMLDelegate import com.catherine.webservices.xml.XMLParserListener import kotlinx.android.synthetic.main.activity_main.* import org.dom4j.Document import java.io.IOException import java.util.* /** * Created by Catherine on 2017/8/14. * Soft-World Inc. * [email protected] */ class MainActivity : BaseFragmentActivity(), MainInterface { companion object { private val TAG = "MainActivity" } private var sv: Server? = null private var networkHealthListeners: MutableList<NetworkHealthListener?>? = null @SuppressLint("MissingSuperCall") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState, R.layout.activity_main, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.BLUETOOTH)) } override fun onPermissionGranted() { setView() MyApplication.INSTANCE.init() sv = Server(this@MainActivity, object : AsyncResponse { override fun onFailure(errorCode: Int) { CLog.e(TAG, "errorCode:$errorCode") } }) val checkStateWork = Handler(MyApplication.INSTANCE.calHandlerThread.looper) checkStateWork.post { val networkHelper = NetworkHelper() CLog.d(TAG, "isNetworkHealthy:${NetworkHelper.isNetworkHealthy()}") CLog.d(TAG, "isWifi:${networkHelper.isWifi}") networkHelper.listenToNetworkState(object : NetworkHealthListener { override fun networkConnected(type: String) { CLog.i(TAG, "network connected, type:$type") for (i in 0 until networkHealthListeners!!.size) { networkHealthListeners?.get(i)?.networkConnected(type) } } override fun networkDisable() { CLog.e(TAG, "network disable") for (i in 0 until networkHealthListeners!!.size) { networkHealthListeners?.get(i)?.networkDisable() } } }) } } private val fm = supportFragmentManager /** * 跳页至某Fragment * * @param position position of tabLayout */ override fun switchTab(position: Int) { if (position < resources.getStringArray(R.array.tab_array).size) { vp_content.currentItem = position } } /** * 跳页至某Fragment * * @param id Tag of the Fragment */ override fun callFragment(id: Int) { callFragment(id, null) } /** * 跳页至某Fragment * * @param id Tag of the Fragment * @param bundle argument of the Fragment */ override fun callFragment(id: Int, bundle: Bundle?) { fl_main_container.visibility = View.VISIBLE var fragment: Fragment? = null val tag = Constants.Fragments.TAG(id) val title = Constants.Fragments.TITLE(id) when (id) { //null bundle Constants.Fragments.F_Gallery -> { fragment = GalleryFragment.newInstance(true) } Constants.Fragments.F_WEBVIEW_SETTINGS -> { fragment = WebViewSettingsFragment.newInstance(true) } Constants.Fragments.F_WEBVIEW_HISTORY -> { fragment = WebViewHistoryFragment.newInstance(true) } Constants.Fragments.F_WEBVIEW_TEST_LIST -> { fragment = WebViewTestListFragment.newInstance(true) } Constants.Fragments.F_NETWORK_ANALYTICS -> { fragment = NetworkAnalyticsFragment.newInstance(true) } Constants.Fragments.F_OKHTTP -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { fragment = OkHttp3Fragment.newInstance(true) } else { DialogManager.showAlertDialog(MainActivity@ this, "Can not run okHttp3 due to low API level.\n The min API level must be 19 (KITKAT).") { _, _ -> } } } //has bundle Constants.Fragments.F_FULL_WEBVIEW -> { fragment = FullWebViewFragment.newInstance(true) } Constants.Fragments.F_NETWORK_INFO_ANALYTICS -> { fragment = NetworkInfoAnalyticsFragment.newInstance(true) } Constants.Fragments.F_WIFI_CONFIGURATION_ANALYTICS -> { fragment = WifiConfigurationAnalyticsFragment.newInstance(true) } Constants.Fragments.F_WIFI_INFO -> { fragment = WifiInfoFragment() } Constants.Fragments.F_SCAN_RESULT_INFO -> { fragment = ScanResultInfoFragment() } } //Avoid to launch duplicated fragments if (fm.backStackEntryCount > 0 && fm.fragments[fm.fragments.size - 1].tag == tag) { return } if (bundle != null) fragment?.arguments = bundle CLog.d(TAG, "call $id ,has bundle? ${bundle != null}") val transaction = fm.beginTransaction() transaction.add(R.id.fl_main_container, fragment, tag) transaction.addToBackStack(title) transaction.commitAllowingStateLoss() } /** * 开启fragment dialog * * @param id Tag of the Fragment Dialog */ override fun callFragmentDialog(id: Int) { callFragmentDialog(id, null) } /** * 开启fragment dialog * * @param id Tag of the Fragment Dialog * @param bundle argument of the Fragment Dialog */ override fun callFragmentDialog(id: Int, bundle: Bundle?) { CLog.d(TAG, "call " + id + " with bundle? " + (bundle != null)) var fragment: MyDialogFragment? = null val tag = Constants.Fragments.TAG(id) when (id) { Constants.Fragments.F_D_SCAN_RESULT -> { fragment = ScanResultDialog() } Constants.Fragments.F_D_WIFI_CONFIGURATIONS -> { fragment = WifiConfigurationsDialog() } } if (bundle != null) fragment?.arguments = bundle if (fragment != null) { val trans = supportFragmentManager.beginTransaction() trans.addToBackStack(null) fragment.show(trans, tag) } } override fun onDestroy() { networkHealthListeners?.clear() super.onDestroy() } /** * Clear all fragments in stack */ override fun clearAllFragments() { for (i in 0 until fm.backStackEntryCount) { fm.popBackStack() fl_main_container.visibility = View.GONE } } /** * Simulate BackKey event */ override fun backToPreviousPage() { if (fm.backStackEntryCount > 0) { if (fm.backStackEntryCount == 1) fl_main_container.visibility = View.GONE fm.popBackStack() } else onBackPressed() } override fun addBottomLayout(id: Int) { val view = layoutInflater.inflate(id, null) fl_bottom.addView(view) } override fun restoreBottomLayout() { fl_bottom.removeAllViews() addBottomLayout(R.layout.bottom_main) } override fun getBottomLayout(): View { return fl_bottom } private var backKeyEventListener: MutableList<BackKeyListener?>? = null override fun setBackKeyListener(listener: BackKeyListener) { backKeyEventListener?.set(vp_content.currentItem, listener) } override fun removeBackKeyListener() { backKeyEventListener?.set(vp_content.currentItem, null) } override fun hideKeyboard() { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager if (imm.isActive) { imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); // hide } } override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK) { if (drawer_layout.isDrawerOpen(left_drawer)) { drawer_layout.closeDrawer(left_drawer) return true } else { if (backKeyEventListener?.get(vp_content.currentItem) != null) { backKeyEventListener?.get(vp_content.currentItem)?.OnKeyDown() return true } } } return super.onKeyDown(keyCode, event) } override fun openSlideMenu() { drawer_layout.openDrawer(left_drawer) } private fun setView() { val menu = resources.getStringArray(R.array.drawer_array) left_drawer.adapter = ArrayAdapter<String>(this, R.layout.drawer_list_item, menu) // Sets the drawer shadow drawer_layout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START) left_drawer.onItemClickListener = AdapterView.OnItemClickListener { _, _, pos, _ -> when (pos) { 0 -> { callFragment(Constants.Fragments.F_FULL_WEBVIEW) } 1 -> { callFragment(Constants.Fragments.F_NETWORK_ANALYTICS) } 2 -> { callFragment(Constants.Fragments.F_WEBVIEW_SETTINGS) } 3 -> { callFragment(Constants.Fragments.F_WEBVIEW_HISTORY) } } // left_drawer.setItemChecked(pos, true) drawer_layout.closeDrawer(left_drawer) } vp_content.adapter = MainViewPagerAdapter(MainActivity@ this, supportFragmentManager) tabLayout.setupWithViewPager(vp_content) tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener { override fun onTabSelected(tab: TabLayout.Tab) { restoreBottomLayout() when (tab) { tabLayout.getTabAt(Constants.Fragments.F_APACHE) -> vp_content.currentItem = Constants.Fragments.F_APACHE tabLayout.getTabAt(Constants.Fragments.F_HTTP_URL_CONNECTION) -> vp_content.currentItem = Constants.Fragments.F_HTTP_URL_CONNECTION tabLayout.getTabAt(Constants.Fragments.F_OKHTTP) -> vp_content.currentItem = Constants.Fragments.F_OKHTTP tabLayout.getTabAt(Constants.Fragments.F_DOWNLOADER) -> vp_content.currentItem = Constants.Fragments.F_DOWNLOADER tabLayout.getTabAt(Constants.Fragments.F_CACHE) -> { //Push broadcast before initialize so the broadcast won't be captured at first time. //So I update view twice - first one would be done while initializing, another would be done after catch broadcast. sv?.pushBoolean(Commands.UPDATE_P04, true) vp_content.currentItem = Constants.Fragments.F_CACHE } tabLayout.getTabAt(Constants.Fragments.F_UPLOAD) -> vp_content.currentItem = Constants.Fragments.F_UPLOAD tabLayout.getTabAt(Constants.Fragments.F_SOCKET) -> vp_content.currentItem = Constants.Fragments.F_SOCKET tabLayout.getTabAt(Constants.Fragments.F_WEBVIEW) -> vp_content.currentItem = Constants.Fragments.F_WEBVIEW } } override fun onTabUnselected(tab: TabLayout.Tab) { } override fun onTabReselected(tab: TabLayout.Tab) { } }) //set current tab // tabLayout.setScrollPosition(vp_content.adapter.count, 0f, true) // vp_content.currentItem = vp_content.adapter.count networkHealthListeners = ArrayList() backKeyEventListener = ArrayList() for (i in 0 until vp_content.adapter.count) { backKeyEventListener?.add(null) } addBottomLayout(R.layout.bottom_main) fl_bottom.setOnClickListener { val intent = Intent() intent.setClass(this, DeviceInfoActivity::class.java) startActivity(intent) } iv_github.setOnClickListener { callFragment(Constants.Fragments.F_FULL_WEBVIEW) } tv_github.setOnClickListener { callFragment(Constants.Fragments.F_FULL_WEBVIEW) } iv_menu.setOnClickListener { openSlideMenu() } } override fun listenToNetworkState(listener: NetworkHealthListener) { networkHealthListeners?.add(listener) } override fun stopListeningToNetworkState(listener: NetworkHealthListener) { networkHealthListeners?.remove(listener) } fun testKotlin() { val tmp = KotlinTemplate() tmp.basicSyntax() tmp.printSth() tmp.printSth("20f8-ads3bqwe-9d8vasd", "3f-s1v0m3") tmp.doRecursive() val player = Player() player.play("http://ws.stream.qqmusic.qq.com/C2000012Ppbd3hjGOK.m4a") player.pause() player.resume() player.seekTo(30000) player.stop() tmp.callJava() tmp.runOnNewThread() } fun testXML() { try { val xmlDelegate = XMLDelegate() xmlDelegate.read("name", assets.open("sample.xml"), SAXParser(), object : XMLParserListener { override fun onSuccess(doc: Document) { CLog.d(TAG, "onSuccess:" + doc.asXML()) } override fun onSuccess(message: String) { CLog.d(TAG, "onSuccess:" + message) } override fun onSuccess(message: List<String>) { CLog.d(TAG, "onSuccess:" + message) } override fun onFail() { CLog.d(TAG, "onFail") } }) xmlDelegate.read("time", assets.open("sample.xml"), DOMParser(), object : XMLParserListener { override fun onSuccess(doc: Document) { CLog.d(TAG, "onSuccess:${doc.asXML()}") } override fun onSuccess(message: String) { CLog.d(TAG, "onSuccess:$message") } override fun onSuccess(message: List<String>) { CLog.d(TAG, "onSuccess:$message") } override fun onFail() { CLog.d(TAG, "onFail") } }) xmlDelegate.modify(assets.open("sample.xml"), object : XMLParserListener { override fun onSuccess(doc: Document) { CLog.d(TAG, "onSuccess:${doc.asXML()}") } override fun onSuccess(message: String) { CLog.d(TAG, "onSuccess:$message") } override fun onSuccess(message: List<String>) { CLog.d(TAG, "onSuccess:$message") } override fun onFail() { CLog.d(TAG, "onFail") } }) xmlDelegate.romove(assets.open("sample.xml"), object : XMLParserListener { override fun onSuccess(doc: Document) { CLog.d(TAG, "onSuccess:${doc.asXML()}") } override fun onSuccess(message: String) { CLog.d(TAG, "onSuccess:$message") } override fun onSuccess(message: List<String>) { CLog.d(TAG, "onSuccess:$message") } override fun onFail() { CLog.d(TAG, "onFail") } }) } catch (e: IOException) { e.printStackTrace() } } }
apache-2.0
5635adbe9014b2157a5dba90d3f28d42
33.996024
167
0.59558
4.735808
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/listener/PlayerQuitListener.kt
1
2499
package com.rpkit.players.bukkit.listener import com.rpkit.core.service.Services import com.rpkit.players.bukkit.RPKPlayersBukkit import com.rpkit.players.bukkit.profile.RPKProfile import com.rpkit.players.bukkit.profile.RPKProfileService import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.PlayerQuitEvent import java.util.concurrent.CompletableFuture class PlayerQuitListener(private val plugin: RPKPlayersBukkit) : Listener { @EventHandler fun onPlayerQuit(event: PlayerQuitEvent) { val profileService = Services[RPKProfileService::class.java] ?: return val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return minecraftProfileService.getMinecraftProfile(event.player).thenAccept { minecraftProfile -> if (minecraftProfile == null) return@thenAccept val profile = minecraftProfile.profile plugin.server.scheduler.runTask(plugin, Runnable { val minecraftProfileFutures = plugin.server.onlinePlayers.map { bukkitPlayer -> minecraftProfileService.getMinecraftProfile(bukkitPlayer) } if (profile is RPKProfile) { CompletableFuture.runAsync { CompletableFuture.allOf(*minecraftProfileFutures.toTypedArray()).join() val minecraftProfiles = minecraftProfileFutures.mapNotNull(CompletableFuture<RPKMinecraftProfile?>::join) .filter { it != minecraftProfile } if (!minecraftProfile.isOnline) { if (minecraftProfiles.none { if (it.isOnline) return@none true val otherProfile = it.profile return@none otherProfile is RPKProfile && otherProfile.id?.value == profile.id?.value }) { profileService.unloadProfile(profile) } } } } }) if (!minecraftProfile.isOnline) { minecraftProfileService.unloadMinecraftProfile(minecraftProfile) } } } }
apache-2.0
77d42db3f5ccf12651d0d8b8cdef8ec9
48.019608
121
0.618247
6.200993
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-unconsciousness-bukkit/src/main/kotlin/com/rpkit/unconsciousness/bukkit/command/WakeCommand.kt
1
3714
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.unconsciousness.bukkit.command import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import com.rpkit.unconsciousness.bukkit.RPKUnconsciousnessBukkit import com.rpkit.unconsciousness.bukkit.unconsciousness.RPKUnconsciousnessService import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class WakeCommand(private val plugin: RPKUnconsciousnessBukkit) : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (!sender.hasPermission("rpkit.unconsciousness.command.wake")) { sender.sendMessage(plugin.messages["no-permission-wake"]) return true } val target = if (args.isNotEmpty()) plugin.server.getPlayer(args[0]) ?: sender as? Player else sender as? Player if (target == null) { sender.sendMessage(plugin.messages["wake-no-target"]) return true } val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] if (minecraftProfileService == null) { sender.sendMessage(plugin.messages["no-minecraft-profile-service"]) return true } val characterService = Services[RPKCharacterService::class.java] if (characterService == null) { sender.sendMessage(plugin.messages["no-character-service"]) return true } val unconsciousnessService = Services[RPKUnconsciousnessService::class.java] if (unconsciousnessService == null) { sender.sendMessage(plugin.messages["no-unconsciousness-service"]) return true } val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(target) if (minecraftProfile == null) { sender.sendMessage(plugin.messages["no-minecraft-profile-other", mapOf( "player" to target.name )]) return true } val character = characterService.getPreloadedActiveCharacter(minecraftProfile) if (character == null) { sender.sendMessage(plugin.messages["no-character-other", mapOf( "player" to minecraftProfile.name )]) return true } unconsciousnessService.isUnconscious(character).thenAccept { isUnconscious -> if (!isUnconscious) { sender.sendMessage(plugin.messages["wake-already-awake", mapOf( "character" to character.name )]) return@thenAccept } unconsciousnessService.setUnconscious(character, false).thenRun { sender.sendMessage( plugin.messages["wake-success", mapOf( "character" to character.name )] ) } } return true } }
apache-2.0
60df985cf5f7f522f5ea7273325c3cae
41.689655
120
0.660474
4.677582
false
false
false
false
cketti/k-9
app/k9mail/src/main/java/com/fsck/k9/App.kt
1
4996
package com.fsck.k9 import android.app.Application import android.content.res.Configuration import android.content.res.Resources import app.k9mail.ui.widget.list.MessageListWidgetManager import com.fsck.k9.activity.MessageCompose import com.fsck.k9.controller.MessagingController import com.fsck.k9.notification.NotificationChannelManager import com.fsck.k9.ui.base.AppLanguageManager import com.fsck.k9.ui.base.ThemeManager import com.fsck.k9.ui.base.extensions.currentLocale import java.util.Locale import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.plus import org.koin.android.ext.android.inject import timber.log.Timber class App : Application() { private val messagingController: MessagingController by inject() private val messagingListenerProvider: MessagingListenerProvider by inject() private val themeManager: ThemeManager by inject() private val appLanguageManager: AppLanguageManager by inject() private val notificationChannelManager: NotificationChannelManager by inject() private val messageListWidgetManager: MessageListWidgetManager by inject() private val appCoroutineScope: CoroutineScope = GlobalScope + Dispatchers.Main private var appLanguageManagerInitialized = false override fun onCreate() { Core.earlyInit() super.onCreate() DI.start(this, coreModules + uiModules + appModules) K9.init(this) Core.init(this) initializeAppLanguage() updateNotificationChannelsOnAppLanguageChanges() themeManager.init() messageListWidgetManager.init() messagingListenerProvider.listeners.forEach { listener -> messagingController.addListener(listener) } } private fun initializeAppLanguage() { appLanguageManager.init() applyOverrideLocaleToConfiguration() appLanguageManagerInitialized = true listenForAppLanguageChanges() } private fun applyOverrideLocaleToConfiguration() { appLanguageManager.getOverrideLocale()?.let { overrideLocale -> updateConfigurationWithLocale(superResources.configuration, overrideLocale) } } private fun listenForAppLanguageChanges() { appLanguageManager.overrideLocale .drop(1) // We already applied the initial value .onEach { overrideLocale -> val locale = overrideLocale ?: Locale.getDefault() updateConfigurationWithLocale(superResources.configuration, locale) } .launchIn(appCoroutineScope) } override fun onConfigurationChanged(newConfiguration: Configuration) { applyOverrideLocaleToConfiguration() super.onConfigurationChanged(superResources.configuration) } private fun updateConfigurationWithLocale(configuration: Configuration, locale: Locale) { Timber.d("Updating application configuration with locale '$locale'") val newConfiguration = Configuration(configuration).apply { currentLocale = locale } @Suppress("DEPRECATION") superResources.updateConfiguration(newConfiguration, superResources.displayMetrics) } private val superResources: Resources get() = super.getResources() // Creating a WebView instance triggers something that will cause the configuration of the Application's Resources // instance to be reset to the default, i.e. not containing our locale override. Unfortunately, we're not notified // about this event. So we're checking each time someone asks for the Resources instance whether we need to change // the configuration again. Luckily, right now (Android 11), the platform is calling this method right after // resetting the configuration. override fun getResources(): Resources { val resources = super.getResources() if (appLanguageManagerInitialized) { appLanguageManager.getOverrideLocale()?.let { overrideLocale -> if (resources.configuration.currentLocale != overrideLocale) { Timber.w("Resources configuration was reset. Re-applying locale override.") appLanguageManager.applyOverrideLocale() applyOverrideLocaleToConfiguration() } } } return resources } private fun updateNotificationChannelsOnAppLanguageChanges() { appLanguageManager.appLocale .distinctUntilChanged() .onEach { notificationChannelManager.updateChannels() } .launchIn(appCoroutineScope) } companion object { val appConfig = AppConfig( componentsToDisable = listOf(MessageCompose::class.java) ) } }
apache-2.0
d649dea0f9027a364ca7eccd7770bea0
37.728682
118
0.722378
5.360515
false
true
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustModItemImplMixin.kt
1
1810
package org.rust.lang.core.psi.impl.mixin import com.intellij.lang.ASTNode import com.intellij.psi.PsiDirectory import com.intellij.psi.stubs.IStubElementType import com.intellij.psi.util.PsiTreeUtil import org.rust.ide.icons.RustIcons import org.rust.lang.core.psi.* import org.rust.lang.core.psi.impl.RustPsiImplUtil import org.rust.lang.core.psi.impl.RustStubbedNamedElementImpl import org.rust.lang.core.stubs.RustModItemElementStub import org.rust.lang.core.symbols.RustPath import javax.swing.Icon abstract class RustModItemImplMixin : RustStubbedNamedElementImpl<RustModItemElementStub>, RustModItemElement { constructor(node: ASTNode) : super(node) constructor(stub: RustModItemElementStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType) override fun getIcon(flags: Int): Icon = iconWithVisibility(flags, RustIcons.MODULE) override val isPublic: Boolean get() = RustPsiImplUtil.isPublic(this, stub) override val `super`: RustMod get() = containingMod override val modName: String? get() = name override val crateRelativePath: RustPath.CrateRelative? get() = RustPsiImplUtil.modCrateRelativePath(this) override val ownsDirectory: Boolean = true // Any inline nested mod owns a directory override val ownedDirectory: PsiDirectory? get() { val name = name ?: return null return `super`.ownedDirectory?.findSubdirectory(name) } override val isCrateRoot: Boolean = false override val innerAttrList: List<RustInnerAttrElement> get() = PsiTreeUtil.getChildrenOfTypeAsList(this, RustInnerAttrElement::class.java) override val outerAttrList: List<RustOuterAttrElement> get() = PsiTreeUtil.getChildrenOfTypeAsList(this, RustOuterAttrElement::class.java) }
mit
5d3a19b411e91b23a86cd2f5366ee5ba
36.708333
110
0.755249
4.425428
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/ide/intentions/AddDeriveIntention.kt
1
2646
package org.rust.ide.intentions import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.util.PsiTreeUtil import org.rust.lang.core.psi.* import org.rust.lang.core.psi.util.parentOfType class AddDeriveIntention : PsiElementBaseIntentionAction() { override fun getFamilyName() = "Add derive clause" override fun getText() = "Add derive clause" override fun startInWriteAction() = true override fun invoke(project: Project, editor: Editor, element: PsiElement) { val (item, keyword) = getTarget(element) ?: return val deriveAttr = findOrCreateDeriveAttr(project, item, keyword) ?: return val reformattedDeriveAttr = reformat(project, item, deriveAttr) moveCaret(editor, reformattedDeriveAttr) } override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean = element.isWritable && getTarget(element) != null private fun getTarget(element: PsiElement): Pair<RustStructOrEnumItemElement, PsiElement>? { val item = element.parentOfType<RustStructOrEnumItemElement>() ?: return null val keyword = when (item) { is RustStructItemElement -> item.vis ?: item.struct is RustEnumItemElement -> item.vis ?: item.enum else -> null } ?: return null return item to keyword } private fun findOrCreateDeriveAttr(project: Project, item: RustStructOrEnumItemElement, keyword: PsiElement): RustOuterAttrElement? { val existingDeriveAttr = item.findOuterAttr("derive") if (existingDeriveAttr != null) { return existingDeriveAttr } val attr = RustPsiFactory(project).createOuterAttr("derive()") return item.addBefore(attr, keyword) as RustOuterAttrElement } private fun reformat(project: Project, item: RustStructOrEnumItemElement, deriveAttr: RustOuterAttrElement): RustOuterAttrElement { val marker = Object() PsiTreeUtil.mark(deriveAttr, marker) val reformattedItem = CodeStyleManager.getInstance(project).reformat(item) return PsiTreeUtil.releaseMark(reformattedItem, marker) as RustOuterAttrElement } private fun moveCaret(editor: Editor, deriveAttr: RustOuterAttrElement) { val offset = deriveAttr.metaItem.rparen?.textOffset ?: deriveAttr.rbrack.textOffset ?: deriveAttr.textOffset editor.caretModel.moveToOffset(offset) } }
mit
6082ca57ffe19177670575fcfc4d859e
42.377049
137
0.720711
4.767568
false
false
false
false
googlesamples/android-play-location
LocationAddressKotlin/app/src/main/java/com/google/android/gms/location/sample/locationaddress/Constants.kt
1
1082
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gms.location.sample.locationaddress /** * Constant values reused in this sample. */ object Constants { const val SUCCESS_RESULT = 0 const val FAILURE_RESULT = 1 private const val PACKAGE_NAME = "com.google.android.gms.location.sample.locationaddress" const val RECEIVER = "$PACKAGE_NAME.RECEIVER" const val RESULT_DATA_KEY = "$PACKAGE_NAME.RESULT_DATA_KEY" const val LOCATION_DATA_EXTRA = "$PACKAGE_NAME.LOCATION_DATA_EXTRA" }
apache-2.0
d47ad43a35a392135f4ca9fd298639ad
30.823529
93
0.731978
4.037313
false
false
false
false
cketti/okhttp
okhttp/src/main/kotlin/okhttp3/Handshake.kt
1
6902
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.io.IOException import java.security.Principal import java.security.cert.Certificate import java.security.cert.X509Certificate import javax.net.ssl.SSLPeerUnverifiedException import javax.net.ssl.SSLSession import okhttp3.internal.immutableListOf import okhttp3.internal.toImmutableList /** * A record of a TLS handshake. For HTTPS clients, the client is *local* and the remote server is * its *peer*. * * This value object describes a completed handshake. Use [ConnectionSpec] to set policy for new * handshakes. */ class Handshake internal constructor( /** * Returns the TLS version used for this connection. This value wasn't tracked prior to OkHttp * 3.0. For responses cached by preceding versions this returns [TlsVersion.SSL_3_0]. */ @get:JvmName("tlsVersion") val tlsVersion: TlsVersion, /** Returns the cipher suite used for the connection. */ @get:JvmName("cipherSuite") val cipherSuite: CipherSuite, /** Returns a possibly-empty list of certificates that identify this peer. */ @get:JvmName("localCertificates") val localCertificates: List<Certificate>, // Delayed provider of peerCertificates, to allow lazy cleaning. peerCertificatesFn: () -> List<Certificate> ) { /** Returns a possibly-empty list of certificates that identify the remote peer. */ @get:JvmName("peerCertificates") val peerCertificates: List<Certificate> by lazy { try { peerCertificatesFn() } catch (spue: SSLPeerUnverifiedException) { listOf<Certificate>() } } @JvmName("-deprecated_tlsVersion") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "tlsVersion"), level = DeprecationLevel.ERROR) fun tlsVersion() = tlsVersion @JvmName("-deprecated_cipherSuite") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "cipherSuite"), level = DeprecationLevel.ERROR) fun cipherSuite() = cipherSuite @JvmName("-deprecated_peerCertificates") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "peerCertificates"), level = DeprecationLevel.ERROR) fun peerCertificates() = peerCertificates /** Returns the remote peer's principle, or null if that peer is anonymous. */ @get:JvmName("peerPrincipal") val peerPrincipal: Principal? get() = (peerCertificates.firstOrNull() as? X509Certificate)?.subjectX500Principal @JvmName("-deprecated_peerPrincipal") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "peerPrincipal"), level = DeprecationLevel.ERROR) fun peerPrincipal() = peerPrincipal @JvmName("-deprecated_localCertificates") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "localCertificates"), level = DeprecationLevel.ERROR) fun localCertificates() = localCertificates /** Returns the local principle, or null if this peer is anonymous. */ @get:JvmName("localPrincipal") val localPrincipal: Principal? get() = (localCertificates.firstOrNull() as? X509Certificate)?.subjectX500Principal @JvmName("-deprecated_localPrincipal") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "localPrincipal"), level = DeprecationLevel.ERROR) fun localPrincipal() = localPrincipal override fun equals(other: Any?): Boolean { return other is Handshake && other.tlsVersion == tlsVersion && other.cipherSuite == cipherSuite && other.peerCertificates == peerCertificates && other.localCertificates == localCertificates } override fun hashCode(): Int { var result = 17 result = 31 * result + tlsVersion.hashCode() result = 31 * result + cipherSuite.hashCode() result = 31 * result + peerCertificates.hashCode() result = 31 * result + localCertificates.hashCode() return result } override fun toString(): String { val peerCertificatesString = peerCertificates.map { it.name }.toString() return "Handshake{" + "tlsVersion=$tlsVersion " + "cipherSuite=$cipherSuite " + "peerCertificates=$peerCertificatesString " + "localCertificates=${localCertificates.map { it.name }}}" } private val Certificate.name: String get() = when (this) { is X509Certificate -> subjectDN.toString() else -> type } companion object { @Throws(IOException::class) @JvmStatic @JvmName("get") fun SSLSession.handshake(): Handshake { val cipherSuiteString = checkNotNull(cipherSuite) { "cipherSuite == null" } val cipherSuite = when (cipherSuiteString) { "TLS_NULL_WITH_NULL_NULL", "SSL_NULL_WITH_NULL_NULL" -> { throw IOException("cipherSuite == $cipherSuiteString") } else -> CipherSuite.forJavaName(cipherSuiteString) } val tlsVersionString = checkNotNull(protocol) { "tlsVersion == null" } if ("NONE" == tlsVersionString) throw IOException("tlsVersion == NONE") val tlsVersion = TlsVersion.forJavaName(tlsVersionString) val peerCertificatesCopy = try { peerCertificates.toImmutableList() } catch (_: SSLPeerUnverifiedException) { listOf<Certificate>() } return Handshake(tlsVersion, cipherSuite, localCertificates.toImmutableList()) { peerCertificatesCopy } } private fun Array<out Certificate>?.toImmutableList(): List<Certificate> { return if (this != null) { immutableListOf(*this) } else { emptyList() } } @Throws(IOException::class) @JvmName("-deprecated_get") @Deprecated( message = "moved to extension function", replaceWith = ReplaceWith(expression = "sslSession.handshake()"), level = DeprecationLevel.ERROR) fun get(sslSession: SSLSession) = sslSession.handshake() @JvmStatic fun get( tlsVersion: TlsVersion, cipherSuite: CipherSuite, peerCertificates: List<Certificate>, localCertificates: List<Certificate> ): Handshake { val peerCertificatesCopy = peerCertificates.toImmutableList() return Handshake(tlsVersion, cipherSuite, localCertificates.toImmutableList()) { peerCertificatesCopy } } } }
apache-2.0
9fd7973c653d704a9bf1019b858be0e5
33.683417
97
0.695306
4.586047
false
false
false
false
ssaqua/ProximityService
app/src/main/kotlin/ss/proximityservice/settings/SettingsActivity.kt
1
5512
package ss.proximityservice.settings import android.annotation.SuppressLint import android.app.ActivityManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.BitmapFactory import android.os.Build import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.SeekBar import androidx.core.content.ContextCompat import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import androidx.localbroadcastmanager.content.LocalBroadcastManager import com.google.android.gms.oss.licenses.OssLicensesMenuActivity import dagger.android.support.DaggerAppCompatActivity import kotlinx.android.synthetic.main.activity_settings.* import ss.proximityservice.ProximityService import ss.proximityservice.ProximityService.Companion.INTENT_NOTIFY_ACTIVE import ss.proximityservice.ProximityService.Companion.INTENT_NOTIFY_INACTIVE import ss.proximityservice.R import ss.proximityservice.data.EventObserver import javax.inject.Inject class SettingsActivity : DaggerAppCompatActivity() { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var viewModel: SettingsViewModel private val stateReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { viewModel.updateState(intent.action) } } private val intentFilter = IntentFilter().apply { addAction(INTENT_NOTIFY_ACTIVE) addAction(INTENT_NOTIFY_INACTIVE) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) setSupportActionBar(toolbar) viewModel = ViewModelProviders.of(this, viewModelFactory) .get(SettingsViewModel::class.java) viewModel.serviceState.observe(this, Observer(::updateConditionCard)) viewModel.alert.observe(this, EventObserver { dialog -> dialog.show(this) }) viewModel.operationalModeResId.observe(this, Observer { resId -> @SuppressLint("ResourceType") operational_mode_secondary_text.text = getString(resId) }) viewModel.notificationBehaviorResId.observe(this, Observer { resId -> @SuppressLint("ResourceType") notification_behavior_secondary_text.text = getString(resId) }) viewModel.screenOffDelayResId.observe(this, Observer { resId -> @SuppressLint("ResourceType") screen_off_delay_secondary_text.text = getString(resId) }) viewModel.screenOffDelayProgress.observe(this, Observer { progress -> setting_screen_off_delay_seekbar.progress = progress }) btn_service.setOnClickListener { startService( Intent(this, ProximityService::class.java) .setAction(viewModel.getNextIntentAction()) ) } setting_operational_mode.setOnClickListener { viewModel.operationalModeClick() } setting_notification_behavior.setOnClickListener { viewModel.notificationBehaviorClick() } setting_screen_off_delay_seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { viewModel.screenOffDelayProgress(progress) } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) { viewModel.screenOffDelayUpdate(seekBar.progress) } }) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val taskDescription = ActivityManager.TaskDescription( getString(R.string.app_name), BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher), resources.getColor(R.color.primaryDark) ) setTaskDescription(taskDescription) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.options, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_open_source_licenses -> { startActivity(Intent(this, OssLicensesMenuActivity::class.java)) true } else -> super.onOptionsItemSelected(item) } } override fun onStart() { super.onStart() LocalBroadcastManager.getInstance(this).registerReceiver(stateReceiver, intentFilter) } override fun onStop() { super.onStop() LocalBroadcastManager.getInstance(this).unregisterReceiver(stateReceiver) } private fun updateConditionCard(serviceState: Boolean) { val colorId = if (serviceState) R.color.accent else R.color.primaryLight val conditionTextId = if (serviceState) R.string.condition_active else R.string.condition_inactive val btnTextId = if (serviceState) R.string.button_off else R.string.button_on condition_card.setBackgroundColor(ContextCompat.getColor(this, colorId)) tv_condition.text = getString(conditionTextId) btn_service.text = getString(btnTextId) } }
apache-2.0
8b95cc89687cda8a86aaa4f3ad459de4
38.371429
106
0.706459
5.224645
false
false
false
false
vsch/SmartData
test/src/com/vladsch/smart/SmartCharSequenceWrapperTest.kt
1
4107
/* * Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.vladsch.smart import org.junit.Assert.assertEquals import org.junit.Test class SmartCharSequenceWrapperTest() { val string = """0123456789 0123456789 0123456789 0123456789 """ val chars: CharSequence init { chars = SmartCharArraySequence(string.toCharArray()) } @Test @Throws(Exception::class) fun test_basic1() { val charSeq = SmartCharSequenceWrapper(chars); assertEquals(string, charSeq.toString()) } @Test @Throws(Exception::class) fun test_basic2() { val charSeq = SmartCharSequenceWrapper(chars, 0, string.length); assertEquals(string, charSeq.toString()) } @Test @Throws(Exception::class) fun test_basic3() { val charSeq = SmartCharSequenceWrapper(chars, 0, string.length); val charSeq2 = charSeq.subSequence(0, string.length) assertEquals(charSeq, charSeq2) } @Test @Throws(Exception::class) fun test_basic4() { val charSeq = SmartCharSequenceWrapper(chars, 0, string.length); val charSeq2 = charSeq.subSequence(11, string.length) assertEquals(string.substring(11), charSeq2.toString()) } @Test @Throws(Exception::class) fun test_basic5() { val charSeq = SmartCharSequenceWrapper(chars, 0, string.length); val charSeq1 = charSeq.subSequence(0, 11) val charSeq2 = charSeq.subSequence(11, 22) assertEquals(string.substring(0, 11), charSeq1.toString()) assertEquals(string.substring(11, 22), charSeq2.toString()) } @Test @Throws(Exception::class) fun test_basic6() { val charSeq = SmartCharSequenceWrapper(chars, 0, string.length); val charSeq1 = charSeq.subSequence(0, 11) val charSeq2 = charSeq.subSequence(11, 22) val charSeq3 = charSeq.subSequence(22, 33) assertEquals(string.substring(0, 11), charSeq1.toString()) assertEquals(string.substring(11, 22), charSeq2.toString()) assertEquals(string.substring(22, 33), charSeq3.toString()) // these are contiguous // assertEquals(true, charSeq1.splicedWith(charSeq2) != null) // assertEquals(true, charSeq2.splicedWith(charSeq3) != null) // assertEquals(charSeq.subSequence(0, 33).toString(), charSeq1.splicedWith(charSeq2.splicedWith(charSeq3)).toString()) } @Test @Throws(Exception::class) fun test_basic7() { val charSeq = SmartCharSequenceWrapper(chars, 0, string.length); val charSeq1 = charSeq.subSequence(0, 11) val charSeq2 = charSeq.subSequence(11, 22) val charSeq3 = charSeq.subSequence(22, 33) assertEquals(string.substring(0, 11), String(charSeq1.chars)) assertEquals(string.substring(11, 22), String(charSeq2.chars)) assertEquals(string.substring(22, 33), String(charSeq3.chars)) // these are contiguous // assertEquals(true, charSeq1.splicedWith(charSeq2) != null) // assertEquals(true, charSeq2.splicedWith(charSeq3) != null) // assertEquals(charSeq.subSequence(0, 33).toString(), charSeq1.splicedWith(charSeq2.splicedWith(charSeq3)).toString()) } }
apache-2.0
48b98199ec2b1753ca54787a57e2d85a
35.345133
134
0.67665
4.234021
false
true
false
false
kotlintest/kotlintest
kotest-assertions/src/commonMain/kotlin/io/kotest/inspectors/Inspectors.kt
1
2630
package io.kotest.inspectors fun <T> Array<T>.forAll(fn: (T) -> Unit) = apply { forAll(this.asList(), fn) } fun <T> Collection<T>.forAll(fn: (T) -> Unit) = apply { forAll(this, fn) } fun <T> Sequence<T>.forAll(fn: (T) -> Unit) = apply { forAll(this.toList(), fn) } fun <T> Array<T>.forOne(fn: (T) -> Unit) = apply { forOne(this.asList(), fn) } fun <T> Collection<T>.forOne(fn: (T) -> Unit) = apply { forExactly(1, this, fn) } fun <T> Sequence<T>.forOne(fn: (T) -> Unit) = apply { forOne(this.toList(), fn) } fun <T> Array<T>.forExactly(k: Int, fn: (T) -> Unit) = apply { forExactly(k, this.asList(), fn) } fun <T> Collection<T>.forExactly(k: Int, fn: (T) -> Unit) = apply { forExactly(k, this, fn) } fun <T> Sequence<T>.forExactly(k: Int, fn: (T) -> Unit) = apply { forExactly(k, this.toList(), fn) } fun <T> Array<T>.forSome(f: (T) -> Unit) = apply { forSome(this.asList(), f) } fun <T> Collection<T>.forSome(fn: (T) -> Unit) = apply { forSome(this, fn) } fun <T> Sequence<T>.forSome(fn: (T) -> Unit) = apply { forSome(this.toList(), fn) } fun <T> Array<T>.forAny(f: (T) -> Unit) = apply { forAny(this, f) } fun <T> Collection<T>.forAny(f: (T) -> Unit) = apply { forAny(this, f) } fun <T> Sequence<T>.forAny(fn: (T) -> Unit) = apply { forAny(this.toList(), fn) } fun <T> Array<T>.forAtLeastOne(f: (T) -> Unit) = apply { forAtLeastOne(this.asList(), f) } fun <T> Collection<T>.forAtLeastOne(f: (T) -> Unit) = apply { forAtLeastOne(this, f) } fun <T> Sequence<T>.forAtLeastOne(fn: (T) -> Unit) = apply { forAtLeastOne(this.toList(), fn) } fun <T> Array<T>.forAtLeast(k: Int, f: (T) -> Unit) = apply { forAtLeast(k, this.asList(), f) } fun <T> Collection<T>.forAtLeast(k: Int, fn: (T) -> Unit) = apply { forAtLeast(k, this, fn) } fun <T> Sequence<T>.forAtLeast(k: Int, fn: (T) -> Unit) = apply { forAtLeast(k, this.toList(), fn) } fun <T> Array<T>.forAtMostOne(f: (T) -> Unit) = apply { forAtMost(1, this.asList(), f) } fun <T> Collection<T>.forAtMostOne(f: (T) -> Unit) = apply { forAtMost(1, this, f) } fun <T> Sequence<T>.forAtMostOne(fn: (T) -> Unit) = apply { forAtMostOne(this.toList(), fn) } fun <T> Array<T>.forAtMost(k: Int, f: (T) -> Unit) = apply { forAtMost(k, this.asList(), f) } fun <T> Collection<T>.forAtMost(k: Int, fn: (T) -> Unit) = apply { forAtMost(k, this, fn) } fun <T> Sequence<T>.forAtMost(k: Int, fn: (T) -> Unit) = apply { forAtMost(k, this.toList(), fn) } fun <T> Array<T>.forNone(f: (T) -> Unit) = apply { forNone(this.asList(), f) } fun <T> Collection<T>.forNone(f: (T) -> Unit) = apply { forNone(this, f) } fun <T> Sequence<T>.forNone(fn: (T) -> Unit) = apply { forNone(this.toList(), fn) }
apache-2.0
ea04fef4d9b04025e42fb8500dd755ed
63.146341
100
0.607985
2.573386
false
false
false
false
JackParisi/DroidBox
droidbox/src/main/java/com/github/giacomoparisi/droidbox/recycler/layoutmanager/DroidSpanningLayoutManager.kt
1
2136
package com.github.giacomoparisi.droidbox.recycler.layoutmanager import android.content.Context import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import android.util.AttributeSet import android.view.ViewGroup /** * Created by Giacomo Parisi on 03/11/17. * https://github.com/giacomoParisi */ class DroidSpanningLayoutManager : androidx.recyclerview.widget.LinearLayoutManager { private val horizontalSpace: Int get() = width - paddingRight - paddingLeft private val verticalSpace: Int get() = height - paddingBottom - paddingTop constructor(context: Context) : super(context) constructor(context: Context, orientation: Int, reverseLayout: Boolean) : super(context, orientation, reverseLayout) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) override fun generateDefaultLayoutParams(): androidx.recyclerview.widget.RecyclerView.LayoutParams = spanLayoutSize(super.generateDefaultLayoutParams()) override fun generateLayoutParams(c: Context, attrs: AttributeSet): androidx.recyclerview.widget.RecyclerView.LayoutParams = spanLayoutSize(super.generateLayoutParams(c, attrs)) override fun generateLayoutParams(lp: ViewGroup.LayoutParams): androidx.recyclerview.widget.RecyclerView.LayoutParams = spanLayoutSize(super.generateLayoutParams(lp)) private fun spanLayoutSize(layoutParams: androidx.recyclerview.widget.RecyclerView.LayoutParams): androidx.recyclerview.widget.RecyclerView.LayoutParams { if (orientation == androidx.recyclerview.widget.LinearLayoutManager.HORIZONTAL) { layoutParams.width = Math.round(horizontalSpace / itemCount.toDouble()).toInt() } else if (orientation == androidx.recyclerview.widget.LinearLayoutManager.VERTICAL) { layoutParams.height = Math.round(verticalSpace / itemCount.toDouble()).toInt() } return layoutParams } override fun canScrollVertically(): Boolean = false override fun canScrollHorizontally(): Boolean = false }
apache-2.0
37c748fb1b505eb923d3b966b685c628
45.456522
181
0.777622
5.110048
false
false
false
false
MaximeJallu/AndroidTools
kotlin/RecyclerAdapter.kt
1
6286
package {package_name} import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.oxylane.android.cubeinstore.data.interfaces.IBaseCommunication import com.oxylane.android.cubeinstore.data.interfaces.IViewType import com.oxylane.android.cubeinstore.ui.fragment.interfaces.IAdapterChanged import com.oxylane.android.cubeinstore.ui.viewholder.RecyclerViewHolder import java.security.AccessControlException import java.util.* /** * @author Maxime Jallu * @since 03/05/2017 * * Use this Class for : <br></br> * ... {DOCUMENTATION} */ open class RecyclerAdapter<T> : RecyclerView.Adapter<RecyclerViewHolder<T>> { private var mTList: MutableList<T> private var mFactory: ViewHolderFactory<T>? = null private var mAdapterChanged: IAdapterChanged? = null constructor() { mTList = ArrayList() } constructor(factory: ViewHolderFactory<T>) : this(ArrayList<T>(), factory, null) constructor(viewHolderType: Class<out RecyclerViewHolder<T>>) : this(ArrayList<T>(), viewHolderType, null) constructor(viewHolderType: Class<out RecyclerViewHolder<T>>, callback: IBaseCommunication<*>?) : this(ArrayList<T>(), viewHolderType, callback) @JvmOverloads constructor(TList: MutableList<T>, viewHolderType: Class<out RecyclerViewHolder<T>>, callback: IBaseCommunication<*>? = null) : this(TList, ViewHolderFactory<T>(viewHolderType), callback) constructor(TList: MutableList<T>, factory: ViewHolderFactory<T>, callback: IBaseCommunication<*>?) { mTList = TList mFactory = factory mFactory!!.communication = callback } open fun setFactory(factory: ViewHolderFactory<T>) { mFactory = factory } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder<T>? { if (mFactory == null) { throw AccessControlException("mFactory is not instancied. thanks use setFactory() method.") } return mFactory!!.createVH(LayoutInflater.from(parent.context) .inflate(mFactory!!.getLayoutRes(viewType), parent, false), viewType) } override fun onBindViewHolder(holder: RecyclerViewHolder<T>, position: Int) { holder.item = getItem(position) holder.isBound = false holder.bind(holder.item!!) holder.isBound = true } override fun getItemCount(): Int { return mTList.size } /** * Get Item * * @param position position founded * @return instance to position */ fun getItem(position: Int): T { return mTList[position] } override fun getItemViewType(position: Int): Int { return if (getItem(position) != null && getItem(position) is IViewType) { (getItem(position) as IViewType).itemViewType } else super.getItemViewType(position) } fun putViewType(viewType: Int, viewHolder: Class<out RecyclerViewHolder<T>>) { mFactory!!.putViewType(viewType, viewHolder) } operator fun contains(obj: T): Boolean { return mTList.contains(obj) } protected fun callChangedListener() { if (mAdapterChanged != null) { mAdapterChanged!!.onItemCountChange(itemCount) } } fun setOnAdapterChangedListener(adapterChanged: IAdapterChanged) { mAdapterChanged = adapterChanged } fun setCommunication(communication: IBaseCommunication<*>) { mFactory!!.communication = communication notifyDataSetChanged() } /** * Inserts the specified element at the specified position in this list (optional operation). * Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). * * @param item element to be inserted */ fun addItem(item: T) { mTList.add(item) notifyItemInserted(mTList.size) } /** * Inserts the specified element at the specified position in this list (optional operation). * Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). * * @param item element to be inserted * @param position index at which the specified element is to be inserted */ fun addItem(item: T, position: Int) { val pos = Math.min(position, mTList.size) mTList.add(pos, item) notifyItemInserted(pos) } /** * Inserts the specified element at the specified position in this list (optional operation). * Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). * * @param collection elements to be inserted */ fun addAll(collection: List<T>) { mTList.addAll(collection) val start = Math.max(0, mTList.size - collection.size - 1) notifyItemRangeInserted(start, collection.size) } /** * Inserts the specified element at the specified position in this list (optional operation). * Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). * * @param item the element to be removed */ fun removeItem(item: T) { removeItem(tList.indexOf(item)) } /** * Inserts the specified element at the specified position in this list (optional operation). * Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). * * @param position the index of the element to be removed */ fun removeItem(position: Int) { if (position > -1 && position < mTList.size) { mTList.removeAt(position) notifyItemRemoved(position) } } /** * Set new list items and notifyDataSetChanged() * * @param list new instance items list for bind views * @link notifyDataSetChanged */ fun updateItems(list: MutableList<T>) { mTList = list notifyDataSetChanged() } /** * @return instance items list */ val tList: List<T> get() = mTList val isEmpty: Boolean get() = mTList.isEmpty() }
gpl-3.0
ffaba5033a5947e9ee796ba7c49f6159
32.978378
205
0.669901
4.426761
false
false
false
false
Bombe/Sone
src/main/kotlin/net/pterodactylus/sone/template/ShortenFilter.kt
1
1668
package net.pterodactylus.sone.template import net.pterodactylus.sone.text.LinkPart import net.pterodactylus.sone.text.Part import net.pterodactylus.sone.text.PlainTextPart import net.pterodactylus.util.template.Filter import net.pterodactylus.util.template.TemplateContext import java.util.* /** * [Filter] that shortens a number of [Part]s in order to restrict the maximum visible text length. */ class ShortenFilter : Filter { override fun format(templateContext: TemplateContext?, data: Any?, parameters: Map<String, Any?>?): Any? { @Suppress("UNCHECKED_CAST") val parts = data as? Iterable<Part> ?: return null val length = parameters?.parseInt("length") ?: -1 val cutOffLength = parameters?.parseInt("cut-off-length") ?: length if (length > -1) { var allPartsLength = 0 val shortenedParts = ArrayList<Part>() for (part in parts) { if (part is PlainTextPart) { val longText = part.text if (allPartsLength < cutOffLength) { if (allPartsLength + longText.length > cutOffLength) { shortenedParts.add(PlainTextPart(longText.substring(0, cutOffLength - allPartsLength) + "…")) } else { shortenedParts.add(part) } } allPartsLength += longText.length } else if (part is LinkPart) { if (allPartsLength < cutOffLength) { shortenedParts.add(part) } allPartsLength += part.text.length } else { if (allPartsLength < cutOffLength) { shortenedParts.add(part) } } } if (allPartsLength > length) { return shortenedParts } } return parts } private fun Map<String, Any?>.parseInt(key: String) = this[key]?.toString()?.toInt() }
gpl-3.0
769b0b1185775802e82b7324bd50b631
29.851852
107
0.686675
3.537155
false
false
false
false
pokebyte/ararat
library/src/test/java/org/akop/ararat/BaseTest.kt
1
5700
// Copyright (c) Akop Karapetyan // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package org.akop.ararat import org.akop.ararat.core.Crossword import org.akop.ararat.core.buildCrossword import org.akop.ararat.io.CrosswordFormatter import org.junit.Assert import java.io.File open class BaseTest { val root = File("src/test/res") protected fun CrosswordFormatter.load(path: String): Crossword = File(root, path).inputStream().use { s -> buildCrossword { read(this, s) } } protected fun assertMetadata(actual: Crossword, expected: Metadata) { Assert.assertEquals("Width mismatch!", expected.width, actual.width) Assert.assertEquals("Height mismatch!", expected.height, actual.height) Assert.assertEquals("SquareCount mismatch!", expected.squareCount, actual.squareCount) Assert.assertEquals("Flag mismatch!", expected.flags, actual.flags) Assert.assertEquals("Title mismatch!", expected.title, actual.title) Assert.assertEquals("Description mismatch!", expected.description, actual.description) Assert.assertEquals("Author mismatch!", expected.author, actual.author) Assert.assertEquals("Copyright mismatch!", expected.copyright, actual.copyright) Assert.assertEquals("Comment mismatch!", expected.comment, actual.comment) Assert.assertEquals("Date mismatch!", expected.date, actual.date) Assert.assertEquals("Hash mismatch!", expected.hash, actual.hash) } protected fun assertLayout(actual: Crossword, expected: Array<Array<String?>>) { actual.cellMap.forEachIndexed { i, actualRow -> actualRow.forEachIndexed { j, actualCell -> Assert.assertEquals("Layout mismatch @char[$i,$j]", expected[i][j], actualCell?.chars) } } } protected fun assertAttrLayout(actual: Crossword, expected: Array<Array<String?>>) { actual.cellMap.forEachIndexed { i, actualRow -> actualRow.forEachIndexed { j, actualCell -> Assert.assertEquals("Layout mismatch @attr[$i,$j]", when (expected[i][j]) { "." -> 0 "O" -> Crossword.Cell.ATTR_CIRCLED else -> null }, actualCell?.attrFlags?.toInt()) } } } protected fun assertHints(actual: Crossword, expected: Array<String>) { val actualHints = actual.wordsAcross + actual.wordsDown Assert.assertEquals("Hint count mismatch", actualHints.size, expected.size) (0..actualHints.lastIndex).forEach { i -> Assert.assertEquals("Hint mismatch @[$i]", expected[i], actualHints[i].hintSynopsis()) } } @Suppress("unused") protected fun Crossword.dumpMetadata() { println("width = $width") println("height = $height") println("squareCount = $squareCount") println("title = ${title.enquote()}") println("flags = $flags") println("description = ${description.enquote()}") println("author = ${author.enquote()}") println("copyright = ${copyright.enquote()}") println("comment = ${comment.enquote()}") println("date = $date") println("hash = ${hash.enquote()}") } @Suppress("unused") protected fun Crossword.dumpLayout() { cellMap.forEach { row -> println(row.toList().joinToString("") { it?.chars ?: "#" }) } } @Suppress("unused") protected fun Crossword.dumpAttrLayout() { cellMap.forEach { row -> println(row.toList().joinToString("") { val flag: Int? = it?.attrFlags?.toInt() when { flag?.and(Crossword.Cell.ATTR_CIRCLED) == Crossword.Cell.ATTR_CIRCLED -> "O" flag == 0 -> "." flag == null -> "#" else -> "!" } }) } } @Suppress("unused") protected fun Crossword.dumpHints() { (wordsAcross + wordsDown).forEach { println(it.hintSynopsis().replace("\"", "\\\"")) } } private fun Crossword.Word.hintSynopsis(): String { val dir = when (direction) { Crossword.Word.DIR_ACROSS -> "A" Crossword.Word.DIR_DOWN -> "D" else -> "?" } return "$number$dir.$hint" } private fun String?.enquote(): String? = this?.let { "\"${it.replace("\"", "\\\"") }\"" } }
mit
7861c6991b9fe926ce76869ece9d39f5
39.140845
96
0.605263
4.683648
false
false
false
false
yschimke/oksocial
src/test/kotlin/com/baulsupp/okurl/network/dnsoverhttps/TestDohMain.kt
1
3202
/* * Copyright (C) 2014 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.baulsupp.okurl.network.dnsoverhttps import okhttp3.Cache import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.OkHttpClient import okhttp3.dnsoverhttps.DnsOverHttps import java.io.File import java.io.IOException import java.net.UnknownHostException import java.security.Security import java.util.Arrays object TestDohMain { @Throws(IOException::class) @JvmStatic fun main(args: Array<String>) { Security.insertProviderAt(org.conscrypt.OpenSSLProvider(), 1) var bootstrapClient = OkHttpClient.Builder().build() var names = Arrays.asList("google.com", "graph.facebook.com", "sdflkhfsdlkjdf.ee") try { println("uncached\n********\n") var dnsProviders = DohProviders.providers(bootstrapClient, false) runBatch(dnsProviders, names) val dnsCache = Cache(File("./target/TestDohMain.cache." + System.currentTimeMillis()), (10 * 1024 * 1024).toLong()) println("Bad targets\n***********\n") val url = "https://dns.cloudflare.com/.not-so-well-known/run-dmc-query".toHttpUrl() val badProviders = listOf(DnsOverHttps.Builder().client(bootstrapClient) .url(url) .post(true) .build()) runBatch(badProviders, names) println("cached first run\n****************\n") names = Arrays.asList("google.com", "graph.facebook.com") bootstrapClient = bootstrapClient.newBuilder().cache(dnsCache).build() dnsProviders = DohProviders.providers(bootstrapClient, true) runBatch(dnsProviders, names) println("cached second run\n*****************\n") dnsProviders = DohProviders.providers(bootstrapClient, true) runBatch(dnsProviders, names) } finally { bootstrapClient.connectionPool.evictAll() bootstrapClient.dispatcher.executorService.shutdownNow() val cache = bootstrapClient.cache cache?.close() } } private fun runBatch(dnsProviders: List<DnsOverHttps>, names: List<String>) { var time = System.currentTimeMillis() for (dns in dnsProviders) { println("Testing " + dns.url) for (host in names) { print("$host: ") System.out.flush() try { val results = dns.lookup(host) println(results) } catch (uhe: UnknownHostException) { var e: Throwable? = uhe while (e != null) { println(e.toString()) e = e.cause } } } println() } time = System.currentTimeMillis() - time println("Time: " + time.toDouble() / 1000 + " seconds\n") } }
apache-2.0
d7d6dc6fb1e0eb1d0ec6ad42e2ef4f81
30.087379
92
0.656152
4.058302
false
false
false
false
wireapp/wire-android
storage/src/androidTest/kotlin/com/waz/zclient/storage/userdatabase/assets/AssetsV1TableTestHelper.kt
1
968
package com.waz.zclient.storage.userdatabase.assets import android.content.ContentValues import com.waz.zclient.storage.DbSQLiteOpenHelper class AssetsV1TableTestHelper private constructor() { companion object { private const val ASSETS_TABLE_NAME = "Assets" private const val ASSET_ID_COL = "_id" private const val ASSET_TYPE_COL = "asset_type" private const val ASSET_DATA_COL = "data" fun insertV1Asset( id: String, assetType: String, data: String, openHelper: DbSQLiteOpenHelper ) { val contentValues = ContentValues().also { it.put(ASSET_ID_COL, id) it.put(ASSET_TYPE_COL, assetType) it.put(ASSET_DATA_COL, data) } openHelper.insertWithOnConflict( tableName = ASSETS_TABLE_NAME, contentValues = contentValues ) } } }
gpl-3.0
90a5f75bdb06eee99210baca11f7fda1
28.333333
55
0.585744
4.544601
false
false
false
false
square/leakcanary
shark/src/test/java/shark/TestUtil.kt
2
3771
package shark import java.io.File import java.lang.ref.PhantomReference import java.lang.ref.SoftReference import java.lang.ref.WeakReference import shark.HprofHeapGraph.Companion.openHeapGraph import shark.ReferencePattern.InstanceFieldPattern import shark.ReferencePattern.JavaLocalPattern fun <T : HeapAnalysis> DualSourceProvider.checkForLeaks( objectInspectors: List<ObjectInspector> = emptyList(), computeRetainedHeapSize: Boolean = false, referenceMatchers: List<ReferenceMatcher> = defaultReferenceMatchers, metadataExtractor: MetadataExtractor = MetadataExtractor.NO_OP, proguardMapping: ProguardMapping? = null, leakingObjectFinder: LeakingObjectFinder = FilteringLeakingObjectFinder(ObjectInspectors.jdkLeakingObjectFilters), file: File = File("/no/file") ): T { val inspectors = if (ObjectInspectors.KEYED_WEAK_REFERENCE !in objectInspectors) { objectInspectors + ObjectInspectors.KEYED_WEAK_REFERENCE } else { objectInspectors } val heapAnalyzer = HeapAnalyzer(OnAnalysisProgressListener.NO_OP) val result = openHeapGraph(proguardMapping).use { graph -> heapAnalyzer.analyze( heapDumpFile = file, graph = graph, leakingObjectFinder = leakingObjectFinder, referenceMatchers = referenceMatchers, computeRetainedHeapSize = computeRetainedHeapSize, objectInspectors = inspectors, metadataExtractor = metadataExtractor, ) } if (result is HeapAnalysisFailure) { println(result) } @Suppress("UNCHECKED_CAST") return result as T } fun <T : HeapAnalysis> File.checkForLeaks( objectInspectors: List<ObjectInspector> = emptyList(), computeRetainedHeapSize: Boolean = false, referenceMatchers: List<ReferenceMatcher> = defaultReferenceMatchers, metadataExtractor: MetadataExtractor = MetadataExtractor.NO_OP, proguardMapping: ProguardMapping? = null, leakingObjectFinder: LeakingObjectFinder = FilteringLeakingObjectFinder(ObjectInspectors.jdkLeakingObjectFilters), ): T { return FileSourceProvider(this).checkForLeaks( objectInspectors, computeRetainedHeapSize, referenceMatchers, metadataExtractor, proguardMapping, leakingObjectFinder, this ) } val defaultReferenceMatchers: List<ReferenceMatcher> = listOf( IgnoredReferenceMatcher( pattern = InstanceFieldPattern(WeakReference::class.java.name, "referent") ), IgnoredReferenceMatcher( pattern = InstanceFieldPattern("leakcanary.KeyedWeakReference", "referent") ), IgnoredReferenceMatcher( pattern = InstanceFieldPattern(SoftReference::class.java.name, "referent") ), IgnoredReferenceMatcher( pattern = InstanceFieldPattern(PhantomReference::class.java.name, "referent") ), IgnoredReferenceMatcher( pattern = InstanceFieldPattern("java.lang.ref.Finalizer", "prev") ), IgnoredReferenceMatcher( pattern = InstanceFieldPattern("java.lang.ref.Finalizer", "element") ), IgnoredReferenceMatcher( pattern = InstanceFieldPattern("java.lang.ref.Finalizer", "next") ), IgnoredReferenceMatcher( pattern = InstanceFieldPattern("java.lang.ref.FinalizerReference", "prev") ), IgnoredReferenceMatcher( pattern = InstanceFieldPattern("java.lang.ref.FinalizerReference", "element") ), IgnoredReferenceMatcher( pattern = InstanceFieldPattern("java.lang.ref.FinalizerReference", "next") ), IgnoredReferenceMatcher( pattern = InstanceFieldPattern("sun.misc.Cleaner", "prev") ), IgnoredReferenceMatcher( pattern = InstanceFieldPattern("sun.misc.Cleaner", "next") ), IgnoredReferenceMatcher( pattern = JavaLocalPattern("FinalizerWatchdogDaemon") ), IgnoredReferenceMatcher( pattern = JavaLocalPattern("main") ) )
apache-2.0
6591559b2f27a47dbbc5fcc52ef76783
35.259615
116
0.754177
5.014628
false
false
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/stdext/Profiling.kt
2
3986
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ @file:Suppress("unused") package org.rust.stdext import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicLong import kotlin.system.measureNanoTime import kotlin.system.measureTimeMillis class Timings( private val values: LinkedHashMap<String, Long> = LinkedHashMap() ) { fun <T> measure(name: String, f: () -> T): T { check(name !in values) var result: T? = null values[name] = measureTimeMillis { result = f() } @Suppress("UNCHECKED_CAST") return result as T } fun merge(other: Timings): Timings { check(values.isEmpty() || other.values.isEmpty() || values.size == other.values.size) val result = Timings() for (k in values.keys.union(other.values.keys)) { result.values[k] = // https://www.youtube.com/watch?v=vrfYLlR8X8k&feature=youtu.be&t=25m17s minOf(values.getOrDefault(k, Long.MAX_VALUE), other.values.getOrDefault(k, Long.MAX_VALUE)) } return result } fun report() { if (values.isEmpty()) { println("No metrics recorder") return } val width = values.keys.map { it.length }.max()!! for ((k, v) in values) { println("${k.padEnd(width)}: $v ms") } val total = values.values.sum() println("$total ms total.") println() } } interface RsWatch { val name: String val totalNs: AtomicLong } /** * Useful to quickly measure total times of a certain repeated * operation during profiling. * * Create a global StopWatch instance, use [messages] function * around interesting block, see the results at the end. Note * that [measure] is not reentrant, and will double count * recursive activities like resolve. If you want reentrancy, * use [RsReentrantStopWatch] * * **FOR DEVELOPMENT ONLY** */ class RsStopWatch( override val name: String ) : RsWatch { override var totalNs: AtomicLong = AtomicLong(0) init { WATCHES += this } fun <T> measure(block: () -> T): T { var result: T? = null totalNs.addAndGet(measureNanoTime { result = block() }) @Suppress("UNCHECKED_CAST") return result as T } } /** * Like [RsStopWatch], but requires an explicit start and is reentrant */ class RsReentrantStopWatch(override val name: String) : RsWatch { override val totalNs: AtomicLong = AtomicLong(0) private val started: AtomicBoolean = AtomicBoolean(false) private val nesting = NestingCounter() init { WATCHES += this } fun start() { started.set(true) } fun <T> measure(block: () -> T): T { var result: T? = null if (nesting.enter() && started.get()) { totalNs.addAndGet(measureNanoTime { result = block() }) } else { result = block() } nesting.exit() @Suppress("UNCHECKED_CAST") return result as T } } private class NestingCounter : ThreadLocal<Int>() { override fun initialValue(): Int = 0 fun enter(): Boolean { val v = get() set(v + 1) return v == 0 } fun exit() { set(get() - 1) } } private object WATCHES { private val registered = ConcurrentHashMap.newKeySet<RsWatch>() init { Runtime.getRuntime().addShutdownHook(object : Thread() { override fun run() { println("\nWatches:") for (watch in registered.sortedBy { -it.totalNs.get() }) { val ms = watch.totalNs.get() / 1_000_000 println(" ${ms.toString().padEnd(4)} ms ${watch.name}") } } }) } operator fun plusAssign(watch: RsWatch) { registered += watch } }
mit
70bbe323e22557d942eaa3297bab7656
25.397351
107
0.590818
4.034413
false
false
false
false
Fitbit/MvRx
mvrx/src/main/kotlin/com/airbnb/mvrx/MavericksMutabilityHelper.kt
1
4844
package com.airbnb.mvrx import android.os.Build import android.util.SparseArray import androidx.collection.ArrayMap import androidx.collection.LongSparseArray import androidx.collection.SparseArrayCompat import java.lang.reflect.Field import java.lang.reflect.Modifier import java.lang.reflect.ParameterizedType import kotlin.reflect.KCallable import kotlin.reflect.KClass private const val IMMUTABLE_LIST_MESSAGE = "Use the immutable listOf(...) method instead. You can append it with `val newList = listA + listB`" private const val IMMUTABLE_MAP_MESSAGE = "Use the immutable mapOf(...) method instead. You can append it with `val newMap = mapA + mapB`" /** * Ensures that the state class is immutable. * NOTE: Kotlin collections immutability is a compile-time check only and the underlying classes are * mutable so it is impossible to detect them here. * Kotlin mutability: https://stackoverflow.com/a/33732403/715633 * * As a result, you may not use MutableList, mutableListOf(...) or the map variants by convention only. */ internal fun KClass<*>.assertImmutability() { require(java.isData) { "MvRx state must be a data class! - ${this::class.simpleName}" } fun Field.isSubtype(vararg classes: KClass<*>): Boolean { return classes.any { klass -> return when (val returnType = this.type) { is ParameterizedType -> klass.java.isAssignableFrom(returnType.rawType as Class<*>) else -> klass.java.isAssignableFrom(returnType) } } } java.declaredFields // During tests, jacoco can add a transient field called jacocoData. .filterNot { Modifier.isTransient(it.modifiers) } .forEach { prop -> when { !Modifier.isFinal(prop.modifiers) -> "State property ${prop.name} must be a val, not a var." prop.isSubtype(ArrayList::class) -> "You cannot use ArrayList for ${prop.name}.\n$IMMUTABLE_LIST_MESSAGE" prop.isSubtype(SparseArray::class) -> "You cannot use SparseArray for ${prop.name}.\n$IMMUTABLE_LIST_MESSAGE" prop.isSubtype(LongSparseArray::class) -> "You cannot use LongSparseArray for ${prop.name}.\n$IMMUTABLE_LIST_MESSAGE" prop.isSubtype(SparseArrayCompat::class) -> "You cannot use SparseArrayCompat for ${prop.name}.\n$IMMUTABLE_LIST_MESSAGE" prop.isSubtype(ArrayMap::class) -> "You cannot use ArrayMap for ${prop.name}.\n$IMMUTABLE_MAP_MESSAGE" Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && prop.isSubtype(android.util.ArrayMap::class) -> "You cannot use ArrayMap for ${prop.name}.\n$IMMUTABLE_MAP_MESSAGE" prop.isSubtype(HashMap::class) -> "You cannot use HashMap for ${prop.name}.\n$IMMUTABLE_MAP_MESSAGE" prop.isSubtype(Function::class, KCallable::class) -> { "You cannot use functions inside MvRx state. Only pure data should be represented: ${prop.name}" } else -> null }?.let { throw IllegalArgumentException("Invalid property in state ${this@assertImmutability::class.simpleName}: $it") } } } /** * Since we can only use java reflection, this basically duck types a data class. * componentN methods are also used for @PersistState. */ internal val Class<*>.isData: Boolean get() { if (!declaredMethods.any { it.name == "copy\$default" && it.isSynthetic }) { return false } // if the data class property is internal then kotlin appends '$module_name_debug' to the // expected function name. declaredMethods.firstOrNull { it.name.startsWith("component1") } ?: return false declaredMethods.firstOrNull { it.name == "equals" } ?: return false declaredMethods.firstOrNull { it.name == "hashCode" } ?: return false return true } /** * Checks that a state's value is not changed over its lifetime. */ internal class MutableStateChecker<S : MavericksState>(val initialState: S) { data class StateWrapper<S : MavericksState>(val state: S) { private val originalHashCode = hashCode() fun validate() = require(originalHashCode == hashCode()) { "${state::class.java.simpleName} was mutated. State classes should be immutable." } } private var previousState = StateWrapper(initialState) /** * Should be called whenever state changes. This validates that the hashcode of each state * instance does not change between when it is first set and when the next state is set. * If it does change it means different state instances share some mutable data structure. */ fun onStateChanged(newState: S) { previousState.validate() previousState = StateWrapper(newState) } }
apache-2.0
f42a68287821a5b2956552fcfab1f3de
45.576923
137
0.672378
4.514445
false
false
false
false
rahulsom/grooves
grooves-diagrams/src/main/kotlin/com/github/rahulsom/grooves/asciidoctor/Event.kt
1
4477
package com.github.rahulsom.grooves.asciidoctor import com.github.rahulsom.grooves.asciidoctor.Constants.aggregateHeight import com.github.rahulsom.grooves.asciidoctor.Constants.aggregateWidth import com.github.rahulsom.grooves.asciidoctor.Constants.eventLineHeight import com.github.rahulsom.grooves.asciidoctor.Constants.eventSpace import com.github.rahulsom.grooves.asciidoctor.Constants.offset import com.github.rahulsom.svg.Circle import com.github.rahulsom.svg.G import com.github.rahulsom.svg.ObjectFactory import java.text.SimpleDateFormat import java.util.Date import kotlin.math.abs import kotlin.math.sqrt /** * Represents an event while rendering in asciidoctor. * * @author Rahul Somasunderam */ class Event(private val counter: Int, var id: String, var date: Date, var description: String, var type: EventType) { override fun toString(): String { val sdf = SimpleDateFormat("yyyy-MM-dd") return " - $id ${sdf.format(date)} $description ($type)" } var reverted = false var x: Int = 0 var y: Int = 0 fun buildSvg(index: Int, svgBuilder: SvgBuilder): G { if (description == ".") { return G() } val xOffset = svgBuilder.dates[date]!! // builder.mkp.comment(toString()) val revertedClass = if (this.reverted) "reverted" else "" val g = G().withId("event_$counter") .withClazz("event ${this.type.name} $revertedClass") var x = (10 + aggregateWidth * 2 + xOffset * eventSpace).toInt() var y = index * eventLineHeight + offset + aggregateHeight / 2 while (svgBuilder.allEvents.find { it.x == x && it.y == y } != null) { y -= (20 * sqrt(3.0) / 2).toInt() x += 10 } this.x = x this.y = y if (type == EventType.Revert) { val revertedId = description.split(' ').last() val reverted = svgBuilder.allEvents.find { it.id == revertedId }!! val x1 = reverted.x + (this.x - reverted.x) / 2 val y1 = y - ((this.x - reverted.x) / 3) g.withSVGDescriptionClassOrSVGAnimationClassOrSVGStructureClass( ObjectFactory().createPath( ObjectFactory().createPath().withD("M$x $y Q $x1 $y1, ${reverted.x + 15} ${reverted.y - 15}") ) ) } if (type == EventType.DeprecatedBy || type == EventType.Join || type == EventType.Disjoin) { val otherId = description.split(' ').last() val other = svgBuilder.allEvents.find { it.id == otherId }!! if (other.x > 0 && other.y > 0) { val x1 = (if (type == EventType.Disjoin) -30 else 30) * abs(other.y - y) / eventLineHeight val xContactOffset = if (type == EventType.Disjoin) -10 else 10 val y1 = (y + other.y) / 2 var yOffset = if (y > other.y) 10 else -10 if (type == EventType.DeprecatedBy) { yOffset *= 2 } g.withSVGDescriptionClassOrSVGAnimationClassOrSVGStructureClass( ObjectFactory().createPath( ObjectFactory().createPath().withD( "M${this.x} $y Q ${x1 + this.x} $y1, ${other.x + xContactOffset} ${other.y + yOffset}" ) ) ) } } if (description.contains("created")) { g.withSVGDescriptionClassOrSVGAnimationClassOrSVGStructureClass( ObjectFactory().createCircle( Circle().withCx("${this.x}").withCy("$y").withR("14") .withStrokeDasharray("2, 5") .withClazz("eventCreated ${this.type.name}") ) ) } g.withSVGDescriptionClassOrSVGAnimationClassOrSVGStructureClass( ObjectFactory().createCircle( ObjectFactory().createCircle().withCx("${this.x}").withCy("${this.y}") .withR("10") .withClazz("event ${this.type.name} $revertedClass") ) ) g.withSVGDescriptionClassOrSVGAnimationClassOrSVGStructureClass( ObjectFactory().createText( ObjectFactory().createText().withX("${this.x}").withY("${this.y}") .withClazz("eventId").withContent(this.id) ) ) return g } }
apache-2.0
6283d5d391f70e09f26d3a30db14bb88
37.603448
117
0.565557
4.018851
false
false
false
false
orbit/orbit
src/orbit-server/src/main/kotlin/orbit/server/net/RemoteMeshNodeManager.kt
1
2628
/* Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved. This file is part of the Orbit Project <https://www.orbit.cloud>. See license in LICENSE. */ package orbit.server.net import io.micrometer.core.instrument.Metrics import mu.KotlinLogging import orbit.server.mesh.ClusterManager import orbit.server.mesh.LocalNodeInfo import orbit.server.mesh.MANAGEMENT_NAMESPACE import orbit.server.service.Meters import orbit.shared.mesh.NodeId import orbit.shared.mesh.NodeStatus import java.util.concurrent.ConcurrentHashMap class RemoteMeshNodeManager( private val localNode: LocalNodeInfo, private val clusterManager: ClusterManager ) { private val logger = KotlinLogging.logger { } private val connections = ConcurrentHashMap<NodeId, RemoteMeshNodeConnection>() init { Metrics.gauge(Meters.Names.ConnectedNodes, connections) { c -> c.count().toDouble() } } suspend fun tick() { refreshConnections() } fun getNode(nodeId: NodeId): RemoteMeshNodeConnection? { return connections[nodeId] } suspend fun refreshConnections() { val allNodes = clusterManager.getAllNodes() val meshNodes = allNodes .filter { node -> node.nodeStatus == NodeStatus.ACTIVE } .filter { node -> node.id.namespace == MANAGEMENT_NAMESPACE } .filter { node -> !this.connections.containsKey(node.id) } .filter { node -> node.id != localNode.info.id } .filter { node -> node.url != null && node.url != localNode.info.url } meshNodes.forEach { node -> logger.info("Connecting to peer ${node.id.key} @${node.url}...") this.connections[node.id] = RemoteMeshNodeConnection(localNode, node) logger.debug { "${localNode.info.id} -> ${connections.map { c -> c.key }}"} } connections.values.forEach { node -> if (allNodes.none { it.id == node.id }) { logger.info("Removing peer ${node.id.key}...") connections[node.id]!!.disconnect() connections.remove(node.id) logger.debug { "${localNode.info.id} -> ${connections.map { c -> c.key }}"} } } val visibleNodes = localNode.info.visibleNodes .filter { node -> node.namespace != MANAGEMENT_NAMESPACE } .plus(connections.values.map { n -> n.id }).toSet() if (!visibleNodes.equals(localNode.info.id)) { clusterManager.updateNode(localNode.info.id) { node -> node!!.copy(visibleNodes = visibleNodes) } } } }
bsd-3-clause
be0b77f535e8aee66e50b1b3b28b8eeb
35
93
0.631279
4.191388
false
false
false
false
sangcomz/FishBun
FishBun/src/main/java/com/sangcomz/fishbun/ui/detail/model/DetailImageRepositoryImpl.kt
1
1476
package com.sangcomz.fishbun.ui.detail.model import android.net.Uri import com.sangcomz.fishbun.adapter.image.ImageAdapter import com.sangcomz.fishbun.datasource.FishBunDataSource class DetailImageRepositoryImpl(private val fishBunDataSource: FishBunDataSource) : DetailImageRepository { override fun getPickerImage(index: Int) = fishBunDataSource.getPickerImages().getOrNull(index) override fun getPickerImages(): List<Uri> = fishBunDataSource.getPickerImages() override fun isSelected(imageUri: Uri) = fishBunDataSource.getSelectedImageList().contains(imageUri) override fun getImageIndex(imageUri: Uri) = fishBunDataSource.getSelectedImageList().indexOf(imageUri) override fun selectImage(imageUri: Uri) { fishBunDataSource.selectImage(imageUri) } override fun unselectImage(imageUri: Uri) { fishBunDataSource.unselectImage(imageUri) } override fun getImageAdapter() = fishBunDataSource.getImageAdapter() override fun isFullSelected(): Boolean = fishBunDataSource.getSelectedImageList().size == fishBunDataSource.getMaxCount() override fun checkForFinish(): Boolean = fishBunDataSource.getIsAutomaticClose() && isFullSelected() override fun getMessageLimitReached() = fishBunDataSource.getMessageLimitReached() override fun getMaxCount() = fishBunDataSource.getMaxCount() override fun getDetailPickerViewData() = fishBunDataSource.getDetailViewData() }
apache-2.0
fedc511a4e6d71e5567df5844f84ed8d
35.925
98
0.772358
4.986486
false
false
false
false
http4k/http4k
http4k-incubator/src/test/kotlin/org/http4k/routing/experimental/ResourceLoadingHandlerTest.kt
1
7834
package org.http4k.routing.experimental import com.natpryce.hamkrest.Matcher import com.natpryce.hamkrest.absent import com.natpryce.hamkrest.and import com.natpryce.hamkrest.anything import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.apache.hc.core5.http.io.entity.EmptyInputStream import org.http4k.core.ContentType.Companion.TEXT_PLAIN import org.http4k.core.MemoryRequest import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.NOT_FOUND import org.http4k.core.Status.Companion.NOT_MODIFIED import org.http4k.core.Status.Companion.OK import org.http4k.core.Uri import org.http4k.core.etag.ETag import org.http4k.hamkrest.hasBody import org.http4k.hamkrest.hasContentType import org.http4k.hamkrest.hasHeader import org.http4k.hamkrest.hasStatus import org.http4k.routing.Router import org.http4k.routing.RouterMatch import org.junit.jupiter.api.Test import java.time.Instant class NewResourceLoadingHandlerTest { private val resources = HashMap<String, Resource>() private val handler = ResourceLoadingHandler("/root", InMemoryResourceLoader(resources)) private val now = Instant.parse("2018-08-09T23:06:00Z") @Test fun `no resource returns NOT_FOUND`() { assertThat(handler(MemoryRequest(GET, Uri.of("/root/nosuch"))), equalTo(Response(NOT_FOUND))) } @Test fun `returns content, content type, length and body`() { resources["/file.txt"] = InMemoryResource("content", TEXT_PLAIN, lastModified = now, etag = ETag("etag-value", weak = true)) assertThat( handler(Request(GET, Uri.of("/root/file.txt"))), allOf( hasStatus(OK), hasContentType(TEXT_PLAIN.withNoDirectives()), hasHeader("Content-Length", "7"), hasHeader("Last-Modified", "Thu, 9 Aug 2018 23:06:00 GMT"), hasHeader("ETag", """W/"etag-value""""), hasBody("content") )) } @Test fun `returns no length and last modified if null from resource`() { resources["/file.txt"] = IndeterminateLengthResource() assertThat( handler(Request(GET, Uri.of("/root/file.txt"))), allOf( hasStatus(OK), hasHeader("Content-Length", absent()), hasHeader("Last-Modified", absent()), hasHeader("ETag", absent()) )) } @Test fun `returns content if resource is modified by time`() { resources["/file.txt"] = InMemoryResource("content", TEXT_PLAIN, lastModified = now) assertThat( handler(MemoryRequest(GET, Uri.of("/root/file.txt"), listOf("If-Modified-Since" to "Thu, 9 Aug 2018 23:05:59 GMT"))), allOf( hasStatus(OK), hasHeader("Last-Modified", "Thu, 9 Aug 2018 23:06:00 GMT"), hasBody("content") )) } @Test fun `returns NOT_MODIFIED if resource is not modified by time`() { resources["/file.txt"] = InMemoryResource("content", TEXT_PLAIN, lastModified = now) assertThat( handler(MemoryRequest(GET, Uri.of("/root/file.txt"), listOf("If-Modified-Since" to "Thu, 9 Aug 2018 23:06:00 GMT"))), allOf( hasStatus(NOT_MODIFIED), hasHeader("Last-Modified", "Thu, 9 Aug 2018 23:06:00 GMT"), hasBody("") )) assertThat( handler(MemoryRequest(GET, Uri.of("/root/file.txt"), listOf("If-Modified-Since" to "Thu, 9 Aug 2018 23:06:01 GMT"))), allOf( hasStatus(NOT_MODIFIED), hasHeader("Last-Modified", "Thu, 9 Aug 2018 23:06:00 GMT"), hasBody("") )) } @Test fun `returns content if no last modified property`() { resources["/file.txt"] = InMemoryResource("content", TEXT_PLAIN, lastModified = null) assertThat( handler(MemoryRequest(GET, Uri.of("/root/file.txt"), listOf("If-Modified-Since" to "Thu, 9 Aug 2018 23:05:59 GMT"))), allOf( hasStatus(OK), hasHeader("Last-Modified", absent()), hasBody("content") )) } @Test fun `returns content for incorrect date format`() { resources["/file.txt"] = InMemoryResource("content", TEXT_PLAIN) assertThat( handler(MemoryRequest(GET, Uri.of("/root/file.txt"), listOf("If-Modified-Since" to "NOT A DATE"))), allOf( hasStatus(OK), hasBody("content") )) } @Test fun `returns content if resource does not match etag`() { resources["/file.txt"] = InMemoryResource("content", TEXT_PLAIN, etag = ETag("etag-value", weak = true)) assertThat( handler(MemoryRequest(GET, Uri.of("/root/file.txt"), listOf("If-None-Match" to """"something-else""""))), allOf( hasStatus(OK), hasHeader("ETag", """W/"etag-value""""), hasBody("content") )) } @Test fun `returns NOT_MODIFIED if resource does match etag`() { resources["/file.txt"] = InMemoryResource("content", TEXT_PLAIN, etag = ETag("etag-value", weak = true)) assertThat( handler(MemoryRequest(GET, Uri.of("/root/file.txt"), listOf("If-None-Match" to """"something-else", W/"etag-value""""))), allOf( hasStatus(NOT_MODIFIED), hasHeader("ETag", """W/"etag-value""""), hasBody("") )) assertThat( handler(MemoryRequest(GET, Uri.of("/root/file.txt"), listOf("If-None-Match" to """*"""))), allOf( hasStatus(NOT_MODIFIED), hasHeader("ETag", """W/"etag-value""""), hasBody("") )) assertThat( // should match strong etag even though resource is weak handler(MemoryRequest(GET, Uri.of("/root/file.txt"), listOf("If-None-Match" to """"etag-value""""))), allOf( hasStatus(NOT_MODIFIED), hasHeader("ETag", """W/"etag-value""""), hasBody("") )) } @Test fun `returns content if no etag property`() { resources["/file.txt"] = InMemoryResource("content", TEXT_PLAIN, etag = null) assertThat( handler(MemoryRequest(GET, Uri.of("/root/file.txt"), listOf("If-None-Match" to """*"""))), allOf( hasStatus(OK), hasHeader("ETag", absent()), hasBody("content") )) } } private class IndeterminateLengthResource : Resource { override fun openStream() = EmptyInputStream.INSTANCE!! } private class InMemoryResourceLoader(val resources: Map<String, Resource>) : Router { override fun match(request: Request): RouterMatch = resources[request.uri.path]?.let { RouterMatch.MatchingHandler(it, description) } ?: RouterMatch.Unmatched(description) } /** * Returns a matcher that matches if all of the supplied matchers match. */ fun <T> allOf(matchers: List<Matcher<T>>): Matcher<T> = matchers.reducedWith(Matcher<T>::and) /** * Returns a matcher that matches if all of the supplied matchers match. */ fun <T> allOf(vararg matchers: Matcher<T>): Matcher<T> = allOf(matchers.asList()) @Suppress("UNCHECKED_CAST") private fun <T> List<Matcher<T>>.reducedWith(op: (Matcher<T>, Matcher<T>) -> Matcher<T>): Matcher<T> = when { isEmpty() -> anything else -> reduce(op) }
apache-2.0
e5e3a3ed064cd8972108cc93fcb836a1
36.845411
132
0.584759
4.191546
false
true
false
false
GlimpseFramework/glimpse-framework
jogl/src/main/kotlin/glimpse/jogl/GlimpseFrame.kt
1
2740
package glimpse.jogl import com.jogamp.opengl.GLAutoDrawable import com.jogamp.opengl.GLEventListener import com.jogamp.opengl.awt.GLJPanel import com.jogamp.opengl.util.FPSAnimator import glimpse.gles.Disposables import glimpse.gles.GLES import glimpse.gles.Viewport import glimpse.gles.delegates.GLESDelegate import java.util.concurrent.BlockingQueue import javax.swing.JFrame /** * Glimpse Framework [JFrame] implementation. * * @param title Frame title. * @param width Frame initial width. * @param height Frame initial height. * @param fps Frames per second animation rate. */ class GlimpseFrame(title: String = "", width: Int = 640, height: Int = 480, fps: Int = 30) : JFrame(title) { private val gles: GLES by GLESDelegate private var init: GLES.() -> Unit = {} private var reshape: GLES.(viewport: Viewport) -> Unit = {} private var display: GLES.() -> Unit = {} private var dispose: GLES.() -> Unit = {} private val canvas = GLJPanel() private val animator = FPSAnimator(canvas, fps) private val eventListener = EventListener() private val actions: BlockingQueue<GLES.() -> Unit> = java.util.concurrent.LinkedBlockingQueue() init { contentPane.add(canvas) canvas.addGLEventListener(eventListener) setSize(width, height) setLocationRelativeTo(null) onClose { animator.stop() dispose() System.exit(0) } } /** * Starts GL animation. */ fun start() { isVisible = true animator.start() } /** * GL initialization lambda. */ fun onInit(init: GLES.() -> Unit) { this.init = init } /** * GL resize lambda. */ fun onResize(reshape: GLES.(Viewport) -> Unit) { this.reshape = reshape } /** * GL rendering lambda. */ fun onRender(display: GLES.() -> Unit) { this.display = display } /** * GL dispose lambda. */ fun onDispose(dispose: GLES.() -> Unit) { this.dispose = dispose } /** * Enqueues an [action] to be run in GLES context. */ fun runInGLESContext(action: GLES.() -> Unit) { actions.put(action) } private inner class EventListener : GLEventListener { override fun init(drawable: GLAutoDrawable?) { require(drawable!!.gl.isGL2ES2) { "OpenGL does not conform to GL2ES2 profile." } GLESDelegate(glimpse.jogl.gles.GLES(drawable.gl.gL2ES2)) gles.init() runActions() } override fun reshape(drawable: GLAutoDrawable?, x: Int, y: Int, width: Int, height: Int) { gles.reshape(Viewport(width, height)) } override fun display(drawable: GLAutoDrawable?) { runActions() gles.display() } override fun dispose(drawable: GLAutoDrawable?) { gles.dispose() Disposables.disposeAll() } private fun runActions() { while (!actions.isEmpty()) { actions.poll().invoke(gles) } } } }
apache-2.0
539e61d7ae0438b2f43483025faea52e
21.276423
109
0.685401
3.395291
false
false
false
false
yamamotoj/workshop-jb
src/i_introduction/_8_Extension_Functions/ExtensionFunctions.kt
1
993
package i_introduction._8_Extension_Functions.StringExtensions import util.TODO fun String.lastChar() = this.charAt(this.length() - 1) //'this' can be omitted fun String.lastChar1() = charAt(length() - 1) fun use() { // Try Ctrl+Space after the dot: lastChar() visible in completion and can be easily found "abc".lastChar() } // 'lastChar' compiles to a static function in the class StringExtensionsPackage // and can be used in Java with String as a first argument (see JavaCode8.useExtension) fun todoTask8() = TODO( """ Task 8. Implement extension functions Int.r(), Pair<Int, Int>.r() to support the following way of creating rational numbers: 1.r(), Pair(1, 2).r() """, references = { 1.r(); Pair(1, 2).r(); RationalNumber(1, 9) }) data class RationalNumber(val numerator: Int, val denominator: Int) fun Int.r(): RationalNumber = RationalNumber(this, 1) fun Pair<Int, Int>.r(): RationalNumber = RationalNumber(first, second)
mit
e93cb9d2dd52348e8c031e5c61ba36a2
29.090909
93
0.682779
3.719101
false
false
false
false
openhab/openhab.android
mobile/src/main/java/org/openhab/habdroid/util/AsyncServiceResolver.kt
1
4468
/* * Copyright (c) 2010-2022 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.habdroid.util import android.content.Context import android.net.wifi.WifiManager.MulticastLock import android.util.Log import java.net.BindException import java.net.Inet4Address import java.net.InetAddress import java.net.NetworkInterface import java.net.SocketException import javax.jmdns.JmDNS import javax.jmdns.ServiceEvent import javax.jmdns.ServiceInfo import javax.jmdns.ServiceListener import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ClosedSendChannelException import kotlinx.coroutines.channels.onClosed import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import org.openhab.habdroid.core.OpenHabApplication class AsyncServiceResolver( context: Context, private val serviceType: String, private val scope: CoroutineScope ) : ServiceListener { // Multicast lock for mDNS private val multicastLock: MulticastLock // mDNS service private var jmDns: JmDNS? = null private val serviceInfoChannel = Channel<ServiceInfo>(0) private val localIpv4Address: InetAddress? get() { try { val en = NetworkInterface.getNetworkInterfaces() while (en.hasMoreElements()) { val intf = en.nextElement() val enumIpAddr = intf.inetAddresses while (enumIpAddr?.hasMoreElements() == true) { val inetAddress = enumIpAddr.nextElement() Log.i(TAG, "IP: ${inetAddress.hostAddress}") if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) { Log.i(TAG, "Selected ${inetAddress.getHostAddress()}") return inetAddress } } } } catch (e: SocketException) { Log.e(TAG, e.toString()) } return null } init { val wifiManager = context.getWifiManager(OpenHabApplication.DATA_ACCESS_TAG_SERVER_DISCOVERY) multicastLock = wifiManager.createMulticastLock("HABDroidMulticastLock") multicastLock.setReferenceCounted(true) } suspend fun resolve(): ServiceInfo? { try { multicastLock.acquire() } catch (e: SecurityException) { Log.e(TAG, "Could not acquire multicast lock", e) } catch (e: UnsupportedOperationException) { Log.e(TAG, "Could not acquire multicast lock", e) } Log.i(TAG, "Discovering service $serviceType") withContext(Dispatchers.IO) { try { jmDns = JmDNS.create(localIpv4Address) } catch (e: SocketException) { Log.e(TAG, "Error creating JmDNS instance", e) return@withContext null } catch (e: BindException) { Log.e(TAG, "Error creating JmDNS instance", e) return@withContext null } jmDns?.addServiceListener(serviceType, this@AsyncServiceResolver) } val info = withTimeoutOrNull(DEFAULT_DISCOVERY_TIMEOUT) { serviceInfoChannel.receive() } multicastLock.release() withContext(Dispatchers.IO) { jmDns?.close() } return info } override fun serviceAdded(event: ServiceEvent) { Log.d(TAG, "Service added ${event.name}") jmDns?.requestServiceInfo(event.type, event.name, 1) } override fun serviceRemoved(event: ServiceEvent) {} override fun serviceResolved(event: ServiceEvent) { scope.launch { serviceInfoChannel.trySend(event.info) .onClosed { throw it ?: ClosedSendChannelException("Channel was closed normally") } } } companion object { private val TAG = AsyncServiceResolver::class.java.simpleName private const val DEFAULT_DISCOVERY_TIMEOUT = 3000L const val OPENHAB_SERVICE_TYPE = "_openhab-server-ssl._tcp.local." } }
epl-1.0
e1fc474769d856d3d3e0bfde8f587e7e
32.848485
101
0.654432
4.508577
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/bus_stop_bench/AddBenchStatusOnBusStop.kt
1
2182
package de.westnordost.streetcomplete.quests.bus_stop_bench import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.meta.updateWithCheckDate import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.PEDESTRIAN import de.westnordost.streetcomplete.ktx.arrayOfNotNull import de.westnordost.streetcomplete.ktx.containsAnyKey import de.westnordost.streetcomplete.ktx.toYesNo import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment class AddBenchStatusOnBusStop : OsmFilterQuestType<Boolean>() { override val elementFilter = """ nodes with ( (public_transport = platform and ~bus|trolleybus|tram ~ yes) or (highway = bus_stop and public_transport != stop_position) ) and physically_present != no and naptan:BusStopType != HAR and (!bench or bench older today -4 years) """ override val commitMessage = "Add whether a bus stop has a bench" override val wikiLink = "Key:bench" override val icon = R.drawable.ic_quest_bench_public_transport override val questTypeAchievements = listOf(PEDESTRIAN) override fun getTitle(tags: Map<String, String>): Int { val hasName = tags.containsAnyKey("name", "ref") val isTram = tags["tram"] == "yes" return when { isTram && hasName -> R.string.quest_busStopBench_tram_name_title isTram -> R.string.quest_busStopBench_tram_title hasName -> R.string.quest_busStopBench_name_title else -> R.string.quest_busStopBench_title } } override fun getTitleArgs(tags: Map<String, String>, featureName: Lazy<String?>): Array<String> = arrayOfNotNull(tags["name"] ?: tags["ref"]) override fun createForm() = YesNoQuestAnswerFragment() override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) { changes.updateWithCheckDate("bench", answer.toYesNo()) } }
gpl-3.0
970555d29707a21e2cab2322185d7415
41.784314
101
0.704858
4.434959
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
fluxc/src/main/java/org/wordpress/android/fluxc/store/stats/insights/CommentsStore.kt
2
2551
package org.wordpress.android.fluxc.store.stats.insights import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.stats.InsightsMapper import org.wordpress.android.fluxc.model.stats.LimitMode import org.wordpress.android.fluxc.model.stats.LimitMode.Top import org.wordpress.android.fluxc.network.rest.wpcom.stats.insights.CommentsRestClient import org.wordpress.android.fluxc.persistence.InsightsSqlUtils.CommentsInsightsSqlUtils import org.wordpress.android.fluxc.store.StatsStore.OnStatsFetched import org.wordpress.android.fluxc.store.StatsStore.StatsError import org.wordpress.android.fluxc.store.StatsStore.StatsErrorType.INVALID_RESPONSE import org.wordpress.android.fluxc.tools.CoroutineEngine import org.wordpress.android.util.AppLog.T.STATS import javax.inject.Inject import javax.inject.Singleton @Singleton class CommentsStore @Inject constructor( private val restClient: CommentsRestClient, private val sqlUtils: CommentsInsightsSqlUtils, private val insightsMapper: InsightsMapper, private val coroutineEngine: CoroutineEngine ) { suspend fun fetchComments(siteModel: SiteModel, limitMode: LimitMode, forced: Boolean = false) = coroutineEngine.withDefaultContext(STATS, this, "fetchComments") { val requestedItems = if (limitMode is Top) limitMode.limit else Int.MAX_VALUE if (!forced && sqlUtils.hasFreshRequest(siteModel, requestedItems)) { return@withDefaultContext OnStatsFetched(getComments(siteModel, limitMode), cached = true) } val responsePayload = restClient.fetchTopComments(siteModel, forced = forced) return@withDefaultContext when { responsePayload.isError -> { OnStatsFetched(responsePayload.error) } responsePayload.response != null -> { sqlUtils.insert( siteModel, responsePayload.response, requestedItems ) OnStatsFetched(insightsMapper.map(responsePayload.response, limitMode)) } else -> OnStatsFetched(StatsError(INVALID_RESPONSE)) } } fun getComments(site: SiteModel, cacheMode: LimitMode) = coroutineEngine.run(STATS, this, "getComments") { sqlUtils.select(site)?.let { insightsMapper.map(it, cacheMode) } } }
gpl-2.0
ed1746a265016608126a7a7d6b696d86
50.02
110
0.680125
5.081673
false
false
false
false
CajetanP/coding-exercises
Others/Kotlin/kotlin-koans/src/i_introduction/_4_Lambdas/n04Lambdas.kt
1
736
package i_introduction._4_Lambdas import util.TODO import util.doc4 fun example() { val sum = { x: Int, y: Int -> x + y } val square: (Int) -> Int = { x -> x * x } sum(1, square(2)) == 5 } fun todoTask4(collection: Collection<Int>): Nothing = TODO( """ Task 4. Rewrite 'JavaCode4.task4()' in Kotlin using lambdas: return true if the collection contains an even number. You can find the appropriate function to call on 'Collection' by using code completion. Don't use the class 'Iterables'. """, documentation = doc4(), references = { JavaCode4().task4(collection) }) fun task4(collection: Collection<Int>): Boolean { return collection.any { it % 2 == 0 } }
mit
860e9c5b2d41bf41693b0308543aa299
25.285714
95
0.619565
3.736041
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/test/kotlin/org/wfanet/measurement/api/v2alpha/EventTemplatesTest.kt
1
2196
// Copyright 2020 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.api.v2alpha import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 private const val PROTO_PACKAGE = "wfa.measurement.api.v2alpha.event_templates.testing" private const val BANNER_TEMPLATE_NAME = "$PROTO_PACKAGE.TestBannerTemplate" private const val VIDEO_TEMPLATE_NAME = "$PROTO_PACKAGE.TestVideoTemplate" @RunWith(JUnit4::class) class EventTemplatesTest { @Test fun `initializeTypeRegistry() contains correct templates`() { assertThat(templateFieldList(BANNER_TEMPLATE_NAME)).containsExactly("Gender") assertThat(templateFieldList(VIDEO_TEMPLATE_NAME)).containsExactly("Age Range", "View Duration") } @Test fun `loadTemplate() template contains correct custom options`() { assertThat(getEventTemplateForType(BANNER_TEMPLATE_NAME)?.displayName).isEqualTo("Banner Ad") assertThat(getEventTemplateForType(BANNER_TEMPLATE_NAME)?.description) .isEqualTo("A simple Event Template for a banner ad.") assertThat(getEventTemplateForType(VIDEO_TEMPLATE_NAME)?.displayName).isEqualTo("Video Ad") assertThat(getEventTemplateForType(VIDEO_TEMPLATE_NAME)?.description) .isEqualTo("A simple Event Template for a video ad.") } private fun getEventTemplateForType(messageName: String) = EventTemplates.getEventTemplateForType(messageName) private fun templateFieldList(messageName: String): List<String> = checkNotNull( getEventTemplateForType(messageName)?.eventFields?.map { field -> field.displayName } ) }
apache-2.0
71551f73e00f15ea3a350a0dc90c0769
41.230769
100
0.770947
4.289063
false
true
false
false
ziggy42/Blum
app/src/main/java/com/andreapivetta/blu/ui/main/MainActivity.kt
1
6034
package com.andreapivetta.blu.ui.main import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Bundle import android.support.v4.view.MenuItemCompat import android.support.v7.widget.SearchView import android.view.Menu import android.view.MenuItem import com.andreapivetta.blu.R import com.andreapivetta.blu.common.settings.AppSettings import com.andreapivetta.blu.common.settings.AppSettingsFactory import com.andreapivetta.blu.common.utils.pushFragment import com.andreapivetta.blu.common.utils.visible import com.andreapivetta.blu.data.model.Notification import com.andreapivetta.blu.data.model.PrivateMessage import com.andreapivetta.blu.data.storage.AppStorageFactory import com.andreapivetta.blu.ui.custom.ThemedActivity import com.andreapivetta.blu.ui.newtweet.NewTweetActivity import com.andreapivetta.blu.ui.notifications.NotificationsActivity import com.andreapivetta.blu.ui.privatemessages.PrivateMessagesActivity import com.andreapivetta.blu.ui.profile.UserActivity import com.andreapivetta.blu.ui.search.SearchActivity import com.andreapivetta.blu.ui.settings.SettingsActivity import com.andreapivetta.blu.ui.setup.SetupActivity import com.andreapivetta.blu.ui.timeline.TimelineFragment import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.menu_messages.view.* import kotlinx.android.synthetic.main.menu_notifications.view.* class MainActivity : ThemedActivity(), MainMvpView { private var notificationsCount = 0L private var messagesCount = 0L private val receiver: NotificationUpdatesReceiver? by lazy { NotificationUpdatesReceiver() } private val settings: AppSettings by lazy { AppSettingsFactory.getAppSettings(this) } override fun onResume() { super.onResume() registerReceiver(receiver, IntentFilter(Notification.NEW_NOTIFICATION_INTENT)) registerReceiver(receiver, IntentFilter(PrivateMessage.NEW_PRIVATE_MESSAGE_INTENT)) val storage = AppStorageFactory.getAppStorage() messagesCount = storage.getUnreadPrivateMessagesCount() notificationsCount = storage.getUnreadNotificationsCount() invalidateOptionsMenu() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) fab.setOnClickListener { newTweet() } if (savedInstanceState == null) pushFragment(R.id.container_frameLayout, TimelineFragment.newInstance()) if (!settings.isUserDataDownloaded()) SetupActivity.launch(this) } override fun onDestroy() { super.onDestroy() unregisterReceiver(receiver) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menu?.clear() menuInflater.inflate(R.menu.menu_main, menu) var item = menu?.findItem(R.id.action_notifications) MenuItemCompat.setActionView(item, R.layout.menu_notifications) var view = MenuItemCompat.getActionView(item) val notificationImageButton = view.findViewById(R.id.notificationImageButton) notificationImageButton.setOnClickListener { notificationsCount = 0 invalidateOptionsMenu() openNotifications() } if (notificationsCount > 0) { val notificationsCountTextView = view.notificationCountTextView notificationsCountTextView.visible() notificationsCountTextView.text = if (notificationsCount < 100) "$notificationsCount" else "99" } item = menu?.findItem(R.id.action_messages) MenuItemCompat.setActionView(item, R.layout.menu_messages) view = MenuItemCompat.getActionView(item) val messagesImageButton = view.findViewById(R.id.messagesImageButton) messagesImageButton.setOnClickListener { openMessages() } if (messagesCount > 0) { val messagesCountTextView = view.messagesCountTextView messagesCountTextView.visible() messagesCountTextView.text = if (messagesCount < 100) "$messagesCount" else "99" } (MenuItemCompat.getActionView(menu?.findItem(R.id.action_search)) as SearchView) .setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { search(query) return true } override fun onQueryTextChange(s: String) = false }) return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { R.id.action_settings -> openSettings() R.id.action_profile -> openProfile() } return super.onOptionsItemSelected(item) } override fun search(string: String) { SearchActivity.launch(this, string) } override fun openSettings() { SettingsActivity.launch(this) } override fun openNotifications() { NotificationsActivity.launch(this) } override fun openMessages() { PrivateMessagesActivity.launch(this) } override fun openProfile() { UserActivity.launch(this, settings.getLoggedUserScreenName()) } override fun newTweet() { NewTweetActivity.launch(this) } inner class NotificationUpdatesReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { when (intent?.action) { Notification.NEW_NOTIFICATION_INTENT -> { notificationsCount++ invalidateOptionsMenu() } PrivateMessage.NEW_PRIVATE_MESSAGE_INTENT -> { messagesCount++ invalidateOptionsMenu() } } } } }
apache-2.0
9160d827938a0e4f5e21ffb6dca7672a
35.349398
96
0.69357
5.045151
false
false
false
false
sys1yagi/swipe-android
core/src/main/java/com/sys1yagi/swipe/core/entity/swipe/SwipeElement.kt
1
8437
package com.sys1yagi.swipe.core.entity.swipe import com.google.gson.JsonObject import com.google.gson.annotations.SerializedName import java.util.* /** * Element properties * id (String): the element identifier to identify an element in the associated Scene * element (String): the name of the named Element to inherit properties from * x (Float or Percent): x-position of the left-top corner of element, default is 0 * y (Float or Percent): y-position of the left-top corner of the element, default is 0 * pos ([Float/Percent, Float/Percent]): alternative way to specificy the position by the location of the anchor point * anchor ([Float/Percent, Float/Percent]): anchor point, default is ["50%", "50%"] * w (Float, Percent or "fill"): width of the element, default is "100%". * h (Float, Percent or "fill"): height of the element, default is "100%" * bc (Color): background color, default is clear, animatable * clip (Boolean): Specifies clipping behavior, default is false * borderWidth (Float): Width of the border, default is 0, animatable * borderColor (Color): Color of the border, animatable * cornerRadius (Float): Size of the corner radius, animatable * opacity (Float): Opacity of the element, between 0 to 1, animatable * rotate (Float or Float[3]): Rotation in degree around the anchor point, clockwise, defalut is 0, animatable. * scale (Float or [Float, Float]): Scaling factor around the anchor point, default is [1, 1], animatable * translate ([Float, Float]): Translation, default is [0, 0], animatable * text (String): Text to display * textAlign (String): Text alignment, center (default), left or right * fontSize (Float or Percent): Font size * textColor (Color): Color of the text, animatable * img (URL): Image to display, animatable * mask (URL): Image mask (PNG with the alpha channel) * sprite (URL): Sprite to display * slice ([Int, Int]): Dimension of the sprite * slot ([Int, Int]): Slot to diplay, animatable * path (Path): Path to display (SVG style), animatable * lineWidth (Float): Width of stroke, default is 0 * strokeColor (Color): Color of the stroke, default is black, animatable * fillColor (Color): Fill color, default is clear, animatable * strokeStart (Float): Starting offset, default is 0, animatable * strokeEnd (Float): Ending offset, default is 1, animatable * video or radio (URL): Video/Radio to play * videoStart (Float): Starting point of the video in seconds, default is 0 * videoDuration (Float): Ending point of the video in seconds * stream (Bool): Specifies if the resource specified with the video tag is stream or not, default is false * to (Transition Animation): Specifies the Transitional Animation * loop (Loop Animation): Specifies the Loop Animation * tiling (Bool): Specifies the tiling (to be used with shift loop animation) * action (String): Specifies the Action * repeat (Bool): Repeat rule for the element. The default is false. */ class SwipeElement : Cloneable { @SerializedName("id") var id: String? = null @SerializedName("element") var element: String = "" @SerializedName("x") var x: String = "0" @SerializedName("y") var y: String = "0" @SerializedName("pos") var pos: Array<String>? = null @SerializedName("anchor") var anchor: Array<String>? = null @SerializedName("w") var w: String = "0" @SerializedName("h") var h: String = "0" @SerializedName("bc") var bc: String? = null @SerializedName("clip") var isClip: Boolean = false @SerializedName("borderWidth") var borderWidth: Float = 0.toFloat() @SerializedName("borderColor") var borderColor: String? = null @SerializedName("cornerRadius") var cornerRadius: Float = 0.toFloat() @SerializedName("opacity") var opacity: Float = 0.toFloat() internal set @SerializedName("rotate") var rotate: String = "0" @SerializedName("scale") var scale: String = "[1, 1]" @SerializedName("translate") var translate: FloatArray = FloatArray(2, { 1f }) @SerializedName("text") var text: String = "" @SerializedName("markdown") var markdown: List<String> = listOf() @SerializedName("textAlign") var textAlign: String = "center" @SerializedName("fontSize") var fontSize: String = "" @SerializedName("textColor") var textColor: String = "#000000" @SerializedName("img") var img: String = "" @SerializedName("mask") var mask: String = "" @SerializedName("sprite") var sprite: String = "" @SerializedName("slice") var slice: IntArray? = null @SerializedName("slot") var slot: IntArray? = null // TODO @SerializedName("path") var path: String? = null @SerializedName("fillColor") var fillColor: String? = null @SerializedName("video") var video: String? = null @SerializedName("radio") var radio: String? = null @SerializedName("stream") var isStream: Boolean = false internal set // TODO @SerializedName("to") var to: JsonObject? = null @SerializedName("loop") var loop: JsonObject? = null @SerializedName("tiling") var isTiling: Boolean = false @SerializedName("action") var action: String? = null @SerializedName("repeat") var isRepeat: Boolean = false @SerializedName("shadow") var shadow: Shadow? = null @SerializedName("elements") var elements: List<SwipeElement>? = null override public fun clone(): SwipeElement { val clone = SwipeElement() clone.id = id clone.element = element clone.x = x clone.y = y clone.pos = pos?.copyOf() clone.anchor = anchor?.copyOf() clone.w = w clone.h = h clone.bc = bc clone.isClip = isClip clone.borderWidth = borderWidth clone.borderColor = borderColor clone.cornerRadius = cornerRadius clone.opacity = opacity clone.rotate = rotate clone.scale = scale clone.translate = translate.copyOf() clone.text = text clone.markdown = ArrayList<String>(markdown) clone.textAlign = textAlign clone.fontSize = fontSize clone.textColor = textColor clone.img = img clone.mask = mask clone.sprite = sprite clone.slice = slice?.copyOf() clone.slot = slot?.copyOf() clone.path = path clone.fillColor = fillColor clone.video = video clone.radio = radio clone.isStream = isStream //TODO // clone.to = JsonParser().parse(to?.toString()).asJsonObject // clone.loop = JsonParser().parse(loop?.toString()).asJsonObject clone.isTiling = isTiling clone.action = action clone.isRepeat = isRepeat clone.shadow = shadow?.clone() clone.elements = elements?.let { val cloneElements = ArrayList<SwipeElement>() it.forEach { cloneElements.add(it.clone() as SwipeElement) } cloneElements } ?: null return clone } fun inheritElement(parent: SwipeElement): SwipeElement { val inherited = parent.clone() // if (!"0".equals(w)) { inherited.w = w } if (!"0".equals(h)) { inherited.h = h } if (!"0".equals(x)) { inherited.x = x } if (!"0".equals(y)) { inherited.y = y } shadow?.let { inherited.shadow = it.clone() } inherited.markdown = ArrayList<String>(markdown) inherited.cornerRadius = cornerRadius val elements = elements?.let { ArrayList<SwipeElement>(elements) } ?: ArrayList<SwipeElement>() parent.elements?.forEach { var parentElement: SwipeElement? = it for (i in 0..elements.size - 1) { if (elements[i].id?.let { it.equals(parentElement?.id) } ?: false) { val e = elements[i].inheritElement(parentElement!!) elements[i] = e parentElement = null break } } parentElement?.let { elements.add(it) } } inherited.elements = elements return inherited } }
mit
0d41956ce6eca746d60ed27f71529ae7
30.018382
118
0.624037
4.378308
false
false
false
false
AcapellaSoft/Aconite
aconite-client/src/io/aconite/client/Service.kt
1
1899
package io.aconite.client import io.aconite.Request import io.aconite.serializers.Cookie import io.aconite.serializers.CookieStringSerializer import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicReference import kotlin.reflect.KClass import kotlin.reflect.full.createType interface Service<out T: Any> { /** * Get or create client proxy for specified [address]. * @param[address] address in format: http://localhost:8080 * @return client proxy */ operator fun get(address: String): T /** * Merge [cookie] with internal cookie map. * All subsequent requests will contain this cookie. */ fun setCookie(cookie: Cookie) /** * Clears internal cookie map. * All subsequent requests will contain no cookie. */ fun clearCookie() } internal class ServiceImpl<out T: Any>( private val module: ModuleProxy, private val iface: KClass<T> ) : Service<T> { private val proxies = ConcurrentHashMap<String, T>() private val cookie = AtomicReference(emptyMap<String, String>()) private val cookieSerializer = CookieStringSerializer.create(this::get, Cookie::class.createType())!! override fun get(address: String): T = proxies.computeIfAbsent(address) { // todo: check address format val headers = cookie.get().let { if (it.isNotEmpty()) mapOf( "Cookie" to cookieSerializer.serialize(Cookie(it))!! ) else emptyMap() } val request = Request( headers = headers ) KotlinProxyFactory.create(iface) { fn, args -> module.invoke(fn, address, request, args) } } override fun setCookie(cookie: Cookie) { this.cookie.getAndUpdate { it + cookie.data } } override fun clearCookie() { this.cookie.set(emptyMap()) } }
mit
ba1b910dac6d6479310c1acb0fbacd69
28.6875
105
0.651922
4.468235
false
false
false
false
stepstone-tech/android-material-stepper
material-stepper/src/test/java/com/stepstone/stepper/StepperLayoutTest.kt
2
12624
package com.stepstone.stepper import android.widget.LinearLayout import com.stepstone.stepper.test.* import com.stepstone.stepper.test.assertion.StepperLayoutAssert import com.stepstone.stepper.test.runner.StepperRobolectricTestRunner import com.stepstone.stepper.test.test_double.SpyStepAdapter import com.stepstone.stepper.viewmodel.StepViewModel import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito import org.robolectric.Robolectric import org.robolectric.RuntimeEnvironment /** * @author Piotr Zawadzki */ @RunWith(StepperRobolectricTestRunner::class) class StepperLayoutTest { companion object { const val ORIENTATION_HORIZONTAL = "horizontal" const val LAST_PAGE_INDEX = 2 } lateinit var stepperLayout: StepperLayout @Test fun `All type specific indicators should be hidden when adapter is not set for StepperLayout with 'progress_bar' type`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_PROGRESS_BAR) //when stepperLayout = createStepperLayoutInActivity(attributeSet) //then assertStepperLayout() .hasHorizontalProgressBarHidden() .hasDottedProgressBarHidden() .hasTabsHidden() } @Test fun `All type specific indicators should be hidden when adapter is not set for StepperLayout with 'dots' type`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_DOTS) //when stepperLayout = createStepperLayoutInActivity(attributeSet) //then assertStepperLayout() .hasDottedProgressBarHidden() .hasHorizontalProgressBarHidden() .hasTabsHidden() } @Test fun `All type specific indicators should be hidden when adapter is not set for StepperLayout with 'tabs' type`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_TABS) //when stepperLayout = createStepperLayoutInActivity(attributeSet) //then assertStepperLayout() .hasTabsHidden() .hasHorizontalProgressBarHidden() .hasDottedProgressBarHidden() } @Test fun `All type specific indicators should be hidden when adapter is not set for StepperLayout with 'none' type`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_NONE) //when stepperLayout = createStepperLayoutInActivity(attributeSet) //then assertStepperLayout() .hasHorizontalProgressBarHidden() .hasDottedProgressBarHidden() .hasTabsHidden() } @Test fun `All type specific indicators should be hidden when adapter is set for StepperLayout with 'none' type`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_NONE) //when stepperLayout = createStepperLayoutWithAdapterSetInActivity(attributeSet) //then assertStepperLayout() .hasHorizontalProgressBarHidden() .hasDottedProgressBarHidden() .hasTabsHidden() } @Test fun `Horizontal progress bar should be shown when adapter is set for Stepper with 'progress_bar' type`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_PROGRESS_BAR) //when stepperLayout = createStepperLayoutWithAdapterSetInActivity(attributeSet) //then assertStepperLayout() .hasHorizontalProgressBarShown() .hasDottedProgressBarHidden() .hasTabsHidden() assertFirstFragmentWasNotifiedAboutBeingSelected() } @Test fun `Dotted progress bar should be shown when adapter is set for Stepper with 'dots' type`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_DOTS) //when stepperLayout = createStepperLayoutWithAdapterSetInActivity(attributeSet) //then assertStepperLayout() .hasDottedProgressBarShown() .hasHorizontalProgressBarHidden() .hasTabsHidden() assertFirstFragmentWasNotifiedAboutBeingSelected() } @Test fun `Tabs should be shown when adapter is set for Stepper with 'tabs' type`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_TABS) //when stepperLayout = createStepperLayoutWithAdapterSetInActivity(attributeSet) //then assertStepperLayout() .hasTabsShown() .hasHorizontalProgressBarHidden() .hasDottedProgressBarHidden() assertFirstFragmentWasNotifiedAboutBeingSelected() } @Test fun `Horizontal orientation should be ignored if set in View attributes`() { //given val attributeSet = Robolectric.buildAttributeSet() .addAttribute(R.attr.ms_stepperType, TYPE_DOTS) .addAttribute(android.R.attr.orientation, ORIENTATION_HORIZONTAL) .build() //when stepperLayout = createStepperLayoutInActivity(attributeSet) //then assertStepperLayout().hasOrientation(LinearLayout.VERTICAL) } @Test fun `Horizontal orientation should be ignored if set programmatically`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_DOTS) stepperLayout = createStepperLayoutInActivity(attributeSet) //when stepperLayout.orientation = LinearLayout.HORIZONTAL //then assertStepperLayout().hasOrientation(LinearLayout.VERTICAL) } @Test fun `Horizontal orientation should be set by default`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_DOTS) //when stepperLayout = createStepperLayoutInActivity(attributeSet) //then assertStepperLayout().hasOrientation(LinearLayout.VERTICAL) } @Test fun `Bottom navigation should be visible by default`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_TABS) //when stepperLayout = createStepperLayoutInActivity(attributeSet) //then assertStepperLayout().hasBottomNavigationShown() } @Test fun `Bottom navigation should be hidden if 'ms_showBottomNavigation' attribute is set to 'false' in XML`() { //given val attributeSet = Robolectric.buildAttributeSet() .addAttribute(R.attr.ms_stepperType, TYPE_TABS) .addAttribute(R.attr.ms_showBottomNavigation, "false") .build() //when stepperLayout = createStepperLayoutInActivity(attributeSet) //then assertStepperLayout().hasBottomNavigationHidden() } @Test fun `Bottom navigation should be hidden if set programmatically`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_TABS) stepperLayout = createStepperLayoutInActivity(attributeSet) //when stepperLayout.setShowBottomNavigation(false) //then assertStepperLayout().hasBottomNavigationHidden() } @Test fun `Bottom navigation should be shown if set programmatically`() { //given val attributeSet = Robolectric.buildAttributeSet() .addAttribute(R.attr.ms_stepperType, TYPE_TABS) .addAttribute(R.attr.ms_showBottomNavigation, "false") .build() stepperLayout = createStepperLayoutInActivity(attributeSet) //when stepperLayout.setShowBottomNavigation(true) //then assertStepperLayout().hasBottomNavigationShown() } @Test fun `Should show only 'Next' button on first page by default`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_TABS) //when stepperLayout = createStepperLayoutWithAdapterSetInActivity(attributeSet) //then assertStepperLayout() .hasBackButtonHidden() .hasNextButtonShown() .hasCompleteButtonHidden() } @Test fun `Should show 'Back' and 'Next' buttons on first page if specified in view attributes`() { //given val attributeSet = Robolectric.buildAttributeSet() .addAttribute(R.attr.ms_stepperType, TYPE_TABS) .addAttribute(R.attr.ms_showBackButtonOnFirstStep, true.toString()) .build() //when stepperLayout = createStepperLayoutWithAdapterSetInActivity(attributeSet) //then assertStepperLayout() .hasBackButtonShown() .hasNextButtonShown() .hasCompleteButtonHidden() } @Test fun `Should show 'Complete' button (and 'Back' button) on last page by default`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_TABS) stepperLayout = createStepperLayoutWithAdapterSetInActivity(attributeSet) //when goToLastPage() //then assertStepperLayout() .hasBackButtonShown() .hasNextButtonHidden() .hasCompleteButtonShown() } @Test fun `Should show 'Back' and 'Next' buttons on middle page by default`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_TABS) stepperLayout = createStepperLayoutWithAdapterSetInActivity(attributeSet) //when goToMiddlePage() //then assertStepperLayout() .hasBackButtonShown() .hasNextButtonShown() .hasCompleteButtonHidden() } @Test fun `Should hide 'Next' button on first page if specified in first step's StepViewModel`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_TABS) val firstStepViewModel = StepViewModel.Builder(RuntimeEnvironment.application) .setEndButtonVisible(false) .create() //when stepperLayout = createStepperLayoutWithAdapterSetInActivity(attributeSet, firstStepViewModel, null, null) //then assertStepperLayout() .hasBackButtonHidden() .hasNextButtonHidden() .hasCompleteButtonHidden() } @Test fun `Should hide 'Back' and 'Next' buttons on middle page if specified in middle step's StepViewModel`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_TABS) val middleStepViewModel = StepViewModel.Builder(RuntimeEnvironment.application) .setEndButtonVisible(false) .setBackButtonVisible(false) .create() stepperLayout = createStepperLayoutWithAdapterSetInActivity(attributeSet, null, middleStepViewModel, null) //when goToMiddlePage() //then assertStepperLayout() .hasBackButtonHidden() .hasNextButtonHidden() .hasCompleteButtonHidden() } @Test fun `Should hide 'Complete' button on last page if specified in last step's StepViewModel`() { //given val attributeSet = createAttributeSetWithStepperType(TYPE_TABS) val lastStepViewModel = StepViewModel.Builder(RuntimeEnvironment.application) .setEndButtonVisible(false) .create() stepperLayout = createStepperLayoutWithAdapterSetInActivity(attributeSet, null, null, lastStepViewModel) //when goToLastPage() //then assertStepperLayout() .hasBackButtonShown() .hasNextButtonHidden() .hasCompleteButtonHidden() } private fun goToLastPage() { stepperLayout.currentStepPosition = LAST_PAGE_INDEX } private fun goToMiddlePage() { stepperLayout.currentStepPosition = LAST_PAGE_INDEX - 1 } fun assertStepperLayout(): StepperLayoutAssert { return StepperLayoutAssert.assertThat(stepperLayout) } fun assertFirstFragmentWasNotifiedAboutBeingSelected() { val stepAdapter = stepperLayout.adapter as SpyStepAdapter val firstStep = stepAdapter.steps.get(0) Assert.assertNotNull("Step not found", firstStep) Mockito.verify(firstStep).onSelected() } }
apache-2.0
2ced855c3bb529bde6df72704087a4e9
31.124682
126
0.648606
5.340102
false
true
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/browser/StorageBrowserFragment.kt
1
11341
/* * ************************************************************************* * StorageBrowserFragment.java * ************************************************************************** * Copyright © 2015 VLC authors and VideoLAN * Author: Geoffrey Métais * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * *************************************************************************** */ package org.videolan.vlc.gui.browser import android.annotation.TargetApi import android.content.DialogInterface import android.os.Build import android.os.Bundle import android.text.InputType import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.CheckBox import androidx.appcompat.app.AlertDialog import androidx.appcompat.widget.AppCompatEditText import androidx.collection.SimpleArrayMap import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import kotlinx.coroutines.launch import org.videolan.libvlc.util.AndroidUtil import org.videolan.medialibrary.MLServiceLocator import org.videolan.medialibrary.interfaces.EntryPointsEventsCb import org.videolan.medialibrary.interfaces.Medialibrary import org.videolan.medialibrary.interfaces.media.MediaWrapper import org.videolan.medialibrary.media.MediaLibraryItem import org.videolan.medialibrary.media.Storage import org.videolan.resources.CTX_CUSTOM_REMOVE import org.videolan.tools.* import org.videolan.vlc.MediaParsingService import org.videolan.vlc.R import org.videolan.vlc.databinding.BrowserItemBinding import org.videolan.vlc.gui.AudioPlayerContainerActivity import org.videolan.vlc.gui.dialogs.showContext import org.videolan.vlc.gui.helpers.MedialibraryUtils import org.videolan.vlc.gui.helpers.ThreeStatesCheckbox import org.videolan.vlc.gui.helpers.UiTools import org.videolan.vlc.gui.onboarding.OnboardingActivity import org.videolan.vlc.viewmodels.browser.TYPE_STORAGE import org.videolan.vlc.viewmodels.browser.getBrowserModel import java.io.File const val KEY_IN_MEDIALIB = "key_in_medialib" @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi class StorageBrowserFragment : FileBrowserFragment(), EntryPointsEventsCb, BrowserContainer<MediaLibraryItem> { override var scannedDirectory = false private val processingFolders = SimpleArrayMap<String, CheckBox>() private var snack: com.google.android.material.snackbar.Snackbar? = null private var alertDialog: AlertDialog? = null override val inCards = false override val categoryTitle: String get() = getString(R.string.directories_summary) override fun createFragment(): Fragment { return StorageBrowserFragment() } override fun onCreate(bundle: Bundle?) { var bundle = bundle super.onCreate(bundle) adapter = StorageBrowserAdapter(this) if (bundle == null) bundle = arguments if (bundle != null) scannedDirectory = bundle.getBoolean(KEY_IN_MEDIALIB) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (isRootDirectory && Settings.showTvUi) { snack = com.google.android.material.snackbar.Snackbar.make(view, R.string.tv_settings_hint, com.google.android.material.snackbar.Snackbar.LENGTH_INDEFINITE) if (AndroidUtil.isLolliPopOrLater) snack?.view?.elevation = view.resources.getDimensionPixelSize(R.dimen.audio_player_elevation).toFloat() } } override fun setupBrowser() { viewModel = getBrowserModel(TYPE_STORAGE, mrl, showHiddenFiles) } override fun onStart() { super.onStart() Medialibrary.getInstance().addEntryPointsEventsCb(this) snack?.show() lifecycleScope.launchWhenStarted { if (isAdded) (adapter as StorageBrowserAdapter).updateListState(requireContext()) } } override fun onStop() { super.onStop() Medialibrary.getInstance().removeEntryPointsEventsCb(this) snack?.dismiss() alertDialog?.let { if (it.isShowing) it.dismiss() } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putBoolean(KEY_IN_MEDIALIB, scannedDirectory) } override fun onPrepareOptionsMenu(menu: Menu) { super.onPrepareOptionsMenu(menu) menu.findItem(R.id.ml_menu_custom_dir)?.isVisible = true menu.findItem(R.id.ml_menu_refresh)?.isVisible = false } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.ml_menu_custom_dir) { showAddDirectoryDialog() return true } return super.onOptionsItemSelected(item) } fun browse(media: MediaWrapper, position: Int, scanned: Boolean) { val ft = activity?.supportFragmentManager?.beginTransaction() val next = createFragment() val args = Bundle() args.putParcelable(KEY_MEDIA, media) args.putBoolean(KEY_IN_MEDIALIB, scannedDirectory || scanned) next.arguments = args ft?.replace(R.id.fragment_placeholder, next, media.location) ft?.addToBackStack(if (isRootDirectory) "root" else if (currentMedia != null) currentMedia?.uri.toString() else mrl!!) ft?.commit() } override fun onCtxClick(v: View, position: Int, item: MediaLibraryItem) { if (isRootDirectory) { val storage = adapter.getItem(position) as Storage val path = storage.uri.path ?: return lifecycleScope.launchWhenStarted { val isCustom = viewModel.customDirectoryExists(path) if (isCustom && isAdded) showContext(requireActivity(), this@StorageBrowserFragment, position, item.title, CTX_CUSTOM_REMOVE) } } } override fun onCtxAction(position: Int, option: Long) { val storage = adapter.getItem(position) as Storage val path = storage.uri.path ?: return viewModel.deleteCustomDirectory(path) viewModel.remove(storage) (activity as AudioPlayerContainerActivity).updateLib() } override fun onClick(v: View, position: Int, item: MediaLibraryItem) { val mw = (item as? Storage)?.let { MLServiceLocator.getAbstractMediaWrapper(it.uri) } ?: return mw.type = MediaWrapper.TYPE_DIR browse(mw, position, (DataBindingUtil.findBinding<BrowserItemBinding>(v))?.browserCheckbox?.state == ThreeStatesCheckbox.STATE_CHECKED) } override fun onMainActionClick(v: View, position: Int, item: MediaLibraryItem) {} fun checkBoxAction(v: View, mrl: String) { val tscb = v as ThreeStatesCheckbox val checked = tscb.state == ThreeStatesCheckbox.STATE_CHECKED val activity = requireActivity() if (activity is OnboardingActivity) { val path = mrl.sanitizePath() if (checked) { MediaParsingService.preselectedStorages.removeAll { it.startsWith(path) } MediaParsingService.preselectedStorages.add(path) } else { MediaParsingService.preselectedStorages.removeAll { it.startsWith(path) } } } else { if (checked) { MedialibraryUtils.addDir(mrl, v.context.applicationContext) val prefs = Settings.getInstance(v.getContext()) if (prefs.getInt(KEY_MEDIALIBRARY_SCAN, -1) != ML_SCAN_ON) prefs.putSingle(KEY_MEDIALIBRARY_SCAN, ML_SCAN_ON) } else MedialibraryUtils.removeDir(mrl) processEvent(v as CheckBox, mrl) } } internal fun processEvent(cbp: CheckBox, mrl: String) { cbp.isEnabled = false processingFolders.put(mrl, cbp) } override fun onEntryPointBanned(entryPoint: String, success: Boolean) {} override fun onEntryPointUnbanned(entryPoint: String, success: Boolean) {} override fun onEntryPointAdded(entryPoint: String, success: Boolean) {} override fun onEntryPointRemoved(entryPoint: String, success: Boolean) { var entryPoint = entryPoint if (entryPoint.endsWith("/")) entryPoint = entryPoint.substring(0, entryPoint.length - 1) if (processingFolders.containsKey(entryPoint)) { processingFolders.remove(entryPoint)?.let { handler.post { it.isEnabled = true if (success) { (adapter as StorageBrowserAdapter).updateMediaDirs(requireContext()) adapter.notifyDataSetChanged() } else it.isChecked = true } } } } override fun onDiscoveryStarted(entryPoint: String) {} override fun onDiscoveryProgress(entryPoint: String) {} override fun onDiscoveryCompleted(entryPoint: String) { var path = entryPoint if (path.endsWith("/")) path = path.dropLast(1) if (processingFolders.containsKey(path)) { val finalPath = path handler.post { processingFolders.get(finalPath)?.isEnabled = true } (adapter as StorageBrowserAdapter).updateMediaDirs(requireContext()) } } private fun showAddDirectoryDialog() { val context = activity val builder = AlertDialog.Builder(context!!) val input = AppCompatEditText(context) input.inputType = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS builder.setTitle(R.string.add_custom_path) builder.setMessage(R.string.add_custom_path_description) builder.setView(input) builder.setNegativeButton(R.string.cancel) { _, _ -> } builder.setPositiveButton(R.string.ok, DialogInterface.OnClickListener { dialog, which -> val path = input.text.toString().trim { it <= ' ' } val f = File(path) if (!f.exists() || !f.isDirectory) { UiTools.snacker(view!!, getString(R.string.directorynotfound, path)) return@OnClickListener } lifecycleScope.launch(CoroutineExceptionHandler { _, _ -> }) { viewModel.addCustomDirectory(f.canonicalPath).join() viewModel.browseRoot() } }) alertDialog = builder.show() } override fun containerActivity() = requireActivity() override val isNetwork = false override val isFile = true }
gpl-2.0
d9367f762ad538052547ece25ac383d1
40.232727
168
0.67625
4.716722
false
false
false
false
AoEiuV020/PaNovel
api/src/main/java/cc/aoeiuv020/panovel/api/site/n9txs.kt
1
1974
@file:Suppress("UnnecessaryVariable") package cc.aoeiuv020.panovel.api.site import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext class N9txs : DslJsoupNovelContext() {init { // 服务器超时,可能是碰巧炸了, // enabled = false site { name = "九桃小说" baseUrl = "https://www.9taoxs.com" logo = "https://tiebapic.baidu.com/forum/pic/item/810a19d8bc3eb135716cd7dfb11ea8d3fd1f442e.jpg" } search { post { // https://www.9txs.com/search.html?searchkey=%E9%83%BD%E5%B8%82 url = "https://so.9txs.org/www/" data { "searchkey" to it } } document { items("ul.library > li") { name("> a.bookname") author("a.author") } } } // https://www.9txs.com/book/43776.html detailPageTemplate = "/book/%s.html" detail { document { novel { name("div.detail > h1") author("div.detail > p:nth-child(3) > a:nth-child(1)") } image("div.detail > a > img") update("div.detail > p:nth-child(6) > span", format = "yyyy-MM-dd HH:mm:ss", block = pickString("\\((.*)\\)")) introduction("p.intro") } } // https://www.9txs.com/book/43776/ chaptersPageTemplate = "/book/%s/" chapters { document { items("div.read > dl:not(:contains(最新章节)) > dd > a") lastUpdate("div.headline > p:nth-child(4)", format = "yyyy-MM-dd HH:mm", block = pickString("更新:(.*)")) } } // https://www.9txs.com/book/43776/166315.html contentPageTemplate = "/book/%s.html" content { document { items("#content") }.dropWhile { it.startsWith("九桃小说") }.dropLastWhile { it.startsWith("您可以在百度里搜索") } } } }
gpl-3.0
ef6fa98e5c2fac2d131488a5cc81d70f
28.2
122
0.508957
3.383244
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/nbt/tags/NbtTag.kt
1
2192
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.tags import java.io.DataOutputStream import java.io.OutputStream import org.apache.commons.lang3.StringUtils interface NbtTag { /** * The payload size of this tag. */ val payloadSize: Int /** * The `Type ID` enum value for this tag. */ val typeId: NbtTypeId /** * Write out the contents of this tag to the given [OutputStream]. */ fun write(stream: DataOutputStream) /** * toString helper method. */ fun toString(sb: StringBuilder, indentLevel: Int, writerState: WriterState): StringBuilder /** * Create a deep-copy of this [NbtTag]. */ fun copy(): NbtTag } // Default implementation via extension properties /** * The `Type ID` byte value for this tag. */ val NbtTag.typeIdByte get() = typeId.typeIdByte val forbiddenCharacters = Regex("""[:(){}\[\],]""") val badFormat = Regex("""^[\d+\-\\\s\n:{}\[\](),].*|.*["\\:{}\[\]()\s\n,]${'$'}""") fun writeString(sb: StringBuilder, s: String): StringBuilder { if (s.isBlank()) { return sb.append('"').append(s.replace("\n", "\\n")).append('"') } if (s == "bytes" || s == "ints" || s == "longs" || s == "true" || s == "false") { // keywords must be quoted return sb.append('"').append(s).append('"') } val replaced = StringUtils.replaceEach(s, arrayOf("\\", "\n", "\"", "\t"), arrayOf("\\\\", "\\n", "\\\"", "\\t")) if (forbiddenCharacters in s || s.matches(badFormat)) { // Use quotes around this awful string return sb.append('"').append(replaced).append('"') } // prefer no quotes return sb.append(replaced) } enum class WriterState { COMPOUND, LIST } fun indent(sb: StringBuilder, indentLevel: Int) { if (indentLevel <= 0) { return } for (i in 0 until indentLevel) { sb.append(" ") } } fun appendName(sb: StringBuilder, name: String?) { if (name != null) { writeString(sb, name) } else { sb.append("\"\"") } sb.append(": ") }
mit
c250d88a2fa9d2a9794122992bffb683
21.597938
117
0.567518
3.727891
false
false
false
false
edvin/tornadofx
src/test/kotlin/tornadofx/testapps/PojoTreeTableColumns.kt
1
1973
package tornadofx.testapps import javafx.scene.control.TreeItem import tornadofx.* import tornadofx.tests.JavaPerson class PojoTreeTableColumnsApp : App(PojoTreeTableColumns::class) class PojoTreeTableColumns : View("Pojo Tree Table Columns") { val people = observableListOf( JavaPerson("Mary Hanes", "IT Administration", "[email protected]", "[email protected]", listOf( JavaPerson("Jacob Mays", "IT Help Desk", "[email protected]", "[email protected]"), JavaPerson("John Ramsy", "IT Help Desk", "[email protected]", "[email protected]"))), JavaPerson("Erin James", "Human Resources", "[email protected]", "[email protected]", listOf( JavaPerson("Erlick Foyes", "Customer Service", "[email protected]", "[email protected]"), JavaPerson("Steve Folley", "Customer Service", "[email protected]", "[email protected]"), JavaPerson("Larry Cable", "Customer Service", "[email protected]", "[email protected]"))) ) // Create the root item that holds all top level employees val rootItem = TreeItem(JavaPerson().apply { name = "Employees by Manager"; employees = people }) override val root = treetableview(rootItem) { prefWidth = 800.0 column<JavaPerson, String>("Name", "name").contentWidth(50) // non type safe column("Department", JavaPerson::getDepartment).remainingWidth() nestedColumn("Email addresses") { column("Primary Email", JavaPerson::getPrimaryEmail) column("Secondary Email", JavaPerson::getSecondaryEmail) } // Always return employees under the current person populate { it.value.employees } // Expand the two first levels root.isExpanded = true root.children.withEach { isExpanded = true } smartResize() } }
apache-2.0
dc6ac8677e91c6e74ebc55433321fedd
46
124
0.659402
3.715631
false
false
false
false