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
ZoranPandovski/al-go-rithms
greedy/Job_sequencing_problem/kotlin/JobSequencing.kt
1
2285
package hacktoberfest import java.util.Arrays import java.util.Comparator /** * Job Sequencing implementation in Kotlin * Algorithmic Paradigm - Greedy Algorithm * Assumes that the activities are already sorted according to their finish time * Time Complexity - O(n^2) */ internal class Job : Comparator<Job> { var id: Char = ' ' var deadline: Int = 0 private var profit: Int = 0 constructor() constructor(id: Char, deadline: Int, profit: Int) { this.id = id this.deadline = deadline this.profit = profit } // Sorts in descending order on the basis of profit for each job override fun compare(j1: Job, j2: Job): Int { return if (j1.profit > j2.profit) -1 else 1 } } object JobSequencing { /** * Schedules jobs based on maximum profit * @param arr array containing jobs with their deadlines and profits */ private fun scheduleJobs(arr: Array<Job>) { // Sort Jobs in descending order on the basis of their profit Arrays.sort(arr, Job()) val n = arr.size print("The following is maximum profit sequence of jobs : \n") val result = IntArray(n) // To store result (Sequence of jobs) val slot = BooleanArray(n) // To keep track of free time slots // Initialize all slots to be free for (i in 0 until n) slot[i] = false // Iterate through all given jobs for (i in 0 until n) { // Find a free slot for this job for (j in kotlin.math.min(n, arr[i].deadline) - 1 downTo 0) { // Free slot found if (!slot[j]) { result[j] = i // Add this job to result slot[j] = true // Make this slot occupied break } } } // Print the result for (i in 0 until n) if (slot[i]) print(arr[result[i]].id + " ") } @JvmStatic fun main(args: Array<String>) { val j1 = Job('a', 2, 100) val j2 = Job('b', 1, 19) val j3 = Job('c', 2, 27) val j4 = Job('d', 1, 25) val j5 = Job('e', 3, 15) val arr = arrayOf(j1, j2, j3, j4, j5) scheduleJobs(arr) } }
cc0-1.0
e59c1355dd1e0b8ab1a4f4d0b02d1a25
26.202381
80
0.550109
3.866328
false
false
false
false
InflationX/ViewPump
viewpump/src/main/java/io/github/inflationx/viewpump/internal/-FallbackViewCreationInterceptor.kt
1
797
@file:JvmName("-FallbackViewCreationInterceptor") package io.github.inflationx.viewpump.internal import io.github.inflationx.viewpump.InflateResult import io.github.inflationx.viewpump.Interceptor import io.github.inflationx.viewpump.Interceptor.Chain @Suppress("ClassName") internal class `-FallbackViewCreationInterceptor` : Interceptor { override fun intercept(chain: Chain): InflateResult { val request = chain.request() val viewCreator = request.fallbackViewCreator val fallbackView = viewCreator.onCreateView(request.parent, request.name, request.context, request.attrs) return InflateResult( view = fallbackView, name = fallbackView?.javaClass?.name ?: request.name, context = request.context, attrs = request.attrs ) } }
apache-2.0
0fafb1173f51d66ec1ce9d4612b70603
32.208333
94
0.749059
4.262032
false
false
false
false
timakden/advent-of-code
src/main/kotlin/ru/timakden/aoc/year2015/day03/Puzzle.kt
1
1313
package ru.timakden.aoc.year2015.day03 import ru.timakden.aoc.util.measure import kotlin.time.ExperimentalTime @ExperimentalTime fun main() { measure { println("Part One: ${solvePartOne(input)}") println("Part Two: ${solvePartTwo(input)}") } } fun solvePartOne(input: String): Int { var x = 0 var y = 0 val coordinates = mutableSetOf(0 to 0) input.forEach { when (it) { '^' -> y++ 'v' -> y-- '<' -> x-- '>' -> x++ } coordinates.add(x to y) } return coordinates.size } fun solvePartTwo(input: String): Int { var santaX = 0 var santaY = 0 var robotX = 0 var robotY = 0 var counter = 0 val coordinates = mutableSetOf(0 to 0) input.forEach { val isCounterEven = counter % 2 == 0 when (it) { '^' -> if (isCounterEven) santaY++ else robotY++ 'v' -> if (isCounterEven) santaY-- else robotY-- '<' -> if (isCounterEven) santaX-- else robotX-- '>' -> if (isCounterEven) santaX++ else robotX++ } when { isCounterEven -> coordinates.add(santaX to santaY) else -> coordinates.add(robotX to robotY) } counter++ } return coordinates.size }
apache-2.0
96b4726885a2db6771d2c1ce98fc57a6
20.883333
62
0.533892
3.772989
false
false
false
false
google/intellij-gn-plugin
src/main/java/com/google/idea/gn/GnLabel.kt
1
2958
// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package com.google.idea.gn import com.google.idea.gn.util.getPathLabel import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiFile import java.io.StringWriter import java.util.regex.Pattern class GnLabel private constructor() { private var targetField: String? = null val target: String? get() = if (targetField == null && parts.isNotEmpty()) { parts[parts.size - 1] } else targetField private fun writeDir(writer: StringWriter) { if (isAbsolute) { writer.write("//") } writer.write(java.lang.String.join("/", *parts)) } fun toFullyQualified(): GnLabel { val ret = GnLabel() ret.isAbsolute = isAbsolute ret.parts = parts ret.targetField = target ret.toolchain = toolchain return ret } fun dropToolChain(): GnLabel { val ret = GnLabel() ret.isAbsolute = isAbsolute ret.parts = parts ret.targetField = targetField ret.toolchain = null return ret } override fun toString(): String { val writer = StringWriter() writeDir(writer) targetField?.let { if (it.isNotEmpty()) { writer.write(":") writer.write(it) } } toolchain?.let { if (it.isNotEmpty()) { writer.write("(") writer.write(it) writer.write(")") } } return writer.toString() } var isAbsolute = false private set var parts: Array<String> = emptyArray() private set var toolchain: String? = null private set val dirString: String get() { val writer = StringWriter() writeDir(writer) return writer.toString() } fun toAbsolute(file: PsiFile): GnLabel? { if (isAbsolute) { return this } val ret = parse(getPathLabel(file)) ?: return null ret.isAbsolute = true ret.toolchain = toolchain ret.targetField = target ret.parts = ret.parts.plus(parts) return ret } companion object { private val PATH_PATTERN = Pattern.compile( """(//)?([a-zA-Z0-9$ \-_./]*)(:[a-zA-Z0-9_\-$.]*)?(\([a-zA-Z0-9_\-$./:]*\))?""") @kotlin.jvm.JvmStatic fun parse(path: String?): GnLabel? { if (path.isNullOrEmpty()) { return null } val out = GnLabel() val m = PATH_PATTERN.matcher(path) if (!m.matches()) { return null } if (m.group(1) != null) { out.isAbsolute = true } out.parts = StringUtil.split(m.group(2), "/", true, true).toTypedArray() out.targetField = m.group(3)?.substring(1) if (out.parts.isEmpty() && out.targetField == null) { return null } out.toolchain = m.group(4) if (out.toolchain != null) { out.toolchain = out.toolchain!!.substring(1, out.toolchain!!.length - 1) } return out } } }
bsd-3-clause
96eaf7015bbb9be138fb56be380bd9d3
23.65
88
0.601758
3.777778
false
false
false
false
mchernyavsky/kotlincheck
src/main/kotlin/io/kotlincheck/Tuples.kt
1
2312
package io.kotlincheck import java.io.Serializable internal data class Tuple2<out T1, out T2>( val elem1: T1, val elem2: T2 ) : Serializable { override fun toString(): String = "($elem1, $elem2)" } internal data class Tuple3<out T1, out T2, out T3>( val elem1: T1, val elem2: T2, val elem3: T3 ) : Serializable { override fun toString(): String = "($elem1, $elem2, $elem3)" } internal data class Tuple4<out T1, out T2, out T3, out T4>( val elem1: T1, val elem2: T2, val elem3: T3, val elem4: T4 ) : Serializable { override fun toString(): String = "($elem1, $elem2, $elem3, $elem4)" } internal data class Tuple5<out T1, out T2, out T3, out T4, out T5>( val elem1: T1, val elem2: T2, val elem3: T3, val elem4: T4, val elem5: T5 ) : Serializable { override fun toString(): String = "($elem1, $elem2, $elem3, $elem4, $elem5)" } internal data class Tuple6<out T1, out T2, out T3, out T4, out T5, out T6>( val elem1: T1, val elem2: T2, val elem3: T3, val elem4: T4, val elem5: T5, val elem6: T6 ) : Serializable { override fun toString(): String = "($elem1, $elem2, $elem3, $elem4, $elem5, $elem6)" } internal data class Tuple7<out T1, out T2, out T3, out T4, out T5, out T6, out T7>( val elem1: T1, val elem2: T2, val elem3: T3, val elem4: T4, val elem5: T5, val elem6: T6, val elem7: T7 ) : Serializable { override fun toString(): String = "($elem1, $elem2, $elem3, $elem4, $elem5, $elem6, $elem7)" } internal data class Tuple8<out T1, out T2, out T3, out T4, out T5, out T6, out T7, out T8>( val elem1: T1, val elem2: T2, val elem3: T3, val elem4: T4, val elem5: T5, val elem6: T6, val elem7: T7, val elem8: T8 ) : Serializable { override fun toString(): String = "($elem1, $elem2, $elem3, $elem4, $elem5, $elem6, $elem7, $elem8)" } internal data class Tuple9<out T1, out T2, out T3, out T4, out T5, out T6, out T7, out T8, out T9>( val elem1: T1, val elem2: T2, val elem3: T3, val elem4: T4, val elem5: T5, val elem6: T6, val elem7: T7, val elem8: T8, val elem9: T9 ) : Serializable { override fun toString(): String = "($elem1, $elem2, $elem3, $elem4, $elem5, $elem6, $elem7, $elem8, $elem9)" }
mit
19894567f0304dd440f7302bdab40fb3
25.574713
112
0.607266
2.612429
false
false
false
false
SofteamOuest/referentiel-personnes-api
src/main/kotlin/com/softeam/referentielpersonnes/command/PersonnesCommandService.kt
1
1310
package com.softeam.referentielpersonnes.command import com.softeam.referentielpersonnes.domain.Personne import com.softeam.referentielpersonnes.repository.PersonneRepository import org.slf4j.LoggerFactory import org.springframework.stereotype.Service @Service class PersonnesCommandService constructor( private val personneRepository: PersonneRepository ) { private val logger = LoggerFactory.getLogger(PersonnesCommandService::class.java) fun create(personne: Personne): Personne { logger.info("Saving new $personne.toString()") return personneRepository.save(personne) } fun update(personne: Personne): Personne { val oldPersonne: Personne? = personneRepository.findOne(personne.id) return if (oldPersonne != null) { logger.info("Updating $oldPersonne.toString()") logger.info("To $personne.toString()") personneRepository.save(personne) } else { personne } } fun delete(id: String) { val personne: Personne? = personneRepository.findOne(id) if (personne != null) { logger.info("Deleting $personne.toString()") personneRepository.delete(id) } else { logger.error("Could not find Personne #$id") } } }
apache-2.0
57368ca8f0b95208e2061bd3f8beec69
30.97561
85
0.676336
4.09375
false
false
false
false
grote/Liberario
app/src/main/java/de/grobox/transportr/trips/detail/TripDrawer.kt
1
8932
/* * Transportr * * Copyright (c) 2013 - 2018 Torsten Grote * * This program is Free Software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.grobox.transportr.trips.detail import android.content.Context import android.graphics.PorterDuff import android.graphics.drawable.Drawable import android.graphics.drawable.LayerDrawable import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import com.mapbox.mapboxsdk.annotations.Icon import com.mapbox.mapboxsdk.annotations.PolylineOptions import com.mapbox.mapboxsdk.geometry.LatLng import com.mapbox.mapboxsdk.geometry.LatLngBounds import com.mapbox.mapboxsdk.maps.MapboxMap import de.grobox.transportr.R import de.grobox.transportr.map.MapDrawer import de.grobox.transportr.utils.DateUtils.getTime import de.grobox.transportr.utils.hasLocation import de.schildbach.pte.dto.Location import de.schildbach.pte.dto.Point import de.schildbach.pte.dto.Stop import de.schildbach.pte.dto.Trip import de.schildbach.pte.dto.Trip.* import java.util.* internal class TripDrawer(context: Context) : MapDrawer(context) { private enum class MarkerType { BEGIN, CHANGE, STOP, END, WALK } fun draw(map: MapboxMap, trip: Trip, zoom: Boolean) { // draw leg path first, so it is always at the bottom var i = 1 val builder = LatLngBounds.Builder() for (leg in trip.legs) { // add path if it is missing if (leg.path == null) calculatePath(leg) if (leg.path == null) continue // get colors val backgroundColor = getBackgroundColor(leg) val foregroundColor = getForegroundColor(leg) // draw leg path first, so it is always at the bottom val points = ArrayList<LatLng>(leg.path.size) leg.path.mapTo(points) { LatLng(it.latAsDouble, it.lonAsDouble) } map.addPolyline(PolylineOptions() .color(backgroundColor) .addAll(points) .width(5f) ) // Only draw marker icons for public transport legs if (leg is Public) { // Draw intermediate stops below all others leg.intermediateStops?.let { for (stop in it) { val stopIcon = getMarkerIcon(MarkerType.STOP, backgroundColor, foregroundColor) val text = getStopText(stop) markLocation(map, stop.location, stopIcon, text) } } // Draw first station or change station if (i == 1 || i == 2 && trip.legs[0] is Individual) { val icon = getMarkerIcon(MarkerType.BEGIN, backgroundColor, foregroundColor) markLocation(map, leg.departure, icon, getStationText(leg, MarkerType.BEGIN)) } else { val icon = getMarkerIcon(MarkerType.CHANGE, backgroundColor, foregroundColor) markLocation(map, leg.departure, icon, getStationText(trip.legs[i - 2], leg)) } // Draw final station only at the end or if end is walking if (i == trip.legs.size || i == trip.legs.size - 1 && trip.legs[i] is Individual) { val icon = getMarkerIcon(MarkerType.END, backgroundColor, foregroundColor) markLocation(map, leg.arrival, icon, getStationText(leg, MarkerType.END)) } } else if (leg is Individual) { // only draw an icon if walk is required in the middle of a trip if (i > 1 && i < trip.legs.size) { val icon = getMarkerIcon(MarkerType.WALK, backgroundColor, foregroundColor) markLocation(map, leg.departure, icon, getStationText(trip.legs[i - 2], leg)) } } i += 1 builder.includes(points) } if (zoom) { zoomToBounds(map, builder, false) } } private fun calculatePath(leg: Leg) { if (leg.path == null) leg.path = ArrayList() if (leg.departure != null && leg.departure.hasLocation()) { leg.path.add(Point.fromDouble(leg.departure.latAsDouble, leg.departure.lonAsDouble)) } if (leg is Public) { leg.intermediateStops?.filter { it.location != null && it.location.hasLocation() }?.forEach { leg.path.add(Point.fromDouble(it.location.latAsDouble, it.location.lonAsDouble)) } } if (leg.arrival != null && leg.arrival.hasLocation()) { leg.path.add(Point.fromDouble(leg.arrival.latAsDouble, leg.arrival.lonAsDouble)) } } @ColorInt private fun getBackgroundColor(leg: Leg): Int { if (leg is Public) { val line = leg.line return if (line?.style != null && line.style!!.backgroundColor != 0) { line.style!!.backgroundColor } else { ContextCompat.getColor(context, R.color.accent) } } return ContextCompat.getColor(context, R.color.walking) } @ColorInt private fun getForegroundColor(leg: Leg): Int { if (leg is Public) { val line = leg.line return if (line?.style != null && line.style!!.foregroundColor != 0) { line.style!!.foregroundColor } else { ContextCompat.getColor(context, android.R.color.white) } } return ContextCompat.getColor(context, android.R.color.black) } private fun markLocation(map: MapboxMap, location: Location, icon: Icon, text: String) { markLocation(map, location, icon, location.uniqueShortName(), text) } private fun getMarkerIcon(type: MarkerType, backgroundColor: Int, foregroundColor: Int): Icon { // Get Drawable val drawable: Drawable if (type == MarkerType.STOP) { drawable = ContextCompat.getDrawable(context, R.drawable.ic_marker_trip_stop) ?: throw RuntimeException() drawable.mutate().setColorFilter(backgroundColor, PorterDuff.Mode.SRC_IN) } else { val res: Int = when (type) { MarkerType.BEGIN -> R.drawable.ic_marker_trip_begin MarkerType.CHANGE -> R.drawable.ic_marker_trip_change MarkerType.END -> R.drawable.ic_marker_trip_end MarkerType.WALK -> R.drawable.ic_marker_trip_walk else -> throw IllegalArgumentException() } drawable = ContextCompat.getDrawable(context, res) as LayerDrawable drawable.getDrawable(0).mutate().setColorFilter(backgroundColor, PorterDuff.Mode.MULTIPLY) drawable.getDrawable(1).mutate().setColorFilter(foregroundColor, PorterDuff.Mode.SRC_IN) } return drawable.toIcon() } private fun getStopText(stop: Stop): String { var text = "" stop.getArrivalTime(false)?.let { text += "${context.getString(R.string.trip_arr)}: ${getTime(context, it)}" } stop.getDepartureTime(false)?.let { if (text.isNotEmpty()) text += "\n" text += "${context.getString(R.string.trip_dep)}: ${getTime(context, it)}" } return text } private fun getStationText(leg: Public, type: MarkerType): String { return when (type) { MarkerType.BEGIN -> leg.getDepartureTime(false)?.let { "${context.getString(R.string.trip_dep)}: ${getTime(context, it)}" } MarkerType.END -> leg.getArrivalTime(false)?.let { "${context.getString(R.string.trip_arr)}: ${getTime(context, it)}" } else -> throw IllegalArgumentException() } ?: "" } private fun getStationText(leg1: Leg, leg2: Leg): String { var text = "" leg1.arrivalTime?.let { text += "${context.getString(R.string.trip_arr)}: ${getTime(context, it)}" } leg2.departureTime?.let { if (text.isNotEmpty()) text += "\n" text += "${context.getString(R.string.trip_dep)}: ${getTime(context, it)}" } return text } }
gpl-3.0
d85d0593f98ae16569baaef699db4855
39.6
117
0.600202
4.432754
false
false
false
false
gradle/gradle
build-logic/binary-compatibility/src/main/kotlin/gradlebuild/binarycompatibility/metadata/KotlinMetadataQueries.kt
3
4762
/* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gradlebuild.binarycompatibility.metadata import gradlebuild.binarycompatibility.intArrayValue import gradlebuild.binarycompatibility.intValue import gradlebuild.binarycompatibility.stringArrayValue import gradlebuild.binarycompatibility.stringValue import javassist.CtClass import javassist.CtConstructor import javassist.CtField import javassist.CtMember import javassist.CtMethod import javassist.Modifier import javassist.bytecode.annotation.Annotation import javassist.bytecode.annotation.AnnotationImpl import kotlinx.metadata.Flag import kotlinx.metadata.jvm.KotlinClassHeader import kotlinx.metadata.jvm.KotlinClassMetadata import java.lang.reflect.Proxy object KotlinMetadataQueries { fun isKotlinFileFacadeClass(ctClass: CtClass): Boolean = if (Modifier.isPrivate(ctClass.modifiers)) false else queryKotlinMetadata(ctClass, false) { metadata -> when (metadata) { is KotlinClassMetadata.FileFacade -> true else -> false } } fun isKotlinInternal(ctClass: CtClass): Boolean = if (Modifier.isPrivate(ctClass.modifiers)) false else hasKotlinFlag(ctClass, Flag.IS_INTERNAL) fun isKotlinInternal(ctMember: CtMember): Boolean = if (Modifier.isPrivate(ctMember.modifiers)) false else hasKotlinFlag(ctMember, Flag.IS_INTERNAL) fun isKotlinOperatorFunction(ctMethod: CtMethod): Boolean = hasKotlinFlag(ctMethod, Flag.Function.IS_OPERATOR) fun isKotlinInfixFunction(ctMethod: CtMethod): Boolean = hasKotlinFlag(ctMethod, Flag.Function.IS_INFIX) private fun hasKotlinFlag(ctClass: CtClass, flag: Flag): Boolean = queryKotlinMetadata(ctClass, false) { metadata -> metadata.hasKotlinFlag(MemberType.TYPE, ctClass.name, flag) } private fun hasKotlinFlag(ctMember: CtMember, flag: Flag): Boolean = queryKotlinMetadata(ctMember.declaringClass, false) { metadata -> metadata.hasKotlinFlag(memberTypeFor(ctMember), ctMember.jvmSignature, flag) } private fun <T : Any?> queryKotlinMetadata(ctClass: CtClass, defaultResult: T, query: (KotlinClassMetadata) -> T): T = ctClass.kotlinClassHeader ?.let { KotlinClassMetadata.read(it) } ?.let { query(it) } ?: defaultResult private val CtClass.kotlinClassHeader: KotlinClassHeader? get() = ctAnnotation<Metadata>()?.let { annotation -> KotlinClassHeader( kind = annotation.getMemberValue("k")?.intValue, metadataVersion = annotation.getMemberValue("mv")?.intArrayValue, data1 = annotation.getMemberValue("d1")?.stringArrayValue, data2 = annotation.getMemberValue("d2")?.stringArrayValue, extraString = annotation.getMemberValue("xs")?.stringValue, packageName = annotation.getMemberValue("pn")?.stringValue, extraInt = annotation.getMemberValue("xi")?.intValue ) } private inline fun <reified T : Any> CtClass.ctAnnotation(): Annotation? = getAnnotation(T::class.java) ?.takeIf { Proxy.isProxyClass(it::class.java) } ?.let { Proxy.getInvocationHandler(it) as? AnnotationImpl } ?.annotation private val CtMember.jvmSignature: String get() = when (this) { is CtField -> "$name:$signature" is CtConstructor -> if (parameterTypes.isEmpty()) "$name$signature" else "<init>$signature" is CtMethod -> "$name$signature" else -> throw IllegalArgumentException("Unsupported javassist member type '${this::class}'") } } internal enum class MemberType { TYPE, CONSTRUCTOR, FIELD, METHOD } private fun memberTypeFor(member: CtMember): MemberType = when (member) { is CtConstructor -> MemberType.CONSTRUCTOR is CtField -> MemberType.FIELD is CtMethod -> MemberType.METHOD else -> throw IllegalArgumentException("Unsupported javassist member type '${member::class}'") }
apache-2.0
ce7936eec8668774cffc113bd205fb56
36.203125
114
0.685846
4.724206
false
false
false
false
Alfresco/activiti-android-app
auth-library/src/main/kotlin/com/alfresco/auth/fragments/BasicAuthFragment.kt
1
2504
package com.alfresco.auth.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.activityViewModels import com.alfresco.android.aims.R import com.alfresco.android.aims.databinding.ContainerAuthBasicBinding import com.alfresco.auth.activity.LoginViewModel import com.alfresco.common.FragmentBuilder class BasicAuthFragment : DialogFragment() { private val viewModel: LoginViewModel by activityViewModels() private var withCloud: Boolean = false private val rootView: View get() = view!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val binding = DataBindingUtil.inflate<ContainerAuthBasicBinding>(inflater, R.layout.container_auth_basic, container, false) binding.viewModel = viewModel binding.lifecycleOwner = this return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel.setHasNavigation(true) updateUi() } private fun updateUi() { if (withCloud) { rootView.findViewById<View>(R.id.tvSigninTo).visibility = View.GONE rootView.findViewById<View>(R.id.tvConnectUrl).visibility = View.GONE rootView.findViewById<View>(R.id.tvBasicAuthInfoCloud).visibility = View.VISIBLE } else { rootView.findViewById<View>(R.id.tvSigninTo).visibility = View.VISIBLE rootView.findViewById<View>(R.id.tvConnectUrl).visibility = View.VISIBLE rootView.findViewById<View>(R.id.tvBasicAuthInfoCloud).visibility = View.GONE } } override fun onStart() { super.onStart() // Reset action bar title activity?.title = "" } class Builder(parent: FragmentActivity) : FragmentBuilder(parent) { override val fragmentTag = TAG override fun build(args: Bundle): Fragment { val fragment = BasicAuthFragment() fragment.arguments = args return fragment } } companion object { val TAG = BasicAuthFragment::class.java.name fun with(activity: FragmentActivity): Builder = Builder(activity) } }
lgpl-3.0
bc42b7452ab7e1517d0c8ff193fa7f13
31.115385
131
0.710463
4.824663
false
false
false
false
VerifAPS/verifaps-lib
lang/src/main/kotlin/edu/kit/iti/formal/automation/st/RefTo.kt
1
2552
package edu.kit.iti.formal.automation.st import edu.kit.iti.formal.automation.exceptions.DataTypeNotDefinedException /*- * #%L * iec61131lang * %% * Copyright (C) 2016 - 2017 Alexander Weigl * %% * This program isType free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program isType 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 clone of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ /** * @param <T> an class which isType identifiable * @author Alexander Weigl * @since 04.03.2017 </T> */ class RefTo<T : Identifiable>(private var name: String?, private var identified: T?) : Cloneable { var identifier: String? get() = if (obj != null) obj!!.name else name set(new) { this.name = new } var obj: T? get() = identified set(value) { // if(value!=null || name == null || value?.name != name ) // throw IllegalStateException("Name does match the object name.") identified = value } val isIdentified: Boolean get() = obj != null constructor() : this(null, null) constructor(identifier: String?) : this(identifier, null) constructor(obj: T) : this(obj.name, obj) override fun clone(): RefTo<T> = RefTo(identifier, obj) fun resolve(func: (String) -> T?) { if (identifier != null) try { obj = func(identifier!!) } catch (e: DataTypeNotDefinedException) { } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is RefTo<*>) return false if (identified != null && identified == other.identified) return true if (name == other.name) return true return false } override fun hashCode(): Int { var result = name?.hashCode() ?: 0 result = 31 * result + (identified?.hashCode() ?: 0) return result } override fun toString(): String { return "RefTo(name=$name, identified=$identified)" } }
gpl-3.0
dd8e5c272b7da81d30838525b12a50fe
29.035294
81
0.612069
4.149593
false
false
false
false
wizardofos/Protozoo
extra/exposed/src/main/kotlin/org/jetbrains/exposed/sql/Function.kt
1
7008
package org.jetbrains.exposed.sql import org.jetbrains.exposed.sql.vendors.currentDialect import org.joda.time.DateTime import java.math.BigDecimal import java.util.* abstract class Function<out T> : ExpressionWithColumnType<T>() class Count(val expr: Expression<*>, val distinct: Boolean = false): Function<Int>() { override fun toSQL(queryBuilder: QueryBuilder): String = "COUNT(${if (distinct) "DISTINCT " else ""}${expr.toSQL(queryBuilder)})" override val columnType: IColumnType = IntegerColumnType() } class Date(val expr: Expression<DateTime?>): Function<DateTime>() { override fun toSQL(queryBuilder: QueryBuilder): String = "DATE(${expr.toSQL(queryBuilder)})" override val columnType: IColumnType = DateColumnType(false) } class CurrentDateTime : Function<DateTime>() { override fun toSQL(queryBuilder: QueryBuilder) = "CURRENT_TIMESTAMP" override val columnType: IColumnType = DateColumnType(false) } class Month(val expr: Expression<DateTime?>): Function<DateTime>() { override fun toSQL(queryBuilder: QueryBuilder): String = "MONTH(${expr.toSQL(queryBuilder)})" override val columnType: IColumnType = DateColumnType(false) } class LowerCase<out T: String?>(val expr: Expression<T>) : Function<T>() { override fun toSQL(queryBuilder: QueryBuilder): String = "LOWER(${expr.toSQL(queryBuilder)})" override val columnType: IColumnType = StringColumnType() } class UpperCase<out T: String?>(val expr: Expression<T>) : Function<T>() { override fun toSQL(queryBuilder: QueryBuilder): String = "UPPER(${expr.toSQL(queryBuilder)})" override val columnType: IColumnType = StringColumnType() } class Min<out T>(val expr: Expression<T>, _columnType: IColumnType): Function<T?>() { override fun toSQL(queryBuilder: QueryBuilder): String = "MIN(${expr.toSQL(queryBuilder)})" override val columnType: IColumnType = _columnType } class Max<out T>(val expr: Expression<T>, _columnType: IColumnType): Function<T?>() { override fun toSQL(queryBuilder: QueryBuilder): String = "MAX(${expr.toSQL(queryBuilder)})" override val columnType: IColumnType = _columnType } class Avg<out T>(val expr: Expression<T>, scale: Int): Function<BigDecimal?>() { override fun toSQL(queryBuilder: QueryBuilder): String = "AVG(${expr.toSQL(queryBuilder)})" override val columnType: IColumnType = DecimalColumnType(Int.MAX_VALUE, scale) } class StdDevPop<out T>(val expr: Expression<T>, scale: Int): Function<BigDecimal?>() { override fun toSQL(queryBuilder: QueryBuilder): String = "STDDEV_POP(${expr.toSQL(queryBuilder)})" override val columnType: IColumnType = DecimalColumnType(Int.MAX_VALUE, scale) } class StdDevSamp<out T>(val expr: Expression<T>, scale: Int): Function<BigDecimal?>() { override fun toSQL(queryBuilder: QueryBuilder): String = "STDDEV_SAMP(${expr.toSQL(queryBuilder)})" override val columnType: IColumnType = DecimalColumnType(Int.MAX_VALUE, scale) } class VarPop<out T>(val expr: Expression<T>, scale: Int): Function<BigDecimal?>() { override fun toSQL(queryBuilder: QueryBuilder): String = "VAR_POP(${expr.toSQL(queryBuilder)})" override val columnType: IColumnType = DecimalColumnType(Int.MAX_VALUE, scale) } class VarSamp<out T>(val expr: Expression<T>, scale: Int): Function<BigDecimal?>() { override fun toSQL(queryBuilder: QueryBuilder): String = "VAR_SAMP(${expr.toSQL(queryBuilder)})" override val columnType: IColumnType = DecimalColumnType(Int.MAX_VALUE, scale) } class Sum<out T>(val expr: Expression<T>, _columnType: IColumnType): Function<T?>() { override fun toSQL(queryBuilder: QueryBuilder): String = "SUM(${expr.toSQL(queryBuilder)})" override val columnType: IColumnType = _columnType } class Coalesce<out T>(val expr: ExpressionWithColumnType<T?>, val alternate: ExpressionWithColumnType<out T>): Function<T>() { override fun toSQL(queryBuilder: QueryBuilder): String = "COALESCE(${expr.toSQL(queryBuilder)}, ${alternate.toSQL(queryBuilder)})" override val columnType: IColumnType = alternate.columnType } class Substring(val expr: Expression<String?>, val start: ExpressionWithColumnType<Int>, val length: ExpressionWithColumnType<Int>): Function<String>() { override fun toSQL(queryBuilder: QueryBuilder): String = currentDialect.functionProvider.substring(expr, start, length, queryBuilder) override val columnType: IColumnType = StringColumnType() } class Random(val seed: Int? = null) : Function<BigDecimal>() { override fun toSQL(queryBuilder: QueryBuilder): String = currentDialect.functionProvider.random(seed) override val columnType: IColumnType = DecimalColumnType(38, 20) } class Cast<out T>(val expr: Expression<*>, override val columnType: IColumnType) : Function<T?>() { override fun toSQL(queryBuilder: QueryBuilder): String = currentDialect.functionProvider.cast(expr, columnType, queryBuilder) } class Trim(val expr: Expression<*>): Function<String>() { override fun toSQL(queryBuilder: QueryBuilder): String = "TRIM(${expr.toSQL(queryBuilder)})" override val columnType: IColumnType = StringColumnType() } class Case(val value: Expression<*>? = null) { fun<T> When (cond: Expression<Boolean>, result: Expression<T>) : CaseWhen<T> = CaseWhen<T>(value).When (cond, result) } class CaseWhen<T> (val value: Expression<*>?) { val cases: ArrayList<Pair<Expression<Boolean>, Expression<T>>> = ArrayList() fun When (cond: Expression<Boolean>, result: Expression<T>) : CaseWhen<T> { cases.add( cond to result ) return this } fun Else(e: Expression<T>) : Expression<T> = CaseWhenElse(this, e) } class CaseWhenElse<T> (val caseWhen: CaseWhen<T>, val elseResult: Expression<T>) : Expression<T>() { override fun toSQL(queryBuilder: QueryBuilder): String = buildString { append("CASE") if (caseWhen.value != null) append( " ${caseWhen.value.toSQL(queryBuilder)}") for ((first, second) in caseWhen.cases) { append(" WHEN ${first.toSQL(queryBuilder)} THEN ${second.toSQL(queryBuilder)}") } append(" ELSE ${elseResult.toSQL(queryBuilder)} END") } } class GroupConcat(val expr: Column<*>, val separator: String?, val distinct: Boolean, vararg val orderBy: Pair<Expression<*>,Boolean>): Function<String?>() { override fun toSQL(queryBuilder: QueryBuilder): String = buildString { append("GROUP_CONCAT(") if (distinct) append("DISTINCT ") append(expr.toSQL(queryBuilder)) orderBy.forEach { append(it.first.toSQL(queryBuilder)) append(" ") if (it.second) { append("ASC") } else { append("DESC") } } separator?.let { append(" SEPARATOR '$separator'") } append(")") } override val columnType: IColumnType = StringColumnType() }
mit
5ec6bcfc552b37c655f43324c91532c3
38.370787
157
0.69335
4.299387
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/listener/PlayerQuitListener.kt
1
1201
package com.rpkit.characters.bukkit.listener import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority.MONITOR import org.bukkit.event.Listener import org.bukkit.event.player.PlayerQuitEvent class PlayerQuitListener : Listener { @EventHandler(priority = MONITOR) fun onPlayerQuit(event: PlayerQuitEvent) { val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return val characterService = Services[RPKCharacterService::class.java] ?: return minecraftProfileService.getMinecraftProfile(event.player).thenAccept { minecraftProfile -> if (minecraftProfile == null) return@thenAccept // If a player relogs quickly, then by the time the data has been retrieved, the player is sometimes back // online. We only want to unload data if the player is offline. if (!minecraftProfile.isOnline) { characterService.unloadActiveCharacter(minecraftProfile) } } } }
apache-2.0
4a4b1bc8d8f52072b806f710946bdf91
41.928571
117
0.745212
5.110638
false
false
false
false
industrial-data-space/trusted-connector
ids-api/src/main/java/de/fhg/aisec/ids/api/acme/SslContextFactoryReloadable.kt
1
894
/*- * ========================LICENSE_START================================= * ids-api * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * 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. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.api.acme interface SslContextFactoryReloadable { fun reload(newKeyStorePath: String?) }
apache-2.0
34f9d19feaaa01ddb58bb3cfc016653a
36.25
75
0.63311
4.492462
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/database/table/RPKNewCharacterCooldownTable.kt
1
5716
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.characters.bukkit.database.table import com.rpkit.characters.bukkit.RPKCharactersBukkit import com.rpkit.characters.bukkit.database.create import com.rpkit.characters.bukkit.database.jooq.Tables.RPKIT_NEW_CHARACTER_COOLDOWN import com.rpkit.characters.bukkit.newcharactercooldown.RPKNewCharacterCooldown import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.players.bukkit.profile.RPKProfile import com.rpkit.players.bukkit.profile.RPKProfileId import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletableFuture.runAsync import java.util.logging.Level.SEVERE class RPKNewCharacterCooldownTable(private val database: Database, private val plugin: RPKCharactersBukkit) : Table { private val profileCache = if (plugin.config.getBoolean("caching.rpkit_new_character_cooldown.profile_id.enabled")) { database.cacheManager.createCache( "rpk-characters-bukkit.rpkit_new_character_cooldown.profile_id", Int::class.javaObjectType, RPKNewCharacterCooldown::class.java, plugin.config.getLong("caching.rpkit_new_character_cooldown.profile_id.size") ) } else { null } fun insert(entity: RPKNewCharacterCooldown): CompletableFuture<Void> { val profileId = entity.profile.id ?: return CompletableFuture.completedFuture(null) return runAsync { database.create .insertInto( RPKIT_NEW_CHARACTER_COOLDOWN, RPKIT_NEW_CHARACTER_COOLDOWN.PROFILE_ID, RPKIT_NEW_CHARACTER_COOLDOWN.COOLDOWN_TIMESTAMP ) .values( profileId.value, entity.cooldownExpiryTime ) .execute() profileCache?.set(profileId.value, entity) }.exceptionally { exception -> plugin.logger.log(SEVERE, "Failed to insert new character cooldown", exception) throw exception } } fun update(entity: RPKNewCharacterCooldown): CompletableFuture<Void> { val profileId = entity.profile.id ?: return CompletableFuture.completedFuture(null) return runAsync { database.create .update(RPKIT_NEW_CHARACTER_COOLDOWN) .set(RPKIT_NEW_CHARACTER_COOLDOWN.COOLDOWN_TIMESTAMP, entity.cooldownExpiryTime) .where(RPKIT_NEW_CHARACTER_COOLDOWN.PROFILE_ID.eq(profileId.value)) .execute() profileCache?.set(profileId.value, entity) }.exceptionally { exception -> plugin.logger.log(SEVERE, "Failed to update new character cooldown", exception) throw exception } } operator fun get(profile: RPKProfile): CompletableFuture<RPKNewCharacterCooldown?> { val profileId = profile.id ?: return CompletableFuture.completedFuture(null) if (profileCache?.containsKey(profileId.value) == true) { return CompletableFuture.completedFuture(profileCache[profileId.value]) } return CompletableFuture.supplyAsync { val result = database.create .select( RPKIT_NEW_CHARACTER_COOLDOWN.PROFILE_ID, RPKIT_NEW_CHARACTER_COOLDOWN.COOLDOWN_TIMESTAMP ) .from(RPKIT_NEW_CHARACTER_COOLDOWN) .where(RPKIT_NEW_CHARACTER_COOLDOWN.PROFILE_ID.eq(profileId.value)) .fetchOne() ?: return@supplyAsync null val newCharacterCooldown = RPKNewCharacterCooldown( profile, result.get(RPKIT_NEW_CHARACTER_COOLDOWN.COOLDOWN_TIMESTAMP) ) profileCache?.set(profileId.value, newCharacterCooldown) return@supplyAsync newCharacterCooldown }.exceptionally { exception -> plugin.logger.log(SEVERE, "Failed to get new character cooldown", exception) throw exception } } fun delete(entity: RPKNewCharacterCooldown): CompletableFuture<Void> { val profileId = entity.profile.id ?: return CompletableFuture.completedFuture(null) return runAsync { database.create .deleteFrom(RPKIT_NEW_CHARACTER_COOLDOWN) .where(RPKIT_NEW_CHARACTER_COOLDOWN.PROFILE_ID.eq(profileId.value)) .execute() profileCache?.remove(profileId.value) }.exceptionally { exception -> plugin.logger.log(SEVERE, "Failed to delete new character cooldown", exception) throw exception } } fun delete(profileId: RPKProfileId): CompletableFuture<Void> = runAsync { database.create .deleteFrom(RPKIT_NEW_CHARACTER_COOLDOWN) .where(RPKIT_NEW_CHARACTER_COOLDOWN.PROFILE_ID.eq(profileId.value)) .execute() profileCache?.remove(profileId.value) }.exceptionally { exception -> plugin.logger.log(SEVERE, "Failed to delete new character cooldown for profile id", exception) throw exception } }
apache-2.0
fd4fe5b94d9b4abf726052fbde6df519
42.310606
121
0.662351
4.759367
false
false
false
false
rethumb/rethumb-examples
examples-read-gps-coordinates/example-kotlin.kt
1
2572
import com.google.gson.Gson import com.google.gson.internal.LinkedTreeMap import java.io.BufferedReader import java.io.InputStreamReader import java.net.URL import java.util.* object KotlinRethumbGPSExample { @Throws(Exception::class) @JvmStatic fun main(args: Array<String>) { val url = URL("http://api.rethumb.com/v1/exif/all/http://images.rethumb.com/image_exif_1.jpg") val reader = BufferedReader(InputStreamReader(url.openStream())) val gson = Gson() val result = gson.fromJson(reader, LinkedTreeMap::class.java) println(parseGPSCoordinates(result)) } private fun parseGPSCoordinates(data: LinkedTreeMap<*, *>): String { if (data.get("GPS") == null) return "GPS Coordinates not found" val values = HashMap<String, String>() values.put("LAT", (data.get("GPS") as LinkedTreeMap<*, *>).get("GPSLatitudeRef").toString()) values.put("LONG", (data.get("GPS") as LinkedTreeMap<*, *>).get("GPSLongitudeRef").toString()) values.put("LAT_DEG", "" + applyDivision(((data["GPS"] as LinkedTreeMap<*, *>)["GPSLatitude"] as List<*>)[0] as String)) values.put("LAT_MIN", "" + applyDivision(((data["GPS"] as LinkedTreeMap<*, *>)["GPSLatitude"] as List<*>)[1] as String)) values.put("LAT_SEC", "" + applyDivision(((data["GPS"] as LinkedTreeMap<*, *>)["GPSLatitude"] as List<*>)[2] as String)) values.put("LONG_DEG", "" + applyDivision(((data["GPS"] as LinkedTreeMap<*, *>)["GPSLongitude"] as List<*>)[0] as String)) values.put("LONG_MIN", "" + applyDivision(((data["GPS"] as LinkedTreeMap<*, *>)["GPSLongitude"] as List<*>)[1] as String)) values.put("LONG_SEC", "" + applyDivision(((data["GPS"] as LinkedTreeMap<*, *>)["GPSLongitude"] as List<*>)[2] as String)) return format("{LAT} {LAT_DEG}° {LAT_MIN}' {LAT_SEC}'' {LONG} {LONG_DEG}° {LONG_MIN}' {LONG_SEC}''", values) } private fun applyDivision(value: String): String { val tokens = value.split(("/").toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray() return trim(java.lang.Float.parseFloat(tokens[0]) / java.lang.Float.parseFloat(tokens[1])) } private fun trim(f: Float): String { if (f.toDouble() == Math.ceil(f.toDouble())) return "" + (f.toInt()) return "" + f } private fun format(str: String, values: Map<String, String>): String { var out: String = str; for (key in values.keys) out = out.replace("{$key}", values[key].toString()) return out } }
unlicense
9d3b196df2f6dceb5132ac5b2b6ebb5c
49.411765
130
0.61751
3.660969
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/ide/template/RustContextType.kt
1
3191
package org.rust.ide.template import com.intellij.codeInsight.template.EverywhereContextType import com.intellij.codeInsight.template.TemplateContextType import com.intellij.openapi.fileTypes.SyntaxHighlighter import com.intellij.openapi.util.Condition import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtilCore import org.rust.ide.highlight.RustHighlighter import org.rust.lang.RustLanguage import org.rust.lang.core.psi.* import org.rust.lang.core.psi.util.parentOfType import kotlin.reflect.KClass sealed class RustContextType( id: String, presentableName: String, baseContextType: KClass<out TemplateContextType> ) : TemplateContextType(id, presentableName, baseContextType.java) { final override fun isInContext(file: PsiFile, offset: Int): Boolean { if (!PsiUtilCore.getLanguageAtOffset(file, offset).isKindOf(RustLanguage)) { return false } val element = file.findElementAt(offset) if (element == null || element is PsiComment || element is RustLiteral) { return false } return isInContext(element) } abstract protected fun isInContext(element: PsiElement): Boolean override fun createHighlighter(): SyntaxHighlighter = RustHighlighter() class Generic : RustContextType("RUST_FILE", "Rust", EverywhereContextType::class) { override fun isInContext(element: PsiElement): Boolean = true } class Statement : RustContextType("RUST_STATEMENT", "Statement", Generic::class) { override fun isInContext(element: PsiElement): Boolean = // We are inside block but there is no item nor attr between PsiTreeUtil.findFirstParent(element, blockOrItem) is RustBlockElement } class Item : RustContextType("RUST_ITEM", "Item", Generic::class) { override fun isInContext(element: PsiElement): Boolean = // We are inside item but there is no block between PsiTreeUtil.findFirstParent(element, blockOrItem) is RustItemElement } class Struct : RustContextType("RUST_STRUCT", "Structure", Item::class) { override fun isInContext(element: PsiElement): Boolean = // Structs can't be nested or contain other expressions, // so it is ok to look for any Struct ancestor. element.parentOfType<RustStructItemElement>() != null } class Mod : RustContextType("RUST_MOD", "Module", Item::class) { override fun isInContext(element: PsiElement): Boolean = // We are inside RustModItemElement PsiTreeUtil.findFirstParent(element, blockOrItem) is RustModItemElement } class Attribute : RustContextType("RUST_ATTRIBUTE", "Attribute", Item::class) { override fun isInContext(element: PsiElement): Boolean = element.parentOfType<RustAttrElement>() != null } companion object { private val blockOrItem = Condition<PsiElement> { element -> element is RustBlockElement || element is RustItemElement || element is RustAttrElement } } }
mit
d4d6e09b30f5de4841aa8ad50aa673e6
38.8875
99
0.709809
4.762687
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/CommandManager.kt
1
21656
package net.perfectdreams.loritta.morenitta.commands import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.commands.nashorn.NashornCommand import net.perfectdreams.loritta.morenitta.commands.vanilla.administration.* import net.perfectdreams.loritta.morenitta.commands.vanilla.discord.* import net.perfectdreams.loritta.morenitta.commands.vanilla.economy.* import net.perfectdreams.loritta.morenitta.commands.vanilla.`fun`.* import net.perfectdreams.loritta.morenitta.commands.vanilla.images.* import net.perfectdreams.loritta.morenitta.commands.vanilla.magic.* import net.perfectdreams.loritta.morenitta.commands.vanilla.minecraft.* import net.perfectdreams.loritta.morenitta.commands.vanilla.misc.* import net.perfectdreams.loritta.morenitta.commands.vanilla.music.LyricsCommand import net.perfectdreams.loritta.morenitta.commands.vanilla.pokemon.PokedexCommand import net.perfectdreams.loritta.morenitta.commands.vanilla.social.* import net.perfectdreams.loritta.morenitta.commands.vanilla.undertale.UndertaleBattleCommand import net.perfectdreams.loritta.morenitta.commands.vanilla.undertale.UndertaleBoxCommand import net.perfectdreams.loritta.morenitta.commands.vanilla.utils.* import net.perfectdreams.loritta.morenitta.dao.ServerConfig import net.perfectdreams.loritta.morenitta.events.LorittaMessageEvent import net.perfectdreams.loritta.morenitta.utils.* import net.perfectdreams.loritta.morenitta.utils.DateUtils import net.perfectdreams.loritta.morenitta.utils.config.EnvironmentType import net.perfectdreams.loritta.morenitta.utils.extensions.await import net.perfectdreams.loritta.morenitta.utils.extensions.localized import net.perfectdreams.loritta.morenitta.utils.extensions.referenceIfPossible import mu.KotlinLogging import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.channel.ChannelType import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel import net.dv8tion.jda.api.exceptions.ErrorResponseException import net.dv8tion.jda.api.utils.MarkdownSanitizer import net.perfectdreams.i18nhelper.core.I18nContext import net.perfectdreams.loritta.common.utils.Emotes import net.perfectdreams.loritta.common.utils.UserPremiumPlans import net.perfectdreams.loritta.morenitta.messages.LorittaReply import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.common.locale.LocaleStringData import net.perfectdreams.loritta.morenitta.dao.servers.moduleconfigs.MiscellaneousConfig import net.perfectdreams.loritta.morenitta.tables.servers.CustomGuildCommands import net.perfectdreams.loritta.morenitta.utils.extensions.textChannel import net.perfectdreams.loritta.morenitta.utils.metrics.Prometheus import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.select import java.sql.Connection import java.util.* import java.util.concurrent.CancellationException class CommandManager(val loritta: LorittaBot) { companion object { val logger = KotlinLogging.logger {} } var commandMap: MutableList<AbstractCommand> = ArrayList() init { commandMap.add(RollCommand(loritta)) commandMap.add(FaustaoCommand(loritta)) commandMap.add(CaraCoroaCommand(loritta)) commandMap.add(PedraPapelTesouraCommand(loritta)) commandMap.add(VaporondaCommand(loritta)) commandMap.add(QualidadeCommand(loritta)) commandMap.add(VaporQualidadeCommand(loritta)) commandMap.add(TretaNewsCommand(loritta)) commandMap.add(MagicBallCommand(loritta)) commandMap.add(NyanCatCommand(loritta)) commandMap.add(PrimeirasPalavrasCommand(loritta)) commandMap.add(InverterCommand(loritta)) // commandMap.add(SpinnerCommand(loritta)) commandMap.add(LavaCommand(loritta)) commandMap.add(LavaReversoCommand(loritta)) commandMap.add(ShipCommand(loritta)) commandMap.add(AvaliarWaifuCommand(loritta)) commandMap.add(RazoesCommand(loritta)) commandMap.add(DeusCommand(loritta)) commandMap.add(PerfeitoCommand(loritta)) commandMap.add(TrumpCommand(loritta)) commandMap.add(CepoCommand(loritta)) commandMap.add(DeusesCommand(loritta)) commandMap.add(GangueCommand(loritta)) commandMap.add(AmigosCommand(loritta)) commandMap.add(DiscordiaCommand(loritta)) commandMap.add(AmizadeCommand(loritta)) commandMap.add(PerdaoCommand(loritta)) commandMap.add(RipVidaCommand(loritta)) commandMap.add(JoojCommand(loritta)) commandMap.add(OjjoCommand(loritta)) commandMap.add(TwitchCommand(loritta)) // =======[ IMAGENS ]====== commandMap.add(GetOverHereCommand(loritta)) commandMap.add(ManiaTitleCardCommand(loritta)) commandMap.add(LaranjoCommand(loritta)) commandMap.add(TriggeredCommand(loritta)) commandMap.add(GumballCommand(loritta)) commandMap.add(ContentAwareScaleCommand(loritta)) commandMap.add(SwingCommand(loritta)) commandMap.add(DemonCommand(loritta)) commandMap.add(KnuxThrowCommand(loritta)) commandMap.add(TextCraftCommand(loritta)) commandMap.add(DrawnMaskCommand(loritta)) // =======[ DIVERSÃO ]====== commandMap.add(BemBoladaCommand(loritta)) commandMap.add(TodoGrupoTemCommand(loritta)) commandMap.add(TioDoPaveCommand(loritta)) commandMap.add(VemDeZapCommand(loritta)) // =======[ MISC ]====== commandMap.add(AjudaCommand(loritta)) commandMap.add(PingCommand(loritta)) commandMap.add(SayCommand(loritta)) commandMap.add(EscolherCommand(loritta)) commandMap.add(LanguageCommand(loritta)) commandMap.add(PatreonCommand(loritta)) // =======[ SOCIAL ]====== commandMap.add(PerfilCommand(loritta)) commandMap.add(BackgroundCommand(loritta)) commandMap.add(SobreMimCommand(loritta)) commandMap.add(RepCommand(loritta)) commandMap.add(RankCommand(loritta)) commandMap.add(EditarXPCommand(loritta)) commandMap.add(AfkCommand(loritta)) commandMap.add(MarryCommand(loritta)) commandMap.add(DivorceCommand(loritta)) commandMap.add(GenderCommand(loritta)) // =======[ UTILS ]======= commandMap.add(TranslateCommand(loritta)) commandMap.add(WikipediaCommand(loritta)) commandMap.add(MoneyCommand(loritta)) commandMap.add(ColorInfoCommand(loritta)) commandMap.add(LembrarCommand(loritta)) commandMap.add(DicioCommand(loritta)) commandMap.add(TempoCommand(loritta)) commandMap.add(PackageInfoCommand(loritta)) commandMap.add(AnagramaCommand(loritta)) commandMap.add(CalculadoraCommand(loritta)) commandMap.add(MorseCommand(loritta)) commandMap.add(OCRCommand(loritta)) commandMap.add(EncodeCommand(loritta)) commandMap.add(LyricsCommand(loritta)) // =======[ DISCORD ]======= commandMap.add(BotInfoCommand(loritta)) commandMap.add(AvatarCommand(loritta)) commandMap.add(ServerIconCommand(loritta)) commandMap.add(EmojiCommand(loritta)) commandMap.add(ServerInfoCommand(loritta)) commandMap.add(InviteCommand(loritta)) commandMap.add(UserInfoCommand(loritta)) commandMap.add(InviteInfoCommand(loritta)) commandMap.add(AddEmojiCommand(loritta)) commandMap.add(RemoveEmojiCommand(loritta)) commandMap.add(EmojiInfoCommand(loritta)) // =======[ MINECRAFT ]======== commandMap.add(OfflineUUIDCommand(loritta)) commandMap.add(McAvatarCommand(loritta)) commandMap.add(McUUIDCommand(loritta)) commandMap.add(McHeadCommand(loritta)) commandMap.add(McBodyCommand(loritta)) commandMap.add(SpigotMcCommand(loritta)) commandMap.add(McConquistaCommand(loritta)) commandMap.add(McSkinCommand(loritta)) commandMap.add(McMoletomCommand(loritta)) // =======[ UNDERTALE ]======== commandMap.add(UndertaleBoxCommand(loritta)) commandMap.add(UndertaleBattleCommand(loritta)) // =======[ POKÉMON ]======== commandMap.add(PokedexCommand(loritta)) // =======[ ANIME ]======== // commandMap.add(MALAnimeCommand(loritta)) // commandMap.add(MALMangaCommand(loritta)) // =======[ ADMIN ]======== commandMap.add(RoleIdCommand(loritta)) commandMap.add(MuteCommand(loritta)) commandMap.add(UnmuteCommand(loritta)) commandMap.add(SlowModeCommand(loritta)) commandMap.add(KickCommand(loritta)) commandMap.add(BanCommand(loritta)) commandMap.add(UnbanCommand(loritta)) commandMap.add(WarnCommand(loritta)) commandMap.add(WarnListCommand(loritta)) commandMap.add(QuickPunishmentCommand(loritta)) commandMap.add(LockCommand(loritta)) commandMap.add(UnlockCommand(loritta)) // =======[ MAGIC ]======== commandMap.add(ReloadCommand(loritta)) commandMap.add(ServerInvitesCommand(loritta)) commandMap.add(LorittaBanCommand(loritta)) commandMap.add(LorittaUnbanCommand(loritta)) commandMap.add(LoriServerListConfigCommand(loritta)) // TODO: Fix compilation? // if (loritta.config.loritta.environment == EnvironmentType.CANARY) // commandMap.add(AntiRaidCommand(loritta)) // =======[ ECONOMIA ]======== commandMap.add(LoraffleCommand(loritta)) commandMap.add(DailyCommand(loritta)) commandMap.add(PagarCommand(loritta)) commandMap.add(SonhosCommand(loritta)) commandMap.add(LigarCommand(loritta)) } suspend fun matches(ev: LorittaMessageEvent, rawArguments: List<String>, serverConfig: ServerConfig, locale: BaseLocale, i18nContext: I18nContext, lorittaUser: LorittaUser): Boolean { // Primeiro os comandos vanilla da Loritta(tm) for (command in commandMap) { if (matches(command, rawArguments, ev, serverConfig, locale, i18nContext, lorittaUser)) return true } // Checking custom commands // To avoid unnecessary databases retrievals, we are going to check if the message starts with the server prefix or with Loritta's mention val nashornCommands = loritta.newSuspendedTransaction { CustomGuildCommands.select { CustomGuildCommands.guild eq serverConfig.id and (CustomGuildCommands.enabled eq true) }.toList() }.map { NashornCommand( loritta, it[CustomGuildCommands.label], it[CustomGuildCommands.code], it[CustomGuildCommands.codeType] ) } for (command in nashornCommands) { if (matches(command, rawArguments, ev, serverConfig, locale, i18nContext, lorittaUser)) return true } return false } /** * Checks if the command should be handled (if all conditions are valid, like labels, etc) * * @param ev the event wrapped in a LorittaMessageEvent * @param legacyServerConfig the server configuration * @param legacyLocale the language of the server * @param lorittaUser the user that is executing this command * @return if the command was handled or not */ suspend fun matches(command: AbstractCommand, rawArguments: List<String>, ev: LorittaMessageEvent, serverConfig: ServerConfig, locale: BaseLocale, i18nContext: I18nContext, lorittaUser: LorittaUser): Boolean { val message = ev.message.contentDisplay val labels = mutableListOf(command.label) labels.addAll(command.aliases) // ignoreCase = true ~ Permite usar "+cOmAnDo" val valid = labels.any { rawArguments[0].equals(it, true) } if (valid) { val isPrivateChannel = ev.isFromType(ChannelType.PRIVATE) val start = System.currentTimeMillis() val rawArgs = rawArguments.joinToString(" ").stripCodeMarks().split(Constants.WHITE_SPACE_MULTIPLE_REGEX) .drop(1) .toTypedArray() val args = rawArgs val strippedArgs: Array<String> if (rawArgs.isNotEmpty()) { strippedArgs = MarkdownSanitizer.sanitize(rawArgs.joinToString(" ")).split(" ").toTypedArray() } else { strippedArgs = rawArgs } val context = CommandContext(loritta, serverConfig, lorittaUser, locale, i18nContext, ev, command, args, rawArgs, strippedArgs) try { CommandUtils.logMessageEvent(ev, logger) // Check if user is banned if (LorittaUtilsKotlin.handleIfBanned(context, lorittaUser.profile)) return true // Cooldown var commandCooldown = command.cooldown val donatorPaid = loritta.getActiveMoneyFromDonationsAsync(ev.author.idLong) val guildId = ev.guild?.idLong val guildPaid = guildId?.let { serverConfig.getActiveDonationKeysValue(loritta) } ?: 0.0 val plan = UserPremiumPlans.getPlanFromValue(donatorPaid) if (plan.lessCooldown) { commandCooldown /= 2 } val (cooldownStatus, cooldownTriggeredAt, cooldown) = loritta.commandCooldownManager.checkCooldown( ev, commandCooldown ) if (cooldownStatus.sendMessage) { val fancy = DateUtils.formatDateDiff(cooldown + cooldownTriggeredAt, locale) val key = when (cooldownStatus) { CommandCooldownManager.CooldownStatus.RATE_LIMITED_SEND_MESSAGE -> LocaleKeyData( "commands.pleaseWaitCooldown", listOf( LocaleStringData(fancy), LocaleStringData("\uD83D\uDE45") ) ) CommandCooldownManager.CooldownStatus.RATE_LIMITED_SEND_MESSAGE_REPEATED -> LocaleKeyData( "commands.pleaseWaitCooldownRepeated", listOf( LocaleStringData(fancy), LocaleStringData(Emotes.LORI_HMPF.toString()) ) ) else -> throw IllegalArgumentException("Invalid Cooldown Status $cooldownStatus, marked as send but there isn't any locale keys related to it!") } context.reply( LorittaReply( locale[key], "\uD83D\uDD25" ) ) return true } else if (cooldownStatus == CommandCooldownManager.CooldownStatus.RATE_LIMITED_MESSAGE_ALREADY_SENT) return true val miscellaneousConfig = serverConfig.getCachedOrRetreiveFromDatabaseAsync<MiscellaneousConfig?>(loritta, ServerConfig::miscellaneousConfig) val enableBomDiaECia = miscellaneousConfig?.enableBomDiaECia ?: false if (serverConfig.blacklistedChannels.contains(ev.channel.idLong) && !lorittaUser.hasPermission(LorittaPermission.BYPASS_COMMAND_BLACKLIST)) { if (!enableBomDiaECia || (enableBomDiaECia && command !is LigarCommand)) { if (serverConfig.warnIfBlacklisted) { if (serverConfig.blacklistedWarning?.isNotEmpty() == true && ev.guild != null && ev.member != null && ev.textChannel != null) { val generatedMessage = MessageUtils.generateMessage( serverConfig.blacklistedWarning ?: "???", listOf(ev.member, ev.textChannel, ev.guild), ev.guild ) if (generatedMessage != null) ev.textChannel.sendMessage(generatedMessage) .referenceIfPossible(ev.message, serverConfig, true) .await() } } return true // Ignorar canais bloqueados (return true = fast break, se está bloqueado o canal no primeiro comando que for executado, os outros obviamente também estarão) } } if (!isPrivateChannel && ev.guild != null && ev.member != null) { // Verificar se o comando está ativado na guild atual if (CommandUtils.checkIfCommandIsDisabledInGuild(loritta, serverConfig, locale, ev.channel, ev.member, command::class.simpleName!!)) return true } // Se estamos dentro de uma guild... (Já que mensagens privadas não possuem permissões) if (!isPrivateChannel && ev.guild != null && ev.member != null && ev.textChannel != null) { // Verificar se a Loritta possui todas as permissões necessárias val botPermissions = ArrayList<Permission>(command.getBotPermissions()) botPermissions.add(Permission.MESSAGE_EMBED_LINKS) botPermissions.add(Permission.MESSAGE_EXT_EMOJI) botPermissions.add(Permission.MESSAGE_ADD_REACTION) botPermissions.add(Permission.MESSAGE_HISTORY) val missingPermissions = ArrayList<Permission>(botPermissions.filterNot { ev.guild.selfMember.hasPermission(ev.textChannel, it) }) if (missingPermissions.isNotEmpty()) { // oh no val required = missingPermissions.joinToString(", ", transform = { "`" + it.localized(locale) + "`" }) context.reply( LorittaReply( locale["commands.loriDoesntHavePermissionDiscord", required, "\uD83D\uDE22", "\uD83D\uDE42"], Constants.ERROR ) ) return true } } if (!isPrivateChannel && ev.member != null && ev.textChannel != null) { val missingPermissions = command.lorittaPermissions.filterNot { lorittaUser.hasPermission(it) } if (missingPermissions.isNotEmpty()) { // oh no val required = missingPermissions.joinToString( ", ", transform = { "`" + locale["commands.loriPermission${it.name}"] + "`" }) var message = locale["commands.loriMissingPermission", required] if (ev.member.hasPermission(Permission.ADMINISTRATOR) || ev.member.hasPermission(Permission.MANAGE_SERVER)) { message += " ${locale["commands.loriMissingPermissionCanConfigure", loritta.config.loritta.website.url]}" } ev.textChannel.sendMessage(Constants.ERROR + " **|** ${ev.member.asMention} $message") .referenceIfPossible(ev.message, serverConfig, true) .await() return true } } if (args.isNotEmpty() && args[0] == "🤷") { // Usar a ajuda caso 🤷 seja usado command.explain(context) return true } if (context.cmd.onlyOwner && !loritta.isOwner(ev.author.id)) { context.reply( LorittaReply( locale["commands.commandOnlyForOwner"], Constants.ERROR ) ) return true } if (!context.canUseCommand()) { val requiredPermissions = command.getDiscordPermissions().filter { !ev.message.member!!.hasPermission(ev.message.textChannel, it) } val required = requiredPermissions.joinToString(", ", transform = { "`" + it.localized(locale) + "`" }) context.reply( LorittaReply( locale["commands.userDoesntHavePermissionDiscord", required], Constants.ERROR ) ) return true } if (context.isPrivateChannel && !command.canUseInPrivateChannel()) { context.sendMessage(Constants.ERROR + " **|** " + context.getAsMention(true) + locale["commands.cantUseInPrivate"]) return true } if (command.needsToUploadFiles()) { if (!LorittaUtils.canUploadFiles(context)) { return true } } // Vamos pegar uma mensagem aleatória de doação, se não for nula, iremos enviar ela :3 DonateUtils.getRandomDonationMessage( loritta, locale, lorittaUser.profile, donatorPaid, guildPaid )?.let { context.reply(it) } if (!context.isPrivateChannel) { val nickname = context.guild.selfMember.nickname if (nickname != null) { // #LoritaTambémTemSentimentos val hasBadNickname = MiscUtils.hasInappropriateWords(nickname) if (hasBadNickname) { context.reply( LorittaReply( locale["commands.lorittaBadNickname"], "<:lori_triste:370344565967814659>" ) ) if (context.guild.selfMember.hasPermission(Permission.NICKNAME_CHANGE)) { context.guild.modifyNickname(context.guild.selfMember, null).queue() } else { return true } } } } if (ev.guild != null && (LorittaUtils.isGuildOwnerBanned(loritta, lorittaUser._profile, ev.guild) || LorittaUtils.isGuildBanned(loritta, ev.guild))) return true // We don't care about locking the row just to update the sent at field loritta.newSuspendedTransaction(transactionIsolation = Connection.TRANSACTION_READ_UNCOMMITTED) { lorittaUser.profile.lastCommandSentAt = System.currentTimeMillis() } CommandUtils.trackCommandToDatabase(loritta, ev, command::class.simpleName ?: "UnknownCommand") loritta.newSuspendedTransaction { val profile = serverConfig.getUserDataIfExistsNested(lorittaUser.profile.userId) if (profile != null && !profile.isInGuild) profile.isInGuild = true } loritta.lorittaShards.updateCachedUserData(context.userHandle) command.run(context, context.locale) if (!isPrivateChannel && ev.guild != null) { if (ev.guild.selfMember.hasPermission(ev.channel as GuildChannel, Permission.MESSAGE_MANAGE) && (serverConfig.deleteMessageAfterCommand)) { ev.message.textChannel.deleteMessageById(ev.messageId).queue({}, { // We don't care if we weren't able to delete the message because it was already deleted }) } } val end = System.currentTimeMillis() val commandLatency = end - start Prometheus.COMMAND_LATENCY.labels(command::class.simpleName).observe(commandLatency.toDouble()) CommandUtils.logMessageEventComplete(ev, logger, commandLatency) return true } catch (e: Exception) { if (e is CancellationException) { logger.error(e) { "RestAction in command ${command::class.simpleName} has been cancelled" } return true } if (e is ErrorResponseException) { if (e.errorCode == 40005) { // Request entity too large if (ev.isFromType(ChannelType.PRIVATE) || (ev.isFromType(ChannelType.TEXT) && ev.textChannel != null && ev.textChannel.canTalk())) context.reply( LorittaReply( locale["commands.imageTooLarge", "8MB", Emotes.LORI_TEMMIE], "\uD83E\uDD37" ) ) return true } } logger.error("Exception ao executar comando ${command.javaClass.simpleName}", e) // Avisar ao usuário que algo deu muito errado val mention = "${ev.author.asMention} " var reply = "\uD83E\uDD37 **|** " + mention + locale["commands.errorWhileExecutingCommand", Emotes.LORI_RAGE, Emotes.LORI_CRYING] if (!e.message.isNullOrEmpty()) reply += " `${e.message!!.escapeMentions()}`" if (ev.isFromType(ChannelType.PRIVATE) || (ev.isFromType(ChannelType.TEXT) && ev.textChannel != null && ev.textChannel.canTalk())) ev.channel.sendMessage(reply) .referenceIfPossible(ev.message, serverConfig, true) .await() return true } } return false } }
agpl-3.0
87d579466b3e81cd1be1755bd51b8bf5
38.404372
210
0.734526
3.805947
false
true
false
false
LorittaBot/Loritta
pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/transactions/ExecutedApplicationCommandsLog.kt
1
1364
package net.perfectdreams.loritta.cinnamon.pudding.tables.transactions import net.perfectdreams.exposedpowerutils.sql.jsonb import net.perfectdreams.exposedpowerutils.sql.postgresEnumeration import net.perfectdreams.loritta.common.commands.ApplicationCommandType import net.perfectdreams.loritta.cinnamon.pudding.tables.LongIdTableWithoutOverriddenPrimaryKey import org.jetbrains.exposed.sql.javatime.timestamp object ExecutedApplicationCommandsLog : LongIdTableWithoutOverriddenPrimaryKey() { val userId = long("user").index() val guildId = long("guild").nullable() val channelId = long("channel") // Because this is already a partition table, we can't change its type (for now) val sentAt = timestamp("sent_at").index() val type = postgresEnumeration<ApplicationCommandType>("type").index() val declaration = text("declaration").index() val executor = text("executor").index() val options = jsonb("options") val success = bool("success") val latency = double("latency") val stacktrace = text("stacktrace").nullable() // Sent At must be a primary key because it is used as a partition key // While this means that all partitions should have an unique ID and Sent At, the ID is always incrementing so I don't think // that this will cause issues override val primaryKey = PrimaryKey(id, sentAt) }
agpl-3.0
70e56b92cc880cb2483f4e5e685e4c87
47.75
128
0.759531
4.592593
false
false
false
false
burntcookie90/Sleep-Cycle-Alarm
mobile/src/main/kotlin/io/dwak/sleepcyclealarm/ui/times/WakeUpTimesFragment.kt
1
3914
package io.dwak.sleepcyclealarm.ui.times import android.content.Context import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import butterknife.bindView import io.dwak.sleepcyclealarm.R import io.dwak.sleepcyclealarm.base.mvp.MvpFragment import io.dwak.sleepcyclealarm.dagger.component.DaggerInteractorComponent import io.dwak.sleepcyclealarm.dagger.module.PresenterModule import io.dwak.sleepcyclealarm.dagger.scope.ViewScope import io.dwak.sleepcyclealarm.model.WakeUpTime import io.dwak.sleepcyclealarm.presenter.WakeUpTimesPresenter import io.dwak.sleepcyclealarm.view.WakeUpTimesView import rx.Observable import java.util.Date @ViewScope public class WakeUpTimesFragment : MvpFragment<WakeUpTimesPresenter>(), WakeUpTimesView { override var itemClicks : Observable<Date>? = null val recycler : RecyclerView by bindView(R.id.recycler) lateinit var adapter : WakeUpTimesAdapter var listener : WakeUpTimesFragmentListener? = null companion object { val EXTRA_SLEEP_NOW = "SLEEP_NOW" val EXTRA_SLEEP_LATER_TIME = "SLEEP_LATER_TIME" fun newInstance() = WakeUpTimesFragment() fun newInstance(sleepNow : Boolean = false) : WakeUpTimesFragment { val extras = Bundle() extras.putBoolean(EXTRA_SLEEP_NOW, sleepNow) val fragment = WakeUpTimesFragment() fragment.arguments = extras return fragment } fun newInstance(sleepLaterTime : Date) : WakeUpTimesFragment { val extras = Bundle() extras.putSerializable(EXTRA_SLEEP_LATER_TIME, sleepLaterTime) val fragment = WakeUpTimesFragment() fragment.arguments = extras return fragment } } override fun inject() { presenterComponentBuilder .presenterModule(PresenterModule(this)) .interactorComponent(DaggerInteractorComponent.create()) .build() .inject(this) } //region lifecycle override fun onCreate(savedInstanceState : Bundle?) { super.onCreate(savedInstanceState) with(arguments) { if (containsKey(EXTRA_SLEEP_NOW)) { presenter.isSleepNow = getBoolean(EXTRA_SLEEP_NOW, false); } else if (containsKey(EXTRA_SLEEP_LATER_TIME)) { presenter.sleepTime = getSerializable(EXTRA_SLEEP_LATER_TIME) as Date } } } override fun onCreateView(inflater : LayoutInflater?, container : ViewGroup?, savedInstanceState : Bundle?) : View? { return inflater?.inflate(R.layout.fragment_sleep_times, container, false); } override fun onAttach(context : Context?) { super.onAttach(context) if (activity is WakeUpTimesFragmentListener) { listener = activity as WakeUpTimesFragmentListener } else { throw RuntimeException("${activity.javaClass.simpleName} must implement WakeUpTimesListener") } } override fun onStart() { super.onStart() adapter = WakeUpTimesAdapter(activity) itemClicks = adapter.observable recycler.adapter = adapter recycler.layoutManager = LinearLayoutManager(activity) presenter.getTimes() } //endregion override fun showTimes(sleepTime : Date, wakeupTimes : List<WakeUpTime>) { adapter.sleepTime = sleepTime wakeupTimes.forEach { adapter.addTime(it) } } override fun setAlarm(wakeUpTime : Date) { listener?.setAlarm(wakeUpTime) } public interface WakeUpTimesFragmentListener { fun setAlarm(wakeUpTime : Date) } }
apache-2.0
8f7bf3082a184d8280831371f2ba03a4
33.646018
105
0.668881
4.868159
false
false
false
false
shyiko/ktlint
ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/SpacingAroundDotRuleTest.kt
1
3837
package com.pinterest.ktlint.ruleset.standard import com.pinterest.ktlint.core.LintError import com.pinterest.ktlint.test.format import com.pinterest.ktlint.test.lint import org.assertj.core.api.Assertions.assertThat import org.junit.Test class SpacingAroundDotRuleTest { @Test fun testLint() { assertThat(SpacingAroundDotRule().lint("fun String .foo() = \"foo . \"")) .isEqualTo( listOf( LintError(1, 11, "dot-spacing", "Unexpected spacing before \".\"") ) ) assertThat(SpacingAroundDotRule().lint("fun String. foo() = \"foo . \"")) .isEqualTo( listOf( LintError(1, 12, "dot-spacing", "Unexpected spacing after \".\"") ) ) assertThat(SpacingAroundDotRule().lint("fun String . foo() = \"foo . \"")) .isEqualTo( listOf( LintError(1, 11, "dot-spacing", "Unexpected spacing before \".\""), LintError(1, 13, "dot-spacing", "Unexpected spacing after \".\"") ) ) assertThat( SpacingAroundDotRule().lint( """ fun String.foo() { (2..10).map { it + 1 } .map { it * 2 } .toSet() } """.trimIndent() ) ).isEmpty() assertThat( SpacingAroundDotRule().lint( """ fun String.foo() { (2..10).map { it + 1 } . map { it * 2 } .toSet() } """.trimIndent() ) ).isEqualTo( listOf( LintError(3, 10, "dot-spacing", "Unexpected spacing after \".\"") ) ) assertThat( SpacingAroundDotRule().lint( """ fun String.foo() { (2..10).map { it + 1 } // Some comment . map { it * 2 } .toSet() } """.trimIndent() ) ).isEqualTo( listOf( LintError(4, 10, "dot-spacing", "Unexpected spacing after \".\"") ) ) } @Test fun testLintComment() { assertThat( SpacingAroundDotRule().lint( """ fun foo() { /**.*/ generateSequence(locate(dir)) { seed -> locate(seed.parent.parent) } // seed.parent == .editorconfig dir .map { it to lazy { load(it) } } } """.trimIndent() ) ).isEmpty() } @Test fun testFormat() { assertThat(SpacingAroundDotRule().format("fun String .foo() = \"foo . \"")) .isEqualTo("fun String.foo() = \"foo . \"") assertThat(SpacingAroundDotRule().format("fun String. foo() = \"foo . \"")) .isEqualTo("fun String.foo() = \"foo . \"") assertThat(SpacingAroundDotRule().format("fun String . foo() = \"foo . \"")) .isEqualTo("fun String.foo() = \"foo . \"") assertThat( SpacingAroundDotRule().format( """ fun String.foo() { (2..10).map { it + 1 } . map { it * 2 } .toSet() } """.trimIndent() ) ).isEqualTo( """ fun String.foo() { (2..10).map { it + 1 } .map { it * 2 } .toSet() } """.trimIndent() ) } }
mit
e624f49c183c7c0d01e21b6aa74308fd
29.212598
124
0.397446
4.996094
false
true
false
false
YounesRahimi/java-utils
src/main/java/ir/iais/utilities/javautils/utils/_KomprehensionsPromise.kt
2
47410
@file:JvmName("KomprehensionsPromise") package ir.iais.utilities.javautils.utils import ir.iais.utilities.javautils.commonForkJoinPool import java.util.concurrent.CompletionStage import java.util.concurrent.Executor fun <T, R> CompletionStage<T>.flatMap(executor: Executor = commonForkJoinPool, func: (T) -> CompletionStage<R>): CompletionStage<R> = this.thenComposeAsync(java.util.function.Function { func(it) }, executor) fun <T, R> CompletionStage<T>.map(executor: Executor = commonForkJoinPool, func: (T) -> R): CompletionStage<R> = this.thenApplyAsync(java.util.function.Function { func(it) }, executor) /** * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.flatMap]. * * @return composed Observable */ fun <A, R> doFlatMap( zero: () -> CompletionStage<A>, one: (A) -> CompletionStage<R>): CompletionStage<R> = zero.invoke() .flatMap { a -> one.invoke(a) } ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.flatMap]. // * // * @return composed Observable // */ //fun <A, B, R> doFlatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .flatMap { a -> // one.invoke(a) // .flatMap { b -> // two.invoke(a, b) // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.flatMap]. // * // * @return composed Observable // */ //fun <A, B, C, R> doFlatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .flatMap { a -> // one.invoke(a) // .flatMap { b -> // two.invoke(a, b) // .flatMap { c -> // three.invoke(a, b, c) // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.flatMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, R> doFlatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .flatMap { a -> // one.invoke(a) // .flatMap { b -> // two.invoke(a, b) // .flatMap { c -> // three.invoke(a, b, c) // .flatMap { d -> // four.invoke(a, b, c, d) // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.flatMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, R> doFlatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<E>, // five: (A, B, C, D, E) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .flatMap { a -> // one.invoke(a) // .flatMap { b -> // two.invoke(a, b) // .flatMap { c -> // three.invoke(a, b, c) // .flatMap { d -> // four.invoke(a, b, c, d) // .flatMap { e -> // five.invoke(a, b, c, d, e) // } // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.flatMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, F, R> doFlatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<E>, // five: (A, B, C, D, E) -> CompletionStage<F>, // six: (A, B, C, D, E, F) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .flatMap { a -> // one.invoke(a) // .flatMap { b -> // two.invoke(a, b) // .flatMap { c -> // three.invoke(a, b, c) // .flatMap { d -> // four.invoke(a, b, c, d) // .flatMap { e -> // five.invoke(a, b, c, d, e) // .flatMap { f -> // six.invoke(a, b, c, d, e, f) // } // } // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.flatMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, F, G, R> doFlatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<E>, // five: (A, B, C, D, E) -> CompletionStage<F>, // six: (A, B, C, D, E, F) -> CompletionStage<G>, // seven: (A, B, C, D, E, F, G) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .flatMap { a -> // one.invoke(a) // .flatMap { b -> // two.invoke(a, b) // .flatMap { c -> // three.invoke(a, b, c) // .flatMap { d -> // four.invoke(a, b, c, d) // .flatMap { e -> // five.invoke(a, b, c, d, e) // .flatMap { f -> // six.invoke(a, b, c, d, e, f) // .flatMap { g -> // seven.invoke(a, b, c, d, e, f, g) // } // } // } // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.flatMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, F, G, H, R> doFlatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<E>, // five: (A, B, C, D, E) -> CompletionStage<F>, // six: (A, B, C, D, E, F) -> CompletionStage<G>, // seven: (A, B, C, D, E, F, G) -> CompletionStage<H>, // eight: (A, B, C, D, E, F, G, H) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .flatMap { a -> // one.invoke(a) // .flatMap { b -> // two.invoke(a, b) // .flatMap { c -> // three.invoke(a, b, c) // .flatMap { d -> // four.invoke(a, b, c, d) // .flatMap { e -> // five.invoke(a, b, c, d, e) // .flatMap { f -> // six.invoke(a, b, c, d, e, f) // .flatMap { g -> // seven.invoke(a, b, c, d, e, f, g) // .flatMap { h -> // eight.invoke(a, b, c, d, e, f, g, h) // } // } // } // } // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.flatMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, F, G, H, I, R> doFlatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<E>, // five: (A, B, C, D, E) -> CompletionStage<F>, // six: (A, B, C, D, E, F) -> CompletionStage<G>, // seven: (A, B, C, D, E, F, G) -> CompletionStage<H>, // eight: (A, B, C, D, E, F, G, H) -> CompletionStage<I>, // nine: (A, B, C, D, E, F, G, H, I) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .flatMap { a -> // one.invoke(a) // .flatMap { b -> // two.invoke(a, b) // .flatMap { c -> // three.invoke(a, b, c) // .flatMap { d -> // four.invoke(a, b, c, d) // .flatMap { e -> // five.invoke(a, b, c, d, e) // .flatMap { f -> // six.invoke(a, b, c, d, e, f) // .flatMap { g -> // seven.invoke(a, b, c, d, e, f, g) // .flatMap { h -> // eight.invoke(a, b, c, d, e, f, g, h) // .flatMap { i -> // nine.invoke(a, b, c, d, e, f, g, h, i) // } // } // } // } // } // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.concatMap]. // * // * @return composed Observable // */ //fun <A, R> doConcatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .concatMap { a -> // one.invoke(a) // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.concatMap]. // * // * @return composed Observable // */ //fun <A, B, R> doConcatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .concatMap { a -> // one.invoke(a) // .concatMap { b -> // two.invoke(a, b) // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.concatMap]. // * // * @return composed Observable // */ //fun <A, B, C, R> doConcatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .concatMap { a -> // one.invoke(a) // .concatMap { b -> // two.invoke(a, b) // .concatMap { c -> // three.invoke(a, b, c) // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.concatMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, R> doConcatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .concatMap { a -> // one.invoke(a) // .concatMap { b -> // two.invoke(a, b) // .concatMap { c -> // three.invoke(a, b, c) // .concatMap { d -> // four.invoke(a, b, c, d) // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.concatMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, R> doConcatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<E>, // five: (A, B, C, D, E) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .concatMap { a -> // one.invoke(a) // .concatMap { b -> // two.invoke(a, b) // .concatMap { c -> // three.invoke(a, b, c) // .concatMap { d -> // four.invoke(a, b, c, d) // .concatMap { e -> // five.invoke(a, b, c, d, e) // } // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.concatMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, F, R> doConcatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<E>, // five: (A, B, C, D, E) -> CompletionStage<F>, // six: (A, B, C, D, E, F) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .concatMap { a -> // one.invoke(a) // .concatMap { b -> // two.invoke(a, b) // .concatMap { c -> // three.invoke(a, b, c) // .concatMap { d -> // four.invoke(a, b, c, d) // .concatMap { e -> // five.invoke(a, b, c, d, e) // .concatMap { f -> // six.invoke(a, b, c, d, e, f) // } // } // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.concatMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, F, G, R> doConcatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<E>, // five: (A, B, C, D, E) -> CompletionStage<F>, // six: (A, B, C, D, E, F) -> CompletionStage<G>, // seven: (A, B, C, D, E, F, G) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .concatMap { a -> // one.invoke(a) // .concatMap { b -> // two.invoke(a, b) // .concatMap { c -> // three.invoke(a, b, c) // .concatMap { d -> // four.invoke(a, b, c, d) // .concatMap { e -> // five.invoke(a, b, c, d, e) // .concatMap { f -> // six.invoke(a, b, c, d, e, f) // .concatMap { g -> // seven.invoke(a, b, c, d, e, f, g) // } // } // } // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.concatMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, F, G, H, R> doConcatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<E>, // five: (A, B, C, D, E) -> CompletionStage<F>, // six: (A, B, C, D, E, F) -> CompletionStage<G>, // seven: (A, B, C, D, E, F, G) -> CompletionStage<H>, // eight: (A, B, C, D, E, F, G, H) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .concatMap { a -> // one.invoke(a) // .concatMap { b -> // two.invoke(a, b) // .concatMap { c -> // three.invoke(a, b, c) // .concatMap { d -> // four.invoke(a, b, c, d) // .concatMap { e -> // five.invoke(a, b, c, d, e) // .concatMap { f -> // six.invoke(a, b, c, d, e, f) // .concatMap { g -> // seven.invoke(a, b, c, d, e, f, g) // .concatMap { h -> // eight.invoke(a, b, c, d, e, f, g, h) // } // } // } // } // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.concatMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, F, G, H, I, R> doConcatMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<E>, // five: (A, B, C, D, E) -> CompletionStage<F>, // six: (A, B, C, D, E, F) -> CompletionStage<G>, // seven: (A, B, C, D, E, F, G) -> CompletionStage<H>, // eight: (A, B, C, D, E, F, G, H) -> CompletionStage<I>, // nine: (A, B, C, D, E, F, G, H, I) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .concatMap { a -> // one.invoke(a) // .concatMap { b -> // two.invoke(a, b) // .concatMap { c -> // three.invoke(a, b, c) // .concatMap { d -> // four.invoke(a, b, c, d) // .concatMap { e -> // five.invoke(a, b, c, d, e) // .concatMap { f -> // six.invoke(a, b, c, d, e, f) // .concatMap { g -> // seven.invoke(a, b, c, d, e, f, g) // .concatMap { h -> // eight.invoke(a, b, c, d, e, f, g, h) // .concatMap { i -> // nine.invoke(a, b, c, d, e, f, g, h, i) // } // } // } // } // } // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.switchMap]. // * // * @return composed Observable // */ //fun <A, R> doSwitchMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .switchMap { a -> // one.invoke(a) // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.switchMap]. // * // * @return composed Observable // */ //fun <A, B, R> doSwitchMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .switchMap { a -> // one.invoke(a) // .switchMap { b -> // two.invoke(a, b) // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.switchMap]. // * // * @return composed Observable // */ //fun <A, B, C, R> doSwitchMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .switchMap { a -> // one.invoke(a) // .switchMap { b -> // two.invoke(a, b) // .switchMap { c -> // three.invoke(a, b, c) // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.switchMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, R> doSwitchMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .switchMap { a -> // one.invoke(a) // .switchMap { b -> // two.invoke(a, b) // .switchMap { c -> // three.invoke(a, b, c) // .switchMap { d -> // four.invoke(a, b, c, d) // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.switchMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, R> doSwitchMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<E>, // five: (A, B, C, D, E) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .switchMap { a -> // one.invoke(a) // .switchMap { b -> // two.invoke(a, b) // .switchMap { c -> // three.invoke(a, b, c) // .switchMap { d -> // four.invoke(a, b, c, d) // .switchMap { e -> // five.invoke(a, b, c, d, e) // } // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.switchMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, F, R> doSwitchMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<E>, // five: (A, B, C, D, E) -> CompletionStage<F>, // six: (A, B, C, D, E, F) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .switchMap { a -> // one.invoke(a) // .switchMap { b -> // two.invoke(a, b) // .switchMap { c -> // three.invoke(a, b, c) // .switchMap { d -> // four.invoke(a, b, c, d) // .switchMap { e -> // five.invoke(a, b, c, d, e) // .switchMap { f -> // six.invoke(a, b, c, d, e, f) // } // } // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.switchMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, F, G, R> doSwitchMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<E>, // five: (A, B, C, D, E) -> CompletionStage<F>, // six: (A, B, C, D, E, F) -> CompletionStage<G>, // seven: (A, B, C, D, E, F, G) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .switchMap { a -> // one.invoke(a) // .switchMap { b -> // two.invoke(a, b) // .switchMap { c -> // three.invoke(a, b, c) // .switchMap { d -> // four.invoke(a, b, c, d) // .switchMap { e -> // five.invoke(a, b, c, d, e) // .switchMap { f -> // six.invoke(a, b, c, d, e, f) // .switchMap { g -> // seven.invoke(a, b, c, d, e, f, g) // } // } // } // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.switchMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, F, G, H, R> doSwitchMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<E>, // five: (A, B, C, D, E) -> CompletionStage<F>, // six: (A, B, C, D, E, F) -> CompletionStage<G>, // seven: (A, B, C, D, E, F, G) -> CompletionStage<H>, // eight: (A, B, C, D, E, F, G, H) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .switchMap { a -> // one.invoke(a) // .switchMap { b -> // two.invoke(a, b) // .switchMap { c -> // three.invoke(a, b, c) // .switchMap { d -> // four.invoke(a, b, c, d) // .switchMap { e -> // five.invoke(a, b, c, d, e) // .switchMap { f -> // six.invoke(a, b, c, d, e, f) // .switchMap { g -> // seven.invoke(a, b, c, d, e, f, g) // .switchMap { h -> // eight.invoke(a, b, c, d, e, f, g, h) // } // } // } // } // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple creation functions chained by [rx.Observable.switchMap]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, F, G, H, I, R> doSwitchMap( // zero: () -> CompletionStage<A>, // one: (A) -> CompletionStage<B>, // two: (A, B) -> CompletionStage<C>, // three: (A, B, C) -> CompletionStage<D>, // four: (A, B, C, D) -> CompletionStage<E>, // five: (A, B, C, D, E) -> CompletionStage<F>, // six: (A, B, C, D, E, F) -> CompletionStage<G>, // seven: (A, B, C, D, E, F, G) -> CompletionStage<H>, // eight: (A, B, C, D, E, F, G, H) -> CompletionStage<I>, // nine: (A, B, C, D, E, F, G, H, I) -> CompletionStage<R>): CompletionStage<R> = // zero.invoke() // .switchMap { a -> // one.invoke(a) // .switchMap { b -> // two.invoke(a, b) // .switchMap { c -> // three.invoke(a, b, c) // .switchMap { d -> // four.invoke(a, b, c, d) // .switchMap { e -> // five.invoke(a, b, c, d, e) // .switchMap { f -> // six.invoke(a, b, c, d, e, f) // .switchMap { g -> // seven.invoke(a, b, c, d, e, f, g) // .switchMap { h -> // eight.invoke(a, b, c, d, e, f, g, h) // .switchMap { i -> // nine.invoke(a, b, c, d, e, f, g, h, i) // } // } // } // } // } // } // } // } // } // ///** // * Composes an [rx.Observable] from multiple [Transformer] chained by [Observable.compose]. // * // * @return composed Observable // */ //fun <A, R> doCompose( // zero: () -> CompletionStage<A>, // one: ObservableTransformer<A, R>): CompletionStage<R> = // zero() // .compose(one) // ///** // * Composes an [rx.Observable] from multiple [Transformer] chained by [Observable.compose]. // * // * @return composed Observable // */ //fun <A, B, R> doCompose( // zero: () -> CompletionStage<A>, // one: ObservableTransformer<A, B>, // two: ObservableTransformer<B, R>): CompletionStage<R> = // zero() // .compose(one) // .compose(two) // ///** // * Composes an [rx.Observable] from multiple [Transformer] chained by [Observable.compose]. // * // * @return composed Observable // */ //fun <A, B, C, R> doCompose( // zero: () -> CompletionStage<A>, // one: ObservableTransformer<A, B>, // two: ObservableTransformer<B, C>, // three: ObservableTransformer<C, R>): CompletionStage<R> = // zero() // .compose(one) // .compose(two) // .compose(three) // ///** // * Composes an [rx.Observable] from multiple [Transformer] chained by [Observable.compose]. // * // * @return composed Observable // */ //fun <A, B, C, D, R> doCompose( // zero: () -> CompletionStage<A>, // one: ObservableTransformer<A, B>, // two: ObservableTransformer<B, C>, // three: ObservableTransformer<C, D>, // four: ObservableTransformer<D, R>): CompletionStage<R> = // zero() // .compose(one) // .compose(two) // .compose(three) // .compose(four) // ///** // * Composes an [rx.Observable] from multiple [Transformer] chained by [Observable.compose]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, R> doCompose( // zero: () -> CompletionStage<A>, // one: ObservableTransformer<A, B>, // two: ObservableTransformer<B, C>, // three: ObservableTransformer<C, D>, // four: ObservableTransformer<D, E>, // five: ObservableTransformer<E, R>): CompletionStage<R> = // zero() // .compose(one) // .compose(two) // .compose(three) // .compose(four) // .compose(five) // ///** // * Composes an [rx.Observable] from multiple [Transformer] chained by [Observable.compose]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, F, R> doCompose( // zero: () -> CompletionStage<A>, // one: ObservableTransformer<A, B>, // two: ObservableTransformer<B, C>, // three: ObservableTransformer<C, D>, // four: ObservableTransformer<D, E>, // five: ObservableTransformer<E, F>, // six: ObservableTransformer<F, R>): CompletionStage<R> = // zero() // .compose(one) // .compose(two) // .compose(three) // .compose(four) // .compose(five) // .compose(six) // ///** // * Composes an [rx.Observable] from multiple [Transformer] chained by [Observable.compose]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, F, G, R> doCompose( // zero: () -> CompletionStage<A>, // one: ObservableTransformer<A, B>, // two: ObservableTransformer<B, C>, // three: ObservableTransformer<C, D>, // four: ObservableTransformer<D, E>, // five: ObservableTransformer<E, F>, // six: ObservableTransformer<F, G>, // seven: ObservableTransformer<G, R>): CompletionStage<R> = // zero() // .compose(one) // .compose(two) // .compose(three) // .compose(four) // .compose(five) // .compose(six) // .compose(seven) // ///** // * Composes an [rx.Observable] from multiple [Transformer] chained by [Observable.compose]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, F, G, H, R> doCompose( // zero: () -> CompletionStage<A>, // one: ObservableTransformer<A, B>, // two: ObservableTransformer<B, C>, // three: ObservableTransformer<C, D>, // four: ObservableTransformer<D, E>, // five: ObservableTransformer<E, F>, // six: ObservableTransformer<F, G>, // seven: ObservableTransformer<G, H>, // eight: ObservableTransformer<H, R>): CompletionStage<R> = // zero() // .compose(one) // .compose(two) // .compose(three) // .compose(four) // .compose(five) // .compose(six) // .compose(seven) // .compose(eight) // ///** // * Composes an [rx.Observable] from multiple [Transformer] chained by [Observable.compose]. // * // * @return composed Observable // */ //fun <A, B, C, D, E, F, G, H, I, R> doCompose( // zero: () -> CompletionStage<A>, // one: ObservableTransformer<A, B>, // two: ObservableTransformer<B, C>, // three: ObservableTransformer<C, D>, // four: ObservableTransformer<D, E>, // five: ObservableTransformer<E, F>, // six: ObservableTransformer<F, G>, // seven: ObservableTransformer<G, H>, // eight: ObservableTransformer<H, I>, // nine: ObservableTransformer<I, R>): CompletionStage<R> = // zero() // .compose(one) // .compose(two) // .compose(three) // .compose(four) // .compose(five) // .compose(six) // .compose(seven) // .compose(eight) // .compose(nine)
gpl-3.0
b937da03ca04af5e6be328228336aa13
48.027921
156
0.303227
4.570079
false
false
false
false
AlmasB/GroupNet
src/test/kotlin/icurves/CycleFinderTest.kt
1
1914
package icurves import icurves.graph.cycles.ElementaryCyclesSearch import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.hasItems import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Test /** * * * @author Almas Baimagambetov ([email protected]) */ class CycleFinderTest { @Test fun `Strong connected components`() { val nodes = arrayOfNulls<String>(10) val adjMatrix = Array(10) { BooleanArray(10) } for (i in 0..9) { nodes[i] = "Node " + i } adjMatrix[0][1] = true adjMatrix[1][2] = true adjMatrix[2][0] = true adjMatrix[2][6] = true adjMatrix[3][4] = true adjMatrix[4][5] = true adjMatrix[4][6] = true adjMatrix[5][3] = true adjMatrix[6][7] = true adjMatrix[7][8] = true adjMatrix[8][6] = true adjMatrix[6][1] = true val ecs = ElementaryCyclesSearch(adjMatrix, nodes) val cycles = ecs.elementaryCycles val results = arrayListOf<String>() for (i in cycles.indices) { var result = "" val cycle = cycles[i] as List<*> for (j in cycle.indices) { val node = cycle[j] as String if (j < cycle.size - 1) { result += (node + " -> ") } else { result += (node) } } results.add(result) } assertThat(results.size, `is`(4)) assertThat(results, hasItems( "Node 0 -> Node 1 -> Node 2", "Node 1 -> Node 2 -> Node 6", "Node 3 -> Node 4 -> Node 5", "Node 6 -> Node 7 -> Node 8" )) // Node 0 -> Node 1 -> Node 2 // Node 1 -> Node 2 -> Node 6 // Node 3 -> Node 4 -> Node 5 // Node 6 -> Node 7 -> Node 8 } }
apache-2.0
5e3b581966fb50523638965da31c5014
25.971831
58
0.498955
3.851107
false
false
false
false
ansman/kotshi
compiler/src/main/kotlin/se/ansman/kotshi/model/JsonAdapterFactory.kt
1
6444
package se.ansman.kotshi.model import com.squareup.kotlinpoet.* import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.moshi.JsonAdapter import se.ansman.kotshi.KotshiConstructor import se.ansman.kotshi.Types internal data class JsonAdapterFactory( val targetType: ClassName, val usageType: UsageType, val generatedAdapters: List<GeneratedAdapter>, val manuallyRegisteredAdapters: List<RegisteredAdapter>, ) { val isEmpty: Boolean get() = generatedAdapters.isEmpty() && manuallyRegisteredAdapters.isEmpty() val factoryClassName: ClassName = ClassName(targetType.packageName, "Kotshi${targetType.simpleNames.joinToString("_")}") companion object { fun <E> E.getManualAdapter( logError: (String, E) -> Unit, getSuperClass: E.() -> E?, getSuperTypeName: E.() -> TypeName?, adapterClassName: ClassName, typeVariables: E.() -> List<TypeVariableName>, isObject: Boolean, isAbstract: Boolean, priority: Int, getKotshiConstructor: E.() -> KotshiConstructor?, getJsonQualifiers: E.() -> Set<AnnotationModel>, ): RegisteredAdapter? { val adapterTypeVariables = typeVariables() val adapterType = findJsonAdapterType( logError = logError, typeVariables = typeVariables, getSuperClass = getSuperClass, getSuperTypeName = getSuperTypeName, ) ?: run { logError( "@RegisterJsonAdapter can only be used on classes that extends JsonAdapter.", this ) return null } if (isAbstract) { logError( "@RegisterJsonAdapter cannot be applied to generic classes.", this ) return null } return RegisteredAdapter( adapterTypeName = if (adapterTypeVariables.isEmpty()) { adapterClassName } else { adapterClassName.parameterizedBy(adapterTypeVariables) }, targetType = adapterType, constructor = if (isObject) { null } else { getKotshiConstructor() ?: run { logError( "Could not find a suitable constructor. A constructor can have any combination of a parameter of type Moshi and of a parameter of type Array<Type>.", this ) return null } }, qualifiers = getJsonQualifiers(), priority = priority, ) } private fun <E> E.findJsonAdapterType( logError: (String, E) -> Unit, typeVariables: E.() -> List<TypeVariableName>, getSuperClass: E.() -> E?, getSuperTypeName: E.() -> TypeName?, typeVariableResolver: (index: Int, TypeVariableName) -> TypeName = { _, type -> type }, ): TypeName? { val typeVariableIndexByName = typeVariables() .withIndex() .associateBy({ it.value.name }, { it.index }) fun TypeName.resolve(): TypeName = when (this) { is ClassName -> this Dynamic -> this is LambdaTypeName -> this // TODO: Resolve names here if possible is ParameterizedTypeName -> copy(typeArguments = typeArguments.map { it.resolve() }) is TypeVariableName -> typeVariableResolver(typeVariableIndexByName.getValue(name), this) is WildcardTypeName -> this } val superTypeName = getSuperTypeName() val adapterType = superTypeName?.asJsonAdapterTypeOrNull() ?: getSuperClass()?.findJsonAdapterType( logError, typeVariables, getSuperClass, getSuperTypeName ) { index, _ -> (superTypeName as ParameterizedTypeName).typeArguments[index] } return adapterType?.resolve() } private fun TypeName.asJsonAdapterTypeOrNull(): TypeName? = (this as? ParameterizedTypeName) ?.takeIf { it.rawType.toString() == JsonAdapter::class.java.name } ?.typeArguments ?.single() } sealed class UsageType { /** Generates an object that directly implements JsonAdapter.Factory */ object Standalone : UsageType() /** Generates an object that implements the given [parent] which in turn implements JsonAdapter.Factory */ data class Subclass(val parent: TypeName, val parentIsInterface: Boolean) : UsageType() } } internal fun <C, P> Sequence<C>.findKotshiConstructor( parameters: C.() -> Iterable<P>, type: P.() -> TypeName, hasDefaultValue: P.() -> Boolean, name: P.() -> String, ): KotshiConstructor? { var hasConstructor = false outer@ for (constructor in this) { hasConstructor = true var moshiParameterName: String? = null var typesParameterName: String? = null for (parameter in constructor.parameters()) { when (type(parameter)) { Types.Moshi.moshi -> { if (moshiParameterName != null) { continue@outer } moshiParameterName = parameter.name() } Types.Kotshi.typesArray -> { if (typesParameterName != null) { continue@outer } typesParameterName = parameter.name() } else -> if (!parameter.hasDefaultValue()) { continue@outer } } } return KotshiConstructor( moshiParameterName = moshiParameterName, typesParameterName = typesParameterName ) } // Every class without an explicit constructor has a default constructor if (!hasConstructor) { return KotshiConstructor() } return null }
apache-2.0
0af719074be9696fd12a950c64da0b88
37.130178
177
0.542831
5.863512
false
false
false
false
RyanAndroidTaylor/Rapido
rapidocommon/src/main/java/com/izeni/rapidocommon/PhotoUtils.kt
1
9345
package com.izeni.rapidocommon import android.app.Activity import android.content.* import android.content.pm.PackageManager import android.database.Cursor import android.media.ExifInterface import android.net.Uri import android.os.Build import android.os.Environment import android.provider.DocumentsContract import android.provider.MediaStore import android.support.v4.content.FileProvider import android.webkit.MimeTypeMap import java.io.File import java.io.IOException import java.lang.Long import java.util.* /** * The MIT License (MIT) * * Copyright (c) 2016 Izeni, Inc. * * 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. **/ object PhotoUtils { fun getImageRotation(context: Context, imageUri: Uri): Int { try { var rotation = ExifInterface.ORIENTATION_UNDEFINED getPath(context, imageUri)?.let { val exif = ExifInterface(it) rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED) } if (rotation == ExifInterface.ORIENTATION_UNDEFINED) return getRotationFromMediaStore(context, imageUri) else return exifToDegrees(rotation) } catch (ex: IOException) { return getRotationFromMediaStore(context, imageUri) } } fun createImageFile(context: Context): File { val imageFileName = "JPEG_${UUID.randomUUID()}" val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) val image = File.createTempFile(imageFileName, ".jpg", storageDir) return image } fun takePicture(context: Activity, code: Int, file: File = createImageFile(context)): File { val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) if (takePictureIntent.resolveActivity(context.packageManager) != null) { val uri = FileProvider.getUriForFile(context, "com.hitlabs.bubble.fileprovider", file) val resInfoList = context.packageManager.queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY) for (resolveInfo in resInfoList) { val packageName = resolveInfo.activityInfo.packageName context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION) } takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri) context.startActivityForResult(takePictureIntent, code) } return file } fun getMimeType(context: Context, uri: Uri): String { if (uri.scheme == ContentResolver.SCHEME_CONTENT) { val cr = context.contentResolver return cr.getType(uri) } else { val fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri.toString()) return MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase()) } } fun getImageContentUri(context: Context, imageFile: File): Uri? { val filePath = imageFile.absolutePath val cursor = context.contentResolver.query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, arrayOf(MediaStore.Images.Media._ID), MediaStore.Images.Media.DATA + "=? ", arrayOf<String>(filePath), null) if (cursor != null && cursor.moveToFirst()) { val id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID)) cursor.close() return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id) } else { if (imageFile.exists()) { val values = ContentValues() values.put(MediaStore.Images.Media.DATA, filePath) return context.contentResolver.insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) } else { return null } } } private fun getRotationFromMediaStore(context: Context, imageUri: Uri): Int { if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) || !DocumentsContract.isDocumentUri(context, imageUri)) { val columns = arrayOf(MediaStore.Images.Media.DATA, MediaStore.Images.Media.ORIENTATION) val cursor = context.contentResolver.query(imageUri, columns, null, null, null) ?: return 0 cursor.moveToFirst() return cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media.ORIENTATION)) ?: 0 } else { var id: String = "" DocumentsContract.getDocumentId(imageUri).split(":").let { if(it.size > 1) id = it[1] else it[0] } val columns = arrayOf(MediaStore.Images.Media.DATA, MediaStore.Images.Media.ORIENTATION) val cursor = context.contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, MediaStore.Images.Media._ID + " = ?", arrayOf(id), null) ?: return 0 cursor.moveToFirst() return cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media.ORIENTATION)) ?: 0 } } fun getPath(context: Context, uri: Uri): String? { val isKitKatOrAbove = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT if (isKitKatOrAbove && DocumentsContract.isDocumentUri(context, uri)) { if ("com.android.externalstorage.documents" == uri.authority) { val docId = DocumentsContract.getDocumentId(uri) val split = docId.split(":") val type = split[0] if ("primary".equals(type, ignoreCase = true)) { return "${Environment.getExternalStorageDirectory()}/${split[1]}" } } else if ("com.android.providers.downloads.documents" == uri.authority) { val id = DocumentsContract.getDocumentId(uri) val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id)) return getDataColumn(context, contentUri, null, null) } else if ("com.android.providers.media.documents" == uri.authority) { val docId = DocumentsContract.getDocumentId(uri) val split = docId.split(":") val type = split[0] val contentUri: Uri = when (type) { "image" -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI "video" -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI "audio" -> MediaStore.Audio.Media.EXTERNAL_CONTENT_URI else -> return null } val selection = "_id=?" val selectionArgs = arrayOf(split[1]) return getDataColumn(context, contentUri, selection, selectionArgs) } } else if ("content".equals(uri.scheme, ignoreCase = true)) { return getDataColumn(context, uri, null, null) } else if ("file".equals(uri.scheme, ignoreCase = true)) { return uri.path } return null } fun getDataColumn(context: Context, uri: Uri, selection: String?, selectionArgs: Array<String>?): String? { var cursor: Cursor? = null val column = "_data" val projection = arrayOf(column) try { cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor != null && cursor.moveToFirst()) { val column_index = cursor.getColumnIndexOrThrow(column) return cursor.getString(column_index) } } finally { if (cursor != null) cursor.close() } return null } private fun exifToDegrees(exifOrientation: Int): Int { if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90 } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { return 180 } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { return 270 } else { return 0 } } }
mit
6b5c46e8490c208c27b6ace792c42b52
40.537778
141
0.631675
4.915834
false
false
false
false
jiangkang/KTools
buildSrc/src/main/kotlin/Deps.kt
1
5163
import Google.vHilt import org.gradle.kotlin.dsl.DependencyHandlerScope const val junit = "junit:junit:4.13" const val mockito = "org.mockito:mockito-core:3.3.3" const val eventBus = "org.greenrobot:eventbus:3.1.1" const val material = "com.google.android.material:material:1.1.0" const val zxing = "com.google.zxing:core:3.4.0" const val lottie = "com.airbnb.android:lottie:3.4.1" const val gson = "com.google.code.gson:gson:2.8.6" const val anrWatchDog = "com.github.anrwatchdog:anrwatchdog:1.4.0" const val hamcrest = "org.hamcrest:hamcrest-library:2.2" const val javapoet = "com.squareup:javapoet:1.13.0" object Google { const val vHilt = "2.28-alpha" const val hiltPlugin = "com.google.dagger:hilt-android-gradle-plugin:$vHilt" const val oboe = "com.google.oboe:oboe:1.4.3" } object Square { object LeakCanary { private const val version = "2.5" const val android = "com.squareup.leakcanary:leakcanary-android:$version" const val sharkHprof = "com.squareup.leakcanary:shark-hprof:$version" const val sharkGraph = "com.squareup.leakcanary:shark-graph:$version" const val sharkAndroid = "com.squareup.leakcanary:shark-android:$version" } } fun DependencyHandlerScope.hilt() { impl("com.google.dagger:hilt-android:$vHilt") kapt("com.google.dagger:hilt-android-compiler:$vHilt") } object Kotlin { const val kotlinVersion = "1.4.21" const val coroutines = "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9" const val stdlib = "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" } object AndroidX { const val core = "androidx.core:core:1.3.0" const val constraintLayout = "androidx.constraintlayout:constraintlayout:2.0.4" const val recyclerView = "androidx.recyclerview:recyclerview:1.1.0" const val testRunner = "androidx.test:runner:1.2.0" const val espressoCore = "androidx.test.espresso:espresso-core:3.2.0" const val annotation = "androidx.annotation:annotation:1.1.0" const val appcompat = "androidx.appcompat:appcompat:1.1.0" const val cardView = "androidx.cardview:cardview:1.0.0" const val dynamicAnimation = "androidx.dynamicanimation:dynamicanimation:1.0.0" const val uiautomator = "androidx.test.uiautomator:uiautomator:2.2.0" const val multiDex = "androidx.multidex:multidex:2.0.1" const val viewpager2 = "androidx.viewpager2:viewpager2:1.0.0" const val print = "androidx.print:print:1.0.0" const val startup = "androidx.startup:startup-runtime:1.0.0" const val futures = "androidx.concurrent:concurrent-futures-ktx:1.1.0" const val tracing = "androidx.tracing:tracing-ktx:1.0.0" const val exifinterface = "androidx.exifinterface:exifinterface:1.3.2" const val customview = "androidx.customview:customview:1.1.0" const val paging = "androidx.paging:paging-runtime:2.1.2" const val biometric = "androidx.biometric:biometric:1.0.1" object Navigation { const val fragment = "androidx.navigation:navigation-fragment:2.3.0" const val ui = "androidx.navigation:navigation-ui:2.3.0" } object Room { const val runtime = "androidx.room:room-runtime:2.2.5" const val compiler = "androidx.room:room-compiler:2.2.5" } object Lifecycle { const val runtime = "androidx.lifecycle:lifecycle-runtime:2.2.0" const val extension = "androidx.lifecycle:lifecycle-extensions:2.2.0" const val viewModel = "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0" const val compiler = "androidx.lifecycle:lifecycle-compiler:2.2.0" } object WorkManager { private const val version = "2.4.0" const val runtime = "androidx.work:work-runtime:$version" // java only const val runtimeKtx = "androidx.work:work-runtime-ktx:$version" // kotlin + coroutines } object DataStore { private const val version = "1.0.0-alpha01" const val preferences = "androidx.datastore:datastore-preferences:$version" // preferences const val core = "androidx.datastore:datastore-core:$version" // proto } } fun DependencyHandlerScope.okHttp() { impl("com.squareup.okhttp3:okhttp:4.4.0") testImpl("com.squareup.okhttp3:mockwebserver:4.2.0") impl("com.squareup.okhttp3:logging-interceptor:4.2.0") } fun DependencyHandlerScope.retrofit() { impl("com.squareup.retrofit2:retrofit:2.6.1") impl("com.squareup.retrofit2:converter-gson:2.6.1") } fun DependencyHandlerScope.glide() { impl("com.github.bumptech.glide:glide:4.11.0") impl("com.github.bumptech.glide:okhttp3-integration:4.11.0") kapt("com.github.bumptech.glide:compiler:4.11.0") } fun DependencyHandlerScope.fresco() { val vFresco = "2.3.0" api("com.facebook.fresco:fresco:$vFresco") api("com.facebook.fresco:animated-gif:$vFresco") api("com.facebook.fresco:webpsupport:$vFresco") api("com.facebook.fresco:animated-webp:$vFresco") } fun DependencyHandlerScope.leakcanary() { val vLeakCanary = "1.6.3" debugImpl("com.squareup.leakcanary:leakcanary-android:$vLeakCanary") releaseImpl("com.squareup.leakcanary:leakcanary-android-no-op:$vLeakCanary") }
mit
e735967bea7b889b39c1554bcbfa9913
40.98374
100
0.712183
3.401186
false
false
false
false
Ribesg/Pure
src/main/kotlin/fr/ribesg/minecraft/pure/bukkit/Pure.kt
1
2891
package fr.ribesg.minecraft.pure.bukkit import fr.ribesg.minecraft.pure.common.Log import fr.ribesg.minecraft.pure.common.MCJarHandler import fr.ribesg.minecraft.pure.common.MCVersion import org.bukkit.World.Environment import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.block.Action import org.bukkit.event.player.PlayerInteractEvent import org.bukkit.generator.ChunkGenerator import org.bukkit.plugin.java.JavaPlugin import java.io.IOException /** * @author Ribesg */ object Pure : JavaPlugin() { private var metrics: PureMetrics? = null override fun onEnable() { Log.initJavaLogger(this.logger) this.metrics = PureMetrics(this) // XXX For debugging that snow bug in 1.6.4 this.server.pluginManager.registerEvents(object : Listener { @EventHandler fun onPlayerInteract(event: PlayerInteractEvent) { val b = when (event.action) { Action.LEFT_CLICK_BLOCK -> event.clickedBlock Action.RIGHT_CLICK_BLOCK -> event.clickedBlock.getRelative(event.blockFace) else -> null } if (b != null) { event.player.sendMessage(b.type.name() + " - " + b.data); } } }, this) } override fun onDisable() { this.metrics = null Log.dereferenceLogger() } override fun getDefaultWorldGenerator(worldName: String, id: String): ChunkGenerator? { if (id.isEmpty()) { Log.error("Parameters are required for the Pure world generator.") return null } val split = id.split(",") if (split.size() > 2) { Log.error("Invalid id: " + id) return null } val version = MCVersion.get(split[0]) ?: return null val environment: Environment? if (split.size() > 1) { try { environment = Environment.valueOf(split[1].toUpperCase()) } catch (e: IllegalArgumentException) { Log.error("Invalid Bukkit Environment String: " + split[1].toUpperCase()) environment = null } } else { environment = null } try { MCJarHandler.require(this.dataFolder.toPath().resolve("jars"), version, true) } catch (e: IOException) { Log.error("Failed to install MC Version $version", e) return null } try { val generator = version.getChunkGenerator(environment) this.metrics?.newGenerator(version, generator) return generator } catch (e: IllegalStateException) { Log.error("Failed to get Chunk Generator for version $version", e) return null } } }
gpl-3.0
695ddc33d200c8edf2a578d546b30f04
30.086022
95
0.584573
4.603503
false
false
false
false
ffgiraldez/rx-mvvm-android
app/src/main/java/es/ffgiraldez/comicsearch/comics/data/network/ComicVineApi.kt
1
676
package es.ffgiraldez.comicsearch.comics.data.network import retrofit2.http.GET import retrofit2.http.Query interface SuspendComicVineApi { companion object { const val KEY = "d800216c205879548fdc491e0a260ff402633c00" const val BASE_URL = "https://www.comicvine.com" } @GET("/api/search?format=json&field_list=name&limit=20&page=1&resources=volume&api_key=$KEY") suspend fun fetchSuggestedVolumes(@Query("query") query: String): SuggestionResponse @GET("/api/search?format=json&field_list=name,image,publisher&limit=20&page=1&resources=volume&api_key=$KEY") suspend fun fetchVolumes(@Query("query") query: String): VolumeResponse }
apache-2.0
62d1b6b04098ba4b60f1537c64b9b74d
36.611111
113
0.747041
3.363184
false
false
false
false
Zomis/UltimateTTT
uttt-jvm/src/test/kotlin/net/zomis/tttultimate/HumanInput.kt
1
2869
package net.zomis.tttultimate import net.zomis.tttultimate.games.TTController import net.zomis.tttultimate.games.TTUltimateController import net.zomis.tttultimate.players.TTAI import net.zomis.tttultimate.players.TTAIFactory import net.zomis.tttultimate.players.TTHuman import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test class HumanInput { private val ai = TTAIFactory.version3().build() internal val logAI = TTAIFactory.best().build() @Test @Disabled fun humanInput() { val human = TTHuman() val controller = TTUltimateController(TTFactories().ultimate(3)) while (!controller.isGameOver) { output(controller) controller.play(human.play(controller)) output(controller) // logAI.logScores(game); val tile = ai.play(controller) ?: continue controller.play(tile) // System.out.println("AI Played at " + tile.getGlobalX() + ", " + tile.getGlobalY()); } human.close() } fun output(game: TTController) { val RADIX = Character.MAX_RADIX val quad = game.game.sizeX * game.game.sizeY val size = game.game.sizeX val pre = " " print("$pre ") for (i in 0 until quad) { if (i > 0 && i % size == 0) print(' ') print(Integer.toString(i, RADIX)) } println("") print(pre + " " + "-".repeat(quad + size + 1)) println("") for (y in 0 until quad) { val out = StringBuilder(pre) for (x in 0 until quad) { if (x == 0) { out.append(Integer.toString(y, RADIX)) out.append('|') } val tile = game.game.getSmallestTile(x, y) out.append(getCharOutput(game, tile!!)) if (x % size == size - 1) out.append('|') } println(out) if (y % size == size - 1) println(pre + " " + "-".repeat(quad + size + 1)) } print(pre) if (game.isGameOver) println("Game is won by " + game.wonBy) else println("Current player is " + game.currentPlayer) println() } companion object { fun getCharOutput(controller: TTController, tile: TTBase): Char { val player = tile.wonBy if (player == null || player === TTPlayer.NONE) return if (controller.isAllowedPlay(tile)) '.' else ' ' if (player === TTPlayer.XO) return '?' val winner = tile.parent!!.wonBy return if (TTPlayer.isExactlyOnePlayer(winner) && !winner.equals(player)) '-' else player.toString()[0] } } }
mit
c06fbb616066d3852508dc39388f19e3
31.602273
100
0.528059
4.018207
false
false
false
false
google-developer-training/android-demos
DonutTracker/NavigationUI/app/src/main/java/com/android/samples/donuttracker/coffee/CoffeeEntryViewModel.kt
2
2045
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.samples.donuttracker.coffee import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.liveData import androidx.lifecycle.viewModelScope import com.android.samples.donuttracker.model.Coffee import com.android.samples.donuttracker.storage.CoffeeDao import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class CoffeeEntryViewModel(private val coffeeDao: CoffeeDao) : ViewModel() { private var coffeeLiveData: LiveData<Coffee>? = null fun get(id: Long): LiveData<Coffee> { return coffeeLiveData ?: liveData { emit(coffeeDao.get(id)) }.also { coffeeLiveData = it } } fun addData( id: Long, name: String, description: String, rating: Int, setupNotification: (Long) -> Unit ) { val coffee = Coffee(id, name, description, rating) CoroutineScope(Dispatchers.IO).launch { var actualId = id if (id > 0) { update(coffee) } else { actualId = insert(coffee) } setupNotification(actualId) } } private suspend fun insert(donut: Coffee) = coffeeDao.insert(donut) private fun update(donut: Coffee) = viewModelScope.launch(Dispatchers.IO) { coffeeDao.update(donut) } }
apache-2.0
b3e3e20d4cafb71ca2a464db8e736244
29.522388
79
0.676773
4.436009
false
false
false
false
devknightz/MinimalWeatherApp
app/src/main/java/you/devknights/minimalweather/viewmodel/MinimalViewModelFactory.kt
1
1720
/* * Copyright 2017 vinayagasundar * Copyright 2017 randhirgupta * * 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 you.devknights.minimalweather.viewmodel import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import javax.inject.Inject import javax.inject.Provider import javax.inject.Singleton /** * @author vinayagasundar */ @Singleton class MinimalViewModelFactory @Inject constructor(private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { var creator: Provider<out ViewModel>? = creators[modelClass] if (creator == null) { for ((key, value) in creators) { if (modelClass.isAssignableFrom(key)) { creator = value break } } } if (creator == null) { throw IllegalArgumentException("unknown model class $modelClass") } try { return creator.get() as T } catch (e: Exception) { throw RuntimeException(e) } } }
apache-2.0
6b7afa5a695a19ae80ab787b449eeeb4
29.175439
133
0.661628
4.574468
false
false
false
false
jdinkla/groovy-java-ray-tracer
src/main/kotlin/net/dinkla/raytracer/lights/Ambient.kt
1
560
package net.dinkla.raytracer.lights import net.dinkla.raytracer.colors.Color import net.dinkla.raytracer.hits.Shade import net.dinkla.raytracer.math.Ray import net.dinkla.raytracer.math.Vector3D import net.dinkla.raytracer.worlds.World open class Ambient : Light() { // emissive material var ls: Double = 1.0 var color: Color = Color.WHITE override fun L(world: World, sr: Shade): Color = color * ls override fun getDirection(sr: Shade) = Vector3D.ZERO override fun inShadow(world: World, ray: Ray, sr: Shade): Boolean = false }
apache-2.0
c9cf2eccb0a6cadc93a4bc4c413701a7
25.666667
77
0.733929
3.566879
false
false
false
false
Ekito/koin
koin-projects/examples/androidx-samples/src/main/java/org/koin/sample/androidx/workmanager/WorkManagerActivity.kt
1
3777
package org.koin.sample.androidx.workmanager import android.annotation.SuppressLint import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.work.* import junit.framework.Assert.assertTrue import kotlinx.android.synthetic.main.workmanager_activity.* import kotlinx.coroutines.* import org.junit.Assert import org.koin.android.ext.android.inject import org.koin.sample.android.R import org.koin.sample.androidx.sdk.HostActivity import org.koin.sample.androidx.utils.navigateTo import org.koin.sample.androidx.workmanager.SimpleWorker.Companion.createData /** * @author : Fabio de Matos * @since : 16/02/2020 **/ class WorkManagerActivity : AppCompatActivity() { private val workManager = WorkManager.getInstance(this) private val service1: SimpleWorkerService by inject() @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // pre-setup: preparing UI setContentView(R.layout.workmanager_activity) title = "Android Work Manager" workmanager_message.text = "Work Manager is starting." workmanager_button.setOnClickListener { navigateTo<HostActivity>(isRoot = true) } workmanager_button.isEnabled = false runWorkers() } private fun runWorkers() { CoroutineScope(Dispatchers.Default) .launch { assertTrue(service1.isEmpty()) // start test enqueuesWorkers() // verify it worked assertResponses(timeoutMs = 5_000) } } /** * Waits for [service1]'s channel for up to [timeoutMs]. * * If channel doesn't contain 2 items by then, throws exception and crashes app. * */ @SuppressLint("SetTextI18n") private suspend fun assertResponses(timeoutMs: Long) { try { withTimeout(timeoutMs) { service1.popAnswer() .let { Assert.assertEquals(SimpleWorker.answer1st, it) } service1.popAnswer() .let { Assert.assertEquals(SimpleWorker.answer2nd, it) } service1.isEmpty() } } catch (e: CancellationException) { throw RuntimeException(e) // taking too long to receive 42 means WorkManager failed somehow } withContext(Dispatchers.Main) { workmanager_message.text = "Work Manager completed!" workmanager_button.isEnabled = true } } private suspend fun enqueuesWorkers() { WorkManager.getInstance(this@WorkManagerActivity) .cancelAllWork() .result .await() enqueueWork<SimpleWorker>(createData(42)) enqueueWork<SimpleWorker>(createData(43)) } /** * @param T ListenableWorker that will perform work * @param answer the data fed into T when it's about to begin its work */ private inline fun <reified T : ListenableWorker> enqueueWork(data: Data): OneTimeWorkRequest { val workName = SimpleWorker::class.simpleName + data.keyValueMap.getValue(SimpleWorker.KEY_ANSWER) return OneTimeWorkRequestBuilder<T>() .setInputData(data) .build() .also { workManager .enqueueUniqueWork( workName, ExistingWorkPolicy.APPEND, it ) } } }
apache-2.0
d1cd12ddf782a7f064af7ceb093a49e4
30.747899
106
0.587239
5.188187
false
false
false
false
semonte/intellij-community
java/java-tests/testSrc/com/intellij/java/ide/actions/CreateModuleInfoActionTest.kt
1
2394
/* * 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.java.ide.actions import com.intellij.ide.IdeView import com.intellij.ide.fileTemplates.FileTemplateManager import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiJavaModule import com.intellij.psi.PsiManager import com.intellij.testFramework.MapDataContext import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase import com.intellij.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor.MAIN class CreateModuleInfoActionTest : LightJava9ModulesCodeInsightFixtureTestCase() { fun test() { val dir = PsiManager.getInstance(project).findDirectory(MAIN.root())!! val ctx = MapDataContext(mapOf(LangDataKeys.IDE_VIEW to TestIdeView(dir), LangDataKeys.MODULE to myModule)) val event = AnActionEvent.createFromDataContext("", null, ctx) ActionManager.getInstance().getAction("NewModuleInfo")!!.actionPerformed(event) val file = dir.findFile(PsiJavaModule.MODULE_INFO_FILE)!! val p = FileTemplateManager.getInstance(project).defaultProperties assertEquals(""" /** * Created by ${p["USER"]} on ${p["DATE"]}. */ module light.idea.test.case { }""".trimIndent(), file.text) } private class TestIdeView(private val dir: PsiDirectory) : IdeView { override fun getDirectories() = arrayOf(dir) override fun getOrChooseDirectory() = throw UnsupportedOperationException() } override fun setUp() { super.setUp() PlatformTestUtil.setLongMeaninglessFileIncludeTemplateTemporarilyFor(project, testRootDisposable) } }
apache-2.0
50100cbe08e3db98dc5da66122899789
41.017544
111
0.77193
4.59501
false
true
false
false
Sevran/DnDice
app/src/main/java/io/deuxsept/dndice/MainView/RecentFragment.kt
1
2130
package io.deuxsept.dndice.MainView import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import io.deuxsept.dndice.Adapter.RecentAdapter import io.deuxsept.dndice.Database.DatabaseHelper import io.deuxsept.dndice.R /** * Created by Luo * 13/08/2016. */ class RecentFragment : Fragment() { lateinit var mDb: DatabaseHelper lateinit var mNoneView: View lateinit var mRecyclerView: RecyclerView lateinit var mAdapter: RecentAdapter companion object { private var mFragment: RecentFragment? = null fun newInstance(): RecentFragment { if (mFragment == null) { mFragment = RecentFragment() } return mFragment as RecentFragment } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mDb = DatabaseHelper.getInstance(context)!! } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view: View = inflater!!.inflate(R.layout.fragment_recent, container, false) mNoneView = view.findViewById(R.id.recent_none_view) mRecyclerView = view.findViewById(R.id.recent_recycler) as RecyclerView val layoutManager = LinearLayoutManager(context) layoutManager.orientation = LinearLayoutManager.VERTICAL mRecyclerView.layoutManager = layoutManager mAdapter = RecentAdapter(this) mRecyclerView.adapter = mAdapter getRollsFromDatabase() return view } private fun getRollsFromDatabase() { val rolls = mDb.getAllRecentRolls() if (rolls.count() !== 0) mAdapter.addAll(rolls) shouldShowEmptyState() } fun shouldShowEmptyState() { if (mAdapter.itemCount === 0) mNoneView.visibility = View.VISIBLE else mNoneView.visibility = View.GONE } }
mit
bfccf135bd6e6ae3f12cf8a03b029fe7
29.442857
117
0.688732
4.640523
false
false
false
false
Shynixn/BlockBall
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/commandmenu/BossbarPage.kt
1
5812
package com.github.shynixn.blockball.core.logic.business.commandmenu import com.github.shynixn.blockball.api.business.enumeration.* import com.github.shynixn.blockball.api.persistence.entity.Arena import com.github.shynixn.blockball.api.persistence.entity.ChatBuilder import com.github.shynixn.blockball.core.logic.persistence.entity.ChatBuilderEntity /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ class BossbarPage : Page(BossbarPage.ID, EffectsSettingsPage.ID) { companion object { /** Id of the page. */ const val ID = 9 } /** * Returns the key of the command when this page should be executed. * * @return key */ override fun getCommandKey(): MenuPageKey { return MenuPageKey.BOSSBAR } /** * Executes actions for this page. * * @param cache cache */ override fun <P> execute( player: P, command: MenuCommand, cache: Array<Any?>, args: Array<String> ): MenuCommandResult { val arena = cache[0] as Arena val bossbar = arena.meta.bossBarMeta cache[5] = bossbar.flags.map { p -> p.name } if (command == MenuCommand.BOSSBAR_OPEN && args.size == 3) { bossbar.style = BossbarStyle.values()[args[2].toInt()] } else if (command == MenuCommand.BOSSBAR_CALLBACKCOLORS && args.size == 3) { bossbar.color = BossbarColor.values()[args[2].toInt()] } else if (command == MenuCommand.BOSSBAR_CALLBACKFLAGS && args.size == 3) { bossbar.flags.clear() bossbar.flags.add(BossBarFlag.values()[args[2].toInt()]) } else if (command == MenuCommand.BOSSBAR_MESSAGE) { bossbar.message = this.mergeArgs(2, args) } else if (command == MenuCommand.BOSSBAR_TOGGLE) { bossbar.enabled = !bossbar.enabled } else if (command == MenuCommand.BOSSBAR_PERCENT) { val result = args[2].toDoubleOrNull() if (result != null) { bossbar.percentage = result } } return super.execute(player, command, cache, args) } /** * Builds the page content. * * @param cache cache * @return content */ override fun buildPage(cache: Array<Any?>): ChatBuilder { val arena = cache[0] as Arena val bossbar = arena.meta.bossBarMeta if (bossbar.flags.isEmpty()) bossbar.flags.add(BossBarFlag.NONE) val builder = ChatBuilderEntity() .component("- Message: " + bossbar.message).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.BOSSBAR_MESSAGE.command) .setHoverText("Edit the message of the bossbar.") .builder().nextLine() .component("- Enabled: " + bossbar.enabled).builder() .component(MenuClickableItem.TOGGLE.text).setColor(MenuClickableItem.TOGGLE.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.BOSSBAR_TOGGLE.command) .setHoverText("Toggle the bossbar.") .builder().nextLine() .component("- Percentage: " + bossbar.percentage).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.BOSSBAR_PERCENT.command) .setHoverText("Edit the amount of percentage the bossbar is filled.") .builder() .nextLine().component("- Color: " + bossbar.color).builder() .component(MenuClickableItem.SELECT.text).setColor(MenuClickableItem.SELECT.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.LIST_BOSSBARCOLORS.command) .setHoverText("Opens the selectionbox for colors.") .builder().nextLine() .component("- Style: " + bossbar.style).builder() .component(MenuClickableItem.SELECT.text).setColor(MenuClickableItem.SELECT.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.LIST_BOSSBARSTYLES.command) .setHoverText("Opens the selectionbox for styles.") .builder().nextLine() .component("- Flags: " + bossbar.flags[0]).builder() .component(MenuClickableItem.SELECT.text).setColor(MenuClickableItem.SELECT.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.LIST_BOSSBARFLAGS.command) .setHoverText("Opens the selectionbox for flags.") .builder().nextLine() return builder } }
apache-2.0
46888f101733527886241812c85371eb
44.062016
97
0.658981
4.292467
false
false
false
false
dya-tel/TSU-Schedule
src/main/kotlin/ru/dyatel/tsuschedule/layout/WeekdayItem.kt
1
4073
package ru.dyatel.tsuschedule.layout import android.content.Context import android.support.v4.view.ViewCompat import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.Gravity import android.view.View import android.view.ViewGroup import android.widget.TextView import com.mikepenz.fastadapter.FastAdapter import com.mikepenz.fastadapter.adapters.ItemAdapter import com.mikepenz.fastadapter.items.AbstractItem import org.jetbrains.anko.backgroundColorResource import org.jetbrains.anko.cardview.v7.cardView import org.jetbrains.anko.find import org.jetbrains.anko.frameLayout import org.jetbrains.anko.matchParent import org.jetbrains.anko.padding import org.jetbrains.anko.recyclerview.v7.recyclerView import org.jetbrains.anko.textColorResource import org.jetbrains.anko.textView import org.jetbrains.anko.verticalLayout import ru.dyatel.tsuschedule.ADAPTER_WEEKDAY_ITEM_ID import ru.dyatel.tsuschedule.NORMAL_WEEKDAY_ORDER import ru.dyatel.tsuschedule.R import ru.dyatel.tsuschedule.model.Lesson class WeekdayItem<T : Lesson>( private val name: String, lessons: List<T>, viewProvider: (Context) -> LessonView<T> ) : AbstractItem<WeekdayItem<T>, WeekdayItem.ViewHolder<T>>() { private companion object { private val weekdayViewId = View.generateViewId() private val lessonRecyclerViewId = View.generateViewId() } private val adapter = ItemAdapter<LessonItem<T>>() private val fastAdapter: FastAdapter<LessonItem<T>> = FastAdapter.with(adapter) init { withIdentifier(NORMAL_WEEKDAY_ORDER.indexOf(name).toLong()) adapter.set(lessons.map { LessonItem(it, viewProvider) }) } class ViewHolder<T : Lesson>(view: View) : FastAdapter.ViewHolder<WeekdayItem<T>>(view) { private val weekdayView = view.find<TextView>(weekdayViewId) private val lessonRecyclerView = view.find<RecyclerView>(lessonRecyclerViewId) override fun bindView(item: WeekdayItem<T>, payloads: List<Any>) { weekdayView.text = item.name lessonRecyclerView.adapter = item.fastAdapter } override fun unbindView(item: WeekdayItem<T>) { weekdayView.text = null lessonRecyclerView.adapter = null } } override fun createView(ctx: Context, parent: ViewGroup?): View { return ctx.cardView { lparams(width = matchParent) { leftMargin = DIM_CARD_HORIZONTAL_MARGIN rightMargin = DIM_CARD_HORIZONTAL_MARGIN topMargin = DIM_CARD_VERTICAL_MARGIN bottomMargin = DIM_CARD_VERTICAL_MARGIN } cardElevation = DIM_ELEVATION_F radius = DIM_CARD_RADIUS_F verticalLayout(R.style.WeekdayTheme) { lparams(width = matchParent) { padding = DIM_CARD_PADDING } frameLayout { lparams(width = matchParent) { bottomMargin = DIM_CARD_PADDING padding = DIM_MEDIUM } backgroundColorResource = R.color.primary_color textView { id = weekdayViewId gravity = Gravity.CENTER textColorResource = R.color.text_title_color } } recyclerView { id = lessonRecyclerViewId lparams(width = matchParent) layoutManager = LinearLayoutManager(ctx) ViewCompat.setNestedScrollingEnabled(this, false) } } } } override fun getType() = ADAPTER_WEEKDAY_ITEM_ID override fun getViewHolder(view: View) = ViewHolder<T>(view) override fun getLayoutRes() = throw UnsupportedOperationException() override fun equals(other: Any?): Boolean { return super.equals(other) && (other as WeekdayItem<*>).name == name } }
mit
62d71f381995ca82ef7078a4df6745fe
34.112069
93
0.648907
4.803066
false
false
false
false
weibaohui/korm
src/main/kotlin/com/sdibt/korm/core/oql/OQL3.kt
1
2019
/* * 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.sdibt.korm.core.oql class OQL3(private val currentOQL: OQL) : OQL4(currentOQL), IOQL3 { override fun <T> Having(field: T, Value: T, sqlFunctionFormat: String): OQL4 { if (sqlFunctionFormat.isNullOrBlank()) { throw Exception("SQL 格式函数不能为空!") } if (sqlFunctionFormat.contains("--") || sqlFunctionFormat.contains("\'")) { throw IllegalArgumentException("SQL 格式函数不合法!") } if (sqlFunctionFormat.contains("%1\$s") && sqlFunctionFormat.contains("%2\$s")) { val tnf = currentOQL.takeOneStackFields() val fieldName = tnf.field val paraName = currentOQL.createParameter(tnf) val havingString = String.format(sqlFunctionFormat, fieldName, paraName) currentOQL.oqlString += "\r\n HAVING " + havingString return OQL4(currentOQL) } throw IllegalArgumentException("SQL 格式函数要求类似这样的格式:SUM(%1\$s) > %2\$s") } fun Having(block: (r: OQLCompare) -> OQLCompare): OQL4 { val compare = OQLCompare(this.currentOQL) val cmpResult = block(compare) if (cmpResult != null) { currentOQL.oqlString += "\r\n HAVING " + cmpResult.compareString } return OQL4(currentOQL) } }
apache-2.0
c634a11dc615dd84adf4001cdbde17c6
37.333333
83
0.711509
3.388215
false
false
false
false
gameover-fwk/gameover-fwk
src/main/kotlin/gameover/fwk/libgdx/gfx/GeometryUtils.kt
1
3416
package gameover.fwk.libgdx.gfx import com.badlogic.gdx.math.Rectangle import com.badlogic.gdx.math.Vector2 import gameover.fwk.math.MathUtils import gameover.fwk.pool.Vector2Pool object GeometryUtils { fun computeTiledIntersectionPoints(x1: Float, y1: Float, x2: Float, y2: Float): List<Vector2> { val ret = arrayListOf<Vector2>() val diffX = x2 - x1 val fX1 = MathUtils.floor(x1) val diffY = y2 - y1 val fY1 = MathUtils.floor(y1) val alpha = com.badlogic.gdx.math.MathUtils.atan2(diffY, diffX) val angle = Math.abs(alpha % (Math.PI / 2.0)) val inverseAxis = alpha > Math.PI / 2.0 || alpha < -Math.PI / 2.0 val alphaTan = Math.tan(angle).toFloat() val xSign: Float = Math.signum(diffX) val ySign: Float = Math.signum(diffY) val xs = arrayListOf<Float>() val ys = arrayListOf<Float>() var finished = false while (!finished) { val x: Float = if (xSign < 0f) fX1 - (if (fX1 == x1) 1 else 0) - xs.size else fX1 + 1 + xs.size if ((xSign > 0 && x >= x2) || (xSign < 0 && x <= x2) || xSign == 0f) finished = true else xs.add(x) } finished = false while (!finished) { val y: Float = if (ySign < 0f) fY1 - (if (fY1 == y1) 1 else 0) - ys.size else fY1 + 1 + ys.size if ((ySign > 0 && y >= y2) || (ySign < 0 && y <= y2) || ySign == 0f) finished = true else ys.add(y) } for (x in xs) { if (!inverseAxis) ret.add(Vector2Pool.obtain(x, computeYAux(x1, y1, x, ySign, alphaTan))) else ret.add(Vector2Pool.obtain(x, computeXAux(y1, x1, x, ySign, alphaTan))) } for (y in ys) { if (!inverseAxis) ret.add(Vector2Pool.obtain(computeXAux(x1, y1, y, xSign, alphaTan), y)) else ret.add(Vector2Pool.obtain(computeYAux(y1, x1, y, xSign, alphaTan), y)) } ret.sortWith(Function2DPointComparator(xSign, ySign)) var i = ret.size - 2 while ((i >= 0) && (i + 1 < ret.size)) { if (ret.get(i).equals(ret.get(i + 1))) ret.removeAt(i) else i -= 1 } return ret } fun computeYAux(x1: Float, y1: Float, x2: Float, ySign: Float, alphaTan: Float) = y1 + ySign * (alphaTan * Math.abs(x2 - x1)) fun computeXAux(x1: Float, y1: Float, y2: Float, xSign: Float, alphaTan: Float) = x1 + (if (alphaTan != 0f) xSign * (Math.abs(y2 - y1) / alphaTan) else 0f) fun centerAndEdges(area: Rectangle): List<Vector2> = arrayListOf( area.getCenter(Vector2Pool.obtain()), area.getPosition(Vector2Pool.obtain()), area.getPosition(Vector2Pool.obtain()).add(area.width, 0f), area.getPosition(Vector2Pool.obtain()).add(0f, area.height), area.getPosition(Vector2Pool.obtain()).add(area.width, area.height)) } class Function2DPointComparator(val xSign: Float, val ySign: Float) : Comparator<Vector2> { override fun compare(o1: Vector2, o2: Vector2): Int { val signum: Float = Math.signum(o1.x - o2.x) return if (signum == 0f) { (Math.signum(o1.x - o2.x) * ySign).toInt() } else { (signum * xSign).toInt() } } }
mit
d8cb0e0159a4fe3387ad9c9d8f602161
37.818182
159
0.550351
3.222642
false
false
false
false
Vakosta/Chapper
app/src/main/java/org/chapper/chapper/data/model/Chat.kt
1
2038
package org.chapper.chapper.data.model import android.content.Context import android.text.format.DateUtils import com.raizlabs.android.dbflow.annotation.Column import com.raizlabs.android.dbflow.annotation.PrimaryKey import com.raizlabs.android.dbflow.annotation.Table import com.raizlabs.android.dbflow.annotation.Unique import com.raizlabs.android.dbflow.kotlinextensions.* import org.chapper.chapper.R import org.chapper.chapper.data.Constants import org.chapper.chapper.data.database.AppDatabase import org.chapper.chapper.data.repository.MessageRepository import org.chapper.chapper.data.status.MessageStatus import org.chapper.chapper.domain.usecase.DateUseCase import java.text.SimpleDateFormat import java.util.* @Table(database = AppDatabase::class) data class Chat( @PrimaryKey @Unique var id: String = UUID.randomUUID().toString(), @Column var photoId: String = Constants.PHOTO_REQUEST, @Column var firstName: String = "", @Column var lastName: String = "", @Column var username: String = "", @Column var bluetoothMacAddress: String = "", @Column var lastConnection: Date = Date() ) { fun getLastMessage(): Message = MessageRepository.getMessages(id).lastOrNull() ?: Message() fun getNewMessagesNumber(): Int = (select from Message::class where (Message_Table.chatId eq id) and (Message_Table.status eq MessageStatus.INCOMING_UNREAD)) .list.size fun getLastConnectionString(context: Context): String = when { DateUtils.isToday(lastConnection.time) -> "${context.getString(R.string.last_connection_in)} ${SimpleDateFormat("HH:mm").format(lastConnection)}" DateUseCase.isDateInCurrentWeek(lastConnection) -> "${context.getString(R.string.last_connection_in)} ${SimpleDateFormat("EEE").format(lastConnection)}" else -> "${context.getString(R.string.last_connection)} ${SimpleDateFormat("d MMM").format(lastConnection)}" } }
gpl-2.0
eb7783878d8575392f8367906e958f75
35.410714
160
0.716879
4.401728
false
false
false
false
weiweiwitch/third-lab
src/main/kotlin/com/ariane/thirdlab/rtcode/RtCode.kt
1
345
package com.ariane.thirdlab.rtcode const val SUCCESS: Int = 1 const val POST_NOT_FOUND: Int = 10 const val POST_TAG_NOT_FOUND: Int = 20 const val CANT_DEL_PARENT_TAG: Int = 21 // 无法删除拥有子标签的标签 const val CANT_DEL_NO_EMPTY_TAG: Int = 22 // 无法删除非空标签 const val SUMMARY_NOT_FOUND: Int = 30 // 找不到SUMMARY
mit
8e03ecc6a93f28ef54845b0358aa5cb3
32.333333
55
0.732441
2.693694
false
false
false
false
facebook/react-native
packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/PreparePrefabHeadersTaskTest.kt
2
7875
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.tasks.internal import com.facebook.react.tasks.internal.utils.PrefabPreprocessingEntry import com.facebook.react.tests.createProject import com.facebook.react.tests.createTestTask import java.io.* import org.junit.Assert.* import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder class PreparePrefabHeadersTaskTest { @get:Rule val tempFolder = TemporaryFolder() @Test fun preparePrefabHeadersTask_withMissingConfiguration_doesNothing() { val task = createTestTask<PreparePrefabHeadersTask>() task.taskAction() } @Test fun preparePrefabHeadersTask_withSingleEntry_copiesHeaderFile() { val outputDir = tempFolder.newFolder("output") File(tempFolder.root, "input/hello.h").createNewPathAndFile() val project = createProject(projectDir = tempFolder.root) val task = createTestTask<PreparePrefabHeadersTask>(project = project) { it.outputDir.set(outputDir) it.input.set(listOf(PrefabPreprocessingEntry("sample_library", "input/" to ""))) } task.taskAction() assertTrue(File(outputDir, "sample_library/hello.h").exists()) } @Test fun preparePrefabHeadersTask_withSingleEntry_respectsPrefix() { val expectedPrefix = "react/render/something/" val outputDir = tempFolder.newFolder("output") File(tempFolder.root, "input/hello.h").createNewPathAndFile() val project = createProject(projectDir = tempFolder.root) val task = createTestTask<PreparePrefabHeadersTask>(project = project) { it.outputDir.set(outputDir) it.input.set( listOf(PrefabPreprocessingEntry("sample_library", "input/" to expectedPrefix))) } task.taskAction() assertTrue(File(outputDir, "sample_library/${expectedPrefix}hello.h").exists()) } @Test fun preparePrefabHeadersTask_ignoresUnnecessaryFiles() { val expectedPrefix = "react/render/something/" val outputDir = tempFolder.newFolder("output") File(tempFolder.root, "input/hello.hpp").createNewPathAndFile() File(tempFolder.root, "input/hello.cpp").createNewPathAndFile() File(tempFolder.root, "input/CMakeLists.txt").createNewPathAndFile() val project = createProject(projectDir = tempFolder.root) val task = createTestTask<PreparePrefabHeadersTask>(project = project) { it.outputDir.set(outputDir) it.input.set( listOf(PrefabPreprocessingEntry("sample_library", "input/" to expectedPrefix))) } task.taskAction() assertFalse(File(outputDir, "sample_library/hello.hpp").exists()) assertFalse(File(outputDir, "sample_library/hello.cpp").exists()) assertFalse(File(outputDir, "sample_library/CMakeLists.txt").exists()) } @Test fun preparePrefabHeadersTask_withMultiplePaths_copiesHeaderFiles() { val outputDir = tempFolder.newFolder("output") File(tempFolder.root, "input/component1/hello1.h").createNewPathAndFile() File(tempFolder.root, "input/component2/debug/hello2.h").createNewPathAndFile() val project = createProject(projectDir = tempFolder.root) val task = createTestTask<PreparePrefabHeadersTask>(project = project) { it.outputDir.set(outputDir) it.input.set( listOf( PrefabPreprocessingEntry( "sample_library", listOf("input/component1/" to "", "input/component2/" to "")), )) } task.taskAction() assertTrue(File(outputDir, "sample_library/hello1.h").exists()) assertTrue(File(outputDir, "sample_library/debug/hello2.h").exists()) } @Test fun preparePrefabHeadersTask_withMultipleEntries_copiesHeaderFiles() { val outputDir = tempFolder.newFolder("output") File(tempFolder.root, "input/lib1/hello1.h").createNewPathAndFile() File(tempFolder.root, "input/lib2/hello2.h").createNewPathAndFile() val project = createProject(projectDir = tempFolder.root) val task = createTestTask<PreparePrefabHeadersTask>(project = project) { it.outputDir.set(outputDir) it.input.set( listOf( PrefabPreprocessingEntry("libraryone", "input/lib1/" to ""), PrefabPreprocessingEntry("librarytwo", "input/lib2/" to ""))) } task.taskAction() assertTrue(File(outputDir, "libraryone/hello1.h").exists()) assertTrue(File(outputDir, "librarytwo/hello2.h").exists()) } @Test fun preparePrefabHeadersTask_withReusedHeaders_copiesHeadersTwice() { val outputDir = tempFolder.newFolder("output") File(tempFolder.root, "input/lib1/hello1.h").createNewPathAndFile() File(tempFolder.root, "input/lib2/hello2.h").createNewPathAndFile() File(tempFolder.root, "input/shared/sharedheader.h").createNewPathAndFile() val project = createProject(projectDir = tempFolder.root) val task = createTestTask<PreparePrefabHeadersTask>(project = project) { it.outputDir.set(outputDir) it.input.set( listOf( PrefabPreprocessingEntry( "libraryone", listOf("input/lib1/" to "", "input/shared/" to "shared/")), PrefabPreprocessingEntry( "librarytwo", listOf("input/lib2/" to "", "input/shared/" to "shared/")), )) } task.taskAction() assertTrue(File(outputDir, "libraryone/hello1.h").exists()) assertTrue(File(outputDir, "libraryone/shared/sharedheader.h").exists()) assertTrue(File(outputDir, "librarytwo/hello2.h").exists()) assertTrue(File(outputDir, "librarytwo/shared/sharedheader.h").exists()) } @Test fun preparePrefabHeadersTask_withBoostHeaders_filtersThemCorrectly() { val outputDir = tempFolder.newFolder("output") File(tempFolder.root, "boost/boost/config.hpp").createNewPathAndFile() File(tempFolder.root, "boost/boost/operators.hpp").createNewPathAndFile() File(tempFolder.root, "boost/boost/config/default/default.hpp").createNewPathAndFile() File(tempFolder.root, "boost/boost/core/core.hpp").createNewPathAndFile() File(tempFolder.root, "boost/boost/detail/workaround.hpp").createNewPathAndFile() File(tempFolder.root, "boost/boost/preprocessor/preprocessor.hpp").createNewPathAndFile() File(tempFolder.root, "boost/boost/preprocessor/detail/preprocessor_detail.hpp") .createNewPathAndFile() File(tempFolder.root, "boost/boost/anothermodule/wedontuse.hpp").createNewPathAndFile() val project = createProject(projectDir = tempFolder.root) val task = createTestTask<PreparePrefabHeadersTask>(project = project) { it.outputDir.set(outputDir) it.input.set(listOf(PrefabPreprocessingEntry("sample_library", "boost/" to ""))) } task.taskAction() assertTrue(File(outputDir, "sample_library/boost/config.hpp").exists()) assertTrue(File(outputDir, "sample_library/boost/operators.hpp").exists()) assertTrue(File(outputDir, "sample_library/boost/config/default/default.hpp").exists()) assertTrue(File(outputDir, "sample_library/boost/core/core.hpp").exists()) assertTrue(File(outputDir, "sample_library/boost/detail/workaround.hpp").exists()) assertTrue(File(outputDir, "sample_library/boost/preprocessor/preprocessor.hpp").exists()) assertTrue( File(outputDir, "sample_library/boost/preprocessor/detail/preprocessor_detail.hpp") .exists()) assertFalse(File(outputDir, "sample_library/boost/anothermodule/wedontuse.hpp").exists()) } private fun File.createNewPathAndFile() { parentFile.mkdirs() createNewFile() } }
mit
4be351f5dc5f3b2504be4150f8fe9cf9
38.179104
95
0.697651
4.118724
false
true
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/cardviewer/OnRenderProcessGoneDelegate.kt
1
7851
/* * Copyright (c) 2021 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki.cardviewer import android.annotation.TargetApi import android.os.Build import android.webkit.RenderProcessGoneDetail import android.webkit.WebView import androidx.annotation.RequiresApi import androidx.lifecycle.Lifecycle import com.afollestad.materialdialogs.MaterialDialog import com.ichi2.anki.AbstractFlashcardViewer import com.ichi2.anki.R import com.ichi2.anki.UIUtils.showThemedToast import com.ichi2.libanki.CardId import timber.log.Timber /** * Fix for: * #5780 - WebView Renderer OOM crashes reviewer * #8459 - WebView Renderer crash dialog displays when app is minimised (Android 11 - Google Pixel 3A) */ open class OnRenderProcessGoneDelegate(val target: AbstractFlashcardViewer) { lateinit var lifecycle: Lifecycle /** * Last card that the WebView Renderer crashed on. * If we get 2 crashes on the same card, then we likely have an infinite loop and want to exit gracefully. */ private var mLastCrashingCardId: CardId? = null /** Fix: #5780 - WebView Renderer OOM crashes reviewer */ @RequiresApi(api = Build.VERSION_CODES.O) fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean { Timber.i("Obtaining write lock for card") val writeLock = target.writeLock val cardWebView = target.webView Timber.i("Obtained write lock for card") try { writeLock.lock() if (cardWebView == null || cardWebView != view) { // A view crashed that wasn't ours. // We have nothing to handle. Returning false is a desire to crash, so return true. Timber.i("Unrelated WebView Renderer terminated. Crashed: %b", detail.didCrash()) return true } Timber.e("WebView Renderer process terminated. Crashed: %b", detail.didCrash()) target.destroyWebViewFrame() // Only show one message per branch when { !canRecoverFromWebViewRendererCrash() -> { Timber.e("Unrecoverable WebView Render crash") if (!activityIsMinimised()) displayFatalError(detail) target.finishWithoutAnimation() return true } !activityIsMinimised() -> { // #8459 - if the activity is minimised, this is much more likely to happen multiple times and it is // likely not a permanent error due to a bad card, so don't increment mLastCrashingCardId val currentCardId = target.currentCard!!.id if (webViewRendererLastCrashedOnCard(currentCardId)) { Timber.e("Web Renderer crash loop on card: %d", currentCardId) displayRenderLoopDialog(currentCardId, detail) return true } // This logic may need to be better defined. The card could have changed by the time we get here. mLastCrashingCardId = currentCardId displayNonFatalError(detail) } else -> Timber.d("WebView crashed while app was minimised - OOM was safe to handle silently") } // If we get here, the error is non-fatal and we should re-render the WebView target.recreateWebViewFrame() } finally { writeLock.unlock() Timber.d("Relinquished writeLock") } target.displayCardQuestion() // We handled the crash and can continue. return true } @RequiresApi(Build.VERSION_CODES.O) protected open fun displayFatalError(detail: RenderProcessGoneDetail) { if (activityIsMinimised()) { Timber.d("Not showing toast - screen isn't visible") return } val errorMessage = target.resources.getString(R.string.webview_crash_fatal, getErrorCause(detail)) showThemedToast(target, errorMessage, false) } @RequiresApi(Build.VERSION_CODES.O) protected open fun displayNonFatalError(detail: RenderProcessGoneDetail) { if (activityIsMinimised()) { Timber.d("Not showing toast - screen isn't visible") return } val nonFatalError = target.resources.getString(R.string.webview_crash_nonfatal, getErrorCause(detail)) showThemedToast(target, nonFatalError, false) } @RequiresApi(Build.VERSION_CODES.O) protected fun getErrorCause(detail: RenderProcessGoneDetail): String { // It's not necessarily an OOM crash, false implies a general code which is for "system terminated". val errorCauseId = if (detail.didCrash()) R.string.webview_crash_unknown else R.string.webview_crash_oom return target.resources.getString(errorCauseId) } @TargetApi(Build.VERSION_CODES.O) protected open fun displayRenderLoopDialog(currentCardId: CardId, detail: RenderProcessGoneDetail) { val cardInformation = java.lang.Long.toString(currentCardId) val res = target.resources val errorDetails = if (detail.didCrash()) res.getString(R.string.webview_crash_unknwon_detailed) else res.getString(R.string.webview_crash_oom_details) MaterialDialog(target).show { title(R.string.webview_crash_loop_dialog_title) message(text = res.getString(R.string.webview_crash_loop_dialog_content, cardInformation, errorDetails)) positiveButton(R.string.dialog_ok) { onCloseRenderLoopDialog() } cancelable(false) cancelOnTouchOutside(false) } } /** * Issue 8459 * On Android 11, the WebView regularly OOMs even after .onStop() has been called, * but this does not cause .onDestroy() to be called * * We do not want to show toasts or increment the "crash" counter if this occurs. Just handle the issue */ private fun activityIsMinimised(): Boolean { // See diagram on https://developer.android.com/topic/libraries/architecture/lifecycle#lc // STARTED is after .start(), the activity goes to CREATED after .onStop() lifecycle = target.lifecycle return !lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED) } private fun webViewRendererLastCrashedOnCard(cardId: CardId): Boolean = mLastCrashingCardId != null && mLastCrashingCardId == cardId private fun canRecoverFromWebViewRendererCrash(): Boolean = // DEFECT // If we don't have a card to render, we're in a bad state. The class doesn't currently track state // well enough to be able to know exactly where we are in the initialisation pipeline. // so it's best to mark the crash as non-recoverable. // We should fix this, but it's very unlikely that we'll ever get here. Logs will tell // Revisit webViewCrashedOnCard() if changing this. Logic currently assumes we have a card. target.currentCard != null protected fun onCloseRenderLoopDialog() = target.finishWithoutAnimation() }
gpl-3.0
da120efe07098699660cd1cfaded58e4
44.912281
159
0.664374
4.593915
false
false
false
false
tipsy/javalin
javalin/src/main/java/io/javalin/http/Context.kt
1
19801
/* * Javalin - https://javalin.io * Copyright 2017 David Åse * Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE */ package io.javalin.http import io.javalin.core.security.BasicAuthCredentials import io.javalin.core.util.Header import io.javalin.core.validation.BodyValidator import io.javalin.core.validation.Validator import io.javalin.http.util.ContextUtil import io.javalin.http.util.ContextUtil.throwPayloadTooLargeIfPayloadTooLarge import io.javalin.http.util.CookieStore import io.javalin.http.util.MultipartUtil import io.javalin.http.util.SeekableWriter import io.javalin.plugin.json.jsonMapper import io.javalin.plugin.rendering.JavalinRenderer import java.io.InputStream import java.nio.charset.Charset import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.atomic.AtomicReference import java.util.function.Consumer import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse /** * Provides access to functions for handling the request and response * * @see <a href="https://javalin.io/documentation#context">Context in docs</a> */ // don't suppress warnings, since annotated classes are ignored by dokka (yeah...) open class Context(@JvmField val req: HttpServletRequest, @JvmField val res: HttpServletResponse, internal val appAttributes: Map<String, Any> = mapOf()) { // @formatter:off @get:JvmSynthetic @set:JvmSynthetic internal var matchedPath = "" @get:JvmSynthetic @set:JvmSynthetic internal var endpointHandlerPath = "" @get:JvmSynthetic @set:JvmSynthetic internal var pathParamMap = mapOf<String, String>() @get:JvmSynthetic @set:JvmSynthetic internal var handlerType = HandlerType.BEFORE @get:JvmSynthetic @set:JvmSynthetic internal var resultReference = AtomicReference(Result()) // @formatter:on private val cookieStore by lazy { CookieStore(this.jsonMapper(), cookie(CookieStore.COOKIE_NAME)) } private val characterEncoding by lazy { ContextUtil.getRequestCharset(this) ?: "UTF-8" } private val body by lazy { this.throwPayloadTooLargeIfPayloadTooLarge() req.inputStream.readBytes() } /** Gets the handler type of the current handler */ fun handlerType(): HandlerType = handlerType /** Gets an attribute from the Javalin instance serving the request */ fun <T> appAttribute(key: String): T = appAttributes[key] as T /** * Gets cookie store value for specified key. * @see <a href="https://javalin.io/documentation#cookie-store">Cookie store in docs</a> */ fun <T> cookieStore(key: String): T = cookieStore[key] /** * Sets cookie store value for specified key. * Values are made available for other handlers, requests, and servers. * @see <a href="https://javalin.io/documentation#cookie-store">Cookie store in docs</a> */ fun cookieStore(key: String, value: Any) { cookieStore[key] = value cookie(cookieStore.serializeToCookie()) } /** * Clears cookie store in the context and from the response. * @see <a href="https://javalin.io/documentation#cookie-store">Cookie store in docs</a> */ fun clearCookieStore() { cookieStore.clear() removeCookie(CookieStore.COOKIE_NAME) } /** * Gets the path that was used to match request (also includes before/after paths) */ fun matchedPath() = matchedPath /** * Gets the endpoint path that was used to match request (null in before, available in endpoint/after) */ fun endpointHandlerPath() = if (handlerType != HandlerType.BEFORE) { endpointHandlerPath } else { throw IllegalStateException("Cannot access the endpoint handler path in a 'BEFORE' handler") } /////////////////////////////////////////////////////////////// // Request-ish methods /////////////////////////////////////////////////////////////// /** Gets the request body as a [String]. */ fun body(): String = bodyAsBytes().toString(Charset.forName(characterEncoding)) /** Gets the request body as a [ByteArray]. * Calling this method returns the body as a [ByteArray]. If [io.javalin.core.JavalinConfig.maxRequestSize] * is set and body is bigger than its value, a [io.javalin.http.HttpResponseException] is throw, * with status 413 PAYLOAD_TOO_LARGE. */ fun bodyAsBytes(): ByteArray = body /** Maps a JSON body to a Java/Kotlin class using the registered [io.javalin.plugin.json.JsonMapper] */ fun <T> bodyAsClass(clazz: Class<T>): T = jsonMapper().fromJsonString(body(), clazz) /** Reified version of [bodyAsClass] (Kotlin only) */ inline fun <reified T : Any> bodyAsClass(): T = bodyAsClass(T::class.java) /** Maps a JSON body to a Java/Kotlin class using the registered [io.javalin.plugin.json.JsonMapper] */ fun <T> bodyStreamAsClass(clazz: Class<T>): T = jsonMapper().fromJsonStream(req.inputStream, clazz) /** Reified version of [bodyStreamAsClass] (Kotlin only) */ inline fun <reified T : Any> bodyStreamAsClass(): T = bodyStreamAsClass(T::class.java) /** Gets the request body as a [InputStream] */ fun bodyAsInputStream(): InputStream = req.inputStream /** Creates a typed [BodyValidator] for the body() value */ fun <T> bodyValidator(clazz: Class<T>) = BodyValidator(body(), clazz, this.jsonMapper()) /** Reified version of [bodyValidator] (Kotlin only) */ inline fun <reified T : Any> bodyValidator() = bodyValidator(T::class.java) /** Gets first [UploadedFile] for the specified name, or null. */ fun uploadedFile(fileName: String): UploadedFile? = uploadedFiles(fileName).firstOrNull() /** Gets a list of [UploadedFile]s for the specified name, or empty list. */ fun uploadedFiles(fileName: String): List<UploadedFile> { return if (isMultipartFormData()) MultipartUtil.getUploadedFiles(req, fileName) else listOf() } /** Gets a list of [UploadedFile]s, or empty list. */ fun uploadedFiles(): List<UploadedFile> { return if (isMultipartFormData()) MultipartUtil.getUploadedFiles(req) else listOf() } /** Gets a form param if it exists, else null */ fun formParam(key: String): String? = formParams(key).firstOrNull() /** Creates a typed [Validator] for the formParam() value */ fun <T> formParamAsClass(key: String, clazz: Class<T>) = Validator.create(clazz, formParam(key), key) /** Reified version of [formParamAsClass] (Kotlin only) */ inline fun <reified T : Any> formParamAsClass(key: String) = formParamAsClass(key, T::class.java) /** Gets a list of form params for the specified key, or empty list. */ fun formParams(key: String): List<String> = formParamMap()[key] ?: emptyList() /** using an additional map lazily so no new objects are created whenever ctx.formParam*() is called */ private val formParams by lazy { if (isMultipartFormData()) MultipartUtil.getFieldMap(req) else ContextUtil.splitKeyValueStringAndGroupByKey(body(), characterEncoding) } /** Gets a map with all the form param keys and values. */ fun formParamMap(): Map<String, List<String>> = formParams /** * Gets a path param by name (ex: pathParam("param"). * * Ex: If the handler path is /users/{user-id}, * and a browser GETs /users/123, * pathParam("user-id") will return "123" */ fun pathParam(key: String): String = ContextUtil.pathParamOrThrow(pathParamMap, key, matchedPath) /** Creates a typed [Validator] for the pathParam() value */ fun <T> pathParamAsClass(key: String, clazz: Class<T>) = Validator.create(clazz, pathParam(key), key) /** Reified version of [pathParamAsClass] (Kotlin only) */ inline fun <reified T : Any> pathParamAsClass(key: String) = pathParamAsClass(key, T::class.java) /** Gets a map of all the [pathParamAsClass] keys and values. */ fun pathParamMap(): Map<String, String> = Collections.unmodifiableMap(pathParamMap) /** * Checks whether or not basic-auth credentials from the request exists. * * Returns a Boolean which is true if there is an Authorization header with * Basic auth credentials. Returns false otherwise. */ fun basicAuthCredentialsExist(): Boolean = ContextUtil.hasBasicAuthCredentials(header(Header.AUTHORIZATION)) /** * Gets basic-auth credentials from the request, or throws. * * Returns a wrapper object [BasicAuthCredentials] which contains the * Base64 decoded username and password from the Authorization header. */ fun basicAuthCredentials(): BasicAuthCredentials = ContextUtil.getBasicAuthCredentials(header(Header.AUTHORIZATION)) /** Sets an attribute on the request. Attributes are available to other handlers in the request lifecycle */ fun attribute(key: String, value: Any?) = req.setAttribute(key, value) /** Gets the specified attribute from the request. */ fun <T> attribute(key: String): T? = req.getAttribute(key) as? T /** Gets a map with all the attribute keys and values on the request. */ fun attributeMap(): Map<String, Any?> = req.attributeNames.asSequence().associateWith { attribute(it) as Any? } /** Gets the request content length. */ fun contentLength(): Int = req.contentLength /** Gets the request content type, or null. */ fun contentType(): String? = req.contentType /** Gets a request cookie by name, or null. */ fun cookie(name: String): String? = req.cookies?.find { name == it.name }?.value /** Gets a map with all the cookie keys and values on the request. */ fun cookieMap(): Map<String, String> = req.cookies?.associate { it.name to it.value } ?: emptyMap() /** Gets a request header by name, or null. */ fun header(header: String): String? = req.getHeader(header) /** Creates a typed [Validator] for the header() value */ fun <T> headerAsClass(header: String, clazz: Class<T>): Validator<T> = Validator.create(clazz, header(header), header) /** Reified version of [headerAsClass] (Kotlin only) */ inline fun <reified T : Any> headerAsClass(header: String) = headerAsClass(header, T::class.java) /** Gets a map with all the header keys and values on the request. */ fun headerMap(): Map<String, String> = req.headerNames.asSequence().associateWith { header(it)!! } /** Gets the request host, or null. */ fun host(): String? = contextResolver().host.invoke(this) /** Gets the request ip. */ fun ip(): String = contextResolver().ip.invoke(this) /** Returns true if request is multipart. */ fun isMultipart(): Boolean = header(Header.CONTENT_TYPE)?.lowercase(Locale.ROOT)?.contains("multipart/") == true /** Returns true if request is multipart/form-data. */ fun isMultipartFormData(): Boolean = header(Header.CONTENT_TYPE)?.lowercase(Locale.ROOT)?.contains("multipart/form-data") == true /** Gets the request method. */ fun method(): String = req.method /** Gets the request path. */ fun path(): String = req.requestURI /** Gets the request port. */ fun port(): Int = req.serverPort /** Gets the request protocol. */ fun protocol(): String = req.protocol /** Gets a query param if it exists, else null */ fun queryParam(key: String): String? = queryParams(key).firstOrNull() /** Creates a typed [Validator] for the queryParam() value */ fun <T> queryParamAsClass(key: String, clazz: Class<T>) = Validator.create(clazz, queryParam(key), key) /** Reified version of [queryParamAsClass] (Kotlin only) */ inline fun <reified T : Any> queryParamAsClass(key: String) = queryParamAsClass(key, T::class.java) /** Gets a list of query params for the specified key, or empty list. */ fun queryParams(key: String): List<String> = queryParamMap()[key] ?: emptyList() /** using an additional map lazily so no new objects are created whenever ctx.formParam*() is called */ private val queryParams by lazy { ContextUtil.splitKeyValueStringAndGroupByKey(queryString() ?: "", characterEncoding) } /** Gets a map with all the query param keys and values. */ fun queryParamMap(): Map<String, List<String>> = queryParams /** Gets the request query string, or null. */ fun queryString(): String? = req.queryString /** Gets the request scheme. */ fun scheme(): String = contextResolver().scheme.invoke(this) /** Sets an attribute for the user session. */ fun sessionAttribute(key: String, value: Any?) = req.session.setAttribute(key, value) /** Gets specified attribute from the user session, or null. */ fun <T> sessionAttribute(key: String): T? = req.getSession(false)?.getAttribute(key) as? T fun <T> consumeSessionAttribute(key: String) = sessionAttribute<T?>(key).also { this.sessionAttribute(key, null) } /** Sets an attribute for the user session, and caches it on the request */ fun cachedSessionAttribute(key: String, value: Any?) = ContextUtil.cacheAndSetSessionAttribute(key, value, req) /** Gets specified attribute from the request attribute cache, or the user session, or null. */ fun <T> cachedSessionAttribute(key: String): T? = ContextUtil.getCachedRequestAttributeOrSessionAttribute(key, req) /** Gets specified attribute from the request attribute cache, or the user session, or computes the value from callback. */ fun <T> cachedSessionAttributeOrCompute(key: String, callback: (Context) -> T): T? = ContextUtil.cachedSessionAttributeOrCompute(callback, key, this) /** Gets a map of all the attributes in the user session. */ fun sessionAttributeMap(): Map<String, Any?> = req.session.attributeNames.asSequence().associateWith { sessionAttribute(it) } /** Gets the request url. */ fun url(): String = contextResolver().url.invoke(this) /** Gets the full request url, including query string (if present) */ fun fullUrl(): String = contextResolver().fullUrl.invoke(this) /** Gets the request context path. */ fun contextPath(): String = req.contextPath /** Gets the request user agent, or null. */ fun userAgent(): String? = req.getHeader(Header.USER_AGENT) /////////////////////////////////////////////////////////////// // Response-ish methods /////////////////////////////////////////////////////////////// /** Gets the current response [Charset]. */ private fun responseCharset() = try { Charset.forName(res.characterEncoding) } catch (e: Exception) { Charset.defaultCharset() } /** * Sets context result to the specified [String]. * Will overwrite the current result if there is one. */ fun result(resultString: String) = result(resultString.byteInputStream(responseCharset())) /** * Sets context result to the specified array of bytes. * Will overwrite the current result if there is one. */ fun result(resultBytes: ByteArray) = result(resultBytes.inputStream()) /** Gets the current [resultReference] as a [String] (if possible), and reset the underlying stream */ fun resultString() = ContextUtil.readAndResetStreamIfPossible(resultStream(), responseCharset()) /** * Sets context result to the specified [InputStream]. * Will overwrite the current result if there is one. */ fun result(resultStream: InputStream): Context { runCatching { resultStream()?.close() } // avoid memory leaks for multiple result() calls return this.future(CompletableFuture.completedFuture(resultStream)) } /** Writes the specified inputStream as a seekable stream */ @JvmOverloads fun seekableStream(inputStream: InputStream, contentType: String, size: Long = inputStream.available().toLong()) = SeekableWriter.write(this, inputStream, contentType, size) fun resultStream(): InputStream? = resultReference.get().let { result -> result.future.takeIf { it.isDone }?.get() as InputStream? ?: result.previous } /** The default callback (used if no callback is provided) can be configured through [ContextResolver.defaultFutureCallback] */ @JvmOverloads fun future(future: CompletableFuture<*>, callback: Consumer<Any?>? = null): Context { resultReference.updateAndGet { oldResult -> oldResult.future.cancel(true) Result(oldResult.previous, future, callback) } return this } /** Gets the current context result as a [CompletableFuture] (if set). */ fun resultFuture(): CompletableFuture<*>? = resultReference.get().future /** Sets response content type to specified [String] value. */ fun contentType(contentType: String): Context { res.contentType = contentType return this } /** Sets response content type to specified [ContentType] value. */ fun contentType(contentType: ContentType): Context = contentType(contentType.mimeType) /** Sets response header by name and value. */ fun header(name: String, value: String): Context { res.setHeader(name, value) return this } /** Sets the response status code and redirects to the specified location. */ @JvmOverloads fun redirect(location: String, httpStatusCode: Int = HttpServletResponse.SC_MOVED_TEMPORARILY) { res.setHeader(Header.LOCATION, location) status(httpStatusCode) if (handlerType == HandlerType.BEFORE) { throw RedirectResponse(httpStatusCode) } } /** Sets the response status. */ fun status(httpCode: HttpCode): Context = status(httpCode.status) /** Sets the response status. */ fun status(statusCode: Int): Context { res.status = statusCode return this } /** Gets the response status. */ fun status(): Int = res.status /** Sets a cookie with name, value, and (overloaded) max-age. */ @JvmOverloads fun cookie(name: String, value: String, maxAge: Int = -1) = cookie(Cookie(name = name, value = value, maxAge = maxAge)) /** Sets a Cookie. */ fun cookie(cookie: Cookie): Context { res.setJavalinCookie(cookie) return this } /** Removes cookie specified by name and path (optional). */ @JvmOverloads fun removeCookie(name: String, path: String? = "/"): Context { res.addCookie(javax.servlet.http.Cookie(name, "").apply { this.path = path this.maxAge = 0 }) return this } /** Sets context result to specified html string and sets content-type to text/html. */ fun html(html: String): Context = contentType(ContentType.TEXT_HTML).result(html) /** * Serializes object to a JSON-string using the registered [io.javalin.plugin.json.JsonMapper] and sets it as the context result. * Also sets content type to application/json. */ fun json(obj: Any): Context = contentType(ContentType.APPLICATION_JSON).result(jsonMapper().toJsonString(obj)) /** * Serializes object to a JSON-stream using the registered [io.javalin.plugin.json.JsonMapper] and sets it as the context result. * Also sets content type to application/json. */ fun jsonStream(obj: Any): Context = contentType(ContentType.APPLICATION_JSON).result(jsonMapper().toJsonStream(obj)) /** * Renders a file with specified values and sets it as the context result. * Also sets content-type to text/html. * Determines the correct rendering-function based on the file extension. */ @JvmOverloads fun render(filePath: String, model: Map<String, Any?> = mutableMapOf()): Context { return html(JavalinRenderer.renderBasedOnExtension(filePath, model, this)) } }
apache-2.0
a40a1c0000244b9bb75d81045515328f
42.326039
155
0.679545
4.372792
false
false
false
false
burkov/gzip_streamer
src/main/kotlin/com/github/burkov/nginx/gzip_streamer/DevRandomServer.kt
1
2858
package com.github.burkov.nginx.gzip_streamer import io.netty.bootstrap.ServerBootstrap import io.netty.channel.* import io.netty.channel.ChannelFutureListener.CLOSE import io.netty.channel.nio.NioEventLoopGroup import io.netty.channel.socket.SocketChannel import io.netty.channel.socket.nio.NioServerSocketChannel import io.netty.handler.codec.http.* import io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST import io.netty.handler.codec.http.HttpResponseStatus.OK import io.netty.handler.codec.http.HttpVersion.HTTP_1_1 import io.netty.handler.stream.ChunkedStream import io.netty.handler.stream.ChunkedWriteHandler import sun.rmi.transport.Channel import java.io.BufferedInputStream import java.io.FileInputStream class DevRandomServerHandler() : SimpleChannelInboundHandler<FullHttpRequest>() { private val chunkSize = 4096 override fun channelRead0(ctx: ChannelHandlerContext?, msg: FullHttpRequest?) { if (msg == null || ctx == null) throw IllegalArgumentException("ctx and msg required") if (!msg.decoderResult.isSuccess) { ctx.writeAndFlush(DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)).addListener(CLOSE) return } val resp = DefaultHttpResponse(HTTP_1_1, OK) resp.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/octet-stream") resp.headers().set(HttpHeaders.Names.TRANSFER_ENCODING, "chunked") ctx.write(resp) ctx.write(ChunkedStream(BufferedInputStream(FileInputStream("/dev/urandom")), chunkSize)) ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(CLOSE) } } class DevRandomServer() { private val channelInitializer = object : ChannelInitializer<SocketChannel>() { override fun initChannel(ch: SocketChannel?) { ch!!.pipeline().run { addLast(HttpRequestDecoder()) addLast(HttpObjectAggregator(65536)) addLast(HttpResponseEncoder()) addLast(ChunkedWriteHandler()) addLast(DevRandomServerHandler()) } } } private val parentGroup = NioEventLoopGroup() private val workerGroup = NioEventLoopGroup() fun shutdown() { workerGroup.shutdownGracefully() parentGroup.shutdownGracefully() } fun waitBind(port: Int = 8081): ChannelFuture { try { return ServerBootstrap().run { group(parentGroup, workerGroup) channel(NioServerSocketChannel::class.java) childHandler(channelInitializer) option(ChannelOption.SO_BACKLOG, 128) childOption(ChannelOption.SO_KEEPALIVE, true) bind(port).sync() } } catch(e: Exception) { e.printStackTrace() shutdown() throw e } } }
apache-2.0
e6f1da7e541dbfda7ae7511ab58938aa
38.150685
97
0.681246
4.708402
false
false
false
false
Finnerale/FileBase
src/main/kotlin/de/leopoldluley/filebase/controller/IconCtrl.kt
1
2096
package de.leopoldluley.filebase.controller import de.leopoldluley.filebase.Extensions.toFXImage import de.leopoldluley.filebase.Utils import de.leopoldluley.filebase.models.Entry import de.leopoldluley.filebase.models.FileType import javafx.scene.image.Image import tornadofx.* import java.io.File class IconCtrl : Controller() { private val fileCtrl: FileCtrl by inject() private val cache = mutableMapOf<String, Image>() private val common = mapOf( FileType.Other to img("/icon/common/Other.png"), FileType.Image to img("/icon/common/Image.png"), FileType.Video to img("/icon/common/Video.png"), FileType.Audio to img("/icon/common/Audio.png"), FileType.Document to img("/icon/common/Document.png"), FileType.Text to img("/icon/common/Text.png"), FileType.Application to img("/icon/common/Application.png"), FileType.Folder to img("/icon/common/Folder.png") ) private val nativeIcons: Boolean init { val test = sun.awt.shell.ShellFolder.getShellFolder(File(System.getProperty("user.home"))).getIcon(true) nativeIcons = test != null } fun getIcon(entry: Entry) = if (nativeIcons) getNativeIcon(entry) else getCommonIcon(entry) private fun getNativeIcon(entry: Entry): Image { val path = fileCtrl.getPathFor(entry) val extension = Utils.getFileExtension(path) if (cache.contains(extension)) { return cache[extension]!! } else { val img = sun.awt.shell.ShellFolder.getShellFolder(path.toFile()).getIcon(true) val image = img?.toFXImage() if (image != null) { cache.put(extension, image) return image } else { return getCommonIcon(entry) } } } private fun getCommonIcon(entry: Entry): Image { return common[entry.type]!! } private fun img(path: String): Image = Image(resources.stream(path)) }
mit
405b3449b94744fce77f723379982e9b
35.789474
112
0.623092
4.268839
false
false
false
false
faceofcat/Tesla-Powered-Thingies
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/animalfarm/VanillaLlama.kt
1
914
package net.ndrei.teslapoweredthingies.machines.animalfarm import net.minecraft.entity.passive.EntityLlama import net.minecraft.init.Blocks import net.minecraft.init.Items import net.minecraft.item.Item import net.minecraft.item.ItemStack /** * Created by CF on 2017-07-07. */ class VanillaLlama(llama: EntityLlama) : VanillaGenericAnimal(llama) { override fun isFood(stack: ItemStack): Boolean { return stack.item === Items.WHEAT || stack.item === Item.getItemFromBlock(Blocks.HAY_BLOCK) } override fun getFoodNeededForMating(stack: ItemStack): Int { return if (stack.item === Item.getItemFromBlock(Blocks.HAY_BLOCK)) 1 else 9 // assume wheat } companion object { fun populateFoodItems(food: MutableList<Item>) { food.add(Item.getItemFromBlock(Blocks.HAY_BLOCK)) food.add(Items.WHEAT) } } }
mit
f4c75a6a939f859180a1309cc9de7f14
27.59375
99
0.680525
3.840336
false
false
false
false
jasonwyatt/AsyncListUtil-Example
app/src/main/java/co/jasonwyatt/asynclistutil_example/database.kt
1
1088
package co.jasonwyatt.asynclistutil_example import android.content.Context import android.database.sqlite.SQLiteDatabase import java.io.File import java.io.FileOutputStream import java.io.InputStream private var database: SQLiteDatabase? = null fun getDatabase(c: Context, assetFileName: String): SQLiteDatabase { if (database == null) { val input = c.applicationContext.assets.open(assetFileName) val outfile = File(c.filesDir, assetFileName) if (outfile.exists()) { outfile.delete() } copyToFile(input, outfile) database = SQLiteDatabase.openOrCreateDatabase(outfile, null) } return database!! } private fun copyToFile(inputStream: InputStream, outputFile: File) { val outputStream = FileOutputStream(outputFile) val buffer = ByteArray(1024 * 8) var numOfBytesToRead: Int = inputStream.read(buffer) while (numOfBytesToRead > 0) { outputStream.write(buffer, 0, numOfBytesToRead) numOfBytesToRead = inputStream.read(buffer) } inputStream.close() outputStream.close() }
unlicense
27d6c7d34da27eb62d2662559176d86a
31.029412
69
0.714154
4.25
false
true
false
false
FHannes/intellij-community
platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.kt
7
6775
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.keymap.impl import com.intellij.configurationStore.LazySchemeProcessor import com.intellij.configurationStore.SchemeDataHolder import com.intellij.ide.WelcomeWizardUtil import com.intellij.openapi.Disposable import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManagerListener import com.intellij.openapi.keymap.ex.KeymapManagerEx import com.intellij.openapi.options.SchemeManager import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Conditions import com.intellij.openapi.util.Disposer import com.intellij.ui.AppUIUtil import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.SmartHashSet import gnu.trove.THashMap import org.jdom.Element import java.util.function.Function internal const val KEYMAPS_DIR_PATH = "keymaps" private const val ACTIVE_KEYMAP = "active_keymap" private const val NAME_ATTRIBUTE = "name" @State(name = "KeymapManager", storages = arrayOf(Storage(value = "keymap.xml", roamingType = RoamingType.PER_OS)), additionalExportFile = KEYMAPS_DIR_PATH) class KeymapManagerImpl(defaultKeymap: DefaultKeymap, factory: SchemeManagerFactory) : KeymapManagerEx(), PersistentStateComponent<Element> { private val listeners = ContainerUtil.createLockFreeCopyOnWriteList<KeymapManagerListener>() private val boundShortcuts = THashMap<String, String>() private val schemeManager: SchemeManager<Keymap> init { schemeManager = factory.create(KEYMAPS_DIR_PATH, object : LazySchemeProcessor<Keymap, KeymapImpl>() { override fun createScheme(dataHolder: SchemeDataHolder<KeymapImpl>, name: String, attributeProvider: Function<String, String?>, isBundled: Boolean) = KeymapImpl(name, dataHolder) override fun onCurrentSchemeSwitched(oldScheme: Keymap?, newScheme: Keymap?) { for (listener in listeners) { listener.activeKeymapChanged(newScheme) } } override fun reloaded(schemeManager: SchemeManager<Keymap>) { if (schemeManager.currentScheme == null) { // listeners expect that event will be fired in EDT AppUIUtil.invokeOnEdt { schemeManager.setCurrentSchemeName(defaultKeymap.defaultKeymapName, true) } } } }) val systemDefaultKeymap = if (WelcomeWizardUtil.getWizardMacKeymap() == null) defaultKeymap.defaultKeymapName else WelcomeWizardUtil.getWizardMacKeymap() for (keymap in defaultKeymap.keymaps) { schemeManager.addScheme(keymap) if (keymap.name == systemDefaultKeymap) { activeKeymap = keymap } } schemeManager.loadSchemes() ourKeymapManagerInitialized = true } companion object { @JvmField var ourKeymapManagerInitialized: Boolean = false } override fun getAllKeymaps() = getKeymaps(Conditions.alwaysTrue<Keymap>()).toTypedArray() fun getKeymaps(additionalFilter: Condition<Keymap>) = schemeManager.allSchemes.filter { !it.presentableName.startsWith("$") && additionalFilter.value(it) } override fun getKeymap(name: String) = schemeManager.findSchemeByName(name) override fun getActiveKeymap() = schemeManager.currentScheme override fun setActiveKeymap(keymap: Keymap?) = schemeManager.setCurrent(keymap) override fun bindShortcuts(sourceActionId: String, targetActionId: String) { boundShortcuts.put(targetActionId, sourceActionId) } override fun unbindShortcuts(targetActionId: String) { boundShortcuts.remove(targetActionId) } override fun getBoundActions() = boundShortcuts.keys override fun getActionBinding(actionId: String): String? { var visited: MutableSet<String>? = null var id = actionId while (true) { val next = boundShortcuts.get(id) ?: break if (visited == null) { visited = SmartHashSet() } id = next if (!visited.add(id)) { break } } return if (id == actionId) null else id } override fun getSchemeManager() = schemeManager fun setKeymaps(keymaps: List<Keymap>, active: Keymap?, removeCondition: Condition<Keymap>?) { schemeManager.setSchemes(keymaps, active, removeCondition) } override fun getState(): Element { val result = Element("state") schemeManager.currentScheme?.let { if (it.name != DefaultKeymap.instance.defaultKeymapName) { val e = Element(ACTIVE_KEYMAP) e.setAttribute(NAME_ATTRIBUTE, it.name) result.addContent(e) } } return result } override fun loadState(state: Element) { val child = state.getChild(ACTIVE_KEYMAP) val activeKeymapName = child?.getAttributeValue(NAME_ATTRIBUTE) if (!activeKeymapName.isNullOrBlank()) { schemeManager.currentSchemeName = activeKeymapName } } @Suppress("OverridingDeprecatedMember") override fun addKeymapManagerListener(listener: KeymapManagerListener) { pollQueue() listeners.add(listener) } @Suppress("DEPRECATION") override fun addKeymapManagerListener(listener: KeymapManagerListener, parentDisposable: Disposable) { pollQueue() listeners.add(listener) Disposer.register(parentDisposable, Disposable { removeKeymapManagerListener(listener) }) } private fun pollQueue() { listeners.removeAll { it is WeakKeymapManagerListener && it.isDead } } @Suppress("OverridingDeprecatedMember") override fun removeKeymapManagerListener(listener: KeymapManagerListener) { pollQueue() listeners.remove(listener) } @Suppress("DEPRECATION") override fun addWeakListener(listener: KeymapManagerListener) { addKeymapManagerListener(WeakKeymapManagerListener(this, listener)) } override fun removeWeakListener(listenerToRemove: KeymapManagerListener) { listeners.removeAll { it is WeakKeymapManagerListener && it.isWrapped(listenerToRemove) } } }
apache-2.0
1f4de998eec0b3d35b500b0dab7c7f0b
35.621622
158
0.740812
4.842745
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/preferences/PreferencesAudio.kt
1
4393
/* * ************************************************************************* * PreferencesAudio.java * ************************************************************************** * Copyright © 2016 VLC authors and VideoLAN * * 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.preferences import android.content.SharedPreferences import android.os.Bundle import androidx.preference.CheckBoxPreference import androidx.preference.Preference import androidx.preference.TwoStatePreference import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import org.videolan.libvlc.util.AndroidUtil import org.videolan.libvlc.util.HWDecoderUtil import org.videolan.vlc.R import org.videolan.tools.AUDIO_DUCKING import org.videolan.resources.AndroidDevices import org.videolan.tools.RESUME_PLAYBACK import org.videolan.resources.VLCInstance @ExperimentalCoroutinesApi @ObsoleteCoroutinesApi class PreferencesAudio : BasePreferenceFragment(), SharedPreferences.OnSharedPreferenceChangeListener { override fun getXml() = R.xml.preferences_audio override fun getTitleId() = R.string.audio_prefs_category override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) findPreference<Preference>(AUDIO_DUCKING)?.isVisible = !AndroidUtil.isOOrLater findPreference<Preference>(RESUME_PLAYBACK)?.isVisible = AndroidDevices.isPhone val aout = HWDecoderUtil.getAudioOutputFromDevice() if (aout != HWDecoderUtil.AudioOutput.ALL) { /* no AudioOutput choice */ findPreference<Preference>("aout")?.isVisible = false } updatePassThroughSummary() val opensles = "1" == preferenceManager.sharedPreferences.getString("aout", "0") if (opensles) findPreference<Preference>("audio_digital_output")?.isVisible = false } private fun updatePassThroughSummary() { val pt = preferenceManager.sharedPreferences.getBoolean("audio_digital_output", false) findPreference<Preference>("audio_digital_output")?.setSummary(if (pt) R.string.audio_digital_output_enabled else R.string.audio_digital_output_disabled) } override fun onStart() { super.onStart() preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this) } override fun onStop() { super.onStop() preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) } override fun onPreferenceTreeClick(preference: Preference): Boolean { if (preference.key == null) return false when (preference.key) { "enable_headset_detection" -> { (requireActivity() as PreferencesActivity).detectHeadset((preference as TwoStatePreference).isChecked) return true } } return super.onPreferenceTreeClick(preference) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { val activity = activity ?: return when (key) { "aout" -> { VLCInstance.restart() (activity as PreferencesActivity).restartMediaPlayer() val opensles = "1" == preferenceManager.sharedPreferences.getString("aout", "0") if (opensles) findPreference<CheckBoxPreference>("audio_digital_output")?.isChecked = false findPreference<Preference>("audio_digital_output")?.isVisible = !opensles } "audio_digital_output" -> updatePassThroughSummary() } } }
gpl-2.0
e5883e7db2b29b71c481ba3dbd1b2323
42.49505
161
0.681011
5.130841
false
false
false
false
d3xter/bo-android
app/src/main/java/org/blitzortung/android/map/overlay/RasterShape.kt
1
2789
/* Copyright 2015 Andreas Würl Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.blitzortung.android.map.overlay import android.graphics.Canvas import android.graphics.Paint import android.graphics.Paint.Align import android.graphics.Point import android.graphics.RectF import android.graphics.drawable.shapes.Shape class RasterShape : Shape() { private val rect: RectF private var color: Int = 0 private var alpha: Int = 0 private var multiplicity: Int = 0 private var textColor: Int = 0 init { rect = RectF() } override fun draw(canvas: Canvas, paint: Paint) { paint.color = color paint.alpha = alpha canvas.drawRect(rect, paint) val textSize = rect.height() / 2.5f if (textSize >= 8f) { paint.color = textColor paint.alpha = calculateAlphaValue(textSize, 20, 80, 255, 60) paint.textAlign = Align.CENTER paint.textSize = textSize canvas.drawText(multiplicity.toString(), 0.0f, 0.4f * textSize, paint) } } override fun hasAlpha(): Boolean { return alpha != 255 } fun update(topLeft: Point, bottomRight: Point, color: Int, multiplicity: Int, textColor: Int) { val x1 = Math.min(topLeft.x.toFloat(), -MIN_SIZE) val y1 = Math.min(topLeft.y.toFloat(), -MIN_SIZE) val x2 = Math.max(bottomRight.x.toFloat(), MIN_SIZE) val y2 = Math.max(bottomRight.y.toFloat(), MIN_SIZE) rect.set(x1, y1, x2, y2) resize(rect.width(), rect.height()) this.multiplicity = multiplicity this.color = color this.textColor = textColor alpha = calculateAlphaValue(rect.width(), 10, 40, 255, 100) } private fun calculateAlphaValue(value: Float, minValue: Int, maxValue: Int, maxAlpha: Int, minAlpha: Int): Int { val targetValue = coerceToRange((value - minValue) / (maxValue - minValue), 0.0f, 1.0f) return minAlpha + ((maxAlpha - minAlpha) * (1.0 - targetValue)).toInt() } private fun coerceToRange(value: Float, lowerBound: Float, upperBound: Float): Float { return Math.min(Math.max(value, lowerBound), upperBound) } companion object { private val MIN_SIZE = 1.5f } }
apache-2.0
134f3d6485e99ae53fae3d203f456041
31.418605
116
0.656743
4.046444
false
false
false
false
fallGamlet/DnestrCinema
app/src/main/java/com/fallgamlet/dnestrcinema/utils/CollectionUtils.kt
1
1415
package com.fallgamlet.dnestrcinema.utils import java.util.* object CollectionUtils { fun isEmpty(collection: Collection<*>?): Boolean { return collection == null || collection.isEmpty() } fun getSize(collection: Collection<*>?): Int { return collection?.size ?: 0 } fun <T> getNonNull(list: List<T>?): List<T> { return list ?: ArrayList() } fun <T> getNonNull(list: Set<T>?): Set<T> { return list ?: HashSet() } fun <T> getList(set: Set<T>?): List<T> { return set?.let { ArrayList(it) } ?: ArrayList() } fun <T> emptyList(): List<T> { return ArrayList() } fun <T, R> mapItems(items: Collection<T>, converter: Converter<T, R>): List<R> { if (isEmpty(items)) { return emptyList() } val resultItems = ArrayList<R>(items.size) for (item in items) { val resItem = converter.convert(item) if (item != null) { resultItems.add(resItem) } } return resultItems } fun <T> forEach(items: Collection<T>, function: Each<T>) { if (isEmpty(items)) { return } for (item in items) { function.run(item) } } interface Converter<T, R> { fun convert(item: T?): R } interface Each<T> { fun run(item: T) } }
gpl-3.0
81a3d1b77849b7b7778e60ead268e827
20.119403
84
0.520141
3.952514
false
false
false
false
iovation/launchkey-android-whitelabel-sdk
demo-app/app/src/kotlinApp/java/com/launchkey/android/authenticator/demo/ui/fragment/CustomLinkingFragment.kt
2
3718
package com.launchkey.android.authenticator.demo.ui.fragment import android.app.ProgressDialog import android.os.Bundle import android.view.View import androidx.appcompat.app.AlertDialog import com.launchkey.android.authenticator.demo.R import com.launchkey.android.authenticator.demo.databinding.DemoFragmentLinkBinding import com.launchkey.android.authenticator.demo.ui.activity.ListDemoActivity import com.launchkey.android.authenticator.demo.util.Utils.finish import com.launchkey.android.authenticator.sdk.core.authentication_management.AuthenticatorManager import com.launchkey.android.authenticator.sdk.core.authentication_management.Device import com.launchkey.android.authenticator.sdk.core.authentication_management.event_callback.DeviceLinkedEventCallback import com.launchkey.android.authenticator.sdk.core.util.CompositeDisposable import java.util.regex.Pattern class CustomLinkingFragment : BaseDemoFragment<DemoFragmentLinkBinding>(R.layout.demo_fragment_link) { private var mLinkingDialog: ProgressDialog? = null private val mAuthenticatorManager = AuthenticatorManager.instance private val compositeDisposable = CompositeDisposable() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupUi(view) } private fun setupUi(root: View) { binding = DemoFragmentLinkBinding.bind(root) binding!!.demoLinkCheckboxDevicenameCustom.setOnCheckedChangeListener { buttonView, isChecked -> binding!!.demoLinkEditName.isEnabled = isChecked } binding!!.demoLinkButton.setOnClickListener { onLink() } mLinkingDialog = ProgressDialog(activity, R.style.AuthenticatorAlertDialogStyle) mLinkingDialog!!.isIndeterminate = true } override fun onPause() { super.onPause() compositeDisposable.clear() } private fun onLink() { val linkingCode = binding!!.demoLinkEditCode.text.toString().trim() val customDeviceName = binding!!.demoLinkEditName.text.toString().trim() if (!Pattern.matches(AuthenticatorManager.REGEX_LINKING_CODE, linkingCode)) { showAlert("Error", "Linking code has illegal characters. Allowed structure: " + AuthenticatorManager.REGEX_LINKING_CODE) return } //depending on the desired approach, it is possible to provide a custom device name // if no custom device name is provided, a default one will be generated // based on the model and manufacturer. mLinkingDialog!!.show() mLinkingDialog!!.setMessage("Verifying linking code...") val deviceName = if (binding!!.demoLinkCheckboxDevicenameCustom.isChecked) customDeviceName else null val overrideNameIfUsed = binding!!.demoLinkCheckboxDevicenameOverride.isChecked compositeDisposable.add(mAuthenticatorManager.linkDevice(requireArguments().getString(ListDemoActivity.EXTRA_SDK_KEY)!!, linkingCode, deviceName, overrideNameIfUsed, object : DeviceLinkedEventCallback() { override fun onSuccess(device: Device) { mLinkingDialog!!.dismiss() finish(this@CustomLinkingFragment) } override fun onFailure(e: Exception) { mLinkingDialog!!.dismiss() showAlert("Error", e.message) } })) } private fun showAlert(title: String, message: String?) { AlertDialog.Builder(requireActivity()) .setTitle(title) .setMessage(message) .setPositiveButton("OK", null) .setOnDismissListener(null) .create() .show() } }
mit
7ec336a76b82fe35ed1d53f68cc3c3fe
46.679487
212
0.717321
4.944149
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/forge/inspections/sideonly/NewExpressionSideOnlyInspection.kt
1
4487
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.forge.inspections.sideonly import com.demonwav.mcdev.util.findContainingClass import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiClass import com.intellij.psi.PsiNewExpression import com.siyeh.ig.BaseInspection import com.siyeh.ig.BaseInspectionVisitor import com.siyeh.ig.InspectionGadgetsFix import org.jetbrains.annotations.Nls class NewExpressionSideOnlyInspection : BaseInspection() { @Nls override fun getDisplayName() = "Invalid usage of class annotated with @SideOnly" override fun buildErrorString(vararg infos: Any) = "A class annotated with @SideOnly can only be used in other matching annotated classes and methods" override fun getStaticDescription(): String? { return "A class that is annotated as @SideOnly(Side.CLIENT) or @SideOnly(Side.SERVER) cannot be " + "used in classes or methods which are annotated differently, or not at all. Since the " + "irrelevant code is removed when operating as a server or a client, common code cannot " + "use @SideOnly annotated classes either." } override fun buildFix(vararg infos: Any): InspectionGadgetsFix? { val annotation = infos[0] as PsiAnnotation return if (annotation.isWritable) { RemoveAnnotationInspectionGadgetsFix(annotation, "Remove @SideOnly annotation from class declaration") } else { null } } override fun buildVisitor(): BaseInspectionVisitor { return object : BaseInspectionVisitor() { override fun visitNewExpression(expression: PsiNewExpression) { if (!SideOnlyUtil.beginningCheck(expression)) { return } val element = expression.classReference ?: return val psiElement = (element.resolve() ?: return) as? PsiClass ?: return var classAnnotation: SideAnnotation? = null var classSide = Side.NONE var offender: PsiClass? = null for ((hierarchyAnnotation, hierarchySide, clazz) in SideOnlyUtil.checkClassHierarchy(psiElement)) { if (hierarchySide !== Side.NONE && hierarchySide !== Side.INVALID) { classAnnotation = hierarchyAnnotation classSide = hierarchySide offender = clazz break } } if (classAnnotation == null || classSide == Side.NONE || offender == null) { return } // Check the class(es) the element is in val containingClass = expression.findContainingClass() ?: return val (_, containingClassSide) = SideOnlyUtil.getSideForClass(containingClass) // Check the method the element is in val (_, methodSide) = SideOnlyUtil.checkElementInMethod(expression) var classAnnotated = false if (containingClassSide !== Side.NONE && containingClassSide !== Side.INVALID ) { if (containingClassSide !== classSide) { registerError(expression, offender.getAnnotation(classAnnotation.annotationName)) } classAnnotated = true } else { if (methodSide === Side.INVALID) { // It's not in a method registerError(expression, offender.getAnnotation(classAnnotation.annotationName)) return } } // Put error on for method if (classSide !== methodSide && methodSide !== Side.INVALID) { if (methodSide === Side.NONE) { // If the class is properly annotated the method doesn't need to also be annotated if (!classAnnotated) { registerError(expression, offender.getAnnotation(classAnnotation.annotationName)) } } else { registerError(expression, offender.getAnnotation(classAnnotation.annotationName)) } } } } } }
mit
f40d3a4d4c835d5a5b71167240fed4e4
39.423423
115
0.582795
5.774775
false
false
false
false
alaminopu/IST-Syllabus
app/src/main/java/org/istbd/IST_Syllabus/bottombar/BottomBar.kt
1
5146
package org.istbd.IST_Syllabus import androidx.compose.animation.core.SpringSpec import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.selection.selectable import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.Shape import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import androidx.navigation.NavController import androidx.navigation.compose.currentBackStackEntryAsState import com.google.accompanist.insets.navigationBarsPadding @Composable fun BottomBar( navController: NavController, tabs: Array<TabSections>, ) { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route val sections = remember { TabSections.values() } val routes = remember { sections.map { it.route } } if (currentRoute in routes) { val currentSection = sections.first { it.route == currentRoute } val shape: Shape = RectangleShape val border: BorderStroke? = null val elevation: Dp = 0.dp NavLayoutBox( elevation, shape, border, currentSection, routes, tabs, currentRoute, navController ) } } @Composable private fun NavLayoutBox( elevation: Dp, shape: Shape, border: BorderStroke?, currentSection: TabSections, routes: List<String>, tabs: Array<TabSections>, currentRoute: String?, navController: NavController ) { Box( modifier = Modifier .shadow(elevation = elevation, shape = shape, clip = false) .zIndex(elevation.value) .then(if (border != null) Modifier.border(border, shape) else Modifier) .clip(shape), ) { CompositionLocalProvider(content = { val springSpec = SpringSpec<Float>( stiffness = 800f, dampingRatio = 0.8f ) BottomNavLayout( selectedIndex = currentSection.ordinal, itemCount = routes.size, indicator = { Spacer( modifier = Modifier .fillMaxSize() .then(BottomNavigationItemPadding) .border(2.dp, Color.White, BottomNavIndicatorShape), ) }, animSpec = springSpec, modifier = Modifier.navigationBarsPadding(start = false, end = false) ) { tabs.forEach { section -> val selected = section == currentSection NavItemBox(selected, section, currentRoute, navController, springSpec) } } }) } } @Composable private fun NavItemBox( selected: Boolean, section: TabSections, currentRoute: String?, navController: NavController, springSpec: SpringSpec<Float> ) { Box( modifier = BottomNavigationItemPadding .clip(BottomNavIndicatorShape) .selectable(selected = selected, onClick = { if (section.route != currentRoute) { navController.navigate(section.route) { launchSingleTop = true restoreState = true popUpTo(findStartDestination(navController.graph).id) { saveState = true } } } }), contentAlignment = Alignment.Center ) { // Animate the icon/text positions within the item based on selection val animationProgress by animateFloatAsState(if (selected) 1f else 0f, springSpec) BottomNavItemLayout( icon = { Image( painter = painterResource(id = section.icon), contentDescription = null ) }, text = { Text( text = section.title, style = MaterialTheme.typography.button, color = Color.White ) }, animationProgress = animationProgress ) } }
gpl-2.0
c8b25717318fe846294108c913442d83
32.855263
90
0.612903
5.224365
false
false
false
false
cashapp/sqldelight
sqldelight-gradle-plugin/src/test/kotlin/app/cash/sqldelight/TestUtil.kt
1
1655
package app.cash.sqldelight import app.cash.sqldelight.core.SqlDelightPropertiesFile import app.cash.sqldelight.gradle.SqlDelightCompilationUnitImpl import app.cash.sqldelight.gradle.SqlDelightDatabasePropertiesImpl import app.cash.sqldelight.gradle.SqlDelightPropertiesFileImpl import app.cash.sqldelight.gradle.SqlDelightSourceFolderImpl import java.io.File internal fun String.withInvariantPathSeparators() = replace("\\", "/") internal fun SqlDelightPropertiesFileImpl.withInvariantPathSeparators(): SqlDelightPropertiesFile { return copy( databases = databases.map { it.withInvariantPathSeparators() }, ) } internal fun SqlDelightDatabasePropertiesImpl.withInvariantPathSeparators(): SqlDelightDatabasePropertiesImpl { return copy( compilationUnits = compilationUnits.map { it.withInvariantPathSeparators() }, ) } internal fun SqlDelightDatabasePropertiesImpl.withSortedCompilationUnits(): SqlDelightDatabasePropertiesImpl { return copy( compilationUnits = compilationUnits.map { it.withSortedSourceFolders() }, ) } private fun SqlDelightCompilationUnitImpl.withInvariantPathSeparators(): SqlDelightCompilationUnitImpl { return copy( sourceFolders = sourceFolders.map { it.withInvariantPathSeparators() }, outputDirectoryFile = File(outputDirectoryFile.path.withInvariantPathSeparators()), ) } private fun SqlDelightCompilationUnitImpl.withSortedSourceFolders(): SqlDelightCompilationUnitImpl { return copy(sourceFolders = sourceFolders.sortedBy { it.folder.path }) } private fun SqlDelightSourceFolderImpl.withInvariantPathSeparators() = copy(folder = File(folder.path.withInvariantPathSeparators()))
apache-2.0
c9a67bbefe5932d9de9b47333594e4e5
38.404762
111
0.825982
5.22082
false
false
false
false
rhdunn/marklogic-intellij-plugin
src/main/java/uk/co/reecedunn/intellij/plugin/core/xml/XmlDocument.kt
1
1384
/* * Copyright (C) 2017 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.core.xml import org.w3c.dom.Document import org.w3c.dom.Element import org.xml.sax.InputSource import java.io.StringReader import javax.xml.parsers.DocumentBuilder import javax.xml.parsers.DocumentBuilderFactory class XmlDocument internal constructor(doc: Document) { val root: Element = doc.documentElement companion object { private fun createDocumentBuilder(): DocumentBuilder { val factory = DocumentBuilderFactory.newInstance() factory.isNamespaceAware = true return factory.newDocumentBuilder() } private val builder = createDocumentBuilder() fun parse(xml: String): XmlDocument = XmlDocument(builder.parse(InputSource(StringReader(xml)))) } }
apache-2.0
a136e33a5a730dc5d1fc7b1f5d22540e
33.6
75
0.729769
4.464516
false
false
false
false
doerfli/hacked
app/src/main/kotlin/li/doerf/hacked/ui/RateUsDialogFragment.kt
1
2286
package li.doerf.hacked.ui import android.app.Dialog import android.content.DialogInterface import android.os.Bundle import android.util.Log import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import androidx.preference.PreferenceManager import li.doerf.hacked.CustomEvent import li.doerf.hacked.R import li.doerf.hacked.util.Analytics import li.doerf.hacked.util.AppReview import li.doerf.hacked.util.RatingHelper class RateUsDialogFragment() : DialogFragment() { private val LOGTAG = javaClass.simpleName private lateinit var appReview: AppReview override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return AlertDialog.Builder(requireContext()) .setTitle(getString(R.string.rating_dialog_title)) .setMessage(getString(R.string.rating_dialog_message)) .setPositiveButton(getString(R.string.rating_dialog_positive)) { _: DialogInterface?, _: Int -> handleClickPositive() } .setNeutralButton(getString(R.string.rating_dialog_neutral)) { _: DialogInterface?, _: Int -> handleClickNeutral() } .setNegativeButton(getString(R.string.rating_dialog_negative)) { _: DialogInterface?, _: Int -> handleClickNegative() }.create() } fun setAppReview(appRevie: AppReview) { this.appReview = appRevie } private fun handleClickPositive() { if (this::appReview.isInitialized) { appReview.showReview() } else { handleClickNeutral(); } } private fun handleClickNeutral() { val settings = PreferenceManager.getDefaultSharedPreferences(requireContext()) val editor = settings.edit() editor.putInt(RatingHelper.PREF_KEY_RATING_COUNTER, 0) editor.apply() Log.i(LOGTAG, "setting: reset rating counter") Analytics.trackCustomEvent(CustomEvent.RATE_LATER) } private fun handleClickNegative() { val settings = PreferenceManager.getDefaultSharedPreferences(requireContext()) val editor = settings.edit() editor.putBoolean(RatingHelper.PREF_KEY_RATING_NEVER, true) editor.apply() Log.i(LOGTAG, "setting: never rate") Analytics.trackCustomEvent(CustomEvent.RATE_NEVER) } }
apache-2.0
114db5c5b8adc29465704429665581d3
38.431034
144
0.701662
4.517787
false
false
false
false
Popalay/Cardme
data/src/main/kotlin/com/popalay/cardme/data/models/Holder.kt
1
1184
package com.popalay.cardme.data.models import com.google.gson.annotations.Expose import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class Holder( @Expose @PrimaryKey var name: String = "", @Expose var isTrash: Boolean = false, var cards: RealmList<Card> = RealmList(), var debts: RealmList<Debt> = RealmList() ) : RealmObject(), StableId { companion object { const val NAME = "name" const val CARDS = "cards" const val DEBTS = "debts" const val IS_TRASH = "isTrash" } override val stableId: Long get() = name.hashCode().toLong() override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as Holder if (name != other.name) return false if (isTrash != other.isTrash) return false return true } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + isTrash.hashCode() return result } override fun toString() = "Holder(name='$name', isTrash=$isTrash)" }
apache-2.0
883503821ac9f7de79a660afffdd107b
25.311111
70
0.619932
4.169014
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/message/MessagesConversationFragment.kt
1
26826
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.fragment.message import android.Manifest import android.accounts.AccountManager import android.app.Activity import android.content.Context import android.content.Intent import android.graphics.PorterDuff import android.graphics.Rect import android.net.Uri import android.os.Bundle import android.support.v4.app.ActivityCompat import android.support.v4.app.FragmentActivity import android.support.v4.app.LoaderManager import android.support.v4.content.ContextCompat import android.support.v4.content.Loader import android.support.v4.widget.TextViewCompat import android.support.v7.app.AppCompatActivity import android.support.v7.widget.FixedLinearLayoutManager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.view.* import com.bumptech.glide.RequestManager import com.squareup.otto.Subscribe import kotlinx.android.synthetic.main.activity_premium_dashboard.* import kotlinx.android.synthetic.main.fragment_messages_conversation.* import kotlinx.android.synthetic.main.fragment_messages_conversation.view.* import kotlinx.android.synthetic.main.layout_toolbar_message_conversation_title.* import org.mariotaku.abstask.library.TaskStarter import org.mariotaku.chameleon.Chameleon import org.mariotaku.chameleon.ChameleonUtils import org.mariotaku.kpreferences.get import org.mariotaku.ktextension.* import org.mariotaku.pickncrop.library.MediaPickerActivity import org.mariotaku.sqliteqb.library.Expression import org.mariotaku.sqliteqb.library.OrderBy import de.vanita5.twittnuker.R import de.vanita5.twittnuker.SecretConstants import de.vanita5.twittnuker.TwittnukerConstants.REQUEST_PICK_MEDIA import de.vanita5.twittnuker.activity.LinkHandlerActivity import de.vanita5.twittnuker.activity.ThemedMediaPickerActivity import de.vanita5.twittnuker.adapter.MediaPreviewAdapter import de.vanita5.twittnuker.adapter.MessagesConversationAdapter import de.vanita5.twittnuker.adapter.iface.ILoadMoreSupportAdapter import de.vanita5.twittnuker.annotation.AccountType import de.vanita5.twittnuker.constant.IntentConstants.* import de.vanita5.twittnuker.constant.nameFirstKey import de.vanita5.twittnuker.constant.newDocumentApiKey import de.vanita5.twittnuker.constant.profileImageStyleKey import de.vanita5.twittnuker.extension.loadProfileImage import de.vanita5.twittnuker.extension.model.* import de.vanita5.twittnuker.fragment.AbsContentListRecyclerViewFragment import de.vanita5.twittnuker.fragment.EditAltTextDialogFragment import de.vanita5.twittnuker.fragment.iface.IToolBarSupportFragment import de.vanita5.twittnuker.loader.ObjectCursorLoader import de.vanita5.twittnuker.model.* import de.vanita5.twittnuker.model.ParcelableMessageConversation.ConversationType import de.vanita5.twittnuker.model.event.GetMessagesTaskEvent import de.vanita5.twittnuker.model.event.SendMessageTaskEvent import de.vanita5.twittnuker.model.util.AccountUtils import de.vanita5.twittnuker.provider.TwidereDataStore.Messages import de.vanita5.twittnuker.service.LengthyOperationsService import de.vanita5.twittnuker.task.compose.AbsAddMediaTask import de.vanita5.twittnuker.task.compose.AbsDeleteMediaTask import de.vanita5.twittnuker.task.twitter.message.DestroyMessageTask import de.vanita5.twittnuker.task.twitter.message.GetMessagesTask import de.vanita5.twittnuker.task.twitter.message.MarkMessageReadTask import de.vanita5.twittnuker.util.ClipboardUtils import de.vanita5.twittnuker.util.DataStoreUtils import de.vanita5.twittnuker.util.IntentUtils import de.vanita5.twittnuker.util.PreviewGridItemDecoration import de.vanita5.twittnuker.view.ExtendedRecyclerView import de.vanita5.twittnuker.view.holder.compose.MediaPreviewViewHolder import org.mariotaku.ktextension.checkAnySelfPermissionsGranted import xyz.klinker.giphy.Giphy import xyz.klinker.giphy.GiphyActivity import java.lang.ref.WeakReference import java.util.concurrent.atomic.AtomicReference class MessagesConversationFragment : AbsContentListRecyclerViewFragment<MessagesConversationAdapter>(), IToolBarSupportFragment, LoaderManager.LoaderCallbacks<List<ParcelableMessage>?>, EditAltTextDialogFragment.EditAltTextCallback { private lateinit var mediaPreviewAdapter: MediaPreviewAdapter private val accountKey: UserKey get() = arguments.getParcelable(EXTRA_ACCOUNT_KEY) private val conversationId: String get() = arguments.getString(EXTRA_CONVERSATION_ID) private val account: AccountDetails? by lazy { AccountUtils.getAccountDetails(AccountManager.get(context), accountKey, true) } private val loadMoreTaskTag: String get() = "loadMore:$accountKey:$conversationId" // Layout manager reversed, so treat start as end override val reachingEnd: Boolean get() = super.reachingStart // Layout manager reversed, so treat end as start override val reachingStart: Boolean get() = super.reachingEnd override val controlBarHeight: Int get() = toolbar.height override var controlBarOffset: Float = 1f override val toolbar: Toolbar get() = conversationContainer.toolbar override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setHasOptionsMenu(true) val account = this.account ?: run { activity?.finish() return } adapter.listener = object : MessagesConversationAdapter.Listener { override fun onMediaClick(position: Int, media: ParcelableMedia, accountKey: UserKey?) { val message = adapter.getMessage(position) IntentUtils.openMediaDirectly(context = context, accountKey = accountKey, media = message.media, current = media, newDocument = preferences[newDocumentApiKey], message = message) } override fun onMessageLongClick(position: Int, holder: RecyclerView.ViewHolder): Boolean { return recyclerView.showContextMenuForChild(holder.itemView) } } mediaPreviewAdapter = MediaPreviewAdapter(context, requestManager) mediaPreviewAdapter.listener = object : MediaPreviewAdapter.Listener { override fun onRemoveClick(position: Int, holder: MediaPreviewViewHolder) { val task = DeleteMediaTask(this@MessagesConversationFragment, arrayOf(mediaPreviewAdapter.getItem(position))) TaskStarter.execute(task) } override fun onEditClick(position: Int, holder: MediaPreviewViewHolder) { attachedMediaPreview.showContextMenuForChild(holder.itemView) } } attachedMediaPreview.layoutManager = FixedLinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) attachedMediaPreview.adapter = mediaPreviewAdapter attachedMediaPreview.addItemDecoration(PreviewGridItemDecoration(resources.getDimensionPixelSize(R.dimen.element_spacing_small))) registerForContextMenu(recyclerView) registerForContextMenu(attachedMediaPreview) sendMessage.setOnClickListener { performSendMessage() } addMedia.setOnClickListener { openMediaPicker() } conversationTitleContainer.setOnClickListener { val intent = IntentUtils.messageConversationInfo(accountKey, conversationId) startActivityForResult(intent, REQUEST_MANAGE_CONVERSATION_INFO) } val activity = this.activity if (activity is AppCompatActivity) { activity.supportActionBar?.setDisplayShowTitleEnabled(false) } val theme = Chameleon.getOverrideTheme(context, activity) conversationTitle.setTextColor(ChameleonUtils.getColorDependent(theme.colorToolbar)) conversationSubtitle.setTextColor(ChameleonUtils.getColorDependent(theme.colorToolbar)) conversationAvatar.style = preferences[profileImageStyleKey] setupEditText() // No refresh for this fragment refreshEnabled = false adapter.loadMoreSupportedPosition = ILoadMoreSupportAdapter.NONE if (account.type == AccountType.TWITTER) { addMedia.visibility = View.VISIBLE } else { addMedia.visibility = View.GONE } if (savedInstanceState != null) { val list = savedInstanceState.getParcelableArrayList<ParcelableMediaUpdate>(EXTRA_MEDIA) if (list != null) { mediaPreviewAdapter.addAll(list) } } updateMediaPreview() loaderManager.initLoader(0, null, this) showProgress() } override fun onStart() { super.onStart() bus.register(this) } override fun onStop() { bus.unregister(this) super.onStop() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelableArrayList(EXTRA_MEDIA, ArrayList(mediaPreviewAdapter.asList())) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (resultCode) { Giphy.REQUEST_GIPHY -> { requestOrPickGif() } } when (requestCode) { REQUEST_PICK_MEDIA, Giphy.REQUEST_GIPHY -> { when (resultCode) { Activity.RESULT_OK -> if (data != null) { val mediaUris = MediaPickerActivity.getMediaUris(data) val types = data.getBundleExtra(MediaPickerActivity.EXTRA_EXTRAS)?.getIntArray(EXTRA_TYPES) TaskStarter.execute(AddMediaTask(this, mediaUris, types, false, false)) } RESULT_SEARCH_GIF -> { val provider = gifShareProvider ?: return startActivityForResult(provider.createGifSelectorIntent(), REQUEST_ADD_GIF) } } } REQUEST_MANAGE_CONVERSATION_INFO -> { if (resultCode == MessageConversationInfoFragment.RESULT_CLOSE) { activity?.finish() } } REQUEST_ADD_GIF -> { if (resultCode == Activity.RESULT_OK && data != null) { val intent = ThemedMediaPickerActivity.withThemed(context) .getMedia(data.data) .extras(Bundle { this[EXTRA_TYPES] = intArrayOf(ParcelableMedia.Type.ANIMATED_GIF) }) .build() startActivityForResult(intent, REQUEST_PICK_MEDIA) } } } } private fun requestOrPickGif() { if (this.context.checkAnySelfPermissionsGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { pickGif() return } ActivityCompat.requestPermissions(this.activity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_PICK_MEDIA_PERMISSION) } private fun pickGif(): Boolean { // Giphy.Builder(this.activity, SecretConstants.GIPHY_API_KEY).maxFileSize(10 * 1024 * 1024).build() val intent = Intent(activity, GiphyActivity::class.java) intent.putExtra(GiphyActivity.EXTRA_API_KEY, SecretConstants.GIPHY_API_KEY) intent.putExtra(GiphyActivity.EXTRA_SIZE_LIMIT, 10 * 1024 * 1024) startActivityForResult(intent, Giphy.REQUEST_GIPHY) return true } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return inflater.inflate(R.layout.fragment_messages_conversation, container, false) } override fun setupWindow(activity: FragmentActivity): Boolean { return false } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_messages_conversation, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { } return false } override fun onCreateLoader(id: Int, args: Bundle?): Loader<List<ParcelableMessage>?> { return ConversationLoader(context, accountKey, conversationId) } override fun onLoadFinished(loader: Loader<List<ParcelableMessage>?>, data: List<ParcelableMessage>?) { val conversationLoader = loader as? ConversationLoader val conversation = conversationLoader?.conversation adapter.setData(conversation, data) adapter.displaySenderProfile = conversation?.conversation_type == ConversationType.GROUP if (conversation?.conversation_extras_type == ParcelableMessageConversation.ExtrasType.TWITTER_OFFICIAL) { adapter.loadMoreSupportedPosition = ILoadMoreSupportAdapter.START } else { adapter.loadMoreSupportedPosition = ILoadMoreSupportAdapter.NONE } showContent() if (conversation != null && !conversation.is_temp) { markRead() } updateConversationStatus() } override fun onLoaderReset(loader: Loader<List<ParcelableMessage>?>) { adapter.setData(null, null) } override fun onCreateAdapter(context: Context, requestManager: RequestManager): MessagesConversationAdapter { return MessagesConversationAdapter(context, this.requestManager) } override fun onCreateLayoutManager(context: Context): LinearLayoutManager { return FixedLinearLayoutManager(context, LinearLayoutManager.VERTICAL, true) } override fun onCreateItemDecoration(context: Context, recyclerView: RecyclerView, layoutManager: LinearLayoutManager): RecyclerView.ItemDecoration? { return null } override fun onLoadMoreContents(position: Long) { if (ILoadMoreSupportAdapter.START !in position) return val message = adapter.getMessage(adapter.messageRange.endInclusive) setLoadMoreIndicatorPosition(position) val param = GetMessagesTask.LoadMoreMessageTaskParam(context, accountKey, conversationId, message.id) param.taskTag = loadMoreTaskTag twitterWrapper.getMessagesAsync(param) } override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenu.ContextMenuInfo) { if (menuInfo !is ExtendedRecyclerView.ContextMenuInfo) return when (menuInfo.recyclerViewId) { R.id.recyclerView -> { val message = adapter.getMessage(menuInfo.position) val conversation = adapter.conversation menu.setHeaderTitle(message.getSummaryText(context, userColorNameManager, conversation, preferences[nameFirstKey])) activity.menuInflater.inflate(R.menu.menu_conversation_message_item, menu) } R.id.attachedMediaPreview -> { menu.setHeaderTitle(R.string.edit_media) activity.menuInflater.inflate(R.menu.menu_attached_media_edit, menu) } } } override fun onContextItemSelected(item: MenuItem): Boolean { val menuInfo = item.menuInfo as? ExtendedRecyclerView.ContextMenuInfo ?: run { return super.onContextItemSelected(item) } when (menuInfo.recyclerViewId) { R.id.recyclerView -> { val message = adapter.getMessage(menuInfo.position) when (item.itemId) { R.id.copy -> { ClipboardUtils.setText(context, message.text_unescaped) } R.id.delete -> { val task = DestroyMessageTask(context, message.account_key, message.conversation_id, message.id) TaskStarter.execute(task) } } return true } R.id.attachedMediaPreview -> { when (item.itemId) { R.id.edit_description -> { val position = menuInfo.position val altText = mediaPreviewAdapter.getItem(position).alt_text executeAfterFragmentResumed { fragment -> EditAltTextDialogFragment.show(fragment.childFragmentManager, position, altText) } } } return true } } return super.onContextItemSelected(item) } override fun onSetAltText(position: Int, altText: String?) { mediaPreviewAdapter.setAltText(position, altText) } override fun onApplySystemWindowInsets(insets: Rect) { view?.setPadding(insets.left, insets.top, insets.right, insets.bottom) } @Subscribe fun onGetMessagesTaskEvent(event: GetMessagesTaskEvent) { if (!event.running && event.taskTag == loadMoreTaskTag) { setLoadMoreIndicatorPosition(ILoadMoreSupportAdapter.NONE) } } @Subscribe fun onSendMessageTaskEvent(event: SendMessageTaskEvent) { if (!event.success || event.accountKey != accountKey || event.conversationId != conversationId) { return } val newConversationId = event.newConversationId ?: return arguments[EXTRA_CONVERSATION_ID] = newConversationId if (activity is LinkHandlerActivity) { activity.intent = IntentUtils.messageConversation(accountKey, newConversationId) } loaderManager.restartLoader(0, null, this) } private fun performSendMessage() { val conversation = adapter.conversation ?: return val conversationAccount = this.account ?: return if (conversation.readOnly) return if (editText.empty && mediaPreviewAdapter.itemCount == 0) { editText.error = getString(R.string.hint_error_message_no_content) return } if (conversationAccount.type == AccountType.TWITTER) { if (mediaPreviewAdapter.itemCount > defaultFeatures.twitterDirectMessageMediaLimit) { editText.error = getString(R.string.error_message_media_message_too_many) return } else { editText.error = null } } else if (mediaPreviewAdapter.itemCount > 0) { editText.error = getString(R.string.error_message_media_message_attachment_not_supported) return } val text = editText.text.toString() val message = ParcelableNewMessage().apply { this.account = conversationAccount this.media = mediaPreviewAdapter.asList().toTypedArray() this.conversation_id = conversation.id this.recipient_ids = conversation.participants?.filter { it.key != accountKey }?.map { it.key.id }?.toTypedArray() this.text = text this.is_temp_conversation = conversation.is_temp } LengthyOperationsService.sendMessageAsync(context, message) editText.text = null // Clear media, those media will be deleted after sent mediaPreviewAdapter.clear() updateMediaPreview() } private fun openMediaPicker() { val builder = ThemedMediaPickerActivity.withThemed(context) builder.pickSources(arrayOf(MediaPickerActivity.SOURCE_CAMERA, MediaPickerActivity.SOURCE_CAMCORDER, MediaPickerActivity.SOURCE_GALLERY, MediaPickerActivity.SOURCE_CLIPBOARD)) builder.addEntry(getString(R.string.add_gif), INTENT_ACTION_PICK_GIF, Giphy.REQUEST_GIPHY) builder.containsVideo(true) builder.allowMultiple(false) val intent = builder.build() startActivityForResult(intent, REQUEST_PICK_MEDIA) } private fun attachMedia(media: List<ParcelableMediaUpdate>) { mediaPreviewAdapter.addAll(media) updateMediaPreview() } private fun removeMedia(media: List<ParcelableMediaUpdate>) { mediaPreviewAdapter.removeAll(media) updateMediaPreview() } private fun updateMediaPreview() { attachedMediaPreview.visibility = if (mediaPreviewAdapter.itemCount > 0) { View.VISIBLE } else { View.GONE } editText.error = null } private fun setProgressVisible(visible: Boolean) { } private fun markRead() { TaskStarter.execute(MarkMessageReadTask(context, accountKey, conversationId)) } private fun updateConversationStatus() { if (context == null || isDetached || (activity?.isFinishing ?: true)) return val conversation = adapter.conversation ?: return val title = conversation.getTitle(context, userColorNameManager, preferences[nameFirstKey]).first val subtitle = conversation.getSubtitle(context) activity.title = title val readOnly = conversation.readOnly addMedia.isEnabled = !readOnly sendMessage.isEnabled = !readOnly editText.isEnabled = !readOnly conversationTitle.spannable = title if (subtitle != null) { conversationSubtitle.visibility = View.VISIBLE conversationSubtitle.spannable = subtitle } else { conversationSubtitle.visibility = View.GONE } val stateIcon = if (conversation.notificationDisabled) { ContextCompat.getDrawable(context, R.drawable.ic_message_type_speaker_muted).apply { mutate() setColorFilter(conversationTitle.currentTextColor, PorterDuff.Mode.SRC_ATOP) } } else { null } TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(conversationTitle, null, null, stateIcon, null) requestManager.loadProfileImage(context, conversation, preferences[profileImageStyleKey]) .into(conversationAvatar) } private fun setupEditText() { editText.imageInputListener = { contentInfo -> val type = if (contentInfo.description.mimeTypeCount > 0) { AbsAddMediaTask.inferMediaType(contentInfo.description.getMimeType(0)) } else { ParcelableMedia.Type.IMAGE } val task = AddMediaTask(this, arrayOf(contentInfo.contentUri), intArrayOf(type), true, false) task.callback = { contentInfo.releasePermission() } TaskStarter.execute(task) } } internal class AddMediaTask( fragment: MessagesConversationFragment, sources: Array<Uri>, types: IntArray?, copySrc: Boolean, deleteSrc: Boolean ) : AbsAddMediaTask<((List<ParcelableMediaUpdate>?) -> Unit)?>(fragment.context, sources, types, copySrc, deleteSrc) { private val fragmentRef = WeakReference(fragment) override fun afterExecute(callback: ((List<ParcelableMediaUpdate>?) -> Unit)?, result: List<ParcelableMediaUpdate>?) { callback?.invoke(result) val fragment = fragmentRef.get() if (fragment != null && result != null) { fragment.setProgressVisible(false) fragment.attachMedia(result) } } override fun beforeExecute() { val fragment = fragmentRef.get() ?: return fragment.setProgressVisible(true) } } internal class DeleteMediaTask( fragment: MessagesConversationFragment, val media: Array<ParcelableMediaUpdate> ) : AbsDeleteMediaTask<MessagesConversationFragment>(fragment.context, media.mapToArray { Uri.parse(it.uri) }) { init { callback = fragment } override fun afterExecute(callback: MessagesConversationFragment?, results: BooleanArray) { if (callback == null) return callback.setProgressVisible(false) callback.removeMedia(media.toList()) } override fun beforeExecute() { val fragment = callback ?: return fragment.setProgressVisible(true) } } internal class ConversationLoader( context: Context, val accountKey: UserKey, val conversationId: String ) : ObjectCursorLoader<ParcelableMessage>(context, ParcelableMessage::class.java) { private val atomicConversation = AtomicReference<ParcelableMessageConversation?>() val conversation: ParcelableMessageConversation? get() = atomicConversation.get() init { uri = Messages.CONTENT_URI projection = Messages.COLUMNS selection = Expression.and(Expression.equalsArgs(Messages.ACCOUNT_KEY), Expression.equalsArgs(Messages.CONVERSATION_ID)).sql selectionArgs = arrayOf(accountKey.toString(), conversationId) sortOrder = OrderBy(Messages.SORT_ID, false).sql isUseCache = false } override fun onLoadInBackground(): MutableList<ParcelableMessage> { atomicConversation.set(DataStoreUtils.findMessageConversation(context, accountKey, conversationId)) return super.onLoadInBackground() } } companion object { private const val REQUEST_MANAGE_CONVERSATION_INFO = 101 private const val REQUEST_ADD_GIF = 102 private const val RESULT_SEARCH_GIF = 11 private const val EXTRA_TYPES = "types" private const val REQUEST_PICK_MEDIA_PERMISSION = 302 } }
gpl-3.0
d091ae7572f3f17c5eabd9d2d68798d1
39.893293
137
0.671401
5.119466
false
false
false
false
Sss1986/KotlinAnkoTest
app/src/main/java/com/xintiaotime/kotlinankotest/Main22Activity.kt
1
1151
package com.xintiaotime.kotlinankotest import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.ArrayAdapter import org.jetbrains.anko.* import org.jetbrains.anko.recyclerview.v7.recyclerView import org.jetbrains.anko.sdk25.coroutines.onClick class Main22Activity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val lambda = { left : Int , right : Int -> left + right } var items = ArrayList<String>() for (i in 0..99){ items.add("明天会更好") } verticalLayout { val text = textView("这是第二个activity"){ textSize = 24f }.lparams{ width = matchParent } val button = button("点击提示"){ textSize = 24F }.lparams{ width = wrapContent height = wrapContent gravity = 17 } button.onClick { startActivity<Main3Activity>() } } } }
apache-2.0
650738ac906ef1554f5049c6e23f8692
25.738095
56
0.556545
4.778723
false
false
false
false
peervalhoegen/SudoQ
sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/sudoku/Sudoku.kt
1
9116
/* * SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least. * Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ package de.sudoq.model.sudoku import de.sudoq.model.ModelChangeListener import de.sudoq.model.ObservableModelImpl import de.sudoq.model.sudoku.complexity.Complexity import de.sudoq.model.sudoku.sudokuTypes.SudokuType import java.util.* import kotlin.collections.component1 import kotlin.collections.component2 import kotlin.collections.set /** * This class represents a Sudoku with mit seinem Typ, seinen Feldern und seinem Schwierigkeitsgrad. */ open class Sudoku : ObservableModelImpl<Cell>, Iterable<Cell>, ModelChangeListener<Cell> { /** An ID uniquely identifying the Sudoku */ var id: Int = 0 /** Counts how often the Sudoku was already transformed */ var transformCount = 0 private set /** Eine Map, welche jeder Position des Sudokus ein Feld zuweist */ @JvmField var cells: HashMap<Position, Cell>? = null private var cellPositions: MutableMap<Int, Position>? = null /** The Type of the Sudoku */ var sudokuType: SudokuType? = null private set /** The Complexity of this Sudoku */ var complexity: Complexity? = null /** * All Cells are set as editable. * * @param type Type of the Sudoku * @param map A Map from Positions to solution values. Values in pre-filled Cells are negated. (actually bitwise negated) * @param setValues A Map from Position to whether the value is pre-filled. */ @JvmOverloads constructor( type: SudokuType, map: PositionMap<Int>? = PositionMap((type.size)!!), setValues: PositionMap<Boolean>? = PositionMap((type.size)!!) ) { var cellIdCounter = 1 cellPositions = HashMap() sudokuType = type cells = HashMap() // iterate over the constraints of the type and create the fields for (constraint in type) { for (position in constraint) { if (!cells!!.containsKey(position)) { var f: Cell val solution = map?.get(position) f = if (solution != null) { val editable = setValues == null || setValues[position] == null || setValues[position] == false Cell(editable, solution, cellIdCounter, type.numberOfSymbols) } else { Cell(cellIdCounter, type.numberOfSymbols) } cells!![position] = f cellPositions!![cellIdCounter++] = position f.registerListener(this) } } } } /** Creates a completely empty sudoku that has to be filled */ @Deprecated("DO NOT USE THIS METHOD (if you are not from us)") internal constructor() { id = -1 } /*init from basic properties. use this to init from BE */ constructor( id: Int, transformCount: Int, sudokuType: SudokuType, complexity: Complexity, cells: HashMap<Position, Cell> ) { this.id = id this.transformCount = transformCount this.sudokuType = sudokuType this.complexity = complexity this.cells = cells cellPositions = HashMap() cells.forEach { (pos, c) -> cellPositions!![c.id] = pos } cells.values.forEach { cell -> cell.registerListener(this) } } /** increases transform count by one */ fun increaseTransformCount() { transformCount++ } /** * Returns the [Cell] at the specified [Position]. * If the position is not mapped to a cell, null is returned * * @param position Position of the cell * @return Cell at the [Position] or null if it is not mapped to a [Cell]. */ fun getCell(position: Position): Cell? { //todo refactor so that a miss leads to illegal args exception return cells!![position] } /** * Returns the [Cell] at the id. * * @param id ID of the [Cell] to return * @return the [Cell] at the specified id or null of id not found */ fun getCell(id: Int): Cell? { return getCell(cellPositions!![id]!!) } /** * Maps the [Position] to the [Cell] * if cell is null nothing happens * * * @param cell the new [Cell] * @param position the [Position] for the new Cell */ fun setCell(cell: Cell?, position: Position) { //todo cell can be null because samurai transformation needs it -> refactor? if (cell == null) return cells!![position] = cell cellPositions!![cell.id] = position } /** * Checks if the id is mapped to a cell */ fun hasCell(id: Int): Boolean { if (cellPositions == null) return false val p: Position = cellPositions!![id] ?: return false return cells?.get(p) != null } /** * Returns the [Position] of the [Cell] if the given id. * Ist id noch nicht vergeben wird null zurückgegeben * * @param id ID of the Cell of the Position to return * @return the [Position] of the id or null if id not found */ fun getPosition(id: Int): Position? { return cellPositions!![id] } /** * Returns an [Iterator] over the [Cell]s. * * @return An [Iterator] over the [Cell]s */ override fun iterator(): Iterator<Cell> { return cells!!.values.iterator() } /** * Checks if the Sudoku is completely filled and solved correctly. * * @return true, iff Sudoku is fully filled and solved correctly */ open val isFinished: Boolean get() { //todo doesn't check for completeness var allCorrect = true for (cell in cells!!.values) if (!cell.isSolvedCorrect) { allCorrect = false break } return allCorrect } /** * {@inheritDoc} */ override fun onModelChanged(changedCell: Cell) { notifyListeners(changedCell) } /** * {@inheritDoc} */ override fun equals(other: Any?): Boolean { if (other != null && other is Sudoku) { val complexityMatch = complexity === other.complexity val typeMatch = sudokuType!!.enumType === other.sudokuType!!.enumType var fieldsMatch = true for (f in cells!!.values) { if (!other.hasCell(f.id) || f != other.getCell(f.id)) { fieldsMatch = false break } } return complexityMatch && typeMatch && fieldsMatch } return false } /** * Checks if this [Sudoku] has errors, i.e. if there is a [Cell] where the value is not the * correct solution. * * @return true, if there are incorrectly solved cells, false otherwise */ open fun hasErrors(): Boolean { for (f in cells!!.values) if (!f.isNotWrong) return true return false //return this.fields.values().stream().anyMatch(f -> !f.isNotWrong()); //looks weird but be very careful with simplifications! } //debug override fun toString(): String { val sb = StringBuilder() val OFFSET = if (sudokuType!!.numberOfSymbols < 10) "" else " " val EMPTY = if (sudokuType!!.numberOfSymbols < 10) "x" else "xx" val NONE = if (sudokuType!!.numberOfSymbols < 10) " " else " " for (j in 0 until sudokuType!!.size!!.y) { for (i in 0 until sudokuType!!.size!!.x) { val f = getCell(Position[i, j]) var op: String if (f != null) { //feld existiert val value = f.currentValue op = if (value == -1) EMPTY else if (value < 10) OFFSET + value else value.toString() + "" sb.append(op) } else { sb.append(NONE) } sb.append(" ") //separator } sb.replace(sb.length - 1, sb.length, "\n") } sb.delete(sb.length - 1, sb.length) return sb.toString() } }
gpl-3.0
63e80f864070710496dfd28cf33a12d5
32.025362
243
0.576915
4.532074
false
false
false
false
codeka/wwmmo
client/src/main/kotlin/au/com/codeka/warworlds/client/game/welcome/SignInLayout.kt
1
2670
package au.com.codeka.warworlds.client.game.welcome import android.content.Context import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.Button import android.widget.EditText import android.widget.RelativeLayout import android.widget.TextView import au.com.codeka.warworlds.client.R import au.com.codeka.warworlds.client.util.GameSettings import au.com.codeka.warworlds.client.util.GameSettings.getString import au.com.codeka.warworlds.client.util.ViewBackgroundGenerator.setBackground import com.google.common.base.Preconditions /** * Layout for [SignInScreen]. */ class SignInLayout(context: Context?, callbacks: Callbacks) : RelativeLayout(context) { interface Callbacks { fun onSignInClick() fun onCreateEmpireClick() fun onCancelClick() } private val signInButton: Button private val cancelButton: Button private val signInHelp: TextView private val signInError: TextView private var inCreateEmpireError: Boolean = false init { View.inflate(context, R.layout.signin, this) setBackground(this) signInHelp = findViewById(R.id.signin_help) signInError = findViewById(R.id.signin_error) signInButton = findViewById(R.id.signin_btn) cancelButton = findViewById(R.id.cancel_btn) signInButton.setOnClickListener { if (inCreateEmpireError) { callbacks.onCreateEmpireClick() } else { callbacks.onSignInClick() } } cancelButton.setOnClickListener { callbacks.onCancelClick() } } /** * Update the state of the UI. * * @param helpResId The resource ID to use for the help text. * @param signInResId * @param isCancel */ fun updateState( helpResId: Int, signInEnabled: Boolean, signInResId: Int, isCancel: Boolean) { signInHelp.setText(helpResId) signInButton.isEnabled = signInEnabled signInButton.setText(signInResId) cancelButton.setText(if (isCancel) R.string.cancel else R.string.back) } fun setForceSignIn(helpResId: Int) { signInHelp.setText(helpResId) signInButton.setText(R.string.yes) cancelButton.setText(R.string.no) } fun setCreateEmpireError(helpResId: Int, emailAddr: String?) { signInHelp.text = resources.getString(helpResId, emailAddr) signInButton.isEnabled = true signInButton.setText(R.string.create_empire) cancelButton.setText(R.string.cancel) inCreateEmpireError = true } fun setErrorMsg(resId: Int) { signInError.setText(resId) } fun setErrorMsg(errorMsg: String?) { if (errorMsg == null) { signInError.text = "" } else { signInError.text = errorMsg } } }
mit
220c8262828778cd1d93af031b41e866
27.115789
87
0.729963
4.015038
false
false
false
false
ryan652/EasyCrypt
appKotlin/src/main/java/com/pvryan/easycryptsample/action/FragmentGeneratePassword.kt
1
4009
/* * Copyright 2018 Priyank Vasa * 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.pvryan.easycryptsample.action import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.pvryan.easycrypt.ECKeys import com.pvryan.easycrypt.symmetric.ECPasswordListener import com.pvryan.easycryptsample.Constants import com.pvryan.easycryptsample.R import com.pvryan.easycryptsample.extensions.snackShort import com.pvryan.easycryptsample.extensions.toNumber import kotlinx.android.synthetic.main.fragment_generate_password.* import org.jetbrains.anko.support.v4.defaultSharedPreferences import org.jetbrains.anko.support.v4.onUiThread import java.security.InvalidParameterException class FragmentGeneratePassword : Fragment() { private val eCPasswords = ECKeys() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_generate_password, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val clipboard = activity?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager llOutputTitleP.setOnLongClickListener { val data = ClipData.newPlainText("result", tvResultP.text) clipboard.primaryClip = data view.snackShort("Output copied to clipboard") true } buttonSecureRandomP.setOnClickListener { try { val symbols: String = edCharsP.text.toString() if (symbols.isNotEmpty()) { tvResultP.text = eCPasswords.genSecureRandomPassword( edLengthP.text.toString().toNumber(Constants.DEFAULT_PASSWORD_LENGTH), symbols.toCharArray()) } else { tvResultP.text = eCPasswords.genSecureRandomPassword( edLengthP.text.toString().toNumber(Constants.DEFAULT_PASSWORD_LENGTH)) } } catch (e: InvalidParameterException) { view.snackShort(e.localizedMessage) } catch (e: NumberFormatException) { view.snackShort("Too big number.") } } buttonRandomOrgP.setOnClickListener { try { eCPasswords.genRandomOrgPassword( edLengthP.text.toString().toNumber(Constants.DEFAULT_PASSWORD_LENGTH), defaultSharedPreferences.getString(getString(R.string.pref_api_key), ""), object : ECPasswordListener { override fun onFailure(message: String, e: Exception) { onUiThread { view.snackShort("Invalid API key: ${e.localizedMessage}") } } override fun onGenerated(password: String) { tvResultP.text = password } }) } catch (e: NumberFormatException) { view.snackShort("Too big number.") } } } companion object { fun newInstance(): Fragment = FragmentGeneratePassword() } }
apache-2.0
e57fa5468fb67f40bec225aefd13ceee
39.908163
116
0.650536
5.068268
false
false
false
false
arcuri82/testing_security_development_enterprise_systems
advanced/exercise-solutions/card-game/part-10/e2e-tests/src/test/kotlin/org/tsdes/advanced/exercises/cardgame/e2etests/RestIT.kt
1
8552
package org.tsdes.advanced.exercises.cardgame.e2etests import io.restassured.RestAssured import io.restassured.RestAssured.given import io.restassured.http.ContentType import org.awaitility.Awaitility import org.hamcrest.CoreMatchers import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.Matchers.greaterThan import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import org.testcontainers.containers.DockerComposeContainer import org.testcontainers.containers.wait.strategy.Wait import org.testcontainers.junit.jupiter.Container import org.testcontainers.junit.jupiter.Testcontainers import java.io.File import java.time.Duration import java.util.concurrent.TimeUnit @Disabled @Testcontainers class RestIT { companion object { init { RestAssured.enableLoggingOfRequestAndResponseIfValidationFails() RestAssured.port = 80 } class KDockerComposeContainer(id: String, path: File) : DockerComposeContainer<KDockerComposeContainer>(id, path) @Container @JvmField val env = KDockerComposeContainer("card-game", File("../docker-compose.yml")) .withExposedService("discovery", 8500, Wait.forListeningPort().withStartupTimeout(Duration.ofSeconds(240))) .withLogConsumer("cards_0") { print("[CARD_0] " + it.utf8String) } .withLogConsumer("cards_1") { print("[CARD_1] " + it.utf8String) } .withLogConsumer("user-collections") { print("[USER_COLLECTIONS] " + it.utf8String) } .withLogConsumer("scores") { print("[SCORES] " + it.utf8String) } .withLocalCompose(true) @BeforeAll @JvmStatic fun waitForServers() { Awaitility.await().atMost(240, TimeUnit.SECONDS) .pollDelay(Duration.ofSeconds(20)) .pollInterval(Duration.ofSeconds(10)) .ignoreExceptions() .until { given().baseUri("http://${env.getServiceHost("discovery", 8500)}") .port(env.getServicePort("discovery", 8500)) .get("/v1/agent/services") .then() .body("size()", equalTo(5)) true } } } @Test fun testGetCollection() { Awaitility.await().atMost(120, TimeUnit.SECONDS) .pollInterval(Duration.ofSeconds(10)) .ignoreExceptions() .until { given().get("/api/cards/collection_v1_000") .then() .statusCode(200) .body("data.cards.size", greaterThan(10)) true } } @Test fun testGetScores() { Awaitility.await().atMost(120, TimeUnit.SECONDS) .pollInterval(Duration.ofSeconds(10)) .ignoreExceptions() .until { given().accept(ContentType.JSON) .get("/api/scores") .then() .statusCode(200) .body("data.list.size()", greaterThan(0)) true } } @Test fun testCreateUser() { Awaitility.await().atMost(120, TimeUnit.SECONDS) .pollInterval(Duration.ofSeconds(10)) .ignoreExceptions() .until { val id = "foo_testCreateUser_" + System.currentTimeMillis() given().get("/api/user-collections/$id") .then() .statusCode(401) val password = "123456" val cookie = given().contentType(ContentType.JSON) .body(""" { "userId": "$id", "password": "$password" } """.trimIndent()) .post("/api/auth/signUp") .then() .statusCode(201) .header("Set-Cookie", CoreMatchers.not(equalTo(null))) .extract().cookie("SESSION") given().cookie("SESSION", cookie) .put("/api/user-collections/$id") // .then() //could be 400 if AMQP already registered it // .statusCode(201) given().cookie("SESSION", cookie) .get("/api/user-collections/$id") .then() .statusCode(200) true } } @Test fun testAMQPSignUp() { Awaitility.await().atMost(120, TimeUnit.SECONDS) .pollInterval(Duration.ofSeconds(10)) .ignoreExceptions() .until { val id = "foo_testCreateUser_" + System.currentTimeMillis() given().get("/api/auth/user") .then() .statusCode(401) given().put("/api/user-collections/$id") .then() .statusCode(401) given().get("/api/scores/$id") .then() .statusCode(404) val password = "123456" val cookie = given().contentType(ContentType.JSON) .body(""" { "userId": "$id", "password": "$password" } """.trimIndent()) .post("/api/auth/signUp") .then() .statusCode(201) .header("Set-Cookie", CoreMatchers.not(equalTo(null))) .extract().cookie("SESSION") given().cookie("SESSION", cookie) .get("/api/auth/user") .then() .statusCode(200) Awaitility.await().atMost(10, TimeUnit.SECONDS) .pollInterval(Duration.ofSeconds(2)) .ignoreExceptions() .until { given().cookie("SESSION", cookie) .get("/api/user-collections/$id") .then() .statusCode(200) given().get("/api/scores/$id") .then() .statusCode(200) .body("data.score", equalTo(0)) true } true } } @Test fun testUserCollectionAccessControl() { val alice = "alice_testUserCollectionAccessControl_" + System.currentTimeMillis() val eve = "eve_testUserCollectionAccessControl_" + System.currentTimeMillis() given().get("/api/user-collections/$alice").then().statusCode(401) given().put("/api/user-collections/$alice").then().statusCode(401) given().patch("/api/user-collections/$alice").then().statusCode(401) val cookie = given().contentType(ContentType.JSON) .body(""" { "userId": "$eve", "password": "123456" } """.trimIndent()) .post("/api/auth/signUp") .then() .statusCode(201) .header("Set-Cookie", CoreMatchers.not(equalTo(null))) .extract().cookie("SESSION") given().cookie("SESSION", cookie) .get("/api/user-collections/$alice") .then() .statusCode(403) } }
lgpl-3.0
5b24212e3612c3db2419dc7582ad035d
35.395745
121
0.439312
5.564086
false
true
false
false
deva666/anko
anko/idea-plugin/xml-converter/src/org/jetbrains/kotlin/android/xmlconverter/Util.kt
2
2066
/* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.android.xmlconverter import com.google.gson.Gson import com.google.gson.reflect.TypeToken import org.jetbrains.kotlin.android.attrs.Attrs import org.jetbrains.kotlin.android.attrs.readResource private val INTENT = " " internal val attrs = Gson().fromJson(readResource("../attrs.json"), Attrs::class.java) internal val viewHierarchy = Gson().fromJson<Map<String, List<String>>>(readResource("../views.json"), (object : TypeToken<Map<String, List<String>>>() {}).type) internal data class KeyValuePair(val key: String, val value: String) { override fun toString() = if (value.isNotEmpty()) "$key = $value" else key } internal operator fun String.times(value: String) = KeyValuePair(this, value) internal fun <T: Any, R: Any> List<T>.findFirst(transformer: (T) -> R?): R? { for (item in this) { val r = transformer(item) if (r != null) return r } return null } internal fun String.indent(width: Int): String { if (isEmpty()) return this val intent = INTENT.repeat(width) return split('\n').map { intent + it }.joinToString("\n") } internal fun String.swapCamelCase(): String { val ch = withIndex().firstOrNull { Character.isUpperCase(it.value) } return if (ch == null) this else substring(ch.index).toLowerCase() + substring(0, ch.index).firstCapital() } internal fun String.firstCapital(): String = if (isEmpty()) this else Character.toUpperCase(this[0]) + substring(1)
apache-2.0
5fae19b42cf77aa738d2fa885843a243
35.910714
115
0.710068
3.804788
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/SpanStyle.kt
3
37851
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shadow import androidx.compose.ui.graphics.drawscope.DrawStyle import androidx.compose.ui.graphics.drawscope.Fill import androidx.compose.ui.graphics.lerp import androidx.compose.ui.graphics.takeOrElse import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontSynthesis import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.lerp import androidx.compose.ui.text.intl.LocaleList import androidx.compose.ui.text.style.BaselineShift import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextForegroundStyle import androidx.compose.ui.text.style.TextGeometricTransform import androidx.compose.ui.text.style.lerp import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.isUnspecified import androidx.compose.ui.unit.lerp import androidx.compose.ui.unit.sp /** The default font size if none is specified. */ private val DefaultFontSize = 14.sp private val DefaultLetterSpacing = 0.sp private val DefaultBackgroundColor = Color.Transparent // TODO(nona): Introduce TextUnit.Original for representing "do not change the original result". // Need to distinguish from Inherit. private val DefaultColor = Color.Black /** * Styling configuration for a text span. This configuration only allows character level styling, * in order to set paragraph level styling such as line height, or text alignment please see * [ParagraphStyle]. * * @sample androidx.compose.ui.text.samples.SpanStyleSample * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderSample * * @param fontSize The size of glyphs (in logical pixels) to use when painting the text. This * may be [TextUnit.Unspecified] for inheriting from another [SpanStyle]. * @param fontWeight The typeface thickness to use when painting the text (e.g., bold). * @param fontStyle The typeface variant to use when drawing the letters (e.g., italic). * @param fontSynthesis Whether to synthesize font weight and/or style when the requested weight or * style cannot be found in the provided font family. * @param fontFamily The font family to be used when rendering the text. * @param fontFeatureSettings The advanced typography settings provided by font. The format is the * same as the CSS font-feature-settings attribute: * https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop * @param letterSpacing The amount of space (in em) to add between each letter. * @param baselineShift The amount by which the text is shifted up from the current baseline. * @param textGeometricTransform The geometric transformation applied the text. * @param localeList The locale list used to select region-specific glyphs. * @param background The background color for the text. * @param textDecoration The decorations to paint on the text (e.g., an underline). * @param shadow The shadow effect applied on the text. * @param platformStyle Platform specific [SpanStyle] parameters. * @param drawStyle Drawing style of text, whether fill in the text while drawing or stroke around * the edges. * * @see AnnotatedString * @see TextStyle * @see ParagraphStyle */ @Immutable class SpanStyle internal constructor( // The fill to draw text, a unified representation of Color and Brush. internal val textForegroundStyle: TextForegroundStyle, val fontSize: TextUnit = TextUnit.Unspecified, val fontWeight: FontWeight? = null, val fontStyle: FontStyle? = null, val fontSynthesis: FontSynthesis? = null, val fontFamily: FontFamily? = null, val fontFeatureSettings: String? = null, val letterSpacing: TextUnit = TextUnit.Unspecified, val baselineShift: BaselineShift? = null, val textGeometricTransform: TextGeometricTransform? = null, val localeList: LocaleList? = null, val background: Color = Color.Unspecified, val textDecoration: TextDecoration? = null, val shadow: Shadow? = null, val platformStyle: PlatformSpanStyle? = null, @Suppress("OPT_IN_MARKER_ON_WRONG_TARGET") @property:ExperimentalTextApi @get:ExperimentalTextApi val drawStyle: DrawStyle? = null ) { /** * Styling configuration for a text span. This configuration only allows character level styling, * in order to set paragraph level styling such as line height, or text alignment please see * [ParagraphStyle]. * * @sample androidx.compose.ui.text.samples.SpanStyleSample * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderSample * * @param color The text color. * @param fontSize The size of glyphs (in logical pixels) to use when painting the text. This * may be [TextUnit.Unspecified] for inheriting from another [SpanStyle]. * @param fontWeight The typeface thickness to use when painting the text (e.g., bold). * @param fontStyle The typeface variant to use when drawing the letters (e.g., italic). * @param fontSynthesis Whether to synthesize font weight and/or style when the requested weight * or style cannot be found in the provided font family. * @param fontFamily The font family to be used when rendering the text. * @param fontFeatureSettings The advanced typography settings provided by font. The format is * the same as the CSS font-feature-settings attribute: * https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop * @param letterSpacing The amount of space (in em) to add between each letter. * @param baselineShift The amount by which the text is shifted up from the current baseline. * @param textGeometricTransform The geometric transformation applied the text. * @param localeList The locale list used to select region-specific glyphs. * @param background The background color for the text. * @param textDecoration The decorations to paint on the text (e.g., an underline). * @param shadow The shadow effect applied on the text. * * @see AnnotatedString * @see TextStyle * @see ParagraphStyle */ constructor( color: Color = Color.Unspecified, fontSize: TextUnit = TextUnit.Unspecified, fontWeight: FontWeight? = null, fontStyle: FontStyle? = null, fontSynthesis: FontSynthesis? = null, fontFamily: FontFamily? = null, fontFeatureSettings: String? = null, letterSpacing: TextUnit = TextUnit.Unspecified, baselineShift: BaselineShift? = null, textGeometricTransform: TextGeometricTransform? = null, localeList: LocaleList? = null, background: Color = Color.Unspecified, textDecoration: TextDecoration? = null, shadow: Shadow? = null ) : this( textForegroundStyle = TextForegroundStyle.from(color), fontSize = fontSize, fontWeight = fontWeight, fontStyle = fontStyle, fontSynthesis = fontSynthesis, fontFamily = fontFamily, fontFeatureSettings = fontFeatureSettings, letterSpacing = letterSpacing, baselineShift = baselineShift, textGeometricTransform = textGeometricTransform, localeList = localeList, background = background, textDecoration = textDecoration, shadow = shadow, platformStyle = null ) /** * Styling configuration for a text span. This configuration only allows character level styling, * in order to set paragraph level styling such as line height, or text alignment please see * [ParagraphStyle]. * * @sample androidx.compose.ui.text.samples.SpanStyleSample * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderSample * * @param color The color to draw the text. * @param fontSize The size of glyphs (in logical pixels) to use when painting the text. This * may be [TextUnit.Unspecified] for inheriting from another [SpanStyle]. * @param fontWeight The typeface thickness to use when painting the text (e.g., bold). * @param fontStyle The typeface variant to use when drawing the letters (e.g., italic). * @param fontSynthesis Whether to synthesize font weight and/or style when the requested weight * or style cannot be found in the provided font family. * @param fontFamily The font family to be used when rendering the text. * @param fontFeatureSettings The advanced typography settings provided by font. The format is * the same as the CSS font-feature-settings attribute: * https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop * @param letterSpacing The amount of space (in em) to add between each letter. * @param baselineShift The amount by which the text is shifted up from the current baseline. * @param textGeometricTransform The geometric transformation applied the text. * @param localeList The locale list used to select region-specific glyphs. * @param background The background color for the text. * @param textDecoration The decorations to paint on the text (e.g., an underline). * @param shadow The shadow effect applied on the text. * @param platformStyle Platform specific [SpanStyle] parameters. * * @see AnnotatedString * @see TextStyle * @see ParagraphStyle */ constructor( color: Color = Color.Unspecified, fontSize: TextUnit = TextUnit.Unspecified, fontWeight: FontWeight? = null, fontStyle: FontStyle? = null, fontSynthesis: FontSynthesis? = null, fontFamily: FontFamily? = null, fontFeatureSettings: String? = null, letterSpacing: TextUnit = TextUnit.Unspecified, baselineShift: BaselineShift? = null, textGeometricTransform: TextGeometricTransform? = null, localeList: LocaleList? = null, background: Color = Color.Unspecified, textDecoration: TextDecoration? = null, shadow: Shadow? = null, platformStyle: PlatformSpanStyle? = null ) : this( textForegroundStyle = TextForegroundStyle.from(color), fontSize = fontSize, fontWeight = fontWeight, fontStyle = fontStyle, fontSynthesis = fontSynthesis, fontFamily = fontFamily, fontFeatureSettings = fontFeatureSettings, letterSpacing = letterSpacing, baselineShift = baselineShift, textGeometricTransform = textGeometricTransform, localeList = localeList, background = background, textDecoration = textDecoration, shadow = shadow, platformStyle = platformStyle ) /** * Styling configuration for a text span. This configuration only allows character level styling, * in order to set paragraph level styling such as line height, or text alignment please see * [ParagraphStyle]. * * @sample androidx.compose.ui.text.samples.SpanStyleSample * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderSample * * @param color The color to draw the text. * @param fontSize The size of glyphs (in logical pixels) to use when painting the text. This * may be [TextUnit.Unspecified] for inheriting from another [SpanStyle]. * @param fontWeight The typeface thickness to use when painting the text (e.g., bold). * @param fontStyle The typeface variant to use when drawing the letters (e.g., italic). * @param fontSynthesis Whether to synthesize font weight and/or style when the requested weight * or style cannot be found in the provided font family. * @param fontFamily The font family to be used when rendering the text. * @param fontFeatureSettings The advanced typography settings provided by font. The format is * the same as the CSS font-feature-settings attribute: * https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop * @param letterSpacing The amount of space (in em) to add between each letter. * @param baselineShift The amount by which the text is shifted up from the current baseline. * @param textGeometricTransform The geometric transformation applied the text. * @param localeList The locale list used to select region-specific glyphs. * @param background The background color for the text. * @param textDecoration The decorations to paint on the text (e.g., an underline). * @param shadow The shadow effect applied on the text. * @param platformStyle Platform specific [SpanStyle] parameters. * @param drawStyle Drawing style of text, whether fill in the text while drawing or stroke * around the edges. * * @see AnnotatedString * @see TextStyle * @see ParagraphStyle */ @ExperimentalTextApi constructor( color: Color = Color.Unspecified, fontSize: TextUnit = TextUnit.Unspecified, fontWeight: FontWeight? = null, fontStyle: FontStyle? = null, fontSynthesis: FontSynthesis? = null, fontFamily: FontFamily? = null, fontFeatureSettings: String? = null, letterSpacing: TextUnit = TextUnit.Unspecified, baselineShift: BaselineShift? = null, textGeometricTransform: TextGeometricTransform? = null, localeList: LocaleList? = null, background: Color = Color.Unspecified, textDecoration: TextDecoration? = null, shadow: Shadow? = null, platformStyle: PlatformSpanStyle? = null, drawStyle: DrawStyle? = null ) : this( textForegroundStyle = TextForegroundStyle.from(color), fontSize = fontSize, fontWeight = fontWeight, fontStyle = fontStyle, fontSynthesis = fontSynthesis, fontFamily = fontFamily, fontFeatureSettings = fontFeatureSettings, letterSpacing = letterSpacing, baselineShift = baselineShift, textGeometricTransform = textGeometricTransform, localeList = localeList, background = background, textDecoration = textDecoration, shadow = shadow, platformStyle = platformStyle, drawStyle = drawStyle ) /** * Styling configuration for a text span. This configuration only allows character level styling, * in order to set paragraph level styling such as line height, or text alignment please see * [ParagraphStyle]. * * @sample androidx.compose.ui.text.samples.SpanStyleBrushSample * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderSample * * @param brush The brush to use when painting the text. If brush is given as null, it will be * treated as unspecified. It is equivalent to calling the alternative color constructor with * [Color.Unspecified] * @param alpha Opacity to be applied to [brush] from 0.0f to 1.0f representing fully * transparent to fully opaque respectively. * @param fontSize The size of glyphs (in logical pixels) to use when painting the text. This * may be [TextUnit.Unspecified] for inheriting from another [SpanStyle]. * @param fontWeight The typeface thickness to use when painting the text (e.g., bold). * @param fontStyle The typeface variant to use when drawing the letters (e.g., italic). * @param fontSynthesis Whether to synthesize font weight and/or style when the requested weight * or style cannot be found in the provided font family. * @param fontFamily The font family to be used when rendering the text. * @param fontFeatureSettings The advanced typography settings provided by font. The format is * the same as the CSS font-feature-settings attribute: * https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop * @param letterSpacing The amount of space (in em) to add between each letter. * @param baselineShift The amount by which the text is shifted up from the current baseline. * @param textGeometricTransform The geometric transformation applied the text. * @param localeList The locale list used to select region-specific glyphs. * @param background The background color for the text. * @param textDecoration The decorations to paint on the text (e.g., an underline). * @param shadow The shadow effect applied on the text. * @param platformStyle Platform specific [SpanStyle] parameters. * @param drawStyle Drawing style of text, whether fill in the text while drawing or stroke * around the edges. * * @see AnnotatedString * @see TextStyle * @see ParagraphStyle */ @ExperimentalTextApi constructor( brush: Brush?, alpha: Float = Float.NaN, fontSize: TextUnit = TextUnit.Unspecified, fontWeight: FontWeight? = null, fontStyle: FontStyle? = null, fontSynthesis: FontSynthesis? = null, fontFamily: FontFamily? = null, fontFeatureSettings: String? = null, letterSpacing: TextUnit = TextUnit.Unspecified, baselineShift: BaselineShift? = null, textGeometricTransform: TextGeometricTransform? = null, localeList: LocaleList? = null, background: Color = Color.Unspecified, textDecoration: TextDecoration? = null, shadow: Shadow? = null, platformStyle: PlatformSpanStyle? = null, drawStyle: DrawStyle? = null ) : this( textForegroundStyle = TextForegroundStyle.from(brush, alpha), fontSize = fontSize, fontWeight = fontWeight, fontStyle = fontStyle, fontSynthesis = fontSynthesis, fontFamily = fontFamily, fontFeatureSettings = fontFeatureSettings, letterSpacing = letterSpacing, baselineShift = baselineShift, textGeometricTransform = textGeometricTransform, localeList = localeList, background = background, textDecoration = textDecoration, shadow = shadow, platformStyle = platformStyle, drawStyle = drawStyle ) /** * Color to draw text. */ val color: Color get() = this.textForegroundStyle.color /** * Brush to draw text. If not null, overrides [color]. */ @ExperimentalTextApi @Suppress("OPT_IN_MARKER_ON_WRONG_TARGET") @get:ExperimentalTextApi val brush: Brush? get() = this.textForegroundStyle.brush /** * Opacity of text. This value is either provided along side Brush, or via alpha channel in * color. */ @ExperimentalTextApi @Suppress("OPT_IN_MARKER_ON_WRONG_TARGET") @get:ExperimentalTextApi val alpha: Float get() = this.textForegroundStyle.alpha /** * Returns a new span style that is a combination of this style and the given [other] style. * * [other] span style's null or inherit properties are replaced with the non-null properties of * this span style. Another way to think of it is that the "missing" properties of the [other] * style are _filled_ by the properties of this style. * * If the given span style is null, returns this span style. */ @OptIn(ExperimentalTextApi::class) @Stable fun merge(other: SpanStyle? = null): SpanStyle { if (other == null) return this return SpanStyle( textForegroundStyle = textForegroundStyle.merge(other.textForegroundStyle), fontFamily = other.fontFamily ?: this.fontFamily, fontSize = if (!other.fontSize.isUnspecified) other.fontSize else this.fontSize, fontWeight = other.fontWeight ?: this.fontWeight, fontStyle = other.fontStyle ?: this.fontStyle, fontSynthesis = other.fontSynthesis ?: this.fontSynthesis, fontFeatureSettings = other.fontFeatureSettings ?: this.fontFeatureSettings, letterSpacing = if (!other.letterSpacing.isUnspecified) { other.letterSpacing } else { this.letterSpacing }, baselineShift = other.baselineShift ?: this.baselineShift, textGeometricTransform = other.textGeometricTransform ?: this.textGeometricTransform, localeList = other.localeList ?: this.localeList, background = other.background.takeOrElse { this.background }, textDecoration = other.textDecoration ?: this.textDecoration, shadow = other.shadow ?: this.shadow, platformStyle = mergePlatformStyle(other.platformStyle), drawStyle = other.drawStyle ?: this.drawStyle ) } private fun mergePlatformStyle(other: PlatformSpanStyle?): PlatformSpanStyle? { if (platformStyle == null) return other if (other == null) return platformStyle return platformStyle.merge(other) } /** * Plus operator overload that applies a [merge]. */ @Stable operator fun plus(other: SpanStyle): SpanStyle = this.merge(other) @OptIn(ExperimentalTextApi::class) fun copy( color: Color = this.color, fontSize: TextUnit = this.fontSize, fontWeight: FontWeight? = this.fontWeight, fontStyle: FontStyle? = this.fontStyle, fontSynthesis: FontSynthesis? = this.fontSynthesis, fontFamily: FontFamily? = this.fontFamily, fontFeatureSettings: String? = this.fontFeatureSettings, letterSpacing: TextUnit = this.letterSpacing, baselineShift: BaselineShift? = this.baselineShift, textGeometricTransform: TextGeometricTransform? = this.textGeometricTransform, localeList: LocaleList? = this.localeList, background: Color = this.background, textDecoration: TextDecoration? = this.textDecoration, shadow: Shadow? = this.shadow ): SpanStyle { return SpanStyle( textForegroundStyle = if (color == this.color) { textForegroundStyle } else { TextForegroundStyle.from(color) }, fontSize = fontSize, fontWeight = fontWeight, fontStyle = fontStyle, fontSynthesis = fontSynthesis, fontFamily = fontFamily, fontFeatureSettings = fontFeatureSettings, letterSpacing = letterSpacing, baselineShift = baselineShift, textGeometricTransform = textGeometricTransform, localeList = localeList, background = background, textDecoration = textDecoration, shadow = shadow, platformStyle = this.platformStyle, drawStyle = this.drawStyle ) } fun copy( color: Color = this.color, fontSize: TextUnit = this.fontSize, fontWeight: FontWeight? = this.fontWeight, fontStyle: FontStyle? = this.fontStyle, fontSynthesis: FontSynthesis? = this.fontSynthesis, fontFamily: FontFamily? = this.fontFamily, fontFeatureSettings: String? = this.fontFeatureSettings, letterSpacing: TextUnit = this.letterSpacing, baselineShift: BaselineShift? = this.baselineShift, textGeometricTransform: TextGeometricTransform? = this.textGeometricTransform, localeList: LocaleList? = this.localeList, background: Color = this.background, textDecoration: TextDecoration? = this.textDecoration, shadow: Shadow? = this.shadow, platformStyle: PlatformSpanStyle? = this.platformStyle ): SpanStyle { return SpanStyle( textForegroundStyle = if (color == this.color) { textForegroundStyle } else { TextForegroundStyle.from(color) }, fontSize = fontSize, fontWeight = fontWeight, fontStyle = fontStyle, fontSynthesis = fontSynthesis, fontFamily = fontFamily, fontFeatureSettings = fontFeatureSettings, letterSpacing = letterSpacing, baselineShift = baselineShift, textGeometricTransform = textGeometricTransform, localeList = localeList, background = background, textDecoration = textDecoration, shadow = shadow, platformStyle = platformStyle ) } @ExperimentalTextApi fun copy( color: Color = this.color, fontSize: TextUnit = this.fontSize, fontWeight: FontWeight? = this.fontWeight, fontStyle: FontStyle? = this.fontStyle, fontSynthesis: FontSynthesis? = this.fontSynthesis, fontFamily: FontFamily? = this.fontFamily, fontFeatureSettings: String? = this.fontFeatureSettings, letterSpacing: TextUnit = this.letterSpacing, baselineShift: BaselineShift? = this.baselineShift, textGeometricTransform: TextGeometricTransform? = this.textGeometricTransform, localeList: LocaleList? = this.localeList, background: Color = this.background, textDecoration: TextDecoration? = this.textDecoration, shadow: Shadow? = this.shadow, platformStyle: PlatformSpanStyle? = this.platformStyle, drawStyle: DrawStyle? = this.drawStyle ): SpanStyle { return SpanStyle( textForegroundStyle = if (color == this.color) { textForegroundStyle } else { TextForegroundStyle.from(color) }, fontSize = fontSize, fontWeight = fontWeight, fontStyle = fontStyle, fontSynthesis = fontSynthesis, fontFamily = fontFamily, fontFeatureSettings = fontFeatureSettings, letterSpacing = letterSpacing, baselineShift = baselineShift, textGeometricTransform = textGeometricTransform, localeList = localeList, background = background, textDecoration = textDecoration, shadow = shadow, platformStyle = platformStyle, drawStyle = drawStyle ) } @ExperimentalTextApi fun copy( brush: Brush?, alpha: Float = this.alpha, fontSize: TextUnit = this.fontSize, fontWeight: FontWeight? = this.fontWeight, fontStyle: FontStyle? = this.fontStyle, fontSynthesis: FontSynthesis? = this.fontSynthesis, fontFamily: FontFamily? = this.fontFamily, fontFeatureSettings: String? = this.fontFeatureSettings, letterSpacing: TextUnit = this.letterSpacing, baselineShift: BaselineShift? = this.baselineShift, textGeometricTransform: TextGeometricTransform? = this.textGeometricTransform, localeList: LocaleList? = this.localeList, background: Color = this.background, textDecoration: TextDecoration? = this.textDecoration, shadow: Shadow? = this.shadow, platformStyle: PlatformSpanStyle? = this.platformStyle, drawStyle: DrawStyle? = this.drawStyle ): SpanStyle { return SpanStyle( textForegroundStyle = TextForegroundStyle.from(brush, alpha), fontSize = fontSize, fontWeight = fontWeight, fontStyle = fontStyle, fontSynthesis = fontSynthesis, fontFamily = fontFamily, fontFeatureSettings = fontFeatureSettings, letterSpacing = letterSpacing, baselineShift = baselineShift, textGeometricTransform = textGeometricTransform, localeList = localeList, background = background, textDecoration = textDecoration, shadow = shadow, platformStyle = platformStyle, drawStyle = drawStyle ) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SpanStyle) return false return hasSameLayoutAffectingAttributes(other) && hasSameNonLayoutAttributes(other) } internal fun hasSameLayoutAffectingAttributes(other: SpanStyle): Boolean { if (this === other) return true if (fontSize != other.fontSize) return false if (fontWeight != other.fontWeight) return false if (fontStyle != other.fontStyle) return false if (fontSynthesis != other.fontSynthesis) return false if (fontFamily != other.fontFamily) return false if (fontFeatureSettings != other.fontFeatureSettings) return false if (letterSpacing != other.letterSpacing) return false if (baselineShift != other.baselineShift) return false if (textGeometricTransform != other.textGeometricTransform) return false if (localeList != other.localeList) return false if (background != other.background) return false if (platformStyle != other.platformStyle) return false return true } @OptIn(ExperimentalTextApi::class) private fun hasSameNonLayoutAttributes(other: SpanStyle): Boolean { if (textForegroundStyle != other.textForegroundStyle) return false if (textDecoration != other.textDecoration) return false if (shadow != other.shadow) return false if (drawStyle != other.drawStyle) return false return true } @OptIn(ExperimentalTextApi::class) override fun hashCode(): Int { var result = color.hashCode() result = 31 * result + brush.hashCode() result = 31 * result + alpha.hashCode() result = 31 * result + fontSize.hashCode() result = 31 * result + (fontWeight?.hashCode() ?: 0) result = 31 * result + (fontStyle?.hashCode() ?: 0) result = 31 * result + (fontSynthesis?.hashCode() ?: 0) result = 31 * result + (fontFamily?.hashCode() ?: 0) result = 31 * result + (fontFeatureSettings?.hashCode() ?: 0) result = 31 * result + letterSpacing.hashCode() result = 31 * result + (baselineShift?.hashCode() ?: 0) result = 31 * result + (textGeometricTransform?.hashCode() ?: 0) result = 31 * result + (localeList?.hashCode() ?: 0) result = 31 * result + background.hashCode() result = 31 * result + (textDecoration?.hashCode() ?: 0) result = 31 * result + (shadow?.hashCode() ?: 0) result = 31 * result + (platformStyle?.hashCode() ?: 0) result = 31 * result + (drawStyle?.hashCode() ?: 0) return result } internal fun hashCodeLayoutAffectingAttributes(): Int { var result = fontSize.hashCode() result = 31 * result + (fontWeight?.hashCode() ?: 0) result = 31 * result + (fontStyle?.hashCode() ?: 0) result = 31 * result + (fontSynthesis?.hashCode() ?: 0) result = 31 * result + (fontFamily?.hashCode() ?: 0) result = 31 * result + (fontFeatureSettings?.hashCode() ?: 0) result = 31 * result + letterSpacing.hashCode() result = 31 * result + (baselineShift?.hashCode() ?: 0) result = 31 * result + (textGeometricTransform?.hashCode() ?: 0) result = 31 * result + (localeList?.hashCode() ?: 0) result = 31 * result + background.hashCode() result = 31 * result + (platformStyle?.hashCode() ?: 0) return result } @OptIn(ExperimentalTextApi::class) override fun toString(): String { return "SpanStyle(" + "color=$color, " + "brush=$brush, " + "alpha=$alpha, " + "fontSize=$fontSize, " + "fontWeight=$fontWeight, " + "fontStyle=$fontStyle, " + "fontSynthesis=$fontSynthesis, " + "fontFamily=$fontFamily, " + "fontFeatureSettings=$fontFeatureSettings, " + "letterSpacing=$letterSpacing, " + "baselineShift=$baselineShift, " + "textGeometricTransform=$textGeometricTransform, " + "localeList=$localeList, " + "background=$background, " + "textDecoration=$textDecoration, " + "shadow=$shadow, " + "platformStyle=$platformStyle, " + "drawStyle=$drawStyle" + ")" } } /** * @param a An sp value. Maybe [TextUnit.Unspecified] * @param b An sp value. Maybe [TextUnit.Unspecified] */ internal fun lerpTextUnitInheritable(a: TextUnit, b: TextUnit, t: Float): TextUnit { if (a.isUnspecified || b.isUnspecified) return lerpDiscrete(a, b, t) return lerp(a, b, t) } /** * Lerp between two values that cannot be transitioned. Returns [a] if [fraction] is smaller than * 0.5 otherwise [b]. */ internal fun <T> lerpDiscrete(a: T, b: T, fraction: Float): T = if (fraction < 0.5) a else b /** * Interpolate between two span styles. * * This will not work well if the styles don't set the same fields. * * The [fraction] argument represents position on the timeline, with 0.0 meaning * that the interpolation has not started, returning [start] (or something * equivalent to [start]), 1.0 meaning that the interpolation has finished, * returning [stop] (or something equivalent to [stop]), and values in between * meaning that the interpolation is at the relevant point on the timeline * between [start] and [stop]. The interpolation can be extrapolated beyond 0.0 and * 1.0, so negative values and values greater than 1.0 are valid. */ @OptIn(ExperimentalTextApi::class) fun lerp(start: SpanStyle, stop: SpanStyle, fraction: Float): SpanStyle { return SpanStyle( textForegroundStyle = lerp(start.textForegroundStyle, stop.textForegroundStyle, fraction), fontFamily = lerpDiscrete( start.fontFamily, stop.fontFamily, fraction ), fontSize = lerpTextUnitInheritable(start.fontSize, stop.fontSize, fraction), fontWeight = lerp( start.fontWeight ?: FontWeight.Normal, stop.fontWeight ?: FontWeight.Normal, fraction ), fontStyle = lerpDiscrete( start.fontStyle, stop.fontStyle, fraction ), fontSynthesis = lerpDiscrete( start.fontSynthesis, stop.fontSynthesis, fraction ), fontFeatureSettings = lerpDiscrete( start.fontFeatureSettings, stop.fontFeatureSettings, fraction ), letterSpacing = lerpTextUnitInheritable( start.letterSpacing, stop.letterSpacing, fraction ), baselineShift = lerp( start.baselineShift ?: BaselineShift(0f), stop.baselineShift ?: BaselineShift(0f), fraction ), textGeometricTransform = lerp( start.textGeometricTransform ?: TextGeometricTransform.None, stop.textGeometricTransform ?: TextGeometricTransform.None, fraction ), localeList = lerpDiscrete(start.localeList, stop.localeList, fraction), background = lerp( start.background, stop.background, fraction ), textDecoration = lerpDiscrete( start.textDecoration, stop.textDecoration, fraction ), shadow = lerp( start.shadow ?: Shadow(), stop.shadow ?: Shadow(), fraction ), platformStyle = lerpPlatformStyle(start.platformStyle, stop.platformStyle, fraction), drawStyle = lerpDiscrete( start.drawStyle, stop.drawStyle, fraction ) ) } private fun lerpPlatformStyle( start: PlatformSpanStyle?, stop: PlatformSpanStyle?, fraction: Float ): PlatformSpanStyle? { if (start == null && stop == null) return null val startNonNull = start ?: PlatformSpanStyle.Default val stopNonNull = stop ?: PlatformSpanStyle.Default return lerp(startNonNull, stopNonNull, fraction) } @OptIn(ExperimentalTextApi::class) internal fun resolveSpanStyleDefaults(style: SpanStyle) = SpanStyle( textForegroundStyle = style.textForegroundStyle.takeOrElse { TextForegroundStyle.from(DefaultColor) }, fontSize = if (style.fontSize.isUnspecified) DefaultFontSize else style.fontSize, fontWeight = style.fontWeight ?: FontWeight.Normal, fontStyle = style.fontStyle ?: FontStyle.Normal, fontSynthesis = style.fontSynthesis ?: FontSynthesis.All, fontFamily = style.fontFamily ?: FontFamily.Default, fontFeatureSettings = style.fontFeatureSettings ?: "", letterSpacing = if (style.letterSpacing.isUnspecified) { DefaultLetterSpacing } else { style.letterSpacing }, baselineShift = style.baselineShift ?: BaselineShift.None, textGeometricTransform = style.textGeometricTransform ?: TextGeometricTransform.None, localeList = style.localeList ?: LocaleList.current, background = style.background.takeOrElse { DefaultBackgroundColor }, textDecoration = style.textDecoration ?: TextDecoration.None, shadow = style.shadow ?: Shadow.None, platformStyle = style.platformStyle, drawStyle = style.drawStyle ?: Fill )
apache-2.0
612652948d390ee4ff01e1f687dad581
43.219626
101
0.671026
4.885261
false
false
false
false
djkovrik/YapTalker
app/src/main/java/com/sedsoftware/yaptalker/presentation/mapper/NewsModelMapper.kt
1
1994
package com.sedsoftware.yaptalker.presentation.mapper import com.sedsoftware.yaptalker.data.extensions.getLastDigits import com.sedsoftware.yaptalker.domain.entity.base.NewsItem import com.sedsoftware.yaptalker.presentation.mapper.util.DateTransformer import com.sedsoftware.yaptalker.presentation.mapper.util.TextTransformer import com.sedsoftware.yaptalker.presentation.mapper.util.VideoTypeDetector import com.sedsoftware.yaptalker.presentation.model.base.NewsItemModel import io.reactivex.functions.Function import javax.inject.Inject class NewsModelMapper @Inject constructor( private val textTransformer: TextTransformer, private val dateTransformer: DateTransformer, private val videoTypeDetector: VideoTypeDetector ) : Function<List<NewsItem>, List<NewsItemModel>> { override fun apply(from: List<NewsItem>): List<NewsItemModel> = from.map { mapItem(it) } private fun mapItem(item: NewsItem): NewsItemModel = NewsItemModel( title = item.title, link = item.link, topicId = item.id, rating = textTransformer.transformRankToFormattedText(item.rating), images = item.images, videos = item.videos, videosRaw = item.videosRaw, videosLinks = item.videosLinks.map { link -> if (link.contains("yapfiles.ru")) link else "" }, videoTypes = item.videos.map { videoTypeDetector.detectVideoType(it) }, author = item.author, authorLink = item.authorLink, date = dateTransformer.transformDateToShortView(item.date), forumName = textTransformer.transformNewsForumTitle(item.forumName), forumLink = item.forumLink, forumId = item.forumLink.getLastDigits(), comments = textTransformer.transformCommentsLabel(item.comments), cleanedDescription = textTransformer.transformHtmlToSpanned(item.cleanedDescription), isYapLink = item.isYapLink ) }
apache-2.0
cb638f85b2798f9e19ad79af795a0019
46.47619
106
0.717653
4.552511
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/mixin/insight/MixinEntryPoint.kt
1
2791
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.insight import com.demonwav.mcdev.platform.mixin.handlers.InjectorAnnotationHandler import com.demonwav.mcdev.platform.mixin.handlers.MixinAnnotationHandler import com.demonwav.mcdev.util.toTypedArray import com.intellij.codeInspection.reference.RefElement import com.intellij.codeInspection.visibility.EntryPointWithVisibilityLevel import com.intellij.psi.PsiElement import com.intellij.psi.PsiMember import com.intellij.psi.PsiMethod import com.intellij.psi.util.PsiUtil import com.intellij.util.xmlb.XmlSerializer import org.jdom.Element class MixinEntryPoint : EntryPointWithVisibilityLevel() { @JvmField var MIXIN_ENTRY_POINT = true override fun getId() = "mixin" override fun getDisplayName() = "Mixin injectors" override fun getTitle() = "Suggest private visibility level for Mixin injectors" // TODO: support more handlers than the builtin // need to find a way to access the project for that override fun getIgnoreAnnotations() = MixinAnnotationHandler.getBuiltinHandlers() .filter { (_, handler) -> handler.isEntryPoint } .map { (name, _) -> name } .toTypedArray() override fun isEntryPoint(element: PsiElement): Boolean { if (element !is PsiMethod) { return false } val project = element.project for (annotation in element.annotations) { val qName = annotation.qualifiedName ?: continue val handler = MixinAnnotationHandler.forMixinAnnotation(qName, project) if (handler != null && handler.isEntryPoint) { return true } } return false } override fun isEntryPoint(refElement: RefElement, psiElement: PsiElement) = isEntryPoint(psiElement) override fun getMinVisibilityLevel(member: PsiMember): Int { if (member !is PsiMethod) { return -1 } val project = member.project for (annotation in member.annotations) { val qName = annotation.qualifiedName ?: continue val handler = MixinAnnotationHandler.forMixinAnnotation(qName, project) if (handler is InjectorAnnotationHandler) { return PsiUtil.ACCESS_LEVEL_PRIVATE } } return -1 } override fun isSelected() = MIXIN_ENTRY_POINT override fun setSelected(selected: Boolean) { MIXIN_ENTRY_POINT = selected } override fun readExternal(element: Element) = XmlSerializer.serializeInto(this, element) override fun writeExternal(element: Element) = XmlSerializer.serializeInto(this, element) }
mit
2b37b40d1a1515bc0d6464328017c301
33.45679
104
0.688284
4.82872
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/util/UriUtils.kt
1
5626
/* * Copyright (C) 2014-2017 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.util import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.net.Uri import org.andstatus.app.service.ConnectionState import org.json.JSONObject import java.net.URL import java.util.* import java.util.function.Function object UriUtils { fun fromAlternativeTags(jso: JSONObject?, tag1: String?, tag2: String?): Uri { var uri = fromJson(jso, tag1) if (isEmpty(uri)) { uri = fromJson(jso, tag2) } return uri } fun nonEmpty(uri: Uri?): Boolean { return !isEmpty(uri) } /** @return true for null also */ fun isEmpty(uri: Uri?): Boolean { return uri == null || Uri.EMPTY == uri } fun fromJson(jsoIn: JSONObject?, pathIn: String?): Uri { if (jsoIn == null || pathIn.isNullOrEmpty()) return Uri.EMPTY val path: Array<String?> = pathIn.split("/".toRegex()).toTypedArray() val jso = if (path.size == 2) jsoIn.optJSONObject(path[0]) else jsoIn val urlTag = if (path.size == 2) path[1] else pathIn return if (jso != null && !urlTag.isNullOrEmpty() && jso.has(urlTag)) { fromString(JsonUtils.optString(jso, urlTag)) } else Uri.EMPTY } fun map(uri: Uri, mapper: Function<String?, String?>): Uri { return fromString(mapper.apply(uri.toString())) } fun toDownloadableOptional(uriString: String?): Optional<Uri> { return toOptional(uriString).filter { obj: Uri -> isDownloadable(obj) } } fun toOptional(uriString: String?): Optional<Uri> { if (uriString.isNullOrEmpty()) return Optional.empty() val uri = fromString(uriString) return if (uri === Uri.EMPTY) Optional.empty() else Optional.of(uri) } fun fromString(strUri: String?): Uri { return if (strUri == null || SharedPreferencesUtil.isEmpty(strUri)) Uri.EMPTY else Uri.parse(strUri.trim { it <= ' ' }) } fun notNull(uri: Uri?): Uri { return uri ?: Uri.EMPTY } fun fromUrl(url: URL?): Uri { return if (url == null) { Uri.EMPTY } else { fromString(url.toExternalForm()) } } /** See http://developer.android.com/guide/topics/providers/document-provider.html */ fun flagsToTakePersistableUriPermission(): Int { var flags = Intent.FLAG_GRANT_READ_URI_PERMISSION flags = flags or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION return flags } /** See http://stackoverflow.com/questions/25999886/android-content-provider-uri-doesnt-work-after-reboot */ fun takePersistableUriPermission(context: Context, uri: Uri, takeFlagsIn: Int) { if (takeFlagsIn and Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION != 0) { val takeFlags = takeFlagsIn and (Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) try { context.getContentResolver().takePersistableUriPermission(uri, takeFlags) } catch (e: SecurityException) { MyLog.i(context, "Exception while taking persistable URI permission for '$uri'", e) } } else { MyLog.i(context, "No persistable URI permission for '$uri'") } } fun isDownloadable(uri: Uri?): Boolean { if (uri != null) { val scheme = uri.scheme if (scheme != null) { when (scheme) { "http", "https", "magnet" -> return true else -> { } } } } return false } fun isRealOid(oid: String?): Boolean { return !nonRealOid(oid) } fun nonRealOid(oid: String?): Boolean { return StringUtil.isEmptyOrTemp(oid) } fun nonEmptyOid(oid: String?): Boolean { return !isEmptyOid(oid) } fun isEmptyOid(oid: String?): Boolean { return SharedPreferencesUtil.isEmpty(oid) } /** * Based on http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-timeouts */ fun getConnectionState(context: Context): ConnectionState { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager? ?: return ConnectionState.UNKNOWN var state = ConnectionState.OFFLINE val networkInfoOnline = connectivityManager.activeNetworkInfo ?: return state state = if (networkInfoOnline.isAvailable && networkInfoOnline.isConnected) { ConnectionState.ONLINE } else { return state } val networkInfoWiFi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) ?: return state if (networkInfoWiFi.isAvailable && networkInfoWiFi.isConnected) { state = ConnectionState.WIFI } return state } }
apache-2.0
c1487b4965185171f2dd2171127e9638
34.383648
125
0.628688
4.334361
false
false
false
false
stfalcon-studio/uaroads_android
app/src/main/java/com/stfalcon/new_uaroads_android/features/record/service/RecordService.kt
1
10373
/* * Copyright (c) 2017 stfalcon.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.stfalcon.new_uaroads_android.features.record.service import android.app.PendingIntent import android.content.Context import android.content.Intent import android.location.Location import android.os.Binder import android.os.Handler import android.os.IBinder import android.support.v7.app.NotificationCompat import android.telephony.PhoneStateListener import android.telephony.TelephonyManager import com.stfalcon.new_uaroads_android.R import com.stfalcon.new_uaroads_android.common.analytics.AnalyticsManager import com.stfalcon.new_uaroads_android.common.database.RealmService import com.stfalcon.new_uaroads_android.common.database.models.TrackRealm import com.stfalcon.new_uaroads_android.ext.log import com.stfalcon.new_uaroads_android.features.main.MainActivity import com.stfalcon.new_uaroads_android.features.record.managers.Point import com.stfalcon.new_uaroads_android.features.record.managers.PointCollector import com.stfalcon.new_uaroads_android.features.tracks.autoupload.AutoUploaderJobScheduler import dagger.android.DaggerService import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.subjects.BehaviorSubject import org.jetbrains.anko.intentFor import org.jetbrains.anko.toast import java.util.* import javax.inject.Inject /* * Created by Anton Bevza on 4/20/17. */ class RecordService : DaggerService(), IRecordService { //region Static companion object { val STATE_IDLE = 1 val STATE_RECORD = 2 val STATE_PAUSE = 3 val KEY_ACTION = "action" val ACTION_START_INDEPENDENTLY = "start_independently" val ACTION_STOP_INDEPENDENTLY = "stop_independently" val ACTION_START_WITH_NAVIGATOR = "start_with_navigator" val ACTION_STOP_WITH_NAVIGATOR = "stop_with_navigator" fun startIndependently(context: Context) { context.startService(context.intentFor<RecordService>().putExtra(KEY_ACTION, ACTION_START_INDEPENDENTLY)) } fun stopIndependently(context: Context) { context.startService(context.intentFor<RecordService>().putExtra(KEY_ACTION, ACTION_STOP_INDEPENDENTLY)) } } //endregion //region Injection fields @Inject lateinit var pointCollector: PointCollector @Inject lateinit var realmService: RealmService @Inject lateinit var autoUploaderJobScheduler: AutoUploaderJobScheduler @Inject lateinit var analyticsManager: AnalyticsManager @Inject lateinit var telManager: TelephonyManager //endregion //region Public fields val mBinder = LocalBinder() //endregion //region Private fields private val NOTIFICATION = 2525 private lateinit var stateObserver: BehaviorSubject<Int> private lateinit var distanceObserver: BehaviorSubject<Int> private var currentTrackId: String? = null private val disposables = CompositeDisposable() private var isRunningIndependently = false //endregion //region Lifecycle methods override fun onBind(intent: Intent?): IBinder? = mBinder override fun onCreate() { super.onCreate() stateObserver = BehaviorSubject.create() distanceObserver = BehaviorSubject.create() telManager.listen(RecordPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { log("service started") intent?.extras?.let { if (it.containsKey(KEY_ACTION)) { when (it.get(KEY_ACTION)) { ACTION_START_INDEPENDENTLY -> { if (currentTrackId == null) { isRunningIndependently = true startRecord() analyticsManager.sendStartAutoRecord() } } ACTION_STOP_INDEPENDENTLY -> { if (isRunningIndependently && currentTrackId != null) { stopRecord() analyticsManager.sendStopAutoRecord() } } ACTION_START_WITH_NAVIGATOR -> { if (currentTrackId == null) { startRecord() } } ACTION_STOP_WITH_NAVIGATOR -> { if (currentTrackId != null) { stopRecord() } } } } } return START_STICKY } override fun onDestroy() { log("service destroyed") stopRecord() realmService.closeRealm() super.onDestroy() } //endregion //region Public methods override fun startRecord() { stateObserver.onNext(STATE_RECORD) showRecordNotification() currentTrackId = UUID.randomUUID().toString() currentTrackId?.let { realmService.createTrack(it, isRunningIndependently) } disposables.add(pointCollector.getPointObservable() .doOnNext { if (it.type == Point.POINT_TYPE_CP) { log("cp") } else { log("origin") } } .buffer(20) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ points -> currentTrackId?.let { realmService.savePoints(it, points) } }, { if (it is SecurityException) { toast(R.string.error_location_permission_not_granted) } }) ) disposables.add(pointCollector.getFilteredLocationObservable() .buffer(2, 1) .subscribe({ val distance = it[0].distanceTo(it[1]).toInt() // in m currentTrackId?.let { trackId -> realmService.getTrack(trackId).let { val trackDistance = it.distance + distance realmService.updateTrackDistance(trackId, trackDistance) distanceObserver.onNext(trackDistance) } } }, { if (it is SecurityException) { toast(R.string.error_location_permission_not_granted) } }) ) distanceObserver.onNext(0) pointCollector.startCollectionData() } override fun stopRecord() { stopForeground(true) pointCollector.stopCollectionData() disposables.clear() currentTrackId?.let { val track = realmService.getTrack(it) if (track.distance > 100) { realmService.updateTrackStatus(it, TrackRealm.STATUS_NOT_SENT) autoUploaderJobScheduler.scheduleAutoUploadingService() } else { realmService.deleteTrack(it) } } currentTrackId = null stateObserver.onNext(STATE_IDLE) isRunningIndependently = false stopSelf() } override fun pauseRecord() { stateObserver.onNext(STATE_PAUSE) showRecordNotification(pause = true) pointCollector.stopCollectionData() } override fun continueRecord() { stateObserver.onNext(STATE_RECORD) showRecordNotification() pointCollector.startCollectionData() } override fun getStateFlow(): Observable<Int> { return stateObserver } override fun getForceValuesFlow(): Observable<Double> { return pointCollector.getForceValuesObservable() } override fun getTrackDistanceFlow(): Observable<Int> { return distanceObserver } override fun getPureLocationFlow(): Observable<Location> { return pointCollector.getPureLocationObservable() } //endregion //region Private methods private fun showRecordNotification(pause: Boolean = false) { val text = if (pause) getString(R.string.ntf_pause) else getString(R.string.ntf_recording) val contentIntent = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), 0) val mBuilder = NotificationCompat.Builder(this) .setSmallIcon(if (pause) R.drawable.ic_notify_pause else R.drawable.ic_notify_play) .setContentTitle(text) .setContentIntent(contentIntent) .setContentText(getString(R.string.app_name)) as NotificationCompat.Builder startForeground(NOTIFICATION, mBuilder.build()) } //endregion //region LocalBinder inner class LocalBinder : Binder() { internal val service: IRecordService get() = this@RecordService } //endregion //region RecordPhoneStateListener inner class RecordPhoneStateListener : PhoneStateListener() { override fun onCallStateChanged(state: Int, incomingNumber: String?) { when (state) { TelephonyManager.CALL_STATE_IDLE -> { if (currentTrackId != null) { Handler().postDelayed({ continueRecord() }, 3000) } } TelephonyManager.CALL_STATE_RINGING -> { if (currentTrackId != null) { pauseRecord() } } } } } //endregion }
apache-2.0
f2df7ebb6c48f09afef171d14ab97bd3
35.020833
117
0.605514
5.04033
false
false
false
false
rhdunn/xquery-intellij-plugin
src/intellij-compat/src/223/native/com/intellij/compat/openapi/roots/MockContentEntry.kt
1
4385
/* * Copyright (C) 2018, 2022 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.compat.openapi.roots import com.intellij.openapi.roots.* import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.annotations.TestOnly import org.jetbrains.jps.model.JpsElement import org.jetbrains.jps.model.module.JpsModuleSourceRootType @TestOnly @Suppress("NonExtendableApiUsage") open class MockContentEntry : ContentEntry { override fun isSynthetic(): Boolean = TODO() override fun getFile(): VirtualFile? = TODO() override fun getUrl(): String = TODO() override fun getSourceFolders(): Array<SourceFolder> = TODO() override fun getSourceFolders(rootType: JpsModuleSourceRootType<*>): MutableList<SourceFolder> = TODO() override fun getSourceFolders( rootTypes: MutableSet<out JpsModuleSourceRootType<*>> ): MutableList<SourceFolder> = TODO() override fun getSourceFolderFiles(): Array<VirtualFile> = TODO() override fun getExcludeFolders(): Array<ExcludeFolder> = TODO() override fun getExcludeFolderUrls(): MutableList<String> = TODO() override fun getExcludeFolderFiles(): Array<VirtualFile> = TODO() override fun addSourceFolder(file: VirtualFile, isTestSource: Boolean): SourceFolder = TODO() override fun addSourceFolder( file: VirtualFile, isTestSource: Boolean, packagePrefix: String ): SourceFolder = TODO() override fun <P : JpsElement> addSourceFolder( file: VirtualFile, type: JpsModuleSourceRootType<P>, properties: P ): SourceFolder = TODO() override fun <P : JpsElement?> addSourceFolder( file: VirtualFile, type: JpsModuleSourceRootType<P> ): SourceFolder = TODO() override fun addSourceFolder(url: String, isTestSource: Boolean): SourceFolder = TODO() override fun <P : JpsElement?> addSourceFolder(url: String, type: JpsModuleSourceRootType<P>): SourceFolder { TODO("Not yet implemented") } override fun <P : JpsElement?> addSourceFolder( url: String, type: JpsModuleSourceRootType<P>, externalSource: ProjectModelExternalSource ): SourceFolder { TODO("Not yet implemented") } override fun <P : JpsElement?> addSourceFolder( url: String, type: JpsModuleSourceRootType<P>, useSourceOfContentRoot: Boolean ): SourceFolder { TODO("Not yet implemented") } override fun <P : JpsElement> addSourceFolder( url: String, type: JpsModuleSourceRootType<P>, properties: P ): SourceFolder { TODO("Not yet implemented") } override fun <P : JpsElement> addSourceFolder( url: String, type: JpsModuleSourceRootType<P>, properties: P, externalSource: ProjectModelExternalSource? ): SourceFolder { TODO("Not yet implemented") } override fun removeSourceFolder(sourceFolder: SourceFolder): Unit = TODO() override fun clearSourceFolders(): Unit = TODO() override fun addExcludeFolder(file: VirtualFile): ExcludeFolder = TODO() override fun addExcludeFolder(url: String): ExcludeFolder = TODO() override fun addExcludeFolder(url: String, source: ProjectModelExternalSource?): ExcludeFolder = TODO() override fun removeExcludeFolder(excludeFolder: ExcludeFolder): Unit = TODO() override fun removeExcludeFolder(url: String): Boolean = TODO() override fun clearExcludeFolders(): Unit = TODO() override fun getExcludePatterns(): MutableList<String> = TODO() override fun addExcludePattern(pattern: String): Unit = TODO() override fun removeExcludePattern(pattern: String): Unit = TODO() override fun setExcludePatterns(patterns: MutableList<String>): Unit = TODO() override fun getRootModel(): ModuleRootModel = TODO() }
apache-2.0
810653b3b7f77d8e94b453aaa695e8e8
32.219697
113
0.704903
5.104773
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewHolders/SectionViewHolder.kt
1
3018
package com.habitrpg.android.habitica.ui.viewHolders import android.content.Context import android.view.Gravity import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Button import android.widget.LinearLayout import android.widget.Spinner import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.extensions.inflate import com.habitrpg.android.habitica.models.inventory.StableSection class SectionViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val label: TextView = itemView.findViewById(R.id.label) private val selectionSpinner: Spinner? = itemView.findViewById(R.id.classSelectionSpinner) val switchClassButton: Button? = itemView.findViewById(R.id.switch_class_button) internal val notesWrapper: LinearLayout? = itemView.findViewById(R.id.header_notes_wrapper) internal val notesView: TextView? = itemView.findViewById(R.id.headerNotesView) private val countPill: TextView? = itemView.findViewById(R.id.count_pill) var context: Context = itemView.context var spinnerSelectionChanged: (() -> Unit)? = null constructor(parent: ViewGroup) : this(parent.inflate(R.layout.customization_section_header)) init { selectionSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { spinnerSelectionChanged?.invoke() } override fun onItemSelected( parent: AdapterView<*>?, view: View?, position: Int, id: Long ) { spinnerSelectionChanged?.invoke() } } } fun bind(title: String) { try { val stringID = context.resources.getIdentifier("section$title", "string", context.packageName) this.label.text = context.getString(stringID) } catch (e: Exception) { this.label.text = title } } fun bind(section: StableSection) { label.text = section.text if (section.key == "special") { countPill?.visibility = View.GONE } else { countPill?.visibility = View.VISIBLE } label.gravity = Gravity.START countPill?.text = itemView.context.getString(R.string.pet_ownership_fraction, section.ownedCount, section.totalCount) } var spinnerAdapter: ArrayAdapter<CharSequence>? = null set(value) { field = value selectionSpinner?.adapter = field selectionSpinner?.visibility = if (value != null) View.VISIBLE else View.GONE } var selectedItem: Int = 0 get() = selectionSpinner?.selectedItemPosition ?: 0 set(value) { field = value selectionSpinner?.setSelection(field) } }
gpl-3.0
42968f8489ce7797eaa0003fd4a5a4f1
35.804878
125
0.6723
4.693624
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/widget/TaskListWidgetProvider.kt
1
5061
package com.habitrpg.android.habitica.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.content.ComponentName import android.content.Context import android.content.Intent import android.net.Uri import android.widget.RemoteViews import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.data.TaskRepository import com.habitrpg.android.habitica.extensions.withImmutableFlag import com.habitrpg.android.habitica.extensions.withMutableFlag import com.habitrpg.android.habitica.helpers.ExceptionHandler import com.habitrpg.android.habitica.ui.activities.MainActivity import javax.inject.Inject abstract class TaskListWidgetProvider : BaseWidgetProvider() { @Inject lateinit var taskRepository: TaskRepository protected abstract val serviceClass: Class<*> protected abstract val providerClass: Class<*> protected abstract val titleResId: Int private fun setUp() { if (!hasInjected) { hasInjected = true HabiticaBaseApplication.userComponent?.inject(this) } } override fun onReceive(context: Context, intent: Intent) { setUp() if (intent.action == DAILY_ACTION) { val appWidgetId = intent.getIntExtra( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID ) val taskId = intent.getStringExtra(TASK_ID_ITEM) if (taskId != null) { userRepository.getUserFlowable().firstElement().flatMap { user -> taskRepository.taskChecked(user, taskId, up = true, force = false, notifyFunc = null) } .subscribe( { taskDirectionData -> showToastForTaskDirection(context, taskDirectionData) AppWidgetManager.getInstance(context).notifyAppWidgetViewDataChanged(appWidgetId, R.id.list_view) }, ExceptionHandler.rx() ) } } super.onReceive(context, intent) } override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { super.onUpdate(context, appWidgetManager, appWidgetIds) setUp() val thisWidget = ComponentName(context, providerClass) val allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget) for (widgetId in allWidgetIds) { val options = appWidgetManager.getAppWidgetOptions(widgetId) appWidgetManager.partiallyUpdateAppWidget( widgetId, sizeRemoteViews(context, options, widgetId) ) } for (appWidgetId in appWidgetIds) { val intent = Intent(context, serviceClass) intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) intent.data = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)) val rv = RemoteViews(context.packageName, R.layout.widget_task_list) rv.setRemoteAdapter(R.id.list_view, intent) rv.setEmptyView(R.id.list_view, R.id.emptyView) rv.setTextViewText(R.id.widget_title, context.getString(titleResId)) // if the user click on the title: open App val openAppIntent = Intent(context.applicationContext, MainActivity::class.java) val openApp = PendingIntent.getActivity(context, 0, openAppIntent, withImmutableFlag(PendingIntent.FLAG_UPDATE_CURRENT)) rv.setOnClickPendingIntent(R.id.widget_title, openApp) val taskIntent = Intent(context, providerClass) taskIntent.action = DAILY_ACTION taskIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) intent.data = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)) val toastPendingIntent = PendingIntent.getBroadcast( context, 0, taskIntent, withMutableFlag(PendingIntent.FLAG_UPDATE_CURRENT) ) rv.setPendingIntentTemplate(R.id.list_view, toastPendingIntent) appWidgetManager.updateAppWidget(appWidgetId, rv) AppWidgetManager.getInstance(context).notifyAppWidgetViewDataChanged(appWidgetId, R.id.list_view) } super.onUpdate(context, appWidgetManager, appWidgetIds) } override fun layoutResourceId(): Int { return R.layout.widget_task_list } override fun configureRemoteViews( remoteViews: RemoteViews, widgetId: Int, columns: Int, rows: Int ): RemoteViews { return remoteViews } companion object { const val DAILY_ACTION = "com.habitrpg.android.habitica.DAILY_ACTION" const val TASK_ID_ITEM = "com.habitrpg.android.habitica.TASK_ID_ITEM" } }
gpl-3.0
15333ba2d762b25d77fd6f9f525f2400
37.850394
169
0.648884
5.13286
false
false
false
false
kesmarag/megaptera
src/main/org/kesmarag/megaptera/data/DataSet.kt
1
2090
package org.kesmarag.megaptera.data import org.apache.commons.csv.CSVFormat import org.kesmarag.megaptera.utils.listOfFiles import java.io.File import java.io.FileReader import java.io.Reader import java.io.Serializable class DataSet(filePattern: String = "*.csv", var candidateOwners: Int = 1): Serializable { public var members: MutableList<ObservationSet> = arrayListOf() private set public var size: Int = 0 private set public var observationLength: Int = 0 private set init { load(filePattern) redistribute() println("DataSet size = $size") } public operator fun get(q: Int): ObservationSet = members[q] private fun load(filePattern: String): Unit { val lof: List<File> = listOfFiles(filePattern) size = lof.size for (file in lof) { var observationSet = ObservationSet(candidateOwners) val reader: Reader = FileReader(file) var records = CSVFormat.EXCEL.parse(reader) for (r in records) { val rSize = r.size() if (observationLength == 0) { observationLength = rSize } if (rSize != observationLength) { throw IllegalArgumentException("observation with " + "different length in file ${file.absolutePath.toString()}") } val tmpArray = DoubleArray(rSize) for (j in 0..rSize - 1) { tmpArray[j] = r[j].toDouble() } observationSet += Observation(tmpArray) } observationSet.label = file.name members.add(observationSet) } } public fun redistribute() = members.forEach { it.redistribute(candidateOwners, 0) } public fun standardize() = members.forEach { it.standardize() } override fun toString(): String { val str = "DataSet(size=$size,observationLength=$observationLength,candidateOwners=$candidateOwners)" return str } }
apache-2.0
aee16855128ec10c785301d6c50d2925
31.671875
109
0.593301
4.553377
false
false
false
false
MarkNKamau/JustJava-Android
app/src/main/java/com/marknkamau/justjava/ui/orders/OrdersAdapter.kt
1
4120
package com.marknkamau.justjava.ui.orders import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.marknjunge.core.data.model.Order import com.marknjunge.core.data.model.OrderStatus import com.marknkamau.justjava.R import com.marknkamau.justjava.databinding.ItemOrderBinding import com.marknkamau.justjava.utils.CurrencyFormatter import com.marknkamau.justjava.utils.DateTime import com.marknkamau.justjava.utils.capitalize class OrdersAdapter( private val context: Context, private val onClick: (item: Order) -> Unit ) : RecyclerView.Adapter<OrdersAdapter.ViewHolder>() { val items = mutableListOf<Order>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = ItemOrderBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(context, binding, onClick) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(items[position]) } override fun getItemCount() = items.size fun setItems(newItems: List<Order>, animated: Boolean = true) { if (animated) { val result = DiffUtil.calculateDiff(ItemDiffCallback(items, newItems.toMutableList())) items.clear() items.addAll(newItems) result.dispatchUpdatesTo(this) } else { items.clear() items.addAll(newItems) notifyDataSetChanged() } } inner class ViewHolder( private val context: Context, private val binding: ItemOrderBinding, private val onClick: (Order) -> Unit ) : RecyclerView.ViewHolder(binding.root) { fun bind(order: Order) { binding.tvOrderId.text = order.id binding.tvOrderDate.text = DateTime.fromTimestamp(order.datePlaced).format("hh:mm a, d MMM yyyy") binding.tvOrderStatus.text = order.status.s.capitalize().replace("_", " ") binding.tvOrderItems.text = order.items.joinToString { it.productName } binding.tvOrderTotal.text = context.getString(R.string.price_listing, CurrencyFormatter.format(order.totalPrice)) val statusTextColor = when (order.status) { OrderStatus.PENDING -> R.color.colorOrderPendingText OrderStatus.CONFIRMED -> R.color.colorOrderConfirmedText OrderStatus.IN_PROGRESS -> R.color.colorOrderInProgressText OrderStatus.COMPLETED -> R.color.colorOrderCompletedText OrderStatus.CANCELLED -> R.color.colorOrderCancelledText } binding.tvOrderStatus.setTextColor(ContextCompat.getColor(context, statusTextColor)) val statusDrawable = when (order.status) { OrderStatus.PENDING -> R.drawable.bg_order_pending OrderStatus.CONFIRMED -> R.drawable.bg_order_confirmed OrderStatus.IN_PROGRESS -> R.drawable.bg_order_in_progress OrderStatus.COMPLETED -> R.drawable.bg_order_completed OrderStatus.CANCELLED -> R.drawable.bg_order_cancelled } binding.tvOrderStatus.setBackgroundResource(statusDrawable) binding.root.setOnClickListener { onClick(order) } } } class ItemDiffCallback<Order>( private val oldList: MutableList<Order>, private val newList: MutableList<Order> ) : DiffUtil.Callback() { override fun getOldListSize() = oldList.size override fun getNewListSize() = newList.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return newList[newItemPosition]!! == oldList[oldItemPosition] } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return newList[newItemPosition]!! == oldList[oldItemPosition] } } }
apache-2.0
3c1556489bcfe5dea079b87f9547e074
39.792079
109
0.676214
4.893112
false
false
false
false
CzBiX/klog
src/main/kotlin/com/czbix/klog/http/SecureCookie.kt
1
2677
package com.czbix.klog.http import com.czbix.klog.common.Config import com.czbix.klog.utils.now import io.netty.handler.codec.http.Cookie import io.netty.handler.codec.http.QueryStringDecoder import org.apache.commons.codec.binary.Hex import java.util.concurrent.TimeUnit import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec object SecureCookie { private const val ALGORITHM = "HmacSHA256" private val KEY = Config.getCookieSecureKey() private val SPEC = SecretKeySpec(KEY.toByteArray(), ALGORITHM) fun createSign(ver: String, time: Long, name: String, value: String): String { val toSign = arrayOf( ver, time.toString(), name, value, "" // keep for sign ).joinToString("|") val mac = Mac.getInstance(ALGORITHM) mac.init(SPEC) val sign = Hex.encodeHexString(mac.doFinal(toSign.toByteArray())) return sign } var Cookie.secureValue: String? /** * The format consists of a version number and a series of * fields, the last of which is a signature, all separated * by pipes. All numbers are in decimal format with no * leading zeros. The signature is an HMAC-SHA256 of the * whole string up to that point, including the final pipe. * * The fields are: * - format version (i.e. 1; no length prefix) * - timestamp (integer seconds since epoch) * - value (not encoded; assumed to be ~alphanumeric) * - signature (hex-encoded; no length prefix) */ get() { val decode = QueryStringDecoder.decodeComponent(value()) val parts = decode.split('|') if (parts.size != 4) return null val (version, timestamp, value, signature) = parts if (version != "1") return null if (timestamp.toLong() > now()) return null val sign = createSign(version, timestamp.toLong(), name(), value) if (signature != sign) return null return value } set(newValue) { if (newValue == null) { setValue(null) } else { val time = TimeUnit.MILLISECONDS.toSeconds(now()) + maxAge() val actValue = arrayOf( "1", time.toString(), value(), "" // keep for sign ).joinToString("|") val result = actValue + createSign("1", time, name(), newValue) setValue(result) } } }
apache-2.0
77cf8bf89967e6ff9551020ad380c7e5
33.320513
82
0.560329
4.655652
false
false
false
false
da1z/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/EventDispatcher.kt
4
4821
/* * 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.testGuiFramework.recorder import com.intellij.openapi.actionSystem.* import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.util.SystemInfo import java.awt.Component import java.awt.Container import java.awt.KeyboardFocusManager import java.awt.Point import java.awt.event.KeyEvent import java.awt.event.MouseEvent import java.awt.event.MouseEvent.MOUSE_PRESSED import java.util.* import javax.swing.JFrame import javax.swing.KeyStroke import javax.swing.RootPaneContainer import javax.swing.SwingUtilities /** * @author Sergey Karashevich */ object EventDispatcher { private val LOG = Logger.getInstance("#${EventDispatcher::class.qualifiedName}") private val MAC_NATIVE_ACTIONS = arrayOf("ShowSettings", "EditorEscape") fun processMouseEvent(event: MouseEvent) { if (event.id != MOUSE_PRESSED) return val eventComponent: Component? = event.component if (isMainFrame(eventComponent)) return val mousePoint = event.point var actualComponent: Component? = null when (eventComponent) { is RootPaneContainer -> { val layeredPane = eventComponent.layeredPane val point = SwingUtilities.convertPoint(eventComponent, mousePoint, layeredPane) actualComponent = layeredPane.findComponentAt(point) } is Container -> actualComponent = eventComponent.findComponentAt(mousePoint) } if (actualComponent == null) actualComponent = KeyboardFocusManager.getCurrentKeyboardFocusManager().focusOwner if (actualComponent != null) { LOG.info("Delegate click from component:${actualComponent}") val convertedPoint = Point(event.locationOnScreen.x - actualComponent.locationOnScreen.x, event.locationOnScreen.y - actualComponent.locationOnScreen.y) ScriptGenerator.clickComponent(actualComponent, convertedPoint, event) } } fun processKeyBoardEvent(keyEvent: KeyEvent) { if (isMainFrame(keyEvent.component)) return if (keyEvent.id == KeyEvent.KEY_TYPED) ScriptGenerator.processTyping(keyEvent) if (SystemInfo.isMac && keyEvent.id == KeyEvent.KEY_PRESSED) { //we are redirecting native Mac action as an Intellij actions LOG.info(keyEvent.toString()) val actionIds = KeymapManager.getInstance().activeKeymap.getActionIds(KeyStroke.getKeyStrokeForEvent(keyEvent)) for(actionId in actionIds){ if(isMacNativeAction(keyEvent)) { val action = ActionManager.getInstance().getAction(actionId) val actionEvent = AnActionEvent.createFromInputEvent(keyEvent, ActionPlaces.UNKNOWN, action.templatePresentation, DataContext.EMPTY_CONTEXT) ScriptGenerator.processKeyActionEvent(action, actionEvent) } } } } fun processActionEvent(action: AnAction, event: AnActionEvent?) { if (event == null) return val inputEvent = event.inputEvent if (inputEvent is KeyEvent) { if(!isMacNativeAction(inputEvent)) { ScriptGenerator.processKeyActionEvent(action, event) } } else { val actionManager = ActionManager.getInstance() val mainActions = (actionManager.getAction(IdeActions.GROUP_MAIN_MENU) as ActionGroup).getFlatIdList() if (mainActions.contains(actionManager.getId(action))) ScriptGenerator.processMainMenuActionEvent(action, event) } } private fun ActionGroup.getFlatIdList(): List<String> { val actionManager = ActionManager.getInstance() val result = ArrayList<String>() this.getChildren(null).forEach { action -> if (action is ActionGroup) result.addAll(action.getFlatIdList()) else result.add(actionManager.getId(action)) } return result } private fun isMainFrame(component: Component?): Boolean { return component is JFrame && component.title == "GUI Script Editor" } private fun isMacNativeAction(keyEvent: KeyEvent): Boolean{ if (!SystemInfo.isMac) return false val actionIds = KeymapManager.getInstance().activeKeymap.getActionIds(KeyStroke.getKeyStrokeForEvent(keyEvent)) return actionIds.any { it in MAC_NATIVE_ACTIONS } } }
apache-2.0
fe39884e0e16c7bad390188e559f2184
38.52459
123
0.731591
4.708008
false
false
false
false
Heiner1/AndroidAPS
automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.kt
1
3485
package info.nightscout.androidaps.plugins.general.automation.triggers import com.google.common.base.Optional import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import org.json.JSONException import org.json.JSONObject import org.junit.Assert import org.junit.Before import org.junit.Test import org.mockito.Mockito.`when` class TriggerProfilePercentTest : TriggerTestBase() { private val now = 1514766900000L @Before fun mock() { `when`(profileFunction.getProfile()).thenReturn(validProfile) `when`(dateUtil.now()).thenReturn(now) } @Test fun shouldRunTest() { var t: TriggerProfilePercent = TriggerProfilePercent(injector).setValue(101.0).comparator(Comparator.Compare.IS_EQUAL) Assert.assertFalse(t.shouldRun()) t = TriggerProfilePercent(injector).setValue(100.0).comparator(Comparator.Compare.IS_EQUAL) Assert.assertTrue(t.shouldRun()) t = TriggerProfilePercent(injector).setValue(100.0).comparator(Comparator.Compare.IS_EQUAL_OR_GREATER) Assert.assertTrue(t.shouldRun()) t = TriggerProfilePercent(injector).setValue(90.0).comparator(Comparator.Compare.IS_EQUAL_OR_GREATER) Assert.assertTrue(t.shouldRun()) t = TriggerProfilePercent(injector).setValue(100.0).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER) Assert.assertTrue(t.shouldRun()) t = TriggerProfilePercent(injector).setValue(101.0).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER) Assert.assertTrue(t.shouldRun()) t = TriggerProfilePercent(injector).setValue(215.0).comparator(Comparator.Compare.IS_EQUAL) Assert.assertFalse(t.shouldRun()) t = TriggerProfilePercent(injector).setValue(110.0).comparator(Comparator.Compare.IS_EQUAL_OR_GREATER) Assert.assertFalse(t.shouldRun()) t = TriggerProfilePercent(injector).setValue(90.0).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER) Assert.assertFalse(t.shouldRun()) } @Test fun copyConstructorTest() { val t: TriggerProfilePercent = TriggerProfilePercent(injector).setValue(213.0).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER) val t1 = t.duplicate() as TriggerProfilePercent Assert.assertEquals(213.0, t1.pct.value, 0.01) Assert.assertEquals(Comparator.Compare.IS_EQUAL_OR_LESSER, t.comparator.value) } private val bgJson = "{\"data\":{\"comparator\":\"IS_EQUAL\",\"percentage\":110},\"type\":\"TriggerProfilePercent\"}" @Test fun toJSONTest() { val t: TriggerProfilePercent = TriggerProfilePercent(injector).setValue(110.0).comparator(Comparator.Compare.IS_EQUAL) Assert.assertEquals(bgJson, t.toJSON()) } @Test fun fromJSONTest() { val t: TriggerProfilePercent = TriggerProfilePercent(injector).setValue(120.0).comparator(Comparator.Compare.IS_EQUAL) val t2 = TriggerDummy(injector).instantiate(JSONObject(t.toJSON())) as TriggerProfilePercent Assert.assertEquals(Comparator.Compare.IS_EQUAL, t2.comparator.value) Assert.assertEquals(120.0, t2.pct.value, 0.01) } @Test fun iconTest() { Assert.assertEquals(Optional.of(R.drawable.ic_actions_profileswitch), TriggerProfilePercent(injector).icon()) } @Test fun friendlyNameTest() { Assert.assertEquals(R.string.profilepercentage.toLong(), TriggerProfilePercent(injector).friendlyName().toLong()) // not mocked } }
agpl-3.0
5a062c72d4ba917423066509c6e4c8d5
48.8
136
0.729125
4.047619
false
true
false
false
realm/realm-java
examples/kotlinExample/src/main/kotlin/io/realm/examples/kotlin/KotlinExampleActivity.kt
1
7156
/* * Copyright 2015 Realm 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 io.realm.examples.kotlin import android.app.Activity import android.os.Bundle import android.util.Log import android.widget.LinearLayout import android.widget.TextView import io.realm.Realm import io.realm.Sort import io.realm.examples.kotlin.model.Cat import io.realm.examples.kotlin.model.Dog import io.realm.examples.kotlin.model.Person import io.realm.kotlin.createObject import io.realm.kotlin.where import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread class KotlinExampleActivity : Activity() { companion object { const val TAG: String = "KotlinExampleActivity" } private lateinit var rootLayout: LinearLayout private lateinit var realm: Realm override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_realm_basic_example) rootLayout = findViewById(R.id.container) rootLayout.removeAllViews() // Open the realm for the UI thread. realm = Realm.getDefaultInstance() // Delete all persons // Using executeTransaction with a lambda reduces code size and makes it impossible // to forget to commit the transaction. realm.executeTransaction { realm -> realm.deleteAll() } // These operations are small enough that // we can generally safely run them on the UI thread. basicCRUD(realm) basicQuery(realm) basicLinkQuery(realm) // More complex operations can be executed on another thread, for example using // Anko's doAsync extension method. doAsync { var info = "" // Open the default realm. All threads must use its own reference to the realm. // Those can not be transferred across threads. // Realm implements the Closable interface, therefore // we can make use of Kotlin's built-in extension method 'use' (pun intended). Realm.getDefaultInstance().use { realm -> info += complexReadWrite(realm) info += complexQuery(realm) } uiThread { showStatus(info) } } } override fun onDestroy() { super.onDestroy() realm.close() // Remember to close Realm when done. } private fun showStatus(text: String) { Log.i(TAG, text) val textView = TextView(this) textView.text = text rootLayout.addView(textView) } @Suppress("NAME_SHADOWING") private fun basicCRUD(realm: Realm) { showStatus("Perform basic Create/Read/Update/Delete (CRUD) operations...") // All writes must be wrapped in a transaction to facilitate safe multi threading realm.executeTransaction { realm -> // Add a person val person = realm.createObject<Person>(0) person.name = "Young Person" person.age = 14 } // Find the first person (no query conditions) and read a field val person = realm.where<Person>().findFirst()!! showStatus(person.name + ": " + person.age) // Update person in a transaction realm.executeTransaction { _ -> person.name = "Senior Person" person.age = 99 showStatus(person.name + " got older: " + person.age) } } private fun basicQuery(realm: Realm) { showStatus("\nPerforming basic Query operation...") showStatus("Number of persons: ${realm.where<Person>().count()}") val ageCriteria = 99 val results = realm.where<Person>().equalTo("age", ageCriteria).findAll() showStatus("Size of result set: " + results.size) } private fun basicLinkQuery(realm: Realm) { showStatus("\nPerforming basic Link Query operation...") showStatus("Number of persons: ${realm.where<Person>().count()}") val results = realm.where<Person>().equalTo("cats.name", "Tiger").findAll() showStatus("Size of result set: ${results.size}") } private fun complexReadWrite(realm: Realm): String { var status = "\nPerforming complex Read/Write operation..." // Add ten persons in one transaction realm.executeTransaction { val fido = realm.createObject<Dog>() fido.name = "fido" for (i in 1..9) { val person = realm.createObject<Person>(i.toLong()) person.name = "Person no. $i" person.age = i person.dog = fido // The field tempReference is annotated with @Ignore. // This means setTempReference sets the Person tempReference // field directly. The tempReference is NOT saved as part of // the RealmObject: person.tempReference = 42 for (j in 0..i - 1) { val cat = realm.createObject<Cat>() cat.name = "Cat_$j" person.cats.add(cat) } } } // Implicit read transactions allow you to access your objects status += "\nNumber of persons: ${realm.where<Person>().count()}" // Iterate over all objects for (person in realm.where<Person>().findAll()) { val dogName: String = person?.dog?.name ?: "None" status += "\n${person.name}: ${person.age} : $dogName : ${person.cats.size}" // The field tempReference is annotated with @Ignore // Though we initially set its value to 42, it has // not been saved as part of the Person RealmObject: check(person.tempReference == 0) } // Sorting val sortedPersons = realm.where<Person>().sort(Person::age.name, Sort.DESCENDING).findAll() status += "\nSorting ${sortedPersons.last()?.name} == ${realm.where<Person>().findAll().first()?.name}" return status } private fun complexQuery(realm: Realm): String { var status = "\n\nPerforming complex Query operation..." status += "\nNumber of persons: ${realm.where<Person>().count()}" // Find all persons where age between 7 and 9 and name begins with "Person". val results = realm.where<Person>() .between("age", 7, 9) // Notice implicit "and" operation .beginsWith("name", "Person") .findAll() status += "\nSize of result set: ${results.size}" return status } }
apache-2.0
b03ceffb36b58ba9a271ffc317ffe6cc
34.078431
111
0.612214
4.667971
false
false
false
false
xiprox/Tensuu
app/src/main/java/tr/xip/scd/tensuu/ui/mypoints/ReasonsAutoCompleteAdapter.kt
1
2180
package tr.xip.scd.tensuu.ui.mypoints import android.view.View import android.view.ViewGroup import android.widget.Filter import android.widget.Filterable import io.realm.Case import io.realm.OrderedRealmCollection import io.realm.Realm import io.realm.RealmBaseAdapter import kotlinx.android.synthetic.main.item_simple_list.view.* import tr.xip.scd.tensuu.App import tr.xip.scd.tensuu.R import tr.xip.scd.tensuu.realm.model.PointReason import tr.xip.scd.tensuu.realm.model.PointReasonFields import tr.xip.scd.tensuu.common.ext.getLayoutInflater class ReasonsAutoCompleteAdapter(val realm: Realm, var data: OrderedRealmCollection<PointReason>) : RealmBaseAdapter<PointReason>(data), Filterable { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var v = convertView if (v == null) { v = App.context.getLayoutInflater().inflate(R.layout.item_simple_list, parent, false) } v!!.text.text = data[position].text return v } override fun getCount(): Int = data.size override fun getItem(position: Int): PointReason? = data[position] override fun getFilter(): Filter { return object : Filter() { var hasResults = false override fun convertResultToString(resultValue: Any?): CharSequence { return (resultValue as PointReason).text ?: "?" } override fun performFiltering(constraint: CharSequence?): FilterResults { val results = FilterResults() results.count = if (hasResults) 1 else 0 return results } override fun publishResults(constraint: CharSequence?, results: FilterResults?) { if (constraint != null) { val q = constraint.toString() data = realm .where(PointReason::class.java) .contains(PointReasonFields.TEXT, q, Case.INSENSITIVE) .findAll() hasResults = data.size > 0 } notifyDataSetChanged() } } } }
gpl-3.0
8e067259e819c7bba1721585b9104cdd
34.177419
97
0.625229
4.718615
false
false
false
false
Adventech/sabbath-school-android-2
common/core/src/main/java/com/cryart/sabbathschool/core/extensions/prefs/SSPrefsImpl.kt
1
10439
/* * Copyright (c) 2021. Adventech <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.cryart.sabbathschool.core.extensions.prefs import android.app.LocaleManager import android.content.Context import android.content.SharedPreferences import android.os.Build import androidx.core.content.edit import androidx.datastore.core.DataStore import androidx.datastore.preferences.SharedPreferencesMigration import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.emptyPreferences import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import androidx.preference.PreferenceManager import com.cryart.sabbathschool.core.extensions.context.systemService import com.cryart.sabbathschool.core.extensions.sdk.isAtLeastApi import com.cryart.sabbathschool.core.misc.SSConstants import com.cryart.sabbathschool.core.misc.SSHelper import com.cryart.sabbathschool.core.model.ReminderTime import com.cryart.sabbathschool.core.model.SSReadingDisplayOptions import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import timber.log.Timber import java.util.Locale import javax.inject.Inject private val Context.dataStore: DataStore<Preferences> by preferencesDataStore( name = "ss_prefs", produceMigrations = { listOf( SharedPreferencesMigration( it, "${it.packageName}_preferences", setOf( SSConstants.SS_SETTINGS_THEME_KEY, SSConstants.SS_SETTINGS_SIZE_KEY, SSConstants.SS_SETTINGS_FONT_KEY ) ) ) } ) internal class SSPrefsImpl( private val dataStore: DataStore<Preferences>, private val sharedPreferences: SharedPreferences, private val coroutineScope: CoroutineScope, private val context: Context ) : SSPrefs { @Inject constructor(@ApplicationContext context: Context) : this( dataStore = context.dataStore, sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context), coroutineScope = CoroutineScope(Dispatchers.IO), context = context ) init { handleAppLocalesPref() } private fun preferencesFlow(): Flow<Preferences> = dataStore.data .catch { exception -> Timber.e(exception) emit(emptyPreferences()) } override fun reminderEnabled(): Boolean = sharedPreferences.getBoolean( SSConstants.SS_SETTINGS_REMINDER_ENABLED_KEY, true ) override fun setReminderEnabled(enabled: Boolean) = sharedPreferences.edit { putBoolean(SSConstants.SS_SETTINGS_REMINDER_ENABLED_KEY, enabled) } override fun getReminderTime(): ReminderTime { val timeStr = sharedPreferences.getString( SSConstants.SS_SETTINGS_REMINDER_TIME_KEY, SSConstants.SS_SETTINGS_REMINDER_TIME_DEFAULT_VALUE ) val hour = SSHelper.parseHourFromString( timeStr, SSConstants.SS_REMINDER_TIME_SETTINGS_FORMAT ) val min = SSHelper.parseMinuteFromString( timeStr, SSConstants.SS_REMINDER_TIME_SETTINGS_FORMAT ) return ReminderTime(hour, min) } override fun getLanguageCode(): String { val code = sharedPreferences.getString( SSConstants.SS_LAST_LANGUAGE_INDEX, Locale.getDefault().language )!! return mapLanguageCode(code) } override fun getLanguageCodeFlow(): Flow<String> = preferencesFlow() .map { preferences -> val code = preferences[stringPreferencesKey(SSConstants.SS_LAST_LANGUAGE_INDEX)] ?: getLanguageCode() mapLanguageCode(code) } .distinctUntilChanged() override fun setLanguageCode(languageCode: String) { sharedPreferences.edit { putString(SSConstants.SS_LAST_LANGUAGE_INDEX, languageCode) } coroutineScope.launch { dataStore.edit { settings -> settings[stringPreferencesKey(SSConstants.SS_LAST_LANGUAGE_INDEX)] = languageCode } } } private fun mapLanguageCode(code: String): String { return when (code) { "iw" -> "he" "fil" -> "tl" else -> code } } override fun getLastQuarterlyIndex(): String? { return sharedPreferences.getString(SSConstants.SS_LAST_QUARTERLY_INDEX, null) } override fun setLastQuarterlyIndex(index: String?) { sharedPreferences.edit { putString(SSConstants.SS_LAST_QUARTERLY_INDEX, index) } } override fun getReaderArtifactLastModified(): String? { return sharedPreferences.getString(SSConstants.SS_READER_ARTIFACT_LAST_MODIFIED, null) } override fun setReaderArtifactLastModified(lastModified: String) { sharedPreferences.edit { putString(SSConstants.SS_READER_ARTIFACT_LAST_MODIFIED, lastModified) } } /** * By pre-loading the [SSReadingDisplayOptions] in [displayOptionsFlow] * Later synchronous reads may be faster or may avoid a disk I/O operation * altogether if the initial read has completed. */ override fun getDisplayOptions(callback: (SSReadingDisplayOptions) -> Unit) { coroutineScope.launch { val settings = try { dataStore.data.first() } catch (ex: Exception) { Timber.e(ex) emptyPreferences() } callback(settings.toDisplayOptions()) } } override fun displayOptionsFlow(): Flow<SSReadingDisplayOptions> = preferencesFlow() .map { preferences -> preferences.toDisplayOptions() } .distinctUntilChanged() private fun Preferences.toDisplayOptions(): SSReadingDisplayOptions { val theme = this[stringPreferencesKey(SSConstants.SS_SETTINGS_THEME_KEY)] ?: SSReadingDisplayOptions.SS_THEME_DEFAULT val size = this[stringPreferencesKey(SSConstants.SS_SETTINGS_SIZE_KEY)] ?: SSReadingDisplayOptions.SS_SIZE_MEDIUM val font = this[stringPreferencesKey(SSConstants.SS_SETTINGS_FONT_KEY)] ?: SSReadingDisplayOptions.SS_FONT_LATO return SSReadingDisplayOptions(theme, size, font) } override fun setDisplayOptions(ssReadingDisplayOptions: SSReadingDisplayOptions) { coroutineScope.launch { dataStore.edit { settings -> val themePrefKey = stringPreferencesKey(SSConstants.SS_SETTINGS_THEME_KEY) val fontPrefKey = stringPreferencesKey(SSConstants.SS_SETTINGS_FONT_KEY) val sizePrefKey = stringPreferencesKey(SSConstants.SS_SETTINGS_SIZE_KEY) if (settings[themePrefKey] != ssReadingDisplayOptions.theme) { settings[themePrefKey] = ssReadingDisplayOptions.theme } if (settings[fontPrefKey] != ssReadingDisplayOptions.font) { settings[fontPrefKey] = ssReadingDisplayOptions.font } if (settings[sizePrefKey] != ssReadingDisplayOptions.size) { settings[sizePrefKey] = ssReadingDisplayOptions.size } } } } override fun isAppReBrandingPromptShown(): Boolean = sharedPreferences.getBoolean( SSConstants.SS_APP_RE_BRANDING_PROMPT_SEEN, false ) override fun isReminderScheduled(): Boolean = sharedPreferences.getBoolean( SSConstants.SS_REMINDER_SCHEDULED, false ) override fun setAppReBrandingShown() = sharedPreferences.edit { putBoolean(SSConstants.SS_APP_RE_BRANDING_PROMPT_SEEN, true) } override fun setThemeColor(primary: String, primaryDark: String) { sharedPreferences.edit { putString(SSConstants.SS_COLOR_THEME_LAST_PRIMARY, primary) putString(SSConstants.SS_COLOR_THEME_LAST_PRIMARY_DARK, primaryDark) } } override fun setReminderScheduled(scheduled: Boolean) = sharedPreferences.edit { putBoolean(SSConstants.SS_REMINDER_SCHEDULED, scheduled) } override fun isReadingLatestQuarterly(): Boolean { return sharedPreferences.getBoolean(SSConstants.SS_LATEST_QUARTERLY, false) } override fun setReadingLatestQuarterly(state: Boolean) = sharedPreferences.edit { putBoolean(SSConstants.SS_LATEST_QUARTERLY, state) } override fun clear() { sharedPreferences.edit { clear() } coroutineScope.launch { dataStore.edit { it.clear() } } } private fun handleAppLocalesPref() { if (isAtLeastApi(Build.VERSION_CODES.TIRAMISU)) { val locale = context.systemService<LocaleManager>(Context.LOCALE_SERVICE) .applicationLocales .takeUnless { it.isEmpty }?.get(0) ?: Locale.forLanguageTag(getLanguageCode()) setLanguageCode(locale.language) } } }
mit
419d97147f5500786167b1ca30d0b384
36.415771
125
0.687326
4.853092
false
false
false
false
Adventech/sabbath-school-android-2
common/models/src/main/java/app/ss/models/media/AudioFile.kt
1
1512
/* * Copyright (c) 2022. Adventech <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package app.ss.models.media import android.net.Uri import androidx.annotation.Keep @Keep data class AudioFile( val id: String, val title: String = "", val artist: String = "", val source: Uri = Uri.EMPTY, val image: String = "", val imageRatio: String = "", val target: String = "", val targetIndex: String = "", val duration: Long = 0 )
mit
ed0b4c23fd3baae7a98760bcaf24a08f
37.769231
80
0.727513
4.295455
false
false
false
false
Yubico/yubioath-desktop
android/app/src/main/kotlin/com/yubico/authenticator/logging/FlutterLog.kt
1
2910
/* * Copyright (C) 2022 Yubico. * * 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.yubico.authenticator.logging import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.MethodChannel class FlutterLog(messenger: BinaryMessenger) { private var channel = MethodChannel(messenger, "android.log.redirect") init { channel.setMethodCallHandler { call, result -> when (call.method) { "log" -> { val message = call.argument<String>("message") val error = call.argument<String>("error") val loggerName = call.argument<String>("loggerName") val levelValue = call.argument<String>("level") val level = logLevelFromArgument(levelValue) if (level == null) { loggerError("Invalid level for message from [$loggerName]: $levelValue") } else if (loggerName != null && message != null) { log(level, loggerName, message, error) result.success(null) } else { result.error("-1", "Invalid log parameters", null) } } "setLevel" -> { val levelArgValue = call.argument<String>("level") val requestedLogLevel = logLevelFromArgument(levelArgValue) if (requestedLogLevel != null) { Log.setLevel(requestedLogLevel) } else { loggerError("Invalid log level requested: $levelArgValue") } result.success(null) } "getLogs" -> { result.success(Log.getBuffer()) } else -> { result.notImplemented() } } } } private fun logLevelFromArgument(argValue: String?): Log.LogLevel? = Log.LogLevel.values().firstOrNull { it.name == argValue?.uppercase() } private fun loggerError(message: String) { log(Log.LogLevel.ERROR,"FlutterLog", message, null) } private fun log(level: Log.LogLevel, loggerName: String, message: String, error: String?) { Log.log(level, loggerName, message, error) } }
apache-2.0
3bc6d8643173ee27088e0066bbe2c668
37.813333
96
0.561168
4.89899
false
false
false
false
PolymerLabs/arcs
java/arcs/core/analysis/PredicateUtils.kt
1
4049
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.analysis import arcs.core.data.InformationFlowLabel import arcs.core.data.InformationFlowLabel.Predicate import java.util.BitSet /** * Represents a conjunct in a Disjunctive Normal Form (DNF). * * [mask] determines the set of indices that are valid in [bits]. Suppose that the universe of * labels is {A, B, C}. Here are some examples of how various conjuncts are represented: * * Conjunction : (mask, bits) * A : (100, 100) * not(A) : (100, 000) * A and B : (110, 110) * A and not(B) : (110, 100) */ data class Conjunct(val mask: BitSet, val bits: BitSet) /** * Returns the predicate in Disjunctive Normal Form (DNF) as [Set<Conjunct>]. * * The [indices] map is used to determine the index of an [InformationFlowLabel] in the bitset of * the conjuncts. Suppose that the universe of labels is {A, B, C}. Here are some examples: * * Predicate : {(mask, bits)} * A : {(100, 100)} * not(A) : {(100, 000)} * A and B : {(110, 110)} * A and not(B) : {(110, 100)} * A or B : {(100, 100), (010, 010)} * A or not(B) : {(100, 100), (010, 000)} * (A and B) or (C) : {(110, 110), (001, 001)} */ fun InformationFlowLabel.Predicate.asDNF( indices: Map<InformationFlowLabel, Int> ): Set<Conjunct> { // TODO(b/157530728): This is not very efficient. We will want to replace this with // an implementation that uses a Binary Decision Diagram (BDD). when (this) { is Predicate.Label -> { val index = indices.getValue(label) val result = BitSet(indices.size).apply { set(index) } return setOf(Conjunct(result, result)) } is Predicate.Not -> { val labelPredicate = requireNotNull(predicate as? Predicate.Label) { // TODO(b/157530728): It will be easy to handle `not` when we have a proper // datastructure like BDDs. For now, we only support `not` on labels. "Not is only supported for label predicates when converting to bitsets!" } val index = indices.getValue(labelPredicate.label) val mask = BitSet(indices.size).apply { set(index) } val result = BitSet(indices.size) return setOf(Conjunct(mask, result)) } is Predicate.Or -> { val lhsConjuncts = lhs.asDNF(indices) val rhsConjuncts = rhs.asDNF(indices) return lhsConjuncts union rhsConjuncts } is Predicate.And -> { val lhsConjuncts = lhs.asDNF(indices) val rhsConjuncts = rhs.asDNF(indices) return lhsConjuncts.and(rhsConjuncts, indices) } } } /** Returns the DNF form for ([this] and [that]) by applying distributivity law. */ private fun Set<Conjunct>.and( that: Set<Conjunct>, indices: Map<InformationFlowLabel, Int> ): Set<Conjunct> { val result = mutableSetOf<Conjunct>() // Apply distributivity law. forEach { (thisMask, thisBits) -> that.forEach { (thatMask, thatBits) -> val commonThisBits = BitSet(indices.size).apply { or(thisMask) and(thatMask) and(thisBits) } val commonThatBits = BitSet(indices.size).apply { or(thisMask) and(thatMask) and(thatBits) } // Make sure that the common bits match. If they don't match, then this // combination is contradiction and, therefore, is not included in the result. if (commonThatBits == commonThisBits) { val combinedMask = BitSet(indices.size).apply { or(thisMask) or(thatMask) } val combinedBits = BitSet(indices.size).apply { or(thisBits) or(thatBits) } result.add(Conjunct(combinedMask, combinedBits)) } } } return result.toSet() }
bsd-3-clause
986ef39bec0b87f3651008cd886861ed
33.606838
97
0.630526
3.599111
false
false
false
false
duncte123/SkyBot
src/main/kotlin/ml/duncte123/skybot/objects/RadioStream.kt
1
1721
/* * Skybot, a multipurpose discord bot * Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32" * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ml.duncte123.skybot.objects class RadioStream(var name: String, val url: String, val website: String) { // private fun hasWebsite() = !website.isNullOrBlank() // fun toEmbedString(): String = "[$name]($url) ${if (hasWebsite()) "from [$website]($website)" else ""}" fun toEmbedString(): String = "[$name]($url) from [$website]($website)" override fun equals(other: Any?): Boolean { if (other !is RadioStream) { return false } return this.name == other.name && this.url == other.url && this.website == other.website } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + url.hashCode() result = 31 * result + website.hashCode() return result } override fun toString(): String { return "RadioStream(name='$name', url='$url', website=$website)" } }
agpl-3.0
05590b19e61ca1fc3d71da9b860b4d1e
37.244444
108
0.665892
4.137019
false
false
false
false
fcostaa/kotlin-rxjava-android
feature/wiki/src/main/kotlin/com/github/felipehjcosta/marvelapp/wiki/view/WikiFragment.kt
1
7989
package com.github.felipehjcosta.marvelapp.wiki.view import android.os.Bundle import android.view.* import android.widget.FrameLayout import android.widget.ImageView import android.widget.TextView import androidx.fragment.app.Fragment import com.github.felipehjcosta.layoutmanager.GalleryLayoutManager import com.github.felipehjcosta.marvelapp.base.imageloader.ImageLoader import com.github.felipehjcosta.marvelapp.base.navigator.AppNavigator import com.github.felipehjcosta.marvelapp.base.rx.plusAssign import com.github.felipehjcosta.marvelapp.base.view.viewBinding import com.github.felipehjcosta.marvelapp.wiki.R import com.github.felipehjcosta.marvelapp.wiki.databinding.FragmentWikiBinding import com.github.felipehjcosta.marvelapp.wiki.di.setupDependencyInjection import com.github.felipehjcosta.marvelapp.wiki.presentation.CharacterItemViewModel import com.github.felipehjcosta.marvelapp.wiki.presentation.HighlightedCharactersViewModel import com.github.felipehjcosta.marvelapp.wiki.presentation.OthersCharactersViewModel import com.github.felipehjcosta.recyclerviewdsl.onRecyclerView import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject import com.github.felipehjcosta.marvelapp.base.R as RBase class WikiFragment : Fragment(R.layout.fragment_wiki) { private val binding by viewBinding(FragmentWikiBinding::bind) @Inject lateinit var highlightedCharactersViewModel: HighlightedCharactersViewModel @Inject lateinit var othersCharactersViewModel: OthersCharactersViewModel @Inject lateinit var imageLoader: ImageLoader @Inject lateinit var appNavigator: AppNavigator private lateinit var compositeDisposable: CompositeDisposable private lateinit var highlightedCharactersLayoutManager: GalleryLayoutManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setupDependencyInjection() setHasOptionsMenu(true) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) highlightedCharactersLayoutManager = GalleryLayoutManager().apply { attach(binding.highlightedCharactersRecyclerView) } bind() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.wiki_toolbar_menu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { R.id.wiki_menu_search -> { activity?.let { appNavigator.showList(it) } true } else -> super.onOptionsItemSelected(item) } private fun bind() { compositeDisposable = CompositeDisposable() bindHighlightedCharactersSection() bindOthersCharactersSection() } private fun bindHighlightedCharactersSection() { compositeDisposable += highlightedCharactersViewModel.output.items .doOnNext { characters -> WikiGalleryCallbacksHandler( imageLoader, characters, binding.highlightedCharactersContainer ).apply { highlightedCharactersLayoutManager.itemTransformer = this highlightedCharactersLayoutManager.onItemSelectedListener = this } } .subscribe { displayHighlightedCharacters(it) } compositeDisposable += highlightedCharactersViewModel.output.showLoading .filter { it == true } .doOnNext { LoadingWikiGalleryCallbacksHandler().apply { highlightedCharactersLayoutManager.itemTransformer = this } } .subscribe { displayLoadingHighlightedCharacters() } } private fun displayLoadingHighlightedCharacters() { onRecyclerView(binding.highlightedCharactersRecyclerView) { bind(R.layout.loading_highlighted_characters_item) { withItems(arrayOfNulls<Any?>(LOADING_CHARACTERS_COUNT).toList()) {} } } } private fun displayHighlightedCharacters(list: List<CharacterItemViewModel>) { onRecyclerView(binding.highlightedCharactersRecyclerView) { bind(R.layout.highlighted_characters_fragment_item) { withItems(list) { on<FrameLayout>(R.id.container) { it.view?.foreground = context?.getDrawable(R.drawable.highlighted_characters_foreground) } on<TextView>(R.id.title) { it.view?.text = it.item?.name } on<ImageView>(R.id.image) { val imageUrl = it.item?.image val imageView = it.view if (imageUrl != null && imageView != null) { imageLoader.loadImage(imageUrl, imageView) } } onClick { _, characterItemViewModel -> activity?.let { appNavigator.showDetail(it, characterItemViewModel?.id ?: 0L) } } } } } } private fun bindOthersCharactersSection() { compositeDisposable += highlightedCharactersViewModel.input.loadItemsCommand.execute().subscribe() compositeDisposable += othersCharactersViewModel.output.items .subscribe { displayOthersCharacters(it) } compositeDisposable += othersCharactersViewModel.output.showLoading .filter { it == true } .subscribe { displayLoadingOthersCharacters() } compositeDisposable += othersCharactersViewModel.input.loadItemsCommand.execute().subscribe() } private fun displayLoadingOthersCharacters() { onRecyclerView(binding.othersCharactersRecyclerView) { withGridLayout { spanCount = GRID_SPAN_COUNT } bind(R.layout.loading_others_characters_item) { withItems(arrayOfNulls<Any?>(LOADING_CHARACTERS_COUNT).toList()) {} } } } private fun displayOthersCharacters(list: List<CharacterItemViewModel>) { onRecyclerView(binding.othersCharactersRecyclerView) { withGridLayout { spanCount = GRID_SPAN_COUNT } bind(R.layout.others_characters_fragment_item) { withItems(list) { on<TextView>(R.id.title) { it.view?.text = it.item?.name } on<ImageView>(R.id.image) { val imageUrl = it.item?.image val imageView = it.view if (imageUrl != null && imageView != null) { val cornerRadius = imageView.resources .getDimensionPixelSize(RBase.dimen.image_default_color_radius) imageLoader.loadRoundedImage(imageUrl, imageView, cornerRadius) } } onClick { _, characterItemViewModel -> activity?.let { appNavigator.showDetail(it, characterItemViewModel?.id ?: 0) } } } } } } override fun onDestroyView() { super.onDestroyView() unbind() } private fun unbind() { compositeDisposable.dispose() } companion object { private const val GRID_SPAN_COUNT = 3 private const val LOADING_CHARACTERS_COUNT = 7 fun newInstance() = WikiFragment() } }
mit
eef79f761c85ac43f4e942994d35ea27
36.507042
106
0.61835
5.722779
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/neuralprocessor/recurrent/RecurrentNeuralProcessor.kt
1
25936
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.neuralprocessor.recurrent import com.kotlinnlp.simplednn.core.arrays.DistributionArray import com.kotlinnlp.simplednn.core.layers.LayerParameters import com.kotlinnlp.simplednn.core.layers.Layer import com.kotlinnlp.simplednn.core.layers.LayerType import com.kotlinnlp.simplednn.core.layers.models.recurrent.GatedRecurrentLayer import com.kotlinnlp.simplednn.core.layers.models.recurrent.RecurrentLayer import com.kotlinnlp.simplednn.core.layers.models.merge.MergeLayer import com.kotlinnlp.simplednn.core.layers.StackedLayersParameters import com.kotlinnlp.simplednn.core.layers.RecurrentStackedLayers import com.kotlinnlp.simplednn.core.layers.StatesWindow import com.kotlinnlp.simplednn.core.layers.helpers.ParamsErrorsCollector import com.kotlinnlp.simplednn.core.neuralprocessor.NeuralProcessor import com.kotlinnlp.simplednn.core.optimizer.ParamsErrorsAccumulator import com.kotlinnlp.simplednn.core.optimizer.ParamsErrorsList import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray import com.kotlinnlp.simplednn.simplemath.ndarray.Shape /** * The neural processor that acts on networks of stacked-layers with recurrent connections. * * @property model the stacked-layers parameters * @param dropouts the probability of dropout for each stacked layer * @property propagateToInput whether to propagate the errors to the input during the [backward] * @param paramsErrorsCollector where to collect the local params errors during the [backward] (optional) * @property id an identification number useful to track a specific processor */ class RecurrentNeuralProcessor<InputNDArrayType : NDArray<InputNDArrayType>>( val model: StackedLayersParameters, private val dropouts: List<Double>, override val propagateToInput: Boolean, private val paramsErrorsCollector: ParamsErrorsCollector = ParamsErrorsCollector(), override val id: Int = 0 ) : StatesWindow<InputNDArrayType>(), NeuralProcessor< List<InputNDArrayType>, // InputType List<DenseNDArray>, // OutputType List<DenseNDArray>, // ErrorsType List<DenseNDArray> // InputErrorsType > { /** * The neural processor that acts on networks of stacked-layers with recurrent connections. * * @param model the stacked-layers parameters * @param dropout the probability of dropout for each stacked layer (default 0.0) * @param propagateToInput whether to propagate the errors to the input during the [backward] * @param paramsErrorsCollector where to collect the local params errors during the [backward] (optional) * @param id an identification number useful to track a specific processor */ constructor( model: StackedLayersParameters, dropout: Double = 0.0, propagateToInput: Boolean, paramsErrorsCollector: ParamsErrorsCollector = ParamsErrorsCollector(), id: Int = 0 ): this( model = model, dropouts = List(model.numOfLayers) { dropout }, propagateToInput = propagateToInput, paramsErrorsCollector = paramsErrorsCollector, id = id ) /** * The sequence of states. */ private val sequence: NNSequence<InputNDArrayType> = NNSequence(this.model) /** * Set each time a single forward or a single backward are called */ private var curStateIndex: Int = 0 /** * An index which indicates the last state (-1 if the sequence is empty). */ private var lastStateIndex: Int = -1 /** * The number of states processed in the current sequence. */ private val numOfStates: Int get() = this.lastStateIndex + 1 /** * The helper which calculates the importance scores of all the previous states of a given one, in a RAN neural * network. */ private val ranImportanceHelper: RANImportanceHelper by lazy { RANImportanceHelper() } /** * The params errors accumulator. */ private val paramsErrorsAccumulator by lazy { ParamsErrorsAccumulator() } /** * An array of the size equal to the output layer size filled by zeroes. */ private val zeroErrors: DenseNDArray by lazy { DenseNDArrayFactory.zeros(shape = Shape(this.model.layersConfiguration.last().size)) } /** * @param copy a Boolean indicating whether the returned arrays must be a copy or a reference * * @return the output arrays of the layers or null if no forward has been called */ fun getCurState(copy: Boolean = true): List<DenseNDArray>? = if (this.lastStateIndex >= 0) this.sequence.getStateStructure(this.curStateIndex).layers.map { if (copy) it.outputArray.values.copy() else it.outputArray.values } else null /** * @return the previous network structure with respect to the [curStateIndex] */ override fun getPrevState(): RecurrentStackedLayers<InputNDArrayType>? = if (this.curStateIndex in 1 .. this.lastStateIndex) this.sequence.getStateStructure(this.curStateIndex - 1) else null /** * @return the next network structure with respect to the [curStateIndex] */ override fun getNextState(): RecurrentStackedLayers<InputNDArrayType>? = if (this.curStateIndex < this.lastStateIndex) // it works also for the init hidden structure this.sequence.getStateStructure(this.curStateIndex + 1) else null /** * @param copy a Boolean indicating whether the returned output must be a copy or a reference * * @return the output of the last [forward] */ fun getOutput(copy: Boolean = true): DenseNDArray = if (copy) this.sequence.getStateStructure(this.lastStateIndex).outputLayer.outputArray.values.copy() else this.sequence.getStateStructure(this.lastStateIndex).outputLayer.outputArray.values /** * @param copy a Boolean indicating whether the returned errors must be a copy or a reference * * @return the accumulated errors of the network parameters */ override fun getParamsErrors(copy: Boolean): ParamsErrorsList = this.paramsErrorsAccumulator.getParamsErrors(copy = copy) /** * Get the input errors of all the elements of the last forwarded sequence, in the same order. * This method should be called after a backward. * * @param copy a Boolean indicating whether the returned errors must be a copy or a reference * * @return an array containing the errors of the input sequence */ override fun getInputErrors(copy: Boolean): List<DenseNDArray> = List( size = this.numOfStates, init = { i -> this.getInputErrors(elementIndex = i, copy = copy) } ) /** * Get the inputs errors of all the elements of the last forwarded sequence, in the same order, in case of the input * layer is a Merge layer. * This method should be called after a backward. * * @param copy a Boolean indicating whether the returned errors must be a copy or a reference * * @return an array containing the errors of the input sequence */ fun getInputsSequenceErrors(copy: Boolean = true): List<List<DenseNDArray>> = List( size = this.numOfStates, init = { i -> this.getInputsErrors(elementIndex = i, copy = copy) } ) /** * Get the input errors of an element of the last forwarded sequence. * This method must be used only when the input layer is not a [MergeLayer] and it should be called after a backward. * * @param elementIndex the index of an element of the input sequence * @param copy a Boolean indicating whether the returned errors must be a copy or a reference * * @return the input errors of the network structure at the given index of the sequence */ fun getInputErrors(elementIndex: Int, copy: Boolean = true): DenseNDArray { require(elementIndex in 0 .. this.lastStateIndex) { "The element index ($elementIndex) must be in the range of the sequence [0, $lastStateIndex]" } val layers: RecurrentStackedLayers<InputNDArrayType> = this.sequence.getStateStructure(elementIndex) require(layers.inputLayer !is MergeLayer<InputNDArrayType>) return layers.inputLayer.inputArray.let { if (copy) it.errors.copy() else it.errors } } /** * Get the inputs errors of an element of the last forwarded sequence, in case of the input layer is a Merge layer. * This method must be used only when the input layer is a [MergeLayer] and it should be called after a backward. * * @param elementIndex the index of an element of the input sequence * @param copy a Boolean indicating whether the returned errors must be a copy or a reference * * @return the list of inputs errors of the network structure at the given index of the sequence */ fun getInputsErrors(elementIndex: Int, copy: Boolean = true): List<DenseNDArray> { require(elementIndex in 0 .. this.lastStateIndex) { "element index (%d) must be within the length of the sequence in the range [0, %d]" .format(elementIndex, this.lastStateIndex) } val layers: RecurrentStackedLayers<InputNDArrayType> = this.sequence.getStateStructure(elementIndex) require(layers.inputLayer is MergeLayer<InputNDArrayType>) return (layers.inputLayer as MergeLayer<InputNDArrayType>).inputArrays.map { if (copy) it.errors.copy() else it.errors } } /** * Get the errors of the initial hidden arrays. * This method should be used only if initial hidden arrays has been passed in the last [forward] call. * * @return the errors of the initial hidden arrays (null if no init hidden is used for a certain layer) */ fun getInitHiddenErrors(): List<DenseNDArray?> = this.sequence.getStateStructure(0).getInitHiddenErrors() /** * @param copy a Boolean indicating whether the returned arrays must be a copy or a reference * * @return the output sequence */ fun getOutputSequence(copy: Boolean = true): List<DenseNDArray> = List(this.numOfStates) { i -> this.sequence.getStateStructure(i).outputLayer.outputArray.values.let { if (copy) it.copy() else it } } /** * Execute the forward of the input to the output. * * @param input the whole input sequence * * @return the output sequence */ override fun forward(input: List<InputNDArrayType>): List<DenseNDArray> { require(input.isNotEmpty()) { "The input cannot be empty." } this.forward(input = input, initHiddenArrays = null, saveContributions = false) return this.getOutputSequence(copy = true) // TODO: check copy } /** * Execute the forward of an input sequence to the output, returning the last state output only. * * Set the [initHiddenArrays] to use them as previous hidden in the first forward. Set some of them to null to don't * use them for certain layers. * * @param input the whole input sequence * @param initHiddenArrays the list of initial hidden arrays (one per layer, null by default) * @param saveContributions whether to save the contributions of each input to its output (needed to calculate * the relevance) * * @return the last state output */ fun forward(input: List<InputNDArrayType>, initHiddenArrays: List<DenseNDArray?>? = null, saveContributions: Boolean = false): DenseNDArray { require(input.isNotEmpty()) { "The input cannot be empty." } input.forEachIndexed { i, values -> this.forward( input = values, firstState = (i == 0), initHiddenArrays = initHiddenArrays, saveContributions = saveContributions) } return this.getOutput() } /** * Execute the forward of the input of the current state to the output, returning the related output. * * Set the [initHiddenArrays] to use them as previous hidden in the first forward. Set some of them to null to don't * use them for certain layers. * [initHiddenArrays] will be ignored if [firstState] is false. * * @param input the input sequence * @param firstState whether the current one is the first state (if `true` the sequence is reset) * @param initHiddenArrays the list of initial hidden arrays (one per layer, null by default) * @param saveContributions whether to save the contributions of each input to its output (needed to calculate * the relevance) * * @return the last state output */ fun forward(input: InputNDArrayType, firstState: Boolean, initHiddenArrays: List<DenseNDArray?>? = null, saveContributions: Boolean = false): DenseNDArray { if (firstState) this.reset() this.addNewState(saveContributions) this.curStateIndex = this.lastStateIndex // crucial to provide the right context this.forwardCurrentState( features = input, initHiddenArrays = initHiddenArrays, saveContributions = saveContributions) return this.getOutput() } /** * Execute the forward of an input sequence to the output, when the input layer is a [MergeLayer], returning the last * state output only. * * Set the [initHiddenArrays] to use them as previous hidden in the first forward. Set some of them to null to don't * use them for certain layers. * * @param input the whole input sequence * @param initHiddenArrays the list of initial hidden arrays (one per layer, null by default) * @param saveContributions whether to save the contributions of each input to its output (needed to calculate * the relevance) * * @return the last state output */ fun forward(input: ArrayList<List<InputNDArrayType>>, initHiddenArrays: List<DenseNDArray?>? = null, saveContributions: Boolean = false): DenseNDArray { require(input.isNotEmpty()) { "The input cannot be empty." } input.forEachIndexed { i, values -> this.forward( input = values, firstState = (i == 0), initHiddenArrays = initHiddenArrays, saveContributions = saveContributions) } return this.getOutput() } /** * Execute the forward of the input of the current state to the output, when the input layer is a [MergeLayer], * returning the related output. * * Set the [initHiddenArrays] to use them as previous hidden in the first forward. Set some of them to null to don't * use them for certain layers. * [initHiddenArrays] will be ignored if [firstState] is false. * * @param input the list of features to forward from the input to the output * @param firstState whether the current one is the first state (if `true` the sequence is reset) * @param initHiddenArrays the list of initial hidden arrays (one per layer, null by default) * @param saveContributions whether to save the contributions of each input to its output (needed to calculate * the relevance) * * @return the last state output */ fun forward(input: List<InputNDArrayType>, firstState: Boolean, initHiddenArrays: List<DenseNDArray?>? = null, saveContributions: Boolean = false): DenseNDArray { require(input.isNotEmpty()) { "The input cannot be empty." } if (firstState) this.reset() this.addNewState(saveContributions) this.curStateIndex = this.lastStateIndex // crucial to provide the right context this.forwardCurrentState( input = input, initHiddenArrays = initHiddenArrays, saveContributions = saveContributions) return this.getOutput() } /** * Calculate the relevance of the input of a state respect to the output of another (or the same) state. * * @param stateFrom the index of the state from whose input to calculate the relevance * @param stateTo the index of the state whose output will be used as reference to calculate the relevance * @param relevantOutcomesDistribution the distribution which indicates which outcomes are relevant, used * as reference to calculate the relevance of the input * @param copy whether to return a copy of the relevance or not * * @return the relevance of the input of the state [stateFrom] respect to the output of the state [stateTo] */ fun calculateRelevance(stateFrom: Int, stateTo: Int, relevantOutcomesDistribution: DistributionArray, copy: Boolean = true): NDArray<*> { require(stateFrom <= stateTo) { "stateFrom ($stateFrom) must be <= stateTo ($stateTo)" } require(stateFrom in 0 .. this.lastStateIndex) { "The state-from ($stateFrom) index exceeded the sequence size ($numOfStates)" } this.sequence.getStateStructure(stateTo).layers.last().setOutputRelevance(relevantOutcomesDistribution) for (stateIndex in (stateFrom .. stateTo).reversed()) { this.curStateIndex = stateIndex // crucial to provide the right context this.propagateRelevanceOnCurrentState(isFirstState = stateIndex == stateFrom, isLastState = stateIndex == stateTo) } return this.getInputRelevance(stateIndex = stateFrom, copy = copy) } /** * Get the importance scores of the previous states respect to a given state. * The scores values are in the range [0.0, 1.0]. * * This method should be called only after a [forward] call. * It is required that the network structures contain only a RAN layer. * * @param stateIndex the index of a state * * @return the array containing the importance scores of the previous states */ fun getRANImportanceScores(stateIndex: Int): DenseNDArray { require(stateIndex > 0) { "Cannot get the importance score of the first state." } require(this.model.layersConfiguration.count { it.connectionType == LayerType.Connection.RAN } == 1) { "It is required that only one layer must be a RAN layer to get the RAN importance score." } return this.ranImportanceHelper.getImportanceScores( states = (0 .. stateIndex).map { this.sequence.getStateStructure(it) }) } /** * Propagate the errors of the last state output with a stochastic gradient descent (SGD) algorithm. * * @param outputErrors the output errors of the last state */ fun backward(outputErrors: DenseNDArray) { this.backward( outputErrors = List(this.numOfStates) { i -> if (i == this.lastStateIndex) outputErrors else this.zeroErrors }) } /** * Propagate the output errors of the whole sequence with a stochastic gradient descent (SGD) algorithm. * * @param outputErrors the errors of the whole sequence outputs */ override fun backward(outputErrors: List<DenseNDArray>) { require(outputErrors.size == (this.numOfStates)) { "The number of errors (${outputErrors.size}) does not reflect the length of the sequence ($numOfStates)" } for (i in (0 .. this.lastStateIndex).reversed()) { this.backwardStep(outputErrors[i]) } } /** * Execute a single step of backward, respect to the last forwarded sequence, starting from the last state. * Each time this function is called, the focused state becomes the previous. * * @param outputErrors the output errors of the current state */ private fun backwardStep(outputErrors: DenseNDArray) { require(this.curStateIndex <= this.lastStateIndex) { "The current state ($curStateIndex) cannot be greater then the last state index ($lastStateIndex)." } this.sequence.getStateStructure(this.curStateIndex).backward( outputErrors = outputErrors, propagateToInput = this.propagateToInput ).let { paramsErrors -> this.paramsErrorsAccumulator.accumulate(paramsErrors) } this.curStateIndex-- } /** * Add a new state to the sequence. * * @param saveContributions whether to save the contributions of each input to its output (needed to calculate the * relevance) */ private fun addNewState(saveContributions: Boolean = false) { if (this.lastStateIndex == this.sequence.lastIndex) { val layers = RecurrentStackedLayers(params = this.model, dropouts = this.dropouts, statesWindow = this).apply { setParamsErrorsCollector(paramsErrorsCollector) } this.sequence.add(layers = layers, saveContributions = saveContributions) } this.lastStateIndex++ } /** * Forward the current state input to the output. * * @param features the features to forward from the input to the output * @param initHiddenArrays the list of initial hidden arrays (one per layer, can be null) * @param saveContributions whether to save the contributions of each input to its output (needed to calculate the * relevance) */ private fun forwardCurrentState(features: InputNDArrayType, initHiddenArrays: List<DenseNDArray?>?, saveContributions: Boolean) { val layers: RecurrentStackedLayers<InputNDArrayType> = this.sequence.getStateStructure(this.lastStateIndex) layers.setInitHidden(arrays = if (this.curStateIndex == 0) initHiddenArrays else null) if (saveContributions) layers.forward(features, contributions = this.sequence.getStateContributions(this.lastStateIndex)) else layers.forward(features) } /** * Forward the current state when the input layer is a Merge layer. * * @param input the list of features to forward from the input to the output * @param initHiddenArrays the list of initial hidden arrays (one per layer, can be null) * @param saveContributions whether to save the contributions of each input to its output (needed to calculate the * relevance) */ private fun forwardCurrentState(input: List<InputNDArrayType>, initHiddenArrays: List<DenseNDArray?>?, saveContributions: Boolean) { val layers: RecurrentStackedLayers<InputNDArrayType> = this.sequence.getStateStructure(this.lastStateIndex) layers.setInitHidden(arrays = if (this.curStateIndex == 0) initHiddenArrays else null) if (saveContributions) layers.forward(input, contributions = this.sequence.getStateContributions(this.lastStateIndex)) else layers.forward(input) } /** * Propagate the relevance backward through the layers of the current state. * * @param isFirstState a Boolean indicating if the current state is the first * @param isLastState a Boolean indicating if the current state is the last */ private fun propagateRelevanceOnCurrentState(isFirstState: Boolean, isLastState: Boolean) { val layers: RecurrentStackedLayers<InputNDArrayType> = this.sequence.getStateStructure(this.curStateIndex) var isPropagating: Boolean = isLastState for ((layerIndex, layer) in layers.layers.withIndex().reversed()) { layers.curLayerIndex = layerIndex // crucial to provide the right context val isCurLayerRecurrent = layer is RecurrentLayer val isPrevLayerRecurrent = layerIndex > 0 && layers.layers[layerIndex - 1] is RecurrentLayer isPropagating = isPropagating || isCurLayerRecurrent if (isPropagating) { this.propagateLayerRelevance( layer = layer, layerIndex = layerIndex, propagateToPrevState = !isFirstState && isCurLayerRecurrent, propagateToInput = layerIndex > 0 || isFirstState, replaceInputRelevance = isLastState || !isPrevLayerRecurrent ) } } } /** * Propagate the relevance backward through the current layer. * * @param layer the current layer * @param layerIndex the current layer index * @param propagateToPrevState whether to propagate to the previous state * @param propagateToInput whether to propagate to the input * @param replaceInputRelevance a Boolean if the relevance of the input must be replaced or added */ private fun propagateLayerRelevance(layer: Layer<*>, layerIndex: Int, propagateToPrevState: Boolean, propagateToInput: Boolean, replaceInputRelevance: Boolean) { require(propagateToInput || propagateToPrevState) val contributions: LayerParameters = this.sequence.getStateContributions(this.curStateIndex).paramsPerLayer[layerIndex] if (layer is GatedRecurrentLayer) layer.propagateRelevanceToGates(contributions) if (propagateToInput) { if (replaceInputRelevance) layer.setInputRelevance(contributions) else layer.addInputRelevance(contributions) } if (propagateToPrevState) (layer as RecurrentLayer).setRecurrentRelevance(contributions) } /** * Get the relevance of the input of a state of the sequence. * (If the input is Dense it is Dense, if the input is Sparse or SparseBinary it is Sparse). * * @param stateIndex the index of the state from which to extract the input relevance * @param copy whether to return a copy of the relevance or not * * @return the relevance of the input respect to the output */ private fun getInputRelevance(stateIndex: Int, copy: Boolean = true): NDArray<*> = this.sequence.getStateStructure(stateIndex).inputLayer.inputArray.relevance.let { if (copy) it.copy() else it } /** * Reset the sequence. */ private fun reset() { this.lastStateIndex = -1 this.paramsErrorsAccumulator.clear() } }
mpl-2.0
02953fa754483080d8468f261cab1941
38.657492
120
0.703694
4.583952
false
false
false
false
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/constants/Protocol.kt
1
2141
package com.kelsos.mbrc.constants object Protocol { const val Player = "player" const val ProtocolTag = "protocol" const val PluginVersion = "pluginversion" const val ClientNotAllowed = "notallowed" const val PlayerStatus = "playerstatus" const val PlayerRepeat = "playerrepeat" const val PlayerScrobble = "scrobbler" const val PlayerShuffle = "playershuffle" const val PlayerMute = "playermute" const val PlayerPlayPause = "playerplaypause" const val PlayerPrevious = "playerprevious" const val PlayerNext = "playernext" const val PlayerStop = "playerstop" const val PlayerState = "playerstate" const val PlayerVolume = "playervolume" const val NowPlayingTrack = "nowplayingtrack" const val NowPlayingCover = "nowplayingcover" const val NowPlayingPosition = "nowplayingposition" const val NowPlayingLyrics = "nowplayinglyrics" const val NowPlayingRating = "nowplayingrating" const val NowPlayingLfmRating = "nowplayinglfmrating" const val NowPlayingList = "nowplayinglist" const val NowPlayingListPlay = "nowplayinglistplay" const val NowPlayingListRemove = "nowplayinglistremove" const val NowPlayingListMove = "nowplayinglistmove" const val NowPlayingListSearch = "nowplayinglistsearch" const val NowPlayingQueue = "nowplayingqueue" const val ALL = "All" const val DISCOVERY = "discovery" const val PING = "ping" const val PONG = "pong" const val INIT = "init" const val PlayerPlay = "playerplay" const val PlayerPause = "playerpause" const val PlaylistList = "playlistlist" const val PlaylistPlay = "playlistplay" const val NoBroadcast = "nobroadcast" const val LibraryBrowseGenres = "browsegenres" const val LibraryBrowseArtists = "browseartists" const val LibraryBrowseAlbums = "browsealbums" const val LibraryBrowseTracks = "browsetracks" const val ONE = "one" const val VerifyConnection = "verifyconnection" const val RadioStations = "radiostations" const val ProtocolVersionNumber = 4 const val PlayerOutput = "playeroutput" const val PlayerOutputSwitch = "playeroutputswitch" const val LibraryCover = "libraryalbumcover" }
gpl-3.0
6d21af56281c7103c8b72af651ae5d6f
32.984127
57
0.765997
4.273453
false
false
false
false
VTUZ-12IE1bzud/TruckMonitor-Android
app/src/main/kotlin/ru/annin/truckmonitor/presentation/ui/alert/ErrorAlert.kt
1
3481
package ru.annin.truckmonitor.presentation.ui.alert import android.app.Dialog import android.content.DialogInterface import android.graphics.drawable.Drawable import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.app.AlertDialog import com.arellomobile.mvp.MvpAppCompatDialogFragment import ru.annin.truckmonitor.R import ru.annin.truckmonitor.data.InvalidEmailPasswordException import ru.annin.truckmonitor.data.NoInternetConnectionException import ru.annin.truckmonitor.data.ServerNotAvailableException /** * Диалог информирующий об ошибке. * * @author Pavel Annin. */ class ErrorAlert : MvpAppCompatDialogFragment() { companion object { @JvmField val TAG: String = "ru.annin.truckmonitor.ErrorAlert" private const val ARG_ERROR = "ru.annin.truckmonitor.arg.error" @JvmStatic fun newInstance(error: Throwable) = ErrorAlert().apply { arguments = Bundle().apply { putSerializable(ARG_ERROR, error) } } } private enum class Icon {NONE, INTERNET, WARNING } private data class ErrorContent(val icon: Icon, val title: String? = null, val description: String? = null) override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { super.onCreateDialog(savedInstanceState) // Data's val error = arguments?.getSerializable(ARG_ERROR) as Throwable val (icon, title, description) = generateContent(error) val iconDrawable: Drawable? = when (icon) { ErrorAlert.Icon.NONE -> null ErrorAlert.Icon.WARNING -> ContextCompat.getDrawable(activity, R.drawable.ic_error_warning) ErrorAlert.Icon.INTERNET -> ContextCompat.getDrawable(activity, R.drawable.ic_error_wifi) else -> null } return AlertDialog.Builder(activity) .setIcon(iconDrawable) .setTitle(title) .setMessage(description) .setPositiveButton(R.string.alert_error_positive, { dialogInterface: DialogInterface, _: Int -> dialogInterface.dismiss() }) .create() } private fun generateContent(err: Throwable?): ErrorContent { val icon: Icon val title: String? val description: String? when (err) { is NoInternetConnectionException -> { icon = Icon.INTERNET title = getString(R.string.alert_error_no_internet_connection_title) description = getString(R.string.alert_error_no_internet_connection_description) } is ServerNotAvailableException -> { icon = Icon.WARNING title = getString(R.string.alert_error_server_not_available_title) description = getString(R.string.alert_error_server_not_available_description) } is InvalidEmailPasswordException -> { icon = Icon.WARNING title = getString(R.string.alert_error_invalid_email_password_title) description = getString(R.string.alert_error_invalid_email_password_description) } else -> { icon = Icon.WARNING title = getString(R.string.alert_error_unknown_title) description = getString(R.string.alert_error_unknown_description) } } return ErrorContent(icon, title, description) } }
apache-2.0
313a3295840ba401adad920a834627fd
38.712644
140
0.652866
4.648721
false
false
false
false
byu-oit/android-byu-suite-v2
support/src/main/java/edu/byu/support/payment/controller/PaymentAccountsActivity.kt
1
3839
package edu.byu.support.payment.controller import android.app.AlertDialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import android.widget.TextView import edu.byu.support.ByuClickListener import edu.byu.support.ByuViewHolder import edu.byu.support.R import edu.byu.support.activity.ByuActivity import edu.byu.support.activity.ByuRecyclerViewActivity import edu.byu.support.adapter.ByuRecyclerAdapter import edu.byu.support.payment.model.PaymentAccount import edu.byu.support.retrofit.ByuSuccessCallback import edu.byu.support.utils.setPositiveButton import retrofit2.Call import retrofit2.Response /** * Created by geogor37 on 2/9/18 */ abstract class PaymentAccountsActivity: ByuRecyclerViewActivity() { protected val adapter: PaymentMethodAdapter = PaymentMethodAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState, R.layout.payment_accounts_activity) setAdapter(adapter) showProgressDialog() loadPaymentMethods() findViewById<Button>(R.id.manageSourcesButton).setOnClickListener { startChromeTabView(getString(R.string.manage_sources_url)) } } abstract fun loadPaymentMethods() abstract fun continuePaymentProcess(selectedPaymentAccount: PaymentAccount) protected fun showNoAccountsDialog() { AlertDialog.Builder(this) .setTitle(R.string.no_payment_account_title) .setMessage(R.string.no_payment_account_message) .setPositiveButton { _, _ -> onBackPressed() startChromeTabView(getString(R.string.manage_sources_url)) } .setNegativeButton(getString(android.R.string.no)) { _, _ -> onBackPressed() } .show() } protected inner class PaymentMethodAdapter(list: List<PaymentAccount>? = null): ByuRecyclerAdapter<PaymentAccount>(list) { override fun getItemViewType(position: Int): Int { return R.layout.payment_method_list_item } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ByuViewHolder<PaymentAccount> { return PaymentMethodViewHolder(LayoutInflater.from(this@PaymentAccountsActivity).inflate(viewType, parent, false)) } private inner class PaymentMethodViewHolder(itemView: View): ByuViewHolder<PaymentAccount>(itemView) { private val accountTypeImageView = itemView.findViewById<ImageView>(R.id.accountTypeImage) private val accountNumberTextView = itemView.findViewById<TextView>(R.id.accountNumberText) private val accountNicknameTextView = itemView.findViewById<TextView>(R.id.accountNickNameText) private val financialInstitutionTextView = itemView.findViewById<TextView>(R.id.financialInstitutionText) private val processingFeeTextView = itemView.findViewById<TextView>(R.id.processingFeeText) override fun bind(data: PaymentAccount, listener: ByuClickListener<PaymentAccount>?) { accountTypeImageView.setImageResource(data.getImage()) accountNumberTextView.text = data.getFormattedAccountNumber() accountNicknameTextView.text = data.nickname ?: "" financialInstitutionTextView.text = data.financialInstitution processingFeeTextView.visibility = if (data.isCreditCard()) View.VISIBLE else View.GONE itemView.setOnClickListener { continuePaymentProcess(data) } } } } protected abstract inner class PaymentAccountsCallback<T>(callManager: ByuActivity, pathToReadableError: String? = null, defaultErrorMessage: String = ERROR_MESSAGE): ByuSuccessCallback<T>(callManager, defaultErrorMessage, pathToReadableError) { abstract fun parseResponse(response: Response<T>?): List<PaymentAccount>? override fun onSuccess(call: Call<T>?, response: Response<T>?) { dismissProgressDialog() adapter.list = parseResponse(response) if (adapter.isEmpty) { showNoAccountsDialog() } } } }
apache-2.0
0368df39661a41393cd0b79a3472adcc
38.587629
168
0.796301
4.218681
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/friends/feed/post/AddPostDialogController.kt
1
15486
package io.ipoli.android.friends.feed.post import android.annotation.SuppressLint import android.app.Activity.RESULT_OK import android.content.Intent import android.graphics.Bitmap import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.GradientDrawable import android.net.Uri import android.os.Bundle import android.support.v7.app.AlertDialog import android.text.SpannableString import android.view.LayoutInflater import android.view.View import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import io.ipoli.android.R import io.ipoli.android.challenge.entity.Challenge import io.ipoli.android.common.AppState import io.ipoli.android.common.BaseViewStateReducer import io.ipoli.android.common.DataLoadedAction import io.ipoli.android.common.datetime.minutes import io.ipoli.android.common.redux.Action import io.ipoli.android.common.redux.BaseViewState import io.ipoli.android.common.showImagePicker import io.ipoli.android.common.text.DurationFormatter import io.ipoli.android.common.view.* import io.ipoli.android.friends.feed.lightenText import io.ipoli.android.friends.feed.post.AddPostViewState.StateType.* import io.ipoli.android.habit.data.Habit import io.ipoli.android.pet.AndroidPetAvatar import io.ipoli.android.player.data.AndroidAvatar import io.ipoli.android.quest.Quest import kotlinx.android.synthetic.main.item_feed.view.* import kotlinx.android.synthetic.main.view_dialog_header.view.* import java.io.ByteArrayOutputStream sealed class AddPostAction : Action { data class ImagePicked(val imagePath: Uri) : AddPostAction() data class Load(val questId: String?, val habitId: String?, val challengeId: String?) : AddPostAction() data class Save( val playerMessage: String?, val imageData: ByteArray? ) : AddPostAction() } object AddPostReducer : BaseViewStateReducer<AddPostViewState>() { override val stateKey = key<AddPostViewState>() override fun reduce( state: AppState, subState: AddPostViewState, action: Action ) = when (action) { is AddPostAction.Load -> subState.copy(type = LOADING) is DataLoadedAction.AddPostDataChanged -> { val player = action.player subState.copy( type = DATA_CHANGED, quest = action.quest, habit = action.habit, challenge = action.challenge, petAvatar = AndroidPetAvatar.valueOf(player.pet.avatar.name), playerAvatar = AndroidAvatar.valueOf(player.avatar.name), playerName = player.displayName, playerUsername = player.username, playerLevel = player.level ) } is AddPostAction.ImagePicked -> subState.copy( type = IMAGE_CHANGED, imagePath = action.imagePath ) else -> subState } override fun defaultState() = AddPostViewState( type = LOADING, petAvatar = null, playerAvatar = null, playerName = null, playerUsername = null, playerLevel = null, imagePath = null, quest = null, habit = null, challenge = null ) } data class AddPostViewState( val type: StateType, val petAvatar: AndroidPetAvatar?, val playerAvatar: AndroidAvatar?, val playerName: String?, val playerUsername: String?, val playerLevel: Int?, val imagePath: Uri?, val quest: Quest?, val habit: Habit?, val challenge: Challenge? ) : BaseViewState() { enum class StateType { LOADING, DATA_CHANGED, IMAGE_CHANGED } } class AddPostDialogController(args: Bundle? = null) : ReduxDialogController<AddPostAction, AddPostViewState, AddPostReducer>(args) { override val reducer = AddPostReducer companion object { const val PICK_IMAGE_REQUEST_CODE = 42 } private var questId: String? = null private var habitId: String? = null private var challengeId: String? = null private var postListener: (() -> Unit)? = null constructor( questId: String?, habitId: String?, challengeId: String?, postListener: (() -> Unit)? = null ) : this() { this.questId = questId this.habitId = habitId this.challengeId = challengeId this.postListener = postListener } @SuppressLint("InflateParams") override fun onCreateContentView(inflater: LayoutInflater, savedViewState: Bundle?): View { val view = inflater.inflate(R.layout.dialog_add_post, null) view.feedItemContainer.background = null registerForActivityResult(PICK_IMAGE_REQUEST_CODE) view.pickPostImage.onDebounceClick { activity?.showImagePicker(PICK_IMAGE_REQUEST_CODE) } view.divider.gone() view.comment.gone() view.share.gone() view.reactionGroup.goneViews() return view } override fun onCreateLoadAction() = AddPostAction.Load( questId = questId, habitId = habitId, challengeId = challengeId ) override fun onHeaderViewCreated(headerView: View) { headerView.dialogHeaderTitle.setText(R.string.add_post_title) } override fun onCreateDialog( dialogBuilder: AlertDialog.Builder, contentView: View, savedViewState: Bundle? ): AlertDialog = dialogBuilder .setPositiveButton(R.string.dialog_ok, null) .setNegativeButton(R.string.cancel, null) .create() override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if ((requestCode == PICK_IMAGE_REQUEST_CODE) && resultCode == RESULT_OK && data != null && data.data != null ) { dispatch(AddPostAction.ImagePicked(data.data)) } } override fun onDialogCreated(dialog: AlertDialog, contentView: View) { dialog.setOnShowListener { setPositiveButtonListener { contentView.postImage.isDrawingCacheEnabled = true contentView.postImage.buildDrawingCache() val imageData = contentView.postImage.drawable?.let { val bm = (contentView.postImage.drawable as BitmapDrawable).bitmap val baos = ByteArrayOutputStream() bm.compress(Bitmap.CompressFormat.JPEG, 80, baos) baos.toByteArray() } dispatch( AddPostAction.Save( contentView.playerMessageEdit.text.toString(), imageData ) ) dismiss() postListener?.invoke() } } } override fun render(state: AddPostViewState, view: View) { when (state.type) { DATA_CHANGED -> { changeIcon(AndroidPetAvatar.valueOf(state.petAvatar!!.name).headImage) renderPlayer(view, state) view.postedTime.text = "Now" renderMessage(view, state) view.pickPostImage.visible() if (state.imagePath == null) { view.postImage.gone() } else { view.postImage.loadFromFile(state.imagePath) view.postImage.visible() } } else -> { } } } private fun renderMessage( view: View, state: AddPostViewState ) { view.messageGroup.visible() (view.complexGroup.views() + view.feedBigPicture + view.feedAchievement).map { it.gone() } view.challengeGroup.gone() val vm = state.postViewModel view.feedMessage.text = vm.text view.feedMessageIcon.setImageResource(vm.icon) if (vm is PostViewModel.QuestViewModel && vm.challengeName != null) { view.feedChallengeTitle.text = vm.challengeName view.challengeGroup.visible() val challengeGradientDrawable = view.feedChallengeIconBackground.background as GradientDrawable challengeGradientDrawable.mutate() challengeGradientDrawable.setColor(colorRes(R.color.md_blue_500)) } } private fun renderPlayer( view: View, state: AddPostViewState ) { Glide.with(view.context).load(state.playerAvatar!!.image) .apply(RequestOptions.circleCropTransform()) .into(view.playerAvatar) val gradientDrawable = view.playerAvatar.background as GradientDrawable gradientDrawable.mutate() gradientDrawable.setColor(colorRes(state.playerAvatar.backgroundColor)) view.playerName.text = if (state.playerName.isNullOrBlank()) stringRes(R.string.unknown_hero) else state.playerName @SuppressLint("SetTextI18n") view.playerUsername.text = "@${state.playerUsername}" view.playerLevel.text = "Level ${state.playerLevel}" } sealed class PostViewModel { abstract val text: SpannableString abstract val icon: Int data class QuestViewModel( override val text: SpannableString, override val icon: Int, val challengeName: String? = null ) : PostViewModel() data class HabitViewModel( override val text: SpannableString, override val icon: Int, val challengeName: String? = null ) : PostViewModel() data class ChallengeViewModel( override val text: SpannableString, override val icon: Int ) : PostViewModel() } private val AddPostViewState.postViewModel: PostViewModel get() = when { quest != null && !quest.isFromChallenge && !quest.hasPomodoroTimer -> { val completedQuest = stringRes(R.string.feed_completed_quest) val message = "$completedQuest ${quest.name}" val trackedDuration = if (quest.hasTimer) quest.actualDuration.asMinutes else 0.minutes val finalMessage = if (trackedDuration.intValue > 0) { val duration = stringRes( R.string.feed_timer, DurationFormatter.formatShort( activity!!, trackedDuration.intValue ) ) activity!!.lightenText(message + duration, completedQuest, duration) } else activity!!.lightenText(message, completedQuest) PostViewModel.QuestViewModel(finalMessage, R.drawable.ic_post_done) } quest != null && quest.isFromChallenge && !quest.hasPomodoroTimer -> { val completedQuest = stringRes(R.string.feed_completed_quest) val message = "$completedQuest ${quest.name}" val durationTracked = if (quest.hasTimer) quest.actualDuration.asMinutes else 0.minutes val finalMessage = if (durationTracked.intValue > 0) { val duration = stringRes( R.string.feed_timer, DurationFormatter.formatShort( activity!!, durationTracked.intValue ) ) activity!!.lightenText(message + duration, completedQuest, duration) } else activity!!.lightenText(message, completedQuest) PostViewModel.QuestViewModel( finalMessage, R.drawable.ic_post_done, challenge!!.name ) } quest != null && !quest.isFromChallenge -> { val completedQuest = stringRes(R.string.feed_completed_quest) val pomodoros = stringRes(R.string.feed_pomodoro_count, quest.totalPomodoros!!) val m = "$completedQuest ${quest.name} $pomodoros" PostViewModel.QuestViewModel( activity!!.lightenText(m, completedQuest, pomodoros), R.drawable.ic_post_done ) } quest != null && quest.isFromChallenge -> { val completedQuest = stringRes(R.string.feed_completed_quest) val pomodoros = stringRes(R.string.feed_pomodoro_count, quest.totalPomodoros!!) val m = "$completedQuest ${quest.name} $pomodoros" PostViewModel.QuestViewModel( activity!!.lightenText(m, completedQuest, pomodoros), R.drawable.ic_post_done, challenge!!.name ) } habit != null -> { val streak = habit.streak.current val bestStreak = habit.streak.best val message = when { streak == 1 -> { val completedHabit = stringRes(R.string.feed_completed_habit) val m = "$completedHabit ${habit.name}" activity!!.lightenText(m, completedHabit) } streak < bestStreak -> { val completedHabit = stringRes(R.string.feed_completed_habit) val timesInARow = stringRes(R.string.feed_times_in_a_row) val m = "$completedHabit ${habit.name} ${streak} $timesInARow" activity!!.lightenText(m, completedHabit, timesInARow) } else -> { val newBestStreak = stringRes(R.string.feed_best_streak_habit) val timesInARow = stringRes(R.string.feed_times_in_a_row) val m = "$newBestStreak ${habit.name}: ${bestStreak} $timesInARow" activity!!.lightenText(m, newBestStreak, timesInARow) } } PostViewModel.HabitViewModel( message, R.drawable.ic_post_habit, if (habit.isFromChallenge) challenge!!.name else null ) } challenge != null && !challenge.isCompleted -> { val accepted = stringRes(R.string.feed_accepted_challenge) val m = "$accepted ${challenge.name}" PostViewModel.ChallengeViewModel( activity!!.lightenText(m, accepted), R.drawable.ic_post_challenge ) } challenge != null && challenge.isCompleted -> { val completed = stringRes(R.string.feed_completed_challenge) val m = "$completed ${challenge.name}" PostViewModel.ChallengeViewModel( activity!!.lightenText(m, completed), R.drawable.ic_post_challenge ) } else -> throw IllegalArgumentException() } }
gpl-3.0
3a4033bcf6681c4cf5c991a2123c656b
35.269321
104
0.579297
5.062439
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/common/PermissionRationaleDialogController.kt
1
1984
package io.ipoli.android.common import android.os.Bundle import android.support.v7.app.AlertDialog import android.view.LayoutInflater import android.view.View import android.widget.TextView import io.ipoli.android.R import io.ipoli.android.common.view.BaseDialogController import io.ipoli.android.common.view.stringRes import kotlinx.android.synthetic.main.view_dialog_header.view.* /** * Created by Polina Zhelyazkova <[email protected]> * on 4/2/18. */ class PermissionRationaleDialogController(args: Bundle? = null) : BaseDialogController(args) { private lateinit var message: String private lateinit var positiveListener: () -> Unit private lateinit var negativeListener: () -> Unit constructor( message: String, positiveListener: () -> Unit, negativeListener: () -> Unit ) : this() { this.message = message this.positiveListener = positiveListener this.negativeListener = negativeListener } override fun onCreateContentView(inflater: LayoutInflater, savedViewState: Bundle?): View { val view = inflater.inflate(R.layout.dialog_permission_rationale, null) (view as TextView).text = if (message.isNotEmpty()) message else stringRes(R.string.permission_rationale_default_message) return view } override fun onCreateDialog( dialogBuilder: AlertDialog.Builder, contentView: View, savedViewState: Bundle? ): AlertDialog = dialogBuilder .setPositiveButton(R.string.dialog_ok, { _, _ -> positiveListener() }) .setNegativeButton(R.string.cancel, { _, _ -> negativeListener() }) .create() override fun onHeaderViewCreated(headerView: View?) { headerView!!.dialogHeaderTitle.setText(R.string.permission_rationale_title) headerView.dialogHeaderIcon.setImageResource(R.drawable.logo) } }
gpl-3.0
900c96224772d95d46e8839217103271
30.507937
95
0.673387
4.679245
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/accessibility/AccessibilityUsageTrackerCollector.kt
5
1410
// 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.accessibility import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventId import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.openapi.project.Project import com.intellij.openapi.startup.ProjectPostStartupActivity import java.util.concurrent.ConcurrentLinkedQueue internal class AccessibilityUsageTrackerCollector : CounterUsagesCollector() { override fun getGroup(): EventLogGroup = GROUP class CollectStatisticsTask : ProjectPostStartupActivity { override suspend fun execute(project: Project) { raisedEvents.forEach(EventId::log) } } companion object { private val raisedEvents: MutableCollection<EventId> = ConcurrentLinkedQueue() private val GROUP = EventLogGroup("accessibility", 1) @JvmField val SCREEN_READER_DETECTED = GROUP.registerEvent("screen.reader.detected") @JvmField val SCREEN_READER_SUPPORT_ENABLED = GROUP.registerEvent("screen.reader.support.enabled") @JvmField val SCREEN_READER_SUPPORT_ENABLED_VM = GROUP.registerEvent("screen.reader.support.enabled.in.vmoptions") @JvmStatic fun featureTriggered(feature: EventId) { raisedEvents.add(feature) } } }
apache-2.0
3f7c30bc196c0a284b3041f101d0b9dc
38.194444
120
0.785816
4.7
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/fe10/highlighting/src/org/jetbrains/kotlin/idea/highlighter/dsl/DslKotlinHighlightingVisitorExtension.kt
7
3252
// 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.highlighter.dsl import com.intellij.ide.highlighter.custom.CustomHighlighterColors.* import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.psi.PsiElement import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.base.fe10.highlighting.KotlinBaseFe10HighlightingBundle import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingVisitorExtension import org.jetbrains.kotlin.resolve.calls.DslMarkerUtils import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.annotationClass import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import kotlin.math.absoluteValue class DslKotlinHighlightingVisitorExtension : KotlinHighlightingVisitorExtension() { override fun highlightDeclaration(elementToHighlight: PsiElement, descriptor: DeclarationDescriptor): TextAttributesKey? { return null } override fun highlightCall(elementToHighlight: PsiElement, resolvedCall: ResolvedCall<*>): TextAttributesKey? { return dslCustomTextStyle(resolvedCall.resultingDescriptor) } companion object { private const val STYLE_COUNT = 4 private val STYLE_KEYS = listOf( CUSTOM_KEYWORD1_ATTRIBUTES, CUSTOM_KEYWORD2_ATTRIBUTES, CUSTOM_KEYWORD3_ATTRIBUTES, CUSTOM_KEYWORD4_ATTRIBUTES ) private val styles = (1..STYLE_COUNT).map { index -> TextAttributesKey.createTextAttributesKey(externalKeyName(index), STYLE_KEYS[index - 1]) } val descriptionsToStyles = (1..STYLE_COUNT).associate { index -> KotlinBaseFe10HighlightingBundle.message("highlighter.name.dsl") + styleOptionDisplayName(index) to styleById(index) } fun externalKeyName(index: Int) = "KOTLIN_DSL_STYLE$index" fun styleOptionDisplayName(index: Int) = KotlinBaseFe10HighlightingBundle.message("highlighter.name.style") + index fun styleIdByMarkerAnnotation(markerAnnotation: ClassDescriptor): Int { val markerAnnotationFqName = markerAnnotation.fqNameSafe return (markerAnnotationFqName.asString().hashCode() % STYLE_COUNT).absoluteValue + 1 } fun dslCustomTextStyle(callableDescriptor: CallableDescriptor): TextAttributesKey? { val markerAnnotation = callableDescriptor.annotations.find { annotation -> annotation.annotationClass?.isDslHighlightingMarker() ?: false }?.annotationClass ?: return null val styleId = styleIdByMarkerAnnotation(markerAnnotation) return styleById(styleId) } fun styleById(styleId: Int): TextAttributesKey = styles[styleId - 1] } } @ApiStatus.Internal fun ClassDescriptor.isDslHighlightingMarker(): Boolean { return annotations.any { it.annotationClass?.fqNameSafe == DslMarkerUtils.DSL_MARKER_FQ_NAME } }
apache-2.0
afd8b1b4806f73ca606cb0fa22db018d
42.945946
128
0.750615
5.034056
false
false
false
false
GunoH/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/Changes.kt
15
993
/* * Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.intellij.build.images.sync internal class Changes(val includeRemoved: Boolean = true) { enum class Type { MODIFIED, ADDED, DELETED } val added: MutableCollection<String> = mutableListOf() val modified: MutableCollection<String> = mutableListOf() val removed: MutableCollection<String> = mutableListOf() fun all() = mutableListOf<String>().also { it += added it += modified if (includeRemoved) it += removed } fun clear() { added.clear() modified.clear() removed.clear() } fun register(type: Type, changes: Collection<String>) { added.removeAll(changes) modified.removeAll(changes) removed.removeAll(changes) when (type) { Type.ADDED -> added += changes Type.MODIFIED -> modified += changes Type.DELETED -> removed += changes } } }
apache-2.0
8906fc63431247bd1ec308ba52882206
25.864865
140
0.677744
4.189873
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpData.kt
4
3863
// 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.refactoring.pullUp import com.intellij.psi.PsiNamedElement import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor import org.jetbrains.kotlin.idea.refactoring.memberInfo.KtPsiClassWrapper import org.jetbrains.kotlin.idea.refactoring.memberInfo.getClassDescriptorIfAny import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.idea.util.getTypeSubstitution import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.utils.collectDescriptorsFiltered import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.utils.keysToMapExceptNulls class KotlinPullUpData( val sourceClass: KtClassOrObject, val targetClass: PsiNamedElement, val membersToMove: Collection<KtNamedDeclaration> ) { val resolutionFacade = sourceClass.getResolutionFacade() val sourceClassContext = resolutionFacade.analyzeWithAllCompilerChecks(sourceClass).bindingContext val sourceClassDescriptor = sourceClassContext[BindingContext.DECLARATION_TO_DESCRIPTOR, sourceClass] as ClassDescriptor val memberDescriptors = membersToMove.keysToMapExceptNulls { when (it) { is KtPsiClassWrapper -> it.psiClass.getJavaClassDescriptor(resolutionFacade) is KtParameter -> sourceClassContext[BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, it] else -> sourceClassContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it] } } val targetClassDescriptor = targetClass.getClassDescriptorIfAny(resolutionFacade)!! val superEntryForTargetClass = sourceClass.getSuperTypeEntryByDescriptor(targetClassDescriptor, sourceClassContext) val targetClassSuperResolvedCall = superEntryForTargetClass.getResolvedCall(sourceClassContext) private val typeParametersInSourceClassContext by lazy { sourceClassDescriptor.declaredTypeParameters + sourceClass.getResolutionScope(sourceClassContext, resolutionFacade) .collectDescriptorsFiltered(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS) .filterIsInstance<TypeParameterDescriptor>() } val sourceToTargetClassSubstitutor: TypeSubstitutor by lazy { val substitution = LinkedHashMap<TypeConstructor, TypeProjection>() typeParametersInSourceClassContext.forEach { substitution[it.typeConstructor] = TypeProjectionImpl(TypeIntersector.getUpperBoundsAsType(it)) } val superClassSubstitution = getTypeSubstitution(targetClassDescriptor.defaultType, sourceClassDescriptor.defaultType) ?: emptyMap() for ((typeConstructor, typeProjection) in superClassSubstitution) { val subClassTypeParameter = typeProjection.type.constructor.declarationDescriptor as? TypeParameterDescriptor ?: continue val superClassTypeParameter = typeConstructor.declarationDescriptor ?: continue substitution[subClassTypeParameter.typeConstructor] = TypeProjectionImpl(superClassTypeParameter.defaultType) } TypeSubstitutor.create(substitution) } val isInterfaceTarget: Boolean = targetClassDescriptor.kind == ClassKind.INTERFACE }
apache-2.0
95d5c0953609e2ca1ef95a9c894f671f
49.828947
158
0.802485
5.77429
false
false
false
false
jk1/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUAnnotation.kt
4
2446
/* * 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 org.jetbrains.uast.java import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiClass import org.jetbrains.uast.* import org.jetbrains.uast.java.expressions.JavaUNamedExpression class JavaUAnnotation( override val psi: PsiAnnotation, givenParent: UElement? ) : JavaAbstractUElement(givenParent), UAnnotationEx, UAnchorOwner { override val javaPsi: PsiAnnotation = psi override val qualifiedName: String? get() = psi.qualifiedName override val attributeValues: List<UNamedExpression> by lz { val attributes = psi.parameterList.attributes attributes.map { attribute -> JavaUNamedExpression(attribute, this) } } override val uastAnchor: UIdentifier? get() = psi.nameReferenceElement?.referenceNameElement?.let { UIdentifier(it, this) } override fun resolve(): PsiClass? = psi.nameReferenceElement?.resolve() as? PsiClass override fun findAttributeValue(name: String?): UExpression? { val context = getUastContext() val attributeValue = psi.findAttributeValue(name) ?: return null return context.convertElement(attributeValue, this, null) as? UExpression ?: UastEmptyExpression(this) } override fun findDeclaredAttributeValue(name: String?): UExpression? { val context = getUastContext() val attributeValue = psi.findDeclaredAttributeValue(name) ?: return null return context.convertElement(attributeValue, this, null) as? UExpression ?: UastEmptyExpression(this) } companion object { @JvmStatic fun wrap(annotation: PsiAnnotation): UAnnotation = JavaUAnnotation(annotation, null) @JvmStatic fun wrap(annotations: List<PsiAnnotation>): List<UAnnotation> = annotations.map { JavaUAnnotation(it, null) } @JvmStatic fun wrap(annotations: Array<PsiAnnotation>): List<UAnnotation> = annotations.map { JavaUAnnotation(it, null) } } }
apache-2.0
4d7a70fc5aac0420194a77662ae9e7d0
36.075758
114
0.754702
4.676864
false
false
false
false
ktorio/ktor
ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/CIOHeaders.kt
1
1384
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.http.cio import io.ktor.http.* import io.ktor.util.* /** * An adapter from CIO low-level headers map to ktor [Headers] interface */ public class CIOHeaders(private val headers: HttpHeadersMap) : Headers { private val names: Set<String> by lazy(LazyThreadSafetyMode.NONE) { LinkedHashSet<String>(headers.size).apply { for (i in 0 until headers.size) { add(headers.nameAt(i).toString()) } } } override val caseInsensitiveName: Boolean get() = true override fun names(): Set<String> = names override fun get(name: String): String? = headers[name]?.toString() override fun getAll(name: String): List<String>? = headers.getAll(name).map { it.toString() }.toList().takeIf { it.isNotEmpty() } override fun isEmpty(): Boolean = headers.size == 0 override fun entries(): Set<Map.Entry<String, List<String>>> { return (0 until headers.size).map { idx -> Entry(idx) }.toSet() } private inner class Entry(private val idx: Int) : Map.Entry<String, List<String>> { override val key: String get() = headers.nameAt(idx).toString() override val value: List<String> get() = listOf(headers.valueAt(idx).toString()) } }
apache-2.0
2f5fa77654d5326a24df464aec974324
33.6
118
0.653179
3.88764
false
false
false
false
marius-m/wt4
models/src/main/java/lt/markmerkk/entities/TimeGap.kt
1
2583
package lt.markmerkk.entities import lt.markmerkk.TimeProvider import lt.markmerkk.round import lt.markmerkk.utils.LogFormatters import org.joda.time.DateTime import org.joda.time.Duration import org.joda.time.LocalDate import org.joda.time.LocalTime data class TimeGap private constructor( val start: DateTime, val end: DateTime ) { val duration: Duration = Duration(start, end) companion object { fun asEmpty(timeProvider: TimeProvider): TimeGap { val now = timeProvider.now().round() return TimeGap(start = now, end = now) } fun fromRaw( startDateRaw: String, startTimeRaw: String, endDateRaw: String, endTimeRaw: String ): TimeGap { val startDate = LogFormatters.dateFromRawOrDefault(startDateRaw) val startTime = LogFormatters.timeFromRawOrDefault(startTimeRaw) val endDate = LogFormatters.dateFromRawOrDefault(endDateRaw) val endTime = LogFormatters.timeFromRawOrDefault(endTimeRaw) return from( start = startDate.toDateTime(startTime), end = endDate.toDateTime(endTime) ) } /** * Ensures the time gap is a valid one * Note: Will always have at least 1 min gap */ fun from(start: DateTime, end: DateTime): TimeGap { val rStart = start.round() val rEnd = end.round() if (rStart.isEqual(rEnd) || rEnd.isBefore(rStart)) { return TimeGap(rStart, rStart) } return TimeGap(rStart, rEnd) } fun TimeGap.withStartDate(startDate: LocalDate): TimeGap { return from( start = start.withDate(startDate), end = end ) } fun TimeGap.withStartTime(startTime: LocalTime): TimeGap { return from( start = start.withTime(startTime.round()), end = end ) } fun TimeGap.withEndDate(endDate: LocalDate): TimeGap { return from( start = start, end = end.withDate(endDate) ) } fun TimeGap.withEndTime(endTime: LocalTime): TimeGap { return from( start = start, end = end.withTime(endTime.round()) ) } fun LogTime.toTimeGap(): TimeGap { return from(start = this.start, end = this.end) } } }
apache-2.0
224ac98f558dbc93e122da2b189b9e0f
29.046512
76
0.555943
4.68784
false
false
false
false
cfieber/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/StartExecutionHandler.kt
1
4485
/* * Copyright 2017 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.q.handler import com.netflix.spinnaker.orca.ExecutionStatus.* import com.netflix.spinnaker.orca.events.ExecutionComplete import com.netflix.spinnaker.orca.events.ExecutionStarted import com.netflix.spinnaker.orca.ext.initialStages import com.netflix.spinnaker.orca.pipeline.model.Execution import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.q.CancelExecution import com.netflix.spinnaker.orca.q.StartExecution import com.netflix.spinnaker.orca.q.StartStage import com.netflix.spinnaker.orca.q.pending.PendingExecutionService import com.netflix.spinnaker.q.Queue import net.logstash.logback.argument.StructuredArguments.value import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Qualifier import org.springframework.context.ApplicationEventPublisher import org.springframework.stereotype.Component import java.time.Clock import java.time.Instant @Component class StartExecutionHandler( override val queue: Queue, override val repository: ExecutionRepository, private val pendingExecutionService: PendingExecutionService, @Qualifier("queueEventPublisher") private val publisher: ApplicationEventPublisher, private val clock: Clock ) : OrcaMessageHandler<StartExecution> { override val messageType = StartExecution::class.java private val log: Logger get() = LoggerFactory.getLogger(javaClass) override fun handle(message: StartExecution) { message.withExecution { execution -> if (execution.status == NOT_STARTED && !execution.isCanceled) { if (execution.shouldQueue()) { execution.pipelineConfigId?.let { log.info("Queueing {} {} {}", execution.application, execution.name, execution.id) pendingExecutionService.enqueue(it, message) } } else { start(execution) } } else { terminate(execution) } } } private fun start(execution: Execution) { if (execution.isAfterStartTimeExpiry()) { log.warn("Execution (type ${execution.type}, id {}, application: {}) start was canceled because" + "start time would be after defined start time expiry (now: ${clock.millis()}, expiry: ${execution.startTimeExpiry})", value("executionId", execution.id), value("application", execution.application)) queue.push(CancelExecution( execution.type, execution.id, execution.application, "spinnaker", "Could not begin execution before start time expiry" )) } else { val initialStages = execution.initialStages() if (initialStages.isEmpty()) { log.warn("No initial stages found (executionId: ${execution.id})") repository.updateStatus(execution.type, execution.id, TERMINAL) publisher.publishEvent(ExecutionComplete(this, execution.type, execution.id, TERMINAL)) } else { repository.updateStatus(execution.type, execution.id, RUNNING) initialStages.forEach { queue.push(StartStage(it)) } publisher.publishEvent(ExecutionStarted(this, execution.type, execution.id)) } } } private fun terminate(execution: Execution) { if (execution.status == CANCELED || execution.isCanceled) { publisher.publishEvent(ExecutionComplete(this, execution.type, execution.id, execution.status)) } else { log.warn("Execution (type: ${execution.type}, id: {}, status: ${execution.status}, application: {})" + " cannot be started unless state is NOT_STARTED. Ignoring StartExecution message.", value("executionId", execution.id), value("application", execution.application)) } } private fun Execution.isAfterStartTimeExpiry() = startTimeExpiry ?.let { Instant.ofEpochMilli(it) } ?.isBefore(clock.instant()) ?: false }
apache-2.0
45d1ae144126189900cf7efc6371151e
39.405405
125
0.725975
4.525732
false
false
false
false