repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
53 values
size
stringlengths
2
6
content
stringlengths
73
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
977
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
square/leakcanary
shark/src/main/java/shark/internal/ShallowSizeCalculator.kt
2
2730
package shark.internal import shark.HeapGraph import shark.HeapObject.HeapClass import shark.HeapObject.HeapInstance import shark.HeapObject.HeapObjectArray import shark.HeapObject.HeapPrimitiveArray import shark.internal.ObjectArrayReferenceReader.Companion.isSkippablePrimitiveWrapperArray import shark.ValueHolder /** * Provides approximations for the shallow size of objects in memory. * * Determining the actual shallow size of an object in memory is hard, as it changes for each VM * implementation, depending on the various memory layout optimizations and bit alignment. * * More on this topic: https://dev.to/pyricau/the-real-size-of-android-objects-1i2e */ internal class ShallowSizeCalculator(private val graph: HeapGraph) { fun computeShallowSize(objectId: Long): Int { return when (val heapObject = graph.findObjectById(objectId)) { is HeapInstance -> { if (heapObject.instanceClassName == "java.lang.String") { // In PathFinder we ignore the value field of String instances when building the dominator // tree, so we add that size back here. val valueObjectId = heapObject["java.lang.String", "value"]?.value?.asNonNullObjectId heapObject.byteSize + if (valueObjectId != null) { computeShallowSize(valueObjectId) } else { 0 } } else { // Total byte size of fields for instances of this class, as registered in the class dump. // The actual memory layout likely differs. heapObject.byteSize } } // Number of elements * object id size is HeapObjectArray -> { if (heapObject.isSkippablePrimitiveWrapperArray) { // In PathFinder we ignore references from primitive wrapper arrays when building the // dominator tree, so we add that size back here. val elementIds = heapObject.readRecord().elementIds val shallowSize = elementIds.size * graph.identifierByteSize val firstNonNullElement = elementIds.firstOrNull { it != ValueHolder.NULL_REFERENCE } if (firstNonNullElement != null) { val sizeOfOneElement = computeShallowSize(firstNonNullElement) val countOfNonNullElements = elementIds.count { it != ValueHolder.NULL_REFERENCE } shallowSize + (sizeOfOneElement * countOfNonNullElements) } else { shallowSize } } else { heapObject.byteSize } } // Number of elements * primitive type size is HeapPrimitiveArray -> heapObject.byteSize // This is probably way off but is a cheap approximation. is HeapClass -> heapObject.recordSize } } }
apache-2.0
607adf9fd6464d355ed22e2f2b93d63b
41
100
0.681685
4.857651
false
false
false
false
spinnaker/gate
gate-proxy/src/main/kotlin/com/netflix/spinnaker/gate/controllers/ApiExtensionController.kt
1
3960
/* * Copyright 2020 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.gate.controllers import com.netflix.spinnaker.gate.api.extension.ApiExtension import com.netflix.spinnaker.gate.api.extension.HttpRequest import com.netflix.spinnaker.kork.annotations.Alpha import com.netflix.spinnaker.kork.exceptions.SpinnakerException import com.netflix.spinnaker.kork.exceptions.SystemException import com.netflix.spinnaker.kork.web.exceptions.NotFoundException import com.squareup.okhttp.internal.http.HttpMethod import org.springframework.beans.factory.ObjectProvider import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.util.CollectionUtils import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import java.io.IOException import java.util.stream.Collectors import javax.servlet.http.HttpServletRequest /** * A top-level [RestController] that exposes all api extensions under a common * `/extensions/{{ApiExtension.id}}` path. */ @Alpha @RestController @RequestMapping("/extensions") class ApiExtensionController @Autowired constructor(private val apiExtensionsProvider: ObjectProvider<List<ApiExtension>>) { init { val duplicateApiExtensionIds = apiExtensionsProvider.getIfAvailable { ArrayList() } .groupBy { it.id().toLowerCase() } .filter { it.value.size > 1 } .map { it.value } .flatten() .map { "[class=${it.javaClass}], id=${it.id()}]" } if (duplicateApiExtensionIds.isNotEmpty()) { throw SystemException("Duplicate api extensions were detected (${duplicateApiExtensionIds.joinToString(", ")}") } } @RequestMapping(value = ["/{extension}/**"]) fun any( @PathVariable(value = "extension") extension: String, @RequestParam requestParams: Map<String?, String?>?, httpServletRequest: HttpServletRequest ): ResponseEntity<Any> { val httpRequest = HttpRequest.of( httpServletRequest.method, httpServletRequest.requestURI.replace("/extensions/$extension", ""), httpServletRequest.headerNames.toList().map { it to httpServletRequest.getHeader(it) }.toMap(), requestParams ) if (HttpMethod.permitsRequestBody(httpRequest.method)) { try { httpRequest.body = httpServletRequest .reader .lines() .collect(Collectors.joining(System.lineSeparator())) } catch (e: IOException) { throw SpinnakerException("Unable to read request body", e) } } val apiExtension = apiExtensionsProvider.getIfAvailable { ArrayList() }.stream() .filter { e: ApiExtension -> e.id().equals(extension, ignoreCase = true) && e.handles(httpRequest) } .findFirst() if (!apiExtension.isPresent) { throw NotFoundException() } val httpResponse = apiExtension.get().handle(httpRequest) val status = HttpStatus.resolve(httpResponse.status) ?: throw SpinnakerException("Unsupported http status code: " + httpResponse.status) return ResponseEntity( httpResponse.body, CollectionUtils.toMultiValueMap(httpResponse.headers.map { it.key to listOf(it.value) }.toMap()), status ) } }
apache-2.0
d176b8621a4563e40d435c3f101e2266
37.076923
124
0.740909
4.551724
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/psi/element/MdLinkElementStubElementType.kt
1
3660
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.psi.element import com.intellij.lang.LighterAST import com.intellij.lang.LighterASTNode import com.intellij.lang.LighterASTTokenNode import com.intellij.psi.PsiElement import com.intellij.psi.stubs.* import com.intellij.psi.tree.IElementType import com.intellij.util.CharTable import com.vladsch.md.nav.MdLanguage import com.vladsch.md.nav.psi.index.MdLinkElementIndex import java.io.IOException abstract class MdLinkElementStubElementType<Elem : MdLinkElement<*>, Stub : MdLinkElementStub<Elem>>(debugName: String) : ILightStubElementType<Stub, Elem>(debugName, MdLanguage.INSTANCE) { abstract override fun createPsi(stub: Stub): Elem // = MultiMarkdownWikiLinkImpl(stub, this) abstract override fun getExternalId(): String //= "markdown.link-element" abstract fun createStub(parentStub: StubElement<PsiElement>, linkRefWithAnchorText: String): Stub //= MultiMarkdownWikiLinkStubImpl(parentStub, linkRefWithAnchorText) abstract fun getLinkRefTextType(): IElementType? //= MultiMarkdownTypes.WIKI_LINK_REF_TEXT abstract fun getLinkRefAnchorMarkerType(): IElementType? //= MultiMarkdownTypes.WIKI_LINK_REF_ANCHOR_MARKER abstract fun getLinkRefAnchorType(): IElementType? //= MultiMarkdownTypes.WIKI_LINK_REF_ANCHOR override fun createStub(psi: Elem, parentStub: StubElement<PsiElement>): Stub { return createStub(parentStub, psi.linkRefWithAnchorText) } @Throws(IOException::class) override fun serialize(stub: Stub, dataStream: StubOutputStream) { //dataStream.writeName(stub.getKey()); dataStream.writeName(stub.linkRefWithAnchorText) } @Throws(IOException::class) override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<PsiElement>): Stub { val linkRefWithAnchorText = dataStream.readName()?.string ?: "" return createStub(parentStub, linkRefWithAnchorText) } override fun indexStub(stub: Stub, sink: IndexSink) { sink.occurrence(MdLinkElementIndex.KEY, stub.linkRefWithAnchorText) } override fun createStub(tree: LighterAST, node: LighterASTNode, parentStub: StubElement<PsiElement>): Stub { val children = tree.getChildren(node) var linkRefWithAnchorText: String = "" var count = 1 if (getLinkRefAnchorMarkerType() != null) count++ if (getLinkRefAnchorType() != null) count++ for (child in children) { if (child.tokenType == getLinkRefTextType()) { linkRefWithAnchorText += if (child !is LighterASTTokenNode) child.toString() else intern(tree.charTable, child) if (--count == 0) break } if (child.tokenType == getLinkRefAnchorMarkerType()) { linkRefWithAnchorText += if (child !is LighterASTTokenNode) child.toString() else intern(tree.charTable, child) if (--count == 0) break } if (child.tokenType == getLinkRefAnchorType()) { linkRefWithAnchorText += if (child !is LighterASTTokenNode) child.toString() else intern(tree.charTable, child) break } } return createStub(parentStub, linkRefWithAnchorText) } companion object { private fun intern(table: CharTable, node: LighterASTNode): String { assert(node is LighterASTTokenNode, { node }) return table.intern((node as LighterASTTokenNode).text).toString() } } }
apache-2.0
2c52a8b6ff2bbb08c235f63f29194253
46.532468
177
0.707923
4.912752
false
true
false
false
rei-m/android_hyakuninisshu
feature/corecomponent/src/main/java/me/rei_m/hyakuninisshu/feature/corecomponent/widget/view/VerticalSingleLineTextView.kt
1
2668
/* * Copyright (c) 2020. Rei Matsushita * * 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. */ /* ktlint-disable package-name */ package me.rei_m.hyakuninisshu.feature.corecomponent.widget.view import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.util.AttributeSet import android.view.View import androidx.annotation.DimenRes import androidx.core.content.res.ResourcesCompat import me.rei_m.hyakuninisshu.feature.corecomponent.R class VerticalSingleLineTextView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { private val paint: Paint = Paint() private var text: String = "" private var textSize: Int = 0 init { initialize(context) } private fun initialize(context: Context) { val resources = context.resources text = "" textSize = context.resources.getDimensionPixelOffset(R.dimen.text_l) with(paint) { isAntiAlias = true textSize = [email protected]() color = ResourcesCompat.getColor(resources, R.color.blackba, null) typeface = ResourcesCompat.getFont(context, R.font.hannari) } } fun setTextSize(@DimenRes dimenId: Int) { textSize = context.resources.getDimensionPixelOffset(dimenId) paint.textSize = textSize.toFloat() } fun setTextSizeByPx(textSize: Int) { this.textSize = textSize paint.textSize = textSize.toFloat() } fun drawText(text: String?) { if (text != null) { this.text = text } val layoutParams = layoutParams layoutParams.width = textSize layoutParams.height = (textSize.toDouble() * this.text.length.toDouble() * 1.05).toInt() setLayoutParams(layoutParams) invalidate() } override fun onDraw(canvas: Canvas) { val textLength = text.length for (i in 0 until textLength) { canvas.drawText(text.substring(i, i + 1), 0f, (textSize * (i + 1)).toFloat(), paint) } } }
apache-2.0
890e2e8a81884c7ea103aca1f1bb34b3
31.536585
112
0.67991
4.417219
false
false
false
false
vitoling/HiWeather
src/main/kotlin/com/vito/work/weather/service/LocationService.kt
1
12297
package com.vito.work.weather.service import com.vito.work.weather.config.Constant import com.vito.work.weather.domain.beans.api.LocationData import com.vito.work.weather.domain.beans.api.LocationData.Companion.LOCATION_INFO_TYPE_ONE import com.vito.work.weather.domain.beans.api.LocationData.Companion.LOCATION_INFO_TYPE_TWO import com.vito.work.weather.domain.beans.api.LocationData.Companion.LOCATION_INFO_TYPE_ZERO import com.vito.work.weather.domain.beans.api.LocationInfo import com.vito.work.weather.domain.beans.api.locationInfoParser import com.vito.work.weather.dto.City import com.vito.work.weather.dto.District import com.vito.work.weather.dto.Province import com.vito.work.weather.repo.CityDao import com.vito.work.weather.repo.DistrictDao import com.vito.work.weather.repo.ProvinceDao import com.vito.work.weather.service.spider.AQICityPageProcessor import com.vito.work.weather.service.spider.AbstractSpiderTask import com.vito.work.weather.util.cnweather.getResultBean import com.vito.work.weather.util.http.BusinessError import com.vito.work.weather.util.http.BusinessException import com.vito.work.weather.util.http.HttpUtil import com.vito.work.weather.util.http.sendGetRequestViaHttpClient import org.jetbrains.annotations.Contract import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import us.codecraft.webmagic.ResultItems import us.codecraft.webmagic.Spider import us.codecraft.webmagic.scheduler.QueueScheduler import java.io.BufferedReader import java.io.InputStreamReader import java.nio.charset.Charset import java.util.* import javax.annotation.PreDestroy import javax.annotation.Resource /** * Created by lingzhiyuan. * Date : 16/4/5. * Time : 下午7:06. * Description: * */ @Service(value = "locationService") @Transactional class LocationService : AbstractSpiderTask() { @Resource lateinit var districtDao: DistrictDao @Resource lateinit var cityDao: CityDao @Resource lateinit var provinceDao: ProvinceDao @PreDestroy fun destroy() { spider.close() } companion object { val logger = LoggerFactory.getLogger(LocationService::class.java) !! val spider = Spider.create(AQICityPageProcessor()).thread(Constant.SPIDER_THREAD_COUNT) !! } /** * 获取所有省份 * */ fun findProvinces(): List<Province> = provinceDao.findAll(Province::class.java) /** * 获取省份 * @param provinceId 省份的 id * */ fun getProvince(provinceId: Long) = provinceDao.findById(Province::class.java, provinceId) /** * 获取所有城市 * @param provinceId 省份的 id, 为0时返回所有城市 * */ fun findCities(provinceId: Long = 0): List<City>? = if (provinceId == 0L) cityDao.findAll(City::class.java) else cityDao.findCities(provinceId) /** * 获取一个城市 * @param cityId 城市的 id * */ fun getCity(cityId: Long) = cityDao.findById(City::class.java, cityId) /** * 根据省份列表查询出城市列表 * @param provinces 需要查询的省份列表 * */ fun findCities(provinces: List<Province>) = provinces .map { it.id } .map { cityDao.findCities(it) } .reduce { acc, list -> acc + list } /** * 查询出所有的区 * @param cityId 城市的 id * */ fun findDistricts(cityId: Long = 0) = if (cityId == 0L) districtDao.findAll(District::class.java) else districtDao.findDistricts(cityId) fun updateProvince() { val provinces = updateProvincesFromWeb() provinces.forEach { provinceDao save it } } fun updateCity() { val provinces = provinceDao.findAll(Province::class.java) val cities = updateCitiesFromWebByProvinces(provinces) cities.forEach { cityDao save it } } fun updateDistrict() { val cities = cityDao.findAll(City::class.java) // 获取 tianqi.com上的所有区县 updateDistrictsFromWebByCities(cities).run { // 给有 aqi 数据的区县添加pinyin_aqi updateAQIDistricts(this).let { // 从文件中筛选出中国天气网上有的区县 updateDistrictsFromFile(this).forEach { districtDao save it } } } } fun updateDistrictViaAPI() { val districts = districtDao.findAll(District::class.java) districts.apply { districtDao batchDelete districtDao.findObsoleteDistricts(districts.map { it.id }) com.vito.work.weather.service.updateDistrictViaAPI(this) this.forEach { districtDao save it } } } /** * 执行更新任务 * */ fun execute(type: Int) { try { task { when (type) { LOCATION_INFO_TYPE_ZERO -> updateProvince() LOCATION_INFO_TYPE_ONE -> updateCity() LOCATION_INFO_TYPE_TWO -> updateDistrict() 3 -> updateDistrictViaAPI() } } } finally { spider.scheduler = QueueScheduler() } } } // end LocationService /** * 通过网站 API获取省的信息, 并保存到数据库中 * */ private val updateProvincesFromWeb: () -> List<Province> = { var provinces = listOf<Province>() val params = HashMap<String, Any>() params.put("type", LocationData.LOCATION_INFO_TYPE_ZERO) // 获取原始的JSON数据, 结构为 List val data: String = fetchAndConvertDataFromWeb(params) // 通过 mapper 转换成 LocationInfo 对象 val locationInfo = locationInfoParser(LocationData.LOCATION_INFO_TYPE_ZERO, data) // 将对象中的数据保存到数据库中 if (locationInfo != null) { provinces = getProvincesFromLocationInfo(locationInfo) } LocationService.logger.info("Provinces Updated") provinces } /** * 通过网站API, 根据省爬取所有市的信息 * */ @Contract("null->null") private fun updateCitiesFromWebByProvinces(provinces: List<Province>): List<City> { val cities = provinces .map { mapOf("type" to LocationData.LOCATION_INFO_TYPE_ONE, "pid" to it.id) } .map(::fetchAndConvertDataFromWeb) .map { locationInfoParser(LocationData.LOCATION_INFO_TYPE_ONE, it) } .filterNotNull() .map(::getCitiesFromLocationInfo) .reduce { acc, list -> acc + list } LocationService.logger.info("Cities Updated") return cities } /** * 通过网站 API, 根据市爬去所有区县信息 * */ @Contract("null->null") private fun updateDistrictsFromWebByCities(cities: List<City>): List<District> { val districts = cities .map { mapOf("type" to LocationData.LOCATION_INFO_TYPE_TWO, "pid" to it.province, "cid" to it.id) } .map(::fetchAndConvertDataFromWeb) .map { locationInfoParser(LocationData.LOCATION_INFO_TYPE_TWO, it) } .filterNotNull() .map(::getDistrictsFromLocationInfo) .reduce { acc, list -> acc + list } return districts } /** * 从获取到的区域信息中提取省信息并保存 * */ private fun getProvincesFromLocationInfo(locationInfo: LocationInfo): List<Province> { val value = locationInfo.value.toSortedMap() val pys = locationInfo.py.toSortedMap() val ishots = locationInfo.ishot.toSortedMap() val provinces = value.map { Province().apply { id = it.key title = it.value?.split(" ")?.last() !! pinyin = pys[it.key] !! ishot = ishots[it.key] !! } } return provinces } /** * 从获取到的区域信息中提取城市信息并保存 * */ private fun getCitiesFromLocationInfo(locationInfo: LocationInfo): List<City> { val value = locationInfo.value.toSortedMap() val pys = locationInfo.py.toSortedMap() val ishots = locationInfo.ishot.toSortedMap() val cities = value.map { City().apply { id = it.key title = it.value?.split(" ")?.last() !! pinyin = pys[it.key] !! ishot = ishots[it.key] !! province = id / 100 } } return cities } /** * 从获取到的区域信息中提取省信息并保存 * */ private fun getDistrictsFromLocationInfo(locationInfo: LocationInfo): List<District> { val value = locationInfo.value.toSortedMap() val pys = locationInfo.py.toSortedMap() val ishots = locationInfo.ishot.toSortedMap() val districts = value.map { it -> District().apply { id = it.key city = (it.key - 101000000 - (it.key - 101000000) % 100) / 100 title = it.value?.split(" ")?.last() !! pinyin = pys[it.key] !! ishot = ishots[it.key] !! } } return districts } /** * 获取数据并转换成正确的 json 格式 * */ private fun fetchAndConvertDataFromWeb(params: Map<String, Any>): String { var data = HttpUtil.sendGetRequestViaHttpClient(Constant.LOCATION_SOURCE_URL, params, hashMapOf(), Charset.forName("utf-8")) data = data?.substring(data.indexOf('(') + 1, data.length - 1)?.removeSuffix(")") return data ?: throw BusinessException(BusinessError.ERROR_RESOURCE_NOT_FOUND) } /** * 到网上获取区县的 aqi pinyin * * 天气网有两套拼音,一套大多数天气通用的区县拼音, 第二套市空气质量板块专有的 pinyin, 需要区分使用 * * */ private fun updateAQIDistricts(districts: List<District>): List<District> { val resultItems: ResultItems = LocationService.spider.get("http://www.tianqi.com/air/") val receivedUrls: List<String> = resultItems.get("urls") val titles: List<String> = resultItems.get("titles") val pinyins = receivedUrls.map { it.substringAfter("/air/").removeSuffix(".html") } districts.forEach { district -> titles.forEachIndexed { index, title -> if (title.contains(district.title.split(" ").last())) { district.pinyin_aqi = pinyins[index] } } } return districts } /** * 通过中国天气网的API更新信息 * */ private fun updateDistrictViaAPI(districts: List<District>) { districts.forEach { try { val resultBean = getResultBean(it) val c = resultBean?.c if (c != null) { it.longitude = c.c13 it.latitude = c.c14 it.zipcode = c.c12 it.altitude = c.c15.toDouble() } } catch(ex: Exception) { ex.printStackTrace() } } } /** * 从文件中更新区县信息 * * 文件来源为中国天气网, 所有基本信息以中国天气网为准 * */ private fun updateDistrictsFromFile(districts: List<District>): List<District> { data class TempDistrict(val id: Long, val title: String, val city: String, val province: String) val strList = mutableListOf<String>() try { val br: BufferedReader val reader: InputStreamReader = InputStreamReader(LocationService::class.java.getResourceAsStream(Constant.DISTRICT_API_FILE_LOCATION), "UTF-8") br = BufferedReader(reader) do { val line = br.readLine() if (! line.isNullOrBlank() && line.trim().isNotEmpty()) { strList.add(line) } } while (line != null) reader.close() br.close() } catch(ex: Exception) { ex.printStackTrace() throw ex } val tempDistricts = strList .filter { it.trim().isNotEmpty() } .map { it.trim().split(",") } .map { TempDistrict(it[0].toLong(), it[1], it[2], it[3]) } districts.forEach { district -> val tempDistrict = tempDistricts.firstOrNull { it.id == district.id } if (tempDistrict == null) { // id 为 -1的项目为无效项目 district.id = -1L } else { district.title = tempDistrict.title } } return districts.filter { it.id != -1L } }
gpl-3.0
9915a86d3e66afbf825e6bbaa6ddaa27
29.933155
152
0.630132
3.887433
false
false
false
false
danwallach/XStopwatch
wear/src/main/kotlin/org/dwallach/xstopwatch/TimerActivity.kt
1
10752
package org.dwallach.xstopwatch import android.app.Activity import android.app.Dialog import android.app.DialogFragment import android.app.TimePickerDialog import android.content.pm.PackageManager import android.os.Bundle import android.os.Handler import android.os.Looper import android.os.Message import android.provider.AlarmClock import android.util.Log import android.view.View import android.widget.ImageButton import android.widget.TimePicker import java.lang.ref.WeakReference import java.util.Observable import java.util.Observer import kotlinx.android.synthetic.main.activity_timer.* import org.jetbrains.anko.* class TimerActivity : Activity(), Observer { private var notificationHelper: NotificationHelper? = null private var buttonStateHandler: Handler? = null private var playButton: ImageButton? = null private var stopwatchText: StopwatchText? = null class MyHandler(looper: Looper, timerActivity: TimerActivity) : Handler(looper) { private val timerActivityRef = WeakReference(timerActivity) override fun handleMessage(inputMessage: Message) { Log.v(TAG, "button state message received") timerActivityRef.get()?.setPlayButtonIcon() } } // see http://developer.android.com/guide/topics/ui/controls/pickers.html /** * this uses the built-in TimePickerDialog to ask the user to specify the hours and minutes * for the count-down timer. Of course, it works fine on the emulator and on a Moto360, but * totally fails on the LG G Watch and G Watch R, apparently trying to show a full-blown * Material Design awesome thing that was never tuned to fit on a watch. Instead, see * the separate TimePickerFragment class, which might be ugly, but at least it works consistently. * TODO: move back to this code and kill TimePickerFragment once they fix the bug in Wear */ class FailedTimePickerFragment : DialogFragment(), TimePickerDialog.OnTimeSetListener { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { // Use the current time as the default values for the picker val duration = TimerState.duration // in milliseconds val minute = (duration / 60000 % 60).toInt() val hour = (duration / 3600000).toInt() // Create a new instance of TimePickerDialog and return it return TimePickerDialog(activity, R.style.Theme_Wearable_Modal, this, hour, minute, true) } override fun onTimeSet(view: TimePicker, hour: Int, minute: Int) { // Do something with the time chosen by the user Log.v(TAG, "User selected time: %d:%02d".format(hour, minute)) TimerState.setDuration(null, hour * 3600000L + minute * 60000L) PreferencesHelper.savePreferences(context) PreferencesHelper.broadcastPreferences(context, Constants.timerUpdateIntent) } } // call to this specified in the layout xml files fun showTimePickerDialog(v: View) = TimePickerFragment().show(fragmentManager, "timePicker") // FailedTimePickerFragment().show(fragmentManager, "timePicker") // call to this specified in the layout xml files fun launchStopwatch(view: View) = startActivity<StopwatchActivity>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.v(TAG, "onCreate") try { val pinfo = packageManager.getPackageInfo(packageName, 0) val versionNumber = pinfo.versionCode val versionName = pinfo.versionName Log.i(TAG, "Version: $versionName ($versionNumber)") } catch (e: PackageManager.NameNotFoundException) { Log.e(TAG, "couldn't read version", e) } intent.log(TAG) // dumps info from the intent into the log // there's a chance we were launched through a specific intent to set a timer for // a particular length; this is how we figure it out val paramLength = intent.getIntExtra(AlarmClock.EXTRA_LENGTH, 0) // this used to be set to true, but not in recent Android Wear versions. We used // to default to "false", meaning we'd put up the activity and wouldn't start it. // We now default to "true", meaning we'll still put up the activity, but we'll // also start the timer. val skipUI = intent.getBooleanExtra(AlarmClock.EXTRA_SKIP_UI, true) // Google's docs say: This action requests a timer to be started for a specific length of time. // If no length is specified, the implementation should start an activity that is capable of // setting a timer (EXTRA_SKIP_UI is ignored in this case). If a length is specified, and // EXTRA_SKIP_UI is true, the implementation should remove this timer after it has been dismissed. // If an identical, unused timer exists matching both parameters, an implementation may re-use // it instead of creating a new one (in this case, the timer should not be removed after dismissal). // This action always starts the timer. // (http://developer.android.com/reference/android/provider/AlarmClock.html) // Here's what we're going to do. In this app, we want to support only one timer, rather than // the multiple timers suggested by the documentation above. Our solution, at least for now: // if an intent comes in while a timer is running, the old one is nuked and the new one is it. // We're going to assume that SKIP_UI is true and treat that a hint to start the timer. If it's // explicitly false, which doesn't seem likely, then we'll assume that Android is telling us // to have more user interaction, and therefore we won't auto-start the timer. if (paramLength > 0 && paramLength <= 86400) { Log.v(TAG, "onCreate, somebody told us a time value: $paramLength") val durationMillis = (paramLength * 1000).toLong() TimerState.setDuration(this@TimerActivity, durationMillis) TimerState.reset(this@TimerActivity) if (skipUI) TimerState.click(this@TimerActivity) PreferencesHelper.savePreferences(this@TimerActivity) PreferencesHelper.broadcastPreferences(this@TimerActivity, Constants.timerUpdateIntent) } else { // bring in saved preferences PreferencesHelper.loadPreferences(this@TimerActivity) } setContentView(R.layout.activity_timer) // This buttonState business is all about dealing with alarms, which go to // NotificationService, on a different thread, which needs to ping us to // update the UI, if we exist. This handler will always run on the UI thread. // It's invoked from the update() method down below, which may run on other threads. buttonStateHandler = MyHandler(Looper.getMainLooper(), this) watch_view_stub.setOnLayoutInflatedListener { Log.v(TAG, "onLayoutInflated") val resetButton = it.find<ImageButton>(R.id.resetButton) playButton = it.find<ImageButton>(R.id.playButton) stopwatchText = it.find<StopwatchText>(R.id.elapsedTime) stopwatchText?.setSharedState(TimerState) // now that we've loaded the state, we know whether we're playing or paused setPlayButtonIcon() // get the notification service running as well; it will stick around to make sure // the broadcast receiver is alive NotificationService.kickStart(this@TimerActivity) // set up notification helper, and use this as a proxy for whether // or not we need to set up everybody who pays attention to the timerState if (notificationHelper == null) { notificationHelper = NotificationHelper(this@TimerActivity, R.drawable.sandwatch_trans, resources.getString(R.string.timer_app_name), TimerState) setStopwatchObservers(true) } resetButton.setOnClickListener { TimerState.reset(this@TimerActivity) PreferencesHelper.savePreferences(this@TimerActivity) PreferencesHelper.broadcastPreferences(this@TimerActivity, Constants.timerUpdateIntent) } playButton?.setOnClickListener { TimerState.click(this@TimerActivity) PreferencesHelper.savePreferences(this@TimerActivity) PreferencesHelper.broadcastPreferences(this@TimerActivity, Constants.timerUpdateIntent) } } } /** * install the observers that care about the timerState: "this", which updates the * visible UI parts of the activity, and the notificationHelper, which deals with the popup * notifications elsewhere * @param includeActivity If the current activity isn't visible, then make this false and it won't be notified */ private fun setStopwatchObservers(includeActivity: Boolean) { TimerState.deleteObservers() if (notificationHelper != null) TimerState.addObserver(notificationHelper) if (includeActivity) { TimerState.addObserver(this) if (stopwatchText != null) TimerState.addObserver(stopwatchText) } } override fun onStart() { super.onStart() Log.v(TAG, "onStart") TimerState.isVisible = true setStopwatchObservers(true) } override fun onResume() { super.onResume() Log.v(TAG, "onResume") TimerState.isVisible = true setStopwatchObservers(true) } override fun onPause() { super.onPause() Log.v(TAG, "onPause") TimerState.isVisible = false setStopwatchObservers(false) } override fun update(observable: Observable?, data: Any?) { Log.v(TAG, "activity update") // We might be called on the UI thread or on a service thread; we need to dispatch this // entirely on the UI thread, since we're ultimately going to be monkeying with the UI. // Thus this nonsense. buttonStateHandler?.sendEmptyMessage(0) } private fun setPlayButtonIcon() { Log.v(TAG, "setPlayButtonIcon") playButton?.setImageResource( if(TimerState.isRunning) android.R.drawable.ic_media_pause else android.R.drawable.ic_media_play) } companion object { private const val TAG = "TimerActivity" } }
gpl-3.0
2785a845b5c2297a52e8424adb200e0e
41.164706
114
0.66676
4.989327
false
false
false
false
msebire/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/ProjectFrameBounds.kt
2
3697
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.wm.impl import com.intellij.openapi.components.* import com.intellij.openapi.project.Project import com.intellij.openapi.util.ModificationTracker import com.intellij.openapi.wm.WindowManager import com.intellij.openapi.wm.impl.WindowManagerImpl.FrameBoundsConverter.convertToDeviceSpace import com.intellij.util.xmlb.annotations.Attribute import com.intellij.util.xmlb.annotations.Property import org.jdom.Element import java.awt.Frame import java.awt.Rectangle @State(name = "ProjectFrameBounds", storages = [(Storage(StoragePathMacros.WORKSPACE_FILE))]) class ProjectFrameBounds(private val project: Project) : PersistentStateComponent<FrameInfo>, ModificationTracker { companion object { @JvmStatic fun getInstance(project: Project) = project.service<ProjectFrameBounds>() } // in device space var rawFrameInfo: FrameInfo? = null private set val isInFullScreen: Boolean get() = rawFrameInfo?.fullScreen ?: false override fun getState() = rawFrameInfo override fun loadState(state: FrameInfo) { rawFrameInfo = state state.resetModificationCount() } override fun getModificationCount(): Long { val frameInfoInDeviceSpace = (WindowManager.getInstance() as? WindowManagerImpl)?.getFrameInfoInDeviceSpace(project) if (frameInfoInDeviceSpace != null) { if (rawFrameInfo == null) { rawFrameInfo = frameInfoInDeviceSpace } else { rawFrameInfo!!.copyFrom(frameInfoInDeviceSpace) } } return rawFrameInfo?.modificationCount ?: 0 } } class FrameInfo : BaseState() { // flat is used due to backward compatibility @get:Property(flat = true) var bounds by property<Rectangle?>(null) { it == null || (it.width == 0 && it.height == 0 && it.x == 0 && it.y == 0) } @get:Attribute var extendedState by property(Frame.NORMAL) @get:Attribute var fullScreen by property(false) } fun WindowManagerImpl.getFrameInfoInDeviceSpace(project: Project): FrameInfo? { val frame = getFrame(project) ?: return null // updateFrameBounds will also update myDefaultFrameInfo, // so, we have to call this method before other code in this method and if later extendedState is used only for macOS val extendedState = updateFrameBounds(frame) val frameInfo = FrameInfo() // save bounds even if maximized because on unmaximize we must restore previous frame bounds frameInfo.bounds = convertToDeviceSpace(frame.graphicsConfiguration, myDefaultFrameInfo.bounds!!) frameInfo.extendedState = extendedState if (isFullScreenSupportedInCurrentOS) { frameInfo.fullScreen = frame.isInFullScreen } return frameInfo } private const val X_ATTR = "x" private const val Y_ATTR = "y" private const val WIDTH_ATTR = "width" private const val HEIGHT_ATTR = "height" fun serializeBounds(bounds: Rectangle, element: Element) { element.setAttribute(X_ATTR, Integer.toString(bounds.x)) element.setAttribute(Y_ATTR, Integer.toString(bounds.y)) element.setAttribute(WIDTH_ATTR, Integer.toString(bounds.width)) element.setAttribute(HEIGHT_ATTR, Integer.toString(bounds.height)) } fun deserializeBounds(element: Element): Rectangle? { try { val x = element.getAttributeValue(X_ATTR)?.toInt() ?: return null val y = element.getAttributeValue(Y_ATTR)?.toInt() ?: return null val w = element.getAttributeValue(WIDTH_ATTR)?.toInt() ?: return null val h = element.getAttributeValue(HEIGHT_ATTR)?.toInt() ?: return null return Rectangle(x, y, w, h) } catch (ignored: NumberFormatException) { return null } }
apache-2.0
4841f1c163436fd6127029a94744a39c
36.734694
147
0.750068
4.354535
false
false
false
false
alashow/music-android
modules/common-ui-components/src/main/java/tm/alashow/ui/components/Error.kt
1
3222
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.ui.components import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.LottieConstants import com.airbnb.lottie.compose.rememberLottieComposition import tm.alashow.ui.Zoomable import tm.alashow.ui.colorFilterDynamicProperty import tm.alashow.ui.theme.AppTheme @Composable fun EmptyErrorBox( modifier: Modifier = Modifier, message: String = stringResource(R.string.error_empty), retryVisible: Boolean = true, onRetryClick: () -> Unit = {}, ) { ErrorBox( title = stringResource(R.string.error_empty_title), message = message, retryVisible = retryVisible, onRetryClick = onRetryClick, modifier = modifier ) } @Preview @Composable fun ErrorBox( modifier: Modifier = Modifier, title: String = stringResource(R.string.error_title), message: String = stringResource(R.string.error_unknown), retryVisible: Boolean = true, onRetryClick: () -> Unit = {} ) { val loadingYOffset = 130.dp Box( contentAlignment = Alignment.Center, modifier = modifier .fillMaxWidth() .offset(y = loadingYOffset / 3f) ) { val wavesComposition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.waves)) Zoomable { LottieAnimation( wavesComposition, speed = 0.5f, iterations = LottieConstants.IterateForever, dynamicProperties = colorFilterDynamicProperty(MaterialTheme.colors.secondary.copy(alpha = 0.1f)), modifier = Modifier.offset(y = -loadingYOffset) ) } Column( verticalArrangement = Arrangement.spacedBy(AppTheme.specs.paddingTiny), horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .align(Alignment.Center) .padding(top = AppTheme.specs.paddingLarge) ) { Text(title, style = MaterialTheme.typography.h6.copy(fontWeight = FontWeight.Bold)) Text(message) if (retryVisible) TextRoundedButton( onClick = onRetryClick, text = stringResource(R.string.error_retry), modifier = Modifier.padding(top = AppTheme.specs.padding) ) } } }
apache-2.0
75ae5c397dc843726f6bf178e736593a
34.021739
114
0.689013
4.609442
false
false
false
false
vhromada/Catalog-Swing
src/main/kotlin/cz/vhromada/catalog/gui/movie/MovieInfoDialog.kt
1
17662
package cz.vhromada.catalog.gui.movie import cz.vhromada.catalog.entity.Genre import cz.vhromada.catalog.entity.Medium import cz.vhromada.catalog.entity.Movie import cz.vhromada.catalog.facade.GenreFacade import cz.vhromada.catalog.facade.PictureFacade import cz.vhromada.catalog.gui.common.AbstractInfoDialog import cz.vhromada.catalog.gui.common.CatalogSwingConstants import cz.vhromada.catalog.gui.common.DialogResult import cz.vhromada.catalog.gui.common.Picture import cz.vhromada.common.entity.Time import cz.vhromada.common.utils.Constants import java.awt.EventQueue import javax.swing.ButtonGroup import javax.swing.GroupLayout import javax.swing.JButton import javax.swing.JCheckBox import javax.swing.JLabel import javax.swing.JRadioButton import javax.swing.JSpinner import javax.swing.JTextField import javax.swing.SpinnerNumberModel /** * A class represents dialog for movie. * * @author Vladimir Hromada */ class MovieInfoDialog : AbstractInfoDialog<Movie> { /** * Facade for genres */ private val genreFacade: GenreFacade /** * Facade for pictures */ private val pictureFacade: PictureFacade /** * List of genres */ private val genres: MutableList<Genre> /** * List of pictures */ private val pictures: MutableList<Int> /** * List of media */ private var media: MutableList<Medium> /** * Label for czech name */ private val czechNameLabel = JLabel("Czech name") /** * Text field for czech name */ private val czechNameData = JTextField() /** * Label for original name */ private val originalNameLabel = JLabel("Original name") /** * Text field for original name */ private val originalNameData = JTextField() /** * Label for year */ private val yearLabel = JLabel("Year") /** * Spinner for year */ private val yearData = JSpinner(SpinnerNumberModel(Constants.CURRENT_YEAR, Constants.MIN_YEAR, Constants.CURRENT_YEAR, 1)) /** * Label for language */ private val languageLabel = JLabel("Language") /** * Button group for languages */ private val languagesButtonGroup = ButtonGroup() /** * Radio button for czech language */ private val czechLanguageData = JRadioButton("Czech", true) /** * Radio button for english language */ private val englishLanguageData = JRadioButton("English") /** * Radio button for french language */ private val frenchLanguageData = JRadioButton("French") /** * Radio button for japanese language */ private val japaneseLanguageData = JRadioButton("Japanese") /** * Radio button for slovak language */ private val slovakLanguageData = JRadioButton("Slovak") /** * Label for subtitles */ private val subtitlesLabel = JLabel("Subtitles") /** * Check box for czech subtitles */ private val czechSubtitlesData = JCheckBox("Czech") /** * Check box for english subtitles */ private val englishSubtitlesData = JCheckBox("English") /** * Label for media */ private val mediaLabel = JLabel("Media") /** * Data with media */ private val mediaData = JLabel() /** * Button for changing media */ private val mediaButton = JButton("Change media", Picture.CHOOSE.icon) /** * Label for ČSFD */ private val csfdLabel = JLabel("ČSFD") /** * Text field for ČSFD */ private val csfdData = JTextField() /** * Check box for IMDB code */ private val imdbCodeLabel = JCheckBox("IMDB code") /** * Spinner for IMDB code */ private val imdbCodeData = JSpinner(SpinnerNumberModel(1, 1, Constants.MAX_IMDB_CODE, 1)) /** * Label for czech Wikipedia */ private val wikiCzLabel = JLabel("Czech Wikipedia") /** * Text field for czech Wikipedia */ private val wikiCzData = JTextField() /** * Label for english Wikipedia */ private val wikiEnLabel = JLabel("English Wikipedia") /** * Text field for english Wikipedia */ private val wikiEnData = JTextField() /** * Label for picture */ private val pictureLabel = JLabel("Picture") /** * Data with picture */ private val pictureData = JLabel() /** * Button for changing picture */ private val pictureButton = JButton("Change picture", Picture.CHOOSE.icon) /** * Label for note */ private val noteLabel = JLabel("Note") /** * Text field for note */ private val noteData = JTextField() /** * Label for genres */ private val genreLabel = JLabel("Genres") /** * Data with genres */ private val genreData = JLabel() /** * Button for changing genres */ private val genresButton = JButton("Change genres", Picture.CHOOSE.icon) /** * Creates a new instance of MovieInfoDialog. * * @param genreFacade facade for genres * @param pictureFacade facade for pictures */ constructor(genreFacade: GenreFacade, pictureFacade: PictureFacade) { init() this.genreFacade = genreFacade this.pictureFacade = pictureFacade this.genres = mutableListOf() this.pictures = mutableListOf() this.media = mutableListOf() imdbCodeData.isEnabled = false } /** * Creates a new instance of MovieInfoDialog. * * @param genreFacade facade for genres * @param pictureFacade facade for pictures * @param movie movie */ constructor(genreFacade: GenreFacade, pictureFacade: PictureFacade, movie: Movie) : super(movie) { init() this.genreFacade = genreFacade this.pictureFacade = pictureFacade this.genres = movie.genres!!.filterNotNull().toMutableList() this.pictures = mutableListOf() if (movie.picture != null) { this.pictures.add(movie.picture!!) } this.media = movie.media!!.filterNotNull().toMutableList() this.czechNameData.text = movie.czechName this.originalNameData.text = movie.originalName this.yearData.value = movie.year initLanguage(movie.language!!, this.czechLanguageData, this.englishLanguageData, this.frenchLanguageData, this.japaneseLanguageData, this.slovakLanguageData) initSubtitles(movie.subtitles!!, this.czechSubtitlesData, this.englishSubtitlesData) this.mediaData.text = getMedia() this.csfdData.text = movie.csfd if (movie.imdbCode!! > 0) { this.imdbCodeLabel.isSelected = true this.imdbCodeData.value = movie.imdbCode } else { this.imdbCodeLabel.isSelected = false this.imdbCodeData.isEnabled = false } this.wikiCzData.text = movie.wikiCz this.wikiEnData.text = movie.wikiEn this.pictureData.text = getPicture(this.pictures) this.noteData.text = movie.note this.genreData.text = getGenres(this.genres) } @Suppress("DuplicatedCode") override fun initComponents() { initLabelComponent(czechNameLabel, czechNameData) initLabelComponent(originalNameLabel, originalNameData) initLabelComponent(yearLabel, yearData) initLabelComponent(csfdLabel, csfdData) initLabelComponent(wikiCzLabel, wikiCzData) initLabelComponent(wikiEnLabel, wikiEnData) initLabelComponent(pictureLabel, pictureData) initLabelComponent(noteLabel, noteData) addInputValidator(czechNameData) addInputValidator(originalNameData) languagesButtonGroup.add(czechLanguageData) languagesButtonGroup.add(englishLanguageData) languagesButtonGroup.add(frenchLanguageData) languagesButtonGroup.add(japaneseLanguageData) languagesButtonGroup.add(slovakLanguageData) languageLabel.isFocusable = false subtitlesLabel.isFocusable = false mediaData.isFocusable = false pictureData.isFocusable = false genreData.isFocusable = false imdbCodeLabel.addChangeListener { imdbCodeData.isEnabled = imdbCodeLabel.isSelected } mediaButton.addActionListener { mediaAction() } pictureButton.addActionListener { pictureAction(pictureFacade, pictures, pictureData) } genresButton.addActionListener { genresAction(genreFacade, genres, genreData) } } override fun processData(objectData: Movie?): Movie { if (objectData == null) { return Movie(id = null, czechName = czechNameData.text, originalName = originalNameData.text, year = yearData.value as Int, language = getSelectedLanguage(languagesButtonGroup.selection, czechLanguageData, englishLanguageData, frenchLanguageData, japaneseLanguageData), subtitles = getSelectedSubtitles(czechSubtitlesData, englishSubtitlesData), media = media, csfd = csfdData.text, imdbCode = if (imdbCodeLabel.isSelected) imdbCodeData.value as Int else -1, wikiEn = wikiEnData.text, wikiCz = wikiCzData.text, picture = if (pictures.isEmpty()) null else pictures[0], note = noteData.text, position = null, genres = genres) } return objectData.copy(czechName = czechNameData.text, originalName = originalNameData.text, year = yearData.value as Int, language = getSelectedLanguage(languagesButtonGroup.selection, czechLanguageData, englishLanguageData, frenchLanguageData, japaneseLanguageData), subtitles = getSelectedSubtitles(czechSubtitlesData, englishSubtitlesData), media = media, csfd = csfdData.text, imdbCode = if (imdbCodeLabel.isSelected) imdbCodeData.value as Int else -1, wikiEn = wikiEnData.text, wikiCz = wikiCzData.text, picture = if (pictures.isEmpty()) null else pictures[0], note = noteData.text, genres = genres) } /** * Returns true if input is valid: czech name isn't empty string, original name isn't empty string, media isn't empty collection, genres isn't empty collection * * @return true if input is valid: czech name isn't empty string, original name isn't empty string, media isn't empty collection, genres isn't empty collection */ override fun isInputValid(): Boolean { return czechNameData.text.isNotBlank() && originalNameData.text.isNotBlank() && media.isNotEmpty() && genres.isNotEmpty() } @Suppress("DuplicatedCode") override fun getHorizontalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group { return group .addGroup(createHorizontalComponents(layout, czechNameLabel, czechNameData)) .addGroup(createHorizontalComponents(layout, originalNameLabel, originalNameData)) .addGroup(createHorizontalComponents(layout, yearLabel, yearData)) .addGroup(createHorizontalComponents(layout, languageLabel, czechLanguageData)) .addGroup(createHorizontalSelectableComponent(layout, englishLanguageData)) .addGroup(createHorizontalSelectableComponent(layout, frenchLanguageData)) .addGroup(createHorizontalSelectableComponent(layout, japaneseLanguageData)) .addGroup(createHorizontalSelectableComponent(layout, slovakLanguageData)) .addGroup(createHorizontalComponents(layout, subtitlesLabel, czechSubtitlesData)) .addGroup(createHorizontalSelectableComponent(layout, englishSubtitlesData)) .addGroup(createHorizontalComponents(layout, mediaLabel, mediaData)) .addComponent(mediaButton, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE) .addGroup(createHorizontalComponents(layout, csfdLabel, csfdData)) .addGroup(createHorizontalComponents(layout, imdbCodeLabel, imdbCodeData)) .addGroup(createHorizontalComponents(layout, wikiCzLabel, wikiCzData)) .addGroup(createHorizontalComponents(layout, wikiEnLabel, wikiEnData)) .addGroup(createHorizontalComponents(layout, pictureLabel, pictureData)) .addComponent(pictureButton, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE) .addGroup(createHorizontalComponents(layout, noteLabel, noteData)) .addGroup(createHorizontalComponents(layout, genreLabel, genreData)) .addComponent(genresButton, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE) } @Suppress("DuplicatedCode") override fun getVerticalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group { return group .addGroup(createVerticalComponents(layout, czechNameLabel, czechNameData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, originalNameLabel, originalNameData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, yearLabel, yearData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, languageLabel, czechLanguageData)) .addGap(VERTICAL_GAP_SIZE) .addComponent(englishLanguageData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE) .addGap(VERTICAL_GAP_SIZE) .addComponent(frenchLanguageData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE) .addGap(VERTICAL_GAP_SIZE) .addComponent(japaneseLanguageData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE) .addGap(VERTICAL_GAP_SIZE) .addComponent(slovakLanguageData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, subtitlesLabel, czechSubtitlesData)) .addGap(VERTICAL_GAP_SIZE) .addComponent(englishSubtitlesData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, mediaLabel, mediaData)) .addGap(VERTICAL_GAP_SIZE) .addComponent(mediaButton, CatalogSwingConstants.VERTICAL_BUTTON_SIZE, CatalogSwingConstants.VERTICAL_BUTTON_SIZE, CatalogSwingConstants.VERTICAL_BUTTON_SIZE) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, csfdLabel, csfdData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, imdbCodeLabel, imdbCodeData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, wikiCzLabel, wikiCzData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, wikiEnLabel, wikiEnData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, pictureLabel, pictureData)) .addGap(VERTICAL_GAP_SIZE) .addComponent(pictureButton, CatalogSwingConstants.VERTICAL_BUTTON_SIZE, CatalogSwingConstants.VERTICAL_BUTTON_SIZE, CatalogSwingConstants.VERTICAL_BUTTON_SIZE) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, noteLabel, noteData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, genreLabel, genreData)) .addGap(VERTICAL_GAP_SIZE) .addComponent(genresButton, CatalogSwingConstants.VERTICAL_BUTTON_SIZE, CatalogSwingConstants.VERTICAL_BUTTON_SIZE, CatalogSwingConstants.VERTICAL_BUTTON_SIZE) } /** * Returns media. * * @return media */ private fun getMedia(): String { if (media.isNullOrEmpty()) { return "" } val mediaString = StringBuilder() for (medium in media) { mediaString.append(Time(medium.length!!)) mediaString.append(", ") } return mediaString.substring(0, mediaString.length - 2) } /** * Performs action for button Change media. */ private fun mediaAction() { EventQueue.invokeLater { val dialog = MediumChooseDialog(media) dialog.isVisible = true if (dialog.returnStatus === DialogResult.OK) { mediaData.text = getMedia() setOkButtonEnabled(isInputValid()) } } } }
mit
c436564890a0e6558054b0aea509525f
36.813704
192
0.659324
5.322182
false
false
false
false
afollestad/material-dialogs
files/src/main/java/com/afollestad/materialdialogs/files/FileChooserAdapter.kt
2
8694
/** * Designed and developed by Aidan Follestad (@afollestad) * * 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.afollestad.materialdialogs.files import android.view.LayoutInflater import android.view.View import android.view.View.OnClickListener import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.annotation.StringRes import androidx.recyclerview.widget.RecyclerView import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.WhichButton.POSITIVE import com.afollestad.materialdialogs.actions.hasActionButtons import com.afollestad.materialdialogs.actions.setActionButtonEnabled import com.afollestad.materialdialogs.callbacks.onDismiss import com.afollestad.materialdialogs.files.util.betterParent import com.afollestad.materialdialogs.files.util.friendlyName import com.afollestad.materialdialogs.files.util.hasParent import com.afollestad.materialdialogs.files.util.jumpOverEmulated import com.afollestad.materialdialogs.files.util.setVisible import com.afollestad.materialdialogs.list.getItemSelector import com.afollestad.materialdialogs.utils.MDUtil.isColorDark import com.afollestad.materialdialogs.utils.MDUtil.maybeSetTextColor import com.afollestad.materialdialogs.utils.MDUtil.resolveColor import java.io.File import java.util.Locale import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext internal class FileChooserViewHolder( itemView: View, private val adapter: FileChooserAdapter ) : RecyclerView.ViewHolder(itemView), OnClickListener { init { itemView.setOnClickListener(this) } val iconView: ImageView = itemView.findViewById(R.id.icon) val nameView: TextView = itemView.findViewById(R.id.name) override fun onClick(view: View) = adapter.itemClicked(adapterPosition) } /** @author Aidan Follestad (afollestad */ internal class FileChooserAdapter( private val dialog: MaterialDialog, initialFolder: File, private val waitForPositiveButton: Boolean, private val emptyView: TextView, private val onlyFolders: Boolean, private val filter: FileFilter, private val allowFolderCreation: Boolean, @StringRes private val folderCreationLabel: Int?, private val callback: FileCallback ) : RecyclerView.Adapter<FileChooserViewHolder>() { var selectedFile: File? = null private var currentFolder = initialFolder private var listingJob: Job? = null private var contents: List<File>? = null private val isLightTheme = resolveColor(dialog.windowContext, attr = android.R.attr.textColorPrimary).isColorDark() init { dialog.onDismiss { listingJob?.cancel() } switchDirectory(initialFolder) } fun itemClicked(index: Int) { val parent = currentFolder.betterParent(dialog.context, allowFolderCreation, filter) if (parent != null && index == goUpIndex()) { // go up switchDirectory(parent) return } else if (currentFolder.canWrite() && allowFolderCreation && index == newFolderIndex()) { // New folder dialog.showNewFolderCreator( parent = currentFolder, folderCreationLabel = folderCreationLabel ) { // Refresh view switchDirectory(currentFolder) } return } val actualIndex = actualIndex(index) val selected = contents!![actualIndex].jumpOverEmulated(dialog.context) if (selected.isDirectory) { switchDirectory(selected) } else { val previousSelectedIndex = getSelectedIndex() this.selectedFile = selected val actualWaitForPositive = waitForPositiveButton && dialog.hasActionButtons() if (actualWaitForPositive) { dialog.setActionButtonEnabled(POSITIVE, true) notifyItemChanged(index) notifyItemChanged(previousSelectedIndex) } else { callback?.invoke(dialog, selected) dialog.dismiss() } } } private fun switchDirectory(directory: File) { listingJob?.cancel() listingJob = GlobalScope.launch(Main) { if (onlyFolders) { selectedFile = directory dialog.setActionButtonEnabled(POSITIVE, true) } currentFolder = directory dialog.title(text = directory.friendlyName(dialog.context)) val result = withContext(IO) { val rawContents = directory.listFiles() ?: emptyArray() if (onlyFolders) { rawContents .filter { it.isDirectory && filter?.invoke(it) ?: true } .sortedBy { it.name.toLowerCase(Locale.getDefault()) } } else { rawContents .filter { filter?.invoke(it) ?: true } .sortedWith(compareBy({ !it.isDirectory }, { it.nameWithoutExtension.toLowerCase(Locale.getDefault()) })) } } contents = result.apply { emptyView.setVisible(isEmpty()) } notifyDataSetChanged() } } override fun getItemCount(): Int { var count = contents?.size ?: 0 if (currentFolder.hasParent(dialog.context, allowFolderCreation, filter)) { count += 1 } if (allowFolderCreation && currentFolder.canWrite()) { count += 1 } return count } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): FileChooserViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.md_file_chooser_item, parent, false) view.background = dialog.getItemSelector() val viewHolder = FileChooserViewHolder(view, this) viewHolder.nameView.maybeSetTextColor(dialog.windowContext, R.attr.md_color_content) return viewHolder } override fun onBindViewHolder( holder: FileChooserViewHolder, position: Int ) { val currentParent = currentFolder.betterParent(dialog.context, allowFolderCreation, filter) if (currentParent != null && position == goUpIndex()) { // Go up holder.iconView.setImageResource( if (isLightTheme) R.drawable.icon_return_dark else R.drawable.icon_return_light ) holder.nameView.text = currentParent.name holder.itemView.isActivated = false return } if (allowFolderCreation && currentFolder.canWrite() && position == newFolderIndex()) { // New folder holder.iconView.setImageResource( if (isLightTheme) R.drawable.icon_new_folder_dark else R.drawable.icon_new_folder_light ) holder.nameView.text = dialog.windowContext.getString( folderCreationLabel ?: R.string.files_new_folder ) holder.itemView.isActivated = false return } val actualIndex = actualIndex(position) val item = contents!![actualIndex] holder.iconView.setImageResource(item.iconRes()) holder.nameView.text = item.name holder.itemView.isActivated = selectedFile?.absolutePath == item.absolutePath ?: false } private fun goUpIndex() = if (currentFolder.hasParent(dialog.context, allowFolderCreation, filter)) 0 else -1 private fun newFolderIndex() = if (currentFolder.hasParent(dialog.context, allowFolderCreation, filter)) 1 else 0 private fun actualIndex(position: Int): Int { var actualIndex = position if (currentFolder.hasParent(dialog.context, allowFolderCreation, filter)) { actualIndex -= 1 } if (currentFolder.canWrite() && allowFolderCreation) { actualIndex -= 1 } return actualIndex } private fun File.iconRes(): Int { return if (isLightTheme) { if (this.isDirectory) R.drawable.icon_folder_dark else R.drawable.icon_file_dark } else { if (this.isDirectory) R.drawable.icon_folder_light else R.drawable.icon_file_light } } private fun getSelectedIndex(): Int { if (selectedFile == null) return -1 else if (contents?.isEmpty() == true) return -1 val index = contents?.indexOfFirst { it.absolutePath == selectedFile?.absolutePath } ?: -1 return if (index > -1 && currentFolder.hasParent(dialog.context, allowFolderCreation, filter)) index + 1 else index } }
apache-2.0
a5098645a54eea64728e947d732ca210
33.228346
119
0.716356
4.699459
false
false
false
false
rock3r/detekt
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/ReturnCountSpec.kt
1
11651
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.test.TestConfig import io.gitlab.arturbosch.detekt.test.compileAndLint import io.gitlab.arturbosch.detekt.test.lint import org.assertj.core.api.Assertions.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class ReturnCountSpec : Spek({ describe("ReturnCount rule") { context("a file with an if condition guard clause and 2 returns") { val code = """ fun test(x: Int): Int { if (x < 4) return 0 when (x) { 5 -> return 5 4 -> return 4 } } """ it("should not get flagged for if condition guard clauses") { val findings = ReturnCount(TestConfig(mapOf(ReturnCount.EXCLUDE_GUARD_CLAUSES to "true"))) .lint(code) assertThat(findings).isEmpty() } } context("a file with an ELVIS operator guard clause and 2 returns") { val code = """ fun test(x: Int): Int { val y = x ?: return 0 when (x) { 5 -> return 5 4 -> return 4 } } """ it("should not get flagged for ELVIS operator guard clauses") { val findings = ReturnCount(TestConfig(mapOf(ReturnCount.EXCLUDE_GUARD_CLAUSES to "true"))) .lint(code) assertThat(findings).isEmpty() } } context("a file with 2 returns and an if condition guard clause which is not the first statement") { val code = """ fun test(x: Int): Int { when (x) { 5 -> return 5 4 -> return 4 } if (x < 4) return 0 } """ it("should get flagged for an if condition guard clause which is not the first statement") { val findings = ReturnCount(TestConfig(mapOf(ReturnCount.EXCLUDE_GUARD_CLAUSES to "true"))) .lint(code) assertThat(findings).hasSize(1) } } context("a file with 2 returns and an ELVIS guard clause which is not the first statement") { val code = """ fun test(x: Int): Int { when (x) { 5 -> return 5 4 -> return 4 } val y = x ?: return 0 } """ it("should get flagged for an ELVIS guard clause which is not the first statement") { val findings = ReturnCount(TestConfig(mapOf(ReturnCount.EXCLUDE_GUARD_CLAUSES to "true"))) .lint(code) assertThat(findings).hasSize(1) } } context("a file with multiple guard clauses") { val code = """ fun multipleGuards(a: Int?, b: Any?, c: Int?) { if(a == null) return val models = b as? Int ?: return val position = c?.takeIf { it != -1 } ?: return if(b !is String) return return } """.trimIndent() it("should not count all four guard clauses") { val findings = ReturnCount(TestConfig( ReturnCount.EXCLUDE_GUARD_CLAUSES to "true" )).compileAndLint(code) assertThat(findings).isEmpty() } it("should count all four guard clauses") { val findings = ReturnCount(TestConfig( ReturnCount.EXCLUDE_GUARD_CLAUSES to "false" )).compileAndLint(code) assertThat(findings).hasSize(1) } } context("a file with 3 returns") { val code = """ fun test(x: Int): Int { when (x) { 5 -> return 5 4 -> return 4 3 -> return 3 } } """ it("should get flagged by default") { val findings = ReturnCount().lint(code) assertThat(findings).hasSize(1) } it("should not get flagged when max value is 3") { val findings = ReturnCount(TestConfig(mapOf(ReturnCount.MAX to "3"))).lint(code) assertThat(findings).isEmpty() } it("should get flagged when max value is 1") { val findings = ReturnCount(TestConfig(mapOf(ReturnCount.MAX to "1"))).lint(code) assertThat(findings).hasSize(1) } } context("a file with 2 returns") { val code = """ fun test(x: Int): Int { when (x) { 5 -> return 5 4 -> return 4 } } """ it("should not get flagged by default") { val findings = ReturnCount().lint(code) assertThat(findings).isEmpty() } it("should not get flagged when max value is 2") { val findings = ReturnCount(TestConfig(mapOf(ReturnCount.MAX to "2"))).lint(code) assertThat(findings).isEmpty() } it("should get flagged when max value is 1") { val findings = ReturnCount(TestConfig(mapOf(ReturnCount.MAX to "1"))).lint(code) assertThat(findings).hasSize(1) } } context("a function is ignored") { val code = """ fun test(x: Int): Int { when (x) { 5 -> return 5 4 -> return 4 3 -> return 3 } } """ it("should not get flagged") { val findings = ReturnCount(TestConfig(mapOf( ReturnCount.MAX to "2", ReturnCount.EXCLUDED_FUNCTIONS to "test") )).lint(code) assertThat(findings).isEmpty() } } context("a subset of functions are ignored") { val code = """ fun test1(x: Int): Int { when (x) { 5 -> return 5 4 -> return 4 3 -> return 3 } } fun test2(x: Int): Int { when (x) { 5 -> return 5 4 -> return 4 3 -> return 3 } } fun test3(x: Int): Int { when (x) { 5 -> return 5 4 -> return 4 3 -> return 3 } } """ it("should flag none of the ignored functions") { val findings = ReturnCount(TestConfig(mapOf( ReturnCount.MAX to "2", ReturnCount.EXCLUDED_FUNCTIONS to "test1,test2") )).lint(code) assertThat(findings).hasSize(1) } } context("a function with inner object") { val code = """ fun test(x: Int): Int { val a = object { fun test2(x: Int): Int { when (x) { 5 -> return 5 else -> return 0 } } } when (x) { 5 -> return 5 else -> return 0 } } """ it("should not get flag when returns is in inner object") { val findings = ReturnCount(TestConfig(mapOf(ReturnCount.MAX to "2"))).lint(code) assertThat(findings).isEmpty() } } context("a function with 2 inner object") { val code = """ fun test(x: Int): Int { val a = object { fun test2(x: Int): Int { val b = object { fun test3(x: Int): Int { when (x) { 5 -> return 5 else -> return 0 } } } when (x) { 5 -> return 5 else -> return 0 } } } when (x) { 5 -> return 5 else -> return 0 } } """ it("should not get flag when returns is in inner object") { val findings = ReturnCount(TestConfig(mapOf(ReturnCount.MAX to "2"))).lint(code) assertThat(findings).isEmpty() } } context("a function with 2 inner object and exceeded max") { val code = """ fun test(x: Int): Int { val a = object { fun test2(x: Int): Int { val b = object { fun test3(x: Int): Int { when (x) { 5 -> return 5 else -> return 0 } } } when (x) { 5 -> return 5 else -> return 0 } } } when (x) { 5 -> return 5 4 -> return 4 3 -> return 3 else -> return 0 } } """ it("should get flagged when returns is in inner object") { val findings = ReturnCount(TestConfig(mapOf(ReturnCount.MAX to "2"))).lint(code) assertThat(findings).hasSize(1) } } context("function with multiple labeled return statements") { val code = """ fun readUsers(name: String): Flowable<User> { return userDao.read(name) .flatMap { if (it.isEmpty()) return@flatMap Flowable.empty<User>() return@flatMap Flowable.just(it[0]) } } """ it("should not count labeled returns from lambda by default") { val findings = ReturnCount().lint(code) assertThat(findings).isEmpty() } it("should count labeled returns from lambda when activated") { val findings = ReturnCount( TestConfig(mapOf(ReturnCount.EXCLUDE_RETURN_FROM_LAMBDA to "false"))).lint(code) assertThat(findings).hasSize(1) } it("should be empty when labeled returns are de-activated") { val findings = ReturnCount( TestConfig(mapOf( ReturnCount.EXCLUDE_LABELED to "true", ReturnCount.EXCLUDE_RETURN_FROM_LAMBDA to "false" ))).lint(code) assertThat(findings).isEmpty() } } } })
apache-2.0
3eee346f20cc4269c73db838a0c3c9f6
32.771014
108
0.414042
5.464822
false
true
false
false
pdvrieze/ProcessManager
PE-common/src/jvmMain/kotlin/nl/adaptivity/process/messaging/EndpointServlet.kt
1
10639
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.messaging import net.devrieze.util.security.AuthenticationNeededException import net.devrieze.util.security.PermissionDeniedException import nl.adaptivity.messaging.HttpResponseException import nl.adaptivity.messaging.MessagingException import nl.adaptivity.rest.annotations.HttpMethod import nl.adaptivity.util.HttpMessage import nl.adaptivity.ws.rest.RestMessageHandler import nl.adaptivity.ws.soap.SoapMessageHandler import javax.servlet.ServletConfig import javax.servlet.ServletException import javax.servlet.http.HttpServlet import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import java.io.FileNotFoundException import java.io.IOException import java.util.logging.Level import java.util.logging.Logger /** * A servlet that serves up web services provided by a [GenericEndpoint] * * @author Paul de Vrieze */ open class EndpointServlet : HttpServlet { /** * Override this to override the endpoint used by this servlet to serve * connections. In most cases it's better to provide the endpoint to the * constructor instead, or as a servlet parameter. * * @return A GenericEndpoint that implements the needed services. * @see {@link .init */ protected var endpointProvider: GenericEndpoint? = null private set /** * Get a soap handler that does the work for us. As the handler caches objects * instead of repeatedly using reflection it needs to be an object and is not * just a set of static methods. * * @return The soap handler. */ private val soapMessageHandler: SoapMessageHandler by lazy { SoapMessageHandler.newInstance(endpointProvider!!) } /** * Get a rest handler that does the work for us. As the handler caches objects * instead of repeatedly using reflection it needs to be an object and is not * just a set of static methods. * * @return The rest handler. */ private val restMessageHandler: RestMessageHandler by lazy { RestMessageHandler.newInstance(endpointProvider!!) } /** * Default constructor that allows this servlet to be instantiated directly in * tomcat. This will set the endpoint to the object itself if the object * implements GenericEndpoint. This allows servlets to provide services by * deriving from [EndpointServlet] */ constructor() { if (this is GenericEndpoint) { endpointProvider = this } } /** * A constructor for subclasses that provide an endpoint to use. * * @param endpoint The endpoint to provide. */ protected constructor(endpoint: GenericEndpoint) { endpointProvider = endpoint } /** * Handle DELETE requests. */ @Throws(ServletException::class, IOException::class) override fun doDelete(req: HttpServletRequest, resp: HttpServletResponse) { processRestSoap(HttpMethod.DELETE, req, resp) } /** * Handle GET requests. */ @Throws(ServletException::class, IOException::class) override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) { processRestSoap(HttpMethod.GET, req, resp) } /** * Handle HEAD requests. */ @Throws(ServletException::class, IOException::class) override fun doHead(req: HttpServletRequest, resp: HttpServletResponse) { processRestSoap(HttpMethod.HEAD, req, resp) } /** * Handle POST requests. */ @Throws(ServletException::class, IOException::class) override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) { processRestSoap(HttpMethod.POST, req, resp) } /** * Handle PUT requests. */ @Throws(ServletException::class, IOException::class) override fun doPut(req: HttpServletRequest, resp: HttpServletResponse) { processRestSoap(HttpMethod.PUT, req, resp) } /** * Method that does the actual work of processing requests. It will, based on * the Content-Type header deterimine whether it's a rest or soap request, and * use a [SoapMessageHandler] or [RestMessageHandler] to actually * process the message. * * @param method The HTTP method invoked. * @param request The request. * @param response The response object on which responses are written. * @todo In case we have a soap request, respond with a proper SOAP fault, not * a generic error message. */ private fun processRestSoap(method: HttpMethod, request: HttpServletRequest, response: HttpServletResponse) { try { request.authenticate(response) // Try to authenticate val message = HttpMessage(request) var soap = false try { try { if (!SoapMessageHandler.isSoapMessage(request)) { val restHandler = restMessageHandler if (!restHandler!!.processRequest(method, message, response)) { logger.warning("Error processing rest request " + request.requestURI) } } else { soap = true val soapHandler = soapMessageHandler if (!soapHandler!!.processRequest(message, response)) { logger.warning("Error processing soap request " + request.requestURI) } } } catch (e: MessagingException) { if (e.cause is Exception) { // getLogger().log(Level.WARNING, "MessagingException "+e.getMessage(), e); throw e.cause as Exception } else { throw e } } } catch (e: AuthenticationNeededException) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No authenticated user.") logger.log(Level.WARNING, "Access attempted without authentication for " + request.requestURI) } catch (e: PermissionDeniedException) { response.sendError( HttpServletResponse.SC_FORBIDDEN, "This user is not allowed to perform the requested action." ) logger.log( Level.WARNING, "Access attempted without authorization by " + request.userPrincipal + " for " + request.requestURI, e ) } catch (e: FileNotFoundException) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "The requested resource is not available.") val logger = logger if (logger.isLoggable(Level.FINER)) { logger.log(Level.FINER, "Access to an invalid resource attempted: " + request.requestURI, e) } else { logger.log(Level.WARNING, "Access to an invalid resource attempted: " + request.requestURI) } } catch (e: HttpResponseException) { response.sendError(e.responseCode, e.message) logger.log(Level.SEVERE, "Error in processing the request for " + request.requestURI, e) } } catch (e: Exception) { try { logger.log(Level.WARNING, "Error when processing REST/SOAP (" + request.requestURI + ")", e) response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.message) } catch (e1: Exception) { e1.addSuppressed(e) logger.log(Level.WARNING, "Failure to notify client of error", e) } } } /** * Initialize the servlet. If there is an `endpoint` parameter to * the servlet this will update the [endpoint][.getEndpointProvider] * used. If getEndpointProvider is overridden, that will still reflect the * actually used endpoint. */ @Throws(ServletException::class) override fun init(config: ServletConfig) { super.init(config) val className = config.getInitParameter("endpoint") if (className == null && endpointProvider === null) { throw ServletException("The EndpointServlet needs to be configured with an endpoint parameter.") } if (endpointProvider === null || className != null) { val clazz: Class<out GenericEndpoint> try { clazz = Class.forName(className).asSubclass(GenericEndpoint::class.java) } catch (e: ClassNotFoundException) { throw ServletException(e) } catch (e: ClassCastException) { throw ServletException( "The endpoint for an EndpointServlet needs to implement " + GenericEndpoint::class.java.name + " the class given is " + className, e ) } try { endpointProvider = clazz.newInstance() endpointProvider!!.initEndpoint(config) } catch (e: InstantiationException) { throw ServletException(e) } catch (e: IllegalAccessException) { throw ServletException(e) } } else { endpointProvider!!.initEndpoint(config) } } override fun destroy() { endpointProvider?.destroy() super.destroy() } companion object { private val LOGGER_NAME = EndpointServlet::class.java.name private val serialVersionUID = 5882346515807438320L /** * Get a logger object for this servlet. * * @return A logger to use to log messages. */ private val logger: Logger get() = Logger.getLogger(LOGGER_NAME) } }
lgpl-3.0
cca82b1274f886e512b308b874a16b21
37.407942
120
0.621111
5.147073
false
false
false
false
CarrotCodes/Pellet
server/src/main/kotlin/dev/pellet/server/codec/http/HTTPCharacters.kt
1
1412
package dev.pellet.server.codec.http object HTTPCharacters { val CHARS = (0..127) .map { it.toChar() } .toSet() val LOALPHA_CHARS = ('a'..'z').toSet() val UPALPHA_CHARS = ('A'..'Z').toSet() val ALPHA_CHARS = LOALPHA_CHARS + UPALPHA_CHARS val DIGIT_CHARS = ('0'..'9').toSet() val CONTROL_CHARS = (0..31).map { it.toChar() }.toSet() + setOf(127.toChar()) const val CARRIAGE_RETURN = 13.toChar() const val LINE_FEED = 10.toChar() const val SPACE = 32.toChar() const val HORIZONTAL_TAB = 9.toChar() const val QUOTE = 34.toChar() const val AMPERSAND = 38.toChar() const val ASTERISK = 42.toChar() const val COLON = 58.toChar() const val SEMICOLON = 59.toChar() const val EQUALS = 61.toChar() const val COMMA = 44.toChar() const val FORWARD_SLASH = 47.toChar() val LWS_CHARS = setOf(SPACE, HORIZONTAL_TAB) val BYTES = CHARS.map { it.code.toByte() }.toSet() val LWS_BYTES = LWS_CHARS.map { it.code.toByte() }.toSet() const val CARRIAGE_RETURN_BYTE = CARRIAGE_RETURN.code.toByte() const val LINE_FEED_BYTE = LINE_FEED.code.toByte() const val SPACE_BYTE = SPACE.code.toByte() const val HORIZONTAL_TAB_BYTE = HORIZONTAL_TAB.code.toByte() const val QUOTE_BYTE = QUOTE.code.toByte() const val COLON_BYTE = COLON.code.toByte() const val COMMA_BYTE = COMMA.code.toByte() }
apache-2.0
e36184be03776a12c5fde64cd5082e2f
34.3
81
0.628895
3.477833
false
false
false
false
sksamuel/elasticsearch-river-neo4j
streamops-session/streamops-session-kafka/src/main/kotlin/com/octaldata/session/kafka/topics/TopicUtils.kt
1
11003
package com.octaldata.session.kafka.topics import com.octaldata.domain.BrokerId import com.octaldata.domain.DeploymentConnectionConfig import com.octaldata.domain.topics.Offset import com.octaldata.domain.topics.PartitionId import com.octaldata.domain.topics.TopicName import com.octaldata.session.ElectionType import com.octaldata.session.TopicPartitionOffsets import com.octaldata.session.kafka.KafkaTopicOps import com.octaldata.session.kafka.Topic import com.octaldata.session.kafka.TopicType import com.octaldata.session.kafka.adminClient import com.octaldata.session.kafka.suspend import com.sksamuel.tabby.results.catching import com.sksamuel.tabby.results.flatMap import kotlinx.coroutines.withTimeout import org.apache.kafka.clients.admin.AlterConfigOp import org.apache.kafka.clients.admin.Config import org.apache.kafka.clients.admin.ConfigEntry import org.apache.kafka.clients.admin.ListOffsetsOptions import org.apache.kafka.clients.admin.ListTopicsOptions import org.apache.kafka.clients.admin.LogDirDescription import org.apache.kafka.clients.admin.NewPartitionReassignment import org.apache.kafka.clients.admin.OffsetSpec import org.apache.kafka.clients.admin.RecordsToDelete import org.apache.kafka.clients.admin.TopicDescription import org.apache.kafka.common.TopicPartition import org.apache.kafka.common.TopicPartitionReplica import org.apache.kafka.common.config.ConfigResource import org.apache.kafka.common.config.TopicConfig import java.util.Optional import kotlin.math.max import kotlin.time.Duration.Companion.seconds class TopicUtils(kafka: DeploymentConnectionConfig.KafkaCompatible) { private val admin = kafka.adminClient() /** * Returns the topic names and types for all topics in the cluster. */ suspend fun topics(filter: String?): Result<List<Topic>> = runCatching { val topics = admin.listTopics(ListTopicsOptions().listInternal(true)).listings().suspend() KafkaTopicOps.logger.debug("Loaded [${topics.size}] topics before filtering") val lowerfilter = filter?.lowercase() topics.filter { lowerfilter == null || it.name().contains(lowerfilter) }.map { val type = when (it.isInternal) { true -> TopicType("internal") else -> TopicType("application") } Topic(TopicName(it.name()), type) } } /** * Returns all [TopicPartition]s for the entire cluster. */ suspend fun tps(): Result<List<TopicPartition>> = catching { admin.listTopics(ListTopicsOptions().listInternal(true)).listings().suspend().toList() .flatMap { t -> val d = admin.describeTopics(listOf(t.name())).all().suspend()[t.name()]!! d.partitions().map { p -> TopicPartition(t.name(), p.partition()) } } } /** * Returns all [TopicPartitionReplica]s for the entire cluster. */ suspend fun tprs(): Result<List<TopicPartitionReplica>> = catching { admin.listTopics(ListTopicsOptions().listInternal(true)).listings().suspend().toList() .flatMap { t -> val d = admin.describeTopics(listOf(t.name())).all().suspend()[t.name()]!! d.partitions().flatMap { p -> p.replicas().map { TopicPartitionReplica(t.name(), p.partition(), it.id()) } } } } /** * Returns the list of [TopicPartition]s for this topic. */ suspend fun tps(topicName: TopicName): Result<List<TopicPartition>> = runCatching { val description = admin.describeTopics(listOf(topicName.value)).all().suspend()[topicName.value] description?.partitions()?.map { TopicPartition(description.name(), it.partition()) } ?: emptyList() } /** * Returns the kafka [TopicDescription] for a single topic. */ suspend fun describe(topicName: TopicName): Result<TopicDescription> = runCatching { admin.describeTopics(listOf(topicName.value)).all().suspend() .getOrElse(topicName.value) { error("Unknown topic ${topicName.value}") } } /** * Returns the kafka [TopicDescription] for the given topics. */ suspend fun describe(topicNames: Collection<TopicName>): Result<Map<TopicName, TopicDescription>> = runCatching { admin.describeTopics(topicNames.map { it.value }).all().suspend().mapKeys { TopicName(it.key) } } suspend fun configs(topicNames: Collection<TopicName>): Result<Map<TopicName, Config>> = runCatching { admin.describeConfigs(topicNames.map { ConfigResource(ConfigResource.Type.TOPIC, it.value) }).all().suspend().mapKeys { TopicName(it.key.name()) } } /** * Returns all [LogDirDescription]s for the given brokers. */ suspend fun logdirs(brokers: Set<Int>): Result<List<LogDirDescription>> = catching { admin.describeLogDirs(brokers).allDescriptions().suspend().values.flatMap { it.values } } /** * Returns the disk space in bytes for the leaders of this topic. */ suspend fun leaderDisk(topicName: TopicName): Result<Long> = catching { val topic = describe(topicName).bind() val leaders = topic.partitions().map { it.leader().id() } val tps = tps(topicName).bind() logdirs(leaders.toSet()).bind() .flatMap { it.replicaInfos().entries } .filter { tps.contains(it.key) } .map { it.value } .sumOf { it.size() } } /** * Returns the disk space in bytes for all replicas of this topic. */ suspend fun replicasDisk(topicName: TopicName): Result<Long> = catching { val topic = describe(topicName).bind() val brokers = topic.partitions().flatMap { it.replicas() }.map { it.id() } val tps = tps(topicName).bind() logdirs(brokers.toSet()).bind() .flatMap { it.replicaInfos().entries } .filter { tps.contains(it.key) } .map { it.value } .sumOf { it.size() } } /** * Returns the start and end offsets for all partitions of the given topic */ suspend fun offsets(topicName: TopicName): Result<List<TopicPartitionOffsets>> { return tps(topicName).flatMap { offsets(it) } } /** * Returns the start and end offsets for a collection of topic-partitions. */ suspend fun offsets(tps: List<TopicPartition>): Result<List<TopicPartitionOffsets>> = runCatching { val starts = offsets(tps, OffsetSpec.earliest()) val ends = offsets(tps, OffsetSpec.latest()) tps.map { tp -> TopicPartitionOffsets( topicName = TopicName(tp.topic()), partitionId = PartitionId(tp.partition().toString()), start = starts[tp] ?: Offset(0), end = ends[tp] ?: Offset(0), ) } } suspend fun offsets( tps: List<TopicPartition>, spec: OffsetSpec, ): Map<TopicPartition, Offset> { return withTimeout(4.seconds) { admin.listOffsets( tps.associate { TopicPartition(it.topic(), it.partition()) to spec }, ListOffsetsOptions().timeoutMs(4000) ).all() .suspend() .mapValues { Offset(it.value.offset()) } } } /** * Returns an estimate of the messages on this topic by calculating the difference * in start and end offsets for each partition. */ suspend fun estimateCount(topicName: TopicName): Result<Long> { return tps(topicName) .flatMap { offsets(it) } .map { it.fold(0L) { acc, op -> acc + op.end.value - op.start.value } } } /** * Returns an estimate of the records per topic by calculating the difference * in start and end offsets for each topic-partition. */ suspend fun estimateCount(tps: List<TopicPartition>): Result<Map<TopicName, Long>> = catching { offsets(tps).bind().groupBy { it.topicName } .mapValues { it.value.sumOf { max(0, it.end.value - it.start.value) } } } suspend fun alterPartitionReassignments( reassignments: Map<TopicPartition, Optional<NewPartitionReassignment>> ): Map<TopicPartition, Void> { return admin.alterPartitionReassignments(reassignments).values().mapValues { it.value.suspend() } } suspend fun setCompaction(topicName: TopicName, compact: Boolean) { setTopicConfig( topicName, TopicConfig.CLEANUP_POLICY_CONFIG, if (compact) TopicConfig.CLEANUP_POLICY_COMPACT else TopicConfig.CLEANUP_POLICY_DELETE ) } suspend fun setTopicConfig( topicName: TopicName, key: String, value: String, opType: AlterConfigOp.OpType = AlterConfigOp.OpType.SET, ) = runCatching { val resource = ConfigResource(ConfigResource.Type.TOPIC, topicName.value) val op = AlterConfigOp(ConfigEntry(key, value), opType) admin.incrementalAlterConfigs(mapOf(resource to listOf(op))).all().suspend() } suspend fun setRetention(topicName: TopicName, retention: Long): Result<Void> { return setTopicConfig(topicName, TopicConfig.RETENTION_MS_CONFIG, retention.toString()) } suspend fun setCompression(topicName: TopicName, compressionType: String): Result<Void> { return setTopicConfig(topicName, TopicConfig.COMPRESSION_TYPE_CONFIG, compressionType) } suspend fun setLeader( topicName: TopicName, partitionId: PartitionId, leader: BrokerId, ): Result<Unit> = catching { val topic = describe(topicName).bind() val partition = topic.partitions() .find { it.partition() == partitionId.value.toInt() } ?: error("Unknown partition ${partitionId.value}") val replicas = partition.replicas().map { it.id() } val newReplicas = (listOf(leader.value.toInt()) + replicas).distinct() val tp = TopicPartition(topicName.value, partition.partition()) admin.alterPartitionReassignments(mapOf(tp to Optional.of(NewPartitionReassignment(newReplicas)))).all().suspend() admin.electLeaders(org.apache.kafka.common.ElectionType.PREFERRED, setOf(tp)).all().suspend() } suspend fun electLeaders( topicName: TopicName, electionType: ElectionType, ): Result<Unit> = catching { // keep only the tps where the leader is not the preferred replica val tps = describe(topicName).bind().partitions() .filter { it.leader().id() != it.replicas().first().id() } .map { TopicPartition(topicName.value, it.partition()) } .toSet() val type = when (electionType) { ElectionType.UNCLEAN -> org.apache.kafka.common.ElectionType.UNCLEAN ElectionType.PREFERRED -> org.apache.kafka.common.ElectionType.PREFERRED } admin.electLeaders(type, tps).all().suspend() } suspend fun truncatePartition(topicName: TopicName, partitionId: PartitionId): Result<Boolean> = catching { val tp = TopicPartition(topicName.value, partitionId.value.toInt()) val end = admin.listOffsets(mapOf(tp to OffsetSpec.latest())).all().suspend()[tp]!! admin.deleteRecords( mapOf(tp to RecordsToDelete.beforeOffset(end.offset())) ).all().suspend() true } }
apache-2.0
ddbfeec87de898b2964c70b506196ff3
38.582734
120
0.679178
4.251546
false
true
false
false
ursjoss/scipamato
public/public-persistence-jooq/src/main/kotlin/ch/difty/scipamato/publ/persistence/paper/PublicPaperFilterConditionMapper.kt
1
5549
package ch.difty.scipamato.publ.persistence.paper import ch.difty.scipamato.common.persistence.AbstractFilterConditionMapper import ch.difty.scipamato.common.persistence.FilterConditionMapper import ch.difty.scipamato.publ.db.tables.Paper import ch.difty.scipamato.publ.db.tables.records.PaperRecord import ch.difty.scipamato.publ.entity.Code import ch.difty.scipamato.publ.entity.filter.PublicPaperFilter import org.jooq.Condition import org.jooq.TableField import org.jooq.impl.DSL import org.jooq.impl.SQLDataType import java.util.regex.Matcher import java.util.regex.Pattern private const val RE_QUOTE = "\"" private val QUOTED = Pattern.compile("$RE_QUOTE([^$RE_QUOTE]+)$RE_QUOTE") private const val QUOTED_GROUP_INDEX = 1 @FilterConditionMapper class PublicPaperFilterConditionMapper : AbstractFilterConditionMapper<PublicPaperFilter>() { @Suppress("ComplexMethod") override fun internalMap(filter: PublicPaperFilter): List<Condition> { val conditions = mutableListOf<Condition>() filter.number?.let { conditions.add(Paper.PAPER.NUMBER.eq(it)) } filter.authorMask?.let { conditions.addAll(Paper.PAPER.AUTHORS.tokenize(it)) } filter.titleMask?.let { conditions.addAll(Paper.PAPER.TITLE.tokenize(it)) } filter.methodsMask?.let { conditions.addAll(Paper.PAPER.METHODS.tokenize(it)) } if (filter.publicationYearFrom != null) { if (hasNoOrIdenticalPubYearUntil(filter)) { conditions.add(Paper.PAPER.PUBLICATION_YEAR.eq(filter.publicationYearFrom)) } else { conditions.add( Paper.PAPER.PUBLICATION_YEAR.between(filter.publicationYearFrom, filter.publicationYearUntil)) } } else if (filter.publicationYearUntil != null) { conditions.add(Paper.PAPER.PUBLICATION_YEAR.le(filter.publicationYearUntil)) } filter.populationCodes?.let { codes -> val ids = codes.map { it.id }.toTypedArray() conditions.add(Paper.PAPER.CODES_POPULATION.contains(ids)) } filter.studyDesignCodes?.let { codes -> val ids = codes.map { it.id }.toTypedArray() conditions.add(Paper.PAPER.CODES_STUDY_DESIGN.contains(ids)) } @Suppress("ComplexCondition") if ( filter.codesOfClass1 != null || filter.codesOfClass2 != null || filter.codesOfClass3 != null || filter.codesOfClass4 != null || filter.codesOfClass5 != null || filter.codesOfClass6 != null || filter.codesOfClass7 != null || filter.codesOfClass8 != null ) { val allCodes = filter.allCodes() if (allCodes.isNotEmpty()) conditions.add(allCodes.toCondition()) } return conditions } private fun hasNoOrIdenticalPubYearUntil(filter: PublicPaperFilter) = filter.publicationYearUntil == null || filter.publicationYearFrom == filter.publicationYearUntil /* * Currently does not allow to mix quoted and unquoted terms. If this will * become necessary we might have to implement a proper tokenization of the * search term, as was done in core with the SearchTerm hierarchy. */ private fun TableField<PaperRecord, String>.tokenize(mask: String): List<Condition> { val m = QUOTED.matcher(mask) val (conditions, done) = tokenizeQuoted(m) return conditions + if (!done) tokenizeUnquoted(mask) else emptyList() } private fun TableField<PaperRecord, String>.tokenizeQuoted(m: Matcher): Pair<List<Condition>, Boolean> { val conditions = mutableListOf<Condition>() var term: String? = null while (m.find()) { term = m.group(QUOTED_GROUP_INDEX) conditions.add(likeIgnoreCase("%$term%")) } return Pair(conditions, term != null) } private fun TableField<PaperRecord, String>.tokenizeUnquoted(mask: String): List<Condition> { val conditions = mutableListOf<Condition>() if (!mask.contains(" ")) conditions.add(likeIgnoreCase("%$mask%")) else for (t in mask.split(" ").toTypedArray()) { val token = t.trim { it <= ' ' } if (token.isNotEmpty()) conditions.add(likeIgnoreCase("%$token%")) } return conditions } private fun PublicPaperFilter.allCodes() = with(this) { codesOfClass1.codesNullSafe() + codesOfClass2.codesNullSafe() + codesOfClass3.codesNullSafe() + codesOfClass4.codesNullSafe() + codesOfClass5.codesNullSafe() + codesOfClass6.codesNullSafe() + codesOfClass7.codesNullSafe() + codesOfClass8.codesNullSafe() } private fun List<Code>?.codesNullSafe() = this?.mapNotNull { it.code } ?: emptyList() /** * Due to bug https://github.com/jOOQ/jOOQ/issues/4754, the straightforward way * of mapping the codes to the array of type text does not work: * * <pre> * return PAPER.CODES.contains(codeCollection.toArray(new String[0])); * </pre> * * While I originally casted to PostgresDataType.TEXT, I now need to cast to SQLDataType.CLOB * due to https://github.com/jOOQ/jOOQ/issues/7375 */ private fun List<String>.toCondition(): Condition = Paper.PAPER.CODES.contains( DSL.array( mapNotNull { DSL.`val`(it).cast(SQLDataType.CLOB) } ) ) }
bsd-3-clause
743b692b51e2adecb89d32969c74817f
41.037879
114
0.647684
4.589744
false
false
false
false
Mithrandir21/Duopoints
app/src/main/java/com/duopoints/android/ui/views/TitleSubTitleView.kt
1
1074
package com.duopoints.android.ui.views import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import com.duopoints.android.R import kotlinx.android.synthetic.main.custom_view_title_subtitle.view.* class TitleSubTitleView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : FrameLayout(context, attrs, defStyleAttr) { init { View.inflate(context, R.layout.custom_view_title_subtitle, this) attrs?.let { val ta = context.obtainStyledAttributes(it, R.styleable.TitleSubTitleView, 0, 0) try { title.text = ta.getText(R.styleable.TitleSubTitleView_title_text) header.text = ta.getText(R.styleable.TitleSubTitleView_header_text) } finally { ta.recycle() } } } fun setUserTitle(titleText: String) { title.text = titleText } fun setUserHeader(headerText: String) { header.text = headerText } }
gpl-3.0
db6de5c329efa3b1b44457cffde6b3e5
29.714286
121
0.665736
4.211765
false
false
false
false
ansman/okhttp
okhttp/src/main/kotlin/okhttp3/Route.kt
3
3052
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.net.InetSocketAddress import java.net.Proxy /** * The concrete route used by a connection to reach an abstract origin server. When creating a * connection the client has many options: * * * **HTTP proxy:** a proxy server may be explicitly configured for the client. * Otherwise the [proxy selector][java.net.ProxySelector] is used. It may return * multiple proxies to attempt. * * **IP address:** whether connecting directly to an origin server or a proxy, * opening a socket requires an IP address. The DNS server may return multiple IP addresses * to attempt. * * Each route is a specific selection of these options. */ class Route( @get:JvmName("address") val address: Address, /** * Returns the [Proxy] of this route. * * **Warning:** This may disagree with [Address.proxy] when it is null. When * the address's proxy is null, the proxy selector is used. */ @get:JvmName("proxy") val proxy: Proxy, @get:JvmName("socketAddress") val socketAddress: InetSocketAddress ) { @JvmName("-deprecated_address") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "address"), level = DeprecationLevel.ERROR) fun address(): Address = address @JvmName("-deprecated_proxy") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "proxy"), level = DeprecationLevel.ERROR) fun proxy(): Proxy = proxy @JvmName("-deprecated_socketAddress") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "socketAddress"), level = DeprecationLevel.ERROR) fun socketAddress(): InetSocketAddress = socketAddress /** * Returns true if this route tunnels HTTPS through an HTTP proxy. * See [RFC 2817, Section 5.2][rfc_2817]. * * [rfc_2817]: http://www.ietf.org/rfc/rfc2817.txt */ fun requiresTunnel() = address.sslSocketFactory != null && proxy.type() == Proxy.Type.HTTP override fun equals(other: Any?): Boolean { return other is Route && other.address == address && other.proxy == proxy && other.socketAddress == socketAddress } override fun hashCode(): Int { var result = 17 result = 31 * result + address.hashCode() result = 31 * result + proxy.hashCode() result = 31 * result + socketAddress.hashCode() return result } override fun toString(): String = "Route{$socketAddress}" }
apache-2.0
fe2828dfe0c5a8d49def9033249af289
32.538462
94
0.689384
4.23301
false
false
false
false
didi/DoraemonKit
Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/toolpanel/ToolPanelAdapter.kt
1
4686
package com.didichuxing.doraemonkit.kit.toolpanel import android.os.Process import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.RadioButton import android.widget.RadioGroup import android.widget.TextView import com.didichuxing.doraemonkit.BuildConfig import com.didichuxing.doraemonkit.DoKit import com.didichuxing.doraemonkit.R import com.didichuxing.doraemonkit.constant.SharedPrefsKey import com.didichuxing.doraemonkit.util.* import com.didichuxing.doraemonkit.widget.brvah.BaseMultiItemQuickAdapter import com.didichuxing.doraemonkit.widget.brvah.viewholder.BaseViewHolder /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2020/4/29-15:21 * 描 述: * 修订历史: * ================================================ */ class ToolPanelAdapter(kitViews: MutableList<KitWrapItem>?) : BaseMultiItemQuickAdapter<KitWrapItem, BaseViewHolder>(kitViews) { init { addItemType(KitWrapItem.TYPE_TITLE, R.layout.dk_item_group_title) addItemType(KitWrapItem.TYPE_KIT, R.layout.dk_item_kit) addItemType(KitWrapItem.TYPE_MODE, R.layout.dk_item_group_mode) addItemType(KitWrapItem.TYPE_EXIT, R.layout.dk_item_group_exit) addItemType(KitWrapItem.TYPE_VERSION, R.layout.dk_item_group_version) } override fun convert(holder: BaseViewHolder, item: KitWrapItem) { when (item.itemType) { KitWrapItem.TYPE_TITLE -> { item.name.let { if (it == DoKitCommUtil.getString(R.string.dk_category_platform)) { holder.getView<TextView>(R.id.tv_sub_title_name).visibility = View.VISIBLE holder.getView<TextView>(R.id.tv_sub_title_name).text = "(www.dokit.cn)" } else { holder.getView<TextView>(R.id.tv_sub_title_name).visibility = View.GONE } holder.getView<TextView>(R.id.tv_title_name).text = it } } KitWrapItem.TYPE_KIT -> { item.kit?.let { holder.getView<TextView>(R.id.name).setText(it.name) holder.getView<ImageView>(R.id.icon).setImageResource(it.icon) } } KitWrapItem.TYPE_MODE -> { val radioGroup = holder.getView<RadioGroup>(R.id.rb_group) val rbNormal = holder.getView<RadioButton>(R.id.rb_normal) val rbSystem = holder.getView<RadioButton>(R.id.rb_system) radioGroup.setOnCheckedChangeListener { _, checkedId -> if (checkedId == R.id.rb_normal) { //选中normal DoKitSPUtil.putString(SharedPrefsKey.FLOAT_START_MODE, "normal") } else { //选中系统 DoKitSPUtil.putString(SharedPrefsKey.FLOAT_START_MODE, "system") } } rbNormal.setOnClickListener { rbNormal.postDelayed({ AppUtils.relaunchApp() Process.killProcess(Process.myPid()) System.exit(1) }, 500) } rbSystem.setOnClickListener { rbSystem.postDelayed({ AppUtils.relaunchApp() Process.killProcess(Process.myPid()) System.exit(1) }, 500) } val floatMode = DoKitSPUtil.getString(SharedPrefsKey.FLOAT_START_MODE, "normal") if (floatMode == "normal") { rbNormal.isChecked = true } else { rbSystem.isChecked = true } } KitWrapItem.TYPE_EXIT -> { holder.getView<TextView>(R.id.close).setOnClickListener { DoKit.hideToolPanel() DoKit.hide() } } KitWrapItem.TYPE_VERSION -> { val name = holder.getView<TextView>(R.id.version) //适配无法准确获取底部导航栏高度的bug if (name.parent != null) { (name.parent as ViewGroup).setPadding(0, 0, 0, BarUtils.getNavBarHeight()) } val version: String = DoKitCommUtil.getString(R.string.dk_kit_version) name.text = String.format(version, BuildConfig.DOKIT_VERSION) } } } }
apache-2.0
1279611576f2c15b61835f4432dd8377
37.621849
98
0.542428
4.670732
false
false
false
false
natanieljr/droidmate
project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/strategy/manual/ManualExploration.kt
1
6676
@file:Suppress("unused") package org.droidmate.exploration.strategy.manual import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.droidmate.configuration.ConfigProperties.Exploration.launchActivityDelay import org.droidmate.configuration.ConfigProperties.Exploration.widgetActionDelay import org.droidmate.configuration.ConfigProperties.Output.outputDir import org.droidmate.deviceInterface.exploration.ActionType import org.droidmate.deviceInterface.exploration.ExplorationAction import org.droidmate.deviceInterface.exploration.GlobalAction import org.droidmate.deviceInterface.exploration.LaunchApp import org.droidmate.exploration.ExplorationContext import org.droidmate.exploration.actions.pressBack import org.droidmate.exploration.actions.launchApp import org.droidmate.exploration.actions.setText import org.droidmate.exploration.strategy.AExplorationStrategy import org.slf4j.Logger import saarland.cispa.exploration.android.strategy.action.SwipeTo import org.droidmate.exploration.strategy.manual.action.showTargetsInImg import org.droidmate.exploration.strategy.manual.action.triggerTap import org.droidmate.explorationModel.factory.AbstractModel import org.droidmate.explorationModel.interaction.State import org.droidmate.explorationModel.interaction.Widget import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths typealias ActionOnly = TargetTypeI<Int, ExplorationAction?> /** * This class allows to manually navigate through by choosing action targets via keyboard input. * This feature may be used for debugging purposes or as base class * to manually construct exploration models (i.e. for GroundTruth creation). */ open class ManualExploration<T>(private val resetOnStart: Boolean = true) : AExplorationStrategy(), StdinCommandI<T,ExplorationAction> { override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> computeNextAction( eContext: ExplorationContext<M, S, W> ): ExplorationAction = decideBySTDIN() override fun getPriority(): Int = 42 lateinit var eContext: ExplorationContext<*,*,*> override fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> initialize(initialContext: ExplorationContext<M, S, W>) { super.initialize(initialContext) eContext = initialContext Files.deleteIfExists(tmpImg) imgFile.delete() println("\n-----------------------") println("available command options are:") println(actionOptions.joinToString(separator = "\n")) println("-----------------------") println("\tstart exploration for for ${eContext.model.config.appName}") println("-----------------------\n") } protected val state get() = eContext.getCurrentState() private val cfg get() = eContext.model.config // these properties have to be lazy since eContext is only initialized after the method initialize was called protected open val decisionImgDir: Path by lazy { Paths.get(eContext.cfg[outputDir].toString()) } private val imgFile by lazy { decisionImgDir.resolve("stateImg.jpg").toFile() } /** temporary state image (fetched via adb) for target highlighting. */ private val tmpImg by lazy { Paths.get(decisionImgDir.resolve("deviceImg.png").toString()) } private val debugXmlFile by lazy { decisionImgDir.resolve("state.xml").toFile() } // (command: ActionOnly, w: Widget?, candidate: Int?, input: List<String>)->ExplorationAction? override val createAction:CandidateCreator<T, ExplorationAction?> = {cmd, w, _, input -> val lIdx = if(!cmd.requiresWidget()) labelIdx -1 else labelIdx when(cmd){ is DEBUG -> { debugXmlFile.writeText(eContext.lastDump) @Suppress("UNUSED_VARIABLE") val widgets = state.widgets w?.let{ println("${w.id}: resId=${w.resourceId}, nlpText=${w.nlpText}") } null } is CLICK -> w?.triggerTap(delay=eContext.cfg[widgetActionDelay]) is TEXT_INPUT -> if(w?.isInputField == false){ log.error("target is no input field") null } else w?.setText(input[lIdx], sendEnter = false,delay=200) is BACK -> ExplorationAction.pressBack() is RESET -> LaunchApp(eContext.apk.packageName, eContext.cfg[launchActivityDelay]) is SCROLL_RIGHT -> SwipeTo.right(state.widgets) is SCROLL_LEFT -> SwipeTo.left(state.widgets) is SCROLL_UP -> SwipeTo.bottom(state.widgets) is SCROLL_DOWN -> SwipeTo.top(state.widgets) is FETCH -> GlobalAction(ActionType.FetchGUI) is TERMINATE -> GlobalAction(ActionType.Terminate) is LIST_INPUTS -> { println( state.actionableWidgets.mapIndexedNotNull { index, it -> if(it.isInputField) "[$index]:\t $it" else null } .joinToString(separator = "\n")) null } is LIST -> { var i=0 println( state.actionableWidgets.joinToString(separator = "\n") { "[${i++}]:\t "+it } ) null } else -> throw NotImplementedError("missing case") } } // REMARK has to be lazy since createAction is implemented by child classes override val actionOptions: List<TargetTypeI<T, ExplorationAction?>> by lazy { listOf( CLICK(createAction), TEXT_INPUT(createAction), BACK(createAction), RESET(createAction), SCROLL_RIGHT(createAction), SCROLL_LEFT(createAction), SCROLL_UP(createAction), SCROLL_DOWN(createAction), FETCH(createAction), TERMINATE(createAction), LIST_INPUTS(createAction), LIST(createAction), DEBUG(createAction) ) } override val isValid : (input: List<String>, suggested: T?, numCandidates: Int) -> TargetTypeI<T, ExplorationAction?> = { input: List<String>, suggested: T?, numCandidates: Int -> ActionOnly.isValid(false,input,suggested, createAction, actionOptions, numCandidates) } override suspend fun decideBySTDIN(suggested: T?, candidates: List<T>): ExplorationAction{ if(eContext.isEmpty()) { return if (resetOnStart) eContext.launchApp() else GlobalAction(ActionType.FetchGUI) } println("_____________________________") println(state) showTargetsInImg(eContext,state.actionableWidgets,imgFile) withContext(Dispatchers.IO){ Files.deleteIfExists(tmpImg) } if(state.actionableWidgets.any { !it.isVisible }) println("Note there are (invisible) target elements outside of this screen.") var action: ExplorationAction? do { action = fromSTDIN(isValid, widgetTarget = { idString -> idString.toIntOrNull()?.let { id -> if(id<0 || id >= state.actionableWidgets.size){ println("ERROR no widget with id $id available") null } else state.actionableWidgets[id] } }, candidates = candidates, suggested = suggested ) }while(action == null) return action } companion object: Logging { override val log: Logger = getLogger() } }
gpl-3.0
d4ddf907115783200227811e66e617b6
38.976048
136
0.733972
3.910955
false
false
false
false
cout970/ComputerMod
src/main/kotlin/com/cout970/computer/block/OldComputer.kt
1
2584
package com.cout970.computer.block import com.cout970.computer.Computer import com.cout970.computer.tileentity.TileOldComputer import com.google.common.base.Predicate import net.minecraft.block.ITileEntityProvider import net.minecraft.block.material.Material import net.minecraft.block.properties.IProperty import net.minecraft.block.properties.PropertyEnum import net.minecraft.block.state.IBlockState import net.minecraft.entity.EntityLivingBase import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.tileentity.TileEntity import net.minecraft.util.EnumFacing import net.minecraft.util.EnumHand import net.minecraft.util.math.BlockPos import net.minecraft.world.World /** * Created by cout970 on 19/05/2016. */ object OldComputer : BlockMultiState("old_computer", Material.IRON), ITileEntityProvider { lateinit var propertyDirection: IProperty<EnumFacing> override fun createNewTileEntity(worldIn: World?, meta: Int): TileEntity? = TileOldComputer() override fun onBlockActivated(worldIn: World, pos: BlockPos, state: IBlockState, playerIn: EntityPlayer, hand: EnumHand?, heldItem: ItemStack?, side: EnumFacing?, hitX: Float, hitY: Float, hitZ: Float): Boolean { if (!worldIn.isRemote) { val facing = state.getValue(propertyDirection).opposite playerIn.openGui(Computer, if (facing == side) 1 else 0, worldIn, pos.x, pos.y, pos.z) } return true } override fun onBlockPlacedBy(worldIn: World?, pos: BlockPos?, state: IBlockState?, placer: EntityLivingBase?, stack: ItemStack?) { super.onBlockPlacedBy(worldIn, pos, state, placer, stack) val newState = state?.withProperty(propertyDirection, placer?.adjustedHorizontalFacing?.opposite) if (newState != null) { worldIn?.setBlockState(pos, newState) } } override fun getProperties(): Array<IProperty<*>> { propertyDirection = PropertyEnum.create("facing", EnumFacing::class.java, Predicate { it?.frontOffsetY == 0 }) return arrayOf(propertyDirection) } override fun getStateMap(): Map<Int, IBlockState> { return mapOf( 0 to defaultState.withProperty(propertyDirection, EnumFacing.NORTH), 1 to defaultState.withProperty(propertyDirection, EnumFacing.SOUTH), 2 to defaultState.withProperty(propertyDirection, EnumFacing.WEST), 3 to defaultState.withProperty(propertyDirection, EnumFacing.EAST) ) } override fun hasSubtypes(): Boolean = false }
gpl-3.0
ea6f3e607a7cfe40c52742e46d9ed3ed
40.693548
216
0.731424
4.606061
false
false
false
false
cwoolner/flex-poker
src/main/kotlin/com/flexpoker/table/command/events/TableEvents.kt
1
8027
package com.flexpoker.table.command.events import com.fasterxml.jackson.annotation.JsonSubTypes import com.fasterxml.jackson.annotation.JsonTypeInfo import com.flexpoker.framework.event.Event import com.flexpoker.table.command.Card import com.flexpoker.table.command.FlopCards import com.flexpoker.table.command.HandDealerState import com.flexpoker.table.command.PlayerAction import com.flexpoker.table.command.PocketCards import com.flexpoker.table.command.RiverCard import com.flexpoker.table.command.TurnCard import com.flexpoker.table.command.aggregate.HandEvaluation import org.pcollections.PMap import org.pcollections.PSet import org.pcollections.PVector import java.time.Instant import java.util.UUID @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes( JsonSubTypes.Type(value = ActionOnChangedEvent::class, name = "ActionOnChanged"), JsonSubTypes.Type(value = AutoMoveHandForwardEvent::class, name = "AutoMoveHandForward"), JsonSubTypes.Type(value = CardsShuffledEvent::class, name = "CardsShuffled"), JsonSubTypes.Type(value = FlopCardsDealtEvent::class, name = "FlopCardsDealt"), JsonSubTypes.Type(value = HandCompletedEvent::class, name = "HandCompleted"), JsonSubTypes.Type(value = HandDealtEvent::class, name = "HandDealt"), JsonSubTypes.Type(value = LastToActChangedEvent::class, name = "LastToActChanged"), JsonSubTypes.Type(value = PlayerAddedEvent::class, name = "PlayerAdded"), JsonSubTypes.Type(value = PlayerBustedTableEvent::class, name = "PlayerBustedTableEvent"), JsonSubTypes.Type(value = PlayerCalledEvent::class, name = "PlayerCalled"), JsonSubTypes.Type(value = PlayerCheckedEvent::class, name = "PlayerChecked"), JsonSubTypes.Type(value = PlayerFoldedEvent::class, name = "PlayerFolded"), JsonSubTypes.Type(value = PlayerForceCheckedEvent::class, name = "PlayerForceChecked"), JsonSubTypes.Type(value = PlayerForceFoldedEvent::class, name = "PlayerForceFolded"), JsonSubTypes.Type(value = PlayerRaisedEvent::class, name = "PlayerRaised"), JsonSubTypes.Type(value = PlayerRemovedEvent::class, name = "PlayerRemoved"), JsonSubTypes.Type(value = PotAmountIncreasedEvent::class, name = "PotAmountIncreased"), JsonSubTypes.Type(value = PotClosedEvent::class, name = "PotClosed"), JsonSubTypes.Type(value = PotCreatedEvent::class, name = "PotCreated"), JsonSubTypes.Type(value = RiverCardDealtEvent::class, name = "RiverCardDealt"), JsonSubTypes.Type(value = RoundCompletedEvent::class, name = "RoundCompleted"), JsonSubTypes.Type(value = TableCreatedEvent::class, name = "TableCreated"), JsonSubTypes.Type(value = TablePausedEvent::class, name = "TablePaused"), JsonSubTypes.Type(value = TableResumedEvent::class, name = "TableResumed"), JsonSubTypes.Type(value = TurnCardDealtEvent::class, name = "TurnCardDealt"), JsonSubTypes.Type(value = WinnersDeterminedEvent::class, name = "WinnersDetermined") ) sealed interface TableEvent : Event sealed class BaseTableEvent(override val aggregateId: UUID) : TableEvent { override var version = 0 override val time: Instant = Instant.now() } data class ActionOnChangedEvent (val tableId: UUID, val gameId: UUID, val handId: UUID, val playerId: UUID) : BaseTableEvent(tableId) data class AutoMoveHandForwardEvent (val tableId: UUID, val gameId: UUID, val handId: UUID) : BaseTableEvent(tableId) data class CardsShuffledEvent (val tableId: UUID, val gameId: UUID, val shuffledDeck: List<Card>) : BaseTableEvent(tableId) data class FlopCardsDealtEvent (val tableId: UUID, val gameId: UUID, val handId: UUID) : BaseTableEvent(tableId) data class HandCompletedEvent(val tableId: UUID, val gameId: UUID, val handId: UUID, val playerToChipsAtTableMap: PMap<UUID, Int>) : BaseTableEvent(tableId) data class HandDealtEvent ( val tableId: UUID, val gameId: UUID, val handId: UUID, val flopCards: FlopCards, val turnCard: TurnCard, val riverCard: RiverCard, val buttonOnPosition: Int, val smallBlindPosition: Int, val bigBlindPosition: Int, val lastToActPlayerId: UUID, val seatMap: PMap<Int, UUID?>, val playerToPocketCardsMap: PMap<UUID, PocketCards>, val possibleSeatActionsMap: PMap<UUID, Set<PlayerAction>>, val playersStillInHand: PSet<UUID>, val handEvaluations: PVector<HandEvaluation>, val handDealerState: HandDealerState, val chipsInBack: PMap<UUID, Int>, val chipsInFrontMap: PMap<UUID, Int>, val callAmountsMap: PMap<UUID, Int>, val raiseToAmountsMap: PMap<UUID, Int>, val smallBlind: Int, val bigBlind: Int) : BaseTableEvent(tableId) data class LastToActChangedEvent (val tableId: UUID, val gameId: UUID, val handId: UUID, val playerId: UUID) : BaseTableEvent(tableId) data class PlayerAddedEvent (val tableId: UUID, val gameId: UUID, val playerId: UUID, val chipsInBack: Int, val position: Int) : BaseTableEvent(tableId) data class PlayerBustedTableEvent (val tableId: UUID, val gameId: UUID, val playerId: UUID) : BaseTableEvent(tableId) data class PlayerCalledEvent (val tableId: UUID, val gameId: UUID, val handId: UUID, val playerId: UUID) : BaseTableEvent(tableId) data class PlayerCheckedEvent (val tableId: UUID, val gameId: UUID, val handId: UUID, val playerId: UUID) : BaseTableEvent(tableId) data class PlayerFoldedEvent (val tableId: UUID, val gameId: UUID, val handId: UUID, val playerId: UUID) : BaseTableEvent(tableId) data class PlayerForceCheckedEvent (val tableId: UUID, val gameId: UUID, val handId: UUID, val playerId: UUID) : BaseTableEvent(tableId) data class PlayerForceFoldedEvent (val tableId: UUID, val gameId: UUID, val handId: UUID, val playerId: UUID) : BaseTableEvent(tableId) data class PlayerRaisedEvent (val tableId: UUID, val gameId: UUID, val handId: UUID, val playerId: UUID, val raiseToAmount: Int) : BaseTableEvent(tableId) data class PlayerRemovedEvent (val tableId: UUID, val gameId: UUID, val playerId: UUID) : BaseTableEvent(tableId) data class PotAmountIncreasedEvent (val tableId: UUID, val gameId: UUID, val handId: UUID, val potId: UUID, val amountIncreased: Int) : BaseTableEvent(tableId) data class PotClosedEvent (val tableId: UUID, val gameId: UUID, val handId: UUID, val potId: UUID) : BaseTableEvent(tableId) data class PotCreatedEvent (val tableId: UUID, val gameId: UUID, val handId: UUID, val potId: UUID, val playersInvolved: Set<UUID>) : BaseTableEvent(tableId) data class RiverCardDealtEvent (val tableId: UUID, val gameId: UUID, val handId: UUID) : BaseTableEvent(tableId) data class RoundCompletedEvent (val tableId: UUID, val gameId: UUID, val handId: UUID, val nextHandDealerState: HandDealerState) : BaseTableEvent(tableId) data class TableCreatedEvent (val tableId: UUID, val gameId: UUID, val numberOfPlayersPerTable: Int, val seatPositionToPlayerMap: PMap<Int, UUID?>, val startingNumberOfChips: Int) : BaseTableEvent(tableId) data class TablePausedEvent (val tableId: UUID, val gameId: UUID) : BaseTableEvent(tableId) data class TableResumedEvent (val tableId: UUID, val gameId: UUID) : BaseTableEvent(tableId) data class TurnCardDealtEvent (val tableId: UUID, val gameId: UUID, val handId: UUID) : BaseTableEvent(tableId) data class WinnersDeterminedEvent (val tableId: UUID, val gameId: UUID, val handId: UUID, val playersToShowCards: Set<UUID>, val playersToChipsWonMap: PMap<UUID, Int>) : BaseTableEvent(tableId)
gpl-2.0
a964468691246e6662a8388563b6bc9a
52.872483
113
0.714962
4.412864
false
false
false
false
FFlorien/AmpachePlayer
app/src/main/java/be/florien/anyflow/data/server/model/AmpachePlayList.kt
1
486
package be.florien.anyflow.data.server.model import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonInclude /** * Server-side data structures that relates to playlist */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) class AmpachePlayList { var id: Long = 0 var name: String = "" var owner: String = "" var items: Int = 0 var tag: List<AmpacheTagName> = mutableListOf() }
gpl-3.0
a610a4dc448e9b02572e02727183b98d
26.055556
60
0.746914
4.05
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/intentions/AddImplIntention.kt
1
1229
package org.rust.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RsImplItem import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.psi.ext.RsStructOrEnumItemElement import org.rust.lang.core.psi.ext.parentOfType class AddImplIntention : RsElementBaseIntentionAction<AddImplIntention.Context>() { override fun getText() = "Add impl block" override fun getFamilyName() = text class Context(val type: RsStructOrEnumItemElement, val name: String) override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? { val struct = element.parentOfType<RsStructOrEnumItemElement>() ?: return null val name = struct.name ?: return null return Context(struct, name) } override fun invoke(project: Project, editor: Editor, ctx: Context) { var impl = RsPsiFactory(project).createInherentImplItem(ctx.name, ctx.type.typeParameterList, ctx.type.whereClause) impl = ctx.type.parent.addAfter(impl, ctx.type) as RsImplItem editor.caretModel.moveToOffset(impl.textOffset + impl.textLength - 1) } }
mit
78c82a0e6d5f4e0bc86e282484c78575
39.966667
123
0.755899
4.28223
false
false
false
false
nickbutcher/plaid
app/src/main/java/io/plaidapp/ui/recyclerview/GridItemDividerDecoration.kt
1
2870
/* * Copyright 2019 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.plaidapp.ui.recyclerview import android.content.Context import android.graphics.Canvas import android.graphics.Paint import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.annotation.DimenRes import androidx.annotation.Dimension import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import io.plaidapp.core.ui.recyclerview.Divided /** * A [RecyclerView.ItemDecoration] which draws dividers (along the right & bottom) * for [RecyclerView.ViewHolder]s which implement [Divided]. */ class GridItemDividerDecoration( @param:Dimension private val dividerSize: Int, @ColorInt dividerColor: Int ) : RecyclerView.ItemDecoration() { private val paint: Paint = Paint().also { it.color = dividerColor it.style = Paint.Style.FILL } constructor( context: Context, @DimenRes dividerSizeResId: Int, @ColorRes dividerColorResId: Int ) : this( context.resources.getDimensionPixelSize(dividerSizeResId), ContextCompat.getColor(context, dividerColorResId) ) override fun onDrawOver(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) { if (parent.isAnimating) return val lm = parent.layoutManager ?: return (0 until parent.childCount).forEach { i -> val child = parent.getChildAt(i) val viewHolder = parent.getChildViewHolder(child) if (viewHolder is Divided) { val right = lm.getDecoratedRight(child) val bottom = lm.getDecoratedBottom(child) // draw the bottom divider canvas.drawRect( lm.getDecoratedLeft(child).toFloat(), (bottom - dividerSize).toFloat(), right.toFloat(), bottom.toFloat(), paint ) // draw the right edge divider canvas.drawRect( (right - dividerSize).toFloat(), lm.getDecoratedTop(child).toFloat(), right.toFloat(), (bottom - dividerSize).toFloat(), paint ) } } } }
apache-2.0
25eddf2c7835ede0e5693274547654b3
33.578313
94
0.641115
4.939759
false
false
false
false
material-components/material-components-android-examples
Reply/app/src/main/java/com/materialstudies/reply/ui/nav/OnSandwichSlideAction.kt
1
1768
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.materialstudies.reply.ui.nav import android.view.View import androidx.annotation.FloatRange import com.materialstudies.reply.util.normalize /** * Callback used to run actions when the offset/progress of [BottomNavDrawerFragment]'s account * picker sandwich animation changes. */ interface OnSandwichSlideAction { /** * Called when the sandwich animation is running, either opening or closing the account picker. * [slideOffset] is a value between 0 and 1. 0 represents the closed, default state with the * account picker not visible. 1 represents the open state with the account picker visible. */ fun onSlide( @FloatRange( from = 0.0, fromInclusive = true, to = 1.0, toInclusive = true ) slideOffset: Float ) } /** * Rotate the given [view] counter-clockwise by 180 degrees. */ class HalfCounterClockwiseRotateSlideAction( private val view: View ) : OnSandwichSlideAction { override fun onSlide(slideOffset: Float) { view.rotation = slideOffset.normalize( 0F, 1F, 180F, 0F ) } }
apache-2.0
ed45697246f287bc16e373124fb79da2
29.5
99
0.684389
4.35468
false
false
false
false
255BITS/hypr
app/src/main/java/hypr/hypergan/com/hypr/Main/MainInteractor.kt
1
3168
package hypr.hypergan.com.hypr.Main import android.content.Context import android.util.Log import hotchemi.android.rate.AppRate import hypr.hypergan.com.hypr.Generator.Generator import hypr.hypergan.com.hypr.Network.ModelDownloader import hypr.hypergan.com.hypr.R import hypr.hypergan.com.hypr.Util.GoogleSignIn import hypr.hypergan.com.hypr.Util.InAppBilling.IabHelper import hypr.hypergan.com.hypr.Util.InAppBilling.Inventory import hypr.hypergan.com.hypr.Util.JsonReader import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async as async import org.greenrobot.eventbus.EventBus import org.jetbrains.anko.coroutines.experimental.bg import java.io.File class MainInteractor(val context: Context) : MainMvp.interactor { var presenter: MainPresenter? = null var billingHelper: IabHelper = IabHelper(context, context.getString(R.string.API_KEY)) val googleSignInClient = GoogleSignIn(context) var listOfGenerators: List<Generator>? = listOf() var modelDownloader = ModelDownloader() init { googleSignInClient.client.connect() startInAppBilling() } private fun startInAppBilling() { billingHelper.startSetup { result -> if (result.isSuccess) { billingHelper.isConnected = true } else { billingHelper.isConnected = false Log.d("IabHelper", "Problem setting up In-app Billing: $result") } } } override fun hasBoughtItem(itemId: String): Boolean { val hasBoughtItem = if (itemId.isEmpty()) { true } else { val inventory = query(mutableListOf(itemId)) inventory.hasPurchase(itemId) } return hasBoughtItem } fun query(skus: MutableList<String>): Inventory { return if (billingHelper.isConnected) { billingHelper.queryInventory(true, skus, null) } else { Inventory() } } override fun stopInAppBilling() { billingHelper.disposeWhenFinished() } private fun showDownloadProgress(bytesTransferred: Long, totalByteCount: Long) { val percent: Float = (bytesTransferred * 100.0f) / totalByteCount EventBus.getDefault().post(percent) } override fun getGeneratorsFromNetwork(applicationContext: Context): Deferred<List<Generator>?> { return GlobalScope.async(Dispatchers.Main) { val listOfGenerators = GlobalScope.async { JsonReader().getGeneratorsFromJson(applicationContext) }.await() [email protected] = listOfGenerators return@async listOfGenerators } } fun rateAppInit() { AppRate.with(context) .setInstallDays(0) .setLaunchTimes(3) .setRemindInterval(2) .setShowLaterButton(true) .setDebug(false) .setOnClickButtonListener { which -> Log.d(MainActivity::class.java.name, Integer.toString(which)) } .monitor() } }
mit
d74c151fa6291148862b2750a6c9b679
32
119
0.665088
4.714286
false
false
false
false
martin-nordberg/KatyDOM
Katydid-Events-JVM/src/main/kotlin/x/katydid/events/types/KatydidMouseEventImpl.kt
1
1696
// // (C) Copyright 2018-2019 Martin E. Nordberg III // Apache 2.0 License // package /*jvm*/x.katydid.events.types import o.katydid.events.types.KatydidMouseEvent import x.katydid.events.domevents.MouseEvent //--------------------------------------------------------------------------------------------------------------------- open class KatydidMouseEventImpl( private val event: MouseEvent ) : KatydidUiEventImpl(event), KatydidMouseEvent { override val altKey: Boolean get() = TODO("not implemented") override val button: Short get() = TODO("not implemented") override val buttons: Short get() = TODO("not implemented") override val clientX: Int get() = TODO("not implemented") override val clientY: Int get() = TODO("not implemented") override val ctrlKey: Boolean get() = TODO("not implemented") override val metaKey: Boolean get() = TODO("not implemented") override val offsetX: Double get() = TODO("not implemented") override val offsetY: Double get() = TODO("not implemented") override val pageX: Double get() = TODO("not implemented") override val pageY: Double get() = TODO("not implemented") override val screenX: Int get() = TODO("not implemented") override val screenY: Int get() = TODO("not implemented") override val shiftKey: Boolean get() = TODO("not implemented") override fun getModifierState(key: String): Boolean { TODO("not implemented") } } //---------------------------------------------------------------------------------------------------------------------
apache-2.0
663af54a51913281fa00d61cbbe47029
24.313433
119
0.549528
5.062687
false
false
false
false
mctoyama/PixelClient
src/main/kotlin/org/pixelndice/table/pixelclient/fx/PopupBar.kt
1
1929
package org.pixelndice.table.pixelclient.fx import javafx.scene.Node import javafx.scene.control.Label import javafx.scene.control.TextField import javafx.scene.input.KeyCode import javafx.scene.input.KeyEvent import javafx.scene.layout.VBox import javafx.stage.Popup import javafx.stage.Screen import org.pixelndice.table.pixelclient.PixelResourceBundle import org.pixelndice.table.pixelclient.ds.resource.Bar class PopupBar(owner: Node, bar: Bar): Popup(){ private val vbox = VBox() private val label = Label(PixelResourceBundle.getString("key.bar")) private val textField = TextField() init { val rect = javafx.scene.shape.Rectangle(15.0,15.0) rect.fill = bar.color label.graphic = rect textField.setOnKeyPressed { event: KeyEvent -> if( event.code == KeyCode.ENTER) { content.clear() var text = textField.text.trim() if( text.startsWith("+")){ text = text.removePrefix("+") if( text.toIntOrNull() != null ) bar.current += text.toInt() }else if (text.startsWith("-")){ text = text.removePrefix("-") if( text.toIntOrNull() != null ) bar.current -= text.toInt() }else{ if (text.startsWith("=")) text = text.removePrefix("=") if( text.toIntOrNull() != null ) bar.current = text.toInt() } }else if( event.code == KeyCode.ESCAPE) content.clear() } vbox.children.addAll(label,textField) content.add(vbox) val primaryScreenBounds = Screen.getPrimary().visualBounds show(owner, Math.ceil(primaryScreenBounds.width / 2.0), Math.ceil(primaryScreenBounds.height / 2.0)) } }
bsd-2-clause
e4093fe97962c0005b6ed54f41382b64
28.242424
108
0.573872
4.637019
false
false
false
false
mswift42/apg
Wo4/app/src/main/java/mswift42/com/github/wo4/WorkoutDetailFragment.kt
1
1783
package mswift42.com.github.wo4 import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentTransaction import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView /** * A simple [Fragment] subclass. */ class WorkoutDetailFragment : Fragment() { private var workoutId: Long = 0 override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { if (savedInstanceState != null) { workoutId = savedInstanceState.getLong("workoutId") } else { val ft = childFragmentManager.beginTransaction() val stopwatchfragment = StopWatchFragment() ft.replace(R.id.stopwatch_container, stopwatchfragment) ft.addToBackStack(null) ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) ft.commit() } // Inflate the layout for this fragment return inflater!!.inflate(R.layout.fragment_workout_detail, container, false) } fun setWorkoutId(id: Long) { this.workoutId = id } override fun onStart() { super.onStart() val view = view if (view != null) { val title = view.findViewById(R.id.textTitle) as TextView val workout = Workout.workouts[workoutId.toInt()] title.text = workout.name val desc = view.findViewById(R.id.textDescription) as TextView desc.text = workout.description } } override fun onSaveInstanceState(saveInstanceState: Bundle?) { saveInstanceState!!.putLong("workoutId", workoutId) } }// Required empty public constructor
gpl-3.0
d87cb3d7ae3c29e9ff3c851477d7fbb9
30.839286
85
0.654515
4.831978
false
false
false
false
stripe/stripe-android
payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/CountryConfig.kt
1
3001
package com.stripe.android.ui.core.elements import androidx.annotation.RestrictTo import androidx.annotation.StringRes import com.stripe.android.core.model.Country import com.stripe.android.core.model.CountryCode import com.stripe.android.core.model.CountryUtils import com.stripe.android.ui.core.R import java.util.Locale /** * This is the configuration for a country dropdown. * * @property onlyShowCountryCodes: a list of country codes that should be shown. If empty, all * countries will be shown. * @property locale: the locale used to display the country names. * @property tinyMode: whether to display in "tiny mode" when collapsed, a smaller UI form used when * the dropdown menu is inside another component, like [PhoneNumberElement]. * @property collapsedLabelMapper: function called to get the collapsed label for the given country. * @param expandedLabelMapper: function called to get the expanded label for the given country. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class CountryConfig( val onlyShowCountryCodes: Set<String> = emptySet(), val locale: Locale = Locale.getDefault(), override val tinyMode: Boolean = false, private val collapsedLabelMapper: (Country) -> String = { country -> country.name }, expandedLabelMapper: (Country) -> String = { country -> "${countryCodeToEmoji(country.code.value)} ${country.name}" } ) : DropdownConfig { override val debugLabel = "country" @StringRes override val label = R.string.address_label_country_or_region internal val countries = CountryUtils.getOrderedCountries(locale) .filter { onlyShowCountryCodes.isEmpty() || onlyShowCountryCodes.contains(it.code.value) } override val rawItems = countries.map { it.code.value } override val displayItems: List<String> = countries.map(expandedLabelMapper) override fun getSelectedItemLabel(index: Int) = countries.getOrNull(index)?.let(collapsedLabelMapper) ?: "" override fun convertFromRaw(rawValue: String) = CountryUtils.getCountryByCode(CountryCode.create(rawValue), Locale.getDefault()) ?.let { country -> countries.indexOf(country).takeUnless { it == -1 }?.let { displayItems[it] } } ?: displayItems.firstOrNull() ?: "" companion object { /** * Convert 2-letter country code to the corresponding flag, using * [regional indicator symbols](https://en.wikipedia.org/wiki/Regional_indicator_symbol). */ internal fun countryCodeToEmoji(countryCode: String): String { if (countryCode.length != 2) { return "🌐" } val firstLetter = Character.codePointAt(countryCode, 0) - 0x41 + 0x1F1E6 val secondLetter = Character.codePointAt(countryCode, 1) - 0x41 + 0x1F1E6 return String(Character.toChars(firstLetter).plus(Character.toChars(secondLetter))) } } }
mit
4c2f0cbadcc69edd9a20bce6909ae991
40.638889
100
0.692795
4.421829
false
false
false
false
nsev/roadinfo-api-ms
src/main/kotlin/fi/nsev/roadinfo/api/roadFluency/server/JourneyTimeController.kt
1
1175
package fi.nsev.roadinfo.api.roadFluency.server import fi.digitraffic.tie.sujuvuus.schemas.JourneyTimeResponse import fi.nsev.roadinfo.api.roadFluency.common.JourneyTimeService import fi.nsev.roadinfo.api.server.ApiController import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController @RestController class JourneyTimeController : ApiController{ private val journeyTimeService: JourneyTimeService private val logger : Logger = LoggerFactory.getLogger(JourneyTimeController::class.java) @Autowired constructor(journeyTimeService: JourneyTimeService){ this.journeyTimeService = journeyTimeService } @RequestMapping(value = "/journeyTime", method = arrayOf(RequestMethod.GET)) fun journeyTime(): JourneyTimeResponse { logger.debug("/journeyTime called") val journeyTimeResponse : JourneyTimeResponse = journeyTimeService.getJourneyTime() return journeyTimeResponse } }
apache-2.0
768bf247795623c56a5e4b7365d955a5
38.2
92
0.808511
4.484733
false
false
false
false
AndroidX/androidx
room/room-compiler/src/test/kotlin/androidx/room/processor/QueryMethodProcessorTest.kt
3
65422
/* * Copyright (C) 2016 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.room.processor import COMMON import androidx.room.Dao import androidx.room.Query import androidx.room.compiler.codegen.XClassName import androidx.room.compiler.codegen.XTypeName import androidx.room.compiler.codegen.asClassName import androidx.room.compiler.codegen.toJavaPoet import androidx.room.compiler.processing.XType import androidx.room.compiler.processing.XTypeElement import androidx.room.compiler.processing.util.Source import androidx.room.compiler.processing.util.XTestInvocation import androidx.room.compiler.processing.util.runProcessorTest import androidx.room.ext.CommonTypeNames import androidx.room.ext.CommonTypeNames.LIST import androidx.room.ext.GuavaUtilConcurrentTypeNames import androidx.room.ext.KotlinTypeNames import androidx.room.ext.LifecyclesTypeNames import androidx.room.ext.PagingTypeNames import androidx.room.ext.ReactiveStreamsTypeNames import androidx.room.ext.RxJava2TypeNames import androidx.room.ext.RxJava3TypeNames import androidx.room.ext.typeName import androidx.room.parser.QueryType import androidx.room.parser.Table import androidx.room.processor.ProcessorErrors.DO_NOT_USE_GENERIC_IMMUTABLE_MULTIMAP import androidx.room.processor.ProcessorErrors.MAP_INFO_MUST_HAVE_AT_LEAST_ONE_COLUMN_PROVIDED import androidx.room.processor.ProcessorErrors.cannotFindQueryResultAdapter import androidx.room.processor.ProcessorErrors.keyMayNeedMapInfo import androidx.room.processor.ProcessorErrors.valueMayNeedMapInfo import androidx.room.solver.query.result.DataSourceFactoryQueryResultBinder import androidx.room.solver.query.result.ListQueryResultAdapter import androidx.room.solver.query.result.LiveDataQueryResultBinder import androidx.room.solver.query.result.PojoRowAdapter import androidx.room.solver.query.result.SingleColumnRowAdapter import androidx.room.solver.query.result.SingleItemQueryResultAdapter import androidx.room.testing.context import androidx.room.vo.Field import androidx.room.vo.QueryMethod import androidx.room.vo.ReadQueryMethod import androidx.room.vo.Warning import androidx.room.vo.WriteQueryMethod import com.google.common.truth.Truth.assertThat import com.squareup.javapoet.ClassName import com.squareup.javapoet.ParameterizedTypeName import com.squareup.javapoet.TypeName import com.squareup.javapoet.TypeVariableName import createVerifierFromEntitiesAndViews import mockElementAndType import org.hamcrest.CoreMatchers.hasItem import org.hamcrest.CoreMatchers.instanceOf import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.not import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.MatcherAssert.assertThat import org.junit.Assert.assertEquals import org.junit.AssumptionViolatedException import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.mockito.Mockito @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") @RunWith(Parameterized::class) class QueryMethodProcessorTest(private val enableVerification: Boolean) { companion object { const val DAO_PREFIX = """ package foo.bar; import androidx.annotation.NonNull; import androidx.room.*; import java.util.*; import com.google.common.collect.*; @Dao abstract class MyClass { """ const val DAO_PREFIX_KT = """ package foo.bar import androidx.room.* import java.util.* import io.reactivex.* io.reactivex.rxjava3.core.* androidx.lifecycle.* com.google.common.util.concurrent.* org.reactivestreams.* kotlinx.coroutines.flow.* @Dao abstract class MyClass { """ const val DAO_SUFFIX = "}" val POJO = XClassName.get("foo.bar", "MyClass.Pojo") @Parameterized.Parameters(name = "enableDbVerification={0}") @JvmStatic fun getParams() = arrayOf(true, false) fun createField(name: String, columnName: String? = null): Field { val (element, type) = mockElementAndType() return Field( element = element, name = name, type = type, columnName = columnName ?: name, affinity = null ) } } @Test fun testReadNoParams() { singleQueryMethod<ReadQueryMethod>( """ @Query("SELECT * from User") abstract public int[] foo(); """ ) { parsedQuery, _ -> assertThat(parsedQuery.element.jvmName, `is`("foo")) assertThat(parsedQuery.parameters.size, `is`(0)) assertThat( parsedQuery.returnType.asTypeName(), `is`(XTypeName.getArrayName(XTypeName.PRIMITIVE_INT)) ) } } @Test fun testSingleParam() { singleQueryMethod<ReadQueryMethod>( """ @Query("SELECT * from User where uid = :x") abstract public long foo(int x); """ ) { parsedQuery, invocation -> assertThat(parsedQuery.element.jvmName, `is`("foo")) assertThat(parsedQuery.returnType.asTypeName(), `is`(XTypeName.PRIMITIVE_LONG)) assertThat(parsedQuery.parameters.size, `is`(1)) val param = parsedQuery.parameters.first() assertThat(param.name, `is`("x")) assertThat(param.sqlName, `is`("x")) assertThat( param.type, `is`(invocation.processingEnv.requireType(TypeName.INT)) ) } } @Test fun testVarArgs() { singleQueryMethod<ReadQueryMethod>( """ @Query("SELECT * from User where uid in (:ids)") abstract public long foo(int... ids); """ ) { parsedQuery, _ -> assertThat(parsedQuery.element.jvmName, `is`("foo")) assertThat(parsedQuery.returnType.asTypeName(), `is`(XTypeName.PRIMITIVE_LONG)) assertThat(parsedQuery.parameters.size, `is`(1)) val param = parsedQuery.parameters.first() assertThat(param.name, `is`("ids")) assertThat(param.sqlName, `is`("ids")) assertThat( param.type.asTypeName(), `is`(XTypeName.getArrayName(XTypeName.PRIMITIVE_INT)) ) } } @Test fun testParamBindingMatchingNoName() { singleQueryMethod<ReadQueryMethod>( """ @Query("SELECT uid from User where uid = :id") abstract public long getIdById(int id); """ ) { parsedQuery, _ -> val section = parsedQuery.query.bindSections.first() val param = parsedQuery.parameters.firstOrNull() assertThat(section, notNullValue()) assertThat(param, notNullValue()) assertThat(parsedQuery.sectionToParamMapping, `is`(listOf(Pair(section, param)))) } } @Test fun testParamBindingMatchingSimpleBind() { singleQueryMethod<ReadQueryMethod>( """ @Query("SELECT uid from User where uid = :id") abstract public long getIdById(int id); """ ) { parsedQuery, _ -> val section = parsedQuery.query.bindSections.first() val param = parsedQuery.parameters.firstOrNull() assertThat(section, notNullValue()) assertThat(param, notNullValue()) assertThat( parsedQuery.sectionToParamMapping, `is`(listOf(Pair(section, param))) ) } } @Test fun testParamBindingTwoBindVarsIntoTheSameParameter() { singleQueryMethod<ReadQueryMethod>( """ @Query("SELECT uid from User where uid = :id OR uid = :id") abstract public long getIdById(int id); """ ) { parsedQuery, _ -> val section = parsedQuery.query.bindSections[0] val section2 = parsedQuery.query.bindSections[1] val param = parsedQuery.parameters.firstOrNull() assertThat(section, notNullValue()) assertThat(section2, notNullValue()) assertThat(param, notNullValue()) assertThat( parsedQuery.sectionToParamMapping, `is`(listOf(Pair(section, param), Pair(section2, param))) ) } } @Test fun testMissingParameterForBinding() { singleQueryMethod<ReadQueryMethod>( """ @Query("SELECT uid from User where uid = :id OR uid = :uid") abstract public long getIdById(int id); """ ) { parsedQuery, invocation -> val section = parsedQuery.query.bindSections[0] val section2 = parsedQuery.query.bindSections[1] val param = parsedQuery.parameters.firstOrNull() assertThat(section, notNullValue()) assertThat(section2, notNullValue()) assertThat(param, notNullValue()) assertThat( parsedQuery.sectionToParamMapping, `is`(listOf(Pair(section, param), Pair(section2, null))) ) invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.missingParameterForBindVariable(listOf(":uid")) ) } } } @Test fun test2MissingParameterForBinding() { singleQueryMethod<ReadQueryMethod>( """ @Query("SELECT uid from User where name = :bar AND uid = :id OR uid = :uid") abstract public long getIdById(int id); """ ) { parsedQuery, invocation -> val bar = parsedQuery.query.bindSections[0] val id = parsedQuery.query.bindSections[1] val uid = parsedQuery.query.bindSections[2] val param = parsedQuery.parameters.firstOrNull() assertThat(bar, notNullValue()) assertThat(id, notNullValue()) assertThat(uid, notNullValue()) assertThat(param, notNullValue()) assertThat( parsedQuery.sectionToParamMapping, `is`(listOf(Pair(bar, null), Pair(id, param), Pair(uid, null))) ) invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.missingParameterForBindVariable(listOf(":bar", ":uid")) ) } } } @Test fun testUnusedParameters() { singleQueryMethod<ReadQueryMethod>( """ @Query("SELECT uid from User where name = :bar") abstract public long getIdById(int bar, int whyNotUseMe); """ ) { parsedQuery, invocation -> val bar = parsedQuery.query.bindSections[0] val barParam = parsedQuery.parameters.firstOrNull() assertThat(bar, notNullValue()) assertThat(barParam, notNullValue()) assertThat( parsedQuery.sectionToParamMapping, `is`(listOf(Pair(bar, barParam))) ) invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.unusedQueryMethodParameter(listOf("whyNotUseMe")) ) } } } @Test fun testNameWithUnderscore() { singleQueryMethod<ReadQueryMethod>( """ @Query("select * from User where uid = :_blah") abstract public long getSth(int _blah); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.QUERY_PARAMETERS_CANNOT_START_WITH_UNDERSCORE ) } } } @Test fun testGenericReturnType() { singleQueryMethod<ReadQueryMethod>( """ @Query("select * from User") abstract public <T> ${LIST.canonicalName}<T> foo(int x); """ ) { parsedQuery, invocation -> val expected: TypeName = ParameterizedTypeName.get( ClassName.get(List::class.java), TypeVariableName.get("T") ) assertThat(parsedQuery.returnType.typeName, `is`(expected)) invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.CANNOT_USE_UNBOUND_GENERICS_IN_QUERY_METHODS ) } } } @Test fun testBadQuery() { singleQueryMethod<ReadQueryMethod>( """ @Query("select * from :1 :2") abstract public long foo(int x); """ ) { _, invocation -> // do nothing invocation.assertCompilationResult { hasErrorContaining("UNEXPECTED_CHAR=:") } } } @Test fun testLiveDataWithWithClause() { singleQueryMethod<ReadQueryMethod>( """ @Query("WITH RECURSIVE tempTable(n, fact) AS (SELECT 0, 1 UNION ALL SELECT n+1," + " (n+1)*fact FROM tempTable WHERE n < 9) SELECT fact FROM tempTable, User") abstract public ${LifecyclesTypeNames.LIVE_DATA}<${LIST.toJavaPoet()}<Integer>> getFactorialLiveData(); """ ) { parsedQuery, _ -> assertThat(parsedQuery.query.tables, hasItem(Table("User", "User"))) assertThat( parsedQuery.query.tables, not(hasItem(Table("tempTable", "tempTable"))) ) assertThat(parsedQuery.query.tables.size, `is`(1)) } } @Test fun testLiveDataWithNothingToObserve() { singleQueryMethod<ReadQueryMethod>( """ @Query("SELECT 1") abstract public ${LifecyclesTypeNames.LIVE_DATA}<Integer> getOne(); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.OBSERVABLE_QUERY_NOTHING_TO_OBSERVE ) } } } @Test fun testLiveDataWithWithClauseAndNothingToObserve() { singleQueryMethod<ReadQueryMethod>( """ @Query("WITH RECURSIVE tempTable(n, fact) AS (SELECT 0, 1 UNION ALL SELECT n+1," + " (n+1)*fact FROM tempTable WHERE n < 9) SELECT fact FROM tempTable") abstract public ${LifecyclesTypeNames.LIVE_DATA}<${LIST.toJavaPoet()}<Integer>> getFactorialLiveData(); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.OBSERVABLE_QUERY_NOTHING_TO_OBSERVE ) } } } @Test fun testBoundGeneric() { singleQueryMethod<ReadQueryMethod>( """ static abstract class BaseModel<T> { @Query("select COUNT(*) from User") abstract public T getT(); } @Dao static abstract class ExtendingModel extends BaseModel<Integer> { } """ ) { parsedQuery, _ -> assertThat( parsedQuery.returnType.asTypeName(), `is`(XTypeName.BOXED_INT) ) } } @Test fun testBoundGenericParameter() { singleQueryMethod<ReadQueryMethod>( """ static abstract class BaseModel<T> { @Query("select COUNT(*) from User where :t") abstract public int getT(T t); } @Dao static abstract class ExtendingModel extends BaseModel<Integer> { } """ ) { parsedQuery, _ -> assertThat( parsedQuery.parameters.first().type.asTypeName(), `is`( XTypeName.BOXED_INT ) ) } } @Test fun testReadDeleteWithBadReturnType() { singleQueryMethod<WriteQueryMethod>( """ @Query("DELETE from User where uid = :id") abstract public float foo(int id); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors .cannotFindPreparedQueryResultAdapter("float", QueryType.DELETE) ) } } } @Test fun testSimpleDelete() { singleQueryMethod<WriteQueryMethod>( """ @Query("DELETE from User where uid = :id") abstract public int foo(int id); """ ) { parsedQuery, _ -> assertThat(parsedQuery.element.jvmName, `is`("foo")) assertThat(parsedQuery.parameters.size, `is`(1)) assertThat(parsedQuery.returnType.asTypeName(), `is`(XTypeName.PRIMITIVE_INT)) } } @Test fun testVoidDeleteQuery() { singleQueryMethod<WriteQueryMethod>( """ @Query("DELETE from User where uid = :id") abstract public void foo(int id); """ ) { parsedQuery, _ -> assertThat(parsedQuery.element.jvmName, `is`("foo")) assertThat(parsedQuery.parameters.size, `is`(1)) assertThat(parsedQuery.returnType.asTypeName(), `is`(XTypeName.UNIT_VOID)) } } @Test fun testVoidUpdateQuery() { singleQueryMethod<WriteQueryMethod>( """ @Query("update user set name = :name") abstract public void updateAllNames(String name); """ ) { parsedQuery, _ -> assertThat(parsedQuery.element.jvmName, `is`("updateAllNames")) assertThat(parsedQuery.parameters.size, `is`(1)) assertThat(parsedQuery.returnType.asTypeName(), `is`(XTypeName.UNIT_VOID)) assertThat( parsedQuery.parameters.first().type.asTypeName(), `is`(CommonTypeNames.STRING) ) } } @Test fun testVoidInsertQuery() { singleQueryMethod<WriteQueryMethod>( """ @Query("insert into user (name) values (:name)") abstract public void insertUsername(String name); """ ) { parsedQuery, _ -> assertThat(parsedQuery.element.jvmName, `is`("insertUsername")) assertThat(parsedQuery.parameters.size, `is`(1)) assertThat(parsedQuery.returnType.asTypeName(), `is`(XTypeName.UNIT_VOID)) assertThat( parsedQuery.parameters.first().type.asTypeName(), `is`(CommonTypeNames.STRING) ) } } @Test fun testLongInsertQuery() { singleQueryMethod<WriteQueryMethod>( """ @Query("insert into user (name) values (:name)") abstract public long insertUsername(String name); """ ) { parsedQuery, _ -> assertThat(parsedQuery.element.jvmName, `is`("insertUsername")) assertThat(parsedQuery.parameters.size, `is`(1)) assertThat(parsedQuery.returnType.asTypeName(), `is`(XTypeName.PRIMITIVE_LONG)) assertThat( parsedQuery.parameters.first().type.asTypeName(), `is`(CommonTypeNames.STRING) ) } } @Test fun testInsertQueryWithBadReturnType() { singleQueryMethod<WriteQueryMethod>( """ @Query("insert into user (name) values (:name)") abstract public int insert(String name); """ ) { parsedQuery, invocation -> assertThat(parsedQuery.returnType.asTypeName(), `is`(XTypeName.PRIMITIVE_INT)) invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors .cannotFindPreparedQueryResultAdapter("int", QueryType.INSERT) ) } } } @Test fun testLiveDataQuery() { singleQueryMethod<ReadQueryMethod>( """ @Query("select name from user where uid = :id") abstract ${LifecyclesTypeNames.LIVE_DATA}<String> nameLiveData(String id); """ ) { parsedQuery, _ -> assertThat( parsedQuery.returnType.typeName, `is`( ParameterizedTypeName.get( LifecyclesTypeNames.LIVE_DATA, String::class.typeName ) as TypeName ) ) assertThat( parsedQuery.queryResultBinder, instanceOf(LiveDataQueryResultBinder::class.java) ) } } @Test fun testBadReturnForDeleteQuery() { singleQueryMethod<WriteQueryMethod>( """ @Query("delete from user where uid = :id") abstract ${LifecyclesTypeNames.LIVE_DATA}<Integer> deleteLiveData(String id); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.cannotFindPreparedQueryResultAdapter( "androidx.lifecycle.LiveData<java.lang.Integer>", QueryType.DELETE ) ) } } } @Test fun testBadReturnForUpdateQuery() { singleQueryMethod<WriteQueryMethod>( """ @Query("update user set name = :name") abstract ${LifecyclesTypeNames.LIVE_DATA}<Integer> updateNameLiveData(String name); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.cannotFindPreparedQueryResultAdapter( "androidx.lifecycle.LiveData<java.lang.Integer>", QueryType.UPDATE ) ) } } } @Test fun testDataSourceFactoryQuery() { singleQueryMethod<ReadQueryMethod>( """ @Query("select name from user") abstract ${PagingTypeNames.DATA_SOURCE_FACTORY}<Integer, String> nameDataSourceFactory(); """ ) { parsedQuery, _ -> assertThat( parsedQuery.returnType.typeName, `is`( ParameterizedTypeName.get( PagingTypeNames.DATA_SOURCE_FACTORY, Integer::class.typeName, String::class.typeName ) as TypeName ) ) assertThat( parsedQuery.queryResultBinder, instanceOf(DataSourceFactoryQueryResultBinder::class.java) ) val tableNames = (parsedQuery.queryResultBinder as DataSourceFactoryQueryResultBinder) .positionalDataSourceQueryResultBinder.tableNames assertEquals(setOf("user"), tableNames) } } @Test fun testMultiTableDataSourceFactoryQuery() { singleQueryMethod<ReadQueryMethod>( """ @Query("select name from User u LEFT OUTER JOIN Book b ON u.uid == b.uid") abstract ${PagingTypeNames.DATA_SOURCE_FACTORY}<Integer, String> nameDataSourceFactory(); """ ) { parsedQuery, _ -> assertThat( parsedQuery.returnType.typeName, `is`( ParameterizedTypeName.get( PagingTypeNames.DATA_SOURCE_FACTORY, Integer::class.typeName, String::class.typeName ) as TypeName ) ) assertThat( parsedQuery.queryResultBinder, instanceOf(DataSourceFactoryQueryResultBinder::class.java) ) val tableNames = (parsedQuery.queryResultBinder as DataSourceFactoryQueryResultBinder) .positionalDataSourceQueryResultBinder.tableNames assertEquals(setOf("User", "Book"), tableNames) } } @Test fun testBadChannelReturnForQuery() { singleQueryMethod<QueryMethod>( """ @Query("select * from user") abstract ${KotlinTypeNames.CHANNEL}<User> getUsersChannel(); """, additionalSources = listOf(COMMON.CHANNEL) ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.invalidChannelType( KotlinTypeNames.CHANNEL.toString() ) ) } } } @Test fun testBadSendChannelReturnForQuery() { singleQueryMethod<QueryMethod>( """ @Query("select * from user") abstract ${KotlinTypeNames.SEND_CHANNEL}<User> getUsersChannel(); """, additionalSources = listOf(COMMON.SEND_CHANNEL) ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.invalidChannelType( KotlinTypeNames.SEND_CHANNEL.toString() ) ) } } } @Test fun testBadReceiveChannelReturnForQuery() { singleQueryMethod<QueryMethod>( """ @Query("select * from user") abstract ${KotlinTypeNames.RECEIVE_CHANNEL}<User> getUsersChannel(); """, additionalSources = listOf(COMMON.RECEIVE_CHANNEL) ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.invalidChannelType( KotlinTypeNames.RECEIVE_CHANNEL.toString() ) ) } } } @Test fun query_detectTransaction_select() { singleQueryMethod<ReadQueryMethod>( """ @Query("select * from user") abstract int loadUsers(); """ ) { method, _ -> assertThat(method.inTransaction, `is`(false)) } } @Test fun query_detectTransaction_selectInTransaction() { singleQueryMethod<ReadQueryMethod>( """ @Transaction @Query("select * from user") abstract int loadUsers(); """ ) { method, _ -> assertThat(method.inTransaction, `is`(true)) } } @Test fun skipVerification() { singleQueryMethod<ReadQueryMethod>( """ @SkipQueryVerification @Query("SELECT foo from User") abstract public int[] foo(); """ ) { parsedQuery, _ -> assertThat(parsedQuery.element.jvmName, `is`("foo")) assertThat(parsedQuery.parameters.size, `is`(0)) assertThat( parsedQuery.returnType.asTypeName(), `is`(XTypeName.getArrayName(XTypeName.PRIMITIVE_INT)) ) } } @Test fun skipVerificationPojo() { singleQueryMethod<ReadQueryMethod>( """ @SkipQueryVerification @Query("SELECT bookId, uid FROM User") abstract NotAnEntity getPojo(); """ ) { parsedQuery, _ -> assertThat(parsedQuery.element.jvmName, `is`("getPojo")) assertThat(parsedQuery.parameters.size, `is`(0)) assertThat( parsedQuery.returnType.asTypeName(), `is`(COMMON.NOT_AN_ENTITY_TYPE_NAME) ) val adapter = parsedQuery.queryResultBinder.adapter assertThat(checkNotNull(adapter)) assertThat(adapter::class, `is`(SingleItemQueryResultAdapter::class)) val rowAdapter = adapter.rowAdapters.single() assertThat(checkNotNull(rowAdapter)) assertThat(rowAdapter::class, `is`(PojoRowAdapter::class)) } } @Test fun suppressWarnings() { singleQueryMethod<ReadQueryMethod>( """ @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH) @Query("SELECT uid from User") abstract public int[] foo(); """ ) { method, invocation -> assertThat( QueryMethodProcessor( baseContext = invocation.context, containing = Mockito.mock(XType::class.java), executableElement = method.element, dbVerifier = null ).context.logger.suppressedWarnings, `is`(setOf(Warning.CURSOR_MISMATCH)) ) } } @Test fun relationWithExtendsBounds() { if (!enableVerification) { return } singleQueryMethod<ReadQueryMethod>( """ static class Merged extends User { @Relation(parentColumn = "name", entityColumn = "lastName", entity = User.class) java.util.List<? extends User> users; } @Transaction @Query("select * from user") abstract java.util.List<Merged> loadUsers(); """ ) { method, invocation -> assertThat( method.queryResultBinder.adapter, instanceOf(ListQueryResultAdapter::class.java) ) val listAdapter = method.queryResultBinder.adapter as ListQueryResultAdapter assertThat(listAdapter.rowAdapters.single(), instanceOf(PojoRowAdapter::class.java)) val pojoRowAdapter = listAdapter.rowAdapters.single() as PojoRowAdapter assertThat(pojoRowAdapter.relationCollectors.size, `is`(1)) assertThat( pojoRowAdapter.relationCollectors[0].relationTypeName, `is`( CommonTypeNames.ARRAY_LIST.parametrizedBy(COMMON.USER_TYPE_NAME) ) ) invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun pojo_renamedColumn() { pojoTest( """ String name; String lName; """, listOf("name", "lastName as lName") ) { adapter, _, invocation -> assertThat(adapter?.mapping?.unusedColumns, `is`(emptyList())) assertThat(adapter?.mapping?.unusedFields, `is`(emptyList())) invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun pojo_exactMatch() { pojoTest( """ String name; String lastName; """, listOf("name", "lastName") ) { adapter, _, invocation -> assertThat(adapter?.mapping?.unusedColumns, `is`(emptyList())) assertThat(adapter?.mapping?.unusedFields, `is`(emptyList())) invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun pojo_exactMatchWithStar() { pojoTest( """ String name; String lastName; int uid; @ColumnInfo(name = "ageColumn") int age; """, listOf("*") ) { adapter, _, invocation -> assertThat(adapter?.mapping?.unusedColumns, `is`(emptyList())) assertThat(adapter?.mapping?.unusedFields, `is`(emptyList())) invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun primitive_removeUnusedColumns() { if (!enableVerification) { throw AssumptionViolatedException("nothing to test w/o db verification") } singleQueryMethod<ReadQueryMethod>( """ @RewriteQueriesToDropUnusedColumns @Query("select 1 from user") abstract int getOne(); """ ) { method, invocation -> val adapter = method.queryResultBinder.adapter?.rowAdapters?.single() check(adapter is SingleColumnRowAdapter) assertThat(method.query.original) .isEqualTo("select 1 from user") invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun pojo_removeUnusedColumns() { if (!enableVerification) { throw AssumptionViolatedException("nothing to test w/o db verification") } singleQueryMethod<ReadQueryMethod>( """ public static class Pojo { public String name; public String lastName; } @RewriteQueriesToDropUnusedColumns @Query("select * from user LIMIT 1") abstract Pojo loadUsers(); """ ) { method, invocation -> val adapter = method.queryResultBinder.adapter?.rowAdapters?.single() check(adapter is PojoRowAdapter) assertThat(method.query.original) .isEqualTo("SELECT `name`, `lastName` FROM (select * from user LIMIT 1)") invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun pojo_multimapQuery_removeUnusedColumns() { if (!enableVerification) { throw AssumptionViolatedException("nothing to test w/o db verification") } val relatingEntity = Source.java( "foo.bar.Relation", """ package foo.bar; import androidx.room.*; @Entity public class Relation { @PrimaryKey long relationId; long userId; } """.trimIndent() ) singleQueryMethod<ReadQueryMethod>( """ public static class Username { public String name; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Username username = (Username) o; if (name != username.name) return false; return true; } @Override public int hashCode() { return name.hashCode(); } } @RewriteQueriesToDropUnusedColumns @Query("SELECT * FROM User JOIN Relation ON (User.uid = Relation.userId)") abstract Map<Username, List<Relation>> loadUserRelations(); """, additionalSources = listOf(relatingEntity) ) { method, invocation -> assertThat(method.query.original) .isEqualTo( "SELECT `name`, `relationId`, `userId` FROM " + "(SELECT * FROM User JOIN Relation ON (User.uid = Relation.userId))" ) invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun pojo_dontRemoveUnusedColumnsWhenColumnNamesConflict() { if (!enableVerification) { throw AssumptionViolatedException("nothing to test w/o db verification") } singleQueryMethod<ReadQueryMethod>( """ public static class Pojo { public String name; public String lastName; } @RewriteQueriesToDropUnusedColumns @Query("select * from user u, user u2 LIMIT 1") abstract Pojo loadUsers(); """ ) { method, invocation -> val adapter = method.queryResultBinder.adapter?.rowAdapters?.single() check(adapter is PojoRowAdapter) assertThat(method.query.original).isEqualTo("select * from user u, user u2 LIMIT 1") invocation.assertCompilationResult { hasWarningContaining("The query returns some columns [uid") } } } @Test fun pojo_nonJavaName() { pojoTest( """ @ColumnInfo(name = "MAX(ageColumn)") int maxAge; String name; """, listOf("MAX(ageColumn)", "name") ) { adapter, _, invocation -> assertThat(adapter?.mapping?.unusedColumns, `is`(emptyList())) assertThat(adapter?.mapping?.unusedFields, `is`(emptyList())) invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun pojo_noMatchingFields() { pojoTest( """ String nameX; String lastNameX; """, listOf("name", "lastName") ) { adapter, _, invocation -> assertThat(adapter?.mapping?.unusedColumns, `is`(listOf("name", "lastName"))) assertThat(adapter?.mapping?.unusedFields, `is`(adapter?.pojo?.fields as List<Field>)) invocation.assertCompilationResult { hasErrorContaining( cannotFindQueryResultAdapter( XClassName.get("foo.bar", "MyClass", "Pojo").canonicalName ) ) hasWarningContaining( ProcessorErrors.cursorPojoMismatch( pojoTypeNames = listOf(POJO.canonicalName), unusedColumns = listOf("name", "lastName"), pojoUnusedFields = mapOf( POJO.canonicalName to listOf( createField("nameX"), createField("lastNameX") ) ), allColumns = listOf("name", "lastName"), ) ) } } } @Test fun pojo_badQuery() { // do not report mismatch if query is broken pojoTest( """ @ColumnInfo(name = "MAX(ageColumn)") int maxAge; String name; """, listOf("MAX(age)", "name") ) { _, _, invocation -> invocation.assertCompilationResult { hasErrorContaining("no such column: age") hasErrorContaining( cannotFindQueryResultAdapter( XClassName.get("foo.bar", "MyClass", "Pojo").canonicalName ) ) hasErrorCount(2) hasNoWarnings() } } } @Test fun pojo_tooManyColumns() { pojoTest( """ String name; String lastName; """, listOf("uid", "name", "lastName") ) { adapter, _, invocation -> assertThat(adapter?.mapping?.unusedColumns, `is`(listOf("uid"))) assertThat(adapter?.mapping?.unusedFields, `is`(emptyList())) invocation.assertCompilationResult { hasWarningContaining( ProcessorErrors.cursorPojoMismatch( pojoTypeNames = listOf(POJO.canonicalName), unusedColumns = listOf("uid"), pojoUnusedFields = emptyMap(), allColumns = listOf("uid", "name", "lastName"), ) ) } } } @Test fun pojo_tooManyFields() { pojoTest( """ String name; String lastName; """, listOf("lastName") ) { adapter, _, invocation -> assertThat(adapter?.mapping?.unusedColumns, `is`(emptyList())) assertThat( adapter?.mapping?.unusedFields, `is`( adapter?.pojo?.fields?.filter { it.name == "name" } ) ) invocation.assertCompilationResult { hasWarningContaining( ProcessorErrors.cursorPojoMismatch( pojoTypeNames = listOf(POJO.canonicalName), unusedColumns = emptyList(), allColumns = listOf("lastName"), pojoUnusedFields = mapOf(POJO.canonicalName to listOf(createField("name"))), ) ) } } } @Test fun pojo_missingNonNull() { pojoTest( """ @NonNull String name; String lastName; """, listOf("lastName") ) { adapter, _, invocation -> assertThat(adapter?.mapping?.unusedColumns, `is`(emptyList())) assertThat( adapter?.mapping?.unusedFields, `is`( adapter?.pojo?.fields?.filter { it.name == "name" } ) ) invocation.assertCompilationResult { hasWarningContaining( ProcessorErrors.cursorPojoMismatch( pojoTypeNames = listOf(POJO.canonicalName), unusedColumns = emptyList(), pojoUnusedFields = mapOf(POJO.canonicalName to listOf(createField("name"))), allColumns = listOf("lastName"), ) ) hasErrorContaining( ProcessorErrors.pojoMissingNonNull( pojoTypeName = POJO.canonicalName, missingPojoFields = listOf("name"), allQueryColumns = listOf("lastName") ) ) } } } @Test fun pojo_tooManyFieldsAndColumns() { pojoTest( """ String name; String lastName; """, listOf("uid", "name") ) { adapter, _, invocation -> assertThat(adapter?.mapping?.unusedColumns, `is`(listOf("uid"))) assertThat( adapter?.mapping?.unusedFields, `is`( adapter?.pojo?.fields?.filter { it.name == "lastName" } ) ) invocation.assertCompilationResult { hasWarningContaining( ProcessorErrors.cursorPojoMismatch( pojoTypeNames = listOf(POJO.canonicalName), unusedColumns = listOf("uid"), allColumns = listOf("uid", "name"), pojoUnusedFields = mapOf( POJO.canonicalName to listOf(createField("lastName")) ) ) ) } } } @Test fun pojo_expandProjection() { if (!enableVerification) return pojoTest( """ String uid; String name; """, listOf("*"), options = mapOf("room.expandProjection" to "true") ) { adapter, _, invocation -> adapter!! assertThat(adapter.mapping.unusedColumns).isEmpty() assertThat(adapter.mapping.unusedFields).isEmpty() invocation.assertCompilationResult { hasNoWarnings() } } } private fun pojoTest( pojoFields: String, queryColumns: List<String>, options: Map<String, String> = emptyMap(), handler: (PojoRowAdapter?, QueryMethod, XTestInvocation) -> Unit ) { singleQueryMethod<ReadQueryMethod>( """ static class Pojo { $pojoFields } @Query("SELECT ${queryColumns.joinToString(", ")} from User LIMIT 1") abstract MyClass.Pojo getNameAndLastNames(); """, options = options ) { parsedQuery, invocation -> val adapter = parsedQuery.queryResultBinder.adapter if (enableVerification) { if (adapter is SingleItemQueryResultAdapter) { handler( adapter.rowAdapters.single() as? PojoRowAdapter, parsedQuery, invocation ) } else { handler(null, parsedQuery, invocation) } } else { assertThat(adapter, notNullValue()) } } } private fun <T : QueryMethod> singleQueryMethod( vararg input: String, additionalSources: Iterable<Source> = emptyList(), options: Map<String, String> = emptyMap(), handler: (T, XTestInvocation) -> Unit ) { val inputSource = Source.java( "foo.bar.MyClass", DAO_PREFIX + input.joinToString("\n") + DAO_SUFFIX ) val commonSources = listOf( COMMON.LIVE_DATA, COMMON.COMPUTABLE_LIVE_DATA, COMMON.USER, COMMON.BOOK, COMMON.NOT_AN_ENTITY, COMMON.ARTIST, COMMON.SONG, COMMON.IMAGE, COMMON.IMAGE_FORMAT, COMMON.CONVERTER ) runProcessorTest( sources = additionalSources + commonSources + inputSource, options = options ) { invocation -> val (owner, methods) = invocation.roundEnv .getElementsAnnotatedWith(Dao::class.qualifiedName!!) .filterIsInstance<XTypeElement>() .map { typeElement -> Pair( typeElement, typeElement.getAllMethods().filter { method -> method.hasAnnotation(Query::class) }.toList() ) }.first { it.second.isNotEmpty() } val verifier = if (enableVerification) { createVerifierFromEntitiesAndViews(invocation).also( invocation.context::attachDatabaseVerifier ) } else { null } val parser = QueryMethodProcessor( baseContext = invocation.context, containing = owner.type, executableElement = methods.first(), dbVerifier = verifier ) val parsedQuery = parser.process() @Suppress("UNCHECKED_CAST") handler(parsedQuery as T, invocation) } } private fun <T : QueryMethod> singleQueryMethodKotlin( vararg input: String, additionalSources: Iterable<Source> = emptyList(), options: Map<String, String> = emptyMap(), handler: (T, XTestInvocation) -> Unit ) { val inputSource = Source.kotlin( "MyClass.kt", DAO_PREFIX_KT + input.joinToString("\n") + DAO_SUFFIX ) val commonSources = listOf( COMMON.USER, COMMON.BOOK, COMMON.NOT_AN_ENTITY, COMMON.RX2_COMPLETABLE, COMMON.RX2_MAYBE, COMMON.RX2_SINGLE, COMMON.RX2_FLOWABLE, COMMON.RX2_OBSERVABLE, COMMON.RX3_COMPLETABLE, COMMON.RX3_MAYBE, COMMON.RX3_SINGLE, COMMON.RX3_FLOWABLE, COMMON.RX3_OBSERVABLE, COMMON.LISTENABLE_FUTURE, COMMON.LIVE_DATA, COMMON.COMPUTABLE_LIVE_DATA, COMMON.PUBLISHER, COMMON.FLOW, COMMON.GUAVA_ROOM ) runProcessorTest( sources = additionalSources + commonSources + inputSource, options = options ) { invocation -> val (owner, methods) = invocation.roundEnv .getElementsAnnotatedWith(Dao::class.qualifiedName!!) .filterIsInstance<XTypeElement>() .map { typeElement -> Pair( typeElement, typeElement.getAllMethods().filter { method -> method.hasAnnotation(Query::class) }.toList() ) }.first { it.second.isNotEmpty() } val verifier = if (enableVerification) { createVerifierFromEntitiesAndViews(invocation).also( invocation.context::attachDatabaseVerifier ) } else { null } val parser = QueryMethodProcessor( baseContext = invocation.context, containing = owner.type, executableElement = methods.first(), dbVerifier = verifier ) val parsedQuery = parser.process() @Suppress("UNCHECKED_CAST") handler(parsedQuery as T, invocation) } } @Test fun testInvalidLinkedListCollectionInMultimapJoin() { singleQueryMethod<ReadQueryMethod>( """ @Query("select * from User u JOIN Book b ON u.uid == b.uid") abstract Map<User, LinkedList<Book>> getInvalidCollectionMultimap(); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorCount(2) hasErrorContaining("Multimap 'value' collection type must be a List or Set.") hasErrorContaining("Not sure how to convert a Cursor to this method's return type") } } } @Test fun testInvalidGenericMultimapJoin() { singleQueryMethod<ReadQueryMethod>( """ @Query("select * from User u JOIN Book b ON u.uid == b.uid") abstract com.google.common.collect.ImmutableMultimap<User, Book> getInvalidCollectionMultimap(); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorCount(2) hasErrorContaining(DO_NOT_USE_GENERIC_IMMUTABLE_MULTIMAP) hasErrorContaining("Not sure how to convert a Cursor to this method's return type") } } } @Test fun testUseMapInfoWithBothEmptyColumnsProvided() { if (!enableVerification) { return } singleQueryMethod<ReadQueryMethod>( """ @MapInfo @Query("select * from User u JOIN Book b ON u.uid == b.uid") abstract Map<User, Book> getMultimap(); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorCount(1) hasErrorContaining(MAP_INFO_MUST_HAVE_AT_LEAST_ONE_COLUMN_PROVIDED) } } } @Test fun testUseMapInfoWithTableAndColumnName() { if (!enableVerification) { return } singleQueryMethod<ReadQueryMethod>( """ @SuppressWarnings( {RoomWarnings.CURSOR_MISMATCH, RoomWarnings.AMBIGUOUS_COLUMN_IN_RESULT} ) @MapInfo(keyColumn = "uid", keyTable = "u") @Query("SELECT * FROM User u JOIN Book b ON u.uid == b.uid") abstract Map<Integer, Book> getMultimap(); """ ) { _, invocation -> invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun testUseMapInfoWithOriginalTableAndColumnName() { if (!enableVerification) { return } singleQueryMethod<ReadQueryMethod>( """ @SuppressWarnings( {RoomWarnings.CURSOR_MISMATCH, RoomWarnings.AMBIGUOUS_COLUMN_IN_RESULT} ) @MapInfo(keyColumn = "uid", keyTable = "User") @Query("SELECT * FROM User u JOIN Book b ON u.uid == b.uid") abstract Map<Integer, Book> getMultimap(); """ ) { _, invocation -> invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun testUseMapInfoWithColumnAlias() { if (!enableVerification) { return } singleQueryMethod<ReadQueryMethod>( """ @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH) @MapInfo(keyColumn = "name", valueColumn = "bookCount") @Query("SELECT name, (SELECT count(*) FROM User u JOIN Book b ON u.uid == b.uid) " + "AS bookCount FROM User") abstract Map<String, Integer> getMultimap(); """ ) { _, invocation -> invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun testDoesNotImplementEqualsAndHashcodeQuery() { singleQueryMethod<ReadQueryMethod>( """ @Query("select * from User u JOIN Book b ON u.uid == b.uid") abstract Map<User, Book> getMultimap(); """ ) { _, invocation -> invocation.assertCompilationResult { hasWarningCount(1) hasWarningContaining( ProcessorErrors.classMustImplementEqualsAndHashCode( "foo.bar.User" ) ) } } } @Test fun testMissingMapInfoOneToOneString() { singleQueryMethod<ReadQueryMethod>( """ @Query("select * from Artist JOIN Song ON Artist.mArtistName == Song.mArtist") abstract Map<Artist, String> getAllArtistsWithAlbumCoverYear(); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( valueMayNeedMapInfo(String::class.asClassName().canonicalName) ) } } } @Test fun testOneToOneStringMapInfoForKeyInsteadOfColumn() { singleQueryMethod<ReadQueryMethod>( """ @MapInfo(keyColumn = "mArtistName") @Query("select * from Artist JOIN Song ON Artist.mArtistName == Song.mArtist") abstract Map<Artist, String> getAllArtistsWithAlbumCoverYear(); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( valueMayNeedMapInfo(String::class.asClassName().canonicalName) ) } } } @Test fun testMissingMapInfoOneToManyString() { singleQueryMethod<ReadQueryMethod>( """ @Query("select * from Artist JOIN Song ON Artist.mArtistName == Song.mArtist") abstract Map<Artist, List<String>> getAllArtistsWithAlbumCoverYear(); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( valueMayNeedMapInfo(String::class.asClassName().canonicalName) ) } } } @Test fun testMissingMapInfoImmutableListMultimapOneToOneString() { singleQueryMethod<ReadQueryMethod>( """ @Query("select * from Artist JOIN Song ON Artist.mArtistName == Song.mArtist") abstract ImmutableListMultimap<Artist, String> getAllArtistsWithAlbumCoverYear(); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( valueMayNeedMapInfo(String::class.asClassName().canonicalName) ) } } } @Test fun testMissingMapInfoOneToOneLong() { singleQueryMethod<ReadQueryMethod>( """ @Query("SELECT * FROM Artist JOIN Image ON Artist.mArtistName = Image.mArtistInImage") Map<Artist, Long> getAllArtistsWithAlbumCoverYear(); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( valueMayNeedMapInfo(XTypeName.BOXED_LONG.canonicalName) ) } } } @Test fun testMissingMapInfoOneToManyLong() { singleQueryMethod<ReadQueryMethod>( """ @Query("SELECT * FROM Artist JOIN Image ON Artist.mArtistName = Image.mArtistInImage") Map<Artist, Set<Long>> getAllArtistsWithAlbumCoverYear(); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( valueMayNeedMapInfo(XTypeName.BOXED_LONG.canonicalName) ) } } } @Test fun testMissingMapInfoImmutableListMultimapOneToOneLong() { singleQueryMethod<ReadQueryMethod>( """ @Query("SELECT * FROM Artist JOIN Image ON Artist.mArtistName = Image.mArtistInImage") ImmutableListMultimap<Artist, Long> getAllArtistsWithAlbumCoverYear(); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( valueMayNeedMapInfo(XTypeName.BOXED_LONG.canonicalName) ) } } } @Test fun testMissingMapInfoImmutableListMultimapOneToOneTypeConverterKey() { singleQueryMethod<ReadQueryMethod>( """ @TypeConverters(DateConverter.class) @Query("SELECT * FROM Image JOIN Artist ON Artist.mArtistName = Image.mArtistInImage") ImmutableMap<java.util.Date, Artist> getAlbumDateWithBandActivity(); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( keyMayNeedMapInfo("java.util.Date") ) } } } @Test fun testMissingMapInfoImmutableListMultimapOneToOneTypeConverterValue() { singleQueryMethod<ReadQueryMethod>( """ @TypeConverters(DateConverter.class) @Query("SELECT * FROM Artist JOIN Image ON Artist.mArtistName = Image.mArtistInImage") ImmutableMap<Artist, java.util.Date> getAlbumDateWithBandActivity(); """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( valueMayNeedMapInfo("java.util.Date") ) } } } @Test fun testUseMapInfoWithColumnsNotInQuery() { if (!enableVerification) { return } singleQueryMethod<ReadQueryMethod>( """ @MapInfo(keyColumn="cat", valueColumn="dog") @Query("select * from User u JOIN Book b ON u.uid == b.uid") abstract Map<User, Book> getMultimap(); """ ) { _, invocation -> invocation.assertCompilationResult { hasWarningCount(1) hasWarningContaining( ProcessorErrors.classMustImplementEqualsAndHashCode( "foo.bar.User" ) ) hasErrorCount(2) hasErrorContaining( "Column specified in the provided @MapInfo annotation must " + "be present in the query. Provided: cat." ) hasErrorContaining( "Column specified in the provided @MapInfo annotation must " + "be present in the query. Provided: dog." ) } } } @Test fun testAmbiguousColumnInMapInfo() { if (!enableVerification) { // No warning without verification, avoiding false positives return } singleQueryMethod<ReadQueryMethod>( """ @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH) @MapInfo(keyColumn = "uid") @Query("SELECT * FROM User u JOIN Book b ON u.uid == b.uid") abstract Map<Integer, Book> getMultimap(); """ ) { _, invocation -> invocation.assertCompilationResult { hasWarning( ProcessorErrors.ambiguousColumn( "uid", ProcessorErrors.AmbiguousColumnLocation.MAP_INFO, null ) ) } } } @Test fun testAmbiguousColumnInMapPojo() { if (!enableVerification) { // No warning without verification, avoiding false positives return } val extraPojo = Source.java( "foo.bar.Id", """ package foo.bar; public class Id { public int uid; @Override public boolean equals(Object o) { return true; } @Override public int hashCode() { return 0; } } """.trimIndent() ) singleQueryMethod<ReadQueryMethod>( """ @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH) @Query("SELECT * FROM User u JOIN Book b ON u.uid == b.uid") abstract Map<Id, Book> getMultimap(); """, additionalSources = listOf(extraPojo) ) { _, invocation -> invocation.assertCompilationResult { hasWarning( ProcessorErrors.ambiguousColumn( "uid", ProcessorErrors.AmbiguousColumnLocation.POJO, "foo.bar.Id" ) ) } } } @Test fun suspendReturnsDeferredType() { listOf( "${RxJava2TypeNames.FLOWABLE}<Int>", "${RxJava2TypeNames.OBSERVABLE}<Int>", "${RxJava2TypeNames.MAYBE}<Int>", "${RxJava2TypeNames.SINGLE}<Int>", "${RxJava2TypeNames.COMPLETABLE}", "${RxJava3TypeNames.FLOWABLE}<Int>", "${RxJava3TypeNames.OBSERVABLE}<Int>", "${RxJava3TypeNames.MAYBE}<Int>", "${RxJava3TypeNames.SINGLE}<Int>", "${RxJava3TypeNames.COMPLETABLE}", "${LifecyclesTypeNames.LIVE_DATA}<Int>", "${LifecyclesTypeNames.COMPUTABLE_LIVE_DATA}<Int>", "${GuavaUtilConcurrentTypeNames.LISTENABLE_FUTURE}<Int>", "${ReactiveStreamsTypeNames.PUBLISHER}<Int>", "${KotlinTypeNames.FLOW}<Int>" ).forEach { type -> singleQueryMethodKotlin<WriteQueryMethod>( """ @Query("DELETE from User where uid = :id") abstract suspend fun foo(id: Int): $type """ ) { _, invocation -> invocation.assertCompilationResult { val rawTypeName = type.substringBefore("<") hasErrorContaining(ProcessorErrors.suspendReturnsDeferredType(rawTypeName)) } } } } }
apache-2.0
d5d1012d0a4cfd5681c0c1c6d72ac125
34.769273
102
0.524579
5.860611
false
true
false
false
pyamsoft/padlock
padlock/src/main/java/com/pyamsoft/padlock/pin/text/TextPinView.kt
1
7245
/* * Copyright 2019 Peter Kenji Yamanaka * * 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.pyamsoft.padlock.pin.text import android.os.Bundle import android.view.KeyEvent import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.widget.EditText import android.widget.ImageView import android.widget.ScrollView import android.widget.TextView import androidx.annotation.CheckResult import androidx.core.content.ContextCompat import androidx.core.view.isGone import androidx.core.view.isVisible import androidx.lifecycle.LifecycleOwner import com.google.android.material.textfield.TextInputLayout import com.pyamsoft.padlock.R import com.pyamsoft.padlock.pin.BasePinView import com.pyamsoft.pydroid.loader.ImageLoader import com.pyamsoft.pydroid.loader.Loaded import com.pyamsoft.pydroid.ui.util.setOnDebouncedClickListener import com.pyamsoft.pydroid.util.tintWith import timber.log.Timber internal abstract class TextPinView<C : Any> protected constructor( private val imageLoader: ImageLoader, owner: LifecycleOwner, parent: ViewGroup, callback: C, isConfirmMode: Boolean ) : BasePinView<C>(owner, parent, callback, isConfirmMode) { private val attemptLayout by lazyView<TextInputLayout>(R.id.pin_text_attempt) private val reConfirmAttemptLayout by lazyView<TextInputLayout>(R.id.pin_text_reconfirm_attempt) private val optionalHintLayout by lazyView<TextInputLayout>(R.id.pin_text_optional_hint) private val confirmButton by lazyView<ImageView>(R.id.pin_text_confirm) private val showHint by lazyView<TextView>(R.id.pin_text_show_hint) private var confirmLoaded: Loaded? = null override val layoutRoot by lazyView<ScrollView>(R.id.pin_text_root) override val layout: Int = R.layout.layout_pin_text override val snackbarRoot: View get() = layoutRoot override fun onInflated( view: View, savedInstanceState: Bundle? ) { super.onInflated(view, savedInstanceState) showViews() bindIcons() bindClicks() restoreState(savedInstanceState) requireEditText(attemptLayout).requestFocus() } private fun bindIcons() { confirmLoaded?.dispose() confirmLoaded = imageLoader.load(R.drawable.ic_check_24dp) .mutate { it.tintWith(ContextCompat.getColor(confirmButton.context, R.color.orange500)) } .into(confirmButton) } @CheckResult private fun requireEditText(layout: TextInputLayout): EditText { return requireNotNull(layout.editText) } override fun clearDisplay() { requireEditText(attemptLayout).setText("") requireEditText(reConfirmAttemptLayout).setText("") requireEditText(optionalHintLayout).setText("") } override fun onSaveState(outState: Bundle) { outState.putString(CODE_DISPLAY, getAttempt()) outState.putString(CODE_REENTRY_DISPLAY, getReConfirmAttempt()) outState.putString(HINT_DISPLAY, getOptionalHint()) } private fun restoreState(state: Bundle?) { if (state == null) { return } val attempt = requireNotNull(state.getString( CODE_DISPLAY, "")) val reEntry = requireNotNull(state.getString( CODE_REENTRY_DISPLAY, "")) val hint = requireNotNull(state.getString( HINT_DISPLAY, "")) if (attempt.isBlank() && reEntry.isBlank() && hint.isBlank()) { clearDisplay() } else { requireEditText(attemptLayout).setText(attempt) requireEditText(reConfirmAttemptLayout).setText(reEntry) requireEditText(optionalHintLayout).setText(hint) } } override fun onTeardown() { confirmLoaded?.dispose() confirmLoaded = null confirmButton.setOnDebouncedClickListener(null) requireEditText(attemptLayout).setOnEditorActionListener(null) requireEditText(reConfirmAttemptLayout).setOnEditorActionListener(null) requireEditText(optionalHintLayout).setOnEditorActionListener(null) } private fun bindClicks() { confirmButton.setOnDebouncedClickListener { submit() } requireEditText(attemptLayout).also { editView -> setupSubmissionView(editView) { if (reConfirmAttemptLayout.isVisible) { reConfirmAttemptLayout.requestFocus() } else { submit() } } } requireEditText(reConfirmAttemptLayout).also { editView -> setupSubmissionView(editView) { if (optionalHintLayout.isVisible) { optionalHintLayout.requestFocus() } else { submit() } } } requireEditText(optionalHintLayout).also { editView -> setupSubmissionView(editView) { submit() } } } final override fun getAttempt(): String { return requireEditText(attemptLayout).text.toString() } final override fun getReConfirmAttempt(): String { return requireEditText(reConfirmAttemptLayout).text.toString() } final override fun getOptionalHint(): String { return requireEditText(optionalHintLayout).text.toString() } private fun showViews() { if (isConfirmMode) { attemptLayout.isVisible = true showHint.isVisible = true confirmButton.isVisible = true reConfirmAttemptLayout.isGone = true optionalHintLayout.isGone = true } else { attemptLayout.isVisible = true reConfirmAttemptLayout.isVisible = true optionalHintLayout.isVisible = true showHint.isGone = true confirmButton.isGone = true } } private inline fun setupSubmissionView( view: EditText, crossinline onEnter: () -> Unit ) { view.setOnEditorActionListener { _, actionId, keyEvent -> if (keyEvent == null) { Timber.e("KeyEvent was not caused by keypress") return@setOnEditorActionListener false } if (keyEvent.action == KeyEvent.ACTION_DOWN && actionId == EditorInfo.IME_NULL) { Timber.d("KeyEvent is Enter pressed") onEnter() return@setOnEditorActionListener true } Timber.d("Do not handle key event") return@setOnEditorActionListener false } } private fun setEnabled(enable: Boolean) { attemptLayout.isEnabled = enable reConfirmAttemptLayout.isEnabled = enable optionalHintLayout.isEnabled = enable confirmButton.isEnabled = enable showHint.isEnabled = enable } override fun enable() { setEnabled(true) } override fun disable() { setEnabled(false) } protected fun setHintText(hint: String) { if (isConfirmMode) { showHint.text = hint } else { showHint.text = "" } } companion object { private const val CODE_DISPLAY = "CODE_DISPLAY" private const val CODE_REENTRY_DISPLAY = "CODE_REENTRY_DISPLAY" private const val HINT_DISPLAY = "HINT_DISPLAY" } }
apache-2.0
f68a3ac5c2d408908d8bc1eb5287ea8a
28.814815
98
0.719531
4.650193
false
false
false
false
tbaxter120/Restdroid
app/src/main/java/com/ridocula/restdroid/models/viewholders/RequestViewHolder.kt
1
740
package com.ridocula.restdroid.models.viewholders import android.view.View import android.widget.TextView import com.ridocula.restdroid.R import com.ridocula.restdroid.models.Request import com.thoughtbot.expandablerecyclerview.viewholders.ChildViewHolder /** * Created by tbaxter on 7/20/17. */ class RequestViewHolder(itemView: View) : ChildViewHolder(itemView) { var tvUrl: TextView? = null var tvType: TextView? = null init { tvUrl = itemView.findViewById<TextView>(R.id.tvUrl) as TextView tvType = itemView.findViewById<TextView>(R.id.tvType) as TextView } fun onBind(request: Request) { tvUrl?.text = request.url tvType?.text = request.type.toString().toUpperCase() } }
apache-2.0
2a395987246e08e6ccffe300c7dbdda9
25.464286
73
0.724324
3.874346
false
false
false
false
AndroidX/androidx
compose/foundation/foundation/src/androidMain/kotlin/androidx/compose/foundation/PlatformMagnifier.kt
3
6161
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation import android.os.Build import android.view.View import android.widget.Magnifier import androidx.annotation.RequiresApi import androidx.compose.runtime.Stable import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.isSpecified import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntSize import kotlin.math.roundToInt @Stable internal interface PlatformMagnifierFactory { /** * If true, passing a different zoom level to [PlatformMagnifier.update] on the * [PlatformMagnifier] returned from [create] will actually update the magnifier. * If false, a new [PlatformMagnifier] must be created to use a different zoom level. */ val canUpdateZoom: Boolean @OptIn(ExperimentalFoundationApi::class) fun create( style: MagnifierStyle, view: View, density: Density, initialZoom: Float ): PlatformMagnifier companion object { @Stable fun getForCurrentPlatform(): PlatformMagnifierFactory = when { !isPlatformMagnifierSupported() -> { throw UnsupportedOperationException( "Magnifier is only supported on API level 28 and higher." ) } Build.VERSION.SDK_INT == 28 -> PlatformMagnifierFactoryApi28Impl else -> PlatformMagnifierFactoryApi29Impl } } } /** * Abstraction around the framework [Magnifier] class, for testing. */ internal interface PlatformMagnifier { /** Returns the actual size of the magnifier widget, even if not specified at creation. */ val size: IntSize /** Causes the magnifier to re-copy the magnified pixels. Wraps [Magnifier.update]. */ fun updateContent() /** * Sets the properties on a [Magnifier] instance that can be updated without recreating the * magnifier (e.g. [Magnifier.setZoom]) and [shows][Magnifier.show] it. */ fun update( sourceCenter: Offset, magnifierCenter: Offset, zoom: Float ) /** Wraps [Magnifier.dismiss]. */ fun dismiss() } @RequiresApi(28) internal object PlatformMagnifierFactoryApi28Impl : PlatformMagnifierFactory { override val canUpdateZoom: Boolean = false @Suppress("DEPRECATION") @OptIn(ExperimentalFoundationApi::class) override fun create( style: MagnifierStyle, view: View, density: Density, initialZoom: Float ): PlatformMagnifierImpl = PlatformMagnifierImpl(Magnifier(view)) @RequiresApi(28) open class PlatformMagnifierImpl(val magnifier: Magnifier) : PlatformMagnifier { override val size: IntSize get() = IntSize(magnifier.width, magnifier.height) override fun updateContent() { magnifier.update() } override fun update( sourceCenter: Offset, magnifierCenter: Offset, zoom: Float ) { magnifier.show(sourceCenter.x, sourceCenter.y) } override fun dismiss() { magnifier.dismiss() } } } @RequiresApi(29) internal object PlatformMagnifierFactoryApi29Impl : PlatformMagnifierFactory { override val canUpdateZoom: Boolean = true @OptIn(ExperimentalFoundationApi::class) override fun create( style: MagnifierStyle, view: View, density: Density, initialZoom: Float ): PlatformMagnifierImpl { with(density) { // TODO write test for this branch if (style == MagnifierStyle.TextDefault) { // This deprecated constructor is the only public API to create a Magnifier that // uses the system text magnifier defaults. @Suppress("DEPRECATION") return PlatformMagnifierImpl(Magnifier(view)) } val size = style.size.toSize() val cornerRadius = style.cornerRadius.toPx() val elevation = style.elevation.toPx() // When Builder properties are not specified, the widget uses different defaults than it // does for the non-builder constructor above. val magnifier = Magnifier.Builder(view).run { if (size.isSpecified) setSize(size.width.roundToInt(), size.height.roundToInt()) if (!cornerRadius.isNaN()) setCornerRadius(cornerRadius) if (!elevation.isNaN()) setElevation(elevation) if (!initialZoom.isNaN()) setInitialZoom(initialZoom) setClippingEnabled(style.clippingEnabled) // TODO(b/202451044) Support setting fisheye style. build() } return PlatformMagnifierImpl(magnifier) } } @RequiresApi(29) class PlatformMagnifierImpl(magnifier: Magnifier) : PlatformMagnifierFactoryApi28Impl.PlatformMagnifierImpl(magnifier) { override fun update(sourceCenter: Offset, magnifierCenter: Offset, zoom: Float) { if (!zoom.isNaN()) magnifier.zoom = zoom if (magnifierCenter.isSpecified) { magnifier.show( sourceCenter.x, sourceCenter.y, magnifierCenter.x, magnifierCenter.y ) } else { // This overload places the magnifier at a default offset relative to the source. magnifier.show(sourceCenter.x, sourceCenter.y) } } } }
apache-2.0
f096209c28f63ad0c947a5805d112fd9
32.666667
100
0.643727
5.155649
false
false
false
false
yamamotoj/Subskription
example/src/main/kotlin/com/github/yamamotoj/subskription/example/MainPresenter.kt
1
1458
package com.github.yamamotoj.subskription.example import android.content.Context import android.view.View import android.widget.TextView import android.widget.Toast import com.github.yamamotoj.subskription.AutoUnsubscribable import com.github.yamamotoj.subskription.AutoUnsubscribableDelegate import rx.Observable import rx.android.schedulers.AndroidSchedulers import java.util.concurrent.TimeUnit class MainPresenter(val context: Context, val view: View) : AutoUnsubscribable by AutoUnsubscribableDelegate() { val emitter = Observable.interval(1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()) val textView1 = view.findViewById(R.id.textView1) as TextView val textView2 = view.findViewById(R.id.textView2) as TextView init { emitter.autoUnsubscribe().subscribe { textView1.text = it.toString() } emitter.autoUnsubscribe().subscribe { textView2.text = it.toString() } textView1.setOnClickListener { Observable.timer(3, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .autoUnsubscribe("onPause") .doOnSubscribe { textView2.visibility = View.VISIBLE } .doOnUnsubscribe { textView2.visibility = View.INVISIBLE Toast.makeText(context, "unsubscribed", Toast.LENGTH_SHORT).show() } .subscribe() } } }
mit
ea7e6d9d6f89218dec7cb3fad4d73316
40.657143
112
0.687243
4.542056
false
false
false
false
petropavel13/2photo-android
TwoPhoto/app/src/main/java/com/github/petropavel13/twophoto/network/PostsFilters.kt
1
1629
package com.github.petropavel13.twophoto.network import android.os.Bundle /** * Created by petropavel on 17/04/15. */ public class PostsFilters { val artistId: Int? val authorId: Int? val tagId: Int? val categoryId: Int? constructor(artistId: Int? = null, authorId: Int? = null, tagId: Int? = null, categoryId: Int? = null) { this.artistId = artistId this.authorId = authorId this.tagId = tagId this.categoryId = categoryId } constructor(bundle: Bundle) { artistId = if (bundle.containsKey(ARTIST_ID_KEY)) bundle.getInt(ARTIST_ID_KEY) else null authorId = if (bundle.containsKey(AUTHOR_ID_KEY)) bundle.getInt(AUTHOR_ID_KEY) else null tagId = if (bundle.containsKey(TAG_ID_KEY)) bundle.getInt(TAG_ID_KEY) else null categoryId = if (bundle.containsKey(CATEGORY_ID_KEY)) bundle.getInt(CATEGORY_ID_KEY) else null } companion object { private val ARTIST_ID_KEY = "artist_id" private val AUTHOR_ID_KEY = "author_id" private val TAG_ID_KEY = "tag_id" private val CATEGORY_ID_KEY = "category_id" } public val bundle: Bundle get() { val b = Bundle() if (artistId != null) b.putInt(ARTIST_ID_KEY, artistId) if (authorId != null) b.putInt(AUTHOR_ID_KEY, authorId) if (tagId != null) b.putInt(TAG_ID_KEY, tagId) if (categoryId != null) b.putInt(CATEGORY_ID_KEY, categoryId) return b } }
mit
4b69a546f05710d57463419796252722
27.578947
102
0.577041
3.94431
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/BaseFragment.kt
1
4156
package com.habitrpg.android.habitica.ui.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.viewbinding.ViewBinding import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.TutorialRepository import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.proxy.AnalyticsManager import com.habitrpg.android.habitica.ui.activities.MainActivity import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.functions.Consumer import java.util.concurrent.TimeUnit import javax.inject.Inject abstract class BaseFragment<VB : ViewBinding> : Fragment() { var isModal: Boolean = false abstract var binding: VB? @Inject lateinit var tutorialRepository: TutorialRepository @Inject lateinit var analyticsManager: AnalyticsManager var tutorialStepIdentifier: String? = null var tutorialText: String? = null protected var tutorialCanBeDeferred = true var tutorialTexts: MutableList<String> = ArrayList() protected var compositeSubscription: CompositeDisposable = CompositeDisposable() var shouldInitializeComponent = true open val displayedClassName: String? get() = this.javaClass.simpleName fun initializeComponent() { if (!shouldInitializeComponent) return HabiticaBaseApplication.userComponent?.let { injectFragment(it) } } override fun onCreate(savedInstanceState: Bundle?) { initializeComponent() super.onCreate(savedInstanceState) } abstract fun createBinding(inflater: LayoutInflater, container: ViewGroup?): VB override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { compositeSubscription = CompositeDisposable() binding = createBinding(inflater, container) return binding?.root } abstract fun injectFragment(component: UserComponent) override fun onResume() { super.onResume() showTutorialIfNeeded() } private fun showTutorialIfNeeded() { if (view != null) { if (this.tutorialStepIdentifier != null) { compositeSubscription.add( tutorialRepository.getTutorialStep(this.tutorialStepIdentifier ?: "").firstElement() .delay(1, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe( Consumer { step -> if (step != null && step.isValid && step.isManaged && step.shouldDisplay()) { val mainActivity = activity as? MainActivity ?: return@Consumer if (tutorialText != null) { mainActivity.displayTutorialStep(step, tutorialText ?: "", tutorialCanBeDeferred) } else { mainActivity.displayTutorialStep(step, tutorialTexts, tutorialCanBeDeferred) } } }, RxErrorHandler.handleEmptyError() ) ) } } } override fun onDestroyView() { binding = null if (!compositeSubscription.isDisposed) { compositeSubscription.dispose() } super.onDestroyView() } override fun onDestroy() { try { tutorialRepository.close() } catch (exception: UninitializedPropertyAccessException) { /* no-on */ } super.onDestroy() } open fun addToBackStack(): Boolean = true }
gpl-3.0
1eb13001dd436c52ef280670913e8b4e
34.778761
121
0.621752
5.928673
false
false
false
false
pyamsoft/power-manager
powermanager-trigger/src/main/java/com/pyamsoft/powermanager/trigger/db/PowerTriggerDBImpl.kt
1
4978
/* * Copyright 2017 Peter Kenji Yamanaka * * 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.pyamsoft.powermanager.trigger.db import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.support.annotation.CheckResult import android.support.annotation.VisibleForTesting import com.squareup.sqlbrite2.BriteDatabase import com.squareup.sqlbrite2.SqlBrite import io.reactivex.Completable import io.reactivex.Scheduler import io.reactivex.Single import timber.log.Timber import javax.inject.Inject internal class PowerTriggerDBImpl @Inject constructor(context: Context, scheduler: Scheduler) : PowerTriggerDB { private val briteDatabase: BriteDatabase private val openHelper = PowerTriggerOpenHelper(context.applicationContext) init { briteDatabase = SqlBrite.Builder().build().wrapDatabaseHelper(openHelper, scheduler) } @CheckResult override fun insert(entry: PowerTriggerEntry): Completable { return Completable.fromCallable { if (PowerTriggerEntry.isEmpty(entry)) { throw IllegalStateException("Cannot insert empty entries") } Timber.i("DB: INSERT") val percent = entry.percent() return@fromCallable deleteWithPercentUnguarded(percent) }.andThen(Completable.fromCallable { PowerTriggerEntry.insertTrigger(openHelper).executeProgram(entry) }) } override fun updateEnabled(entry: PowerTriggerEntry): Completable { return Completable.fromCallable { Timber.i("DB: UPDATE ENABLED") return@fromCallable PowerTriggerEntry.updateEnabled(openHelper).executeProgram( entry.enabled(), entry.percent()) } } @CheckResult override fun queryAll(): Single<List<PowerTriggerEntry>> { return Single.defer { Timber.i("DB: QUERY ALL") val statement = PowerTriggerEntry.queryAll() return@defer briteDatabase.createQuery(statement.tables, statement.statement, *statement.args).mapToList { PowerTriggerEntry.allEntriesMapper.map(it) }.first( emptyList()) } } @CheckResult override fun queryWithPercent(percent: Int): Single<PowerTriggerEntry> { return Single.defer { Timber.i("DB: QUERY PERCENT") val statement = PowerTriggerEntry.withPercent(percent) return@defer briteDatabase.createQuery(statement.tables, statement.statement, *statement.args).mapToOneOrDefault({ PowerTriggerEntry.withPercentMapper.map(it) }, PowerTriggerEntry.empty).first(PowerTriggerEntry.empty) } } @CheckResult override fun deleteWithPercent(percent: Int): Completable { return Completable.fromCallable { Timber.i("DB: DELETE PERCENT") return@fromCallable deleteWithPercentUnguarded(percent) } } @VisibleForTesting @CheckResult fun deleteWithPercentUnguarded(percent: Int): Int { return PowerTriggerEntry.deleteTrigger(openHelper).executeProgram(percent) } @CheckResult override fun deleteAll(): Completable { return Completable.fromAction { Timber.i("DB: DELETE ALL") briteDatabase.execute(PowerTriggerModel.DELETE_ALL) briteDatabase.close() }.andThen(deleteDatabase()) } override fun deleteDatabase(): Completable { return Completable.fromAction { openHelper.deleteDatabase() } } private class PowerTriggerOpenHelper internal constructor(context: Context) : SQLiteOpenHelper( context.applicationContext, PowerTriggerDBImpl.PowerTriggerOpenHelper.DB_NAME, null, PowerTriggerDBImpl.PowerTriggerOpenHelper.DATABASE_VERSION) { private val appContext: Context = context.applicationContext internal fun deleteDatabase() { appContext.deleteDatabase(DB_NAME) } override fun onCreate(sqLiteDatabase: SQLiteDatabase) { Timber.d("onCreate") sqLiteDatabase.execSQL(PowerTriggerModel.CREATE_TABLE) } override fun onUpgrade(sqLiteDatabase: SQLiteDatabase, oldVersion: Int, newVersion: Int) { Timber.d("onUpgrade from old version %d to new %d", oldVersion, newVersion) if (oldVersion == 1 && newVersion == 2) { Timber.d("on upgrade from 1 to 2, drop entire table") sqLiteDatabase.execSQL("DROP TABLE ${PowerTriggerModel.TABLE_NAME}") Timber.d("Re-create table") onCreate(sqLiteDatabase) } } companion object { private const val DB_NAME = "power_trigger_db" private const val DATABASE_VERSION = 2 } } }
apache-2.0
d1b4242c624057029bc23cee5b3b5910
34.81295
97
0.738449
4.809662
false
false
false
false
TUWien/DocScan
app/src/main/java/at/ac/tuwien/caa/docscan/ui/document/CreateDocumentViewModel.kt
1
1902
package at.ac.tuwien.caa.docscan.ui.document import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import at.ac.tuwien.caa.docscan.db.model.Document import at.ac.tuwien.caa.docscan.db.model.MetaData import at.ac.tuwien.caa.docscan.logic.Resource import at.ac.tuwien.caa.docscan.logic.TranskribusMetaData import at.ac.tuwien.caa.docscan.repository.DocumentRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.util.* class CreateDocumentViewModel(val repository: DocumentRepository) : ViewModel() { val observableResource = MutableLiveData<Resource<Document>>() fun createDocument(title: String, prefix: String?, transkribusMetaData: TranskribusMetaData?) { viewModelScope.launch(Dispatchers.IO) { val document = Document(UUID.randomUUID(), title, filePrefix = prefix, isActive = true) transkribusMetaData?.let { document.metaData = MetaData( relatedUploadId = transkribusMetaData.relatedUploadId, author = transkribusMetaData.author, authority = transkribusMetaData.authority, hierarchy = transkribusMetaData.hierarchy, genre = transkribusMetaData.genre, language = transkribusMetaData.language, isProjectReadme2020 = transkribusMetaData.readme2020, allowImagePublication = transkribusMetaData.readme2020Public, signature = transkribusMetaData.signature, url = transkribusMetaData.url, writer = transkribusMetaData.writer, description = transkribusMetaData.description ) } observableResource.postValue(repository.createDocument(document)) } } }
lgpl-3.0
e1818298d6d3ffd804436b62fbe6aca4
45.390244
99
0.685594
5.594118
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/comment/reference/LuaDocParamNameReference.kt
2
2549
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.comment.reference import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiReferenceBase import com.intellij.util.IncorrectOperationException import com.tang.intellij.lua.comment.LuaCommentUtil import com.tang.intellij.lua.comment.psi.LuaDocParamNameRef import com.tang.intellij.lua.psi.* /** * 函数参数引用 * Created by tangzx on 2016/11/25. */ class LuaDocParamNameReference(element: LuaDocParamNameRef) : PsiReferenceBase<LuaDocParamNameRef>(element) { override fun getRangeInElement(): TextRange { return TextRange(0, myElement.textLength) } override fun isReferenceTo(element: PsiElement): Boolean { return myElement.manager.areElementsEquivalent(element, resolve()) } @Throws(IncorrectOperationException::class) override fun handleElementRename(newElementName: String): PsiElement { val id = LuaElementFactory.createIdentifier(myElement.project, newElementName) myElement.firstChild.replace(id) return id } override fun resolve(): PsiElement? { val owner = LuaCommentUtil.findOwner(myElement) if (owner != null) { val name = myElement.text var target:PsiElement? = null owner.accept(object :LuaVisitor() { override fun visitPsiElement(o: LuaPsiElement) { if (o is LuaParametersOwner) { target = findParamWithName(o.paramNameDefList, name) } target ?: o.acceptChildren(this) } }) return target } return null } private fun findParamWithName(defList: List<LuaParamNameDef>?, str: String): PsiElement? { return defList?.firstOrNull { it.text == str } } override fun getVariants(): Array<Any?> { return arrayOfNulls(0) } }
apache-2.0
62dd1e1ca620b7c58b162e4f11931091
32.826667
109
0.681514
4.546595
false
false
false
false
ohmae/DmsExplorer
mobile/src/main/java/net/mm2d/dmsexplorer/viewmodel/helper/MovieActivityPipHelperOreo.kt
1
6722
/* * Copyright (c) 2017 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.dmsexplorer.viewmodel.helper import android.app.* import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.Rect import android.graphics.drawable.Icon import android.net.Uri import android.os.Build import android.util.Rational import android.view.View import androidx.annotation.DrawableRes import androidx.annotation.RequiresApi import androidx.annotation.StringRes import net.mm2d.dmsexplorer.Const import net.mm2d.dmsexplorer.R import net.mm2d.dmsexplorer.viewmodel.ControlPanelModel import net.mm2d.log.Logger /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ @RequiresApi(api = Build.VERSION_CODES.O) internal class MovieActivityPipHelperOreo( private val activity: Activity ) : MovieActivityPipHelper { private var controlPanelModel: ControlPanelModel? = null private val controlReceiver = object : BroadcastReceiver() { override fun onReceive( context: Context, intent: Intent ) { val action = intent.action val model = controlPanelModel if (action.isNullOrEmpty() || model == null) { return } when (action) { Const.ACTION_PLAY -> { model.onClickPlayPause() activity.setPictureInPictureParams( PictureInPictureParams.Builder() .setActions(makeActions(model.isPlaying)) .build() ) } Const.ACTION_NEXT -> model.onClickNext() Const.ACTION_PREV -> model.onClickPrevious() } } } private fun isPictureInPictureAllowed(): Boolean { val appOps = activity.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager return try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { appOps.unsafeCheckOpNoThrow( AppOpsManager.OPSTR_PICTURE_IN_PICTURE, android.os.Process.myUid(), activity.packageName ) } else { appOps.checkOpNoThrow( AppOpsManager.OPSTR_PICTURE_IN_PICTURE, android.os.Process.myUid(), activity.packageName ) } == AppOpsManager.MODE_ALLOWED } catch (ignored: Exception) { false } } override fun register() { activity.registerReceiver(controlReceiver, makeIntentFilter()) } private fun makeIntentFilter(): IntentFilter = IntentFilter().also { it.addAction(Const.ACTION_PLAY) it.addAction(Const.ACTION_NEXT) it.addAction(Const.ACTION_PREV) } override fun unregister() { activity.unregisterReceiver(controlReceiver) } override fun setControlPanelModel(model: ControlPanelModel?) { controlPanelModel = model } override fun enterPictureInPictureMode(contentView: View) { if (!isPictureInPictureAllowed()) { val intent = Intent(ACTION_PICTURE_IN_PICTURE_SETTINGS) intent.data = Uri.parse("package:" + activity.packageName) activity.startActivity(intent) return } val builder = PictureInPictureParams.Builder() builder.setActions(controlPanelModel?.isPlaying?.let { makeActions(it) }) val rect = makeViewRect(contentView) if (rect.width() > 0 && rect.height() > 0) { builder.setSourceRectHint(rect) .setAspectRatio(Rational(rect.width(), rect.height())) } try { activity.enterPictureInPictureMode(builder.build()) } catch (e: Exception) { Logger.w(e) } } private fun makeViewRect(v: View): Rect = Rect().also { v.getGlobalVisibleRect(it) } private fun makeActions(isPlaying: Boolean): List<RemoteAction>? { val max = activity.maxNumPictureInPictureActions if (max <= 0) { return null } return if (max >= 3) { listOf(makePreviousAction(), makePlayAction(isPlaying), makeNextAction()) } else listOf(makePlayAction(isPlaying)) } private fun makePlayAction(isPlaying: Boolean): RemoteAction = RemoteAction( makeIcon(if (isPlaying) R.drawable.ic_pause else R.drawable.ic_play), getString(R.string.action_play_title), getString(R.string.action_play_description), makePlayPendingIntent(activity) ) private fun makeNextAction(): RemoteAction = RemoteAction( makeIcon(R.drawable.ic_skip_next), getString(R.string.action_next_title), getString(R.string.action_next_description), makeNextPendingIntent(activity) ) private fun makePreviousAction(): RemoteAction = RemoteAction( makeIcon(R.drawable.ic_skip_previous), getString(R.string.action_previous_title), getString(R.string.action_previous_description), makePreviousPendingIntent(activity) ) private fun getString(@StringRes resId: Int): String = activity.resources.getText(resId, "").toString() private fun makeIcon(@DrawableRes resId: Int): Icon = Icon.createWithResource(activity, resId) companion object { private const val ACTION_PICTURE_IN_PICTURE_SETTINGS = "android.settings.PICTURE_IN_PICTURE_SETTINGS" private fun makePlayPendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast( context, Const.REQUEST_CODE_ACTION_PLAY, Intent(Const.ACTION_PLAY), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) private fun makeNextPendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast( context, Const.REQUEST_CODE_ACTION_NEXT, Intent(Const.ACTION_NEXT), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) private fun makePreviousPendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast( context, Const.REQUEST_CODE_ACTION_PREVIOUS, Intent(Const.ACTION_PREV), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) } }
mit
d16d08da0ba1cba98aaf0efe3b58b767
34.294737
98
0.624515
4.838384
false
false
false
false
develar/mapsforge-tile-server
server/src/MapsforgeTileServer.kt
1
7199
package org.develar.mapsforgeTileServer import com.google.common.collect.ImmutableMap import com.google.common.collect.Iterators import io.netty.bootstrap.ServerBootstrap import io.netty.channel.Channel import io.netty.channel.ChannelInitializer import io.netty.channel.ChannelOption import io.netty.channel.epoll.EpollEventLoopGroup import io.netty.channel.epoll.EpollServerSocketChannel import io.netty.channel.nio.NioEventLoopGroup import io.netty.channel.socket.nio.NioServerSocketChannel import io.netty.handler.codec.http.HttpObjectAggregator import io.netty.handler.codec.http.HttpRequestDecoder import io.netty.handler.codec.http.HttpResponseEncoder import io.netty.util.concurrent.Future import org.develar.mapsforgeTileServer.pixi.processPaths import org.kohsuke.args4j.CmdLineException import org.kohsuke.args4j.CmdLineParser import org.mapsforge.core.graphics.GraphicFactory import org.mapsforge.core.graphics.TileBitmap import org.mapsforge.map.awt.AwtGraphicFactory import org.mapsforge.map.awt.AwtTileBitmap import org.mapsforge.map.model.DisplayModel import org.slf4j.Logger import org.slf4j.LoggerFactory import java.awt.image.BufferedImage import java.io.File import java.io.OutputStreamWriter import java.net.InetAddress import java.net.InetSocketAddress import java.nio.file.Path import java.util.ArrayList import java.util.Enumeration import java.util.Locale import java.util.ResourceBundle import java.util.concurrent.atomic.AtomicReference import java.util.function.Consumer import javax.imageio.ImageIO val LOG:Logger = LoggerFactory.getLogger(javaClass<MapsforgeTileServer>()) class MyAwtGraphicFactory() : AwtGraphicFactory() { override fun createTileBitmap(tileSize: Int, hasAlpha: Boolean): TileBitmap { return AwtTileBitmap(BufferedImage(tileSize, tileSize, if (hasAlpha) BufferedImage.TYPE_INT_ARGB else BufferedImage.TYPE_3BYTE_BGR)) } } val AWT_GRAPHIC_FACTORY: GraphicFactory = MyAwtGraphicFactory() public fun main(args: Array<String>) { ImageIO.setUseCache(false) val options = Options() //printUsage(options); try { CmdLineParser(options).parseArgument(args.toList()) } catch (e: CmdLineException) { System.err.print(e.getMessage()) System.exit(64) } val maps = ArrayList<File>(options.maps!!.size()) processPaths(options.maps!!, ".map", Integer.MAX_VALUE, object: Consumer<Path> { override fun accept(path: Path) { maps.add(path.toFile()) } }) if (maps.isEmpty()) { LOG.error("No map specified") return } if (options.maxFileCacheSize == -2.0) { options.maxFileCacheSize = System.getenv("MAX_FILE_CACHE_SIZE")?.toDouble() ?: 30.0 } val mapsforgeTileServer: MapsforgeTileServer try { mapsforgeTileServer = MapsforgeTileServer(maps, options.themes!!) } catch (e: IllegalStateException) { LOG.error(e.getMessage()) return } mapsforgeTileServer.startServer(options) } SuppressWarnings("UnusedDeclaration") private fun printUsage(options: Options) { CmdLineParser(options).printUsage(OutputStreamWriter(System.out), object : ResourceBundle() { private val data = ImmutableMap.Builder<String, String>().put("FILE", "<path>").put("PATH", "<path>").put("VAL", "<string>").put("N", " <int>").build() override fun handleGetObject(key: String): Any { return data.get(key) ?: key } override fun getKeys(): Enumeration<String> { return Iterators.asEnumeration(data.keySet().iterator()) } }) } private fun getAvailableMemory(): Long { val runtime = Runtime.getRuntime() val totalMemory = runtime.totalMemory() // current heap allocated to the VM process val freeMemory = runtime.freeMemory() // out of the current heap, how much is free val maxMemory = runtime.maxMemory() // max heap VM can use e.g. Xmx setting val usedMemory = totalMemory - freeMemory // how much of the current heap the VM is using // available memory i.e. Maximum heap size minus the current amount used return maxMemory - usedMemory } class MapsforgeTileServer(val maps: List<File>, renderThemeFiles: Array<Path>) { val displayModel = DisplayModel() val renderThemeManager = RenderThemeManager(renderThemeFiles, displayModel) fun startServer(options: Options) { val isLinux = System.getProperty("os.name")!!.toLowerCase(Locale.ENGLISH).startsWith("linux") val eventGroup = if (isLinux) EpollEventLoopGroup() else NioEventLoopGroup() val channelRegistrar = ChannelRegistrar() val eventGroupShutdownFeature = AtomicReference<Future<*>>() val shutdownHooks = ArrayList<()->Unit>(4) shutdownHooks.add { LOG.info("Shutdown server"); try { channelRegistrar.closeAndSyncUninterruptibly(); } finally { if (!eventGroupShutdownFeature.compareAndSet(null, eventGroup.shutdownGracefully())) { LOG.error("ereventGroupShutdownFeature was already set"); } renderThemeManager.dispose() } } val executorCount = eventGroup.executorCount() val fileCacheManager = if (options.maxFileCacheSize == 0.0) null else FileCacheManager(options, executorCount, shutdownHooks) val maxMemoryCacheSize = getAvailableMemory() - (64 * 1024 * 1024).toLong() /* leave 64MB for another stuff */ if (maxMemoryCacheSize <= 0) { val runtime = Runtime.getRuntime() LOG.error("Memory not enough, current free memory " + runtime.freeMemory() + ", total memory " + runtime.totalMemory() + ", max memory " + runtime.maxMemory()) return } val tileHttpRequestHandler = TileHttpRequestHandler(this, fileCacheManager, executorCount, maxMemoryCacheSize, shutdownHooks) // task "sync eventGroupShutdownFeature only" must be last shutdownHooks.add { eventGroupShutdownFeature.getAndSet(null)!!.syncUninterruptibly() } val serverBootstrap = ServerBootstrap() serverBootstrap.group(eventGroup).channel(if (isLinux) javaClass<EpollServerSocketChannel>() else javaClass<NioServerSocketChannel>()).childHandler(object : ChannelInitializer<Channel>() { override fun initChannel(channel: Channel) { channel.pipeline().addLast(channelRegistrar) channel.pipeline().addLast(HttpRequestDecoder(), HttpObjectAggregator(1048576 * 10), HttpResponseEncoder()) channel.pipeline().addLast(tileHttpRequestHandler) } }).childOption<Boolean>(ChannelOption.SO_KEEPALIVE, true).childOption<Boolean>(ChannelOption.TCP_NODELAY, true) val address = if (options.host.orEmpty().isEmpty()) InetSocketAddress(InetAddress.getLoopbackAddress(), options.port) else InetSocketAddress(options.host!!, options.port) val serverChannel = serverBootstrap.bind(address).syncUninterruptibly().channel() channelRegistrar.addServerChannel(serverChannel) Runtime.getRuntime().addShutdownHook(Thread(object: Runnable { override fun run() { for (shutdownHook in shutdownHooks) { try { shutdownHook() } catch (e: Throwable) { LOG.error(e.getMessage(), e); } } } })) LOG.info("Listening " + address.getHostName() + ":" + address.getPort()) serverChannel.closeFuture().syncUninterruptibly() } }
mit
da4ef83c7d326ef02ba3a16d06beb99b
37.502674
192
0.740103
4.360388
false
false
false
false
Benestar/focus-android
app/src/main/java/org/mozilla/focus/utils/FileUtils.kt
1
1736
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.utils import android.content.Context import edu.umd.cs.findbugs.annotations.SuppressFBWarnings import java.io.File private const val WEBVIEW_DIRECTORY = "app_webview" private const val LOCAL_STORAGE_DIR = "Local Storage" class FileUtils { companion object { @JvmStatic fun truncateCacheDirectory(context: Context): Boolean { val cacheDirectory = context.cacheDir return cacheDirectory.exists() && deleteContent(cacheDirectory) } @JvmStatic fun deleteWebViewDirectory(context: Context): Boolean { val webviewDirectory = File(context.applicationInfo.dataDir, WEBVIEW_DIRECTORY) return deleteContent(webviewDirectory, doNotEraseWhitelist = setOf( LOCAL_STORAGE_DIR // If the folder or its contents is deleted, WebStorage.deleteAllData does not clear Local Storage in memory. )) } @SuppressFBWarnings("BC_BAD_CAST_TO_ABSTRACT_COLLECTION", "filter casts to Collection and storing in val casts back to List: https://youtrack.jetbrains.com/issue/KT-18311") private fun deleteContent(directory: File, doNotEraseWhitelist: Set<String> = emptySet()): Boolean { val filesToDelete = directory.listFiles()?.filter { !doNotEraseWhitelist.contains(it.name) } ?: return false return filesToDelete.all { it.deleteRecursively() } } } }
mpl-2.0
4ed1cc0ec59f4c1a57d89777fc33d33b
43.512821
147
0.686636
4.462725
false
false
false
false
czyzby/ktx
box2d/src/test/kotlin/ktx/box2d/JointsTest.kt
2
6577
package ktx.box2d import com.badlogic.gdx.physics.box2d.Body import com.badlogic.gdx.physics.box2d.joints.DistanceJoint import com.badlogic.gdx.physics.box2d.joints.DistanceJointDef import org.junit.Assert.assertEquals import org.junit.Assert.assertSame import org.junit.Assert.assertTrue import org.junit.Test /** * Tests joint builder methods. */ class JointsTest { @Test fun `should create Joint with a custom JointDef`() { val (bodyA, bodyB) = getBodies() val jointDefinition = DistanceJointDef() val variable: Int val joint = bodyA.jointWith(bodyB, jointDefinition) { length = 2f assertSame(jointDefinition, this) variable = 42 } assertSame(bodyA, joint.bodyA) assertSame(bodyB, joint.bodyB) assertEquals(bodyA.position, joint.anchorA) assertEquals(bodyB.position, joint.anchorB) assertTrue(joint is DistanceJoint) assertEquals(2f, (joint as DistanceJoint).length) assertEquals(42, variable) bodyA.world.dispose() } @Test fun `should create RevoluteJoint`() { val (bodyA, bodyB) = getBodies() val variable: Int val joint = bodyA.revoluteJointWith(bodyB) { motorSpeed = 2f variable = 42 } assertSame(bodyA, joint.bodyA) assertSame(bodyB, joint.bodyB) assertEquals(bodyA.position, joint.anchorA) assertEquals(bodyB.position, joint.anchorB) assertEquals(2f, joint.motorSpeed) assertEquals(42, variable) bodyA.world.dispose() } @Test fun `should create PrismaticJoint`() { val (bodyA, bodyB) = getBodies() val variable: Int val joint = bodyA.prismaticJointWith(bodyB) { motorSpeed = 2f variable = 42 } assertSame(bodyA, joint.bodyA) assertSame(bodyB, joint.bodyB) assertEquals(bodyA.position, joint.anchorA) assertEquals(bodyB.position, joint.anchorB) assertEquals(2f, joint.motorSpeed) assertEquals(42, variable) bodyA.world.dispose() } @Test fun `should create DistanceJoint`() { val (bodyA, bodyB) = getBodies() val variable: Int val joint = bodyA.distanceJointWith(bodyB) { length = 2f variable = 42 } assertSame(bodyA, joint.bodyA) assertSame(bodyB, joint.bodyB) assertEquals(bodyA.position, joint.anchorA) assertEquals(bodyB.position, joint.anchorB) assertEquals(2f, joint.length) assertEquals(42, variable) bodyA.world.dispose() } @Test fun `should create PulleyJoint`() { val (bodyA, bodyB) = getBodies() val variable: Int val joint = bodyA.pulleyJointWith(bodyB) { ratio = 2f variable = 42 } assertSame(bodyA, joint.bodyA) assertSame(bodyB, joint.bodyB) assertEquals(bodyA.position, joint.anchorA) assertEquals(bodyB.position, joint.anchorB) assertEquals(2f, joint.ratio) assertEquals(42, variable) bodyA.world.dispose() } @Test fun `should create MouseJoint`() { val (bodyA, bodyB) = getBodies() val variable: Int val joint = bodyA.mouseJointWith(bodyB) { dampingRatio = 0.2f variable = 42 } assertSame(bodyA, joint.bodyA) assertSame(bodyB, joint.bodyB) // Anchors are not checked, as initial joint's anchor positions do not match bodies' positions. assertEquals(0.2f, joint.dampingRatio) assertEquals(42, variable) bodyA.world.dispose() } @Test fun `should create GearJoint`() { val (bodyA, bodyB) = getBodies() val jointA = bodyB.revoluteJointWith(bodyA) val jointB = bodyA.revoluteJointWith(bodyB) val variable: Int val joint = bodyA.gearJointWith(bodyB) { joint1 = jointA joint2 = jointB variable = 42 } assertSame(bodyA, joint.bodyA) assertSame(bodyB, joint.bodyB) assertEquals(bodyA.position, joint.anchorA) assertEquals(bodyB.position, joint.anchorB) assertSame(jointA, joint.joint1) assertSame(jointB, joint.joint2) assertEquals(42, variable) bodyA.world.dispose() } @Test fun `should create WheelJoint`() { val (bodyA, bodyB) = getBodies() val variable: Int val joint = bodyA.wheelJointWith(bodyB) { motorSpeed = 2f variable = 42 } assertSame(bodyA, joint.bodyA) assertSame(bodyB, joint.bodyB) assertEquals(bodyA.position, joint.anchorA) assertEquals(bodyB.position, joint.anchorB) assertEquals(2f, joint.motorSpeed) assertEquals(42, variable) bodyA.world.dispose() } @Test fun `should create WeldJoint`() { val (bodyA, bodyB) = getBodies() val variable: Int val joint = bodyA.weldJointWith(bodyB) { dampingRatio = 0.2f variable = 42 } assertSame(bodyA, joint.bodyA) assertSame(bodyB, joint.bodyB) assertEquals(bodyA.position, joint.anchorA) assertEquals(bodyB.position, joint.anchorB) assertEquals(0.2f, joint.dampingRatio) assertEquals(42, variable) bodyA.world.dispose() } @Test fun `should create FrictionJoint`() { val (bodyA, bodyB) = getBodies() val variable: Int val joint = bodyA.frictionJointWith(bodyB) { maxForce = 2f variable = 42 } assertSame(bodyA, joint.bodyA) assertSame(bodyB, joint.bodyB) assertEquals(bodyA.position, joint.anchorA) assertEquals(bodyB.position, joint.anchorB) assertEquals(2f, joint.maxForce) assertEquals(42, variable) bodyA.world.dispose() } @Test fun `should create RopeJoint`() { val (bodyA, bodyB) = getBodies() val variable: Int val joint = bodyA.ropeJointWith(bodyB) { maxLength = 2f variable = 42 } assertSame(bodyA, joint.bodyA) assertSame(bodyB, joint.bodyB) assertEquals(bodyA.position, joint.anchorA) assertEquals(bodyB.position, joint.anchorB) assertEquals(2f, joint.maxLength) assertEquals(42, variable) bodyA.world.dispose() } @Test fun `should create MotorJoint`() { val (bodyA, bodyB) = getBodies() val variable: Int val joint = bodyA.motorJointWith(bodyB) { maxForce = 2f variable = 42 } assertSame(bodyA, joint.bodyA) assertSame(bodyB, joint.bodyB) assertEquals(bodyA.position, joint.anchorA) assertEquals(bodyB.position, joint.anchorB) assertEquals(2f, joint.maxForce) assertEquals(42, variable) bodyA.world.dispose() } private fun getBodies(): Pair<Body, Body> { val world = createWorld() val bodyA = world.body { position.set(-1f, 0f) box(1f, 1f) } val bodyB = world.body { position.set(1f, 0f) box(1f, 1f) } return bodyA to bodyB } }
cc0-1.0
1255e3ceeb970139f4d100b66f40c846
24.199234
99
0.672495
3.846199
false
true
false
false
czyzby/ktx
ashley/src/test/kotlin/ktx/ashley/FamiliesSpec.kt
2
2418
package ktx.ashley import com.badlogic.ashley.core.Entity import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it object FamiliesSpec : Spek({ describe("utilities for component families") { val textureEntity = Entity().apply { add(Texture()) } val rigidBodyEntity = Entity().apply { add(RigidBody()) } val textureAndTransformEntity = Entity().apply { add(Texture()) add(Transform()) } val allComponentsEntity = Entity().apply { add(Texture()) add(Transform()) add(RigidBody()) } it("should create a family that matches one of component") { val family = oneOf(Texture::class, Transform::class).get() assertThat(family.matches(textureEntity)).isTrue() assertThat(family.matches(rigidBodyEntity)).isFalse() } it("should create a family that matches all components") { val family = allOf(Texture::class, Transform::class).get() assertThat(family.matches(textureEntity)).isFalse() assertThat(family.matches(textureAndTransformEntity)).isTrue() } it("should create a family that matches any excluded components") { assertThat(exclude(Transform::class).get().matches(textureEntity)).isTrue() assertThat(exclude(Texture::class).get().matches(textureEntity)).isFalse() } describe("composite families") { it("should build a family chained with matching any of one component") { val family = exclude(Transform::class).oneOf(Texture::class, RigidBody::class) assertThat(family.get().matches(textureEntity)).isTrue() assertThat(family.get().matches(textureAndTransformEntity)).isFalse() } it("should build a family chained with matching all components") { val family = exclude(RigidBody::class).allOf(Texture::class, Transform::class) assertThat(family.get().matches(allComponentsEntity)).isFalse() assertThat(family.get().matches(textureAndTransformEntity)).isTrue() } it("should build a family chained with excluding components") { val family = oneOf(RigidBody::class).exclude(Texture::class, Transform::class) assertThat(family.get().matches(allComponentsEntity)).isFalse() assertThat(family.get().matches(rigidBodyEntity)).isTrue() } } } })
cc0-1.0
cd8b5caa4579901ff86d682b40df1789
35.089552
86
0.687345
4.453039
false
false
false
false
mitallast/netty-queue
src/main/java/org/mitallast/queue/crdt/routing/fsm/RoutingTableFSM.kt
1
5930
package org.mitallast.queue.crdt.routing.fsm import com.google.common.base.Preconditions import com.typesafe.config.Config import io.vavr.control.Option import org.mitallast.queue.common.codec.Message import org.mitallast.queue.common.events.EventBus import org.mitallast.queue.common.file.FileService import org.mitallast.queue.common.logging.LoggingService import org.mitallast.queue.crdt.routing.Resource import org.mitallast.queue.crdt.routing.RoutingTable import org.mitallast.queue.crdt.routing.event.RoutingTableChanged import org.mitallast.queue.raft.protocol.RaftSnapshotMetadata import org.mitallast.queue.raft.resource.ResourceFSM import org.mitallast.queue.raft.resource.ResourceRegistry import java.io.File import java.io.IOError import java.io.IOException import javax.inject.Inject class RoutingTableFSM @Inject constructor( config: Config, logging: LoggingService, registry: ResourceRegistry, private val eventBus: EventBus, private val fileService: FileService ) : ResourceFSM { private val logger = logging.logger() private val file: File = fileService.resource("crdt", "routing.bin") @Volatile private var lastApplied: Long = 0 @Volatile private var routingTable: RoutingTable = RoutingTable( config.getInt("crdt.replicas"), config.getInt("crdt.buckets") ) init { restore() registry.register(this) registry.register(AddResource::class.java, this::handle) registry.register(RemoveResource::class.java, this::handle) registry.register(UpdateMembers::class.java, this::handle) registry.register(AddReplica::class.java, this::handle) registry.register(CloseReplica::class.java, this::handle) registry.register(RemoveReplica::class.java, this::handle) registry.register(RoutingTable::class.java, this::handle) } fun get(): RoutingTable { return routingTable } private fun restore() { if (file.length() > 0) { try { fileService.input(file).use { stream -> routingTable = RoutingTable.codec.read(stream) } } catch (e: IOException) { throw IOError(e) } } } private fun persist(index: Long, routingTable: RoutingTable) { Preconditions.checkArgument(index > lastApplied) this.lastApplied = index logger.info("before: {}", this.routingTable) this.routingTable = routingTable logger.info("after: {}", this.routingTable) try { fileService.output(file).use { stream -> RoutingTable.codec.write(stream, routingTable) } } catch (e: IOException) { throw IOError(e) } eventBus.trigger(RoutingTableChanged(index, routingTable)) } private fun handle(index: Long, routingTable: RoutingTable): Option<Message> { if (index <= lastApplied) { return Option.none() } persist(index, routingTable) return Option.none() } private fun handle(index: Long, request: AddResource): Option<Message> { if (index <= lastApplied) { return Option.none() } if (routingTable.hasResource(request.id)) { return Option.some(AddResourceResponse(request.type, request.id, false)) } val resource = Resource( request.id, request.type ) persist(index, routingTable.withResource(resource)) return Option.some(AddResourceResponse(request.type, request.id, true)) } private fun handle(index: Long, request: RemoveResource): Option<Message> { if (index <= lastApplied) { return Option.none() } if (routingTable.hasResource(request.id)) { persist(index, routingTable.withoutResource(request.id)) return Option.some(RemoveResourceResponse(request.type, request.id, true)) } return Option.some(RemoveResourceResponse(request.type, request.id, false)) } private fun handle(index: Long, updateMembers: UpdateMembers): Option<Message> { if (index <= lastApplied) { return Option.none() } persist(index, routingTable.withMembers(updateMembers.members)) return Option.none() } private fun handle(index: Long, request: AddReplica): Option<Message> { if (index <= lastApplied) { return Option.none() } val routingBucket = routingTable.bucket(request.bucket.toLong()) if (!routingBucket.exists(request.member)) { persist(index, routingTable.withReplica(request.bucket, request.member)) } else { logger.warn("node {} already allocated in bucket {}", request.member, request.bucket) } return Option.none() } private fun handle(index: Long, request: CloseReplica): Option<Message> { if (index <= lastApplied) { return Option.none() } val routingBucket = routingTable.bucket(request.bucket.toLong()) val replica = routingBucket.replicas.get(request.replica) if (replica.exists { it.isOpened }) { persist(index, routingTable.withReplica(request.bucket, replica.get().close())) } return Option.none() } private fun handle(index: Long, request: RemoveReplica): Option<Message> { if (index <= lastApplied) { return Option.none() } val routingBucket = routingTable.bucket(request.bucket.toLong()) val replica = routingBucket.replicas.get(request.replica) if (replica.exists { it.isClosed }) { persist(index, routingTable.withoutReplica(request.bucket, request.replica)) } return Option.none() } override fun prepareSnapshot(snapshotMeta: RaftSnapshotMetadata): Option<Message> { return Option.some(routingTable) } }
mit
3ca2c269a1a673833f4956a8969395e6
35.158537
104
0.656998
4.489023
false
false
false
false
BloodWorkXGaming/ExNihiloCreatio
src/main/java/exnihilocreatio/blocks/BlockFluidWitchwater.kt
1
6767
package exnihilocreatio.blocks import exnihilocreatio.ModFluids import exnihilocreatio.api.ExNihiloCreatioAPI.WITCH_WATER_WORLD_REGISTRY import exnihilocreatio.config.ModConfig import exnihilocreatio.util.Data import net.minecraft.block.Block import net.minecraft.block.BlockLiquid import net.minecraft.block.material.Material import net.minecraft.block.state.IBlockState import net.minecraft.entity.Entity import net.minecraft.entity.EntityLivingBase import net.minecraft.entity.effect.EntityLightningBolt import net.minecraft.entity.monster.* import net.minecraft.entity.passive.* import net.minecraft.entity.player.EntityPlayer import net.minecraft.init.MobEffects import net.minecraft.init.SoundEvents import net.minecraft.potion.PotionEffect import net.minecraft.util.EnumFacing import net.minecraft.util.EnumParticleTypes import net.minecraft.util.ResourceLocation import net.minecraft.util.SoundCategory import net.minecraft.util.math.BlockPos import net.minecraft.world.World import net.minecraftforge.fluids.BlockFluidBase import net.minecraftforge.fluids.BlockFluidClassic import net.minecraftforge.fluids.Fluid import net.minecraftforge.fluids.FluidRegistry class BlockFluidWitchwater : BlockFluidClassic(ModFluids.fluidWitchwater, Material.WATER) { init { this.setRegistryName("witchwater") this.translationKey = "witchwater" Data.BLOCKS.add(this) } override fun onEntityCollision(world: World?, pos: BlockPos?, state: IBlockState?, entity: Entity?) { world ?: return entity ?: return if (world.isRemote || entity.isDead) return when (entity) { is EntitySkeleton -> replaceMob(world, entity, EntityWitherSkeleton(world)) is EntityCreeper -> { if (!entity.powered) { entity.onStruckByLightning(EntityLightningBolt(world, entity.posX, entity.posY, entity.posZ, true)) entity.health = entity.maxHealth } } is EntitySlime -> if (entity !is EntityMagmaCube) { val newEntity = EntityMagmaCube(world) newEntity.setSlimeSize(entity.slimeSize, true) replaceMob(world, entity, newEntity) } is EntitySpider -> if (entity !is EntityCaveSpider) replaceMob(world, entity, EntityCaveSpider(world)) is EntitySquid -> replaceMob(world, entity, EntityGhast(world)) is EntityVillager -> { val prof = entity.professionForge val spawnEntity = when (prof.registryName) { PRIEST -> EntityWitch(world) BUTCHER -> EntityVindicator(world) LIBRARIAN -> EntityEvoker(world) else -> EntityZombieVillager(world).apply { this.forgeProfession = prof } } replaceMob(world, entity, spawnEntity) } is EntityCow -> if (entity !is EntityMooshroom) replaceMob(world, entity, EntityMooshroom(world)) is EntityAnimal -> entity.onStruckByLightning(EntityLightningBolt(world, entity.posX, entity.posY, entity.posZ, true)) is EntityPlayer -> { applyPotion(entity, PotionEffect(MobEffects.BLINDNESS, 210, 0)) applyPotion(entity, PotionEffect(MobEffects.WEAKNESS, 210, 2)) applyPotion(entity, PotionEffect(MobEffects.WITHER, 210, 0)) applyPotion(entity, PotionEffect(MobEffects.SLOWNESS, 210, 0)) } } } /** * Renew's a potion effect if the time would be increased by more than 20 ticks */ private fun applyPotion(player: EntityPlayer, potionEffect: PotionEffect) { // Grab the potion effect on the player (null if not active) compare its duration (defaulting to 0) to the new duration if(player.getActivePotionEffect(potionEffect.potion)?.duration ?: 0 <= potionEffect.duration-20) player.addPotionEffect(potionEffect) } private fun replaceMob(world: World, toKill: EntityLivingBase, toSpawn: EntityLivingBase) { toSpawn.setLocationAndAngles(toKill.posX, toKill.posY, toKill.posZ, toKill.rotationYaw, toKill.rotationPitch) toSpawn.renderYawOffset = toKill.renderYawOffset toSpawn.health = toSpawn.maxHealth * toKill.health / toKill.maxHealth toKill.setDead() world.spawnEntity(toSpawn) } companion object { private val PRIEST = ResourceLocation("minecraft:priest") private val BUTCHER = ResourceLocation("minecraft:butcher") private val LIBRARIAN = ResourceLocation("minecraft:librarian") } @Suppress("OverridingDeprecatedMember", "DEPRECATION") override fun neighborChanged(state: IBlockState, world: World, pos: BlockPos, neighborBlock: Block, neighbourPos: BlockPos) { super.neighborChanged(state, world, pos, neighborBlock, neighbourPos) interactWithAdjacent(world, pos) } override fun onBlockAdded(world: World, pos: BlockPos, state: IBlockState) { super.onBlockAdded(world, pos, state) interactWithAdjacent(world, pos) } private fun interactWithAdjacent(world: World, pos: BlockPos) { if(!ModConfig.witchwater.enableWitchWaterBlockForming) return var otherFluid: Fluid? = null for(side in EnumFacing.VALUES) { if(side == EnumFacing.DOWN) continue val offset = world.getBlockState(pos.offset(side)) if(offset.material.isLiquid && offset.block !is BlockFluidWitchwater && (offset.block is BlockFluidBase || offset.block is BlockLiquid)) { otherFluid = FluidRegistry.lookupFluidForBlock(offset.block) break } } if(otherFluid == null) return if(WITCH_WATER_WORLD_REGISTRY.contains(otherFluid)) { val isCold = otherFluid.temperature <= 300 val newState = WITCH_WATER_WORLD_REGISTRY.getResult(otherFluid, world.rand.nextFloat()).blockState world.setBlockState(pos, newState) val sound = if(isCold) SoundEvents.BLOCK_GRAVEL_BREAK else SoundEvents.BLOCK_STONE_BREAK world.playSound(null, pos, sound, SoundCategory.BLOCKS, 0.5f, 2.6f + (world.rand.nextFloat() - world.rand.nextFloat()) * 0.8f) for(i in 0 until 10) { world.spawnParticle(EnumParticleTypes.SMOKE_LARGE, pos.x + world.rand.nextDouble(), pos.y + world.rand.nextDouble(), pos.z + world.rand.nextDouble(), 0.0, 0.0, 0.0) } } } }
mit
f193823d259d845f99e33047e89678c5
39.279762
180
0.660115
4.566127
false
false
false
false
marionthefourth/TicTacToe-in-Kotlin
src/Board.kt
1
3370
/** * Created by MGR4 on 6/24/17. */ class Board { val indicies = array2d(3,3) { " " } fun spotIsAvailable(position:Pair<Int,Int>):Boolean { return indicies[position.first][position.second].equals(" ") } fun fillSpot(position:Pair<Int,Int>,value:String) { indicies[position.first][position.second] = value this.print() } fun isFilled() : Boolean { indicies.forEach { if (it.contains(" ")) { return false } } return true } fun hasCompleteSet() : Pair<Boolean,Int> { val validInputs = arrayOf(" X ", " O ") for (i in 0..validInputs.size-1) { // Search Vertically if (foundMatchesVertically(validInputs[i])) { return Pair(true,i) // Search Horizontally } else if (foundMatchesHorizontally(validInputs[i])) { return Pair(true,i) // Search Diagonally } else if (foundMatchesDiagonally(validInputs[i])) { return Pair(true,i) } } return Pair(false,-1) } fun foundMatchesHorizontally(mark:String) : Boolean { var marksMatching = 0 for (i in 0..2) { for (j in 0..2) { if (indicies[i][j].equals(mark)) { marksMatching++ } else { break } } if (marksMatching == 3) { return true } } return false } fun foundMatchesVertically(mark:String) : Boolean { var marksMatching = 0 for (i in 0..2) { for (j in 0..2) { if (indicies[j][i].equals(mark)) { marksMatching++ } else { break } } if (marksMatching == 3) { return true } } return false } fun foundMatchesDiagonally(mark:String) : Boolean { var marksMatching = 0 for (i in 0..2) { if (indicies[i][i].equals(mark)) { marksMatching++ } else { break } if (marksMatching == 3) { return true } } for (i in 2..0) { var j = i if (i == 2) { j = 0 } else if (i == 1) { j = 1 } else { j = 2 } if (indicies[i][j].equals(mark)) { marksMatching++ } else { break } if (marksMatching == 3) { return true } } return false } fun print() { for (i in 0..2) { for (j in 0..2) { if (!indicies[i][j].equals(" ")) { print(" ${indicies[i][j]} ") } else { print(indicies[i][j]) } if (j != 2) { print(" | ") } } println("") if (i != 2) { for (l in 0..8) { print("_") } println("") } } } }
mit
8ee77db05479a274af7b728aaf57a1cb
22.402778
68
0.381009
4.541779
false
false
false
false
spkingr/50-android-kotlin-projects-in-100-days
ProjectBetterPracticeFragment/app/src/main/java/me/liuqingwen/android/projectbetterpracticefragment/CustomDatabase.kt
1
4032
package me.liuqingwen.android.projectbetterpracticefragment import android.arch.persistence.room.* import android.content.Context import android.os.Parcel import android.os.Parcelable /** * Created by Qingwen on 2018-2018-1-2, project: ProjectBetterPracticeFragment. * * @Author: Qingwen * @DateTime: 2018-1-2 * @Package: me.liuqingwen.android.projectbetterpracticefragment in project: ProjectBetterPracticeFragment * * Notice: If you are using this class or file, check it and do some modification. */ class DatabaseHelper private constructor(context: Context) { companion object { @Volatile private var INSTANCE:DatabaseHelper? = null fun getInstance(context: Context) = if (INSTANCE == null) { synchronized(DatabaseHelper::class) { INSTANCE = DatabaseHelper(context) INSTANCE!! } } else INSTANCE!! } private val appDatabase by lazy(LazyThreadSafetyMode.NONE) { Room.databaseBuilder(context, AppDatabase::class.java, "database.db").build() } private val contactDao by lazy(LazyThreadSafetyMode.NONE) { this.appDatabase.contactDao() } fun getContactById(id:Long) = this.contactDao.findContactById(id) fun getAllContacts() = this.contactDao.findAllContacts() fun addContacts(vararg contact:Contact) = this.contactDao.insertContacts(*contact) fun modifyContacts(vararg contact:Contact) = this.contactDao.updateContacts(*contact) fun removeContacts(vararg contact:Contact) = this.contactDao.deleteContacts(*contact) } @Entity(tableName = "contact") data class Contact(@ColumnInfo(name = "id") @PrimaryKey(autoGenerate = true) var id:Long = 0, @ColumnInfo(name = "name") var name:String = "", @ColumnInfo(name = "phone") var phone:String = "", @ColumnInfo(name = "birthday") var birthday: Long = 0, @ColumnInfo(name = "address") var address:String = "", @ColumnInfo(name = "profile") var profile:String = "", @ColumnInfo(name = "is_star") var isStarContact:Boolean = false, @ColumnInfo(name = "information") var info:String? = null): Parcelable { constructor(parcel: Parcel) : this(parcel.readLong(), parcel.readString(), parcel.readString(), parcel.readLong(), parcel.readString(), parcel.readString(), parcel.readByte() != 0.toByte(), parcel.readString()) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeLong(this.id) parcel.writeString(this.name) parcel.writeString(this.phone) parcel.writeLong(this.birthday) parcel.writeString(this.address) parcel.writeString(this.profile) parcel.writeByte(if (this.isStarContact) 1 else 0) parcel.writeString(this.info) } override fun describeContents(): Int = 0 companion object CREATOR : Parcelable.Creator<Contact> { override fun createFromParcel(parcel: Parcel) = Contact(parcel) override fun newArray(size: Int): Array<Contact?> = arrayOfNulls(size) } } @Dao interface ContactDao { @Query("SELECT * FROM contact WHERE id = :arg0") fun findContactById(id:Long):Contact? @Query("SELECT * FROM contact") fun findAllContacts():List<Contact> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertContacts(vararg contact:Contact) @Update(onConflict = OnConflictStrategy.ABORT) fun updateContacts(vararg contact:Contact) @Delete fun deleteContacts(vararg contact:Contact) } @Database(entities = [Contact::class], version = 1, exportSchema = false) abstract class AppDatabase: RoomDatabase() { abstract fun contactDao():ContactDao }
mit
259dbdd4df195ea27ef9fa1a9727d4c2
38.529412
144
0.635169
4.704784
false
false
false
false
ShadwLink/Shadow-Mapper
src/main/java/nl/shadowlink/tools/shadowlib/ide/ItemTimedObject.kt
1
2853
package nl.shadowlink.tools.shadowlib.ide import nl.shadowlink.tools.io.Vector3D import nl.shadowlink.tools.io.Vector4D import nl.shadowlink.tools.shadowlib.utils.GameType import java.io.BufferedWriter import java.io.IOException import java.util.logging.Level import java.util.logging.Logger /** * @author Shadow-Link */ class ItemTimedObject(private val gameType: GameType) : IdeItem() { lateinit var modelName: String var textureName: String? = null var objectCount = 0 var drawDistance: FloatArray = floatArrayOf() var flag1 = 0 var flag2 = 0 var boundsMin = Vector3D(0.0f, 0.0f, 0.0f) var boundsMax = Vector3D(0.0f, 0.0f, 0.0f) var boundsSphere = Vector4D(0.0f, 0.0f, 0.0f, 0.0f) var WDD: String? = null var timedFlags = 0 override fun read(line: String) { var line = line line = line.replace(" ", "") val split = line.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() modelName = split[0] textureName = split[1] drawDistance = FloatArray(1) drawDistance[0] = java.lang.Float.valueOf(split[2]) flag1 = Integer.valueOf(split[3]) flag2 = Integer.valueOf(split[4]) boundsMin = Vector3D( java.lang.Float.valueOf(split[5]), java.lang.Float.valueOf(split[6]), java.lang.Float.valueOf( split[7] ) ) boundsMax = Vector3D( java.lang.Float.valueOf(split[8]), java.lang.Float.valueOf(split[9]), java.lang.Float.valueOf( split[10] ) ) boundsSphere = Vector4D( java.lang.Float.valueOf(split[11]), java.lang.Float.valueOf(split[12]), java.lang.Float.valueOf( split[13] ), java.lang.Float.valueOf(split[14]) ) WDD = split[15] timedFlags = Integer.valueOf(split[16]) } fun save(output: BufferedWriter) { try { var line = modelName line += ", $textureName" line += ", " + drawDistance[0] line += ", $flag1" line += ", $flag2" line += ", " + boundsMin.x line += ", " + boundsMin.y line += ", " + boundsMin.z line += ", " + boundsMax.x line += ", " + boundsMax.y line += ", " + boundsMax.z line += ", " + boundsSphere.x line += ", " + boundsSphere.y line += ", " + boundsSphere.z line += ", " + boundsSphere.w line += ", $WDD" line += ", $timedFlags" output.write( """ $line """.trimIndent() ) println("Line: $line") } catch (ex: IOException) { Logger.getLogger(ItemObject::class.java.name).log(Level.SEVERE, null, ex) } } }
gpl-2.0
888b72fa8c2dc73de464fbc276391da6
32.186047
108
0.546442
3.78382
false
false
false
false
da1z/intellij-community
plugins/git4idea/tests/git4idea/merge/GitMergeProviderTestCase.kt
1
7428
/* * 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 git4idea.merge import com.intellij.openapi.vcs.Executor.* import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.history.VcsRevisionNumber import com.intellij.openapi.vcs.merge.MergeData import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.LineSeparator import com.intellij.vcsUtil.VcsFileUtil import git4idea.branch.GitRebaseParams import git4idea.repo.GitRepository import git4idea.test.* import git4idea.util.GitFileUtils import java.io.File import java.io.FileNotFoundException abstract class GitMergeProviderTestCase : GitPlatformTest() { protected val FILE = "file.txt" protected val FILE_RENAME = "file_rename.txt" protected val FILE_CONTENT = "\nThis\nis\nsome\ncontent\nto\nmake\ngit\ntreat\nthis\nfile\nas\nrename\nrather\nthan\ninsertion\nand\ndeletion\n" protected lateinit var repository: GitRepository override fun runInDispatchThread(): Boolean = true public override fun setUp() { super.setUp() repository = createRepository(projectPath) cd(projectRoot) git("commit --allow-empty -m initial") touch(FILE, "original" + FILE_CONTENT) git("add .") git("commit -m Base") } protected fun `assert all revisions and paths loaded`(branchCurrent: String, branchLast: String) { `assert all revisions loaded`(branchCurrent, branchLast) `assert revision GOOD, path GOOD`(Side.ORIGINAL) `assert revision GOOD, path GOOD`(Side.LAST) `assert revision GOOD, path GOOD`(Side.CURRENT) } protected fun `assert all revisions loaded`(branchCurrent: String, branchLast: String) { `assert merge conflict`() `assert merge provider consistent`() `assert revision`(Side.ORIGINAL, "master") `assert revision`(Side.LAST, "branch-$branchLast") `assert revision`(Side.CURRENT, "branch-$branchCurrent") } protected fun `invoke merge`(branchCurrent: String, branchLast: String) { git("checkout branch-$branchCurrent") git("merge branch-$branchLast", true) repository.update() } protected fun `invoke rebase`(branchCurrent: String, branchLast: String) { git("checkout branch-$branchCurrent") git("rebase branch-$branchLast", true) repository.update() } protected fun `invoke rebase interactive`(branchCurrent: String, branchLast: String) { git("checkout branch-$branchCurrent") doRebaseInteractive(branchLast) repository.update() } // // Impl // private fun doRebaseInteractive(onto: String) { git.setInteractiveRebaseEditor (TestGitImpl.InteractiveRebaseEditor({ it.lines().mapIndexed { i, s -> if (i != 0) s else s.replace("pick", "reword") }.joinToString(LineSeparator.getSystemLineSeparator().separatorString) }, null)) val rebaseParams = GitRebaseParams(null, null, "branch-$onto", true, false) git.rebase(repository, rebaseParams) } protected fun `init branch - change`(branch: String) { doInitBranch(branch, { overwrite(FILE, "modified: $branch" + FILE_CONTENT) }) } protected fun `init branch - rename`(branch: String, newFileName: String = FILE_RENAME) { doInitBranch(branch, { mv(FILE, newFileName) }) } protected fun `init branch - change and rename`(branch: String, newFileName: String = FILE_RENAME) { doInitBranch(branch, { overwrite(FILE, "modified: $branch" + FILE_CONTENT) mv(FILE, newFileName) }) } protected fun `init branch - delete`(branch: String) { doInitBranch(branch, { rm(FILE) }) } private fun doInitBranch(branch: String, vararg changesToCommit: () -> Unit) { cd(repository) git("checkout master") git("checkout -b branch-$branch") changesToCommit.forEachIndexed { index, changes -> changes() git("add .") git("commit -m $branch-$index") } git("checkout master") } protected fun `assert merge conflict`() { val files = git("ls-files --unmerged -z") assertTrue(files.isNotEmpty()) } protected fun `assert merge provider consistent`() { val provider = repository.vcs.mergeProvider val files = getConflictedFiles() files.forEach { val mergeData = provider.loadRevisions(it.toVF()) Side.values().forEach { val revision = mergeData.revision(it) val path = mergeData.filePath(it) val content = mergeData.content(it) if (revision != null && path != null) { val relativePath = VcsFileUtil.relativePath(projectRoot, path) val hash = revision.asString() val actualContent = GitFileUtils.getFileContent(project, projectRoot, hash, relativePath) assertOrderedEquals(content, actualContent) } } } } protected fun `assert revision`(side: Side, revision: String) { val actualHash = getMergeData().revision(side)!!.asString() val expectedHash = git("show-ref -s $revision") assertEquals(expectedHash, actualHash) } protected fun `assert revision GOOD, path GOOD`(side: Side) { val mergeData = getMergeData() assertNotNull(mergeData.revision(side)) assertNotNull(mergeData.filePath(side)) } protected fun `assert revision GOOD, path BAD `(side: Side) { val mergeData = getMergeData() assertNotNull(mergeData.revision(side)) assertNull(mergeData.filePath(side)) } private fun getConflictedFiles(): List<File> { val records = git("ls-files --unmerged -z").split('\u0000') val files = records.map { it.split('\t').last() }.toSortedSet() return files.map { File(projectPath, it) }.toList() } private fun getConflictFile(): File { val files = getConflictedFiles() if (files.size != 1) fail("More than one conflict: $files") return files.first() } private fun getMergeData(): MergeData { return getMergeData(getConflictFile()) } private fun getMergeData(file: File): MergeData { return repository.vcs.mergeProvider.loadRevisions(file.toVF()) } private fun File.toVF(): VirtualFile { return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(this) ?: throw FileNotFoundException(this.path) } private fun MergeData.content(side: Side): ByteArray = when (side) { Side.ORIGINAL -> this.ORIGINAL Side.LAST -> this.LAST Side.CURRENT -> this.CURRENT } private fun MergeData.revision(side: Side): VcsRevisionNumber? = when (side) { Side.ORIGINAL -> this.ORIGINAL_REVISION_NUMBER Side.LAST -> this.LAST_REVISION_NUMBER Side.CURRENT -> this.CURRENT_REVISION_NUMBER } private fun MergeData.filePath(side: Side): FilePath? = when (side) { Side.ORIGINAL -> this.ORIGINAL_FILE_PATH Side.LAST -> this.LAST_FILE_PATH Side.CURRENT -> this.CURRENT_FILE_PATH } protected enum class Side { ORIGINAL, LAST, CURRENT; } }
apache-2.0
2ef05e3f61ecaae7cf5b1c733cc579da
30.608511
146
0.699111
4.227661
false
false
false
false
maiconhellmann/pomodoro
app/src/main/kotlin/br/com/maiconhellmann/pomodoro/ui/pomodoro/PomodoroPresenter.kt
1
3715
package br.com.maiconhellmann.pomodoro.ui.pomodoro import br.com.maiconhellmann.pomodoro.data.DataManager import br.com.maiconhellmann.pomodoro.data.model.Pomodoro import br.com.maiconhellmann.pomodoro.data.model.PomodoroStatus import br.com.maiconhellmann.pomodoro.util.extension.plus import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.lang.kotlin.subscribeBy import rx.schedulers.Schedulers import timber.log.Timber import java.util.* import java.util.concurrent.TimeUnit /** * Created by hellmanss on 9/4/17. */ class PomodoroPresenter(val dataManager: DataManager) : PomodoroContract.Presenter() { var timerSubscription: Subscription? = null var stopTimerSubscription: Subscription? = null val pomodoroTimebox = 1500000L var pomodoro: Pomodoro? = null override fun startTimer() { stopTimerSubscription?.unsubscribe() pomodoro = Pomodoro(0, Date(), Date() + pomodoroTimebox, status = PomodoroStatus.RUNNING) val dif = (pomodoro!!.endDateTime.time - Date().time)/1000 val timerSubscriber = Observable.interval(1, TimeUnit.SECONDS) .take(dif.toInt()) .map { dif - it } timerSubscription = dataManager.savePomodoro(pomodoro!!) .flatMap { Timber.d("flatMap $it") timerSubscriber }.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy ( onNext = { Timber.d("timerSubscription timer: $it") view.updateTimer(it) if(it<= 1){ view.timerFinished() pomodoro?.status = PomodoroStatus.FINISHED savePomodoro(pomodoro!!) } }, onError = { Timber.d("timerSubscription onError: $it") view.showError(it) } ) view.configureStopButton() } private fun savePomodoro(p: Pomodoro) { dataManager.savePomodoro(p) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy ( onCompleted = { Timber.d("savePomodoro onCompleted") }, onNext = { Timber.d("savePomodoro timer: $it") }, onError = { Timber.d("savePomodoro onError: $it") view.showError(it) } ) } override fun stopTimer() { timerSubscription?.unsubscribe() stopTimerSubscription?.unsubscribe() stopTimerSubscription = dataManager.stopRunningPomodoro(pomodoro!!) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy ( onCompleted = { view.configureStartButton() view.showStoppedMessage() }, onError = { view.showError(it) } ) } override fun detachView() { super.detachView() timerSubscription?.unsubscribe() stopTimerSubscription?.unsubscribe() } }
apache-2.0
3b2ab7dbb54d0ff7e2a9a453ee8532e2
33.728972
97
0.512517
5.934505
false
false
false
false
Heiner1/AndroidAPS
medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryDataUTest.kt
1
4162
package info.nightscout.androidaps.plugins.pump.medtronic.data import com.google.gson.Gson import com.google.gson.internal.LinkedTreeMap import com.google.gson.reflect.TypeToken import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.MedtronicPumpHistoryDecoder import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.TempBasalPair import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import org.junit.Before import org.junit.Test import org.mockito.Mock import java.lang.reflect.Type @Suppress("UNCHECKED_CAST") class MedtronicHistoryDataUTest : TestBase() { @Mock lateinit var medtronicPumpStatus: MedtronicPumpStatus @Before fun setUp() { medtronicUtil = MedtronicUtil(aapsLogger, rxBus, rileyLinkUtil, medtronicPumpStatus) decoder = MedtronicPumpHistoryDecoder(aapsLogger, medtronicUtil, byteUtil) } @Test fun createTBRProcessList() { val unitToTest = MedtronicHistoryData( packetInjector, aapsLogger, sp, rh, rxBus, activePlugin, medtronicUtil, decoder, medtronicPumpStatus, pumpSync, pumpSyncStorage ) val gson = Gson() val fileText = ClassLoader.getSystemResource("tbr_data.json").readText() val listType: Type = object : TypeToken<MutableList<PumpHistoryEntry?>?>() {}.type val yourClassList: MutableList<PumpHistoryEntry> = gson.fromJson(fileText, listType) for (pumpHistoryEntry in yourClassList) { val stringObject = pumpHistoryEntry.decodedData["Object"] as LinkedTreeMap<String, Any> val rate: Double = stringObject["insulinRate"] as Double val durationMinutes: Double = stringObject["durationMinutes"] as Double val durationMinutesInt: Int = durationMinutes.toInt() val tmbPair = TempBasalPair(rate, false, durationMinutesInt) pumpHistoryEntry.decodedData.remove("Object") pumpHistoryEntry.addDecodedData("Object", tmbPair) } println("TBR Pre-Process List: " + gson.toJson(yourClassList)) val createTBRProcessList = unitToTest.createTBRProcessList(yourClassList) println("TBR Process List: " + createTBRProcessList.size) for (tempBasalProcessDTO in createTBRProcessList) { println(tempBasalProcessDTO.toTreatmentString()) } } @Test fun createTBRProcessList_SpecialCase() { val unitToTest = MedtronicHistoryData( packetInjector, aapsLogger, sp, rh, rxBus, activePlugin, medtronicUtil, decoder, medtronicPumpStatus, pumpSync, pumpSyncStorage ) val gson = Gson() val fileText = ClassLoader.getSystemResource("tbr_data_special.json").readText() val listType: Type = object : TypeToken<MutableList<PumpHistoryEntry?>?>() {}.type val yourClassList: MutableList<PumpHistoryEntry> = gson.fromJson(fileText, listType) for (pumpHistoryEntry in yourClassList) { val stringObject = pumpHistoryEntry.decodedData["Object"] as LinkedTreeMap<String, Any> val rate: Double = stringObject["insulinRate"] as Double val durationMinutes: Double = stringObject["durationMinutes"] as Double val durationMinutesInt: Int = durationMinutes.toInt() val tmbPair = TempBasalPair(rate, false, durationMinutesInt) pumpHistoryEntry.decodedData.remove("Object") pumpHistoryEntry.addDecodedData("Object", tmbPair) } println("TBR Pre-Process List (Special): " + gson.toJson(yourClassList)) val createTBRProcessList = unitToTest.createTBRProcessList(yourClassList) println("TBR Process List (Special): " + createTBRProcessList.size) for (tempBasalProcessDTO in createTBRProcessList) { println(tempBasalProcessDTO.toTreatmentString()) } } }
agpl-3.0
bf2931c170f64144f85e3490cb494b61
36.495495
102
0.709034
5.176617
false
true
false
false
Adventech/sabbath-school-android-2
features/media/src/main/kotlin/app/ss/media/playback/ui/nowPlaying/NowPlayingViewModel.kt
1
4103
/* * 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 app.ss.media.playback.ui.nowPlaying import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import app.ss.lessons.data.repository.media.MediaRepository import app.ss.media.playback.AudioQueueManager import app.ss.media.playback.PlaybackConnection import app.ss.media.playback.UPDATE_META_DATA import app.ss.media.playback.extensions.id import app.ss.media.playback.extensions.isPlaying import app.ss.media.playback.model.toAudio import app.ss.models.media.AudioFile import com.cryart.sabbathschool.core.extensions.coroutines.flow.stateIn import com.cryart.sabbathschool.core.extensions.intent.lessonIndex import com.cryart.sabbathschool.core.extensions.intent.readIndex import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class NowPlayingViewModel @Inject constructor( private val repository: MediaRepository, val playbackConnection: PlaybackConnection, private val queueManager: AudioQueueManager, private val savedStateHandle: SavedStateHandle ) : ViewModel() { val nowPlayingAudio: StateFlow<AudioFile> = playbackConnection.nowPlaying .map { metaData -> val def = metaData.toAudio() if (metaData.id.isEmpty()) { def } else { repository.findAudioFile(metaData.id) ?: def } } .stateIn(viewModelScope, AudioFile("")) init { generateQueue() } private fun generateQueue() = viewModelScope.launch { val nowPlaying = playbackConnection.nowPlaying.first() val lessonIndex = savedStateHandle.lessonIndex ?: return@launch val playlist = repository.getPlayList(lessonIndex) if (nowPlaying.id.isEmpty()) { setAudioQueue(playlist) } else { val audio = repository.findAudioFile(nowPlaying.id) if (audio?.targetIndex?.startsWith(lessonIndex) == false) { val state = playbackConnection.playbackState.first() setAudioQueue(playlist, state.isPlaying) } } val currentId = queueManager.currentAudio?.id ?: return@launch if (currentId != nowPlaying.id) { playbackConnection.transportControls?.sendCustomAction(UPDATE_META_DATA, null) } } private fun setAudioQueue(playlist: List<AudioFile>, play: Boolean = false) { if (playlist.isEmpty()) return val index = playlist.indexOfFirst { it.targetIndex == savedStateHandle.readIndex } val position = index.coerceAtLeast(0) queueManager.setAudioQueue(playlist, position) playbackConnection.setQueue(playlist, index) if (play) { playbackConnection.playAudios(playlist, position) } } }
mit
775ecbae3954ac41ca5ccfcd93b4c26b
39.22549
90
0.724592
4.716092
false
false
false
false
k9mail/k-9
app/ui/legacy/src/main/java/com/fsck/k9/contacts/ContactPictureLoader.kt
2
4017
package com.fsck.k9.contacts import android.content.Context import android.graphics.Bitmap import android.net.Uri import android.widget.ImageView import androidx.annotation.WorkerThread import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.request.FutureTarget import com.fsck.k9.mail.Address import com.fsck.k9.ui.R import com.fsck.k9.view.RecipientSelectView.Recipient class ContactPictureLoader( private val context: Context, private val contactLetterBitmapCreator: ContactLetterBitmapCreator ) { private val pictureSizeInPx: Int = PICTURE_SIZE.toDip(context) private val backgroundCacheId: String = with(contactLetterBitmapCreator.config) { if (hasDefaultBackgroundColor) defaultBackgroundColor.toString() else "*" } fun setContactPicture(imageView: ImageView, address: Address) { Glide.with(imageView.context) .load(createContactImage(address, contactLetterOnly = false)) .diskCacheStrategy(DiskCacheStrategy.NONE) .dontAnimate() .into(imageView) } fun setContactPicture(imageView: ImageView, recipient: Recipient) { val contactPictureUri = recipient.photoThumbnailUri if (contactPictureUri != null) { setContactPicture(imageView, contactPictureUri) } else { setFallbackPicture(imageView, recipient.address) } } private fun setContactPicture(imageView: ImageView, contactPictureUri: Uri) { Glide.with(imageView.context) .load(contactPictureUri) .placeholder(R.drawable.ic_contact_picture) .error(R.drawable.ic_contact_picture) .diskCacheStrategy(DiskCacheStrategy.NONE) .dontAnimate() .into(imageView) } private fun setFallbackPicture(imageView: ImageView, address: Address) { Glide.with(imageView.context) .load(createContactImage(address, contactLetterOnly = true)) .diskCacheStrategy(DiskCacheStrategy.NONE) .dontAnimate() .into(imageView) } @WorkerThread fun getContactPicture(recipient: Recipient): Bitmap? { val contactPictureUri = recipient.photoThumbnailUri val address = recipient.address return if (contactPictureUri != null) { getContactPicture(contactPictureUri) } else { getFallbackPicture(address) } } private fun getContactPicture(contactPictureUri: Uri): Bitmap? { return Glide.with(context) .asBitmap() .load(contactPictureUri) .error(R.drawable.ic_contact_picture) .diskCacheStrategy(DiskCacheStrategy.NONE) .dontAnimate() .submit(pictureSizeInPx, pictureSizeInPx) .getOrNull() } private fun getFallbackPicture(address: Address): Bitmap? { return Glide.with(context) .asBitmap() .load(createContactImage(address, contactLetterOnly = true)) .diskCacheStrategy(DiskCacheStrategy.NONE) .dontAnimate() .submit(pictureSizeInPx, pictureSizeInPx) .getOrNull() } private fun createContactImage(address: Address, contactLetterOnly: Boolean): ContactImage { return ContactImage( contactLetterOnly = contactLetterOnly, backgroundCacheId = backgroundCacheId, contactLetterBitmapCreator = contactLetterBitmapCreator, address = address ) } private fun <T> FutureTarget<T>.getOrNull(): T? { return try { get() } catch (e: Exception) { null } } private fun Int.toDip(context: Context): Int = (this * context.resources.displayMetrics.density).toInt() companion object { /** * Resize the pictures to the following value (device-independent pixels). */ private const val PICTURE_SIZE = 40 } }
apache-2.0
5c9e21cbd3dc42e98f5f973dd66c024c
33.333333
108
0.659696
4.990062
false
false
false
false
abigpotostew/easypolitics
ui/src/main/kotlin/bz/stew/bracken/ui/common/query/BillRestQueryUrl.kt
1
936
package bz.stew.bracken.ui.common.query import bz.stew.bracken.ui.context.PageContext /** * Created by stew on 6/28/17. */ class BillRestQueryUrl( pageContext: PageContext, val congress: Int?, val orderBy: OrderBy = OrderBy.DESCENDING_DATE, val limit: Int = 200, val offset: Int = 0) : BillDataServiceEndpoint(pageContext, BillServiceEndpointTypes.MULTI_BILL) { override fun getSearchParameters(): String { val congress: String = congress?.toString() ?: "" return "?congress=$congress&order_by=$orderBy&limit=$limit&offset=$offset" } override fun toString(): String { return getUrl() } fun nextPage(): BillRestQueryUrl { val nextOffset = limit + offset return BillRestQueryUrl( pageContext = this.context, congress = congress, orderBy = orderBy, limit = limit, offset = nextOffset) } }
apache-2.0
8353f8b17d0e9bfad69d7ba78a7619a5
27.393939
102
0.636752
4.235294
false
false
false
false
PolymerLabs/arcs
javatests/arcs/showcase/queries/ProductClassifier.kt
1
2660
package arcs.showcase.queries import arcs.jvm.host.TargetHost /** * This particle is an example of using handles with associated queries. * It performs three different queries which select products based on values provided at runtime: * - an arbitrary double [CHEAP_PRICE] * - an arbitrary double [EXPENSIVE_PRICE], and * - an arbitrary string [SEARCH_NAME]. * * It filters dummy data from [ProductDatabase], but could be used with any other source of data and * performs a simple labelling task showing how data can be combined from different handles without * loading the whole database into the Particle. */ @TargetHost(arcs.android.integration.IntegrationHost::class) class ProductClassifier : AbstractProductClassifier() { override fun onReady() { // This map from product names to 'tags' accumulates the output that this particle provides. val productDescriptions = mutableMapOf<String, MutableSet<String>>() // Here, 'cheap' products are defined as products from the [cheapProducts] handle that have a // price less than or equal to [CHEAP_PRICE]. // i.e. `price <= ?` see the definition in [queries.arcs] handles.cheapProducts.query(CHEAP_PRICE).forEach { productDescriptions.getOrPut(it.name) { mutableSetOf() }.add("cheap") } // Here, 'expensive' products are defined as products from the [expensiveProducts] handle that have a // price greater than or equal to [EXPENSIVE_PRICE]. // i.e. `price >= ?` see the definition in [queries.arcs] handles.expensiveProducts.query(EXPENSIVE_PRICE).forEach { productDescriptions.getOrPut(it.name) { mutableSetOf() }.add("expensive") } // Here, 'named' products are defined as products from the [namedProducts] handle that have the // name equal to [SEARCH_NAME]. // i.e. `name == ?` see the definition in [queries.arcs] handles.namedProducts.query(SEARCH_NAME).forEach { productDescriptions.getOrPut(it.name) { mutableSetOf() }.add("selected") } // This renders the 'tags' and product names as strings and stores them using the // [productDescriptions] handle. handles.productDescriptions.storeAll( productDescriptions.map { (name, tags) -> ProductDescription(description = "$name: ${tags.joinToString()}") } ) } companion object { /** * These constants are arbitrary values to show that query arguments are provided at runtime. * They do not actually need to be constants and could be changed at runtime. */ private const val CHEAP_PRICE = 3.0 private const val EXPENSIVE_PRICE = 25.0 private const val SEARCH_NAME = "Pencil" } }
bsd-3-clause
359682d07c19b84281d0e67852bce29a
43.333333
105
0.710526
4.269663
false
false
false
false
peterholak/graphql-ws-kotlin
example/src/main/kotlin/net/holak/graphql/example/Resolvers.kt
1
1807
@file:Suppress("unused") package net.holak.graphql.example import com.coxautodev.graphql.tools.GraphQLMutationResolver import com.coxautodev.graphql.tools.GraphQLQueryResolver import com.coxautodev.graphql.tools.GraphQLSubscriptionResolver import graphql.schema.DataFetchingEnvironment import net.holak.graphql.ws.Publisher class Store(var currentMessage: Message = Message("Hello world")) class Message(val text: String) { fun randomNumber() = Math.random().times(100).toInt() } class QueryResolver(val store: Store) : GraphQLQueryResolver { fun currentMessage() = store.currentMessage } class MutationResolver(val store: Store, val publisher: Publisher) : GraphQLMutationResolver { fun setMessage(text: String): Message { store.currentMessage = Message(text) publisher.publish("messageChanged", null) return store.currentMessage } } @Suppress("UNUSED_PARAMETER") class SubscriptionResolver(val store: Store) : GraphQLSubscriptionResolver { fun messageChanged(): Message { return store.currentMessage } fun textPublished(env: DataFetchingEnvironment): String { return env.getContext<String>() } fun multiplyPublishedText(by: Int, env: DataFetchingEnvironment): Int { val message = env.getContext<String>().toIntOrNull() ?: return 0 return message * by } fun filteredPublishedText(lessThan: Int, env: DataFetchingEnvironment): Int { return env.getContext<String>().toInt() } fun complexInput(input: VariousTypes): Boolean { return false } } data class VariousTypes( val id: String, val star: Star, val listOfStrings: List<String>, val number: Int ) enum class Star { Wars, Trek, Gate, Craft, Control, Citizen }
mit
8262a26d4a8f66f6931ce170d009a5d9
25.985075
94
0.70891
4.428922
false
false
false
false
gitlui/TDD-Katas
primeFactorsKata/src/PrimeFactorsTest.kt
1
1168
import org.junit.Test import kotlin.test.assertEquals class PrimeFactorsTest { @Test fun factorialTests() { assertEquals(listOf(1), factorialsOf(1)) assertEquals(listOf(2), factorialsOf(2)) assertEquals(listOf(3), factorialsOf(3)) assertEquals(listOf(2, 2), factorialsOf(4)) assertEquals(listOf(5), factorialsOf(5)) assertEquals(listOf(2, 3), factorialsOf(6)) assertEquals(listOf(2, 2, 2), factorialsOf(8)) assertEquals(listOf(3, 3), factorialsOf(9)) assertEquals(listOf(3, 5), factorialsOf(15)) assertEquals(listOf(3, 3, 3), factorialsOf(27)) assertEquals(listOf(5, 5), factorialsOf(25)) assertEquals(listOf(2, 3, 3, 5, 7, 13, 17), factorialsOf(2 * 3 * 3 * 5 * 7 * 13 * 17)) } private fun factorialsOf(n: Int): List<Int> { if (n <= 1) return listOf(n) val factorials = ArrayList<Int>() var remaining = n for (divisor in 2..remaining) while (remaining % divisor == 0) { factorials.add(divisor) remaining /= divisor } return factorials } }
gpl-3.0
56cd95630996755a7314c4458aca5f67
30.594595
94
0.585616
4.069686
false
true
false
false
theScrabi/NewPipe
app/src/main/java/org/schabi/newpipe/database/subscription/SubscriptionDAO.kt
3
3795
package org.schabi.newpipe.database.subscription import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Maybe import org.schabi.newpipe.database.BasicDAO @Dao abstract class SubscriptionDAO : BasicDAO<SubscriptionEntity> { @Query("SELECT COUNT(*) FROM subscriptions") abstract fun rowCount(): Flowable<Long> @Query("SELECT * FROM subscriptions WHERE service_id = :serviceId") abstract override fun listByService(serviceId: Int): Flowable<List<SubscriptionEntity>> @Query("SELECT * FROM subscriptions ORDER BY name COLLATE NOCASE ASC") abstract override fun getAll(): Flowable<List<SubscriptionEntity>> @Query( """ SELECT * FROM subscriptions WHERE name LIKE '%' || :filter || '%' ORDER BY name COLLATE NOCASE ASC """ ) abstract fun getSubscriptionsFiltered(filter: String): Flowable<List<SubscriptionEntity>> @Query( """ SELECT * FROM subscriptions s LEFT JOIN feed_group_subscription_join fgs ON s.uid = fgs.subscription_id WHERE (fgs.subscription_id IS NULL OR fgs.group_id = :currentGroupId) ORDER BY name COLLATE NOCASE ASC """ ) abstract fun getSubscriptionsOnlyUngrouped( currentGroupId: Long ): Flowable<List<SubscriptionEntity>> @Query( """ SELECT * FROM subscriptions s LEFT JOIN feed_group_subscription_join fgs ON s.uid = fgs.subscription_id WHERE (fgs.subscription_id IS NULL OR fgs.group_id = :currentGroupId) AND s.name LIKE '%' || :filter || '%' ORDER BY name COLLATE NOCASE ASC """ ) abstract fun getSubscriptionsOnlyUngroupedFiltered( currentGroupId: Long, filter: String ): Flowable<List<SubscriptionEntity>> @Query("SELECT * FROM subscriptions WHERE url LIKE :url AND service_id = :serviceId") abstract fun getSubscriptionFlowable(serviceId: Int, url: String): Flowable<List<SubscriptionEntity>> @Query("SELECT * FROM subscriptions WHERE url LIKE :url AND service_id = :serviceId") abstract fun getSubscription(serviceId: Int, url: String): Maybe<SubscriptionEntity> @Query("SELECT * FROM subscriptions WHERE uid = :subscriptionId") abstract fun getSubscription(subscriptionId: Long): SubscriptionEntity @Query("DELETE FROM subscriptions") abstract override fun deleteAll(): Int @Query("DELETE FROM subscriptions WHERE url LIKE :url AND service_id = :serviceId") abstract fun deleteSubscription(serviceId: Int, url: String): Int @Query("SELECT uid FROM subscriptions WHERE url LIKE :url AND service_id = :serviceId") internal abstract fun getSubscriptionIdInternal(serviceId: Int, url: String): Long? @Insert(onConflict = OnConflictStrategy.IGNORE) internal abstract fun silentInsertAllInternal(entities: List<SubscriptionEntity>): List<Long> @Transaction open fun upsertAll(entities: List<SubscriptionEntity>): List<SubscriptionEntity> { val insertUidList = silentInsertAllInternal(entities) insertUidList.forEachIndexed { index: Int, uidFromInsert: Long -> val entity = entities[index] if (uidFromInsert != -1L) { entity.uid = uidFromInsert } else { val subscriptionIdFromDb = getSubscriptionIdInternal(entity.serviceId, entity.url) ?: throw IllegalStateException("Subscription cannot be null just after insertion.") entity.uid = subscriptionIdFromDb update(entity) } } return entities } }
gpl-3.0
eeae78ef1cbd5a53c2b205c54f564e99
33.816514
105
0.686957
4.915803
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/detail/PostDayViewsMapper.kt
1
4755
package org.wordpress.android.ui.stats.refresh.lists.detail import org.wordpress.android.R import org.wordpress.android.fluxc.model.stats.PostDetailStatsModel.Day import org.wordpress.android.fluxc.network.utils.StatsGranularity.DAYS import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.BarChartItem import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.BarChartItem.Bar import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ValueItem import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ValueItem.State import org.wordpress.android.ui.stats.refresh.utils.HUNDRED_THOUSAND import org.wordpress.android.ui.stats.refresh.utils.StatsDateFormatter import org.wordpress.android.ui.stats.refresh.utils.StatsUtils import org.wordpress.android.util.text.PercentFormatter import org.wordpress.android.viewmodel.ResourceProvider import java.math.RoundingMode.HALF_UP import javax.inject.Inject class PostDayViewsMapper @Inject constructor( private val resourceProvider: ResourceProvider, private val statsUtils: StatsUtils, private val statsDateFormatter: StatsDateFormatter, private val percentFormatter: PercentFormatter ) { fun buildTitle( selectedItem: Day, previousItem: Day?, isLast: Boolean ): ValueItem { val value = selectedItem.count val previousValue = previousItem?.count val positive = value >= (previousValue ?: 0) val change = buildChange(previousValue, value, positive, isFormattedNumber = true) val unformattedChange = buildChange(previousValue, value, positive, isFormattedNumber = false) val state = when { isLast -> State.NEUTRAL positive -> State.POSITIVE else -> State.NEGATIVE } return ValueItem( value = statsUtils.toFormattedString(value, HUNDRED_THOUSAND), unit = R.string.stats_views, isFirst = true, change = change, state = state, contentDescription = resourceProvider.getString( R.string.stats_overview_content_description, value, resourceProvider.getString(R.string.stats_views), statsDateFormatter.printDate(selectedItem.period), unformattedChange ?: "" ) ) } private fun buildChange( previousValue: Int?, value: Int, positive: Boolean, isFormattedNumber: Boolean ): String? { return previousValue?.let { val difference = value - previousValue val percentage = when (previousValue) { value -> "0" 0 -> "∞" else -> { val percentageValue = difference.toFloat() / previousValue percentFormatter.format(value = percentageValue, rounding = HALF_UP) } } val formattedDifference = mapIntToString(difference, isFormattedNumber) if (positive) { resourceProvider.getString(R.string.stats_traffic_increase, formattedDifference, percentage) } else { resourceProvider.getString(R.string.stats_traffic_change, formattedDifference, percentage) } } } private fun mapIntToString(value: Int, isFormattedNumber: Boolean): String { return when (isFormattedNumber) { true -> statsUtils.toFormattedString(value) false -> value.toString() } } fun buildChart( dayViews: List<Day>, selectedDay: String?, onBarSelected: (String?) -> Unit, onBarChartDrawn: (visibleBarCount: Int) -> Unit ): List<BlockListItem> { val chartItems = dayViews.map { day -> Bar( statsDateFormatter.printGranularDate(day.period, DAYS), day.period, day.count ) } val result = mutableListOf<BlockListItem>() val contentDescriptions = statsUtils.getBarChartEntryContentDescriptions( R.string.stats_views, chartItems ) result.add( BarChartItem( chartItems, selectedItem = selectedDay, onBarSelected = onBarSelected, onBarChartDrawn = onBarChartDrawn, entryContentDescriptions = contentDescriptions ) ) return result } }
gpl-2.0
37f95e4e0249b3bdcca373e0f755f8ef
38.280992
108
0.623396
5.155098
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/ui/reader/usecases/ReaderFetchRelatedPostsUseCaseTest.kt
1
2925
package org.wordpress.android.ui.reader.usecases import androidx.arch.core.executor.testing.InstantTaskExecutorRule import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.InternalCoroutinesApi import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import org.wordpress.android.models.ReaderPost import org.wordpress.android.test import org.wordpress.android.ui.reader.ReaderEvents.RelatedPostsUpdated import org.wordpress.android.ui.reader.actions.ReaderPostActionsWrapper import org.wordpress.android.ui.reader.usecases.ReaderFetchRelatedPostsUseCase.FetchRelatedPostsState import org.wordpress.android.ui.reader.usecases.ReaderFetchRelatedPostsUseCase.FetchRelatedPostsState.Failed import org.wordpress.android.util.NetworkUtilsWrapper @InternalCoroutinesApi @ExperimentalCoroutinesApi @RunWith(MockitoJUnitRunner::class) class ReaderFetchRelatedPostsUseCaseTest { @Rule @JvmField val rule = InstantTaskExecutorRule() lateinit var useCase: ReaderFetchRelatedPostsUseCase @Mock lateinit var readerPostActionsWrapper: ReaderPostActionsWrapper @Mock lateinit var networkUtilsWrapper: NetworkUtilsWrapper @Mock lateinit var readerPost: ReaderPost @Before fun setup() { useCase = ReaderFetchRelatedPostsUseCase(networkUtilsWrapper, readerPostActionsWrapper) whenever(networkUtilsWrapper.isNetworkAvailable()).thenReturn(true) } @Test fun `given no network, when related posts are fetched, then no network is returned`() = test { whenever(networkUtilsWrapper.isNetworkAvailable()).thenReturn(false) val result = useCase.fetchRelatedPosts(readerPost) assertThat(result).isEqualTo(Failed.NoNetwork) } @Test fun `given related posts fetch succeeds, when related posts are fetched, then success is returned`() = test { val successEvent = RelatedPostsUpdated(readerPost, mock(), mock(), true) whenever(readerPostActionsWrapper.requestRelatedPosts(readerPost)) .then { useCase.onRelatedPostUpdated(successEvent) } val result = useCase.fetchRelatedPosts(readerPost) assertThat(result).isInstanceOf(FetchRelatedPostsState.Success::class.java) } @Test fun `given related posts fetch fails, when related posts are fetched, then request failed is returned`() = test { val failedEvent = RelatedPostsUpdated(readerPost, mock(), mock(), false) whenever(readerPostActionsWrapper.requestRelatedPosts(readerPost)) .then { useCase.onRelatedPostUpdated(failedEvent) } val result = useCase.fetchRelatedPosts(readerPost) assertThat(result).isEqualTo(Failed.RequestFailed) } }
gpl-2.0
83583ad0bba9e06a456fff8b06f984d1
39.625
117
0.783932
5.167845
false
true
false
false
Yubico/yubioath-android
app/src/main/kotlin/com/yubico/yubioath/ui/main/OathViewModel.kt
1
5052
package com.yubico.yubioath.ui.main import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import com.yubico.yubikitold.application.oath.OathType import com.yubico.yubioath.client.Code import com.yubico.yubioath.client.Credential import com.yubico.yubioath.client.OathClient import com.yubico.yubioath.ui.BaseViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch class OathViewModel : BaseViewModel() { companion object { const val NDEF_KEY = "NFC:NDEF" private const val MODHEX = "cbdefghijklnrtuv" val CODE_PATTERN = """(\d{6,8})|(!?[1-8$MODHEX${MODHEX.toUpperCase()}]{4}[$MODHEX]{28,60})""".toRegex() } private var credsMap : MutableMap<Credential, Code?> = mutableMapOf() private val _creds = MutableLiveData<Map<Credential, Code?>>() val creds: LiveData<Map<Credential, Code?>> = _creds private val _searchFilter = MutableLiveData<String>().apply { postValue("") } val searchFilter: LiveData<String> = _searchFilter fun setSearchFilter(value: String) { _searchFilter.value = value } private val _filteredCreds = MediatorLiveData<Map<Credential, Code?>>().apply { addSource(creds) { value = creds.value.orEmpty().filterKeys { it.key.contains(searchFilter.value.orEmpty(), true) } } addSource(searchFilter) { value = creds.value.orEmpty().filterKeys { it.key.contains(searchFilter.value.orEmpty(), true) } } } val filteredCreds : LiveData<Map<Credential, Code?>> = _filteredCreds private var refreshJob: Job? = null var selectedItem: Credential? = null var ndefCode: Code? = null fun calculate(credential: Credential) = requestClient(credential.deviceId) { val code = it.calculate(credential, currentTime(true)) Log.d("yubioath", "Calculated code: $credential: $code") credsMap[credential] = code _creds.postValue(credsMap) scheduleRefresh() } fun delete(credential: Credential) = requestClient(credential.deviceId) { it.delete(credential) credsMap - credential _creds.postValue(credsMap) Log.d("yubioath", "Deleted credential: $credential") scheduleRefresh() } fun insertCredential(credential: Credential, code: Code?) { val deviceInfo = deviceInfo.value!! if (deviceInfo.id.isNotEmpty() && credential.deviceId != deviceInfo.id) throw IllegalArgumentException("Credential belongs to different device!") credsMap[credential] = code _creds.postValue(credsMap) scheduleRefresh() } fun clearCredentials() { val deviceInfo = deviceInfo.value!! selectedItem = null credsMap.clear() // If we have a persistent device, we try to re-read the codes and update instead of clearing. if (deviceInfo.persistent) { launch(Dispatchers.Main) { val refreshCreds = requestClient(deviceInfo.id) {} delay(100) //If we can't get the device in 100ms, give up and notify credListener. if (refreshCreds.isActive) { _creds.postValue(mapOf()) scheduleRefresh() } } } else { clearDevice() _creds.postValue(mapOf()) scheduleRefresh() } } private fun currentTime(boost: Boolean = false) = System.currentTimeMillis() + if (!boost && deviceInfo.value!!.persistent) 0 else 10000 fun scheduleRefresh() { refreshJob?.cancel() if (creds.value.isNullOrEmpty()) { val info = deviceInfo.value if (info != null && !info.persistent) { mutableNeedsDevice.postValue(true) } } else { val now = System.currentTimeMillis() //Needs to use real time, not adjusted for non-persistent. val deadline = creds.value.orEmpty().filterKeys { it.type == OathType.TOTP && !it.touch }.values.map { it?.validUntil ?: -1 }.filter { it > now }.min() if (deadline != null) { Log.d("yubioath", "Refresh credentials in ${deadline - now}ms") refreshJob = launch(Dispatchers.Main) { delay(deadline - now) mutableNeedsDevice.value = true } } } } fun stopRefresh() { refreshJob?.cancel() refreshJob = null } override suspend fun useClient(client: OathClient) { credsMap = client.refreshCodes(currentTime(), credsMap).toMutableMap() ndefCode?.let { credsMap[Credential(client.deviceInfo.id, NDEF_KEY, null, false)] = it } ndefCode = null _creds.postValue(credsMap) selectedItem?.let { if (client.deviceInfo.id != it.deviceId) { selectedItem = null } } scheduleRefresh() } }
bsd-2-clause
25907204d63fb7e430e31de7b807fe4a
36.992481
163
0.631433
4.547255
false
false
false
false
MER-GROUP/intellij-community
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/ScopeVariablesGroup.kt
3
3897
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.xdebugger.XDebuggerBundle import com.intellij.xdebugger.frame.XCompositeNode import com.intellij.xdebugger.frame.XValueChildrenList import com.intellij.xdebugger.frame.XValueGroup import org.jetbrains.concurrency.done import org.jetbrains.concurrency.rejected class ScopeVariablesGroup(val scope: Scope, parentContext: VariableContext, callFrame: CallFrame?) : XValueGroup(scope.createScopeNodeName()) { private val context = createVariableContext(scope, parentContext, callFrame) private val callFrame = if (scope.type == Scope.Type.LOCAL) callFrame else null override fun isAutoExpand() = scope.type == Scope.Type.LOCAL || scope.type == Scope.Type.CATCH override fun getComment(): String? { val className = scope.description return if ("Object" == className) null else className } override fun computeChildren(node: XCompositeNode) { val promise = processScopeVariables(scope, node, context, callFrame == null) if (callFrame == null) { return } promise .done(node) { callFrame.receiverVariable .done(node) { node.addChildren(if (it == null) XValueChildrenList.EMPTY else XValueChildrenList.singleton(VariableView(it, context)), true) } .rejected(node) { node.addChildren(XValueChildrenList.EMPTY, true) } } } } fun createAndAddScopeList(node: XCompositeNode, scopes: List<Scope>, context: VariableContext, callFrame: CallFrame?) { val list = XValueChildrenList(scopes.size) for (scope in scopes) { list.addTopGroup(ScopeVariablesGroup(scope, context, callFrame)) } node.addChildren(list, true) } fun createVariableContext(scope: Scope, parentContext: VariableContext, callFrame: CallFrame?): VariableContext { if (callFrame == null || scope.type == Scope.Type.LIBRARY) { // functions scopes - we can watch variables only from global scope return ParentlessVariableContext(parentContext, scope, scope.type == Scope.Type.GLOBAL) } else { return VariableContextWrapper(parentContext, scope) } } private class ParentlessVariableContext(parentContext: VariableContext, scope: Scope, private val watchableAsEvaluationExpression: Boolean) : VariableContextWrapper(parentContext, scope) { override fun watchableAsEvaluationExpression() = watchableAsEvaluationExpression override fun getParent() = null } private fun Scope.createScopeNodeName(): String { when (type) { Scope.Type.GLOBAL -> return XDebuggerBundle.message("scope.global") Scope.Type.LOCAL -> return XDebuggerBundle.message("scope.local") Scope.Type.WITH -> return XDebuggerBundle.message("scope.with") Scope.Type.CLOSURE -> return XDebuggerBundle.message("scope.closure") Scope.Type.CATCH -> return XDebuggerBundle.message("scope.catch") Scope.Type.LIBRARY -> return XDebuggerBundle.message("scope.library") Scope.Type.INSTANCE -> return XDebuggerBundle.message("scope.instance") Scope.Type.CLASS -> return XDebuggerBundle.message("scope.class") Scope.Type.BLOCK -> return XDebuggerBundle.message("scope.block") Scope.Type.SCRIPT -> return XDebuggerBundle.message("scope.script") Scope.Type.UNKNOWN -> return XDebuggerBundle.message("scope.unknown") else -> throw IllegalArgumentException(type.name) } }
apache-2.0
d02d67ba847235eee962d5e843b964f0
41.835165
188
0.752887
4.595519
false
false
false
false
hermantai/samples
kotlin/developer-android/sunflower-main/app/src/main/java/com/google/samples/apps/sunflower/data/UnsplashPagingSource.kt
1
1567
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.sunflower.data import androidx.paging.PagingSource import com.google.samples.apps.sunflower.api.UnsplashService private const val UNSPLASH_STARTING_PAGE_INDEX = 1 class UnsplashPagingSource( private val service: UnsplashService, private val query: String ) : PagingSource<Int, UnsplashPhoto>() { override suspend fun load(params: LoadParams<Int>): LoadResult<Int, UnsplashPhoto> { val page = params.key ?: UNSPLASH_STARTING_PAGE_INDEX return try { val response = service.searchPhotos(query, page, params.loadSize) val photos = response.results LoadResult.Page( data = photos, prevKey = if (page == UNSPLASH_STARTING_PAGE_INDEX) null else page - 1, nextKey = if (page == response.totalPages) null else page + 1 ) } catch (exception: Exception) { LoadResult.Error(exception) } } }
apache-2.0
b122102870121a3b7bbc6b52fe00856d
35.44186
88
0.683472
4.34072
false
false
false
false
square/picasso
picasso-sample/src/main/java/com/example/picasso/SampleListDetailActivity.kt
1
3262
/* * Copyright (C) 2022 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.picasso import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView.OnItemClickListener import android.widget.ImageView import android.widget.ListView import android.widget.TextView import androidx.fragment.app.Fragment class SampleListDetailActivity : PicassoSampleActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { supportFragmentManager .beginTransaction() .add(R.id.sample_content, ListFragment.newInstance()) .commit() } } fun showDetails(url: String) { supportFragmentManager .beginTransaction() .replace(R.id.sample_content, DetailFragment.newInstance(url)) .addToBackStack(null) .commit() } class ListFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val activity = activity as SampleListDetailActivity val adapter = SampleListDetailAdapter(activity) val listView = LayoutInflater.from(activity) .inflate(R.layout.sample_list_detail_list, container, false) as ListView listView.adapter = adapter listView.setOnScrollListener(SampleScrollListener(activity)) listView.onItemClickListener = OnItemClickListener { _, _, position, _ -> val url = adapter.getItem(position) activity.showDetails(url) } return listView } companion object { fun newInstance(): ListFragment { return ListFragment() } } } class DetailFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val activity = activity as SampleListDetailActivity val view = LayoutInflater.from(activity) .inflate(R.layout.sample_list_detail_detail, container, false) val urlView = view.findViewById<TextView>(R.id.url) val imageView = view.findViewById<ImageView>(R.id.photo) val url = requireArguments().getString(KEY_URL) urlView.text = url PicassoInitializer.get() .load(url) .fit() .tag(activity) .into(imageView) return view } companion object { private const val KEY_URL = "picasso:url" fun newInstance(url: String): DetailFragment { return DetailFragment().apply { arguments = Bundle().apply { putString(KEY_URL, url) } } } } } }
apache-2.0
2159a31bbd90d3ecb8f4e47e1705c371
28.654545
80
0.686695
4.640114
false
false
false
false
DarrenAtherton49/droid-community-app
app/src/main/kotlin/com/darrenatherton/droidcommunity/features/feed/FeedPresenter.kt
1
2211
package com.darrenatherton.droidcommunity.features.feed import android.util.Log import com.darrenatherton.droidcommunity.base.presentation.BasePresenter import com.darrenatherton.droidcommunity.base.presentation.BaseView import com.darrenatherton.droidcommunity.common.injection.scope.PerScreen import com.darrenatherton.droidcommunity.domain.usecase.GetFeedSubscriptions import javax.inject.Inject @PerScreen class FeedPresenter @Inject constructor(private val getSubscriptions: GetFeedSubscriptions) : BasePresenter<FeedPresenter.View>() { //=================================================================================== // View attach/detach //=================================================================================== override fun onViewAttached() { loadFeed() } override fun onViewDetached() { } //=================================================================================== // Domain actions to execute //=================================================================================== private fun loadFeed() { //todo show/hide progress/retry etc getSubscriptions.execute( onNext = { it.forEach { Log.d("darren", it.title) } }, onError = { Log.d("darren", "ERROR: " + it.message ) }, onCompleted = { Log.d("darren", "onCompleted") } ) } //=================================================================================== // Actions forwarded from view //=================================================================================== internal fun onFeedItemClicked(subscriptionFeedItem: SubscriptionFeedItem) { performViewAction { showSubscriptionDetail(subscriptionFeedItem) } } //=================================================================================== // View definition //=================================================================================== interface View : BaseView { fun showSubscriptions(items: List<SubscriptionViewItem>) fun showSubscriptionDetail(subscriptionFeedItem: SubscriptionFeedItem) } }
mit
fafc83422177e12e6aedf5f7f4641fc5
37.137931
91
0.468566
7.086538
false
false
false
false
voxelcarrot/Warren
src/main/kotlin/engineer/carrot/warren/warren/handler/rpl/Rpl332Handler.kt
2
1027
package engineer.carrot.warren.warren.handler.rpl import engineer.carrot.warren.kale.IKaleHandler import engineer.carrot.warren.kale.irc.message.rfc1459.rpl.Rpl332Message import engineer.carrot.warren.warren.loggerFor import engineer.carrot.warren.warren.state.CaseMappingState import engineer.carrot.warren.warren.state.JoinedChannelsState class Rpl332Handler(val channelsState: JoinedChannelsState, val caseMappingState: CaseMappingState) : IKaleHandler<Rpl332Message> { private val LOGGER = loggerFor<Rpl332Handler>() override val messageType = Rpl332Message::class.java override fun handle(message: Rpl332Message, tags: Map<String, String?>) { val channel = channelsState[message.channel] val topic = message.topic if (channel == null) { LOGGER.warn("got a topic for a channel we don't think we're in, not doing anything: $message") return } LOGGER.debug("channel topic for ${channel.name}: $topic") channel.topic = topic } }
isc
ed41effd7e2aa6d1c7c6ea54d23bacbe
34.413793
131
0.734177
4.297071
false
false
false
false
mdanielwork/intellij-community
platform/credential-store/src/linuxSecretLibrary.kt
1
6569
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.credentialStore import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.io.jna.DisposableMemory import com.sun.jna.Library import com.sun.jna.Native import com.sun.jna.Pointer import com.sun.jna.Structure import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import java.util.function.Supplier private const val SECRET_SCHEMA_NONE = 0 private const val SECRET_SCHEMA_ATTRIBUTE_STRING = 0 // explicitly create pointer to be explicitly dispose it to avoid sensitive data in the memory internal fun stringPointer(data: ByteArray, clearInput: Boolean = false): DisposableMemory { val pointer = DisposableMemory(data.size + 1L) pointer.write(0, data, 0, data.size) pointer.setByte(data.size.toLong(), 0.toByte()) if (clearInput) { data.fill(0) } return pointer } // we use default collection, it seems no way to use custom internal class SecretCredentialStore(schemeName: String) : CredentialStore { private val serviceAttributeNamePointer by lazy { stringPointer("service".toByteArray()) } private val accountAttributeNamePointer by lazy { stringPointer("account".toByteArray()) } companion object { // no need to load lazily - if store created, then it will be used // and for clients better to get error earlier, in creation place private val library = Native.loadLibrary("secret-1", SecretLibrary::class.java) } private val scheme by lazy { library.secret_schema_new(schemeName, SECRET_SCHEMA_NONE, serviceAttributeNamePointer, SECRET_SCHEMA_ATTRIBUTE_STRING, accountAttributeNamePointer, SECRET_SCHEMA_ATTRIBUTE_STRING, null) } override fun get(attributes: CredentialAttributes): Credentials? { return CompletableFuture.supplyAsync(Supplier { checkError("secret_password_lookup_sync") { errorRef -> val serviceNamePointer = stringPointer(attributes.serviceName.toByteArray()) if (attributes.userName == null) { library.secret_password_lookup_sync(scheme, null, errorRef, serviceAttributeNamePointer, serviceNamePointer, null)?.let { // Secret Service doesn't allow to get attributes, so, we store joined data return@Supplier splitData(it) } } else { library.secret_password_lookup_sync(scheme, null, errorRef, serviceAttributeNamePointer, serviceNamePointer, accountAttributeNamePointer, stringPointer(attributes.userName!!.toByteArray()), null)?.let { return@Supplier splitData(it) } } } }, AppExecutorUtil.getAppExecutorService()) .get(30 /* on Linux first access to keychain can cause system unlock dialog, so, allow user to input data */, TimeUnit.SECONDS) } override fun set(attributes: CredentialAttributes, credentials: Credentials?) { val serviceNamePointer = stringPointer(attributes.serviceName.toByteArray()) val accountName = attributes.userName ?: credentials?.userName if (credentials.isEmpty()) { checkError("secret_password_store_sync") { errorRef -> if (accountName == null) { library.secret_password_clear_sync(scheme, null, errorRef, serviceAttributeNamePointer, serviceNamePointer, null) } else { library.secret_password_clear_sync(scheme, null, errorRef, serviceAttributeNamePointer, serviceNamePointer, accountAttributeNamePointer, stringPointer(accountName.toByteArray()), null) } } return } val passwordPointer = stringPointer(credentials!!.serialize(!attributes.isPasswordMemoryOnly), true) checkError("secret_password_store_sync") { errorRef -> try { if (accountName == null) { library.secret_password_store_sync(scheme, null, serviceNamePointer, passwordPointer, null, errorRef, serviceAttributeNamePointer, serviceNamePointer, null) } else { library.secret_password_store_sync(scheme, null, serviceNamePointer, passwordPointer, null, errorRef, serviceAttributeNamePointer, serviceNamePointer, accountAttributeNamePointer, stringPointer(accountName.toByteArray()), null) } } finally { passwordPointer.dispose() } } } } private inline fun <T> checkError(method: String, task: (errorRef: Array<GErrorStruct?>) -> T): T { val errorRef = arrayOf<GErrorStruct?>(null) val result = task(errorRef) val error = errorRef[0] if (error != null && error.code != 0) { if (error.code == 32584 || error.code == 32618 || error.code == 32606 || error.code == 32642) { LOG.warn("gnome-keyring not installed or kde doesn't support Secret Service API. $method error code ${error.code}, error message ${error.message}") } else { LOG.error("$method error code ${error.code}, error message ${error.message}") } } return result } // we use sync API to simplify - client will use postponed write @Suppress("FunctionName") private interface SecretLibrary : Library { fun secret_schema_new(name: String, flags: Int, vararg attributes: Any?): Pointer fun secret_password_store_sync(scheme: Pointer, collection: Pointer?, label: Pointer, password: Pointer, cancellable: Pointer?, error: Array<GErrorStruct?>, vararg attributes: Pointer?) fun secret_password_lookup_sync(scheme: Pointer, cancellable: Pointer?, error: Array<GErrorStruct?>, vararg attributes: Pointer?): String? fun secret_password_clear_sync(scheme: Pointer, cancellable: Pointer?, error: Array<GErrorStruct?>, vararg attributes: Pointer?) } @Suppress("unused") internal class GErrorStruct : Structure() { @JvmField var domain = 0 @JvmField var code = 0 @JvmField var message: String? = null override fun getFieldOrder() = listOf("domain", "code", "message") }
apache-2.0
0bd2dadf2794e67c75406d576c10d660
43.391892
187
0.649109
5.112062
false
false
false
false
Scavi/BrainSqueeze
src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day21AllergenAssessment.kt
1
2489
package com.scavi.brainsqueeze.adventofcode import java.lang.StringBuilder class Day21AllergenAssessment { private val splitPattern = """([^\(]*)(\(contains\s)([^\)]*)""".toRegex() private data class Food( val allIngredients: MutableMap<String, Int>, val allergenToIngredients: MutableMap<String, MutableSet<String>>) fun solveA(input: List<String>): Int { val food = filter(prepare(input)) return food.allIngredients.values.sum() } fun solveB(input: List<String>): String { val food = filter(prepare(input)) val tmp = StringBuilder() for (k in food.allergenToIngredients.keys.sorted()) { tmp.append(food.allergenToIngredients[k]!!.first()).append(",") } return tmp.toString().substring(0, tmp.length - 1) } private fun prepare(input: List<String>): Food { val allIngredients = mutableMapOf<String, Int>() val allergenToIngredients = mutableMapOf<String, MutableSet<String>>() for (line in input) { val (tmpIngredients, _, allergens) = splitPattern.find(line)!!.destructured val ingredients = tmpIngredients.trim().split(" ").toHashSet() for (ingredient in ingredients) { allIngredients[ingredient] = allIngredients.getOrDefault(ingredient, 0) + 1 } for (tmpAllergen in allergens.split(",")) { val allergen = tmpAllergen.trim() if (allergen in allergenToIngredients) { allergenToIngredients[allergen] = allergenToIngredients[allergen]!!.intersect(ingredients).toMutableSet() } else { allergenToIngredients[allergen] = ingredients } } } return Food(allIngredients, allergenToIngredients) } private fun filter(food: Food): Food { var hasChanges = true while (hasChanges) { hasChanges = false for ((k1, v1) in food.allergenToIngredients) { if (v1.size == 1) { for ((k2, v2) in food.allergenToIngredients) { if (k2 != k1) { hasChanges = hasChanges or v2.removeAll(v1) } } } } } for ((_, v) in food.allergenToIngredients) { food.allIngredients.remove(v.first()) } return food } }
apache-2.0
749799c87c6fb6f383f0e0980039ec50
37.292308
125
0.56127
4.870841
false
false
false
false
AshishKayastha/Movie-Guide
app/src/main/kotlin/com/ashish/movieguide/utils/extensions/StringExtensions.kt
1
2371
package com.ashish.movieguide.utils.extensions import android.text.Spannable import android.text.SpannableString import android.text.style.TypefaceSpan import com.ashish.movieguide.utils.Constants.BACKDROP_URL_PREFIX import com.ashish.movieguide.utils.Constants.ORIGINAL_IMAGE_URL_PREFIX import com.ashish.movieguide.utils.Constants.POSTER_URL_PREFIX import com.ashish.movieguide.utils.Constants.PROFILE_URL_PREFIX import com.ashish.movieguide.utils.Constants.STILL_URL_PREFIX import java.text.NumberFormat /** * Created by Ashish on Jan 03. */ fun CharSequence?.isNotNullOrEmpty() = !this.isNullOrEmpty() && this != "null" fun String?.getYearOnly() = if (isNotNullOrEmpty()) this!!.slice(0..3) else "" fun Int?.getFormattedCurrency(): String { if (this != null && this > 0L) { return String.format("$%s", NumberFormat.getNumberInstance().format(this)) } return "" } fun Int?.getFormattedRuntime(): String { if (this != null && this > 0) { val hours = this / 60 val minutes = this % 60 if (hours > 0) { if (minutes > 0) { return String.format("%dh %dm", hours, minutes) } else { return String.format("%dh", hours) } } else { return String.format("%dm", minutes) } } return "" } inline fun <T> List<T>?.convertListToCommaSeparatedText(crossinline func: (T) -> String): String { var formattedGenre = "" if (this != null && isNotEmpty()) { formattedGenre = joinToString { func(it) } } return formattedGenre } fun String?.getBackdropUrl() = getImageUrl(BACKDROP_URL_PREFIX) fun String?.getPosterUrl() = getImageUrl(POSTER_URL_PREFIX) fun String?.getProfileUrl() = getImageUrl(PROFILE_URL_PREFIX) fun String?.getStillImageUrl() = getImageUrl(STILL_URL_PREFIX) fun String?.getOriginalImageUrl() = getImageUrl(ORIGINAL_IMAGE_URL_PREFIX) fun String?.getImageUrl(urlPrefix: String) = if (isNotNullOrEmpty()) urlPrefix + this else "" fun CharSequence?.getTextWithCustomTypeface(typefaceSpan: TypefaceSpan): SpannableString? { if (isNotNullOrEmpty()) { val spannableString = SpannableString(this) spannableString.setSpan(typefaceSpan, 0, spannableString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) return spannableString } else { return null } }
apache-2.0
593be15ad5a418f1e0f95d76eb2ef1c0
31.054054
108
0.6841
4.094991
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/activity/BaseActivity.kt
1
13148
package org.wikipedia.activity import android.Manifest import android.content.* import android.content.pm.ShortcutManager import android.content.res.Configuration import android.net.ConnectivityManager import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.Settings import android.text.TextUtils import android.view.MenuItem import android.view.MotionEvent import android.view.View import androidx.annotation.ColorInt import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.skydoves.balloon.Balloon import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.disposables.Disposable import io.reactivex.rxjava3.functions.Consumer import org.wikipedia.Constants import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.analytics.LoginFunnel import org.wikipedia.analytics.NotificationFunnel import org.wikipedia.appshortcuts.AppShortcuts import org.wikipedia.auth.AccountUtil import org.wikipedia.crash.CrashReportActivity import org.wikipedia.events.* import org.wikipedia.login.LoginActivity import org.wikipedia.main.MainActivity import org.wikipedia.notifications.NotificationPollBroadcastReceiver import org.wikipedia.readinglist.ReadingListSyncBehaviorDialogs import org.wikipedia.readinglist.sync.ReadingListSyncAdapter import org.wikipedia.readinglist.sync.ReadingListSyncEvent import org.wikipedia.recurring.RecurringTasksExecutor import org.wikipedia.savedpages.SavedPageSyncService import org.wikipedia.settings.Prefs import org.wikipedia.settings.SiteInfoClient import org.wikipedia.util.DeviceUtil import org.wikipedia.util.FeedbackUtil import org.wikipedia.util.PermissionUtil import org.wikipedia.util.ResourceUtil import org.wikipedia.util.log.L import org.wikipedia.views.ImageZoomHelper abstract class BaseActivity : AppCompatActivity() { private lateinit var exclusiveBusMethods: ExclusiveBusConsumer private val networkStateReceiver = NetworkStateReceiver() private var previousNetworkState = WikipediaApp.getInstance().isOnline private val disposables = CompositeDisposable() private var currentTooltip: Balloon? = null private var imageZoomHelper: ImageZoomHelper? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) exclusiveBusMethods = ExclusiveBusConsumer() disposables.add(WikipediaApp.getInstance().bus.subscribe(NonExclusiveBusConsumer())) setTheme() removeSplashBackground() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1 && AppShortcuts.ACTION_APP_SHORTCUT == intent.action) { intent.putExtra(Constants.INTENT_EXTRA_INVOKE_SOURCE, Constants.InvokeSource.APP_SHORTCUTS) val shortcutId = intent.getStringExtra(AppShortcuts.APP_SHORTCUT_ID) if (!TextUtils.isEmpty(shortcutId)) { applicationContext.getSystemService(ShortcutManager::class.java) .reportShortcutUsed(shortcutId) } } supportActionBar?.setDisplayHomeAsUpEnabled(true) if (savedInstanceState == null) { NotificationFunnel.processIntent(intent) } NotificationPollBroadcastReceiver.startPollTask(WikipediaApp.getInstance()) // Conditionally execute all recurring tasks RecurringTasksExecutor(WikipediaApp.getInstance()).run() if (Prefs.isReadingListsFirstTimeSync() && AccountUtil.isLoggedIn) { Prefs.setReadingListsFirstTimeSync(false) Prefs.setReadingListSyncEnabled(true) ReadingListSyncAdapter.manualSyncWithForce() } val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) registerReceiver(networkStateReceiver, filter) DeviceUtil.setLightSystemUiVisibility(this) setStatusBarColor(ResourceUtil.getThemedColor(this, R.attr.paper_color)) setNavigationBarColor(ResourceUtil.getThemedColor(this, R.attr.paper_color)) maybeShowLoggedOutInBackgroundDialog() if (this !is CrashReportActivity) { Prefs.setLocalClassName(localClassName) } } override fun onDestroy() { unregisterReceiver(networkStateReceiver) disposables.dispose() if (EXCLUSIVE_BUS_METHODS === exclusiveBusMethods) { unregisterExclusiveBusMethods() } super.onDestroy() } override fun onStop() { WikipediaApp.getInstance().sessionFunnel.persistSession() super.onStop() } override fun onResume() { super.onResume() WikipediaApp.getInstance().sessionFunnel.touchSession() // allow this activity's exclusive bus methods to override any existing ones. unregisterExclusiveBusMethods() EXCLUSIVE_BUS_METHODS = exclusiveBusMethods EXCLUSIVE_DISPOSABLE = WikipediaApp.getInstance().bus.subscribe(EXCLUSIVE_BUS_METHODS!!) // The UI is likely shown, giving the user the opportunity to exit and making a crash loop // less probable. if (this !is CrashReportActivity) { Prefs.crashedBeforeActivityCreated(false) } } override fun applyOverrideConfiguration(configuration: Configuration) { // TODO: remove when this is fixed: // https://issuetracker.google.com/issues/141132133 // On Lollipop the current version of AndroidX causes a crash when instantiating a WebView. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M && resources.configuration.uiMode == WikipediaApp.getInstance().resources.configuration.uiMode) { return } super.applyOverrideConfiguration(configuration) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { onBackPressed() true } else -> false } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { when (requestCode) { Constants.ACTIVITY_REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION -> if (!PermissionUtil.isPermitted(grantResults)) { L.i("Write permission was denied by user") if (PermissionUtil.shouldShowWritePermissionRationale(this)) { showStoragePermissionSnackbar() } else { showAppSettingSnackbar() } } else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } override fun dispatchTouchEvent(event: MotionEvent): Boolean { dismissCurrentTooltip() imageZoomHelper?.let { return it.onDispatchTouchEvent(event) || super.dispatchTouchEvent(event) } return super.dispatchTouchEvent(event) } protected fun setStatusBarColor(@ColorInt color: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { window.statusBarColor = color } } protected fun setNavigationBarColor(@ColorInt color: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val isDarkThemeOrDarkBackground = (WikipediaApp.getInstance().currentTheme.isDark || color == ContextCompat.getColor(this, android.R.color.black)) window.navigationBarColor = color window.decorView.systemUiVisibility = if (isDarkThemeOrDarkBackground) window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR.inv() else View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR or window.decorView.systemUiVisibility } } protected open fun setTheme() { setTheme(WikipediaApp.getInstance().currentTheme.resourceId) } protected open fun onGoOffline() {} protected open fun onGoOnline() {} private fun requestStoragePermission() { Prefs.setAskedForPermissionOnce(Manifest.permission.WRITE_EXTERNAL_STORAGE) PermissionUtil.requestWriteStorageRuntimePermissions(this@BaseActivity, Constants.ACTIVITY_REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION) } private fun showStoragePermissionSnackbar() { val snackbar = FeedbackUtil.makeSnackbar(this, getString(R.string.offline_read_permission_rationale), FeedbackUtil.LENGTH_DEFAULT) snackbar.setAction(R.string.storage_access_error_retry) { requestStoragePermission() } snackbar.show() } private fun showAppSettingSnackbar() { val snackbar = FeedbackUtil.makeSnackbar(this, getString(R.string.offline_read_final_rationale), FeedbackUtil.LENGTH_DEFAULT) snackbar.setAction(R.string.app_settings) { goToSystemAppSettings() } snackbar.show() } private fun goToSystemAppSettings() { val appSettings = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName")) appSettings.addCategory(Intent.CATEGORY_DEFAULT) appSettings.flags = Intent.FLAG_ACTIVITY_NEW_TASK startActivity(appSettings) } private inner class NetworkStateReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val isDeviceOnline = WikipediaApp.getInstance().isOnline if (isDeviceOnline) { if (!previousNetworkState) { onGoOnline() } SavedPageSyncService.enqueue() } else { onGoOffline() } previousNetworkState = isDeviceOnline } } private fun removeSplashBackground() { window.setBackgroundDrawable(null) } private fun unregisterExclusiveBusMethods() { EXCLUSIVE_DISPOSABLE?.dispose() EXCLUSIVE_DISPOSABLE = null EXCLUSIVE_BUS_METHODS = null } private fun maybeShowLoggedOutInBackgroundDialog() { if (Prefs.wasLoggedOutInBackground()) { Prefs.setLoggedOutInBackground(false) AlertDialog.Builder(this) .setCancelable(false) .setTitle(R.string.logged_out_in_background_title) .setMessage(R.string.logged_out_in_background_dialog) .setPositiveButton(R.string.logged_out_in_background_login) { _: DialogInterface?, _: Int -> startActivity(LoginActivity.newIntent(this@BaseActivity, LoginFunnel.SOURCE_LOGOUT_BACKGROUND)) } .setNegativeButton(R.string.logged_out_in_background_cancel, null) .show() } } private fun dismissCurrentTooltip() { currentTooltip?.dismiss() currentTooltip = null } fun setCurrentTooltip(tooltip: Balloon) { dismissCurrentTooltip() currentTooltip = tooltip } fun setImageZoomHelper() { imageZoomHelper = ImageZoomHelper(this) } /** * Bus consumer that should be registered by all created activities. */ private inner class NonExclusiveBusConsumer : Consumer<Any> { override fun accept(event: Any) { if (event is ThemeFontChangeEvent) { ActivityCompat.recreate(this@BaseActivity) } } } /** * Bus methods that should be caught only by the topmost activity. */ private inner class ExclusiveBusConsumer : Consumer<Any> { override fun accept(event: Any) { if (event is NetworkConnectEvent) { SavedPageSyncService.enqueue() } else if (event is SplitLargeListsEvent) { AlertDialog.Builder(this@BaseActivity) .setMessage(getString(R.string.split_reading_list_message, SiteInfoClient.maxPagesPerReadingList)) .setPositiveButton(R.string.reading_list_split_dialog_ok_button_text, null) .show() } else if (event is ReadingListsNoLongerSyncedEvent) { ReadingListSyncBehaviorDialogs.detectedRemoteTornDownDialog(this@BaseActivity) } else if (event is ReadingListsEnableDialogEvent && this@BaseActivity is MainActivity) { ReadingListSyncBehaviorDialogs.promptEnableSyncDialog(this@BaseActivity) } else if (event is LoggedOutInBackgroundEvent) { maybeShowLoggedOutInBackgroundDialog() } else if (event is ReadingListSyncEvent) { if (event.showMessage && !Prefs.isSuggestedEditsHighestPriorityEnabled()) { FeedbackUtil.makeSnackbar(this@BaseActivity, getString(R.string.reading_list_toast_last_sync), FeedbackUtil.LENGTH_DEFAULT).show() } } } } companion object { private var EXCLUSIVE_BUS_METHODS: ExclusiveBusConsumer? = null private var EXCLUSIVE_DISPOSABLE: Disposable? = null } }
apache-2.0
f6cc3181b8d0d2144e1f2cfe26f61d3b
40.216301
254
0.685199
5.192733
false
false
false
false
cdietze/klay
src/main/kotlin/klay/core/Event.kt
1
3967
package klay.core /** * Defines an event abstraction used in various places. */ abstract class Event { /** The base for all input events. */ open class Input protected constructor( /** * The flags set for this event. See [.isSet], [.setFlag] and [.clearFlag]. */ var flags: Int, /** * The time at which this event was generated, in milliseconds. This time's magnitude is not * portable (i.e. may not be the same across backends), clients must interpret it as only a * monotonically increasing value. */ val time: Double) : Event() { /** Returns true if the `alt` key was down when this event was generated. */ val isAltDown: Boolean get() = isSet(F_ALT_DOWN) /** Returns true if the `ctrl` key was down when this event was generated. */ val isCtrlDown: Boolean get() = isSet(F_CTRL_DOWN) /** Returns true if the `shift` key was down when this event was generated. */ val isShiftDown: Boolean get() = isSet(F_SHIFT_DOWN) /** Returns true if the `meta` key was down when this event was generated. */ val isMetaDown: Boolean get() = isSet(F_META_DOWN) /** Returns whether the `flag` bit is set. */ fun isSet(flag: Int): Boolean { return flags and flag != 0 } /** Sets the `flag` bit. */ fun setFlag(flag: Int) { flags = flags or flag } /** Clears the `flag` bit. */ fun clearFlag(flag: Int) { flags = flags and flag.inv() } /** Sets or clears `flag` based on `on`. */ fun updateFlag(flag: Int, on: Boolean) { if (on) setFlag(flag) else clearFlag(flag) } override fun toString(): String { val builder = StringBuilder(name()).append('[') addFields(builder) return builder.append(']').toString() } protected open fun name(): String { return "Input" } protected open fun addFields(builder: StringBuilder) { builder.append("time=").append(time).append(", flags=").append(flags) } companion object { /** A helper function used by platform input code to compose modifier flags. */ fun modifierFlags(altP: Boolean, ctrlP: Boolean, metaP: Boolean, shiftP: Boolean): Int { var flags = 0 if (altP) flags = flags or F_ALT_DOWN if (ctrlP) flags = flags or F_CTRL_DOWN if (metaP) flags = flags or F_META_DOWN if (shiftP) flags = flags or F_SHIFT_DOWN return flags } } } /** The base for all input events with a screen position. */ open class XY protected constructor(flags: Int, time: Double, /** The screen x-coordinate associated with this event. */ override val x: Float, /** The screen y-coordinate associated with this event. */ override val y: Float) : Input(flags, time), euklid.f.XY { override fun name(): String { return "XY" } override fun addFields(builder: StringBuilder) { super.addFields(builder) builder.append(", x=").append(x).append(", y=").append(y) } } companion object { /** A flag indicating that the default OS behavior for an event should be prevented. */ val F_PREVENT_DEFAULT = 1 shl 0 protected val F_ALT_DOWN = 1 shl 1 protected val F_CTRL_DOWN = 1 shl 2 protected val F_SHIFT_DOWN = 1 shl 3 protected val F_META_DOWN = 1 shl 4 } }
apache-2.0
7643020a5c0fa0b523c125e868789d2e
34.419643
104
0.52483
4.586127
false
false
false
false
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/util/TypeResolver.kt
1
3965
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * 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.github.jonathanxd.kores.util import com.github.jonathanxd.kores.Types import com.github.jonathanxd.kores.type.koresType import java.lang.reflect.Type /** * Resolves a class name which may vary to a [Type] and cache the resolved type. */ @FunctionalInterface interface TypeResolver { /** * Resolves type with [name] to a [Type]. If [isInterface] is `true`, and resolved * type is cached as non-interface, then the type should be replaced with one that is marked as interface. */ fun resolve(name: String, isInterface: Boolean): Type } /** * Resolve type as unknown, same as [resolveClass] */ fun TypeResolver.resolveUnknown(name: String): Type { return this.resolve(name, false) } /** * Resolve type as interface. */ fun TypeResolver.resolveInterface(name: String): Type { return this.resolve(name, true) } /** * Resolve type as class. */ fun TypeResolver.resolveClass(name: String): Type { return this.resolve(name, false) } /** * Simple type resolver */ class SimpleResolver(private val wrapped: TypeResolver, private val resolveLoadedClasses: Boolean) : TypeResolver { override fun resolve(name: String, isInterface: Boolean): Type { @Suppress("NAME_SHADOWING") var name = name when (name) { Types.BYTE.javaSpecName -> return Types.BYTE Types.SHORT.javaSpecName -> return Types.SHORT Types.INT.javaSpecName -> return Types.INT Types.FLOAT.javaSpecName -> return Types.FLOAT Types.DOUBLE.javaSpecName -> return Types.DOUBLE Types.LONG.javaSpecName -> return Types.LONG Types.CHAR.javaSpecName -> return Types.CHAR Types.STRING.javaSpecName -> return Types.STRING Types.BOOLEAN.javaSpecName -> return Types.BOOLEAN Types.VOID.javaSpecName -> return Types.VOID else -> { name = name.replace('/', '.') if (name.startsWith("L") && name.endsWith(";")) { name = name.substring(1, name.length - 1) } if (this.resolveLoadedClasses) { try { val aClass = Class.forName(name) if (aClass != null) return aClass.koresType } catch (ignored: Throwable) { } } return this.wrapped.resolve(name, isInterface) } } } }
mit
a24bbd00743a764b67110e88081499ca
34.401786
118
0.639596
4.552239
false
false
false
false
dahlstrom-g/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/vfs/CustomisableUniqueNameEditorTabTitleProvider.kt
6
1409
// 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.openapi.vcs.vfs import com.intellij.ide.ui.UISettings import com.intellij.openapi.fileEditor.impl.UniqueNameEditorTabTitleProvider import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.annotations.Nls abstract class CustomisableUniqueNameEditorTabTitleProvider : UniqueNameEditorTabTitleProvider(), DumbAware { abstract fun isApplicable(file: VirtualFile): Boolean @NlsContexts.TabTitle abstract fun getEditorTabTitle(file: VirtualFile, @Nls baseUniqueName: String): String override fun getEditorTabTitle(project: Project, file: VirtualFile): String? { if (isApplicable(file)) { return getBaseUniqueName(project, file)?.let { baseName -> getEditorTabTitle(file, baseName) } } return null } @Nls private fun getBaseUniqueName(project: Project, file: VirtualFile): String? { var baseName = super.getEditorTabTitle(project, file) if (baseName == null && UISettings.getInstance().hideKnownExtensionInTabs && !file.isDirectory) { baseName = file.nameWithoutExtension.ifEmpty { file.name } } if (baseName == file.presentableName) return null return baseName } }
apache-2.0
d83539973fbae89cbc76fd39e44c74a3
40.441176
120
0.777147
4.516026
false
false
false
false
jasvilladarez/Kotlin_Practice
BmiCalculator/app/src/main/java/com/jv/practice/bmicalculator/presentation/views/activities/MainActivity.kt
1
3545
/* * Copyright 2016 Jasmine Villadarez * * 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.jv.practice.bmicalculator.presentation.views.activities import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.Toast import com.jv.practice.bmicalculator.R import com.jv.practice.bmicalculator.domain.AnalyseBmi import com.jv.practice.bmicalculator.domain.ComputeImperialBmi import com.jv.practice.bmicalculator.domain.ComputeMetricBmi import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initializeViews() } fun initializeViews() { radioImperial.setOnClickListener(this) radioMetric.setOnClickListener(this) calculate.setOnClickListener(this) radioImperial.performClick() } override fun onClick(v: View) { var viewId = v.id when (viewId) { R.id.radioImperial -> { clearFields() weight.setHint(R.string.weight_lbs) height.setHint(R.string.height_inch) } R.id.radioMetric -> { clearFields() weight.setHint(R.string.weight_kg) height.setHint(R.string.height_m) } R.id.calculate -> { if (validateFields()) return var bmi = doCalculateBmi() analyseBmi(bmi) } else -> { weight.setHint(R.string.weight_lbs) height.setHint(R.string.height_inch) } } } private fun analyseBmi(bmi: Double) { var analyseBmi = AnalyseBmi() analysation.text = analyseBmi.analyseBmi(bmi) } private fun doCalculateBmi(): Double { var w = weight.text.toString() var h = height.text.toString() var value = 0.0 if (radioImperial.isChecked) { var computeImperialBmi = ComputeImperialBmi() value = computeImperialBmi.computeBmi(w.toDouble(), h.toInt()) result.text = String.format("%.${2}f", value) } else if (radioMetric.isChecked) { var computeMetricBmi = ComputeMetricBmi() value = computeMetricBmi.computeBmi(w.toDouble(), h.toDouble()) result.text = String.format("%.${2}f", value) } return value } private fun validateFields(): Boolean { if (weight.text.isEmpty() || height.text.isEmpty()) { Toast.makeText(this, "Please fill all fields", Toast.LENGTH_SHORT).show(); return true; } return false } private fun clearFields() { weight.text.clear() height.text.clear() result.text = "" analysation.text = "" weight.requestFocus() } }
apache-2.0
16ed748dabd2ba1196008d908c2cfbd5
30.096491
86
0.623413
4.4202
false
false
false
false
JesusM/FingerprintManager
kfingerprintmanager/src/main/kotlin/com/jesusm/kfingerprintmanager/base/ui/SystemImpl.kt
1
823
package com.jesusm.kfingerprintmanager.base.ui import android.support.v4.app.FragmentManager class SystemImpl : System { private val FINGERPRINT_DIALOG_TAG = "KFingerprintManager:fingerprintDialog" private var fingerprintBaseDialogFragment: FingerprintBaseDialogFragment<*>? = null private var dialogFragmentManager: FragmentManager? = null override fun showDialog() { fingerprintBaseDialogFragment?.show(dialogFragmentManager, FINGERPRINT_DIALOG_TAG) } override fun addDialogInfo(builder: FingerprintBaseDialogFragment.Builder<out FingerprintBaseDialogFragment<*>, *>?, fragmentManager: FragmentManager?) { builder?.let { fingerprintBaseDialogFragment = it.build() dialogFragmentManager = fragmentManager } } }
mit
54fe7f1d29792135f8c8b7b3f79db49e
36.454545
120
0.72418
5.878571
false
false
false
false
martijn-heil/wac-core
src/main/kotlin/tk/martijn_heil/wac_core/craft/SailingModule.kt
1
6894
/* * wac-core * Copyright (C) 2016 Martijn Heil * * 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 tk.martijn_heil.wac_core.craft import at.pavlov.cannons.API.CannonsAPI import at.pavlov.cannons.Cannons import org.bukkit.Bukkit import org.bukkit.ChatColor import org.bukkit.Material import org.bukkit.Server import org.bukkit.block.Sign import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority.MONITOR import org.bukkit.event.Listener import org.bukkit.event.player.PlayerInteractEvent import org.bukkit.plugin.Plugin import tk.martijn_heil.wac_core.craft.vessel.sail.* import java.io.Closeable import java.util.* import java.util.logging.Logger object SailingModule : AutoCloseable { lateinit private var logger: Logger lateinit private var plugin: Plugin private val server: Server by lazy { plugin.server } private val random = Random() val cannonsAPI: CannonsAPI by lazy { (Bukkit.getPluginManager().getPlugin("Cannons") as Cannons).cannonsAPI } var windFrom: Int = 0 // Wind coming from x degrees private set fun init(plugin: Plugin, logger: Logger) { this.plugin = plugin this.logger = logger server.scheduler.scheduleSyncRepeatingTask(plugin, { windFrom = random.nextInt(360) }, 0, 72000) // Every hour server.scheduler.scheduleSyncRepeatingTask(plugin, { Bukkit.broadcastMessage(ChatColor.AQUA.toString() + "[Wind] " + ChatColor.GRAY + "The wind now blows from $windFrom°.") }, 0, 6000) // Every five minutes CraftManager.init() } override fun close() { CraftManager.close() } private object CraftManager : AutoCloseable { private val crafts: MutableCollection<Craft> = ArrayList() fun init() { server.pluginManager.registerEvents(CraftManagerListener, plugin) } private object CraftManagerListener : Listener { @EventHandler(ignoreCancelled = true, priority = MONITOR) fun onPlayerInteract(e: PlayerInteractEvent) { if (e.clickedBlock != null && (e.clickedBlock.type == Material.SIGN || e.clickedBlock.type == Material.SIGN_POST || e.clickedBlock.type == Material.WALL_SIGN) && (e.clickedBlock.state as Sign).lines[0] == "[Craft]") { val type = (e.clickedBlock.state as Sign).lines[1] if (type == "") { e.player.sendMessage(ChatColor.RED.toString() + "Error: Craft type not specified."); return } when (type) { "Trireme" -> { try { crafts.add(Trireme.detect(plugin, logger, e.clickedBlock.location)) } catch(ex: IllegalStateException) { e.player.sendMessage(ChatColor.RED.toString() + "Error: " + ex.message) } catch(ex: Exception) { e.player.sendMessage(ChatColor.RED.toString() + "An internal server error occurred." + ex.message) ex.printStackTrace() } } "Unireme" -> { try { crafts.add(Unireme.detect(plugin, logger, e.clickedBlock.location)) } catch(ex: IllegalStateException) { e.player.sendMessage(ChatColor.RED.toString() + "Error: " + ex.message) } catch(ex: Exception) { e.player.sendMessage(ChatColor.RED.toString() + "An internal server error occurred." + ex.message) ex.printStackTrace() } } "Count" -> { try { crafts.add(Count.detect(plugin, logger, e.clickedBlock.location)) } catch(ex: IllegalStateException) { e.player.sendMessage(ChatColor.RED.toString() + "Error: " + ex.message) } catch(ex: Exception) { e.player.sendMessage(ChatColor.RED.toString() + "An internal server error occurred." + ex.message) ex.printStackTrace() } } "Speedy" -> { try { crafts.add(Speedy.detect(plugin, logger, e.clickedBlock.location)) } catch(ex: IllegalStateException) { e.player.sendMessage(ChatColor.RED.toString() + "Error: " + ex.message) } catch(ex: Exception) { e.player.sendMessage(ChatColor.RED.toString() + "An internal server error occurred." + ex.message) ex.printStackTrace() } } "Cutter" -> { try { crafts.add(Cutter.detect(plugin, logger, e.clickedBlock.location)) } catch(ex: IllegalStateException) { e.player.sendMessage(ChatColor.RED.toString() + "Error: " + ex.message) } catch(ex: Exception) { e.player.sendMessage(ChatColor.RED.toString() + "An internal server error occurred." + ex.message) ex.printStackTrace() } } } } } } override fun close() { crafts.forEach { if(it is Closeable) it.close() else if (it is AutoCloseable) it.close() } } } }
gpl-3.0
332847416c33d328883cc2f8ac09f352
43.361842
133
0.511824
5.072112
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/workspaceModel/ide/impl/jps/serialization/IdeErrorReporter.kt
4
2554
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.ide.impl.jps.serialization import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.ConfigurationErrorDescription import com.intellij.openapi.module.ConfigurationErrorType import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.io.FileUtil import com.intellij.projectModel.ProjectModelBundle import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleId import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.annotations.Nls internal class IdeErrorReporter(private val project: Project) : ErrorReporter { val errors = ArrayList<ConfigurationErrorDescription>() override fun reportError(message: String, file: VirtualFileUrl) { if (FileUtil.extensionEquals(file.fileName, "iml")) { errors.add(ModuleLoadingErrorDescriptionBridge(message, file, project)) } else { LOG.error("Failed to load ${file.presentableUrl}: $message") } } companion object { private val LOG = logger<IdeErrorReporter>() } } private val MODULE_ERROR: ConfigurationErrorType = object : ConfigurationErrorType(false) { override fun getErrorText(errorCount: Int, firstElementName: @NlsSafe String?): @Nls String { return ProjectModelBundle.message("module.configuration.problem.text", errorCount, firstElementName) } } private class ModuleLoadingErrorDescriptionBridge(@NlsContexts.DetailedDescription description: String, private val moduleFile: VirtualFileUrl, private val project: Project) : ConfigurationErrorDescription(FileUtil.getNameWithoutExtension(moduleFile.fileName), description, MODULE_ERROR) { override fun ignoreInvalidElement() { runWriteAction { WorkspaceModel.getInstance(project).updateProjectModel { builder -> val moduleEntity = builder.resolve(ModuleId(elementName)) if (moduleEntity != null) { builder.removeEntity(moduleEntity) } } } } override fun getIgnoreConfirmationMessage(): String { return ProjectModelBundle.message("module.remove.from.project.confirmation", elementName) } }
apache-2.0
46bbfaa1aafec89a6e0ddbcab0c384ec
42.305085
140
0.757635
4.940039
false
true
false
false
sreich/ore-infinium
core/src/com/ore/infinium/components/BlockComponent.kt
1
1718
/** MIT License Copyright (c) 2016 Shaun Reich <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.ore.infinium.components import com.artemis.Component import com.ore.infinium.util.ExtendedComponent /** * used for blocks when they are held in the inventory or dropped in the world. * they're not used for sending tile regions of course, that would be expensive. * only arrays are used there. */ class BlockComponent : Component(), ExtendedComponent<BlockComponent> { var blockType: Byte = 0 override fun canCombineWith(other: BlockComponent) = this.blockType == other.blockType override fun copyFrom(other: BlockComponent) { this.blockType = other.blockType } }
mit
c926d56ada91bdb33f4d5f36c5d6c60f
37.177778
80
0.774156
4.544974
false
false
false
false
Killian-LeClainche/Java-Base-Application-Engine
src/polaris/okapi/render/RenderManager.kt
1
3756
package polaris.okapi.render import org.lwjgl.opengl.ARBShaderObjects import org.lwjgl.opengl.GL20C.* import polaris.okapi.options.Settings import polaris.okapi.util.readFileAsString import java.io.File /** * Created by Killian Le Clainche on 12/12/2017. */ const val QUAD_POINTS = 6 const val COORDS_UV = 5 class RenderManager(val settings: Settings) { //public static final Shader POS; //public static final Shader POS_COLOR; //public static final Shader POS_TEXTURE; //public static final Shader POS_COLOR_TEXTURE; val posShader: Shader = Shader() val posColorShader: Shader = Shader() val posTextureShader: Shader = Shader() val posColorTextureShader: Shader = Shader() init { posShader.vertexShaderId = loadShader(File("resources/shaders/pos.vert"), GL_VERTEX_SHADER) posShader.fragmentShaderId = loadShader(File("resources/shaders/pos.frag"), GL_FRAGMENT_SHADER) posShader.link() posColorShader.vertexShaderId = loadShader(File("resources/shaders/pos_color.vert"), GL_VERTEX_SHADER) posColorShader.fragmentShaderId = loadShader(File("resources/shaders/pos_color.frag"), GL_FRAGMENT_SHADER) posColorShader.link() posColorTextureShader.vertexShaderId = loadShader(File("resources/shaders/pos_color_texture.vert"), GL_VERTEX_SHADER) posColorTextureShader.fragmentShaderId = loadShader(File("resources/shaders/pos_color_texture.frag"), GL_FRAGMENT_SHADER) posColorTextureShader.link() } /*@JvmOverloads fun print(font: Font, text: String, x: Float, y: Float, z: Float = 0.0f, height: Float): VBO? { val scale = stbtt_ScaleForPixelHeight(font.info, height) val vboBuffer = VBOBuffer((text.length * QUAD_POINTS * COORDS_UV).toLong()) stackPush().use { val nextX = it.floats(x) val nextY = it.floats(y) val quad = STBTTAlignedQuad.mallocStack(it) var currentX: Float var x0: Float var x1: Float var y0: Float var y1: Float for(i in 0 until text.length) { currentX = nextX[0] stbtt_GetPackedQuad(font.chardata, font.width, font.height, text[i].toInt() - 32, nextX, nextY, quad, true) nextX.put(0, scale(currentX, nextX[0], scale)) if(i + 1 < text.length) nextX.put(0, nextX[0] + stbtt_GetCodepointKernAdvance(font.info, text[i].toInt() - 32, text[i + 1].toInt() - 32)) x0 = scale(currentX, quad.x0(), scale) x1 = scale(currentX, quad.x1(), scale) y0 = scale(nextY[0], quad.y0(), scale) y1 = scale(nextY[0], quad.y1(), scale) vboBuffer.rectUV(x0, y0, x1, y1, z, TexCoord(quad.s0(), quad.t0(), quad.s1(), quad.t1())) } } return null }*/ fun loadShader(filename: File, shaderType: Int): Int { var shader = 0 try { shader = glCreateShader(shaderType) if (shader == 0) return 0 glShaderSource(shader, readFileAsString(filename)) glCompileShader(shader) if (glGetShaderi(shader, GL_COMPILE_STATUS) == GL_FALSE) throw RuntimeException("Error creating shader: " + getLogInfo(shader)) return shader } catch (exc: Exception) { if(shader != 0) glDeleteShader(shader) println(exc.message) return -1 } } private fun getLogInfo(obj: Int): String { return ARBShaderObjects.glGetInfoLogARB(obj, ARBShaderObjects.glGetObjectParameteriARB(obj, ARBShaderObjects.GL_OBJECT_INFO_LOG_LENGTH_ARB)) } }
gpl-2.0
f092e87d2ba668630cc2cda2a2603341
31.95614
148
0.620341
3.966209
false
false
false
false
MGaetan89/ShowsRage
app/src/main/kotlin/com/mgaetan89/showsrage/fragment/SettingsFragment.kt
1
6267
package com.mgaetan89.showsrage.fragment import android.content.SharedPreferences import android.os.Bundle import android.support.annotation.StringRes import android.support.annotation.XmlRes import android.support.graphics.drawable.VectorDrawableCompat import android.support.v7.app.AlertDialog import android.support.v7.preference.EditTextPreference import android.support.v7.preference.ListPreference import android.support.v7.preference.Preference import android.support.v7.preference.PreferenceGroup import com.mgaetan89.showsrage.BuildConfig import com.mgaetan89.showsrage.Constants import com.mgaetan89.showsrage.R import com.mgaetan89.showsrage.activity.MainActivity import com.mgaetan89.showsrage.extension.Fields import com.mgaetan89.showsrage.extension.getLanguage import com.mgaetan89.showsrage.extension.getLocale import com.mgaetan89.showsrage.extension.getPreferences import com.mgaetan89.showsrage.extension.getServerAddress import com.takisoft.fix.support.v7.preference.PreferenceFragmentCompat // Code to display preferences values from: http://stackoverflow.com/a/18807490/1914223 open class SettingsFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener { override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val activity = this.activity if (activity is MainActivity) { activity.displayHomeAsUp(true) } } override fun onCreatePreferencesFix(savedInstanceState: Bundle?, rootKey: String?) { this.addPreferencesFromResource(this.getXmlResourceFile()) this.preferenceScreen?.sharedPreferences?.registerOnSharedPreferenceChangeListener(this) } override fun onDestroy() { this.preferenceScreen?.sharedPreferences?.unregisterOnSharedPreferenceChangeListener(this) super.onDestroy() } override fun onPreferenceTreeClick(preference: Preference?): Boolean { if (preference?.key?.startsWith("screen_") == true) { val fragment = getSettingFragmentForScreen(preference.key) if (fragment != null) { this.fragmentManager?.beginTransaction() ?.replace(R.id.content, fragment) ?.addToBackStack("settings") ?.commit() return true } } return super.onPreferenceTreeClick(preference) } override fun onResume() { super.onResume() this.activity?.setTitle(this.getTitleResourceId()) if ("SettingsFragment" == this.javaClass.simpleName) { val context = this.context val serverAddress = context?.getPreferences()?.getServerAddress() this.setScreensIcon() if (context != null && serverAddress.isNullOrEmpty()) { AlertDialog.Builder(context) .setIcon(R.drawable.ic_notification) .setTitle(R.string.app_name) .setMessage(R.string.welcome_message) .setPositiveButton(android.R.string.ok, null) .show() } } this.updatePreferenceGroup(this.preferenceScreen) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) { this.updatePreference(this.findPreference(key)) } private fun getPreferenceValue(key: String, defaultValue: String?) = this.preferenceManager.sharedPreferences?.getString(key, defaultValue) @StringRes internal open fun getTitleResourceId() = R.string.settings @XmlRes internal open fun getXmlResourceFile() = R.xml.settings // This can be set directly in XML when we support API 21+ // Or when the Support Library supports it private fun setScreensIcon() { val screens = mapOf( "screen_server" to R.drawable.ic_wifi_24dp, "screen_display" to R.drawable.ic_device_android_24dp, "screen_behavior" to R.drawable.ic_widgets_24dp, "screen_experimental_features" to R.drawable.ic_explore_24dp, "screen_about" to R.drawable.ic_help_outline_24dp ) screens.forEach { val icon = VectorDrawableCompat.create(this.resources, it.value, this.activity?.theme) this.findPreference(it.key)?.icon = icon } } private fun setupDisplayLanguage(preference: Preference) { val preferences = this.context?.getPreferences() ?: return val preferredLocale = preferences.getLocale() if (preference is ListPreference) { preference.entries = Constants.SUPPORTED_LOCALES.map { it.displayLanguage.capitalize() }.toTypedArray() preference.entryValues = Constants.SUPPORTED_LOCALES.map { it.language }.toTypedArray() if (preferences.getLanguage().isEmpty()) { preference.value = preferredLocale.language } } preference.summary = preferredLocale.displayLanguage.capitalize() } private fun updatePreference(preference: Preference?) { if (preference is EditTextPreference) { val text = preference.text if (Fields.SERVER_PASSWORD.field == preference.key && !text.isNullOrEmpty()) { preference.summary = "*****" } else { preference.summary = text } } else if (preference is ListPreference) { preference.summary = preference.entry } } private fun updatePreferenceGroup(preferenceGroup: PreferenceGroup?) { if (preferenceGroup == null) { return } (0 until preferenceGroup.preferenceCount) .map { preferenceGroup.getPreference(it) } .forEach { if (it is PreferenceGroup) { when (it.key) { "application_version" -> it.summary = BuildConfig.VERSION_NAME "screen_server_api_key" -> it.summary = this.getPreferenceValue("api_key", "") } this.updatePreferenceGroup(it) } else { when (it.key) { Fields.DISPLAY_LANGUAGE.field -> this.setupDisplayLanguage(it) else -> this.updatePreference(it) } } } } companion object { internal fun getSettingFragmentForScreen(screen: String?) = when (screen) { "screen_about" -> SettingsAboutFragment.newInstance() "screen_about_licenses" -> SettingsAboutLicensesFragment.newInstance() "screen_about_shows_rage" -> SettingsAboutShowsRageFragment.newInstance() "screen_behavior" -> SettingsBehaviorFragment.newInstance() "screen_display" -> SettingsDisplayFragment.newInstance() "screen_experimental_features" -> SettingsExperimentalFeaturesFragment.newInstance() "screen_server" -> SettingsServerFragment.newInstance() "screen_server_api_key" -> SettingsServerApiKeyFragment.newInstance() else -> null } fun newInstance() = SettingsFragment() } }
apache-2.0
2ef0d58d786aba108653b48a447574f9
32.335106
110
0.755066
4.04845
false
false
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/service/graduate/design/DefenseArrangementServiceImpl.kt
1
1734
package top.zbeboy.isy.service.graduate.design import org.jooq.DSLContext import org.jooq.Record import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Propagation import org.springframework.transaction.annotation.Transactional import top.zbeboy.isy.domain.Tables.DEFENSE_ARRANGEMENT import top.zbeboy.isy.domain.tables.daos.DefenseArrangementDao import top.zbeboy.isy.domain.tables.pojos.DefenseArrangement import java.util.* import javax.annotation.Resource /** * Created by zbeboy 2018-02-06 . **/ @Service("defenseArrangementService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) open class DefenseArrangementServiceImpl @Autowired constructor(dslContext: DSLContext) : DefenseArrangementService { private val create: DSLContext = dslContext @Resource open lateinit var defenseArrangementDao: DefenseArrangementDao override fun findById(id: String): DefenseArrangement { return defenseArrangementDao.findById(id) } override fun findByGraduationDesignReleaseId(graduationDesignReleaseId: String): Optional<Record> { return create.select() .from(DEFENSE_ARRANGEMENT) .where(DEFENSE_ARRANGEMENT.GRADUATION_DESIGN_RELEASE_ID.eq(graduationDesignReleaseId)) .fetchOptional() } @Transactional(propagation = Propagation.REQUIRED, readOnly = false) override fun save(defenseArrangement: DefenseArrangement) { defenseArrangementDao.insert(defenseArrangement) } override fun update(defenseArrangement: DefenseArrangement) { defenseArrangementDao.update(defenseArrangement) } }
mit
07d372e6df93342d72969d014999fb18
35.914894
117
0.7797
4.954286
false
false
false
false
javache/react-native
ReactAndroid/src/main/java/com/facebook/react/views/view/ReactMapBufferPropSetter.kt
1
17782
/* * 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.views.view import android.graphics.Color import android.graphics.Rect import androidx.core.view.ViewCompat import com.facebook.react.bridge.DynamicFromObject import com.facebook.react.bridge.JavaOnlyArray import com.facebook.react.bridge.JavaOnlyMap import com.facebook.react.bridge.ReadableMap import com.facebook.react.common.mapbuffer.MapBuffer import com.facebook.react.uimanager.PixelUtil import com.facebook.react.uimanager.PointerEvents object ReactMapBufferPropSetter { // ViewProps values private const val VP_ACCESSIBILITY_ACTIONS = 0 private const val VP_ACCESSIBILITY_HINT = 1 private const val VP_ACCESSIBILITY_LABEL = 2 private const val VP_ACCESSIBILITY_LABELLED_BY = 3 private const val VP_ACCESSIBILITY_LIVE_REGION = 4 private const val VP_ACCESSIBILITY_ROLE = 5 private const val VP_ACCESSIBILITY_STATE = 6 private const val VP_ACCESSIBILITY_VALUE = 7 private const val VP_ACCESSIBLE = 8 private const val VP_BACKFACE_VISIBILITY = 9 private const val VP_BG_COLOR = 10 private const val VP_BORDER_COLOR = 11 private const val VP_BORDER_RADII = 12 private const val VP_BORDER_STYLE = 13 private const val VP_COLLAPSABLE = 14 private const val VP_ELEVATION = 15 private const val VP_FOCUSABLE = 16 private const val VP_HAS_TV_FOCUS = 17 private const val VP_HIT_SLOP = 18 private const val VP_IMPORTANT_FOR_ACCESSIBILITY = 19 private const val VP_NATIVE_BACKGROUND = 20 private const val VP_NATIVE_FOREGROUND = 21 private const val VP_NATIVE_ID = 22 private const val VP_OFFSCREEN_ALPHA_COMPOSITING = 23 private const val VP_OPACITY = 24 private const val VP_POINTER_EVENTS = 25 private const val VP_POINTER_ENTER = 26 private const val VP_POINTER_LEAVE = 27 private const val VP_POINTER_MOVE = 28 private const val VP_REMOVE_CLIPPED_SUBVIEW = 29 private const val VP_RENDER_TO_HARDWARE_TEXTURE = 30 private const val VP_SHADOW_COLOR = 31 private const val VP_TEST_ID = 32 private const val VP_TRANSFORM = 33 private const val VP_ZINDEX = 34 private const val VP_POINTER_ENTER_CAPTURE = 38 private const val VP_POINTER_LEAVE_CAPTURE = 39 private const val VP_POINTER_MOVE_CAPTURE = 40 private const val VP_POINTER_OUT = 41 private const val VP_POINTER_OUT_CAPTURE = 42 private const val VP_POINTER_OVER = 43 private const val VP_POINTER_OVER_CAPTURE = 44 private const val VP_BORDER_CURVES = 45 // iOS only private const val VP_FG_COLOR = 46 // iOS only? // Yoga values private const val YG_BORDER_WIDTH = 100 private const val YG_OVERFLOW = 101 // AccessibilityAction values private const val ACCESSIBILITY_ACTION_NAME = 0 private const val ACCESSIBILITY_ACTION_LABEL = 1 // AccessibilityState values private const val ACCESSIBILITY_STATE_BUSY = 0 private const val ACCESSIBILITY_STATE_DISABLED = 1 private const val ACCESSIBILITY_STATE_EXPANDED = 2 private const val ACCESSIBILITY_STATE_SELECTED = 3 private const val ACCESSIBILITY_STATE_CHECKED = 4 private const val EDGE_TOP = 0 private const val EDGE_LEFT = 1 private const val EDGE_RIGHT = 2 private const val EDGE_BOTTOM = 3 private const val EDGE_START = 4 private const val EDGE_END = 5 private const val EDGE_ALL = 6 private const val CORNER_TOP_LEFT = 0 private const val CORNER_TOP_RIGHT = 1 private const val CORNER_BOTTOM_RIGHT = 2 private const val CORNER_BOTTOM_LEFT = 3 private const val CORNER_TOP_START = 4 private const val CORNER_TOP_END = 5 private const val CORNER_BOTTOM_END = 6 private const val CORNER_BOTTOM_START = 7 private const val CORNER_ALL = 8 private const val NATIVE_DRAWABLE_KIND = 0 private const val NATIVE_DRAWABLE_ATTRIBUTE = 1 private const val NATIVE_DRAWABLE_COLOR = 2 private const val NATIVE_DRAWABLE_BORDERLESS = 3 private const val NATIVE_DRAWABLE_RIPPLE_RADIUS = 4 private const val UNDEF_COLOR = Int.MAX_VALUE fun setProps(view: ReactViewGroup, viewManager: ReactViewManager, props: MapBuffer) { for (entry in props) { when (entry.key) { VP_ACCESSIBILITY_ACTIONS -> { viewManager.accessibilityActions(view, entry.mapBufferValue) } VP_ACCESSIBILITY_HINT -> { viewManager.setAccessibilityHint(view, entry.stringValue.takeIf { it.isNotEmpty() }) } VP_ACCESSIBILITY_LABEL -> { viewManager.setAccessibilityLabel(view, entry.stringValue.takeIf { it.isNotEmpty() }) } VP_ACCESSIBILITY_LABELLED_BY -> { viewManager.accessibilityLabelledBy(view, entry.mapBufferValue) } VP_ACCESSIBILITY_LIVE_REGION -> { view.accessibilityLiveRegion(entry.intValue) } VP_ACCESSIBILITY_ROLE -> { viewManager.setAccessibilityRole(view, entry.stringValue.takeIf { it.isNotEmpty() }) } VP_ACCESSIBILITY_STATE -> { viewManager.accessibilityState(view, entry.mapBufferValue) } VP_ACCESSIBILITY_VALUE -> { viewManager.accessibilityValue(view, entry.stringValue) } VP_ACCESSIBLE -> { viewManager.setAccessible(view, entry.booleanValue) } VP_BACKFACE_VISIBILITY -> { viewManager.backfaceVisibility(view, entry.intValue) } VP_BG_COLOR -> { // TODO: color for some reason can be object in Java but not in C++ viewManager.backgroundColor(view, entry.intValue) } VP_FG_COLOR -> { // Prop not used on Android? } VP_BORDER_COLOR -> { viewManager.borderColor(view, entry.mapBufferValue) } VP_BORDER_RADII -> { viewManager.borderRadius(view, entry.mapBufferValue) } VP_BORDER_STYLE -> { val styleBuffer = entry.mapBufferValue if (styleBuffer.contains(CORNER_ALL)) { viewManager.borderStyle(view, (styleBuffer.getDouble(CORNER_ALL)).toInt()) } } VP_ELEVATION -> { viewManager.setElevation(view, entry.doubleValue.toFloat()) } VP_FOCUSABLE -> { viewManager.setFocusable(view, entry.booleanValue) } VP_HAS_TV_FOCUS -> { viewManager.setTVPreferredFocus(view, entry.booleanValue) } VP_HIT_SLOP -> { view.hitSlop(entry.mapBufferValue) } VP_IMPORTANT_FOR_ACCESSIBILITY -> { view.importantForAccessibility(entry.intValue) } VP_NATIVE_BACKGROUND -> { viewManager.nativeBackground(view, entry.mapBufferValue) } VP_NATIVE_FOREGROUND -> { viewManager.nativeForeground(view, entry.mapBufferValue) } VP_NATIVE_ID -> { viewManager.setNativeId(view, entry.stringValue.takeIf { it.isNotEmpty() }) } VP_OFFSCREEN_ALPHA_COMPOSITING -> { viewManager.setNeedsOffscreenAlphaCompositing(view, entry.booleanValue) } VP_OPACITY -> { viewManager.setOpacity(view, entry.doubleValue.toFloat()) } VP_POINTER_EVENTS -> { view.pointerEvents(entry.intValue) } VP_POINTER_ENTER -> { viewManager.setPointerEnter(view, entry.booleanValue) } VP_POINTER_LEAVE -> { viewManager.setPointerLeave(view, entry.booleanValue) } VP_POINTER_MOVE -> { viewManager.setPointerMove(view, entry.booleanValue) } VP_POINTER_ENTER_CAPTURE -> { viewManager.setPointerEnterCapture(view, entry.booleanValue) } VP_POINTER_LEAVE_CAPTURE -> { viewManager.setPointerLeaveCapture(view, entry.booleanValue) } VP_POINTER_MOVE_CAPTURE -> { viewManager.setPointerMoveCapture(view, entry.booleanValue) } VP_POINTER_OUT -> { viewManager.setPointerOut(view, entry.booleanValue) } VP_POINTER_OUT_CAPTURE -> { viewManager.setPointerOutCapture(view, entry.booleanValue) } VP_POINTER_OVER -> { viewManager.setPointerOver(view, entry.booleanValue) } VP_POINTER_OVER_CAPTURE -> { viewManager.setPointerOverCapture(view, entry.booleanValue) } VP_REMOVE_CLIPPED_SUBVIEW -> { viewManager.setRemoveClippedSubviews(view, entry.booleanValue) } VP_RENDER_TO_HARDWARE_TEXTURE -> { viewManager.setRenderToHardwareTexture(view, entry.booleanValue) } VP_SHADOW_COLOR -> { // TODO: color for some reason can be object in Java but not in C++ viewManager.shadowColor(view, entry.intValue) } VP_TEST_ID -> { viewManager.setTestId(view, entry.stringValue.takeIf { it.isNotEmpty() }) } VP_TRANSFORM -> { viewManager.transform(view, entry.mapBufferValue) } VP_ZINDEX -> { viewManager.setZIndex(view, entry.intValue.toFloat()) } YG_BORDER_WIDTH -> { viewManager.borderWidth(view, entry.mapBufferValue) } YG_OVERFLOW -> { viewManager.overflow(view, entry.intValue) } } } } private fun ReactViewManager.accessibilityActions(view: ReactViewGroup, mapBuffer: MapBuffer) { val actions = mutableListOf<ReadableMap>() for (entry in mapBuffer) { val map = JavaOnlyMap() val action = entry.mapBufferValue if (action != null) { map.putString("name", action.getString(ACCESSIBILITY_ACTION_NAME)) if (action.contains(ACCESSIBILITY_ACTION_LABEL)) { map.putString("label", action.getString(ACCESSIBILITY_ACTION_LABEL)) } } actions.add(map) } setAccessibilityActions(view, JavaOnlyArray.from(actions)) } private fun ReactViewGroup.accessibilityLiveRegion(value: Int) { val mode = when (value) { 0 -> ViewCompat.ACCESSIBILITY_LIVE_REGION_NONE 1 -> ViewCompat.ACCESSIBILITY_LIVE_REGION_POLITE 2 -> ViewCompat.ACCESSIBILITY_LIVE_REGION_ASSERTIVE else -> ViewCompat.ACCESSIBILITY_LIVE_REGION_NONE } ViewCompat.setAccessibilityLiveRegion(this, mode) } private fun ReactViewManager.accessibilityState(view: ReactViewGroup, value: MapBuffer) { val accessibilityState = JavaOnlyMap() accessibilityState.putBoolean("selected", value.getBoolean(ACCESSIBILITY_STATE_SELECTED)) accessibilityState.putBoolean("busy", value.getBoolean(ACCESSIBILITY_STATE_BUSY)) accessibilityState.putBoolean("expanded", value.getBoolean(ACCESSIBILITY_STATE_EXPANDED)) accessibilityState.putBoolean("disabled", value.getBoolean(ACCESSIBILITY_STATE_DISABLED)) when (value.getInt(ACCESSIBILITY_STATE_CHECKED)) { // Unchecked 0 -> accessibilityState.putBoolean("checked", false) // Checked 1 -> accessibilityState.putBoolean("checked", true) // Mixed 2 -> accessibilityState.putString("checked", "mixed") // 3 -> None } setViewState(view, accessibilityState) } private fun ReactViewManager.accessibilityValue(view: ReactViewGroup, value: String) { val map = JavaOnlyMap() if (value.isNotEmpty()) { map.putString("text", value) } setAccessibilityValue(view, map) } private fun ReactViewManager.accessibilityLabelledBy(view: ReactViewGroup, value: MapBuffer) { val converted = if (value.count == 0) { DynamicFromObject(null) } else { val array = JavaOnlyArray() for (label in value) { array.pushString(label.stringValue) } DynamicFromObject(array) } setAccessibilityLabelledBy(view, converted) } private fun ReactViewManager.backfaceVisibility(view: ReactViewGroup, value: Int) { val stringName = when (value) { 1 -> "visible" 2 -> "hidden" else -> "auto" } setBackfaceVisibility(view, stringName) } private fun ReactViewManager.backgroundColor(view: ReactViewGroup, value: Int) { val color = value.takeIf { it != UNDEF_COLOR } ?: Color.TRANSPARENT setBackgroundColor(view, color) } private fun ReactViewManager.borderColor(view: ReactViewGroup, value: MapBuffer) { for (entry in value) { val index = when (val key = entry.key) { EDGE_ALL -> 0 EDGE_LEFT -> 1 EDGE_RIGHT -> 2 EDGE_TOP -> 3 EDGE_BOTTOM -> 4 EDGE_START -> 5 EDGE_END -> 6 else -> throw IllegalArgumentException("Unknown key for border color: $key") } val colorValue = entry.intValue setBorderColor(view, index, colorValue.takeIf { it != -1 }) } } private fun ReactViewManager.borderRadius(view: ReactViewGroup, value: MapBuffer) { for (entry in value) { val index = when (val key = entry.key) { CORNER_ALL -> 0 CORNER_TOP_LEFT -> 1 CORNER_TOP_RIGHT -> 2 CORNER_BOTTOM_RIGHT -> 3 CORNER_BOTTOM_LEFT -> 4 CORNER_TOP_START -> 5 CORNER_TOP_END -> 6 CORNER_BOTTOM_START -> 7 CORNER_BOTTOM_END -> 8 else -> throw IllegalArgumentException("Unknown key for border style: $key") } val borderRadius = entry.doubleValue if (!borderRadius.isNaN()) { setBorderRadius(view, index, borderRadius.toFloat()) } } } private fun ReactViewManager.borderStyle(view: ReactViewGroup, value: Int) { val stringValue = when (value) { 0 -> "solid" 1 -> "dotted" 2 -> "dashed" else -> null } setBorderStyle(view, stringValue) } private fun ReactViewGroup.hitSlop(value: MapBuffer) { val rect = Rect( PixelUtil.toPixelFromDIP(value.getDouble(EDGE_LEFT)).toInt(), PixelUtil.toPixelFromDIP(value.getDouble(EDGE_TOP)).toInt(), PixelUtil.toPixelFromDIP(value.getDouble(EDGE_RIGHT)).toInt(), PixelUtil.toPixelFromDIP(value.getDouble(EDGE_BOTTOM)).toInt(), ) hitSlopRect = rect } private fun ReactViewGroup.importantForAccessibility(value: Int) { val mode = when (value) { 0 -> ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO 1 -> ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES 2 -> ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO 3 -> ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS else -> ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO } ViewCompat.setImportantForAccessibility(this, mode) } private fun ReactViewGroup.pointerEvents(value: Int) { val pointerEvents = when (value) { 0 -> PointerEvents.AUTO 1 -> PointerEvents.NONE 2 -> PointerEvents.BOX_NONE 3 -> PointerEvents.BOX_ONLY else -> throw IllegalArgumentException("Unknown value for pointer events: $value") } setPointerEvents(pointerEvents) } private fun ReactViewManager.transform(view: ReactViewGroup, value: MapBuffer) { val list = JavaOnlyArray() for (entry in value) { list.pushDouble(entry.doubleValue) } setTransform(view, list) } private fun ReactViewManager.borderWidth(view: ReactViewGroup, value: MapBuffer) { for (entry in value) { val index = when (val key = entry.key) { EDGE_ALL -> 0 EDGE_LEFT -> 1 EDGE_RIGHT -> 2 EDGE_TOP -> 3 EDGE_BOTTOM -> 4 EDGE_START -> 5 EDGE_END -> 6 else -> throw IllegalArgumentException("Unknown key for border width: $key") } val borderWidth = entry.doubleValue if (!borderWidth.isNaN()) { setBorderWidth(view, index, borderWidth.toFloat()) } } } private fun ReactViewManager.overflow(view: ReactViewGroup, value: Int) { val stringValue = when (value) { 0 -> "visible" 1 -> "hidden" 2 -> "scroll" else -> throw IllegalArgumentException("Unknown overflow value: $value") } setOverflow(view, stringValue) } private fun ReactViewManager.shadowColor(view: ReactViewGroup, value: Int) { val color = value.takeIf { it != UNDEF_COLOR } ?: Color.BLACK setShadowColor(view, color) } private fun ReactViewManager.nativeBackground(view: ReactViewGroup, value: MapBuffer) { setNativeBackground(view, value.toJsDrawableDescription()) } private fun ReactViewManager.nativeForeground(view: ReactViewGroup, value: MapBuffer) { setNativeForeground(view, value.toJsDrawableDescription()) } private fun MapBuffer.toJsDrawableDescription(): ReadableMap? { if (count == 0) { return null } val kind = getInt(NATIVE_DRAWABLE_KIND) val result = JavaOnlyMap() when (kind) { 0 -> { result.putString("type", "ThemeAttrAndroid") result.putString("attribute", getString(NATIVE_DRAWABLE_ATTRIBUTE)) } 1 -> { result.putString("type", "RippleAndroid") if (contains(NATIVE_DRAWABLE_COLOR)) { result.putInt("color", getInt(NATIVE_DRAWABLE_COLOR)) } result.putBoolean("borderless", getBoolean(NATIVE_DRAWABLE_BORDERLESS)) if (contains(NATIVE_DRAWABLE_RIPPLE_RADIUS)) { result.putDouble("rippleRadius", getDouble(NATIVE_DRAWABLE_RIPPLE_RADIUS)) } } else -> throw IllegalArgumentException("Unknown native drawable: $kind") } return result } }
mit
d8cefaa7a436e40b3807c008496757ae
34.281746
97
0.64914
4.443278
false
false
false
false
airbnb/epoxy
epoxy-sample/src/main/java/com/airbnb/epoxy/sample/models/TestModel2.kt
1
522
package com.airbnb.epoxy.sample.models import android.view.View import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyModel import com.airbnb.epoxy.EpoxyModelClass import com.airbnb.epoxy.sample.R @EpoxyModelClass(layout = R.layout.model_color) abstract class TestModel2 : EpoxyModel<View>() { @EpoxyAttribute var num: Int = 0 @EpoxyAttribute var num2: Int = 0 @EpoxyAttribute var num3: Int = 0 @EpoxyAttribute var num4: Int = 0 @EpoxyAttribute var num5: Int = 0 }
apache-2.0
e4e5119e7aed6fae799e2ded88cc35f0
22.727273
48
0.726054
3.755396
false
false
false
false
MGaetan89/ShowsRage
buildSrc/src/main/kotlin/Versions.kt
1
1018
object Versions { const val androidPlugin = "3.1.1" const val assertJAndroid = "1.2.0" const val compileSdk = 27 const val constraintLayout = "2.0.0-alpha1" const val crashlytics = "2.9.4" const val fabricPlugin = "1.25.4" const val fastscroll = "0.2.5" const val firebase = "16.0.1" const val firebaseJobDispatcher = "0.8.5" const val glide = "4.7.1" const val googleServicesPlugin = "4.0.1" const val jacoco = "0.8.1" const val jacocoPlugin = "0.12.0" const val jUnit = "4.12" const val kotlinPlugin = "1.2.51" const val minSdk = 19 const val mockito = "2.19.1" const val okHttp = "2.7.5" const val playServicesCast = "15.0.1" const val preferences = "27.1.1.2" const val realmAdapters = "3.0.0" const val realmPlugin = "5.3.1" const val retrofit = "1.9.0" const val sonarQubePlugin = "2.6.2" const val supportLibrary = "27.1.1" const val supportTestLibrary = "1.0.1" const val targetSdk = this.compileSdk }
apache-2.0
0588692044606b2a36349303ec061c46
34.103448
47
0.632613
3.029762
false
false
false
false
PlanBase/PdfLayoutMgr2
src/main/java/com/planbase/pdf/lm2/contents/WrappedCell.kt
1
13785
// Copyright 2017 PlanBase Inc. // // This file is part of PdfLayoutMgr2 // // PdfLayoutMgr 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. // // PdfLayoutMgr 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 PdfLayoutMgr. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>. // // If you wish to use this code with proprietary software, // contact PlanBase Inc. <https://planbase.com> to purchase a commercial license. package com.planbase.pdf.lm2.contents import com.planbase.pdf.lm2.attributes.Align import com.planbase.pdf.lm2.attributes.BorderStyle import com.planbase.pdf.lm2.attributes.CellStyle import com.planbase.pdf.lm2.attributes.DimAndPageNums import com.planbase.pdf.lm2.attributes.DimAndPageNums.Companion.INVALID_PAGE_RANGE import com.planbase.pdf.lm2.lineWrapping.LineWrapped import com.planbase.pdf.lm2.pages.RenderTarget import com.planbase.pdf.lm2.utils.Coord import com.planbase.pdf.lm2.utils.Dim import org.organicdesign.indented.IndentedStringable import org.organicdesign.indented.StringUtils.iterableToStr class WrappedCell(override val dim: Dim, // measured on the border lines val cellStyle: CellStyle, val rows: List<LineWrapped>, private val requiredSpaceBelow : Double) : LineWrapped, IndentedStringable { override val ascent: Double get() = dim.height override fun indentedStr(indent:Int): String = "WrappedCell($dim, $cellStyle, rows=\n" + "${iterableToStr(indent + "WrappedCell(".length, "listOf", rows)})" override fun toString() = indentedStr(0) private val wrappedBlockDim: Dim = { var width = 0.0 var height = 0.0 for (row in rows) { val rowDim = row.dim width = Math.max(width, rowDim.width) height += rowDim.height } if (cellStyle.align == Align.TOP_LEFT_JUSTIFY) { width = dim.width - cellStyle.boxStyle.leftRightInteriorSp() } Dim(width, height) }() override fun render(lp: RenderTarget, topLeft: Coord, reallyRender: Boolean, justifyWidth:Double): DimAndPageNums = renderCustom(lp, topLeft, dim.height, reallyRender, preventWidows = true) // See: CellTest.testWrapTable for issue. But we can isolate it by testing this method. fun renderCustom(lp: RenderTarget, tempTopLeft: Coord, height: Double, reallyRender: Boolean, preventWidows: Boolean): DimPageNumsAndTopLeft { // println("WrappedCell.renderCustom(${lp.javaClass.simpleName}, $tempTopLeft, $height, $reallyRender)") var pageNums:IntRange = INVALID_PAGE_RANGE var adj:Double var topLeft: Coord if (requiredSpaceBelow == 0.0) { adj = 0.0 topLeft = tempTopLeft } else { // Not part of a table. // // Given topLeft.y and dim, is there room for this cell plus requiredSpaceBelow on this page? // - Yes: Return topLeft.y unchanged. // - No: Is there room on any page? // - No: Return topLeft.y unchanged // - Yes: Return the y value of the top of the next page. // // If not, return the new innerTopLeft.y. // // NO: // Given innerTopLeft.y and wrappedBlockDim, is there room for the block plus requiredSpaceBelow // on this page? If not, return the new innerTopLeft.y. adj = lp.pageBreakingTopMargin(tempTopLeft.y - dim.height, dim.height, requiredSpaceBelow) topLeft = tempTopLeft.minusY(adj) } // Orphan prevention phase 1. I know this doesn't get everything, but have to run with this for now. // Proven to work in at least one case by WrappedCellTest.sixthBullet1LineBeforePgBreak() if ( preventWidows && (adj == 0.0) && (rows.size > 1) ) { val row0 = rows[0] val row1 = rows[1] if ( (row0 !is WrappedList) && (row1 !is WrappedList) ) { val firstTwoRowHeight = row0.dim.height + row1.dim.height adj = lp.pageBreakingTopMargin(topLeft.y - firstTwoRowHeight, firstTwoRowHeight) // println("adj=$adj") if (adj != 0.0) { topLeft = topLeft.minusY(adj) } } } // println("topLeft=$topLeft") // println(" cellStyle=$cellStyle") val boxStyle = cellStyle.boxStyle val border = boxStyle.border // Dim dim = padding.addTo(pcrs.dim); // Draw contents over background, but under border val finalDim = if (dim.height < height) { dim.withHeight(height) } else { dim } // println(" finalDim=$finalDim") val innerDim: Dim = boxStyle.subtractFrom(finalDim) // println(" innerDim=$innerDim") val innerTopLeft = cellStyle.align.innerTopLeft(innerDim, wrappedBlockDim, boxStyle.applyTopLeft(topLeft)) // println(" innerTopLeft=$innerTopLeft") var finalTopLeft = topLeft var y = innerTopLeft.y val lastRow: LineWrapped? = if (rows.isNotEmpty()) { rows[rows.size - 1] } else { null } for ((index, row) in rows.withIndex()) { // println("row=$row") val rowXOffset = cellStyle.align.leftOffset(wrappedBlockDim.width, row.dim.width) // Widow prevention: // If the last line of a paragraph would end up on the next page, push the last TWO lines // onto that page so that neither page is left with a single line widow or orphan. // // Don't do this in a table! Nothing would look weirder than one cell in a row starting on // the next page! // TODO: Did I take care of the case where we are at the top of a page already? if ( preventWidows && (lastRow !is WrappedList) ) { // I tried this 3-row rule, but it didn't work and I became less enamored of the idea. For one thing, // what if there's a heading above this paragraph and we sneak it onto the next page leaving the // paragraph hanging? No, I think to start that simpler is better. If Margaret has to fix one of // these, she can. // // If there are only 3 rows, splitting into 2 and 1 still leaves a lonely row. To avoid that, push // all three to the next page. Less sure about this rule. // if (rows.size == 3) { // if (index == 0) { // val penUltimateRow: MultiLineWrapped = rows[1] // val lastRow: MultiLineWrapped = rows[2] // println("=================== 3 FROM END y=$y") // println("row=$row") // println("penUltimate=$penUltimateRow") // println("lastRow=$lastRow") // y -= lp.pageBreakingTopMargin(y - row.lineHeight, row.lineHeight + penUltimateRow.lineHeight, // lastRow.lineHeight) // println("newY=$y\n") // } // } else // Only do this if both rows will fit on one page! if ( (index == rows.size - 2) && ((row.dim.height + lastRow!!.dim.height) < lp.body.dim.height) ) { // I thought we could call lp.pageBreakingTopMargin to see if the two lines would fit on the // page, but I guess a MultiLineWrapped can have items of different ascent and descent and leading // such that it could have some effect on page-breaking. Honestly, I'm not sure why it would. // But the solution, at least for now, is to instead call render(reallyRender=false). // Returns zero if the last 2 rows fit on this page, otherwise, returns enough offset to push both // to the next page. val finalTwoRowsHeight: Double = row.dim.height + lastRow.dim.height // println("finalTwoRowsHeight=$finalTwoRowsHeight") val adj2 = lp.pageBreakingTopMargin(y - finalTwoRowsHeight, finalTwoRowsHeight, 0.0) // println("adj expected=9.890003 actaul=$adj") y -= adj2 if (rows.size == 2) { finalTopLeft = finalTopLeft.minusY(adj2) } // println("newY expected=37.0 actual=$y\n") // Correct! } // End if this row might need to go to next page to avoid a widow } // End if preventWidows val dimAndPages = row.render(lp, Coord(rowXOffset + innerTopLeft.x, y), reallyRender, if ( (index < rows.size - 1) && (cellStyle.align == Align.TOP_LEFT_JUSTIFY) ) { // Even if we're justifying text, the last row looks better unjustified. innerDim.width } else { 0.0 }) // println("dimAndPages.dim.height=${dimAndPages.dim.height}") y -= dimAndPages.dim.height // y is always the lowest row in the cell. pageNums = dimAndPages.maxExtents(pageNums) } // end for each row // println(" y=$y") // println(" totalHeight=${innerTopLeft.y - y}") // TODO: test that we add bottom padding to y y = minOf(y, topLeft.y - height) // println("height=${innerTopLeft.y - y}") // Draw background first (if necessary) so that everything else ends up on top of it. if (boxStyle.bgColor != null) { // System.out.println("\tCell.render calling putRect..."); lp.fillRect(topLeft.withY(y), dim.withHeight(topLeft.y - y), boxStyle.bgColor, reallyRender) // System.out.println("\tCell.render back from putRect"); } val rightX = topLeft.x + dim.width // Draw border last to cover anything that touches it? if (border != BorderStyle.NO_BORDERS) { val origX = topLeft.x val origY = topLeft.y val topRight = Coord(rightX, origY) val bottomRight = Coord(rightX, y) val bottomLeft = Coord(origX, y) // I'm not using multi-line drawing here (now/yet). // It's complicated, and if there's page breaking it won't work anyway. if ( (pageNums.start == pageNums.endInclusive) && // same page (border.top.thickness > 0) && border.allSame()) { lp.drawLineLoop(listOf(topLeft, topLeft.withX(rightX), Coord(rightX, y), topLeft.withY(y)), border.top, border.lineJoinStyle, null, true) } else { if (border.top.thickness > 0) { lp.drawLine(if (border.left.thickness > 0) { topLeft.plusX(border.left.thickness / -2.0) } else { topLeft }, if (border.right.thickness > 0) { topRight.plusX(border.right.thickness / 2.0) } else { topRight }, border.top, border.lineJoinStyle, reallyRender) } if (border.right.thickness > 0) { lp.drawLine(if (border.top.thickness > 0) { topRight.minusY(border.top.thickness / -2.0) } else { topRight }, if (border.bottom.thickness > 0) { bottomRight.minusY(border.bottom.thickness / 2.0) } else { bottomRight }, border.right, border.lineJoinStyle, reallyRender) } if (border.bottom.thickness > 0) { lp.drawLine(if (border.right.thickness > 0) { bottomRight.plusX(border.right.thickness / 2.0) } else { bottomRight }, if (border.left.thickness > 0) { bottomLeft.plusX(border.left.thickness / 2.0) } else { bottomLeft }, border.bottom, border.lineJoinStyle, reallyRender) } if (border.left.thickness > 0) { lp.drawLine(if (border.bottom.thickness > 0) { bottomLeft.minusY(border.bottom.thickness / 2.0) } else { bottomLeft }, if (border.top.thickness > 0) { topLeft.minusY(border.top.thickness / -2.0) } else { topLeft }, border.left, border.lineJoinStyle, reallyRender) } } } return DimPageNumsAndTopLeft(Dim(rightX - topLeft.x, (topLeft.y - y) + adj ), pageNums, finalTopLeft) } class DimPageNumsAndTopLeft(dim: Dim, pageNums: IntRange, val topLeft: Coord) : DimAndPageNums(dim, pageNums) }
agpl-3.0
e26b30961013e007aca400f4ec2204bb
50.827068
140
0.562568
4.534539
false
false
false
false
GwonHyeok/StickySwitch
stickyswitch/src/main/kotlin/io/ghyeok/stickyswitch/widget/StickySwitch.kt
1
23868
/* * MIT License * * Copyright (c) 2017 GwonHyeok * * 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 io.ghyeok.stickyswitch.widget import android.animation.Animator import android.animation.AnimatorSet import android.animation.ValueAnimator import android.annotation.TargetApi import android.content.Context import android.graphics.* import android.graphics.drawable.Drawable import android.os.Build import android.util.AttributeSet import android.view.MotionEvent import android.view.MotionEvent.ACTION_UP import android.view.View import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.AccelerateInterpolator import android.view.animation.DecelerateInterpolator import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import androidx.appcompat.content.res.AppCompatResources import io.ghyeok.stickyswitch.R /** * Created by ghyeok on 2017. 3. 13.. * * This class implements a beautiful switch widget for android * * @author GwonHyeok */ class StickySwitch : View { @Suppress("unused", "PrivatePropertyName") private val TAG = "StickySwitch" enum class AnimationType { LINE, CURVED } enum class TextVisibility { VISIBLE, INVISIBLE, GONE } // left, right icon drawable var leftIcon: Drawable? = null set(drawable) { field = drawable invalidate() } var rightIcon: Drawable? = null set(drawable) { field = drawable invalidate() } // icon variables var iconSize = 100 set(value) { field = value invalidate() } var iconPadding = 70 set(value) { field = value invalidate() } // text variables var leftText = "" set(value) { field = value invalidate() } var rightText = "" set(value) { field = value invalidate() } // colors var sliderBackgroundColor = 0XFF181821.toInt() set(@ColorInt colorInt) { field = colorInt invalidate() } var switchColor = 0xFF2371FA.toInt() set(@ColorInt colorInt) { field = colorInt invalidate() } var textColor = 0xFFFFFFFF.toInt() set(@ColorInt colorInt) { field = colorInt invalidate() } // typeface var typeFace: Typeface? = null set(typeFace) { field = typeFace leftTextPaint.typeface = typeFace rightTextPaint.typeface = typeFace invalidate() } // rounded rect private val sliderBackgroundPaint = Paint() private val sliderBackgroundRect = RectF() // circular switch private val switchBackgroundPaint = Paint() // left, right text paint and size private val leftTextPaint = Paint() private val leftTextRect = Rect() private val rightTextPaint = Paint() private val rightTextRect = Rect() // left, right text size private var leftTextSize = 50f set(value) { field = value invalidate() } private var rightTextSize = 50f set(value) { field = value invalidate() } // text max,min transparency private val textAlphaMax = 255 private val textAlphaMin = 163 // text color transparency private var leftTextAlpha = textAlphaMax set(value) { field = value invalidate() } private var rightTextAlpha = textAlphaMin set(value) { field = value invalidate() } // text size private var textSize = 50 set(value) { field = value invalidate() } // text size when selected status private var selectedTextSize = 50 set(value) { field = value invalidate() } // switch Status // false : left status // true : right status private var isSwitchOn = false set(value) { field = value invalidate() } // percent of switch animation // animatePercent will be 0.0 ~ 1.0 private var animatePercent: Double = 0.0 set(value) { field = value invalidate() } // circular switch bounce rate // animateBounceRate will be 1.1 ~ 0.0 private var animateBounceRate: Double = 1.0 set(value) { field = value invalidate() } // type of transition animation between states var animationType = AnimationType.LINE set(value) { field = value invalidate() } // listener var onSelectedChangeListener: OnSelectedChangeListener? = null // AnimatorSet, Animation Options var animatorSet: AnimatorSet? = null var animationDuration: Long = 600 // state of text visibility var textVisibility = TextVisibility.VISIBLE set(value) { field = value invalidate() } constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init(attrs, defStyleAttr) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { init(attrs, defStyleAttr, defStyleRes) } init { isClickable = true } fun setA(onSelectedChangeListener: OnSelectedChangeListener) { this.onSelectedChangeListener = onSelectedChangeListener } private fun init(attrs: AttributeSet?, defStyleAttr: Int = 0, defStyleRes: Int = 0) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.StickySwitch, defStyleAttr, defStyleRes) // left switch icon leftIcon = typedArray.getDrawable(R.styleable.StickySwitch_ss_leftIcon) leftText = typedArray.getString(R.styleable.StickySwitch_ss_leftText) ?: leftText // right switch icon rightIcon = typedArray.getDrawable(R.styleable.StickySwitch_ss_rightIcon) rightText = typedArray.getString(R.styleable.StickySwitch_ss_rightText) ?: rightText // icon size iconSize = typedArray.getDimensionPixelSize(R.styleable.StickySwitch_ss_iconSize, iconSize) iconPadding = typedArray.getDimensionPixelSize(R.styleable.StickySwitch_ss_iconPadding, iconPadding) // saved text size textSize = typedArray.getDimensionPixelSize(R.styleable.StickySwitch_ss_textSize, textSize) selectedTextSize = typedArray.getDimensionPixelSize(R.styleable.StickySwitch_ss_selectedTextSize, selectedTextSize) // current text size leftTextSize = selectedTextSize.toFloat() rightTextSize = textSize.toFloat() // slider background color sliderBackgroundColor = typedArray.getColor(R.styleable.StickySwitch_ss_sliderBackgroundColor, sliderBackgroundColor) // switch color switchColor = typedArray.getColor(R.styleable.StickySwitch_ss_switchColor, switchColor) // text color textColor = typedArray.getColor(R.styleable.StickySwitch_ss_textColor, textColor) // animation duration animationDuration = typedArray.getInt(R.styleable.StickySwitch_ss_animationDuration, animationDuration.toInt()).toLong() //animation type animationType = AnimationType.values()[typedArray.getInt(R.styleable.StickySwitch_ss_animationType, AnimationType.LINE.ordinal)] // text visibility textVisibility = TextVisibility.values()[typedArray.getInt(R.styleable.StickySwitch_ss_textVisibility, TextVisibility.VISIBLE.ordinal)] typedArray.recycle() } //used to draw connection between two circle private val connectionPath = Path() val xParam = 1 / 2f //Math.sin(Math.PI / 6).toFloat() val yParam = 0.86602540378f //Math.cos(Math.PI / 6).toFloat() /** * Draw Sticky Switch View * * Animation * * 0% ~ 50% * radius : circle radius -> circle radius / 2 * x : x -> x + widthSpace * y : y * * 50% ~ 100% * radius : circle radius / 2 -> circle radius * x : x + widthSpace -> x + widthSpace * y : y * * @param canvas the canvas on which the background will be drawn */ override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) // icon margin val iconMarginLeft = iconPadding val iconMarginBottom = iconPadding val iconMarginRight = iconPadding val iconMarginTop = iconPadding // icon width, height val iconWidth = iconSize val iconHeight = iconSize // circle Radius val sliderRadius = iconMarginTop + iconHeight / 2f val circleRadius = iconMarginTop + iconHeight / 2f // draw circular rect sliderBackgroundPaint.color = sliderBackgroundColor sliderBackgroundRect.set(0f, 0f, measuredWidth.toFloat(), (iconMarginTop + iconHeight + iconMarginBottom).toFloat()) canvas?.drawRoundRect(sliderBackgroundRect, sliderRadius, sliderRadius, sliderBackgroundPaint) // switch background switchBackgroundPaint.color = switchColor canvas?.save() // if animation is before half val isBeforeHalf = animatePercent in 0.0..0.5 // width at which objects move in animation val widthSpace = measuredWidth - circleRadius * 2 // original circular switch x, y, radius val ocX = (circleRadius + widthSpace * Math.min(1.0, animatePercent * 2)) val ocY = circleRadius val ocRadius = circleRadius * (if (isBeforeHalf) 1.0 - animatePercent else animatePercent) // copied circular switch x, y, radius val ccX = (circleRadius + widthSpace * (if (isBeforeHalf) 0.0 else Math.abs(0.5 - animatePercent) * 2)) val ccY = circleRadius val ccRadius = circleRadius * (if (isBeforeHalf) 1.0 - animatePercent else animatePercent) // circular rectangle val rectL = ccX val rectR = ocX canvas?.drawCircle(ocX.toFloat(), ocY, evaluateBounceRate(ocRadius).toFloat(), switchBackgroundPaint) canvas?.drawCircle(ccX.toFloat(), ccY, evaluateBounceRate(ccRadius).toFloat(), switchBackgroundPaint) if (animationType == AnimationType.LINE) { val rectT = circleRadius - circleRadius / 2 val rectB = circleRadius + circleRadius / 2 canvas?.drawCircle(ccX.toFloat(), ccY, evaluateBounceRate(ccRadius).toFloat(), switchBackgroundPaint) canvas?.drawRect(rectL.toFloat(), rectT, rectR.toFloat(), rectB, switchBackgroundPaint) } else if (animationType == AnimationType.CURVED) { // curved connection between two circles if (animatePercent > 0 && animatePercent < 1) { connectionPath.rewind() //puts points of rectangle on circle, on point π/6 rad val rectLCurve = rectL.toFloat() + ccRadius.toFloat() * xParam val rectRCurve = rectR.toFloat() - ccRadius.toFloat() * xParam val rectTCurve = circleRadius - ccRadius.toFloat() * yParam val rectBCurve = circleRadius + ccRadius.toFloat() * yParam //middle points through which goes cubic interpolation val middlePointX = (rectRCurve + rectLCurve) / 2 val middlePointY = (rectTCurve + rectBCurve) / 2 // draws 'rectangle', but in the way that top line is concave, and bottom is convex connectionPath.moveTo(rectLCurve, rectTCurve) connectionPath.cubicTo( rectLCurve, rectTCurve, middlePointX, middlePointY, rectRCurve, rectTCurve ) connectionPath.lineTo( rectRCurve, rectBCurve ) connectionPath.cubicTo( rectRCurve, rectBCurve, middlePointX, middlePointY, rectLCurve, rectBCurve ) connectionPath.close() canvas?.drawPath(connectionPath, switchBackgroundPaint) } } canvas?.restore() // draw left icon leftIcon?.run { canvas?.let { it.save() setBounds(iconMarginLeft, iconMarginTop, iconMarginLeft + iconWidth, iconMarginTop + iconHeight) alpha = if (isSwitchOn) 153 else 255 draw(it) it.restore() } } // draw right icon rightIcon?.run { canvas?.let { it.save() setBounds(measuredWidth - iconWidth - iconMarginRight, iconMarginTop, measuredWidth - iconMarginRight, iconMarginTop + iconHeight) alpha = if (!isSwitchOn) 153 else 255 draw(it) it.restore() } } // bottom space val bottomSpaceHeight = measuredHeight - (circleRadius * 2) // set text paint leftTextPaint.color = textColor leftTextPaint.alpha = leftTextAlpha rightTextPaint.color = textColor rightTextPaint.alpha = rightTextAlpha // set text size leftTextPaint.textSize = leftTextSize rightTextPaint.textSize = rightTextSize // draw text when isShowText is true if (textVisibility == TextVisibility.VISIBLE) { // measure text size measureText() // left text position val leftTextX = (circleRadius * 2 - leftTextRect.width()) * 0.5 val leftTextY = (circleRadius * 2) + (bottomSpaceHeight * 0.5) + (leftTextRect.height() * 0.25) // draw left text canvas?.save() canvas?.drawText(leftText, leftTextX.toFloat(), leftTextY.toFloat(), leftTextPaint) canvas?.restore() // right text position val rightTextX = ((circleRadius * 2 - rightTextRect.width()) * 0.5) + (measuredWidth - (circleRadius * 2)) val rightTextY = (circleRadius * 2) + (bottomSpaceHeight * 0.5) + (rightTextRect.height() * 0.25) // draw right text canvas?.save() canvas?.drawText(rightText, rightTextX.toFloat(), rightTextY.toFloat(), rightTextPaint) canvas?.restore() } } private fun evaluateBounceRate(value: Double): Double = value * animateBounceRate override fun onTouchEvent(event: MotionEvent?): Boolean { if (isEnabled.not() || isClickable.not()) return false when (event?.action) { ACTION_UP -> { isSwitchOn = isSwitchOn.not() animateCheckState(isSwitchOn) notifySelectedChange() } } return super.onTouchEvent(event) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { // measure text size measureText() val diameter = (iconPadding + iconSize / 2) * 2 val textWidth = leftTextRect.width() + rightTextRect.width() val measuredTextHeight = if (textVisibility == TextVisibility.GONE) 0 else selectedTextSize * 2 val heightMode = MeasureSpec.getMode(heightMeasureSpec) var heightSize = 0 when (heightMode) { MeasureSpec.UNSPECIFIED -> heightSize = heightMeasureSpec MeasureSpec.AT_MOST -> heightSize = diameter + measuredTextHeight MeasureSpec.EXACTLY -> heightSize = MeasureSpec.getSize(heightMeasureSpec) } val widthMode = MeasureSpec.getMode(widthMeasureSpec) var widthSize = 0 when (widthMode) { MeasureSpec.UNSPECIFIED -> widthSize = widthMeasureSpec MeasureSpec.AT_MOST -> widthSize = diameter * 2 + textWidth MeasureSpec.EXACTLY -> widthSize = MeasureSpec.getSize(widthMeasureSpec) } setMeasuredDimension(widthSize, heightSize) } @JvmOverloads fun setDirection(direction: Direction, isAnimate: Boolean = true, shouldTriggerSelected: Boolean = true) { val newSwitchState = when (direction) { Direction.LEFT -> false Direction.RIGHT -> true } if (newSwitchState != isSwitchOn) { isSwitchOn = newSwitchState // cancel animation when if animate is running animatorSet?.cancel() // when isAnimate is false not showing liquid animation if (isAnimate) animateCheckState(isSwitchOn) else changeCheckState(isSwitchOn) if (shouldTriggerSelected) { notifySelectedChange() } } } fun getDirection(): Direction = when (isSwitchOn) { true -> Direction.RIGHT false -> Direction.LEFT } @JvmOverloads fun getText(direction: Direction = getDirection()): String = when (direction) { Direction.LEFT -> leftText Direction.RIGHT -> rightText } fun setLeftIcon(@DrawableRes resourceId: Int) { this.leftIcon = this.getDrawable(resourceId) } fun setRightIcon(@DrawableRes resourceId: Int) { this.rightIcon = this.getDrawable(resourceId) } private fun getDrawable(@DrawableRes resourceId: Int) = AppCompatResources.getDrawable(context, resourceId) private fun notifySelectedChange() { onSelectedChangeListener?.onSelectedChange(if (isSwitchOn) Direction.RIGHT else Direction.LEFT, getText()) } private fun measureText() { leftTextPaint.getTextBounds(leftText, 0, leftText.length, leftTextRect) rightTextPaint.getTextBounds(rightText, 0, rightText.length, rightTextRect) } private fun animateCheckState(newCheckedState: Boolean) { this.animatorSet = AnimatorSet() if (animatorSet != null) { animatorSet?.playTogether( getLiquidAnimator(newCheckedState), leftTextSizeAnimator(newCheckedState), rightTextSizeAnimator(newCheckedState), leftTextAlphaAnimator(newCheckedState), rightTextAlphaAnimator(newCheckedState), getBounceAnimator() ) animatorSet?.start() } } private fun changeCheckState(newCheckedState: Boolean) { // Change TextAlpha Without Animation leftTextAlpha = if (newCheckedState) textAlphaMin else textAlphaMax rightTextAlpha = if (newCheckedState) textAlphaMax else textAlphaMin // Change TextSize without animation leftTextSize = if (newCheckedState) textSize.toFloat() else selectedTextSize.toFloat() rightTextSize = if (newCheckedState) selectedTextSize.toFloat() else textSize.toFloat() // Change Animate Percent(LiquidAnimation) without animation animatePercent = if (newCheckedState) 1.0 else 0.0 animateBounceRate = 1.0 } private fun leftTextAlphaAnimator(newCheckedState: Boolean): Animator { val toAlpha = if (newCheckedState) textAlphaMin else textAlphaMax val animator = ValueAnimator.ofInt(leftTextAlpha, toAlpha) animator.interpolator = AccelerateDecelerateInterpolator() animator.startDelay = animationDuration / 3 animator.duration = animationDuration - (animationDuration / 3) animator.addUpdateListener { leftTextAlpha = (it.animatedValue as Int) } return animator } private fun rightTextAlphaAnimator(newCheckedState: Boolean): Animator { val toAlpha = if (newCheckedState) textAlphaMax else textAlphaMin val animator = ValueAnimator.ofInt(rightTextAlpha, toAlpha) animator.interpolator = AccelerateDecelerateInterpolator() animator.startDelay = animationDuration / 3 animator.duration = animationDuration - (animationDuration / 3) animator.addUpdateListener { rightTextAlpha = (it.animatedValue as Int) } return animator } private fun leftTextSizeAnimator(newCheckedState: Boolean): Animator { val toTextSize = if (newCheckedState) textSize else selectedTextSize val textSizeAnimator = ValueAnimator.ofFloat(leftTextSize, toTextSize.toFloat()) textSizeAnimator.interpolator = AccelerateDecelerateInterpolator() textSizeAnimator.startDelay = animationDuration / 3 textSizeAnimator.duration = animationDuration - (animationDuration / 3) textSizeAnimator.addUpdateListener { leftTextSize = (it.animatedValue as Float) } return textSizeAnimator } private fun rightTextSizeAnimator(newCheckedState: Boolean): Animator { val toTextSize = if (newCheckedState) selectedTextSize else textSize val textSizeAnimator = ValueAnimator.ofFloat(rightTextSize, toTextSize.toFloat()) textSizeAnimator.interpolator = AccelerateDecelerateInterpolator() textSizeAnimator.startDelay = animationDuration / 3 textSizeAnimator.duration = animationDuration - (animationDuration / 3) textSizeAnimator.addUpdateListener { rightTextSize = (it.animatedValue as Float) } return textSizeAnimator } private fun getLiquidAnimator(newCheckedState: Boolean): Animator { val liquidAnimator = ValueAnimator.ofFloat(animatePercent.toFloat(), if (newCheckedState) 1f else 0f) liquidAnimator.duration = animationDuration liquidAnimator.interpolator = AccelerateInterpolator() liquidAnimator.addUpdateListener { animatePercent = (it.animatedValue as Float).toDouble() } return liquidAnimator } private fun getBounceAnimator(): Animator { val animator = ValueAnimator.ofFloat(1f, 0.9f, 1f) animator.duration = (animationDuration * 0.41).toLong() animator.startDelay = animationDuration animator.interpolator = DecelerateInterpolator() animator.addUpdateListener { animateBounceRate = (it.animatedValue as Float).toDouble() } return animator } enum class Direction { LEFT, RIGHT } interface OnSelectedChangeListener { fun onSelectedChange(direction: Direction, text: String) } }
mit
0ff009095e58aab35876f5873c52ae11
34.358519
146
0.636067
5.356149
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignature.kt
1
13007
// 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.changeSignature import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.NlsContexts import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementFactory import com.intellij.psi.PsiMethod import com.intellij.psi.PsiType import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.changeSignature.* import com.intellij.refactoring.ui.RefactoringDialog import com.intellij.refactoring.util.CanonicalTypes import com.intellij.util.VisibilityUtil import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.refactoring.CallableRefactoring import org.jetbrains.kotlin.idea.refactoring.broadcastRefactoringExit import org.jetbrains.kotlin.idea.refactoring.changeSignature.ui.KotlinChangePropertySignatureDialog import org.jetbrains.kotlin.idea.refactoring.changeSignature.ui.KotlinChangeSignatureDialog import org.jetbrains.kotlin.idea.refactoring.createJavaMethod import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.withPsiAttachment import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments interface KotlinChangeSignatureConfiguration { fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor = originalDescriptor fun performSilently(affectedFunctions: Collection<PsiElement>): Boolean = false fun forcePerformForSelectedFunctionOnly(): Boolean = false object Empty : KotlinChangeSignatureConfiguration } fun KotlinMethodDescriptor.modify(action: (KotlinMutableMethodDescriptor) -> Unit): KotlinMethodDescriptor { val newDescriptor = KotlinMutableMethodDescriptor(this) action(newDescriptor) return newDescriptor } fun runChangeSignature( project: Project, editor: Editor?, callableDescriptor: CallableDescriptor, configuration: KotlinChangeSignatureConfiguration, defaultValueContext: PsiElement, @NlsContexts.Command commandName: String? = null ): Boolean { val result = KotlinChangeSignature(project, editor, callableDescriptor, configuration, defaultValueContext, commandName).run() if (!result) { broadcastRefactoringExit(project, "refactoring.changeSignature") } return result } class KotlinChangeSignature( project: Project, editor: Editor?, callableDescriptor: CallableDescriptor, val configuration: KotlinChangeSignatureConfiguration, private val defaultValueContext: PsiElement, @NlsContexts.Command commandName: String? ) : CallableRefactoring<CallableDescriptor>( project, editor, callableDescriptor, commandName ?: RefactoringBundle.message("changeSignature.refactoring.name") ) { override fun forcePerformForSelectedFunctionOnly() = configuration.forcePerformForSelectedFunctionOnly() /** * @param propertyProcessor: * - top level * - member level * - primary constructor * * @param functionProcessor: * - top level * - member level * - local level * - constructors * * @param javaProcessor: * - member level */ private fun <T> selectRefactoringProcessor( descriptor: KotlinMethodDescriptor, propertyProcessor: (KotlinMethodDescriptor) -> T?, functionProcessor: (KotlinMethodDescriptor) -> T?, javaProcessor: (KotlinMethodDescriptor, PsiMethod) -> T?, ): T? { return when (val baseDeclaration = descriptor.baseDeclaration) { is KtProperty, is KtParameter -> propertyProcessor(descriptor) /** * functions: * - top level * - member level * - constructors * * class: * - primary constructor */ is KtFunction, is KtClass -> functionProcessor(descriptor) is PsiMethod -> { if (baseDeclaration.language != JavaLanguage.INSTANCE) { Messages.showErrorDialog( KotlinBundle.message("error.text.can.t.change.signature.of.method", baseDeclaration.language.displayName), commandName ) return null } javaProcessor(descriptor, baseDeclaration) } else -> throw KotlinExceptionWithAttachments("Unexpected declaration: ${baseDeclaration::class}") .withPsiAttachment("element.kt", baseDeclaration) .withPsiAttachment("file.kt", baseDeclaration.containingFile) } } @TestOnly fun createSilentRefactoringProcessor(methodDescriptor: KotlinMethodDescriptor): BaseRefactoringProcessor? = selectRefactoringProcessor( methodDescriptor, propertyProcessor = { KotlinChangePropertySignatureDialog.createProcessorForSilentRefactoring(project, commandName, it) }, functionProcessor = { KotlinChangeSignatureDialog.createRefactoringProcessorForSilentChangeSignature( project, commandName, it, defaultValueContext ) }, javaProcessor = { descriptor, _ -> ChangeSignatureProcessor(project, getPreviewInfoForJavaMethod(descriptor).second) } ) private fun runSilentRefactoring(methodDescriptor: KotlinMethodDescriptor) { createSilentRefactoringProcessor(methodDescriptor)?.run() } private fun runInteractiveRefactoring(methodDescriptor: KotlinMethodDescriptor) { val dialog = selectRefactoringProcessor( methodDescriptor, propertyProcessor = { KotlinChangePropertySignatureDialog(project, it, commandName) }, functionProcessor = { KotlinChangeSignatureDialog(project, editor, it, defaultValueContext, commandName) }, javaProcessor = fun(descriptor: KotlinMethodDescriptor, method: PsiMethod): RefactoringDialog? { if (descriptor is KotlinChangeSignatureData) { ChangeSignatureUtil.invokeChangeSignatureOn(method, project) return null } val (preview, javaChangeInfo) = getPreviewInfoForJavaMethod(descriptor) val javaDescriptor = object : JavaMethodDescriptor(preview) { @Suppress("UNCHECKED_CAST") override fun getParameters() = javaChangeInfo.newParameters.toMutableList() as MutableList<ParameterInfoImpl> } return object : JavaChangeSignatureDialog(project, javaDescriptor, false, null) { override fun createRefactoringProcessor(): BaseRefactoringProcessor { val parameters = parameters LOG.assertTrue(myMethod.method.isValid) val newJavaChangeInfo = JavaChangeInfoImpl( visibility ?: VisibilityUtil.getVisibilityModifier(myMethod.method.modifierList), javaChangeInfo.method, methodName, returnType ?: CanonicalTypes.createTypeWrapper(PsiType.VOID), parameters.toTypedArray(), exceptions, isGenerateDelegate, myMethodsToPropagateParameters ?: HashSet(), myMethodsToPropagateExceptions ?: HashSet() ).also { it.setCheckUnusedParameter() } return ChangeSignatureProcessor(myProject, newJavaChangeInfo) } } }, ) ?: return if (isUnitTestMode()) { try { dialog.performOKAction() } finally { dialog.close(DialogWrapper.OK_EXIT_CODE) } } else { dialog.show() } } private fun getPreviewInfoForJavaMethod(descriptor: KotlinMethodDescriptor): Pair<PsiMethod, JavaChangeInfo> { val originalMethod = descriptor.baseDeclaration as PsiMethod val contextFile = defaultValueContext.containingFile as KtFile // Generate new Java method signature from the Kotlin point of view val ktChangeInfo = KotlinChangeInfo(methodDescriptor = descriptor, context = defaultValueContext) val ktSignature = ktChangeInfo.getNewSignature(descriptor.originalPrimaryCallable) val previewClassName = if (originalMethod.isConstructor) originalMethod.name else "Dummy" val dummyFileText = with(StringBuilder()) { contextFile.packageDirective?.let { append(it.text).append("\n") } append("class $previewClassName {\n").append(ktSignature).append("{}\n}") toString() } val dummyFile = KtPsiFactory(originalMethod.project).createPhysicalFile("dummy.kt", dummyFileText) val dummyDeclaration = (dummyFile.declarations.first() as KtClass).body!!.declarations.first() // Convert to PsiMethod which can be used in Change Signature dialog val containingClass = PsiElementFactory.getInstance(project).createClass(previewClassName) val preview = createJavaMethod(dummyDeclaration.getRepresentativeLightMethod()!!, containingClass) // Create JavaChangeInfo based on new signature // TODO: Support visibility change val visibility = VisibilityUtil.getVisibilityModifier(originalMethod.modifierList) val returnType = CanonicalTypes.createTypeWrapper(preview.returnType ?: PsiType.VOID) val params = (preview.parameterList.parameters.zip(ktChangeInfo.newParameters)).map { val (param, paramInfo) = it // Keep original default value for proper update of Kotlin usages KotlinAwareJavaParameterInfoImpl(paramInfo.oldIndex, param.name, param.type, paramInfo.defaultValueForCall) }.toTypedArray() return preview to JavaChangeInfoImpl( visibility, originalMethod, preview.name, returnType, params, arrayOf<ThrownExceptionInfo>(), false, emptySet<PsiMethod>(), emptySet<PsiMethod>() ) } override fun performRefactoring(descriptorsForChange: Collection<CallableDescriptor>) { val adjustedDescriptor = adjustDescriptor(descriptorsForChange) ?: return val affectedFunctions = adjustedDescriptor.affectedCallables.mapNotNull { it.element } if (affectedFunctions.any { !checkModifiable(it) }) return if (configuration.performSilently(affectedFunctions)) { runSilentRefactoring(adjustedDescriptor) } else { runInteractiveRefactoring(adjustedDescriptor) } } fun adjustDescriptor(descriptorsForSignatureChange: Collection<CallableDescriptor>): KotlinMethodDescriptor? { val baseDescriptor = preferContainedInClass(descriptorsForSignatureChange) val functionDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, baseDescriptor) if (functionDeclaration == null) { LOG.error("Could not find declaration for $baseDescriptor") return null } if (!checkModifiable(functionDeclaration)) { return null } val originalDescriptor = KotlinChangeSignatureData(baseDescriptor, functionDeclaration, descriptorsForSignatureChange) return configuration.configure(originalDescriptor) } private fun preferContainedInClass(descriptorsForSignatureChange: Collection<CallableDescriptor>): CallableDescriptor { for (descriptor in descriptorsForSignatureChange) { val containingDeclaration = descriptor.containingDeclaration if (containingDeclaration is ClassDescriptor && containingDeclaration.kind != ClassKind.INTERFACE) { return descriptor } } //choose at random return descriptorsForSignatureChange.first() } companion object { private val LOG = logger<KotlinChangeSignature>() } }
apache-2.0
90be7e9283a6c70c9a6752120606f4fd
43.544521
158
0.688475
6.265414
false
false
false
false
allotria/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ignore/cache/IgnorePatternsMatchedFilesCache.kt
1
5248
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ignore.cache import com.github.benmanes.caffeine.cache.Caffeine import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.vcs.changes.ignore.util.RegexUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileListener import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.* import com.intellij.psi.search.FilenameIndex import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.Alarm import com.intellij.util.ui.update.DisposableUpdate import com.intellij.util.ui.update.MergingUpdateQueue import com.intellij.util.ui.update.Update import java.util.concurrent.TimeUnit import java.util.regex.Pattern /** * Cache that retrieves matching files using given [Pattern]. * Cache population happened on demand in the background. * The cache eviction happen in the following cases: * * by using [VirtualFileListener] to handle filesystem changes and clean cache if needed for the specific pattern parts. * * after entries have been expired: entries becomes expired if no read/write operations happened with the corresponding key during some amount of time (10 minutes). * * after project dispose */ internal class IgnorePatternsMatchedFilesCache(private val project: Project) : Disposable { private val projectFileIndex = ProjectFileIndex.getInstance(project) private val cache = Caffeine.newBuilder() .expireAfterAccess(10, TimeUnit.MINUTES) .build<String, Collection<VirtualFile>>() private val updateQueue = MergingUpdateQueue("IgnorePatternsMatchedFilesCacheUpdateQueue", 500, true, null, this, null, Alarm.ThreadToUse.POOLED_THREAD) init { ApplicationManager.getApplication().messageBus.connect(this) .subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener { override fun after(events: List<VFileEvent>) { if (cache.estimatedSize() == 0L) { return } for (event in events) { if (event is VFileCreateEvent || event is VFileDeleteEvent || event is VFileCopyEvent) { cleanupCache(event.path) } else if (event is VFilePropertyChangeEvent && event.isRename) { cleanupCache(event.oldPath) cleanupCache(event.path) } else if (event is VFileMoveEvent) { cleanupCache(event.oldPath) cleanupCache(event.path) } } } private fun cleanupCache(path: String) { val cacheMap = cache.asMap() val globCache = PatternCache.getInstance(project) for (key in cacheMap.keys) { val pattern = globCache.getPattern(key) ?: continue val parts = RegexUtil.getParts(pattern) if (RegexUtil.matchAnyPart(parts, path)) { cacheMap.remove(key) } } } }) } override fun dispose() { cache.invalidateAll() updateQueue.cancelAllUpdates() } /** * Finds [VirtualFile] instances in project for the specific [Pattern] and caches them. * * @param pattern to match * @return matched files list */ fun getFilesForPattern(pattern: Pattern): Collection<VirtualFile> { val key = pattern.toString() val files = cache.getIfPresent(key) ?: emptyList() if (files.isEmpty()) { runSearchRequest(key, pattern) } return files } private fun runSearchRequest(key: String, pattern: Pattern) = updateQueue.queue(object : DisposableUpdate(project, key) { override fun canEat(update: Update) = true override fun doRun() = cache.put(key, doSearch(pattern)) }) private fun doSearch(pattern: Pattern): Set<VirtualFile> { val files = HashSet<VirtualFile>(1000) val parts = RegexUtil.getParts(pattern) if (parts.isEmpty()) { return files } val projectScope = GlobalSearchScope.projectScope(project) projectFileIndex.iterateContent { fileOrDir -> ProgressManager.checkCanceled() val name = fileOrDir.name if (RegexUtil.matchAnyPart(parts, name)) { for (file in runReadAction { FilenameIndex.getVirtualFilesByName(name, projectScope) }) { if (file.isValid && RegexUtil.matchAllParts(parts, file.path)) { files.add(file) } } } return@iterateContent true } return files } companion object { @JvmStatic fun getInstance(project: Project): IgnorePatternsMatchedFilesCache { return ServiceManager.getService(project, IgnorePatternsMatchedFilesCache::class.java) } } }
apache-2.0
d7beab78103976b408ff717648a7f8fc
36.219858
166
0.695884
4.644248
false
false
false
false
Kotlin/kotlinx.coroutines
ui/kotlinx-coroutines-android/test/HandlerDispatcherAsyncTest.kt
1
4803
/* * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.android import android.os.* import kotlinx.coroutines.* import org.junit.Test import org.junit.runner.* import org.robolectric.* import org.robolectric.Shadows.* import org.robolectric.annotation.* import org.robolectric.shadows.* import org.robolectric.util.* import java.util.concurrent.* import kotlin.test.* @RunWith(RobolectricTestRunner::class) @Config(manifest = Config.NONE, sdk = [28]) @LooperMode(LooperMode.Mode.LEGACY) class HandlerDispatcherAsyncTest : TestBase() { /** * Because [Dispatchers.Main] is a singleton, we cannot vary its initialization behavior. As a * result we only test its behavior on the newest API level and assert that it uses async * messages. We rely on the other tests to exercise the variance of the mechanism that the main * dispatcher uses to ensure it has correct behavior on all API levels. */ @Test fun mainIsAsync() = runTest { ReflectionHelpers.setStaticField(Build.VERSION::class.java, "SDK_INT", 28) val mainLooper = shadowOf(Looper.getMainLooper()) mainLooper.pause() val mainMessageQueue = shadowOf(Looper.getMainLooper().queue) val job = launch(Dispatchers.Main) { expect(2) } val message = mainMessageQueue.head assertTrue(message.isAsynchronous) job.join(mainLooper) } @Test fun asyncMessagesApi14() = runTest { ReflectionHelpers.setStaticField(Build.VERSION::class.java, "SDK_INT", 14) val main = Looper.getMainLooper().asHandler(async = true).asCoroutineDispatcher() val mainLooper = shadowOf(Looper.getMainLooper()) mainLooper.pause() val mainMessageQueue = shadowOf(Looper.getMainLooper().queue) val job = launch(main) { expect(2) } val message = mainMessageQueue.head assertFalse(message.isAsynchronous) job.join(mainLooper) } @Test fun asyncMessagesApi16() = runTest { ReflectionHelpers.setStaticField(Build.VERSION::class.java, "SDK_INT", 16) val main = Looper.getMainLooper().asHandler(async = true).asCoroutineDispatcher() val mainLooper = shadowOf(Looper.getMainLooper()) mainLooper.pause() val mainMessageQueue = shadowOf(Looper.getMainLooper().queue) val job = launch(main) { expect(2) } val message = mainMessageQueue.head assertTrue(message.isAsynchronous) job.join(mainLooper) } @Test fun asyncMessagesApi28() = runTest { ReflectionHelpers.setStaticField(Build.VERSION::class.java, "SDK_INT", 28) val main = Looper.getMainLooper().asHandler(async = true).asCoroutineDispatcher() val mainLooper = shadowOf(Looper.getMainLooper()) mainLooper.pause() val mainMessageQueue = shadowOf(Looper.getMainLooper().queue) val job = launch(main) { expect(2) } val message = mainMessageQueue.head assertTrue(message.isAsynchronous) job.join(mainLooper) } @Test fun noAsyncMessagesIfNotRequested() = runTest { ReflectionHelpers.setStaticField(Build.VERSION::class.java, "SDK_INT", 28) val main = Looper.getMainLooper().asHandler(async = false).asCoroutineDispatcher() val mainLooper = shadowOf(Looper.getMainLooper()) mainLooper.pause() val mainMessageQueue = shadowOf(Looper.getMainLooper().queue) val job = launch(main) { expect(2) } val message = mainMessageQueue.head assertFalse(message.isAsynchronous) job.join(mainLooper) } @Test fun testToString() { ReflectionHelpers.setStaticField(Build.VERSION::class.java, "SDK_INT", 28) val main = Looper.getMainLooper().asHandler(async = true).asCoroutineDispatcher("testName") assertEquals("testName", main.toString()) assertEquals("testName.immediate", main.immediate.toString()) assertEquals("testName.immediate", main.immediate.immediate.toString()) } private suspend fun Job.join(mainLooper: ShadowLooper) { expect(1) mainLooper.unPause() join() finish(3) } // TODO compile against API 23+ so this can be invoked without reflection. private val Looper.queue: MessageQueue get() = Looper::class.java.getDeclaredMethod("getQueue").invoke(this) as MessageQueue // TODO compile against API 22+ so this can be invoked without reflection. private val Message.isAsynchronous: Boolean get() = Message::class.java.getDeclaredMethod("isAsynchronous").invoke(this) as Boolean }
apache-2.0
00aec89c7a0e7e57939aac17a9a75323
31.89726
102
0.672288
4.736686
false
true
false
false
agoda-com/Kakao
sample/src/androidTest/kotlin/com/agoda/sample/screen/TextInputLayoutScreen.kt
1
544
package com.agoda.sample.screen import com.agoda.kakao.edit.KTextInputLayout import com.agoda.kakao.screen.Screen import com.agoda.kakao.text.KButton import com.agoda.sample.R class TextInputLayoutScreen : Screen<TextInputLayoutScreen>() { val inputLayout = KTextInputLayout { withId(R.id.input_layout) } val toggleCounter = KButton { withId(R.id.toggle_counter) } val toggleHint = KButton { withId(R.id.toggle_hint) } val toggleError = KButton { withId(R.id.toggle_error) } init { rootView = inputLayout } }
apache-2.0
bb0c4cf63a1098139873c3df8fd40885
31
68
0.733456
3.651007
false
false
false
false
leafclick/intellij-community
java/java-impl/src/com/intellij/codeInsight/daemon/problems/ProblemMatcher.kt
1
4392
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.daemon.problems import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder import com.intellij.codeInsight.daemon.impl.analysis.HighlightVisitorImpl import com.intellij.lang.annotation.HighlightSeverity import com.intellij.pom.Navigatable import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil internal class ProblemMatcher { private class ProblemSearcher(private val file: PsiFile): JavaElementVisitor() { val problems = mutableMapOf<Navigatable, String?>() override fun visitElement(element: PsiElement) { findProblem(element) element.parent?.accept(this) } override fun visitReferenceExpression(expression: PsiReferenceExpression) { visitElement(expression) } override fun visitCallExpression(callExpression: PsiCallExpression) { val args = callExpression.argumentList if (args != null) findProblem(args) visitElement(callExpression) } override fun visitAnnotation(annotation: PsiAnnotation) { val paramsList = annotation.parameterList paramsList.attributes.forEach { findProblem(it) } visitElement(annotation) } override fun visitParameter(parameter: PsiParameter) { val parent = parameter.parent if (parent is PsiCatchSection) findProblem(parent.tryStatement) findProblem(parameter) } override fun visitVariable(variable: PsiVariable) { findProblem(variable) } override fun visitStatement(statement: PsiStatement) { findProblem(statement) } override fun visitMethod(method: PsiMethod) { findProblem(method) val typeElement = method.returnTypeElement if (typeElement != null) findProblem(typeElement) val params = method.parameterList findProblem(params) val modifiers = method.modifierList findProblem(modifiers) } override fun visitAnonymousClass(aClass: PsiAnonymousClass) { visitElement(aClass) } override fun visitClass(psiClass: PsiClass) { val modifiers = psiClass.modifierList if (modifiers != null) findProblem(modifiers) findProblem(psiClass) } private fun findProblem(element: PsiElement) { if (element !is Navigatable) return val problemHolder = ProblemHolder(file) val visitor = object : HighlightVisitorImpl() { init { prepareToRunAsInspection(problemHolder) } } element.accept(visitor) problems[element] = problemHolder.problem } private class ProblemHolder(private val file: PsiFile): HighlightInfoHolder(file) { var problem: String? = null override fun add(info: HighlightInfo?): Boolean { if (problem != null || info == null || info.severity != HighlightSeverity.ERROR) return true val place = findPlace(info) if (place !is Navigatable) return true problem = info.description return true } override fun hasErrorResults(): Boolean { return false } private fun findPlace(info: HighlightInfo): PsiElement? { val startElement = file.findElementAt(info.actualStartOffset) ?: return null val endElement = file.findElementAt(info.actualEndOffset - 1) ?: return null return PsiTreeUtil.findCommonParent(startElement, endElement) } } } companion object { internal fun getProblems(usage: PsiElement): List<Problem> { val startElement = getSearchStartElement(usage) ?: return emptyList() val psiFile = startElement.containingFile return collectProblems(psiFile, startElement) } private fun collectProblems(psiFile: PsiFile, startElement: PsiElement): List<Problem> { val searcher = ProblemSearcher(psiFile) startElement.accept(searcher) val file = psiFile.virtualFile return searcher.problems.map { Problem(file, it.value, it.key) } } private fun getSearchStartElement(usage: PsiElement) = when (usage) { is PsiMethod -> usage.modifierList.findAnnotation(CommonClassNames.JAVA_LANG_OVERRIDE) ?: usage is PsiJavaCodeReferenceElement -> usage.referenceNameElement else -> usage } } }
apache-2.0
d293d878be488fe3dbc5c6fb8337f665
32.792308
140
0.711066
5.071594
false
false
false
false
leafclick/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHPRDiffEditorReviewComponentsFactoryImpl.kt
1
4724
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.comment.ui import com.intellij.diff.util.Side import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.util.ui.GraphicsUtil import com.intellij.util.ui.JBInsets import com.intellij.util.ui.JBUI import org.jetbrains.plugins.github.api.data.GHUser import org.jetbrains.plugins.github.pullrequest.avatars.CachingGithubAvatarIconsProvider import org.jetbrains.plugins.github.pullrequest.data.service.GHPRReviewServiceAdapter import org.jetbrains.plugins.github.pullrequest.ui.changes.GHPRCreateDiffCommentParametersHelper import org.jetbrains.plugins.github.util.GithubUIUtil import org.jetbrains.plugins.github.util.successOnEdt import java.awt.* import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import java.awt.geom.RoundRectangle2D import javax.swing.JComponent import javax.swing.JPanel class GHPRDiffEditorReviewComponentsFactoryImpl internal constructor(private val reviewService: GHPRReviewServiceAdapter, private val createCommentParametersHelper: GHPRCreateDiffCommentParametersHelper, private val avatarIconsProviderFactory: CachingGithubAvatarIconsProvider.Factory, private val currentUser: GHUser) : GHPRDiffEditorReviewComponentsFactory { override fun createThreadComponent(thread: GHPRReviewThreadModel): JComponent { val wrapper = RoundedPanel(BorderLayout()).apply { border = JBUI.Borders.empty(2, 0) } val avatarIconsProvider = avatarIconsProviderFactory.create(GithubUIUtil.avatarSize, wrapper) val component = GHPRReviewThreadComponent.create(thread, reviewService, avatarIconsProvider, currentUser).apply { border = JBUI.Borders.empty(8, 8) } wrapper.add(component, BorderLayout.NORTH) component.addComponentListener(object : ComponentAdapter() { override fun componentResized(e: ComponentEvent?) = wrapper.dispatchEvent(ComponentEvent(component, ComponentEvent.COMPONENT_RESIZED)) }) return wrapper } override fun createCommentComponent(side: Side, line: Int, hideCallback: () -> Unit): JComponent { val wrapper = RoundedPanel(BorderLayout()).apply { border = JBUI.Borders.empty(2, 0) } val avatarIconsProvider = avatarIconsProviderFactory.create(GithubUIUtil.avatarSize, wrapper) val model = GHPRSubmittableTextField.Model { val commitSha = createCommentParametersHelper.commitSha val filePath = createCommentParametersHelper.filePath val diffLine = createCommentParametersHelper.findPosition(side, line) ?: error("Can't determine comment position") reviewService.addComment(EmptyProgressIndicator(), it, commitSha, filePath, diffLine).successOnEdt { hideCallback() } } val commentField = GHPRSubmittableTextField.create(model, avatarIconsProvider, currentUser, "Comment") { hideCallback() }.apply { border = JBUI.Borders.empty(8) } wrapper.add(commentField, BorderLayout.NORTH) commentField.addComponentListener(object : ComponentAdapter() { override fun componentResized(e: ComponentEvent?) = wrapper.dispatchEvent(ComponentEvent(commentField, ComponentEvent.COMPONENT_RESIZED)) }) return wrapper } private class RoundedPanel(layout: LayoutManager?) : JPanel(layout) { private var borderLineColor: Color? = null init { cursor = Cursor.getDefaultCursor() updateColors() } override fun updateUI() { super.updateUI() updateColors() } private fun updateColors() { val scheme = EditorColorsManager.getInstance().globalScheme background = scheme.defaultBackground borderLineColor = scheme.getColor(EditorColors.TEARLINE_COLOR) } override fun paintComponent(g: Graphics) { GraphicsUtil.setupRoundedBorderAntialiasing(g) val g2 = g as Graphics2D val rect = Rectangle(size) JBInsets.removeFrom(rect, insets) // 2.25 scale is a @#$!% so we adjust sizes manually val rectangle2d = RoundRectangle2D.Float(rect.x.toFloat() + 0.5f, rect.y.toFloat() + 0.5f, rect.width.toFloat() - 1f, rect.height.toFloat() - 1f, 10f, 10f) g2.color = background g2.fill(rectangle2d) borderLineColor?.let { g2.color = borderLineColor g2.draw(rectangle2d) } } } }
apache-2.0
e51660e81c65c7045c38eb0a18dbded5
40.814159
140
0.734335
4.895337
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/delegatedProperty/varInInnerClass.kt
5
429
import kotlin.reflect.KProperty class Delegate { var inner = 1 operator fun getValue(t: Any?, p: KProperty<*>): Int = inner operator fun setValue(t: Any?, p: KProperty<*>, i: Int) { inner = i } } class A { inner class B { var prop: Int by Delegate() } } fun box(): String { val c = A().B() if(c.prop != 1) return "fail get" c.prop = 2 if (c.prop != 2) return "fail set" return "OK" }
apache-2.0
e0e509f807a243a1d056d56c149a780b
19.428571
73
0.571096
3.177778
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/stdlib/coroutines/SequenceBuilderTest/testExceptionInCoroutine.kt
2
761
import kotlin.test.* import kotlin.coroutines.experimental.buildSequence import kotlin.coroutines.experimental.buildIterator fun box() { var sharedVar = -2 val result = buildSequence { while (true) { when (sharedVar) { -1 -> return@buildSequence -2 -> throw UnsupportedOperationException("-2 is unsupported") else -> yield(sharedVar) } } } val iterator = result.iterator() sharedVar = 1 assertEquals(1, iterator.next()) sharedVar = -2 assertFailsWith<UnsupportedOperationException> { iterator.hasNext() } assertFailsWith<IllegalStateException> { iterator.hasNext() } assertFailsWith<IllegalStateException> { iterator.next() } }
apache-2.0
94d6a87ac5c72de4d93c5aae30a642ee
27.185185
78
0.641261
5.073333
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/boxInline/special/inlineChain.kt
5
755
// FILE: 1.kt class My inline fun <T, R> T.perform(job: (T)-> R) : R { return job(this) } inline fun My.someWork(job: (String) -> Any): Unit { this.perform { job("OK") } } inline fun My.doWork (closure : (param : String) -> Unit) : Unit { this.someWork(closure) } inline fun My.doPerform (closure : (param : My) -> Int) : Int { return perform(closure) } // FILE: 2.kt fun test1(): String { val inlineX = My() var d = ""; inlineX.doWork({ z: String -> d = z; z}) return d } fun test2(): Int { val inlineX = My() return inlineX.perform({ z: My -> 11}) } fun box(): String { if (test1() != "OK") return "test1: ${test1()}" if (test2() != 11) return "test1: ${test2()}" return "OK" }
apache-2.0
3b70e3ed4484a1dda3c29a5cd55ebdf3
16.55814
66
0.543046
2.838346
false
true
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/boxingOptimization/boxedRealsCmp.kt
1
2640
// IGNORE_BACKEND: JS, NATIVE inline fun ltx(a: Comparable<Any>, b: Any) = a < b inline fun lex(a: Comparable<Any>, b: Any) = a <= b inline fun gex(a: Comparable<Any>, b: Any) = a >= b inline fun gtx(a: Comparable<Any>, b: Any) = a > b inline fun lt(a: Any, b: Any) = ltx(a as Comparable<Any>, b) inline fun le(a: Any, b: Any) = lex(a as Comparable<Any>, b) inline fun ge(a: Any, b: Any) = gex(a as Comparable<Any>, b) inline fun gt(a: Any, b: Any) = gtx(a as Comparable<Any>, b) val PLUS0F = 0.0F val MINUS0F = -0.0F val PLUS0D = 0.0 val MINUS0D = -0.0 fun box(): String { return when { !lt(1.0F, 42.0F) -> "Fail 1 LT F" lt(42.0F, 1.0F) -> "Fail 2 LT F" !le(1.0F, 42.0F) -> "Fail 1 LE F" le(42.0F, 1.0F) -> "Fail 2 LE F" !le(1.0F, 1.0F) -> "Fail 3 LE F" !ge(42.0F, 1.0F) -> "Fail 1 GE F" ge(1.0F, 42.0F) -> "Fail 2 GE F" !ge(1.0F, 1.0F) -> "Fail 3 GE F" gt(1.0F, 42.0F) -> "Fail 1 GT F" !gt(42.0F, 1.0F) -> "Fail 2 GT F" !lt(1.0, 42.0) -> "Fail 1 LT D" lt(42.0, 1.0) -> "Fail 2 LT D" !le(1.0, 42.0) -> "Fail 1 LE D" le(42.0, 1.0) -> "Fail 2 LE D" !le(1.0, 1.0) -> "Fail 3 LE D" !ge(42.0, 1.0) -> "Fail 1 GE D" ge(1.0, 42.0) -> "Fail 2 GE D" !ge(1.0, 1.0) -> "Fail 3 GE D" gt(1.0, 42.0) -> "Fail 1 GT D" !gt(42.0, 1.0) -> "Fail 2 GT D" !lt(MINUS0F, PLUS0F) -> "Fail 1 LT +-0 F" lt(PLUS0F, MINUS0F) -> "Fail 2 LT +-0 F" !le(MINUS0F, PLUS0F) -> "Fail 1 LE +-0 F" le(PLUS0F, MINUS0F) -> "Fail 2 LE +-0 F" !le(MINUS0F, MINUS0F) -> "Fail 3 LE +-0 F" !le(PLUS0F, PLUS0F) -> "Fail 3 LE +-0 F" ge(MINUS0F, PLUS0F) -> "Fail 1 GE +-0 F" !ge(PLUS0F, MINUS0F) -> "Fail 2 GE +-0 F" !ge(MINUS0F, MINUS0F) -> "Fail 3 GE +-0 F" !ge(PLUS0F, PLUS0F) -> "Fail 3 GE +-0 F" gt(MINUS0F, PLUS0F) -> "Fail 1 GT +-0 F" !gt(PLUS0F, MINUS0F) -> "Fail 2 GT +-0 F" !lt(MINUS0D, PLUS0D) -> "Fail 1 LT +-0 D" lt(PLUS0D, MINUS0D) -> "Fail 2 LT +-0 D" !le(MINUS0D, PLUS0D) -> "Fail 1 LE +-0 D" le(PLUS0D, MINUS0D) -> "Fail 2 LE +-0 D" !le(MINUS0D, MINUS0D) -> "Fail 3 LE +-0 D" !le(PLUS0D, PLUS0D) -> "Fail 3 LE +-0 D" ge(MINUS0D, PLUS0D) -> "Fail 1 GE +-0 D" !ge(PLUS0D, MINUS0D) -> "Fail 2 GE +-0 D" !ge(MINUS0D, MINUS0D) -> "Fail 3 GE +-0 D" !ge(PLUS0D, PLUS0D) -> "Fail 3 GE +-0 D" gt(MINUS0D, PLUS0D) -> "Fail 1 GT +-0 D" !gt(PLUS0D, MINUS0D) -> "Fail 2 GT +-0 D" else -> "OK" } }
apache-2.0
318b380343bf33a1f94963c1eab0c62e
31.207317
60
0.482197
2.319859
false
false
false
false
smmribeiro/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/execution/target/TargetPhasedBuildActionExecuter.kt
12
1667
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.execution.target import org.gradle.tooling.BuildAction import org.gradle.tooling.BuildActionExecuter import org.gradle.tooling.ResultHandler import org.gradle.tooling.internal.consumer.PhasedBuildAction import org.jetbrains.plugins.gradle.tooling.proxy.TargetBuildParameters.PhasedBuildActionParametersBuilder internal class TargetPhasedBuildActionExecuter(connection: TargetProjectConnection, projectsLoadedAction: PhasedBuildAction.BuildActionWrapper<Any>?, buildFinishedAction: PhasedBuildAction.BuildActionWrapper<Any>?) : TargetBuildExecuter<TargetPhasedBuildActionExecuter, Void>(connection), BuildActionExecuter<Void> { override val targetBuildParametersBuilder = PhasedBuildActionParametersBuilder(projectsLoadedAction?.action, buildFinishedAction?.action) override val buildActions: List<BuildAction<*>> = listOfNotNull(projectsLoadedAction?.action, buildFinishedAction?.action) override fun run(): Void = runAndGetResult() @Suppress("UNCHECKED_CAST") override fun run(handler: ResultHandler<in Void>) = runWithHandler(handler as ResultHandler<Any?>) override fun getThis() = this override fun forTasks(vararg tasks: String) = apply { forTasks(tasks.asList()) } override fun forTasks(tasks: Iterable<String>) = apply { operationParamsBuilder.setTasks(tasks.toList()) } init { operationParamsBuilder.setEntryPoint("TargetPhasedBuildActionExecuter API") } }
apache-2.0
fa924319a7cf914c0283be2d271853fb
60.777778
140
0.776245
5.006006
false
false
false
false