repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
stepstone-tech/android-material-stepper
material-stepper/src/test/java/com/stepstone/stepper/internal/widget/StepViewPagerTest.kt
2
1712
package com.stepstone.stepper.internal.widget import android.view.MotionEvent import com.nhaarman.mockito_kotlin.mock import com.stepstone.stepper.test.runner.StepperRobolectricTestRunner import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RuntimeEnvironment /** * @author Piotr Zawadzki */ @RunWith(StepperRobolectricTestRunner::class) class StepViewPagerTest { val mockTouchEvent: MotionEvent = mock { } val stepPager: StepViewPager = StepViewPager(RuntimeEnvironment.application) @Test fun `Should steal motion events from children if blocking children is enabled`() { //given stepPager.setBlockTouchEventsFromChildrenEnabled(true) //when val shouldStealMotionEventFromChildren = stepPager.onInterceptTouchEvent(mockTouchEvent) //then assertTrue(shouldStealMotionEventFromChildren) } @Test fun `Should not steal motion events from children by default`() { //when val shouldStealMotionEventFromChildren = stepPager.onInterceptTouchEvent(mockTouchEvent) //then assertFalse(shouldStealMotionEventFromChildren) } @Test fun `Should not handle events in 'onTouchEvent(_)' by default`() { //when val eventHandled = stepPager.onInterceptTouchEvent(mockTouchEvent) //then assertFalse(eventHandled) } @Test fun `Should handle touch events in 'onTouchEvent(_)' if blocking children is enabled`() { //when val eventHandled = stepPager.onInterceptTouchEvent(mockTouchEvent) //then assertFalse(eventHandled) } }
apache-2.0
bf1a03c5608da1d3d07520fca3cebdb0
27.081967
96
0.722547
4.782123
false
true
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/media/PlayerController.kt
1
13862
package org.videolan.vlc.media import android.content.Context import android.net.Uri import android.support.v4.media.session.PlaybackStateCompat import android.widget.Toast import androidx.annotation.MainThread import androidx.lifecycle.MutableLiveData import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.actor import org.videolan.libvlc.* import org.videolan.libvlc.interfaces.IMedia import org.videolan.libvlc.interfaces.IMediaList import org.videolan.libvlc.interfaces.IVLCVout import org.videolan.medialibrary.interfaces.media.MediaWrapper import org.videolan.resources.VLCInstance import org.videolan.resources.VLCOptions import org.videolan.tools.KEY_PLAYBACK_RATE import org.videolan.tools.KEY_PLAYBACK_SPEED_PERSIST import org.videolan.tools.Settings import org.videolan.tools.putSingle import org.videolan.vlc.BuildConfig import org.videolan.vlc.PlaybackService import org.videolan.vlc.repository.SlaveRepository import kotlin.math.abs @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi @Suppress("EXPERIMENTAL_FEATURE_WARNING") class PlayerController(val context: Context) : IVLCVout.Callback, MediaPlayer.EventListener, CoroutineScope { override val coroutineContext = Dispatchers.Main.immediate + SupervisorJob() // private val exceptionHandler by lazy(LazyThreadSafetyMode.NONE) { CoroutineExceptionHandler { _, _ -> onPlayerError() } } private val playerContext by lazy(LazyThreadSafetyMode.NONE) { newSingleThreadContext("vlc-player") } private val settings by lazy(LazyThreadSafetyMode.NONE) { Settings.getInstance(context) } val progress by lazy(LazyThreadSafetyMode.NONE) { MutableLiveData<Progress>().apply { value = Progress() } } private val slaveRepository by lazy { SlaveRepository.getInstance(context) } var mediaplayer = newMediaPlayer() private set var switchToVideo = false var seekable = false var pausable = false var previousMediaStats: IMedia.Stats? = null private set @Volatile var hasRenderer = false private set fun getVout(): IVLCVout? = mediaplayer.vlcVout fun canDoPassthrough() = mediaplayer.hasMedia() && !mediaplayer.isReleased && mediaplayer.canDoPassthrough() fun getMedia(): IMedia? = mediaplayer.media fun play() { if (mediaplayer.hasMedia() && !mediaplayer.isReleased) mediaplayer.play() } fun pause(): Boolean { if (isPlaying() && mediaplayer.hasMedia() && pausable) { mediaplayer.pause() return true } return false } fun stop() { if (mediaplayer.hasMedia() && !mediaplayer.isReleased) mediaplayer.stop() setPlaybackStopped() } private fun releaseMedia() = mediaplayer.media?.let { it.setEventListener(null) it.release() } private var mediaplayerEventListener: MediaPlayerEventListener? = null internal suspend fun startPlayback(media: IMedia, listener: MediaPlayerEventListener, time: Long) { mediaplayerEventListener = listener resetPlaybackState(time, media.duration) mediaplayer.setEventListener(null) withContext(Dispatchers.IO) { if (!mediaplayer.isReleased) mediaplayer.media = media.apply { if (hasRenderer) parse() } } mediaplayer.setEventListener(this@PlayerController) if (!mediaplayer.isReleased) { mediaplayer.setEqualizer(VLCOptions.getEqualizerSetFromSettings(context)) mediaplayer.setVideoTitleDisplay(MediaPlayer.Position.Disable, 0) mediaplayer.play() } } private fun resetPlaybackState(time: Long, duration: Long) { seekable = true pausable = true lastTime = time updateProgress(time, duration) } @MainThread fun restart() { val mp = mediaplayer mediaplayer = newMediaPlayer() release(mp) } fun seek(position: Long, length: Double = getLength().toDouble()) { if (length > 0.0) setPosition((position / length).toFloat()) else setTime(position) } fun setPosition(position: Float) { if (seekable && mediaplayer.hasMedia() && !mediaplayer.isReleased) mediaplayer.position = position } fun setTime(time: Long) { if (seekable && mediaplayer.hasMedia() && !mediaplayer.isReleased) mediaplayer.time = time } fun isPlaying() = playbackState == PlaybackStateCompat.STATE_PLAYING fun isVideoPlaying() = !mediaplayer.isReleased && mediaplayer.vlcVout.areViewsAttached() fun canSwitchToVideo() = getVideoTracksCount() > 0 fun getVideoTracksCount() = if (!mediaplayer.isReleased && mediaplayer.hasMedia()) mediaplayer.videoTracksCount else 0 fun getVideoTracks(): Array<out MediaPlayer.TrackDescription>? = if (!mediaplayer.isReleased && mediaplayer.hasMedia()) mediaplayer.videoTracks else emptyArray() fun getVideoTrack() = if (!mediaplayer.isReleased && mediaplayer.hasMedia()) mediaplayer.videoTrack else -1 fun getCurrentVideoTrack(): IMedia.VideoTrack? = if (!mediaplayer.isReleased && mediaplayer.hasMedia()) mediaplayer.currentVideoTrack else null fun getAudioTracksCount() = if (!mediaplayer.isReleased && mediaplayer.hasMedia()) mediaplayer.audioTracksCount else 0 fun getAudioTracks(): Array<out MediaPlayer.TrackDescription>? = if (!mediaplayer.isReleased && mediaplayer.hasMedia()) mediaplayer.audioTracks else emptyArray() fun getAudioTrack() = if (!mediaplayer.isReleased && mediaplayer.hasMedia()) mediaplayer.audioTrack else -1 fun setVideoTrack(index: Int) = !mediaplayer.isReleased && mediaplayer.hasMedia() && mediaplayer.setVideoTrack(index) fun setAudioTrack(index: Int) = !mediaplayer.isReleased && mediaplayer.hasMedia() && mediaplayer.setAudioTrack(index) fun setAudioDigitalOutputEnabled(enabled: Boolean) = !mediaplayer.isReleased && mediaplayer.setAudioDigitalOutputEnabled(enabled) fun getAudioDelay() = if (mediaplayer.hasMedia() && !mediaplayer.isReleased) mediaplayer.audioDelay else 0L fun getSpuDelay() = if (mediaplayer.hasMedia() && !mediaplayer.isReleased) mediaplayer.spuDelay else 0L fun getRate() = if (mediaplayer.hasMedia() && !mediaplayer.isReleased && playbackState != PlaybackStateCompat.STATE_STOPPED) mediaplayer.rate else 1.0f fun setSpuDelay(delay: Long) = mediaplayer.setSpuDelay(delay) fun setVideoTrackEnabled(enabled: Boolean) = mediaplayer.setVideoTrackEnabled(enabled) fun addSubtitleTrack(path: String, select: Boolean) = mediaplayer.addSlave(IMedia.Slave.Type.Subtitle, path, select) fun addSubtitleTrack(uri: Uri, select: Boolean) = mediaplayer.addSlave(IMedia.Slave.Type.Subtitle, uri, select) fun getSpuTracks(): Array<out MediaPlayer.TrackDescription>? = mediaplayer.spuTracks fun getSpuTrack() = mediaplayer.spuTrack fun setSpuTrack(index: Int) = mediaplayer.setSpuTrack(index) fun getSpuTracksCount() = mediaplayer.spuTracksCount fun setAudioDelay(delay: Long) = mediaplayer.setAudioDelay(delay) fun setEqualizer(equalizer: MediaPlayer.Equalizer?) = mediaplayer.setEqualizer(equalizer) @MainThread fun setVideoScale(scale: Float) { mediaplayer.scale = scale } fun setVideoAspectRatio(aspect: String?) { mediaplayer.aspectRatio = aspect } fun setRenderer(renderer: RendererItem?) { if (!mediaplayer.isReleased) mediaplayer.setRenderer(renderer) hasRenderer = renderer !== null } fun release(player: MediaPlayer = mediaplayer) { player.setEventListener(null) if (isVideoPlaying()) player.vlcVout.detachViews() releaseMedia() launch(Dispatchers.IO) { if (BuildConfig.DEBUG) { // Warn if player release is blocking try { withTimeout(5000) { player.release() } } catch (exception: TimeoutCancellationException) { launch { Toast.makeText(context, "media stop has timeouted!", Toast.LENGTH_LONG).show() } } } else player.release() } setPlaybackStopped() } fun setSlaves(media: IMedia, mw: MediaWrapper) = launch { if (mediaplayer.isReleased) return@launch val slaves = mw.slaves slaves?.let { it.forEach { slave -> media.addSlave(slave) } } media.release() slaveRepository.getSlaves(mw.location).forEach { slave -> if (!slaves.contains(slave)) mediaplayer.addSlave(slave.type, Uri.parse(slave.uri), false) } slaves?.let { slaveRepository.saveSlaves(mw) } } private fun newMediaPlayer() : MediaPlayer { return MediaPlayer(VLCInstance.get(context)).apply { setAudioDigitalOutputEnabled(VLCOptions.isAudioDigitalOutputEnabled(settings)) VLCOptions.getAout(settings)?.let { setAudioOutput(it) } setRenderer(PlaybackService.renderer.value) this.vlcVout.addCallback(this@PlayerController) } } override fun onSurfacesCreated(vlcVout: IVLCVout?) {} override fun onSurfacesDestroyed(vlcVout: IVLCVout?) { switchToVideo = false } fun getCurrentTime() = progress.value?.time ?: 0L fun getLength() = progress.value?.length ?: 0L fun setRate(rate: Float, save: Boolean) { if (mediaplayer.isReleased) return mediaplayer.rate = rate if (save && settings.getBoolean(KEY_PLAYBACK_SPEED_PERSIST, false)) settings.putSingle(KEY_PLAYBACK_RATE, rate) } /** * Update current media meta and return true if player needs to be updated * * @param id of the Meta event received, -1 for none * @return true if UI needs to be updated */ internal fun updateCurrentMeta(id: Int, mw: MediaWrapper?): Boolean { if (id == IMedia.Meta.Publisher) return false mw?.updateMeta(mediaplayer) return id != IMedia.Meta.NowPlaying || mw?.nowPlaying !== null } fun setPreviousStats() { val media = mediaplayer.media ?: return previousMediaStats = media.stats media.release() } fun updateViewpoint(yaw: Float, pitch: Float, roll: Float, fov: Float, absolute: Boolean) = mediaplayer.updateViewpoint(yaw, pitch, roll, fov, absolute) fun navigate(where: Int) = mediaplayer.navigate(where) fun getChapters(title: Int): Array<out MediaPlayer.Chapter>? = if (!mediaplayer.isReleased) mediaplayer.getChapters(title) else emptyArray() fun getTitles(): Array<out MediaPlayer.Title>? = if (!mediaplayer.isReleased) mediaplayer.titles else emptyArray() fun getChapterIdx() = if (!mediaplayer.isReleased) mediaplayer.chapter else -1 fun setChapterIdx(chapter: Int) { if (!mediaplayer.isReleased) mediaplayer.chapter = chapter } fun getTitleIdx() = if (!mediaplayer.isReleased) mediaplayer.title else -1 fun setTitleIdx(title: Int) { if (!mediaplayer.isReleased) mediaplayer.title = title } fun getVolume() = if (!mediaplayer.isReleased) mediaplayer.volume else 100 fun setVolume(volume: Int) = if (!mediaplayer.isReleased) mediaplayer.setVolume(volume) else -1 suspend fun expand(): IMediaList? { return mediaplayer.media?.let { return withContext(playerContext) { mediaplayer.setEventListener(null) val items = it.subItems() it.release() mediaplayer.setEventListener(this@PlayerController) items } } } private var lastTime = 0L private val eventActor = actor<MediaPlayer.Event>(capacity = Channel.UNLIMITED, start = CoroutineStart.UNDISPATCHED) { for (event in channel) { when (event.type) { MediaPlayer.Event.Playing -> playbackState = PlaybackStateCompat.STATE_PLAYING MediaPlayer.Event.Paused -> playbackState = PlaybackStateCompat.STATE_PAUSED MediaPlayer.Event.EncounteredError -> setPlaybackStopped() MediaPlayer.Event.PausableChanged -> pausable = event.pausable MediaPlayer.Event.SeekableChanged -> seekable = event.seekable MediaPlayer.Event.LengthChanged -> updateProgress(newLength = event.lengthChanged) MediaPlayer.Event.TimeChanged -> { val time = event.timeChanged if (abs(time - lastTime) > 950L) { updateProgress(newTime = time) lastTime = time } } } mediaplayerEventListener?.onEvent(event) } } @JvmOverloads fun updateProgress(newTime: Long = progress.value?.time ?: 0L, newLength: Long = progress.value?.length ?: 0L) { progress.value = progress.value?.apply { time = newTime; length = newLength } } override fun onEvent(event: MediaPlayer.Event?) { if (event != null) eventActor.offer(event) } private fun setPlaybackStopped() { playbackState = PlaybackStateCompat.STATE_STOPPED updateProgress(0L, 0L) lastTime = 0L } // private fun onPlayerError() { // launch(UI) { // restart() // Toast.makeText(context, context.getString(R.string.feedback_player_crashed), Toast.LENGTH_LONG).show() // } // } companion object { @Volatile var playbackState = PlaybackStateCompat.STATE_NONE private set } } class Progress(var time: Long = 0L, var length: Long = 0L) internal interface MediaPlayerEventListener { suspend fun onEvent(event: MediaPlayer.Event) } private fun Array<IMedia.Slave>?.contains(item: IMedia.Slave) : Boolean { if (this == null) return false for (slave in this) if (slave.uri == item.uri) return true return false }
gpl-2.0
60162f90387b7df4b26dec6e155a7f3b
38.495726
165
0.686265
4.531546
false
false
false
false
light-and-salt/kotloid
src/main/kotlin/kr/or/lightsalt/kotloid/context.kt
1
1955
package kr.or.lightsalt.kotloid import android.annotation.SuppressLint import android.content.* import android.content.pm.PackageManager import android.net.Uri import android.provider.Settings.Secure import android.util.TypedValue import android.widget.Toast import androidx.appcompat.app.AlertDialog import kotlin.reflect.KClass val Context.androidId: String? @SuppressLint("HardwareIds") get() = Secure.getString(contentResolver, Secure.ANDROID_ID) fun Context.dpToPixel(dp: Float) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.displayMetrics) fun Context.getMetaData(name: String) = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA).metaData?.getString(name) fun Context.inchToPixel(inch: Float) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_IN, inch, resources.displayMetrics) fun Context.installPackage(packageName: String, referrer: String? = "") { startActivity(Intent.ACTION_VIEW, "market://details?id=$packageName&referrer=$referrer") } fun Context.isPackageInstalled(packageName: String) = try { packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES) true } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() false } fun Context.pointsToPixel(points: Float) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, points, resources.displayMetrics) fun Context.scaledPixel(value: Float) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, value, resources.displayMetrics) fun Context.showAlertDialog(builder: AlertDialog.Builder.() -> Unit) = AlertDialog.Builder(this).apply(builder).show()!! fun Context.showToast(text: CharSequence, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(this, text, duration).show() } fun Context.startActivity(kClass: KClass<*>) = startActivity(Intent(this, kClass.java)) fun Context.startActivity(action: String, url: String) = startActivity(Intent(action, Uri.parse(url)))
apache-2.0
695350f2cd4c44f933fb4d309bd9a799
34.545455
96
0.798465
3.925703
false
false
false
false
didi/DoraemonKit
Android/dokit-gps-mock/src/main/java/com/didichuxing/doraemonkit/gps_mock/ability/DokitFtAbility.kt
1
787
package com.didichuxing.doraemonkit.kit.filemanager.ability import com.didichuxing.doraemonkit.constant.DoKitModule import com.didichuxing.doraemonkit.kit.core.DokitAbility import com.google.auto.service.AutoService /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2021/6/7-19:50 * 描 述: * 修订历史: * ================================================ */ @AutoService(DokitAbility::class) class DokitGpsMockAbility : DokitAbility { override fun init() { } override fun moduleName(): DoKitModule { return DoKitModule.MODULE_GPS_MOCK } override fun getModuleProcessor(): DokitAbility.DokitModuleProcessor { return DokitGpsMockModuleProcessor() } }
apache-2.0
07796279100b9aeff1dc81e99188ba04
23.7
74
0.616734
4.234286
false
false
false
false
sys1yagi/mastodon4j
sample-kotlin/src/main/java/com/sys1yagi/mastodon4j/sample/StreamPublicTimeline.kt
1
1366
package com.sys1yagi.mastodon4j.sample import com.sys1yagi.mastodon4j.api.Handler import com.sys1yagi.mastodon4j.api.entity.Notification import com.sys1yagi.mastodon4j.api.entity.Status import com.sys1yagi.mastodon4j.api.exception.Mastodon4jRequestException import com.sys1yagi.mastodon4j.api.method.Streaming object StreamPublicTimeline { @JvmStatic fun main(args: Array<String>) { val instanceName = args[0] val credentialFilePath = args[1] // require authentication even if public streaming val client = Authenticator.appRegistrationIfNeeded(instanceName, credentialFilePath, true) val handler = object : Handler { override fun onStatus(status: Status) { println(status.content) } override fun onNotification(notification: Notification) { } override fun onDelete(id: Long) { } } val streaming = Streaming(client) try { val shutdownable = streaming.localPublic(handler) Thread.sleep(10000L) shutdownable.shutdown() } catch(e: Mastodon4jRequestException) { println("error") println(e.response?.code()) println(e.response?.message()) println(e.response?.body()?.string()) return } } }
mit
503ebef75a9927914ae177be8e1794ff
30.045455
98
0.637628
4.478689
false
false
false
false
robertwb/incubator-beam
examples/kotlin/src/main/java/org/apache/beam/examples/kotlin/snippets/Snippets.kt
1
16874
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("UNUSED_VARIABLE") package org.apache.beam.examples.kotlin.snippets import com.google.api.services.bigquery.model.* import com.google.common.collect.ImmutableList import edu.umd.cs.findbugs.annotations.SuppressFBWarnings import org.apache.beam.sdk.Pipeline import org.apache.beam.sdk.coders.AvroCoder import org.apache.beam.sdk.coders.DefaultCoder import org.apache.beam.sdk.coders.DoubleCoder import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.CreateDisposition import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.WriteDisposition import org.apache.beam.sdk.io.gcp.bigquery.DynamicDestinations import org.apache.beam.sdk.io.gcp.bigquery.TableDestination import org.apache.beam.sdk.io.gcp.bigquery.WriteResult import org.apache.beam.sdk.transforms.* import org.apache.beam.sdk.transforms.join.CoGbkResult import org.apache.beam.sdk.transforms.join.CoGroupByKey import org.apache.beam.sdk.transforms.join.KeyedPCollectionTuple import org.apache.beam.sdk.values.* /** Code snippets used in webdocs. */ @Suppress("unused") object Snippets { val tableSchema: TableSchema by lazy { TableSchema().setFields( ImmutableList.of( TableFieldSchema() .setName("year") .setType("INTEGER") .setMode("REQUIRED"), TableFieldSchema() .setName("month") .setType("INTEGER") .setMode("REQUIRED"), TableFieldSchema() .setName("day") .setType("INTEGER") .setMode("REQUIRED"), TableFieldSchema() .setName("maxTemp") .setType("FLOAT") .setMode("NULLABLE"))) } @DefaultCoder(AvroCoder::class) internal class Quote( val source: String = "", val quote: String = "" ) @DefaultCoder(AvroCoder::class) internal class WeatherData( val year: Long = 0, val month: Long = 0, val day: Long = 0, val maxTemp: Double = 0.0 ) @JvmOverloads @SuppressFBWarnings("SE_BAD_FIELD") //Apparently findbugs doesn't like that a non-serialized object i.e. pipeline is being used inside the run{} block fun modelBigQueryIO( pipeline: Pipeline, writeProject: String = "", writeDataset: String = "", writeTable: String = "") { run { // [START BigQueryTableSpec] val tableSpec = "clouddataflow-readonly:samples.weather_stations" // [END BigQueryTableSpec] } run { // [START BigQueryTableSpecWithoutProject] val tableSpec = "samples.weather_stations" // [END BigQueryTableSpecWithoutProject] } run { // [START BigQueryTableSpecObject] val tableSpec = TableReference() .setProjectId("clouddataflow-readonly") .setDatasetId("samples") .setTableId("weather_stations") // [END BigQueryTableSpecObject] } run { val tableSpec = "clouddataflow-readonly:samples.weather_stations" // [START BigQueryReadTable] val maxTemperatures = pipeline.apply(BigQueryIO.readTableRows().from(tableSpec)) // Each row is of type TableRow .apply<PCollection<Double>>( MapElements.into(TypeDescriptors.doubles()) .via(SerializableFunction<TableRow, Double> { it["max_temperature"] as Double? }) ) // [END BigQueryReadTable] } run { val tableSpec = "clouddataflow-readonly:samples.weather_stations" // [START BigQueryReadFunction] val maxTemperatures = pipeline.apply( BigQueryIO.read { it.record["max_temperature"] as Double? } .from(tableSpec) .withCoder(DoubleCoder.of())) // [END BigQueryReadFunction] } run { // [START BigQueryReadQuery] val maxTemperatures = pipeline.apply( BigQueryIO.read { it.record["max_temperature"] as Double? } .fromQuery( "SELECT max_temperature FROM [clouddataflow-readonly:samples.weather_stations]") .withCoder(DoubleCoder.of())) // [END BigQueryReadQuery] } run { // [START BigQueryReadQueryStdSQL] val maxTemperatures = pipeline.apply( BigQueryIO.read { it.record["max_temperature"] as Double? } .fromQuery( "SELECT max_temperature FROM `clouddataflow-readonly.samples.weather_stations`") .usingStandardSql() .withCoder(DoubleCoder.of())) // [END BigQueryReadQueryStdSQL] } // [START BigQuerySchemaJson] val tableSchemaJson = ( "{" + " \"fields\": [" + " {" + " \"name\": \"source\"," + " \"type\": \"STRING\"," + " \"mode\": \"NULLABLE\"" + " }," + " {" + " \"name\": \"quote\"," + " \"type\": \"STRING\"," + " \"mode\": \"REQUIRED\"" + " }" + " ]" + "}") // [END BigQuerySchemaJson] run { var tableSpec = "clouddataflow-readonly:samples.weather_stations" if (writeProject.isNotEmpty() && writeDataset.isNotEmpty() && writeTable.isNotEmpty()) { tableSpec = "$writeProject:$writeDataset.$writeTable" } // [START BigQuerySchemaObject] val tableSchema = TableSchema() .setFields( ImmutableList.of( TableFieldSchema() .setName("source") .setType("STRING") .setMode("NULLABLE"), TableFieldSchema() .setName("quote") .setType("STRING") .setMode("REQUIRED"))) // [END BigQuerySchemaObject] // [START BigQueryWriteInput] /* @DefaultCoder(AvroCoder::class) class Quote( val source: String = "", val quote: String = "" ) */ val quotes = pipeline.apply( Create.of( Quote("Mahatma Gandhi", "My life is my message."), Quote("Yoda", "Do, or do not. There is no 'try'."))) // [END BigQueryWriteInput] // [START BigQueryWriteTable] quotes .apply<PCollection<TableRow>>( MapElements.into(TypeDescriptor.of(TableRow::class.java)) .via(SerializableFunction<Quote, TableRow> { TableRow().set("source", it.source).set("quote", it.quote) })) .apply<WriteResult>( BigQueryIO.writeTableRows() .to(tableSpec) .withSchema(tableSchema) .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE)) // [END BigQueryWriteTable] // [START BigQueryWriteFunction] quotes.apply<WriteResult>( BigQueryIO.write<Quote>() .to(tableSpec) .withSchema(tableSchema) .withFormatFunction { TableRow().set("source", it.source).set("quote", it.quote) } .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE)) // [END BigQueryWriteFunction] // [START BigQueryWriteJsonSchema] quotes.apply<WriteResult>( BigQueryIO.write<Quote>() .to(tableSpec) .withJsonSchema(tableSchemaJson) .withFormatFunction { TableRow().set("source", it.source).set("quote", it.quote) } .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE)) // [END BigQueryWriteJsonSchema] } run { // [START BigQueryWriteDynamicDestinations] /* @DefaultCoder(AvroCoder::class) class WeatherData( val year: Long = 0, val month: Long = 0, val day: Long = 0, val maxTemp: Double = 0.0 ) */ val weatherData = pipeline.apply( BigQueryIO.read { val record = it.record WeatherData( record.get("year") as Long, record.get("month") as Long, record.get("day") as Long, record.get("max_temperature") as Double) } .fromQuery(""" SELECT year, month, day, max_temperature FROM [clouddataflow-readonly:samples.weather_stations] WHERE year BETWEEN 2007 AND 2009 """.trimIndent()) .withCoder(AvroCoder.of(WeatherData::class.java))) // We will send the weather data into different tables for every year. weatherData.apply<WriteResult>( BigQueryIO.write<WeatherData>() .to( object : DynamicDestinations<WeatherData, Long>() { override fun getDestination(elem: ValueInSingleWindow<WeatherData>): Long? { return elem.value!!.year } override fun getTable(destination: Long?): TableDestination { return TableDestination( TableReference() .setProjectId(writeProject) .setDatasetId(writeDataset) .setTableId("${writeTable}_$destination"), "Table for year $destination") } override fun getSchema(destination: Long?): TableSchema { return tableSchema } }) .withFormatFunction { TableRow() .set("year", it.year) .set("month", it.month) .set("day", it.day) .set("maxTemp", it.maxTemp) } .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE)) // [END BigQueryWriteDynamicDestinations] var tableSpec = "clouddataflow-readonly:samples.weather_stations" if (writeProject.isNotEmpty() && writeDataset.isNotEmpty() && writeTable.isNotEmpty()) { tableSpec = "$writeProject:$writeDataset.${writeTable}_partitioning" } // [START BigQueryTimePartitioning] weatherData.apply<WriteResult>( BigQueryIO.write<WeatherData>() .to("${tableSpec}_partitioning") .withSchema(tableSchema) .withFormatFunction { TableRow() .set("year", it.year) .set("month", it.month) .set("day", it.day) .set("maxTemp", it.maxTemp) } // NOTE: an existing table without time partitioning set up will not work .withTimePartitioning(TimePartitioning().setType("DAY")) .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE)) // [END BigQueryTimePartitioning] } } /** Helper function to format results in coGroupByKeyTuple. */ fun formatCoGbkResults( name: String?, emails: Iterable<String>, phones: Iterable<String>): String { val emailsList = ArrayList<String>() for (elem in emails) { emailsList.add("'$elem'") } emailsList.sort() val emailsStr = "[${emailsList.joinToString(", ")}]" val phonesList = ArrayList<String>() for (elem in phones) { phonesList.add("'$elem'") } phonesList.sort() val phonesStr = "[${phonesList.joinToString(", ")}]" return "$name; $emailsStr; $phonesStr" } /** Using a CoGroupByKey transform. */ fun coGroupByKeyTuple( emailsTag: TupleTag<String>, phonesTag: TupleTag<String>, emails: PCollection<KV<String, String>>, phones: PCollection<KV<String, String>>): PCollection<String> { // [START CoGroupByKeyTuple] val results = KeyedPCollectionTuple.of(emailsTag, emails) .and(phonesTag, phones) .apply(CoGroupByKey.create()) // [END CoGroupByKeyTuple] return results.apply( ParDo.of( object : DoFn<KV<String, CoGbkResult>, String>() { @ProcessElement fun processElement(c: ProcessContext) { val e = c.element() val name = e.key val emailsIter = e.value.getAll(emailsTag) val phonesIter = e.value.getAll(phonesTag) val formattedResult = formatCoGbkResults(name, emailsIter, phonesIter) c.output(formattedResult) } })) } } /** Using a Read and Write transform to read/write from/to BigQuery. */
apache-2.0
dadb83283b7885b8b1b7652609cead40
44.117647
143
0.47588
5.397953
false
false
false
false
nickthecoder/paratask
paratask-examples/src/main/kotlin/uk/co/nickthecoder/paratask/examples/MultipleExample.kt
1
2142
package uk.co.nickthecoder.paratask.examples import uk.co.nickthecoder.paratask.AbstractTask import uk.co.nickthecoder.paratask.TaskDescription import uk.co.nickthecoder.paratask.TaskParser import uk.co.nickthecoder.paratask.parameters.* class MultipleExample : AbstractTask() { val info1P = InformationParameter("info1", information = "The default is to allow zero items, so you don't HAVE to enter any strings.") val stringsP = MultipleParameter("strings") { StringParameter(name = "string") // Note. The name doesn't matter! It isn't ever used! } var strings by stringsP val info2P = InformationParameter("info2", information = "Note that there must be at least 2 integers entered, but you can add more (with the " + " buttons.") val intsP = MultipleParameter("integers", minItems = 2, isBoxed = true) { IntParameter(name = "int") } var ints by intsP val complexNumbersP = MultipleParameter("complexNumbers", isBoxed = true) { ImaginaryNumberParameters() } override val taskD = TaskDescription("multipleExample") .addParameters(info1P, stringsP, info2P, intsP, complexNumbersP) override fun run() { println("Strings = $strings") ints.forEach { println("Int = $it") } complexNumbersP.innerParameters.forEach { imaginaryNumberParameters -> println("ComplexNumber ${imaginaryNumberParameters.realP.value} + ${imaginaryNumberParameters.imaginaryP.value}i") } } class ImaginaryNumberParameters : MultipleGroupParameter("complexNumber", "Complex Number") { val realP = DoubleParameter("real") // This name IS used! See the run method val plusP = InformationParameter("plus", information = "+") val imaginaryP = DoubleParameter("imaginary") // This name IS used! See the run method val iP = InformationParameter("i", information = "i") init { addParameters(realP, plusP, imaginaryP, iP) asHorizontal(LabelPosition.NONE) } } } fun main(args: Array<String>) { TaskParser(MultipleExample()).go(args, prompt = true) }
gpl-3.0
48025706d9002cc213b71a0c804c658b
35.931034
162
0.687675
4.284
false
false
false
false
soniccat/android-taskmanager
app_wordteacher_old/src/main/java/com/example/alexeyglushkov/wordteacher/main/MainApplication.kt
1
5151
package com.example.alexeyglushkov.wordteacher.main //import com.dropbox.client2.DropboxAPI; import android.app.Activity import android.app.Application import android.content.Context import android.util.Log import com.example.alexeyglushkov.authcachemanager.AccountCacheStore import com.example.alexeyglushkov.authorization.Auth.Account import com.example.alexeyglushkov.authorization.Auth.AccountStore import com.example.alexeyglushkov.authorization.Auth.Authorizer import com.example.alexeyglushkov.authorization.OAuth.OAuthWebClient import com.example.alexeyglushkov.cachemanager.SimpleStorageCleaner import com.example.alexeyglushkov.cachemanager.Storage import com.example.alexeyglushkov.quizletservice.QuizletRepository import com.example.alexeyglushkov.taskmanager.TaskManager import com.example.alexeyglushkov.tools.ContextProvider import com.example.alexeyglushkov.authorization.AuthActivityProxy import com.example.alexeyglushkov.wordteacher.model.CourseHolder import io.reactivex.internal.functions.Functions import io.reactivex.schedulers.Schedulers import javax.inject.Inject import javax.inject.Named class MainApplication : Application() { @Inject lateinit var accountStore: AccountStore @Inject lateinit var authWebClient: OAuthWebClient lateinit var quizletRepository: QuizletRepository //private @NonNull DropboxService dropboxService; @Inject lateinit var courseHolder: CourseHolder @Inject lateinit var taskManager: TaskManager @Inject lateinit var storage: Storage lateinit var component: MainComponent // public @NonNull DropboxService getDropboxService() { // return dropboxService; // } // Cast Getters val currentContext: Context? get() = currentActivity private val currentActivity: Activity? get() = AuthActivityProxy.getCurrentActivity() //// Initialization @MainScope @dagger.Component(modules = [MainApplicationModule::class]) interface MainComponent { val storage: Storage val taskManager: TaskManager val quizletRepozitory: QuizletRepository @get:Named("quizlet") val quizletAuthorizer: Authorizer @get:Named("quizlet") val quizletAccount: Account @get:Named("foursquare") val foursquareAuthorizer: Authorizer @get:Named("foursquare") val foursquareAccount: Account val courseHolder: CourseHolder fun inject(app: MainApplication) } init { instance = this } override fun onCreate() { super.onCreate() component = DaggerMainApplication_MainComponent.builder() .contextModule(ContextModule(applicationContext)) .build() component.inject(this) cleanCache() loadAccountStore() loadCourseHolder() } //// Events private fun onAccountStoreLoaded() { quizletRepository = component.quizletRepozitory quizletRepository.restoreOrLoad(null) //createDropboxService(); } //// Actions fun loadAccountStore() { try { this.accountStore.load() } catch (e: Exception) { Log.e(TAG, "Can't load account store") e.printStackTrace() } restoreAccounts(this.accountStore as AccountCacheStore) onAccountStoreLoaded() } private fun restoreAccounts(store: AccountCacheStore) { for (acc in store.accounts) { acc.setAuthCredentialStore(store) Networks.restoreAuthorizer(acc) } } fun loadCourseHolder() { //taskManager.addTask(courseHolder.loadCourseListTask) courseHolder.loadCourses(null) } fun cleanCache() { val cleaner = SimpleStorageCleaner() cleaner.clean(storage) .subscribeOn(Schedulers.io()) .subscribe(Functions.EMPTY_ACTION, Functions.emptyConsumer<Any>()) } // private void merge(@NonNull File localFile, @NonNull DropboxAPI.Entry dropboxEntry, DropboxCommandProvider.MergeCompletion completion) { // File outFile; // // try { // File tmpDir = getCacheDir(); // // UUID outFileName = UUID.randomUUID(); // outFile = File.createTempFile(outFileName.toString(), "", getCacheDir()); // // FileMerger fileMerger = new FileObjectMerger(new CourseCodec(), new CourseMerger(), outFile); // DropboxFileMerger merger = new DropboxFileMerger(dropboxService.getApi(), tmpDir, fileMerger); // // merger.merge(localFile, dropboxEntry, completion); // // } catch (Exception ex) { // completion.completed(null, new Error("Merge exception", ex)); // } // } //// Creation Methods companion object { private val TAG = "MainApplication" lateinit var instance: MainApplication private set //// Getters val contextProvider: ContextProvider get() = ContextProvider { MainApplication.instance.currentContext } } }
mit
16d5fea9994d5b69e586e03998d0c014
30.796296
146
0.679286
4.905714
false
false
false
false
cfieber/spinnaker-gradle-project
spinnaker-extensions/src/main/kotlin/com/netflix/spinnaker/gradle/extension/Plugins.kt
1
1187
/* * 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.gradle.extension import org.gradle.api.Project object Plugins { const val GROUP = "Spinnaker Plugins" const val BUNDLE_PLUGINS_TASK_NAME = "bundlePlugins" const val ASSEMBLE_PLUGIN_TASK_NAME = "assemblePlugin" const val RELEASE_BUNDLE_TASK_NAME = "releaseBundle" const val CHECKSUM_BUNDLE_TASK_NAME = "checksumBundle" const val COLLECT_PLUGIN_ZIPS_TASK_NAME = "collectPluginZips" internal fun hasDeckPlugin(project: Project): Boolean = project.rootProject.subprojects.any { it.plugins.hasPlugin(SpinnakerUIExtensionPlugin::class.java) } }
apache-2.0
b2214281366287a978675ffdf1f4fdcc
37.290323
104
0.757372
3.930464
false
false
false
false
FFlorien/AmpachePlayer
app/src/main/java/be/florien/anyflow/feature/player/filter/BaseFilterViewModel.kt
1
1168
package be.florien.anyflow.feature.player.filter import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.map import androidx.lifecycle.viewModelScope import be.florien.anyflow.data.view.Filter import be.florien.anyflow.feature.BaseViewModel import be.florien.anyflow.player.FiltersManager import kotlinx.coroutines.launch open class BaseFilterViewModel(protected val filtersManager: FiltersManager) : BaseViewModel() { val areFiltersInEdition: LiveData<Boolean> = MutableLiveData(true) val currentFilters: LiveData<List<Filter<*>>> = filtersManager.filtersInEdition.map { it.toList() } val hasChangeFromCurrentFilters: LiveData<Boolean> = filtersManager.hasChange fun confirmChanges() { viewModelScope.launch { filtersManager.commitChanges() areFiltersInEdition.mutable.value = false } } fun cancelChanges() { filtersManager.abandonChanges() areFiltersInEdition.mutable.value = false } fun saveFilterGroup(name: String) { viewModelScope.launch { filtersManager.saveCurrentFilterGroup(name) } } }
gpl-3.0
e9b55db685616a665bb5a5abe6a8eddc
32.4
103
0.746575
4.616601
false
false
false
false
Le-Chiffre/Yttrium
MySQL/src/com/rimmer/yttrium/mysql/Column.kt
2
1317
package com.rimmer.yttrium.mysql import com.rimmer.mysql.dsl.Column import com.rimmer.mysql.dsl.Table import com.rimmer.mysql.protocol.CodecExtender import com.rimmer.mysql.protocol.constants.Type import com.rimmer.mysql.protocol.decoder.readLengthEncoded import com.rimmer.mysql.protocol.decoder.unknownTarget import com.rimmer.mysql.protocol.decoder.writeLengthEncoded import com.rimmer.yttrium.ByteString import com.rimmer.yttrium.LocalByteString import io.netty.buffer.ByteBuf fun Table.byteText(name: String): Column<ByteString> { val answer = Column(this, name, ByteString::class.javaObjectType) columns.add(answer) return answer } object Codec: CodecExtender { override fun encode(buffer: ByteBuf, types: ByteArray, index: Int, value: Any) { if(value is ByteString) { types[index * 2] = Type.VARCHAR.toByte() buffer.writeLengthEncoded(value.size) value.write(buffer) } } override fun decodeString(buffer: ByteBuf, targetType: Class<*>?): Any { if(targetType === ByteString::class.java) { val length = buffer.readLengthEncoded().toInt() val bytes = ByteArray(length) buffer.readBytes(bytes) return LocalByteString(bytes) } else throw unknownTarget(targetType) } }
mit
ba6176fb77df50a98e9c8a240f681987
34.621622
84
0.713743
4.128527
false
true
false
false
donald-w/Anki-Android
AnkiDroid/src/main/java/com/ichi2/compat/CompatV29.kt
1
3343
/* * Copyright (c) 2021 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.compat import android.annotation.TargetApi import android.content.ContentValues import android.content.Context import android.graphics.Bitmap import android.media.ThumbnailUtils import android.net.Uri import android.os.Environment import android.provider.MediaStore import android.util.Size import com.ichi2.anki.CollectionHelper import java.io.File /** Implementation of [Compat] for SDK level 29 */ @TargetApi(29) open class CompatV29 : CompatV26(), Compat { override fun hasVideoThumbnail(path: String): Boolean { return try { ThumbnailUtils.createVideoThumbnail(File(path), THUMBNAIL_MINI_KIND, null) // createVideoThumbnail throws an exception if it's null true } catch (e: Exception) { // The default for audio is an IOException, so don't log it // A log line is still produced: // E/MediaMetadataRetrieverJNI: getEmbeddedPicture: Call to getEmbeddedPicture failed false } } override fun saveImage(context: Context, bitmap: Bitmap, baseFileName: String, extension: String, format: Bitmap.CompressFormat, quality: Int): Uri { val imagesCollection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) val destDir = File(Environment.DIRECTORY_PICTURES, "AnkiDroid") val date = CollectionHelper.getInstance().getTimeSafe(context).intTimeMS() val newImage = ContentValues().apply { put(MediaStore.Images.Media.DISPLAY_NAME, "$date.$extension") put(MediaStore.MediaColumns.MIME_TYPE, "image/$extension") put(MediaStore.MediaColumns.DATE_ADDED, date) put(MediaStore.MediaColumns.DATE_MODIFIED, date) put(MediaStore.MediaColumns.SIZE, bitmap.byteCount) put(MediaStore.MediaColumns.WIDTH, bitmap.width) put(MediaStore.MediaColumns.HEIGHT, bitmap.height) put(MediaStore.MediaColumns.RELATIVE_PATH, "$destDir${File.separator}") put(MediaStore.Images.Media.IS_PENDING, 1) } val newImageUri = context.contentResolver.insert(imagesCollection, newImage) context.contentResolver.openOutputStream(newImageUri!!).use { bitmap.compress(format, quality, it) } newImage.clear() newImage.put(MediaStore.Images.Media.IS_PENDING, 0) context.contentResolver.update(newImageUri, newImage, null, null) return newImageUri } companion object { // obtained from AOSP source private val THUMBNAIL_MINI_KIND = Size(512, 384) } }
gpl-3.0
8b9d099830f8f6bf1d6a468b749f5156
42.986842
153
0.702363
4.481233
false
false
false
false
damien5314/RhythmGameScoreCalculator
app/src/main/java/com/ddiehl/rgsc/ddrsn2/DDRSN2Presenter.kt
1
1357
package com.ddiehl.rgsc.ddrsn2 import com.ddiehl.rgsc.ScorePresenter import com.ddiehl.rgsc.data.AndroidStorage import com.ddiehl.rgsc.data.Score import com.ddiehl.rgsc.data.Storage class DDRSN2Presenter(override val _view: DDRSN2View) : ScorePresenter() { override val _storage: Storage = AndroidStorage(Storage.PREFS_DDRSN2) override fun getEmptyScore(): Score { return DDRSN2Score() } override fun getInput(): DDRSN2Score { val score = DDRSN2Score() score.elements[DDRSN2Score.MARVELOUSES]!!.count = _view.marvelouses score.elements[DDRSN2Score.PERFECTS]!!.count = _view.perfects score.elements[DDRSN2Score.GREATS]!!.count = _view.greats score.elements[DDRSN2Score.GOODS]!!.count = _view.goods score.elements[DDRSN2Score.BOOS]!!.count = _view.boos score.elements[DDRSN2Score.MISSES]!!.count = _view.misses score.elements[DDRSN2Score.HOLDS]!!.count = _view.holds score.elements[DDRSN2Score.TOTAL_HOLDS]!!.count = _view.totalHolds _logger.d(score.toString()) return score } override fun isScoreValid(score: Score): Boolean { if (score.elements[DDRSN2Score.HOLDS]!!.count > score.elements[DDRSN2Score.TOTAL_HOLDS]!!.count) { _view.showHoldsInvalid() return false } return true } }
apache-2.0
6bcb90169b1cfc2a6a42c56a209bb140
36.722222
106
0.682388
3.38404
false
false
false
false
pyamsoft/padlock
padlock-model/src/main/java/com/pyamsoft/padlock/model/list/ActivityEntry.kt
1
1298
/* * 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.model.list import com.pyamsoft.padlock.model.LockState sealed class ActivityEntry(name: String) { val group: String init { val lastIndex = name.lastIndexOf('.') if (lastIndex > 0) { group = name.substring(0 until lastIndex) } else { group = name } } data class Group(val name: String) : ActivityEntry(name) data class Item( val name: String, val packageName: String, val lockState: LockState ) : ActivityEntry(name) { val id: String = "$packageName|$name" val activity: String init { val lastIndex = name.lastIndexOf('.') activity = name.substring(lastIndex + 1) } } }
apache-2.0
eedaa22eb2ad03745dbf3b1dac7e15be
23.490566
75
0.6849
4.081761
false
false
false
false
AndroidX/androidx
compose/ui/ui-inspection/src/main/java/androidx/compose/ui/inspection/RecompositionHandler.kt
3
4155
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.inspection import android.util.Log import androidx.annotation.GuardedBy import androidx.compose.runtime.Composer import androidx.inspection.ArtTooling private const val START_RESTART_GROUP = "startRestartGroup(I)Landroidx/compose/runtime/Composer;" private const val SKIP_TO_GROUP_END = "skipToGroupEnd()V" /** * Detection of recompose counts and skips from installing runtime hooks. */ class RecompositionHandler(private val artTooling: ArtTooling) { /** * For each composable store the recomposition [count] and [skips]. */ class Data(var count: Int, var skips: Int) /** * Key of a Composable method. * * The [key] identified the runtime method and the [anchorId] identified a * specific compose node. */ private data class MethodKey(val key: Int, val anchorId: Int) private val lock = Any() @GuardedBy("lock") private var currentlyCollecting = false @GuardedBy("lock") private var hooksInstalled = false @GuardedBy("lock") private val counts = mutableMapOf<MethodKey, Data>() @GuardedBy("lock") private var lastMethodKey: Int = 0 fun changeCollectionMode(startCollecting: Boolean, keepCounts: Boolean) { synchronized(lock) { if (startCollecting != currentlyCollecting) { if (!hooksInstalled) { installHooks() } currentlyCollecting = startCollecting } if (!keepCounts) { counts.clear() } } } fun getCounts(key: Int, anchorId: Int): Data? { synchronized(lock) { return counts[MethodKey(key, anchorId)] } } /** * We install 3 hooks: * - entry hook for ComposerImpl.startRestartGroup gives us the [MethodKey.key] * - exit hook for ComposerImpl.startRestartGroup gives us the [MethodKey.anchorId] * - entry hook for ComposerImpl.skipToGroupEnd converts a recompose count to a skip count. */ private fun installHooks() { val composerImpl = try { Class.forName("${Composer::class.java.name}Impl") } catch (ex: Throwable) { Log.w("Compose", "Could not install recomposition hooks", ex) return } artTooling.registerEntryHook(composerImpl, START_RESTART_GROUP) { _, args -> synchronized(lock) { lastMethodKey = args[0] as Int } } artTooling.registerExitHook(composerImpl, START_RESTART_GROUP) { composer: Composer -> synchronized(lock) { if (currentlyCollecting) { composer.recomposeScopeIdentity?.hashCode()?.let { anchor -> val data = counts.getOrPut(MethodKey(lastMethodKey, anchor)) { Data(0, 0) } data.count++ } } } composer } artTooling.registerEntryHook(composerImpl, SKIP_TO_GROUP_END) { obj, _ -> synchronized(lock) { if (currentlyCollecting) { val composer = obj as? Composer composer?.recomposeScopeIdentity?.hashCode()?.let { anchor -> counts[MethodKey(lastMethodKey, anchor)]?.let { it.count-- it.skips++ } } } } } hooksInstalled = true } }
apache-2.0
9f3ec786c6b5d2d73a1c664e740263e2
32.780488
99
0.597593
4.689616
false
false
false
false
exponent/exponent
packages/expo-localization/android/src/main/java/expo/modules/localization/LocalizationModule.kt
2
2776
package expo.modules.localization import android.os.Bundle import android.view.View import android.text.TextUtils import android.content.Context import android.os.Build.VERSION import android.os.Build.VERSION_CODES import expo.modules.core.Promise import expo.modules.core.ExportedModule import expo.modules.core.interfaces.ExpoMethod import kotlin.collections.ArrayList import java.lang.ref.WeakReference import java.text.DecimalFormatSymbols import java.util.* class LocalizationModule(context: Context) : ExportedModule(context) { private val contextRef: WeakReference<Context> = WeakReference(context) private val applicationContext: Context? get() = contextRef.get()?.applicationContext override fun getName() = "ExpoLocalization" override fun getConstants(): Map<String, Any> { val constants = HashMap<String, Any>() val bundle = bundledConstants for (key in bundle.keySet()) { constants[key] = bundle[key] as Any } return constants } @ExpoMethod fun getLocalizationAsync(promise: Promise) { promise.resolve(bundledConstants) } // TODO: Bacon: add set language private val bundledConstants: Bundle get() { val locale = Locale.getDefault() val locales = locales val localeNames = getLocaleNames(locales) val isRTL = TextUtils.getLayoutDirectionFromLocale(locale) == View.LAYOUT_DIRECTION_RTL val region = getRegionCode(locale) val symbols = DecimalFormatSymbols(locale) return Bundle().apply { putString("currency", getCurrencyCode(locale)) putString("decimalSeparator", symbols.decimalSeparator.toString()) putString("digitGroupingSeparator", symbols.groupingSeparator.toString()) putStringArrayList("isoCurrencyCodes", iSOCurrencyCodes) putBoolean("isMetric", !USES_IMPERIAL.contains(region)) putBoolean("isRTL", isRTL) putString("locale", localeNames[0]) putStringArrayList("locales", localeNames) putString("region", region) putString("timezone", TimeZone.getDefault().id) } } private val locales: ArrayList<Locale> get() { val context = applicationContext ?: return ArrayList() val configuration = context.resources.configuration return if (VERSION.SDK_INT > VERSION_CODES.N) { val locales = ArrayList<Locale>() for (i in 0 until configuration.locales.size()) { locales.add(configuration.locales[i]) } locales } else { arrayListOf(configuration.locale) } } private fun getRegionCode(locale: Locale): String? { val miuiRegion = getSystemProperty("ro.miui.region") return if (!TextUtils.isEmpty(miuiRegion)) { miuiRegion } else getCountryCode(locale) } }
bsd-3-clause
d494021e9ccf1a9ab34d1c4b71bd3772
31.658824
93
0.708573
4.558292
false
true
false
false
jk1/youtrack-idea-plugin
src/main/kotlin/com/github/jk1/ytplugin/issues/actions/AddCommentAction.kt
1
1016
package com.github.jk1.ytplugin.issues.actions import com.github.jk1.ytplugin.issues.model.Issue import com.github.jk1.ytplugin.ui.CommentDialog import com.github.jk1.ytplugin.whenActive import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnActionEvent import javax.swing.Icon class AddCommentAction(private val getSelectedIssue: () -> Issue?) : IssueAction() { override val text = "Add Comment" override val description = "Open the command dialog and add a comment to the selected issue" override val icon: Icon = AllIcons.General.Balloon override val shortcut = "control shift C" override fun actionPerformed(event: AnActionEvent) { event.whenActive { project -> val issue = getSelectedIssue.invoke() if (issue != null) { CommentDialog(project, issue).show() } } } override fun update(event: AnActionEvent) { event.presentation.isEnabled = getSelectedIssue.invoke() != null } }
apache-2.0
0f98705ab1429be1fcfec80635a28045
34.068966
96
0.704724
4.323404
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/refactoring/changeSignature/RsChangeSignatureUsageProcessor.kt
2
5536
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.refactoring.changeSignature import com.intellij.openapi.project.Project import com.intellij.openapi.util.Ref import com.intellij.psi.PsiElement import com.intellij.refactoring.changeSignature.ChangeInfo import com.intellij.refactoring.changeSignature.ChangeSignatureUsageProcessor import com.intellij.refactoring.rename.ResolveSnapshotProvider import com.intellij.usageView.UsageInfo import com.intellij.util.containers.MultiMap import org.rust.RsBundle import org.rust.ide.presentation.getPresentation import org.rust.lang.core.psi.RsFunction import org.rust.lang.core.psi.RsImplItem import org.rust.lang.core.psi.ext.* import org.rust.lang.core.resolve.namespaces import org.rust.stdext.intersects class RsChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { override fun findUsages(changeInfo: ChangeInfo?): Array<UsageInfo> { if (changeInfo !is RsSignatureChangeInfo) return emptyArray() val function = changeInfo.config.function val usages = findFunctionUsages(function).toMutableList() if (function.owner is RsAbstractableOwner.Trait) { function.searchForImplementations().filterIsInstance<RsFunction>().forEach { method -> usages.add(RsFunctionUsage.MethodImplementation(method)) usages.addAll(findFunctionUsages(method)) } } return usages.toTypedArray() } override fun findConflicts(changeInfo: ChangeInfo?, refUsages: Ref<Array<UsageInfo>>): MultiMap<PsiElement, String> { if (changeInfo !is RsSignatureChangeInfo) return MultiMap.empty() val map = MultiMap<PsiElement, String>() val config = changeInfo.config val function = config.function findNameConflicts(function, config, map) findVisibilityConflicts(function, config, refUsages.get(), map) return map } override fun processUsage( changeInfo: ChangeInfo?, usageInfo: UsageInfo?, beforeMethodChange: Boolean, usages: Array<out UsageInfo>? ): Boolean { if (beforeMethodChange) return false if (changeInfo !is RsSignatureChangeInfo) return false if (usageInfo !is RsFunctionUsage) return false val config = changeInfo.config if (usageInfo is RsFunctionUsage.MethodImplementation) { processFunction(config.function.project, config, usageInfo.overriddenMethod, true) } else { processFunctionUsage(config, usageInfo) } return true } override fun processPrimaryMethod(changeInfo: ChangeInfo?): Boolean { if (changeInfo !is RsSignatureChangeInfo) return false val config = changeInfo.config val function = config.function val project = function.project processFunction(project, config, function, changeInfo.changeSignature) return true } override fun shouldPreviewUsages(changeInfo: ChangeInfo?, usages: Array<out UsageInfo>?): Boolean = false override fun setupDefaultValues( changeInfo: ChangeInfo?, refUsages: Ref<Array<UsageInfo>>?, project: Project? ): Boolean { return true } override fun registerConflictResolvers( snapshots: MutableList<in ResolveSnapshotProvider.ResolveSnapshot>, resolveSnapshotProvider: ResolveSnapshotProvider, usages: Array<out UsageInfo>, changeInfo: ChangeInfo? ) {} } private fun findVisibilityConflicts( function: RsFunction, config: RsChangeFunctionSignatureConfig, usages: Array<UsageInfo>, map: MultiMap<PsiElement, String> ) { val functionUsages = usages.filterIsInstance<RsFunctionUsage>() val clone = function.copy() as RsFunction changeVisibility(clone, config) for (usage in functionUsages) { val sourceModule = usage.element.containingMod if (!clone.isVisibleFrom(sourceModule)) { val moduleName = sourceModule.qualifiedName.orEmpty() map.putValue(usage.element, RsBundle.message("refactoring.change.signature.visibility.conflict", moduleName)) } } } private fun findNameConflicts( function: RsFunction, config: RsChangeFunctionSignatureConfig, map: MultiMap<PsiElement, String> ) { val (owner, items) = when (val owner = function.owner) { is RsAbstractableOwner.Impl -> owner.impl to owner.impl.expandedMembers is RsAbstractableOwner.Trait -> owner.trait to owner.trait.expandedMembers else -> { val parent = function.contextStrict<RsItemsOwner>() ?: return val items = parent.expandedItemsCached.getNamedElementsIfCfgEnabled(config.name) ?: return parent to items } } for (item in items) { if (item == function) continue if (!item.existsAfterExpansionSelf) continue val namedItem = item as? RsNamedElement ?: continue if (!function.namespaces.intersects(namedItem.namespaces)) continue if (namedItem.name == config.name) { val presentation = getPresentation(owner) val prefix = if (owner is RsImplItem) "impl " else "" val ownerName = "${prefix}${presentation.presentableText.orEmpty()} ${presentation.locationString.orEmpty()}" map.putValue(namedItem, RsBundle.message("refactoring.change.signature.name.conflict", config.name, ownerName)) } } }
mit
99dc4bb6e2f4e60a2503924a365f8c45
36.917808
123
0.70177
4.886143
false
true
false
false
androidx/androidx
external/paparazzi/paparazzi/src/main/java/app/cash/paparazzi/internal/parsers/ResourceParser.kt
3
4168
/* * Copyright (C) 2021 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 app.cash.paparazzi.internal.parsers import com.android.SdkConstants.AAPT_URI import com.android.SdkConstants.TAG_ATTR import org.kxml2.io.KXmlParser import java.io.InputStream /** * An XML resource parser that creates a tree of [TagSnapshot]s */ class ResourceParser(inputStream: InputStream) : KXmlParser() { init { setFeature(FEATURE_PROCESS_NAMESPACES, true) setInput(inputStream, null) require(START_DOCUMENT, null, null) next() } fun createTagSnapshot(): TagSnapshot { require(START_TAG, null, null) // need to store now, since TagSnapshot is created on end tag after parser mark has moved val tagName = name val tagNamespace = namespace val prefix = prefix val attributes = createAttributesForTag() var hasDeclaredAaptAttrs = false var last: TagSnapshot? = null val children = mutableListOf<TagSnapshot>() while (eventType != END_DOCUMENT) { when (next()) { START_TAG -> { if (AAPT_URI == namespace) { if (TAG_ATTR == name) { val attrAttribute = createAttrTagSnapshot() if (attrAttribute != null) { attributes += attrAttribute hasDeclaredAaptAttrs = true } } // Since we save the aapt:attr tags as an attribute, we do not save them as a child element. Skip. } else { val child = createTagSnapshot() hasDeclaredAaptAttrs = hasDeclaredAaptAttrs || child.hasDeclaredAaptAttrs children += child if (last != null) { last.next = child } last = child } } END_TAG -> { return TagSnapshot( tagName, tagNamespace, prefix, attributes, children.toList(), hasDeclaredAaptAttrs ) } } } throw IllegalStateException("We should never reach here") } private fun createAttrTagSnapshot(): AaptAttrSnapshot? { require(START_TAG, null, "attr") val name = getAttributeValue(null, "name") ?: return null val prefix = findPrefixByQualifiedName(name) val namespace = getNamespace(prefix) val localName = findLocalNameByQualifiedName(name) val id = (++uniqueId).toString() var bundleTagSnapshot: TagSnapshot? = null loop@ while (eventType != END_TAG) { when (nextTag()) { START_TAG -> { bundleTagSnapshot = createTagSnapshot() } END_TAG -> { break@loop } } } return if (bundleTagSnapshot != null) { // swallow end tag nextTag() require(END_TAG, null, "attr") AaptAttrSnapshot(namespace, prefix, localName, id, bundleTagSnapshot) } else { null } } private fun findPrefixByQualifiedName(name: String): String { val prefixEnd = name.indexOf(':') return if (prefixEnd > 0) { name.substring(0, prefixEnd) } else "" } private fun findLocalNameByQualifiedName(name: String): String { return name.substring(name.indexOf(':') + 1) } private fun createAttributesForTag(): MutableList<AttributeSnapshot> { return buildList { for (i in 0 until attributeCount) { add( AttributeSnapshot( getAttributeNamespace(i), getAttributePrefix(i), getAttributeName(i), getAttributeValue(i) ) ) } }.toMutableList() } companion object { private var uniqueId = 0L } }
apache-2.0
3dfd349c3adeb6c69effa4505d099085
27.353741
110
0.617802
4.415254
false
false
false
false
j-selby/EscapistsRuntime
core/src/main/java/net/jselby/escapists/game/ObjectInstance.kt
1
3531
package net.jselby.escapists.game import net.jselby.escapists.data.ObjectDefinition import net.jselby.escapists.data.chunks.ObjectInstances import net.jselby.escapists.data.objects.ObjectCommon import org.mini2Dx.core.graphics.Graphics import java.util.* /** * A instance of an object within the world. * @author j_selby */ abstract class ObjectInstance(definition: ObjectDefinition, instance: ObjectInstances.ObjectInstance) { /** * Returns the name of this object. * @return A String value */ val name: String /** * Returns the ID of this object. * @return An object ID */ private val id: Int /** * Returns the layer that this object exists on. Should not change post init. * @return The layer ID of this object. */ val layerID: Int /** * Returns this Object's ObjectInfo information. * @return A ObjectInfo handle. */ val objectInfo: Int open var x: Float = 0f open var y: Float = 0f var animation = 0 var animationFrame = 0 var imageAlpha = 255 var bold = false var isVisible = true val namedVariables: Map<String, Any> = HashMap() val configVariables: Map<String, Any> = HashMap() val alterableValues: IntArray = IntArray(26); val alterableStrings: Array<String> = Array(26, {i -> ""}); var httpContentLoaded = false var httpContent = "" val listElements: List<String> = ArrayList() var selectedLine = 0 var loadedFile = "" init { this.name = definition.name.trim() this.id = instance.handle this.objectInfo = instance.objectInfo this.layerID = instance.layer.toInt() this.x = instance.x.toFloat() this.y = instance.y.toFloat() if (definition.properties.isCommon) { val objectCommon = (definition.properties.properties as ObjectCommon?)!!; isVisible = objectCommon.isVisibleAtStart; if (objectCommon.values != null) { var i = 0; for (value in objectCommon.values.values) { alterableValues[i++] = value; } } if (objectCommon.strings != null) { var i = 0; for (value in objectCommon.strings.strings) { alterableStrings[i++] = value; } } } } /** * Returns the width of this object * @return A width argument */ abstract val width: Float /** * Returns the height of this object * @return A height argument */ abstract val height: Float /** * Gets the X position of the object as it would be, rendered to the screen. * This is independent of cameras, and is simply accounting for centering, etc. */ open fun getScreenX(): Float = x /** * Gets the Y position of the object as it would be, rendered to the screen. * This is independent of cameras, and is simply accounting for centering, etc. */ open fun getScreenY(): Float = y /** * Ticks this object, accepting input and responding accordingly. * @param container The container to poll information from. */ abstract fun tick(container: EscapistsGame) /** * Draws this object onto the screen. * @param container The container to poll information from. * * * @param g The graphics instance to draw stuff onto. */ abstract fun draw(container: EscapistsGame, g: Graphics) }
mit
1bf99bdff218e8f39a6932dceecde067
26.80315
103
0.61484
4.306098
false
false
false
false
hidroh/tldroid
app/src/main/kotlin/io/github/hidroh/tldroid/CommandActivity.kt
1
5391
package io.github.hidroh.tldroid import android.content.Intent import android.databinding.DataBindingUtil import android.databinding.ViewDataBinding import android.net.Uri import android.os.AsyncTask import android.os.Bundle import android.preference.PreferenceManager import android.support.design.widget.CollapsingToolbarLayout import android.support.v4.view.MenuItemCompat import android.support.v7.app.ActionBar import android.support.v7.widget.ShareActionProvider import android.support.v7.widget.Toolbar import android.text.Html import android.text.TextUtils import android.view.Menu import android.view.MenuItem import android.view.View import android.webkit.WebChromeClient import android.webkit.WebView import android.webkit.WebViewClient import java.lang.ref.WeakReference class CommandActivity : ThemedActivity() { companion object { val EXTRA_QUERY = CommandActivity::class.java.name + ".EXTRA_QUERY" val EXTRA_PLATFORM = CommandActivity::class.java.name + ".EXTRA_PLATFORM" private val STATE_CONTENT = "state:content" private val PLATFORM_OSX = "osx" } private var mContent: String? = null private var mQuery: String? = null private var mPlatform: String? = null private var mBinding: ViewDataBinding? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mQuery = intent.getStringExtra(EXTRA_QUERY) mPlatform = intent.getStringExtra(EXTRA_PLATFORM) title = mQuery mBinding = DataBindingUtil.setContentView<ViewDataBinding>(this, R.layout.activity_command) setSupportActionBar(findViewById(R.id.toolbar) as Toolbar?) supportActionBar!!.displayOptions = ActionBar.DISPLAY_SHOW_HOME or ActionBar.DISPLAY_HOME_AS_UP or ActionBar.DISPLAY_SHOW_TITLE val collapsingToolbar = findViewById(R.id.collapsing_toolbar_layout) as CollapsingToolbarLayout? collapsingToolbar!!.setExpandedTitleTypeface(Application.MONOSPACE_TYPEFACE) collapsingToolbar.setCollapsedTitleTypeface(Application.MONOSPACE_TYPEFACE) val webView = findViewById(R.id.web_view) as WebView? webView!!.setWebChromeClient(WebChromeClient()) webView.setWebViewClient(object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) return true } }) if (savedInstanceState != null) { mContent = savedInstanceState.getString(STATE_CONTENT) } if (mContent == null) { GetCommandTask(this, mPlatform).execute(mQuery) } else { render(mContent) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_run, menu) menuInflater.inflate(R.menu.menu_share, menu) // disable share history MenuItemCompat.setActionProvider(menu.findItem(R.id.menu_share), object : ShareActionProvider(this) { override fun onCreateActionView(): View? { return null } }) return super.onCreateOptionsMenu(menu) } override fun onPrepareOptionsMenu(menu: Menu): Boolean { val itemShare = menu.findItem(R.id.menu_share) val visible = !TextUtils.isEmpty(mContent) itemShare.isVisible = visible if (visible) { (MenuItemCompat.getActionProvider(itemShare) as ShareActionProvider) .setShareIntent(Intent(Intent.ACTION_SEND) .setType("text/plain") .putExtra(Intent.EXTRA_SUBJECT, mQuery) .putExtra(Intent.EXTRA_TEXT, Html.fromHtml(mContent).toString())) } menu.findItem(R.id.menu_run).isVisible = visible && !TextUtils.equals(PLATFORM_OSX, mPlatform) return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finish() return true } if (item.itemId == R.id.menu_run) { startActivity(Intent(this, RunActivity::class.java) .putExtra(RunActivity.EXTRA_COMMAND, mQuery)) return true } return super.onOptionsItemSelected(item) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(STATE_CONTENT, mContent) } internal fun render(html: String?) { mContent = html ?: "" supportInvalidateOptionsMenu() // just display a generic message if empty for now mBinding!!.setVariable(io.github.hidroh.tldroid.BR.content, if (TextUtils.isEmpty(mContent)) getString(R.string.empty_html) else html) } internal class GetCommandTask(commandActivity: CommandActivity, platform: String?) : AsyncTask<String, Void, String>() { private val commandActivity: WeakReference<CommandActivity> = WeakReference(commandActivity) private val processor: MarkdownProcessor = MarkdownProcessor(platform) override fun doInBackground(vararg params: String): String? { val context = commandActivity.get() ?: return null val commandName = params[0] val lastModified = PreferenceManager.getDefaultSharedPreferences(context) .getLong(SyncService.PREF_LAST_ZIPPED, 0L) return processor.process(context, commandName, lastModified) } override fun onPostExecute(s: String?) { if (commandActivity.get() != null) { (commandActivity.get() as CommandActivity).render(s) } } } }
apache-2.0
aeea1d2d3f688e86bca197eff078512b
36.964789
100
0.730106
4.375812
false
false
false
false
hidroh/tldroid
app/src/main/kotlin/io/github/hidroh/tldroid/Bindings.kt
1
3906
package io.github.hidroh.tldroid import android.content.Context import android.database.Cursor import android.databinding.BaseObservable import android.databinding.BindingAdapter import android.support.annotation.AttrRes import android.support.annotation.IdRes import android.support.v4.content.ContextCompat import android.text.SpannableString import android.text.Spanned import android.text.TextUtils import android.text.style.ForegroundColorSpan import android.webkit.WebView import android.widget.TextView object Bindings { private val FORMAT_HTML_COLOR = "%06X" @JvmStatic @BindingAdapter("bind:monospace") fun setFont(textView: TextView, enabled: Boolean) { if (enabled) { textView.typeface = Application.MONOSPACE_TYPEFACE } } @JvmStatic @BindingAdapter("bind:highlightText", "bind:highlightColor") fun highlightText(textView: TextView, highlightText: String, @AttrRes highlightColor: Int) { if (TextUtils.isEmpty(highlightText)) { return } val spannable = SpannableString(textView.text) val start = TextUtils.indexOf(spannable, highlightText) if (start >= 0) { spannable.setSpan(ForegroundColorSpan(ContextCompat.getColor( textView.context, getIdRes(textView.context, highlightColor))), start, start + highlightText.length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE) } textView.text = spannable } @JvmStatic @BindingAdapter("bind:html", "bind:htmlBackgroundColor", "bind:htmlTextColor", "bind:htmlLinkColor", "bind:htmlTextSize", "bind:htmlMargin") fun setHtml(webView: WebView, html: String?, @AttrRes backgroundColor: Int, @AttrRes textColor: Int, @AttrRes linkColor: Int, textSize: Float, margin: Float) { if (TextUtils.isEmpty(html)) { return } webView.setBackgroundColor(ContextCompat.getColor(webView.context, getIdRes(webView.context, backgroundColor))) webView.loadDataWithBaseURL(null, wrapHtml(webView.context, html, textColor, linkColor, textSize, margin), "text/html", "UTF-8", null) } private fun wrapHtml(context: Context, html: String?, @AttrRes textColor: Int, @AttrRes linkColor: Int, textSize: Float, margin: Float): String { return context.getString(R.string.styled_html, html, toHtmlColor(context, textColor), toHtmlColor(context, linkColor), toHtmlPx(context, textSize), toHtmlPx(context, margin), toHtmlColor(context, R.attr.colorDefinition), toHtmlColor(context, R.attr.colorLiteral)) } private fun toHtmlColor(context: Context, @AttrRes colorAttr: Int): String { return String.format(FORMAT_HTML_COLOR, 0xFFFFFF and ContextCompat.getColor(context, getIdRes(context, colorAttr))) } private fun toHtmlPx(context: Context, dimen: Float): Float { return dimen / context.resources.displayMetrics.density } @IdRes private fun getIdRes(context: Context, @AttrRes attrRes: Int): Int { val ta = context.theme.obtainStyledAttributes(intArrayOf(attrRes)) val resId = ta.getResourceId(0, 0) ta.recycle() return resId } class Command : BaseObservable() { var name: String? = null var platform: String? = null companion object { @JvmStatic fun fromProvider(cursor: Cursor): Command { val command = Command() command.name = cursor.getString(cursor.getColumnIndexOrThrow( TldrProvider.CommandEntry.COLUMN_NAME)) command.platform = cursor.getString(cursor.getColumnIndexOrThrow( TldrProvider.CommandEntry.COLUMN_PLATFORM)) return command } } } }
apache-2.0
3ed72dbf96f9dc77119c32c08f2caa9f
31.823529
88
0.666667
4.61157
false
false
false
false
y2k/JoyReactor
ios/src/main/kotlin/y2k/joyreactor/PostViewController.kt
1
8302
package y2k.joyreactor import org.robovm.apple.uikit.* import org.robovm.objc.annotation.CustomClass import org.robovm.objc.annotation.IBOutlet import y2k.joyreactor.common.ListCell import y2k.joyreactor.common.ServiceLocator import y2k.joyreactor.common.bindingBuilder import y2k.joyreactor.common.translate import y2k.joyreactor.model.Comment import y2k.joyreactor.platform.ImageRequest import y2k.joyreactor.viewmodel.PostViewModel /** * Created by y2k on 28/09/15. */ @CustomClass("PostViewController") class PostViewController : UIViewController() { @IBOutlet lateinit var list: UITableView // lateinit var presenter: PostPresenter // internal var comments: CommentGroup? = null // internal var post: Post? = null override fun viewDidLoad() { super.viewDidLoad() // UILongPressGestureRecognizer gr = new UILongPressGestureRecognizer(); // gr.setMinimumPressDuration(0.5); // gr.addListener(s -> { // if (s.getState() != UIGestureRecognizerState.Ended) return; // // UIActionSheet menu = new UIActionSheet(); // menu.addButton(Translator.get("Reply")); // menu.setCancelButtonIndex(menu.addButton(Translator.get("Cancel"))); // menu.setDelegate(new UIActionSheetDelegateAdapter() { // // @Override // public void clicked(UIActionSheet actionSheet, long buttonIndex) { // if (buttonIndex == 0) // getNavigationController().pushViewController( // getStoryboard().instantiateViewController("CreateComment"), true); // } // }); // menu.showFrom(getNavigationItem().getRightBarButtonItem(), true); // }); // list.addGestureRecognizer(gr); val vm = ServiceLocator.resolve<PostViewModel>() bindingBuilder { // FIXME: вернуть загрузку поста tableView(list, vm.comments) { cellSelector { "Comment" } command { vm.selectComment(it) } } } navigationItem.rightBarButtonItem.setOnClickListener { val alert = UIAlertController() alert.addAction(UIAlertAction("Add comment".translate(), UIAlertActionStyle.Default) { s -> navigationController.pushViewController( storyboard.instantiateViewController("CreateComment"), true) }) alert.addAction(UIAlertAction("Save image to gallery".translate(), UIAlertActionStyle.Default) { vm.saveToGallery() }) alert.addAction(UIAlertAction("Open in Safari".translate(), UIAlertActionStyle.Default) { vm.openInBrowser() }) alert.addAction(UIAlertAction("Cancel".translate(), UIAlertActionStyle.Cancel, null)) presentViewController(alert, true, null) } // list.setDelegate(CommentDelegate()) // list.dataSource = CommentDataSource() // list.rowHeight = UITableView.getAutomaticDimension() // list.estimatedRowHeight = 44.0 // // presenter = ServiceLocator.resolve(this) } @CustomClass("CommentCell") class CommentCell : ListCell<Comment>() { @IBOutlet lateinit var commentText: UILabel @IBOutlet lateinit var userImage: UIImageView @IBOutlet lateinit var replies: UILabel @IBOutlet lateinit var rating: UILabel override fun bind(data: Comment, position: Int) { commentText.text = data.text userImage.layer.cornerRadius = userImage.frame.width / 2 ImageRequest() .setUrl(data.userImageObject.toImage()) .setSize(userImage.frame.width.toInt(), userImage.frame.height.toInt()) .to(userImage, { userImage.image = it }) replies.text = "" + data.replies rating.text = "" + data.rating } } // class CommentDataSource : UITableViewDataSourceAdapter() { // override fun getTitleForHeader(tableView: UITableView?, section: Long): String? { // return super.getTitleForHeader(tableView, section) // } // } // override fun updateComments(comments: CommentGroup) { // this.comments = comments // list.reloadData() // } // // override fun updatePostInformation(post: Post) { // this.post = post // list.reloadData() // } // // override fun setIsBusy(isBusy: Boolean) { // navigationItem.setHidesBackButton(isBusy, true) // navigationItem.rightBarButtonItem.isEnabled = !isBusy // } // // override fun showImageSuccessSavedToGallery() { // // TODO // } // // override fun updatePostImage(image: File) { // // TODO: // } // // override fun updateImageDownloadProgress(progress: Int, maxProgress: Int) { // // TODO: // } // // override fun setEnableCreateComments() { // // TODO: // } // // override fun updatePostImages(images: List<Image>) { // // TODO: // } // // override fun updateSimilarPosts(similarPosts: List<SimilarPost>) { // // TODO: // } // private inner class CommentDataSource : UITableViewDataSourceAdapter() { // // override fun getNumberOfRowsInSection(tableView: UITableView?, section: Long): Long { // return ((if (comments == null) 0 else comments!!.size()) + 1).toLong() // } // // override fun getCellForRow(tableView: UITableView?, indexPath: NSIndexPath?): UITableViewCell { // return if (indexPath!!.row == 0) // createHeaderCell(tableView!!) // else // createCommentCell(tableView!!, indexPath) // } // // internal fun createHeaderCell(tableView: UITableView): UITableViewCell { // val cell: UITableViewCell // cell = tableView.dequeueReusableCell("Header") // if (post != null) { // val iv = cell.getViewWithTag(1) as UIImageView // // val image = post!!.image // if (image == null) { // // TODO: // } else { // ImageRequest() // .setUrl(post!!.image) // .setSize(300, (300 / image.aspect).toInt()) // .to(iv) { iv.image = it } // } // } // return cell // } // // internal fun createCommentCell(tableView: UITableView, indexPath: NSIndexPath): UITableViewCell { // val cell: UITableViewCell // cell = tableView.dequeueReusableCell("Comment") // val item = comments!![indexPath.row - 1] // (cell.getViewWithTag(1) as UILabel).text = item.text // // val iv = cell.getViewWithTag(2) as UIImageView // iv.layer.cornerRadius = iv.frame.width / 2 // ImageRequest() // .setUrl(item.userImageObject.toImage()) // .setSize(iv.frame.width.toInt(), iv.frame.height.toInt()) // .to(iv) { iv.image = it } // // (cell.getViewWithTag(3) as UILabel).text = "" + item.replies // (cell.getViewWithTag(4) as UILabel).text = "" + item.rating // // return cell // } // } // // private inner class CommentDelegate : UITableViewDelegateAdapter() { // // override fun didSelectRow(tableView: UITableView?, indexPath: NSIndexPath?) { // presenter.selectComment(comments!![indexPath!!.row - 1].id) // tableView!!.deselectRow(indexPath, true) // } // } }
gpl-2.0
8caf9f8aaada4f2b719ee77d2920dd73
38.442857
111
0.5454
4.663288
false
false
false
false
inorichi/tachiyomi-extensions
src/vi/iutruyentranh/src/eu/kanade/tachiyomi/extension/vi/iutruyentranh/IuTruyenTranh.kt
1
6886
package eu.kanade.tachiyomi.extension.vi.iutruyentranh import android.annotation.SuppressLint import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.OkHttpClient import okhttp3.Request import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat import java.util.Locale class IuTruyenTranh : ParsedHttpSource() { override val name = "IuTruyenTranh" override val baseUrl = "http://iutruyentranh.com" override val lang = "vi" override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient override fun popularMangaSelector() = "div.media" override fun latestUpdatesSelector() = popularMangaSelector() override fun popularMangaRequest(page: Int): Request { return GET("$baseUrl/genre/$page?popular", headers) } override fun latestUpdatesRequest(page: Int): Request { return GET("$baseUrl/latest/$page", headers) } override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() element.select("h4 a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.text() } manga.thumbnail_url = element.select("img").attr("abs:data-original") return manga } override fun latestUpdatesFromElement(element: Element): SManga { return popularMangaFromElement(element) } override fun popularMangaNextPageSelector() = "ul.pagination > li:contains(...»)" override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector() @SuppressLint("DefaultLocale") override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val url = "$baseUrl/search/$page?".toHttpUrlOrNull()!!.newBuilder().addQueryParameter("name", query) val genres = mutableListOf<String>() val genresEx = mutableListOf<String>() (if (filters.isEmpty()) getFilterList() else filters).forEach { filter -> when (filter) { is Author -> url.addQueryParameter("autart", filter.state) is GenreList -> filter.state.forEach { genre -> when (genre.state) { Filter.TriState.STATE_INCLUDE -> genres.add(genre.name.toLowerCase()) Filter.TriState.STATE_EXCLUDE -> genresEx.add(genre.name.toLowerCase()) } } } } if (genres.isNotEmpty()) url.addQueryParameter("genres", genres.joinToString(",")) if (genresEx.isNotEmpty()) url.addQueryParameter("genres-exclude", genresEx.joinToString(",")) return GET(url.toString(), headers) } override fun searchMangaSelector() = popularMangaSelector() override fun searchMangaFromElement(element: Element): SManga { return popularMangaFromElement(element) } override fun searchMangaNextPageSelector() = popularMangaNextPageSelector() override fun mangaDetailsParse(document: Document): SManga { val infoElement = document.select("section.manga article").first() val manga = SManga.create() manga.author = infoElement.select("span[itemprop=author]").first()?.text() manga.genre = infoElement.select("a[itemprop=genre]").joinToString { it.text() } manga.description = infoElement.select("p.box.box-danger").text() manga.status = infoElement.select("a[rel=nofollow]").last()?.text().orEmpty().let { parseStatus(it) } manga.thumbnail_url = infoElement.select("img[class^=thumbnail]").first()?.attr("src") return manga } private fun parseStatus(status: String) = when { status.contains("Đang tiến hành") -> SManga.ONGOING status.contains("Đã hoàn thành") -> SManga.COMPLETED else -> SManga.UNKNOWN } override fun chapterListSelector() = "ul.list-unstyled > table > tbody > tr" override fun chapterFromElement(element: Element): SChapter { val urlElement = element.select("a").first() val chapter = SChapter.create() chapter.setUrlWithoutDomain(urlElement.attr("href") + "&load=all") chapter.name = urlElement.select("b").text() chapter.date_upload = element.select("td:eq(1)").first()?.text()?.let { SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).parse(it)?.time ?: 0L } ?: 0 return chapter } override fun pageListParse(document: Document): List<Page> { return document.select("a.img-link img").mapIndexed { i, img -> Page(i, "", img.attr("abs:src")) } } override fun imageUrlParse(document: Document) = throw UnsupportedOperationException("Not used") private class Author : Filter.Text("Tác giả") private class Genre(name: String) : Filter.TriState(name) private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Thể loại", genres) override fun getFilterList() = FilterList( Author(), GenreList(getGenreList()) ) private fun getGenreList() = listOf( Genre("Action"), Genre("Adult"), Genre("Adventure"), Genre("Anime"), Genre("Bishounen"), Genre("Comedy"), Genre("Cookin"), Genre("Demons"), Genre("Doujinshi"), Genre("Drama"), Genre("Ecchi"), Genre("Fantasy"), Genre("Gender Bender"), Genre("Harem"), Genre("Hentai"), Genre("Historical"), Genre("Horror"), Genre("Josei"), Genre("Live action"), Genre("Magic"), Genre("Manhua"), Genre("Manhwa"), Genre("Martial Arts"), Genre("Mature"), Genre("Mecha"), Genre("Medical"), Genre("Military"), Genre("Mystery"), Genre("One shot"), Genre("Oneshot"), Genre("Other"), Genre("Psychological"), Genre("Romance"), Genre("School Life"), Genre("Sci fi"), Genre("Seinen"), Genre("Shotacon"), Genre("Shoujo"), Genre("Shoujo Ai"), Genre("Shoujoai"), Genre("Shounen"), Genre("Shounen Ai"), Genre("Shounenai"), Genre("Slice of Life"), Genre("Smut"), Genre("Sports"), Genre("Super power"), Genre("Superma"), Genre("Supernatural"), Genre("Tragedy"), Genre("Vampire"), Genre("Webtoon"), Genre("Yaoi"), Genre("Yuri") ) }
apache-2.0
c2c0f9217cbf85ab68e3f304c0509b03
34.05102
109
0.627802
4.635628
false
false
false
false
springboot-angular2-tutorial/android-app
app/src/androidTest/kotlin/com/hana053/micropost/pages/relateduserlist/RelatedUserListActivityTest.kt
1
7768
package com.hana053.micropost.pages.relateduserlist import android.content.Intent import android.support.test.espresso.Espresso.onView import android.support.test.espresso.action.ViewActions.click import android.support.test.espresso.assertion.ViewAssertions.matches import android.support.test.espresso.matcher.ViewMatchers.* import android.support.test.filters.LargeTest import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import com.github.salomonbrys.kodein.bind import com.github.salomonbrys.kodein.instance import com.hana053.micropost.R import com.hana053.micropost.interactor.RelatedUserListInteractor import com.hana053.micropost.interactor.RelationshipInteractor import com.hana053.micropost.pages.relateduserlist.RelatedUserListActivity.ListType.FOLLOWER import com.hana053.micropost.pages.relateduserlist.RelatedUserListActivity.ListType.FOLLOWING import com.hana053.micropost.service.AuthService import com.hana053.micropost.service.Navigator import com.hana053.micropost.testing.* import com.nhaarman.mockito_kotlin.anyOrNull import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import rx.Observable @RunWith(AndroidJUnit4::class) @LargeTest class RelatedUserListActivityTest : InjectableTest by InjectableTestImpl() { @Rule @JvmField val activityRule = ActivityTestRule(RelatedUserListActivity::class.java, false, false) // ------------- FOLLOWER part ------------- @Test fun shouldBeOpenedWhenAuthenticated() { overrideAppBindings { fakeAuthToken() bind<RelatedUserListInteractor>(overrides = true) with instance(mock<RelatedUserListInteractor> { // just avoiding error on { listFollowers(userId = 1, maxId = null) } doReturn Observable.empty() }) } launchActivity(FOLLOWER, 1) onView(withText(R.string.Followers)).check(matches(isDisplayed())) } @Test fun shouldNotBeOpenedWhenNotAuthenticated() { val navigator = mock<Navigator>() overrideAppBindings { bind<Navigator>(overrides = true) with instance(navigator) } launchActivity(FOLLOWER, 1) verify(navigator).navigateToTop() } @Test fun shouldShowFollowers() { overrideAppBindings { fakeAuthToken() bind<RelatedUserListInteractor>(overrides = true) with instance(mock<RelatedUserListInteractor> { on { listFollowers(1, null) } doReturn Observable.just(listOf( TestRelatedUser.copy(relationshipId = 1, name = "John Doe") )) // just avoiding error on { listFollowers(userId = 1, maxId = 1) } doReturn Observable.empty() }) } launchActivity(FOLLOWER, 1) onView(withId(R.id.list_user)) .check(matches(atPositionOnView(0, withText("John Doe"), R.id.tv_user_name))) } @Test fun shouldLoadPreviousUsersWhenReachedToBottom() { overrideAppBindings { fakeAuthToken() bind<RelatedUserListInteractor>(overrides = true) with instance(mock<RelatedUserListInteractor> { on { listFollowers(userId = 1, maxId = null) } doReturn Observable.just(listOf( TestRelatedUser.copy(relationshipId = 1, name = "John Doe") )) on { listFollowers(userId = 1, maxId = 1) } doReturn Observable.just(listOf( TestRelatedUser.copy(relationshipId = 0, name = "Old Follower") )) // just avoiding error on { listFollowers(userId = 1, maxId = 0) } doReturn Observable.empty() }) } launchActivity(FOLLOWER, 1) onView(withId(R.id.list_user)) .check(matches(atPositionOnView(0, withText("John Doe"), R.id.tv_user_name))) onView(withId(R.id.list_user)) .check(matches(atPositionOnView(1, withText("Old Follower"), R.id.tv_user_name))) } @Test fun shouldFollowUserOnList() { overrideAppBindings { fakeAuthToken() bind<AuthService>(overrides = true) with instance(mock<AuthService> { on { auth() } doReturn true on { isMyself(anyOrNull()) } doReturn false // ensure button is shown }) bind<RelatedUserListInteractor>(overrides = true) with instance(mock<RelatedUserListInteractor> { on { listFollowers(1, null) } doReturn Observable.just(listOf( TestRelatedUser.copy(relationshipId = 1, isFollowedByMe = false) // Follow btn will be shown )) // just avoiding error on { listFollowers(userId = 1, maxId = 1) } doReturn Observable.empty() }) bind<RelationshipInteractor>(overrides = true) with instance(mock<RelationshipInteractor> { on { follow(1) } doReturn Observable.just<Void>(null) }) } launchActivity(FOLLOWER, 1) onView(withId(R.id.btn_follow)).perform(click()) onView(withId(R.id.btn_follow)).check(matches(withText(R.string.Unfollow))) } @Test fun shouldNavigateToUserShowWhenAvatarClicked() { val navigator: Navigator = mock() overrideAppBindings { fakeAuthToken() bind<RelatedUserListInteractor>(overrides = true) with instance(mock<RelatedUserListInteractor> { on { listFollowers(1, null) } doReturn Observable.just(listOf( TestRelatedUser.copy(id = 100, relationshipId = 1) )) // just avoiding error on { listFollowers(userId = 1, maxId = 1) } doReturn Observable.empty() }) bind<Navigator>(overrides = true) with instance(navigator) } launchActivity(FOLLOWER, 1) onView(withId(R.id.img_avatar)).perform(click()) verify(navigator).navigateToUserShow(100) } // ------------- FOLLOWING part ------------- @Test fun shouldBeOpenedWhenAuthenticatedAsFollowing() { overrideAppBindings { fakeAuthToken() bind<RelatedUserListInteractor>(overrides = true) with instance(mock<RelatedUserListInteractor> { // just avoiding error on { listFollowings(userId = 1, maxId = null) } doReturn Observable.empty() }) } launchActivity(FOLLOWING, 1) onView(withText(R.string.Followings)).check(matches(isDisplayed())) } @Test fun shouldShowFollowings() { overrideAppBindings { fakeAuthToken() bind<RelatedUserListInteractor>(overrides = true) with instance(mock<RelatedUserListInteractor> { on { listFollowings(1, null) } doReturn Observable.just(listOf( TestRelatedUser.copy(relationshipId = 1, name = "John Doe") )) // just avoiding error on { listFollowings(userId = 1, maxId = 1) } doReturn Observable.empty() }) } launchActivity(FOLLOWING, 1) onView(withId(R.id.list_user)) .check(matches(atPositionOnView(0, withText("John Doe"), R.id.tv_user_name))) } private fun launchActivity(listType: RelatedUserListActivity.ListType, userId: Long) { val intent = Intent() intent.putExtra(RelatedUserListActivity.KEY_USER_ID, userId) intent.putExtra(RelatedUserListActivity.KEY_LIST_TYPE, listType) activityRule.launchActivity(intent) } }
mit
372470412085d08283bba0fb2c4c18de
40.324468
112
0.643666
4.648713
false
true
false
false
springboot-angular2-tutorial/android-app
app/src/main/kotlin/com/hana053/micropost/pages/signup/SignupServiceImpl.kt
1
1563
package com.hana053.micropost.pages.signup import android.content.Context import android.widget.Toast import com.hana053.micropost.interactor.UserInteractor import com.hana053.micropost.service.HttpErrorHandler import com.hana053.micropost.service.LoginService import retrofit2.HttpException import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers class SignupServiceImpl( private val userInteractor: UserInteractor, private val loginService: LoginService, private val signupNavigator: SignupNavigator, private val httpErrorHandler: HttpErrorHandler, context: Context ) : SignupService { private val context = context.applicationContext override fun signup(request: UserInteractor.SignupRequest): Observable<Void> = userInteractor.create(request) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .doOnError { when { isEmailAlreadyTaken(it) -> { Toast.makeText(context, "This email is already taken.", Toast.LENGTH_LONG).show() signupNavigator.navigateToPrev() } else -> httpErrorHandler.handleError(it) } } .onErrorResumeNext { Observable.empty() } .flatMap { loginService.login(request.email, request.password) } private fun isEmailAlreadyTaken(e: Throwable) = e is HttpException && e.code() == 400 }
mit
aa55de2fbffa7d8618a650b74abfdee3
34.545455
105
0.673065
5.025723
false
false
false
false
czyzby/ktx
json/src/main/kotlin/ktx/json/json.kt
2
2131
package ktx.json import com.badlogic.gdx.files.FileHandle import com.badlogic.gdx.utils.Json import com.badlogic.gdx.utils.JsonValue /** * Parse an object of type [T] from a [file]. */ inline fun <reified T> Json.fromJson(file: FileHandle): T = fromJson(T::class.java, file) /** * Parse an object of type [T] from a [string]. */ inline fun <reified T> Json.fromJson(string: String): T = fromJson(T::class.java, string) /** * Sets a [tag] to use instead of the fully qualifier class name for type [T]. * This can make the JSON easier to read. */ inline fun <reified T> Json.addClassTag(tag: String) = addClassTag(tag, T::class.java) /** * Returns the tag for type [T], or null if none was defined. */ inline fun <reified T> Json.getTag(): String? = getTag(T::class.java) /** * Sets the elements in a collection of type [T] to type [E]. * When the element type is known, the class for each element in the collection * does not need to be written unless different from the element type. */ inline fun <reified T, reified E> Json.setElementType(fieldName: String) = setElementType(T::class.java, fieldName, E::class.java) /** * Registers a [serializer] to use for type [T] instead of the default behavior of * serializing all of an object fields. */ inline fun <reified T> Json.setSerializer(serializer: Json.Serializer<T>) = setSerializer(T::class.java, serializer) /** * Read a value of type [T] from a [jsonData] attribute with a [name]. * If [name] is `null`, this will directly read [jsonData] as an object of type [T]. */ inline fun <reified T> Json.readValue(jsonData: JsonValue, name: String? = null): T = readValue(T::class.java, if (name == null) jsonData else jsonData.get(name)) /** * Read an iterable value of type [T] with elements of type [E] from a [jsonData] attribute with a [name]. * If [name] is `null`, this will directly read [jsonData] as an iterable of type [T]. */ inline fun <reified T : Iterable<E>, reified E> Json.readArrayValue(jsonData: JsonValue, name: String? = null): T = readValue(T::class.java, E::class.java, if (name == null) jsonData else jsonData.get(name))
cc0-1.0
ae903b529e2dbee8e3cdf161c5540cff
38.462963
116
0.703426
3.442649
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/shop_type/ShopTypeForm.kt
1
3752
package de.westnordost.streetcomplete.quests.shop_type import android.os.Bundle import android.view.View import android.widget.RadioButton import androidx.core.os.ConfigurationCompat import de.westnordost.osmapi.map.data.OsmNode import de.westnordost.osmfeatures.Feature import de.westnordost.osmfeatures.StringUtils import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.ktx.geometryType import de.westnordost.streetcomplete.ktx.isSomeKindOfShop import de.westnordost.streetcomplete.ktx.toTypedArray import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment import de.westnordost.streetcomplete.util.TextChangedWatcher import kotlinx.android.synthetic.main.view_shop_type.* class ShopTypeForm : AbstractQuestFormAnswerFragment<ShopTypeAnswer>() { override val contentLayoutResId = R.layout.view_shop_type private lateinit var radioButtons: List<RadioButton> private var selectedRadioButtonId: Int = 0 private val shopTypeText get() = presetsEditText.text?.toString().orEmpty().trim() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) radioButtons = listOf(vacantRadioButton, replaceRadioButton, leaveNoteRadioButton) for (radioButton in radioButtons) { radioButton.setOnClickListener { selectRadioButton(it) } } presetsEditText.setAdapter(SearchAdapter(requireContext(), { term -> getFeatures(term) }, { it.name })) presetsEditText.setOnClickListener { selectRadioButton(replaceRadioButton) } presetsEditText.setOnFocusChangeListener { v, hasFocus -> if (hasFocus) selectRadioButton(replaceRadioButton) } presetsEditText.addTextChangedListener(TextChangedWatcher { checkIsFormComplete() }) } override fun onClickOk() { when(selectedRadioButtonId) { R.id.vacantRadioButton -> applyAnswer(IsShopVacant) R.id.leaveNoteRadioButton -> composeNote() R.id.replaceRadioButton -> { val feature = getSelectedFeature() if (feature == null) { presetsEditText.error = context?.resources?.getText(R.string.quest_shop_gone_replaced_answer_error) } else { applyAnswer(ShopType(feature.addTags)) } } } } override fun isFormComplete() = when(selectedRadioButtonId) { R.id.vacantRadioButton -> true R.id.leaveNoteRadioButton -> true R.id.replaceRadioButton -> shopTypeText.isNotEmpty() else -> false } private fun selectRadioButton(radioButton : View) { selectedRadioButtonId = radioButton.id for (b in radioButtons) { b.isChecked = selectedRadioButtonId == b.id } checkIsFormComplete() } private fun getSelectedFeature(): Feature? { val input = presetsEditText.text.toString().trim() return getFeatures(input).firstOrNull()?.takeIf { it.canonicalName == StringUtils.canonicalize(input) } } private fun getFeatures(startsWith: String) : List<Feature> { val context = context ?: return emptyList() val localeList = ConfigurationCompat.getLocales(context.resources.configuration) return featureDictionary .byTerm(startsWith) .forGeometry(osmElement!!.geometryType) .inCountry(countryInfo.countryCode) .forLocale(*localeList.toTypedArray()) .find() .filter { feature -> val fakeElement = OsmNode(-1L, 0, 0.0, 0.0, feature.tags) fakeElement.isSomeKindOfShop() } } }
gpl-3.0
cdf96eb32dc806dae485ee65f170961a
40.230769
119
0.683635
4.949868
false
false
false
false
trife/Field-Book
app/src/main/java/com/fieldbook/tracker/database/dao/ObservationVariableAttributeDao.kt
1
1258
package com.fieldbook.tracker.database.dao import com.fieldbook.tracker.database.* import com.fieldbook.tracker.database.Migrator.ObservationVariableAttribute class ObservationVariableAttributeDao { companion object { fun getAttributeNameById(id: Int) = withDatabase { db -> db.query(ObservationVariableAttribute.tableName, where = "${ObservationVariableAttribute.PK} = ?", whereArgs = arrayOf("$id")).toFirst()["observation_variable_attribute_name"] } fun getAttributeIdByName(name: String): Int = withDatabase { db -> db.query(ObservationVariableAttribute.tableName, where = "observation_variable_attribute_name LIKE ?", whereArgs = arrayOf(name)).toFirst()[ObservationVariableAttribute.PK] as Int } ?: -1 // fun getAll() = withDatabase { it.query(ObservationVariableAttribute.tableName).toTable() } fun getAllNames() = withDatabase { db -> db.query(ObservationVariableAttribute.tableName, select = arrayOf("observation_variable_attribute_name")) .toTable() .map { it["observation_variable_attribute_name"].toString() } } } }
gpl-2.0
723c32b21b24583498b3e44f3fd1da97
34.971429
117
0.641494
5.134694
false
false
false
false
zlyne0/colonization
core/src/promitech/colonization/ai/Units.kt
1
1638
package promitech.colonization.ai import net.sf.freecol.common.model.Colony import net.sf.freecol.common.model.Map import net.sf.freecol.common.model.Tile import net.sf.freecol.common.model.Unit import net.sf.freecol.common.model.player.Player typealias UnitTypeId = String fun Player.findShipsTileLocations(map: Map): List<Tile> { val sourceTiles = mutableListOf<Tile>() for (unit in units) { if (unit.isNaval && unit.isCarrier && !unit.isDamaged) { if (unit.isAtTileLocation) { sourceTiles.add(unit.tile) } else if (unit.isAtEuropeLocation || unit.isAtHighSeasLocation) { sourceTiles.add(map.getSafeTile(entryLocation)) } else if (unit.isAtColonyLocation) { sourceTiles.add(unit.getLocationOrNull(Colony::class.java).tile) } } } return sourceTiles } fun Player.calculateNavyTotalCargo(shipUnitTypeIds: Set<UnitTypeId>): Int { var slots = 0 for (unit in units) { if (shipUnitTypeIds.contains(unit.unitType.id) && !unit.isDamaged) { slots += unit.unitType.getSpace() } } return slots } fun Player.findCarrier(): Unit? { for (u in units) { if (u.isNaval && u.isCarrier && !u.isDamaged) { return u } } return null } class Units { companion object { @JvmField // more free cargo first val FREE_CARGO_SPACE_COMPARATOR = java.util.Comparator<Unit> { o1, o2 -> if (o2.hasMoreFreeCargoSpace(o1)) { 1 } else { -1 } } } }
gpl-2.0
70908c4a1c3fac0e6f37c9871a879237
27.258621
80
0.602564
3.765517
false
false
false
false
apollostack/apollo-android
apollo-http-cache/src/main/kotlin/com/apollographql/apollo3/cache/http/DiskLruHttpCacheStore.kt
1
3088
package com.apollographql.apollo3.cache.http import com.apollographql.apollo3.api.cache.http.HttpCacheRecord import com.apollographql.apollo3.api.cache.http.HttpCacheRecordEditor import com.apollographql.apollo3.api.cache.http.HttpCacheStore import com.apollographql.apollo3.cache.http.internal.DiskLruCache import com.apollographql.apollo3.cache.http.internal.FileSystem import okio.Sink import okio.Source import java.io.File import java.io.IOException import java.util.concurrent.locks.ReadWriteLock import java.util.concurrent.locks.ReentrantReadWriteLock class DiskLruHttpCacheStore(private val fileSystem: FileSystem, private val directory: File, private val maxSize: Long) : HttpCacheStore { private var cache: DiskLruCache private val cacheLock: ReadWriteLock = ReentrantReadWriteLock() constructor(directory: File, maxSize: Long) : this(FileSystem.Companion.SYSTEM, directory, maxSize) {} @Throws(IOException::class) override fun cacheRecord(cacheKey: String): HttpCacheRecord? { val snapshot: DiskLruCache.Snapshot? cacheLock.readLock().lock() snapshot = try { cache[cacheKey] } finally { cacheLock.readLock().unlock() } return if (snapshot == null) { null } else object : HttpCacheRecord { override fun headerSource(): Source { return snapshot.getSource(ENTRY_HEADERS) } override fun bodySource(): Source { return snapshot.getSource(ENTRY_BODY) } override fun close() { snapshot.close() } } } @Throws(IOException::class) override fun cacheRecordEditor(cacheKey: String): HttpCacheRecordEditor? { val editor: DiskLruCache.Editor? cacheLock.readLock().lock() editor = try { cache.edit(cacheKey) } finally { cacheLock.readLock().unlock() } return if (editor == null) { null } else object : HttpCacheRecordEditor { override fun headerSink(): Sink { return editor.newSink(ENTRY_HEADERS) } override fun bodySink(): Sink { return editor.newSink(ENTRY_BODY) } @Throws(IOException::class) override fun abort() { editor.abort() } @Throws(IOException::class) override fun commit() { editor.commit() } } } @Throws(IOException::class) override fun delete() { cacheLock.writeLock().lock() cache = try { cache.delete() createDiskLruCache() } finally { cacheLock.writeLock().unlock() } } @Throws(IOException::class) override fun remove(cacheKey: String) { cacheLock.readLock().lock() try { cache.remove(cacheKey) } finally { cacheLock.readLock().unlock() } } private fun createDiskLruCache(): DiskLruCache { return DiskLruCache.Companion.create(fileSystem, directory, VERSION, ENTRY_COUNT, maxSize) } companion object { private const val VERSION = 99991 private const val ENTRY_HEADERS = 0 private const val ENTRY_BODY = 1 private const val ENTRY_COUNT = 2 } init { cache = createDiskLruCache() } }
mit
af78ec16b06e2cf2e5b37b88d27c3b1b
26.096491
138
0.683614
4.318881
false
false
false
false
saletrak/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/utils/textview/HtmlUtils.kt
1
1045
package io.github.feelfreelinux.wykopmobilny.utils.textview import android.os.Build import android.text.Html import android.text.Spannable import android.text.SpannableStringBuilder import android.text.style.URLSpan import android.view.View import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.WykopLinkHandlerApi fun String.toSpannable(): Spannable { @Suppress("DEPRECATION") (return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) Html.fromHtml(this, Html.FROM_HTML_MODE_COMPACT, null, SpoilerTagHandler()) as Spannable else Html.fromHtml(this, null, SpoilerTagHandler()) as Spannable ) } fun SpannableStringBuilder.makeLinkClickable(span: URLSpan, handler : WykopLinkHandlerApi) { val start = getSpanStart(span) val end = getSpanEnd(span) val flags = getSpanFlags(span) val clickable = object : LinkSpan() { override fun onClick(tv: View) { handler.handleUrl(span.url) } } setSpan(clickable, start, end, flags) removeSpan(span) }
mit
64071a5e89050464d0e91fe301b9730b
32.709677
96
0.733014
3.973384
false
false
false
false
sjnyag/stamp
app/src/main/java/com/sjn/stamp/utils/AudioFocusHelper.kt
1
5005
package com.sjn.stamp.utils import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.media.AudioManager object AudioFocusHelper { private val TAG = LogHelper.makeLogTag(AudioFocusHelper::class.java) // we don't have audio focus, and can't duck (play at a low volume) const val AUDIO_NO_FOCUS_NO_DUCK = 0 // we don't have focus, but can duck (play at a low volume) const val AUDIO_NO_FOCUS_CAN_DUCK = 1 // we have full audio focus const val AUDIO_FOCUSED = 2 class AudioFocusManager(private val context: Context, private val listener: Listener) : AudioManager.OnAudioFocusChangeListener { interface Listener { fun onHeadphonesDisconnected() fun onAudioFocusChange() fun isMediaPlayerPlaying(): Boolean } var playOnFocusGain: Boolean = false // Type of audio focus we have: private var audioFocus = AUDIO_NO_FOCUS_NO_DUCK private var audioNoisyReceiverRegistered: Boolean = false private val audioManager: AudioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager private val audioNoisyIntentFilter = IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY) private val audioNoisyReceiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (AudioManager.ACTION_AUDIO_BECOMING_NOISY == intent.action) { LogHelper.d(TAG, "Headphones disconnected.") listener.onHeadphonesDisconnected() } } } fun start() { playOnFocusGain = true tryToGetAudioFocus() setUpReceiver() } fun setUpReceiver() { if (!audioNoisyReceiverRegistered) { context.registerReceiver(audioNoisyReceiver, audioNoisyIntentFilter) audioNoisyReceiverRegistered = true } } fun releaseReceiver() { // Give up Audio focus if (audioNoisyReceiverRegistered) { context.unregisterReceiver(audioNoisyReceiver) audioNoisyReceiverRegistered = false } } /** * Try to get the system audio focus. */ private fun tryToGetAudioFocus() { LogHelper.d(TAG, "tryToGetAudioFocus") val result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) audioFocus = if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) AUDIO_FOCUSED else AUDIO_NO_FOCUS_NO_DUCK } /** * Give up the audio focus. */ fun giveUpAudioFocus() { LogHelper.d(TAG, "giveUpAudioFocus") if (audioManager.abandonAudioFocus(this) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { audioFocus = AUDIO_NO_FOCUS_NO_DUCK } } fun hasFocus() = !noFocusNoDuck() fun noFocusCanDuck() = audioFocus == AudioFocusHelper.AUDIO_NO_FOCUS_CAN_DUCK private fun noFocusNoDuck() = audioFocus == AudioFocusHelper.AUDIO_NO_FOCUS_NO_DUCK /** * Called by AudioManager on audio focus changes. * Implementation of [android.media.AudioManager.OnAudioFocusChangeListener] */ override fun onAudioFocusChange(focusChange: Int) { LogHelper.d(TAG, "onAudioFocusChange. focusChange=", focusChange) if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { // We have gained focus: audioFocus = AUDIO_FOCUSED } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) { // We have lost focus. If we can duck (low playback volume), we can keep playing. // Otherwise, we need to pause the playback. val canDuck = focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK audioFocus = if (canDuck) AUDIO_NO_FOCUS_CAN_DUCK else AUDIO_NO_FOCUS_NO_DUCK // If we are playing, we need to reset media player by calling configMediaPlayerState // with audioFocus properly set. if (listener.isMediaPlayerPlaying() && !canDuck) { // If we don't have audio focus and can't duck, we create the information that // we were playing, so that we can resume playback once we get the focus back. playOnFocusGain = true } } else { LogHelper.e(TAG, "onAudioFocusChange: Ignoring unsupported focusChange: ", focusChange) } listener.onAudioFocusChange() } } }
apache-2.0
3a03d3d41eec0898cd485bcbe64d1126
41.786325
133
0.621978
4.99003
false
false
false
false
sjnyag/stamp
app/src/main/java/com/sjn/stamp/ui/fragment/media/MyStampListFragment.kt
1
6841
package com.sjn.stamp.ui.fragment.media import android.graphics.Color import android.os.Bundle import android.support.v7.widget.RecyclerView import android.support.v7.widget.helper.ItemTouchHelper import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import com.sjn.stamp.R import com.sjn.stamp.controller.StampController import com.sjn.stamp.ui.SongAdapter import com.sjn.stamp.ui.activity.DrawerActivity import com.sjn.stamp.ui.item.AbstractItem import com.sjn.stamp.ui.item.SongItem import com.sjn.stamp.utils.AlbumArtHelper import com.sjn.stamp.utils.LogHelper import com.sjn.stamp.utils.MediaIDHelper import com.sjn.stamp.utils.cancelSwipe import eu.davidea.fastscroller.FastScroller import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager import eu.davidea.flexibleadapter.helpers.UndoHelper class MyStampListFragment : SongListFragment(), UndoHelper.OnUndoListener, FlexibleAdapter.OnItemSwipeListener { private val categoryValue: String? get() = mediaId?.let { MediaIDHelper.extractBrowseCategoryValueFromMediaID(it) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { LogHelper.d(TAG, "onCreateView START" + mediaId!!) val rootView = inflater.inflate(R.layout.fragment_list, container, false) if (savedInstanceState != null) { listState = savedInstanceState.getParcelable(ListFragment.LIST_STATE_KEY) } loading = rootView.findViewById(R.id.progressBar) emptyView = rootView.findViewById(R.id.empty_view) fastScroller = rootView.findViewById(R.id.fast_scroller) emptyTextView = rootView.findViewById(R.id.empty_text) swipeRefreshLayout = rootView.findViewById(R.id.refresh) recyclerView = rootView.findViewById(R.id.recycler_view) swipeRefreshLayout?.apply { setOnRefreshListener(this@MyStampListFragment) setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW) } adapter = SongAdapter(currentItems, this).apply { setNotifyChangeOfUnfilteredItems(true) setAnimationOnScrolling(false) } recyclerView?.apply { activity?.let { this.layoutManager = SmoothScrollLinearLayoutManager(it).apply { listState?.let { onRestoreInstanceState(it) } } } this.adapter = [email protected] } adapter?.apply { fastScroller = rootView.findViewById<View>(R.id.fast_scroller) as FastScroller isLongPressDragEnabled = false isHandleDragEnabled = false isSwipeEnabled = true setUnlinkAllItemsOnRemoveHeaders(false) setDisplayHeadersAtStartUp(false) setStickyHeaders(false) showAllHeaders() } initializeFabWithStamp() if (isShowing) { notifyFragmentChange() } mediaId?.let { MediaIDHelper.extractBrowseCategoryValueFromMediaID(it)?.let { arguments?.also { if (activity is DrawerActivity) { (activity as DrawerActivity).run { animateAppbar(it.getString("IMAGE_TEXT")) { activity, imageView -> AlbumArtHelper.reload(activity, imageView, it.getString("IMAGE_TYPE"), it.getString("IMAGE_URL"), it.getString("IMAGE_TEXT")) } } } } } } draw() LogHelper.d(TAG, "onCreateView END") return rootView } override fun onItemSwipe(position: Int, direction: Int) { LogHelper.i(TAG, "onItemSwipe position=" + position + " direction=" + if (direction == ItemTouchHelper.LEFT) "LEFT" else "RIGHT") if (adapter?.getItem(position) !is SongItem) return val item = adapter?.getItem(position) as SongItem activity?.run { if (categoryValue?.let { StampController(this).isCategoryStamp(it, false, item.mediaId) } == true) { Toast.makeText(this, R.string.error_message_stamp_failed, Toast.LENGTH_LONG).show() recyclerView?.cancelSwipe(position) return } tryRemove(item, position) } } private fun tryRemove(item: AbstractItem<*>, position: Int) { val positions = mutableListOf(position) val message = StringBuilder().append(item.title).append(" ").append(getString(R.string.action_deleted)) if (item.isSelectable) adapter?.setRestoreSelectionOnUndo(false) adapter?.isPermanentDelete = false swipeRefreshLayout?.isRefreshing = true activity?.let { UndoHelper(adapter, this@MyStampListFragment) .withPayload(null) .withConsecutive(true) .start(positions, it.findViewById(R.id.main_view), message, getString(R.string.undo), UndoHelper.UNDO_TIMEOUT) } } override fun onActionStateChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) { LogHelper.i(TAG, "onActionStateChanged actionState=$actionState") swipeRefreshLayout?.isEnabled = actionState == ItemTouchHelper.ACTION_STATE_IDLE } override fun onActionCanceled(action: Int) { LogHelper.i(TAG, "onUndoConfirmed action=$action") adapter?.restoreDeletedItems() swipeRefreshLayout?.isRefreshing = false if (adapter?.isRestoreWithSelection == true) listener?.restoreSelection() } override fun onActionConfirmed(action: Int, event: Int) { LogHelper.i(TAG, "onDeleteConfirmed action=$action") swipeRefreshLayout?.isRefreshing = false for (adapterItem in adapter?.deletedItems ?: emptyList()) { try { when (adapterItem.layoutRes) { R.layout.recycler_song_item -> { val subItem = adapterItem as SongItem activity?.let { StampController(it).run { categoryValue?.let { removeSong(it, false, subItem.mediaId) } } LogHelper.i(TAG, "Confirm removed " + subItem.toString()) } } } } catch (e: IllegalStateException) { e.printStackTrace() } } } companion object { private val TAG = LogHelper.makeLogTag(MyStampListFragment::class.java) } }
apache-2.0
18507bfec9b2ee8e1ce686d654445e51
40.713415
157
0.629002
4.87598
false
false
false
false
LucasMW/Headache
src/bfide/main.kt
1
1017
internal fun readFromFile(path: String): String { val url: URL = URL(fileURLWithPath = path) val myString: String = String(contentsOf = url) return myString } fun main(args: Array<String>) { val args: List<String> = CommandLine.arguments if ((args.size >= 3)) { } else if ((args.size == 2)) { try { val program: String = readFromFile(path = args[1]) println(top-level) // let interpreter = BrainfuckInterpreter(cells: 30000) // interpreter.dbg_messages = false // interpreter.setProgram(program: program) // interpreter.inputRedirect = false // interpreter.outputRedirect = false // interpreter.execute() } catch (error: Exception) { println("Couldn't read file: ${args[1]}") exit(1) } exit(0) } else { println("Error!\nProgram usage is: \n${args[0]} sourcecode") exit(-1) } }
mit
971100f71b4beb4fc3c2240ee76869f5
28.057143
68
0.54179
4.100806
false
false
false
false
Hexworks/zircon
zircon.core/src/jvmTest/kotlin/org/hexworks/zircon/internal/component/renderer/decoration/BoxDecorationRendererTest.kt
1
4197
package org.hexworks.zircon.internal.component.renderer.decoration import org.assertj.core.api.Assertions.assertThat import org.hexworks.zircon.api.CP437TilesetResources import org.hexworks.zircon.api.ComponentDecorations.box import org.hexworks.zircon.api.Components import org.hexworks.zircon.api.DrawSurfaces import org.hexworks.zircon.api.component.renderer.ComponentDecorationRenderer import org.hexworks.zircon.api.component.renderer.ComponentDecorationRenderer.Alignment.* import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.convertCharacterTilesToString import org.hexworks.zircon.internal.graphics.Renderable import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) class BoxDecorationRendererTest( @Suppress("unused") private val testTitle: String, // used by Parameterized for display in IntelliJ/terminal private val decorator: ComponentDecorationRenderer, private val expected: String ) { @Test fun renderTest() { val target = Components.panel() .withTileset(CP437TilesetResources.rexPaint20x20()) .withDecorations(decorator) .build() val graphics = DrawSurfaces.tileGraphicsBuilder().withSize(Size.create(12, 4)).build() (target as Renderable).render(graphics) assertThat(graphics.convertCharacterTilesToString()).isEqualTo(expected.trimIndent()) } companion object { @Parameterized.Parameters(name = "{index}: {0}") @JvmStatic fun data() = listOf( arrayOf( "Default parameters", box(), """ ┌──────────┐ │ │ │ │ └──────────┘ """ ), arrayOf( "With title", box(title = "Foo"), """ ┌┤Foo├─────┐ │ │ │ │ └──────────┘ """ ), arrayOf( "With title, right-aligned", box(title = "Foo", titleAlignment = TOP_RIGHT), """ ┌─────┤Foo├┐ │ │ │ │ └──────────┘ """ ), // Titlebar is even-sized width, but title is odd-sized, so we're off by half, rounding to the left. arrayOf( "With title, center-aligned, approx center", box(title = "Foo", titleAlignment = TOP_CENTER), """ ┌──┤Foo├───┐ │ │ │ │ └──────────┘ """ ), arrayOf( "With title, center-aligned, exact center", box(title = "Food", titleAlignment = TOP_CENTER), """ ┌──┤Food├──┐ │ │ │ │ └──────────┘ """ ), arrayOf( "With title, bottom left-aligned", box(title = "Foo", titleAlignment = BOTTOM_LEFT), """ ┌──────────┐ │ │ │ │ └┤Foo├─────┘ """ ), arrayOf( "With title, bottom right-aligned", box(title = "Foo", titleAlignment = BOTTOM_RIGHT), """ ┌──────────┐ │ │ │ │ └─────┤Foo├┘ """ ), arrayOf( "With title, bottom center-aligned", box(title = "Foo", titleAlignment = BOTTOM_CENTER), """ ┌──────────┐ │ │ │ │ └──┤Foo├───┘ """ ) ) } }
apache-2.0
823fc9d90a01a1e7e5b7e2528d81b650
34.783019
113
0.468231
4.777078
false
false
false
false
google/identity-credential
appholder/src/main/java/com/android/mdl/app/theme/Type.kt
1
533
package com.android.mdl.app.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp val Typography = Typography( bodyLarge = TextStyle( fontWeight = FontWeight.Bold, fontSize = 36.sp ), bodyMedium = TextStyle( fontWeight = FontWeight.Normal, fontSize = 16.sp, ), bodySmall = TextStyle( fontWeight = FontWeight.Normal, fontSize = 14.sp, ) )
apache-2.0
0615582f4f64bf614786e0ca8e2fbdb7
24.428571
47
0.682927
4.1
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/workers/weeklyroundup/WeeklyRoundupUtils.kt
1
1062
package org.wordpress.android.workers.weeklyroundup import org.wordpress.android.util.AppLog import org.wordpress.android.util.AppLog.T import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.Locale object WeeklyRoundupUtils { private const val STANDARD_DATE_PATTERN = "yyyy-MM-dd" private const val WEEK_PERIOD_DATE_PATTERN = "yyyy'W'MM'W'dd" private val standardFormatter = DateTimeFormatter.ofPattern(STANDARD_DATE_PATTERN, Locale.ROOT) private val weekPeriodFormatter = DateTimeFormatter.ofPattern(WEEK_PERIOD_DATE_PATTERN, Locale.ROOT) fun parseStandardDate(date: String): LocalDate? = safelyParseDate(date, standardFormatter) fun parseWeekPeriodDate(date: String): LocalDate? = safelyParseDate(date, weekPeriodFormatter) private fun safelyParseDate( date: String, formatter: DateTimeFormatter ) = runCatching { LocalDate.parse(date, formatter) } .onFailure { AppLog.e(T.NOTIFS, "Weekly Roundup – Couldn't parse date: $date", it) } .getOrNull() }
gpl-2.0
76530ca2cf8e5102cd3e0d8e670b201c
39.769231
104
0.751887
4.030418
false
false
false
false
Yusuzhan/kotlin-koans
src/i_introduction/_1_Java_To_Kotlin_Converter/JavaToKotlinConverter.kt
1
784
package i_introduction._1_Java_To_Kotlin_Converter import util.TODO fun todoTask1(collection: Collection<Int>): Nothing = TODO( """ Task 1. Rewrite JavaCode1.task1 in Kotlin. In IntelliJ IDEA, you can just copy-paste the code and agree to automatically convert it to Kotlin, but only for this task! """, references = { JavaCode1().task1(collection) }) fun task1(collection: Collection<Int>): String { val sb: StringBuilder = StringBuilder() sb.append("{") val it: Iterator<Int> = collection.iterator() while (it.hasNext()) { val e: Int = it.next() sb.append(e) if (it.hasNext()) { sb.append(", ") } } sb.append("}") println(sb) return sb.toString() }
mit
c2c53a34a9935f05e4aefddd8c8bee0b
25.133333
107
0.594388
3.959596
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/expressionExt.kt
1
3467
// 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.util import com.intellij.lang.jvm.JvmModifier import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiMember import com.intellij.psi.PsiMethod import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.idea.base.psi.textRangeIn as _textRangeIn fun KtCallElement.replaceOrCreateTypeArgumentList(newTypeArgumentList: KtTypeArgumentList) { if (typeArgumentList != null) typeArgumentList?.replace(newTypeArgumentList) else addAfter( newTypeArgumentList, calleeExpression, ) } fun KtModifierListOwner.hasInlineModifier() = hasModifier(KtTokens.INLINE_KEYWORD) fun KtModifierListOwner.hasPrivateModifier() = hasModifier(KtTokens.PRIVATE_KEYWORD) fun KtPrimaryConstructor.mustHaveValOrVar(): Boolean = containingClass()?.let { it.isAnnotation() || it.hasInlineModifier() } ?: false // TODO: add cases fun KtExpression.hasNoSideEffects(): Boolean = when (this) { is KtStringTemplateExpression -> !hasInterpolation() is KtConstantExpression -> true else -> ConstantExpressionEvaluator.getConstant(this, analyze(BodyResolveMode.PARTIAL)) != null } @Deprecated("Please use org.jetbrains.kotlin.idea.base.psi.textRangeIn") fun PsiElement.textRangeIn(other: PsiElement): TextRange = _textRangeIn(other) fun KtDotQualifiedExpression.calleeTextRangeInThis(): TextRange? = callExpression?.calleeExpression?.textRangeIn(this) fun KtNamedDeclaration.nameIdentifierTextRangeInThis(): TextRange? = nameIdentifier?.textRangeIn(this) fun PsiElement.hasComments(): Boolean = anyDescendantOfType<PsiComment>() fun KtDotQualifiedExpression.hasNotReceiver(): Boolean { val element = getQualifiedElementSelector()?.mainReference?.resolve() ?: return false return element is KtClassOrObject || element is KtConstructor<*> || element is KtCallableDeclaration && element.receiverTypeReference == null && (element.containingClassOrObject is KtObjectDeclaration?) || element is PsiMember && element.hasModifier(JvmModifier.STATIC) || element is PsiMethod && element.isConstructor } val KtExpression.isUnitLiteral: Boolean get() = StandardNames.FqNames.unit.shortName() == (this as? KtNameReferenceExpression)?.getReferencedNameAsName() val PsiElement.isAnonymousFunction: Boolean get() = this is KtNamedFunction && isAnonymousFunction val KtNamedFunction.isAnonymousFunction: Boolean get() = nameIdentifier == null val DeclarationDescriptor.isPrimaryConstructorOfDataClass: Boolean get() = this is ConstructorDescriptor && this.isPrimary && this.constructedClass.isData
apache-2.0
385fb32cd117d12cd452aa7637ca3519
45.851351
158
0.801269
5.046579
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/TypeOfAnnotationMemberFix.kt
1
3123
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.CleanupFix import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtTypeReference import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType class TypeOfAnnotationMemberFix( typeReference: KtTypeReference, private val fixedType: String ) : KotlinQuickFixAction<KtTypeReference>(typeReference), CleanupFix { override fun getText(): String = KotlinBundle.message("replace.array.of.boxed.with.array.of.primitive") override fun getFamilyName(): String = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val psiElement = element ?: return psiElement.replace(KtPsiFactory(psiElement).createType(fixedType)) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val typeReference = diagnostic.psiElement as? KtTypeReference ?: return null val type = typeReference.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, typeReference] ?: return null val itemType = type.getArrayItemType() ?: return null val itemTypeName = itemType.constructor.declarationDescriptor?.name?.asString() ?: return null val fixedArrayTypeText = if (itemType.isItemTypeToFix()) { "${itemTypeName}Array" } else { return null } return TypeOfAnnotationMemberFix(typeReference, fixedArrayTypeText) } private fun KotlinType.getArrayItemType(): KotlinType? { if (!KotlinBuiltIns.isArray(this)) { return null } val boxedType = arguments.singleOrNull() ?: return null if (boxedType.isStarProjection) { return null } return boxedType.type } private fun KotlinType.isItemTypeToFix() = KotlinBuiltIns.isByte(this) || KotlinBuiltIns.isChar(this) || KotlinBuiltIns.isShort(this) || KotlinBuiltIns.isInt(this) || KotlinBuiltIns.isLong(this) || KotlinBuiltIns.isFloat(this) || KotlinBuiltIns.isDouble(this) || KotlinBuiltIns.isBoolean(this) } }
apache-2.0
1ee74fc61ae87393c24af9134b93d5f2
42.388889
158
0.704451
5.078049
false
false
false
false
mdaniel/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/diff/CombinedDiffPreview.kt
1
7697
// 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.changes.actions.diff import com.intellij.diff.chains.DiffRequestProducer import com.intellij.diff.tools.combined.* import com.intellij.openapi.Disposable import com.intellij.openapi.ListSelection import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.changes.ChangeViewDiffRequestProcessor.Wrapper import com.intellij.openapi.vcs.changes.DiffPreviewUpdateProcessor import com.intellij.openapi.vcs.changes.DiffRequestProcessorWithProducers import com.intellij.openapi.vcs.changes.EditorTabPreviewBase import com.intellij.openapi.vcs.changes.actions.diff.CombinedDiffPreviewModel.Companion.prepareCombinedDiffModelRequests import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase import com.intellij.openapi.vcs.changes.ui.ChangesTree import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.ExpandableItemsHandler import com.intellij.util.ui.UIUtil import com.intellij.vcsUtil.Delegates import org.jetbrains.annotations.NonNls import javax.swing.JComponent import javax.swing.JTree.TREE_MODEL_PROPERTY @JvmField internal val COMBINED_DIFF_PREVIEW_TAB_NAME = Key.create<() -> @NlsContexts.TabTitle String>("combined_diff_preview_tab_name") class CombinedDiffPreviewVirtualFile(sourceId: String) : CombinedDiffVirtualFile(sourceId, "") abstract class CombinedDiffPreview(protected val tree: ChangesTree, targetComponent: JComponent, isOpenEditorDiffPreviewWithSingleClick: Boolean, needSetupOpenPreviewListeners: Boolean, parentDisposable: Disposable) : EditorTabPreviewBase(tree.project, parentDisposable) { constructor(tree: ChangesTree, parentDisposable: Disposable) : this(tree, tree, false, false, parentDisposable) override val previewFile: VirtualFile by lazy { CombinedDiffPreviewVirtualFile(tree.id) } override val updatePreviewProcessor get() = model protected val model by lazy { createModel().also { model -> model.context.putUserData(COMBINED_DIFF_PREVIEW_TAB_NAME, ::getCombinedDiffTabTitle) project.service<CombinedDiffModelRepository>().registerModel(tree.id, model) } } override fun updatePreview(fromModelRefresh: Boolean) { super.updatePreview(fromModelRefresh) if (isPreviewOpen()) { FileEditorManagerEx.getInstanceEx(project).updateFilePresentation(previewFile) } } init { escapeHandler = Runnable { closePreview() returnFocusToTree() } if (needSetupOpenPreviewListeners) { installListeners(tree, isOpenEditorDiffPreviewWithSingleClick) installNextDiffActionOn(targetComponent) } UIUtil.putClientProperty(tree, ExpandableItemsHandler.IGNORE_ITEM_SELECTION, true) installCombinedDiffModelListener() } private fun installCombinedDiffModelListener() { tree.addPropertyChangeListener(TREE_MODEL_PROPERTY) { if (model.ourDisposable.isDisposed) return@addPropertyChangeListener val changes = model.iterateSelectedOrAllChanges().toList() if (changes.isNotEmpty()) { model.refresh(true) model.reset(prepareCombinedDiffModelRequests(project, changes)) } } } open fun returnFocusToTree() = Unit override fun isPreviewOnDoubleClickAllowed(): Boolean = isCombinedPreviewAllowed() && super.isPreviewOnDoubleClickAllowed() override fun isPreviewOnEnterAllowed(): Boolean = isCombinedPreviewAllowed() && super.isPreviewOnEnterAllowed() protected abstract fun createModel(): CombinedDiffPreviewModel protected abstract fun getCombinedDiffTabTitle(): String override fun updateDiffAction(event: AnActionEvent) { event.presentation.isVisible = event.isFromActionToolbar || event.presentation.isEnabled } override fun getCurrentName(): String? = model.selected?.presentableName override fun hasContent(): Boolean = model.requests.isNotEmpty() internal fun getFileSize(): Int = model.requests.size protected val ChangesTree.id: @NonNls String get() = javaClass.name + "@" + Integer.toHexString(hashCode()) private fun isCombinedPreviewAllowed() = Registry.`is`("enable.combined.diff") } abstract class CombinedDiffPreviewModel(protected val tree: ChangesTree, requests: Map<CombinedBlockId, DiffRequestProducer>, parentDisposable: Disposable) : CombinedDiffModelImpl(tree.project, requests, parentDisposable), DiffPreviewUpdateProcessor, DiffRequestProcessorWithProducers { var selected by Delegates.equalVetoingObservable<Wrapper?>(null) { change -> if (change != null) { selectChangeInTree(change) scrollToChange(change) } } companion object { @JvmStatic fun prepareCombinedDiffModelRequests(project: Project, changes: List<Wrapper>): Map<CombinedBlockId, DiffRequestProducer> { return changes .asSequence() .mapNotNull { wrapper -> wrapper.createProducer(project) ?.let { CombinedPathBlockId(wrapper.filePath, wrapper.fileStatus, wrapper.tag) to it } }.toMap() } } override fun collectDiffProducers(selectedOnly: Boolean): ListSelection<DiffRequestProducer> { return ListSelection.create(requests.values.toList(), selected?.createProducer(project)) } abstract fun iterateAllChanges(): Iterable<Wrapper> protected abstract fun iterateSelectedChanges(): Iterable<Wrapper> protected open fun showAllChangesForEmptySelection(): Boolean { return true } override fun clear() { init() } override fun refresh(fromModelRefresh: Boolean) { if (ourDisposable.isDisposed) return val selectedChanges = iterateSelectedOrAllChanges().toList() val selectedChange = selected?.let { prevSelected -> selectedChanges.find { it == prevSelected } } if (fromModelRefresh && selectedChange == null && selected != null && context.isWindowFocused && context.isFocusedInWindow) { // Do not automatically switch focused viewer if (selectedChanges.size == 1 && iterateAllChanges().any { it: Wrapper -> selected == it }) { selected?.run(::selectChangeInTree) // Restore selection if necessary } return } val newSelected = when { selectedChanges.isEmpty() -> null selectedChange == null -> selectedChanges[0] else -> selectedChange } newSelected?.let { context.putUserData(COMBINED_DIFF_SCROLL_TO_BLOCK, CombinedPathBlockId(it.filePath, it.fileStatus, it.tag)) } selected = newSelected } internal fun iterateSelectedOrAllChanges(): Iterable<Wrapper> { return if (iterateSelectedChanges().none() && showAllChangesForEmptySelection()) iterateAllChanges() else iterateSelectedChanges() } private fun scrollToChange(change: Wrapper) { context.getUserData(COMBINED_DIFF_VIEWER_KEY) ?.selectDiffBlock(CombinedPathBlockId(change.filePath, change.fileStatus, change.tag), ScrollPolicy.DIFF_BLOCK, false) } open fun selectChangeInTree(change: Wrapper) { ChangesBrowserBase.selectObjectWithTag(tree, change.userObject, change.tag) } override fun getComponent(): JComponent = throw UnsupportedOperationException() //only for splitter preview }
apache-2.0
46e7e1b75b47614c6efb4dcf6478a475
38.880829
134
0.747954
4.801622
false
false
false
false
Major-/Vicis
util/src/main/kotlin/rs/emulate/util/crypto/rsa/Rsa.kt
1
2096
package rs.emulate.util.crypto.rsa import io.netty.buffer.ByteBuf import io.netty.buffer.Unpooled import org.bouncycastle.crypto.params.RSAKeyParameters import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters import org.bouncycastle.util.BigIntegers import java.math.BigInteger import java.security.SecureRandom private val random = SecureRandom() fun ByteBuf.rsaEncrypt(key: RSAKeyParameters): ByteBuf { val len = readableBytes() val input = ByteArray(len) readBytes(input) val ciphertext = BigInteger(input) val plaintext = ciphertext.modPow(key.exponent, key.modulus) val output = plaintext.toByteArray() return Unpooled.wrappedBuffer(output) } fun ByteBuf.rsaDecrypt(key: RSAKeyParameters): ByteBuf { require(key.isPrivate) val len = readableBytes() val input = ByteArray(len) readBytes(input) val ciphertext = BigInteger(input) val plaintext: BigInteger if (key is RSAPrivateCrtKeyParameters) { /* blind the input */ val e = key.publicExponent val m = key.modulus val r = BigIntegers.createRandomInRange(BigInteger.ONE, m.subtract(BigInteger.ONE), random ) val blindedCiphertext = r.modPow(e, m).multiply(ciphertext).mod(m) /* decrypt using the Chinese Remainder Theorem */ val p = key.p val q = key.q val dP = key.dp val dQ = key.dq val qInv = key.qInv val mP = blindedCiphertext.remainder(p).modPow(dP, p) val mQ = blindedCiphertext.remainder(q).modPow(dQ, q) val h = mP.subtract(mQ).multiply(qInv).mod(p) val blindedPlaintext = h.multiply(q).add(mQ) /* unblind the output */ val rInv = r.modInverse(m) plaintext = blindedPlaintext.multiply(rInv).mod(m) /* see https://people.redhat.com/~fweimer/rsa-crt-leaks.pdf */ check(ciphertext == plaintext.modPow(e, m)) } else { plaintext = ciphertext.modPow(key.exponent, key.modulus) } val out = plaintext.toByteArray() return Unpooled.wrappedBuffer(out) }
isc
84a0ba2e82ca442751767fb227c1901a
27.324324
91
0.675095
3.742857
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/quest/schedule/summary/usecase/CreateScheduleSummaryItemsUseCase.kt
1
4349
package io.ipoli.android.quest.schedule.summary.usecase import io.ipoli.android.common.UseCase import io.ipoli.android.common.datetime.Time import io.ipoli.android.common.datetime.datesBetween import io.ipoli.android.common.permission.PermissionChecker import io.ipoli.android.event.Event import io.ipoli.android.event.persistence.EventRepository import io.ipoli.android.player.data.Player import io.ipoli.android.player.persistence.PlayerRepository import io.ipoli.android.quest.Color import io.ipoli.android.quest.Quest import org.threeten.bp.LocalDate class CreateScheduleSummaryItemsUseCase( private val eventRepository: EventRepository, private val playerRepository: PlayerRepository, private val permissionChecker: PermissionChecker ) : UseCase<CreateScheduleSummaryItemsUseCase.Params, List<CreateScheduleSummaryItemsUseCase.Schedule>> { override fun execute(parameters: Params): List<Schedule> { val startDate = parameters.startDate val endDate = parameters.endDate val p = parameters.player ?: playerRepository.find()!! val quests = parameters.quests val eventsByDate = getEventsSortedByDate(p, startDate, endDate) val questsByDate = quests.groupBy { it.scheduledDate!! } return startDate.datesBetween(endDate).map { d -> val dailyQuests = questsByDate[d] ?: emptyList() val dailyEvents = eventsByDate[d] ?: emptyList() val qs = dailyQuests.map { Schedule.Item.Quest( name = it.name, color = it.color, isCompleted = it.isCompleted, startTime = it.startTime ) } val es = dailyEvents.map { Schedule.Item.Event(name = it.name, color = it.color, startTime = it.startTime) } val items = (qs + es).sortedBy { it.startTime?.toMinuteOfDay() } Schedule( date = d, items = items ) } } private fun getEventsSortedByDate( p: Player, startDate: LocalDate, endDate: LocalDate ): Map<LocalDate, List<Event>> { if (!permissionChecker.canReadCalendar()) { return emptyMap() } val calendarIds = p.preferences.syncCalendars.map { it.id.toInt() }.toSet() val allEvents = eventRepository.findScheduledBetween(calendarIds, startDate, endDate) .filter { !it.isAllDay } val (multiDayEvents, singleDayEvents) = allEvents.partition { it.startDate != it.endDate } val events = mutableListOf<Event>() multiDayEvents.forEach { events.add( it.copy( endDate = it.startDate, endTime = Time(Time.MINUTES_IN_A_DAY - 1) ) ) events.add( it.copy( startDate = it.endDate, startTime = Time.atHours(0) ) ) if (it.startDate.plusDays(1) != it.endDate) { it.startDate.plusDays(1).datesBetween(it.endDate.minusDays(1)).forEach { date -> events.add( it.copy( startDate = date, endDate = date, startTime = Time.atHours(0), endTime = Time.of(Time.MINUTES_IN_A_DAY - 1) ) ) } } } return (singleDayEvents + events).groupBy { it.startDate } } data class Schedule( val date: LocalDate, val items: List<Item> ) { sealed class Item { abstract val startTime: Time? data class Quest( val name: String, val color: Color, val isCompleted: Boolean, override val startTime: Time? ) : Item() data class Event(val name: String, val color: Int, override val startTime: Time?) : Item() } } data class Params( val quests: List<Quest>, val startDate: LocalDate, val endDate: LocalDate, val player: Player? = null ) }
gpl-3.0
0d0994d6c0250b7f87e5b3354489a53a
30.985294
105
0.560589
4.848384
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/actions/RunScratchAction.kt
4
4117
// 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.scratch.actions import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.project.DumbService import com.intellij.task.ProjectTaskManager import org.jetbrains.kotlin.idea.KotlinJvmBundle import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.core.script.configuration.CompositeScriptConfigurationManager import org.jetbrains.kotlin.idea.scratch.ScratchFile import org.jetbrains.kotlin.idea.scratch.SequentialScratchExecutor import org.jetbrains.kotlin.idea.scratch.printDebugMessage import org.jetbrains.kotlin.utils.addToStdlib.cast import org.jetbrains.kotlin.idea.scratch.LOG as log class RunScratchAction : ScratchAction( KotlinJvmBundle.message("scratch.run.button"), AllIcons.Actions.Execute ) { init { KeymapManager.getInstance().activeKeymap.getShortcuts("Kotlin.RunScratch").firstOrNull()?.let { templatePresentation.text += " (${KeymapUtil.getShortcutText(it)})" } } override fun actionPerformed(e: AnActionEvent) { val scratchFile = e.currentScratchFile ?: return doAction(scratchFile, false) } companion object { fun doAction(scratchFile: ScratchFile, isAutoRun: Boolean) { val project = scratchFile.project val isRepl = scratchFile.options.isRepl val executor = (if (isRepl) scratchFile.replScratchExecutor else scratchFile.compilingScratchExecutor) ?: return log.printDebugMessage("Run Action: isRepl = $isRepl") fun executeScratch() { try { if (isAutoRun && executor is SequentialScratchExecutor) { executor.executeNew() } else { executor.execute() } } catch (ex: Throwable) { executor.errorOccurs(KotlinJvmBundle.message("exception.occurs.during.run.scratch.action"), ex, true) } } val isMakeBeforeRun = scratchFile.options.isMakeBeforeRun log.printDebugMessage("Run Action: isMakeBeforeRun = $isMakeBeforeRun") ScriptConfigurationManager.getInstance(project).cast<CompositeScriptConfigurationManager>() .updateScriptDependenciesIfNeeded(scratchFile.file) val module = scratchFile.module log.printDebugMessage("Run Action: module = ${module?.name}") if (!isAutoRun && module != null && isMakeBeforeRun) { ProjectTaskManager.getInstance(project).build(module).onSuccess { executionResult -> if (executionResult.isAborted || executionResult.hasErrors()) { executor.errorOccurs(KotlinJvmBundle.message("there.were.compilation.errors.in.module.0", module.name)) } if (DumbService.isDumb(project)) { DumbService.getInstance(project).smartInvokeLater { executeScratch() } } else { executeScratch() } } } else { executeScratch() } } } override fun update(e: AnActionEvent) { super.update(e) e.presentation.isEnabled = !ScratchCompilationSupport.isAnyInProgress() if (e.presentation.isEnabled) { e.presentation.text = templatePresentation.text } else { e.presentation.text = KotlinJvmBundle.message("other.scratch.file.execution.is.in.progress") } val scratchFile = e.currentScratchFile ?: return e.presentation.isVisible = !ScratchCompilationSupport.isInProgress(scratchFile) } }
apache-2.0
4bcc63365fae28fb7050d4569e794dff
39.772277
158
0.649502
5.251276
false
false
false
false
GunoH/intellij-community
plugins/full-line/src/org/jetbrains/completion/full/line/platform/diagnostics/log.kt
1
2593
package org.jetbrains.completion.full.line.platform.diagnostics import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.util.EventDispatcher import java.util.* private val LOG = logger<DiagnosticsService>() interface FullLineLogger { fun error(throwable: Throwable) fun debug(text: String) fun debug(text: String, throwable: Throwable) fun info(text: String) fun warn(text: String, throwable: Throwable) val isDebugEnabled: Boolean } @Service class DiagnosticsService { private val dispatcher = EventDispatcher.create(DiagnosticsListener::class.java) fun subscribe(listener: DiagnosticsListener, parentDisposable: Disposable) { dispatcher.addListener(listener, parentDisposable) } fun logger(part: FullLinePart, log: Logger = LOG): FullLineLogger { return object : FullLineLogger { override fun error(throwable: Throwable) = warn("Error happened", throwable) override fun debug(text: String) = onMessage(text) { debug(text) } override fun info(text: String) = onMessage(text) { info(text) } override fun debug(text: String, throwable: Throwable) = onMessage(text) { debug(text, throwable) } override fun warn(text: String, throwable: Throwable) = onMessage(text) { warn(text, throwable) } private fun onMessage(text: String, block: Logger.() -> Unit) { log.block() notifyListeners(text) } private fun notifyListeners(text: String) { if (!dispatcher.hasListeners()) return val message = DiagnosticsListener.Message(text, System.currentTimeMillis(), part) dispatcher.multicaster.messageReceived(message) } override val isDebugEnabled: Boolean = log.isDebugEnabled || dispatcher.hasListeners() } } companion object { fun getInstance(): DiagnosticsService { return service() } } } inline fun <reified T : Any> logger(part: FullLinePart): FullLineLogger = DiagnosticsService.getInstance().logger(part, logger<T>()) interface DiagnosticsListener : EventListener { fun messageReceived(message: Message) data class Message(val text: String, val time: Long, val part: FullLinePart) } enum class FullLinePart { BEAM_SEARCH, // beam search of local models NETWORK, // answers and delays for network PRE_PROCESSING, // preprocessing of FL proposals before showing POST_PROCESSING, // preprocessing of FL proposals after showing }
apache-2.0
c379d1a7af930ed07540a168a487caef
31.012346
132
0.735827
4.424915
false
false
false
false
GunoH/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/timeline/GHPRTimelineItemComponentFactory.kt
1
12959
// 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.github.pullrequest.ui.timeline import com.intellij.collaboration.async.CompletableFutureUtil.successOnEdt import com.intellij.collaboration.ui.codereview.timeline.TimelineItemComponentFactory import com.intellij.icons.AllIcons import com.intellij.ide.BrowserUtil import com.intellij.ide.plugins.newui.HorizontalLayout import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.project.Project import com.intellij.ui.components.ActionLink import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.components.labels.LinkListener import com.intellij.ui.components.panels.HorizontalBox import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.components.panels.VerticalLayout import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import org.intellij.lang.annotations.Language import org.jetbrains.plugins.github.GithubIcons import org.jetbrains.plugins.github.api.data.GHActor import org.jetbrains.plugins.github.api.data.GHGitActor import org.jetbrains.plugins.github.api.data.GHIssueComment import org.jetbrains.plugins.github.api.data.GHUser import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequest import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestCommitShort import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReview import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReviewState.* import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineEvent import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineItem import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.comment.convertToHtml import org.jetbrains.plugins.github.pullrequest.comment.ui.GHPRReviewThreadComponent import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRCommentsDataProvider import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRDetailsDataProvider import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRReviewDataProvider import org.jetbrains.plugins.github.pullrequest.ui.GHEditableHtmlPaneHandle import org.jetbrains.plugins.github.pullrequest.ui.GHTextActions import org.jetbrains.plugins.github.pullrequest.ui.changes.GHPRSuggestedChangeHelper import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider import org.jetbrains.plugins.github.ui.util.GHUIUtil import org.jetbrains.plugins.github.ui.util.HtmlEditorPane import java.awt.Dimension import java.util.* import javax.swing.* import kotlin.math.ceil import kotlin.math.floor class GHPRTimelineItemComponentFactory(private val project: Project, private val detailsDataProvider: GHPRDetailsDataProvider, private val commentsDataProvider: GHPRCommentsDataProvider, private val reviewDataProvider: GHPRReviewDataProvider, private val avatarIconsProvider: GHAvatarIconsProvider, private val reviewsThreadsModelsProvider: GHPRReviewsThreadsModelsProvider, private val reviewDiffComponentFactory: GHPRReviewThreadDiffComponentFactory, private val eventComponentFactory: GHPRTimelineEventComponentFactory<GHPRTimelineEvent>, private val selectInToolWindowHelper: GHPRSelectInToolWindowHelper, private val suggestedChangeHelper: GHPRSuggestedChangeHelper, private val currentUser: GHUser) : TimelineItemComponentFactory<GHPRTimelineItem> { override fun createComponent(item: GHPRTimelineItem): Item { try { return when (item) { is GHPullRequestCommitShort -> createComponent(item) is GHIssueComment -> createComponent(item) is GHPullRequestReview -> createComponent(item) is GHPRTimelineEvent -> eventComponentFactory.createComponent(item) is GHPRTimelineItem.Unknown -> throw IllegalStateException("Unknown item type: " + item.__typename) else -> error("Undefined item type") } } catch (e: Exception) { LOG.warn(e) return Item(AllIcons.General.Warning, HtmlEditorPane(GithubBundle.message("cannot.display.item", e.message ?: ""))) } } private fun createComponent(commit: GHPullRequestCommitShort): Item { val gitCommit = commit.commit val titlePanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(8))).apply { add(userAvatar(gitCommit.author)) add(HtmlEditorPane(gitCommit.messageHeadlineHTML)) add(ActionLink(gitCommit.abbreviatedOid) { selectInToolWindowHelper.selectCommit(gitCommit.abbreviatedOid) }) } return Item(AllIcons.Vcs.CommitNode, titlePanel) } fun createComponent(details: GHPullRequestShort): Item { val contentPanel: JPanel? val actionsPanel: JPanel? if (details is GHPullRequest) { val textPane = HtmlEditorPane(details.body.convertToHtml(project)) val panelHandle = GHEditableHtmlPaneHandle(project, textPane, details::body) { newText -> detailsDataProvider.updateDetails(EmptyProgressIndicator(), description = newText) .successOnEdt { textPane.setBody(it.body.convertToHtml(project)) } } contentPanel = panelHandle.panel actionsPanel = if (details.viewerCanUpdate) NonOpaquePanel(HorizontalLayout(JBUIScale.scale(8))).apply { add(GHTextActions.createEditButton(panelHandle)) } else null } else { contentPanel = null actionsPanel = null } val titlePanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(12))).apply { add(actionTitle(details.author, GithubBundle.message("pull.request.timeline.created"), details.createdAt)) if (actionsPanel != null && actionsPanel.componentCount > 0) add(actionsPanel) } return Item(userAvatar(details.author), titlePanel, contentPanel) } private fun createComponent(comment: GHIssueComment): Item { val textPane = HtmlEditorPane(comment.body.convertToHtml(project)) val panelHandle = GHEditableHtmlPaneHandle(project, textPane, comment::body) { newText -> commentsDataProvider.updateComment(EmptyProgressIndicator(), comment.id, newText) .successOnEdt { textPane.setBody(it.convertToHtml(project)) } } val actionsPanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(8))).apply { if (comment.viewerCanUpdate) add(GHTextActions.createEditButton(panelHandle)) if (comment.viewerCanDelete) add(GHTextActions.createDeleteButton { commentsDataProvider.deleteComment(EmptyProgressIndicator(), comment.id) }) } val titlePanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(12))).apply { add(actionTitle(comment.author, GithubBundle.message("pull.request.timeline.commented"), comment.createdAt)) if (actionsPanel.componentCount > 0) add(actionsPanel) } return Item(userAvatar(comment.author), titlePanel, panelHandle.panel) } private fun createComponent(review: GHPullRequestReview): Item { val reviewThreadsModel = reviewsThreadsModelsProvider.getReviewThreadsModel(review.id) val panelHandle: GHEditableHtmlPaneHandle? if (review.body.isNotEmpty()) { val textPane = HtmlEditorPane(review.body.convertToHtml(project)) panelHandle = GHEditableHtmlPaneHandle(project, textPane, review::body, { newText -> reviewDataProvider.updateReviewBody(EmptyProgressIndicator(), review.id, newText) .successOnEdt { textPane.setBody(it.convertToHtml(project)) } }) } else { panelHandle = null } val actionsPanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(8))).apply { if (panelHandle != null && review.viewerCanUpdate) add(GHTextActions.createEditButton(panelHandle)) } val contentPanel = NonOpaquePanel(VerticalLayout(12)).apply { border = JBUI.Borders.emptyTop(4) if (panelHandle != null) add(panelHandle.panel) add(GHPRReviewThreadsPanel.create(reviewThreadsModel) { GHPRReviewThreadComponent.createWithDiff(project, it, reviewDataProvider, avatarIconsProvider, reviewDiffComponentFactory, selectInToolWindowHelper, suggestedChangeHelper, currentUser) }) } val actionText = when (review.state) { APPROVED -> GithubBundle.message("pull.request.timeline.approved.changes") CHANGES_REQUESTED -> GithubBundle.message("pull.request.timeline.requested.changes") PENDING -> GithubBundle.message("pull.request.timeline.started.review") COMMENTED, DISMISSED -> GithubBundle.message("pull.request.timeline.reviewed") } val titlePanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(12))).apply { add(actionTitle(avatarIconsProvider, review.author, actionText, review.createdAt)) if (actionsPanel.componentCount > 0) add(actionsPanel) } val icon = when (review.state) { APPROVED -> GithubIcons.ReviewAccepted CHANGES_REQUESTED -> GithubIcons.ReviewRejected COMMENTED -> GithubIcons.Review DISMISSED -> GithubIcons.Review PENDING -> GithubIcons.Review } return Item(icon, titlePanel, contentPanel, NOT_DEFINED_SIZE) } private fun userAvatar(user: GHActor?): JLabel { return userAvatar(avatarIconsProvider, user) } private fun userAvatar(user: GHGitActor?): JLabel { return LinkLabel<Any>("", avatarIconsProvider.getIcon(user?.avatarUrl, GHUIUtil.AVATAR_SIZE), LinkListener { _, _ -> user?.url?.let { BrowserUtil.browse(it) } }) } class Item(val marker: JLabel, title: JComponent, content: JComponent? = null, size: Dimension = getDefaultSize()) : JPanel() { constructor(markerIcon: Icon, title: JComponent, content: JComponent? = null, size: Dimension = getDefaultSize()) : this(createMarkerLabel(markerIcon), title, content, size) init { isOpaque = false layout = MigLayout(LC().gridGap("0", "0") .insets("0", "0", "0", "0") .fill()).apply { columnConstraints = "[]${JBUIScale.scale(8)}[]" } add(marker, CC().pushY()) add(title, CC().pushX()) if (content != null) add(content, CC().newline().skip().grow().push().maxWidth(size)) } companion object { private fun CC.maxWidth(dimension: Dimension) = if (dimension.width > 0) this.maxWidth("${dimension.width}") else this private fun createMarkerLabel(markerIcon: Icon) = JLabel(markerIcon).apply { val verticalGap = if (markerIcon.iconHeight < 20) (20f - markerIcon.iconHeight) / 2 else 0f val horizontalGap = if (markerIcon.iconWidth < 20) (20f - markerIcon.iconWidth) / 2 else 0f border = JBUI.Borders.empty(floor(verticalGap).toInt(), floor(horizontalGap).toInt(), ceil(verticalGap).toInt(), ceil(horizontalGap).toInt()) } } } companion object { private val LOG = logger<GHPRTimelineItemComponentFactory>() private val NOT_DEFINED_SIZE = Dimension(-1, -1) fun getDefaultSize() = Dimension(GHUIUtil.getPRTimelineWidth(), -1) fun userAvatar(avatarIconsProvider: GHAvatarIconsProvider, user: GHActor?): JLabel { return LinkLabel<Any>("", avatarIconsProvider.getIcon(user?.avatarUrl, GHUIUtil.AVATAR_SIZE), LinkListener { _, _ -> user?.url?.let { BrowserUtil.browse(it) } }) } fun actionTitle(avatarIconsProvider: GHAvatarIconsProvider, actor: GHActor?, @Language("HTML") actionHTML: String, date: Date) : JComponent { return HorizontalBox().apply { add(userAvatar(avatarIconsProvider, actor)) add(Box.createRigidArea(JBDimension(8, 0))) add(actionTitle(actor, actionHTML, date)) } } fun actionTitle(actor: GHActor?, actionHTML: String, date: Date): JComponent { //language=HTML val text = """<a href='${actor?.url}'>${actor?.login ?: "unknown"}</a> $actionHTML ${GHUIUtil.formatActionDate(date)}""" return HtmlEditorPane(text).apply { foreground = UIUtil.getContextHelpForeground() } } } }
apache-2.0
1dd5310ea58a34b52ec68e5f3073f987
47
140
0.714253
4.916161
false
false
false
false
Akkyen/LootChest
src/main/java/de/mydevtime/sponge/plugin/lootchest/manager/ChestManager.kt
1
5074
package de.mydevtime.sponge.plugin.lootchest.manager import de.mydevtime.sponge.plugin.lootchest.LootChest import de.mydevtime.sponge.plugin.lootchest.data.ChestData import de.mydevtime.sponge.plugin.lootchest.data.RandomData import de.mydevtime.sponge.plugin.lootchest.util.RandomModes import org.slf4j.Logger import org.spongepowered.api.Game import org.spongepowered.api.block.BlockSnapshot import org.spongepowered.api.block.BlockTypes import org.spongepowered.api.block.tileentity.carrier.Chest import org.spongepowered.api.data.type.HandTypes import org.spongepowered.api.entity.living.player.Player import org.spongepowered.api.item.inventory.ItemStackSnapshot import org.spongepowered.api.item.inventory.Slot import java.util.* class ChestManager(val lootChest: LootChest, val game: Game, val logger: Logger) { var list: HashSet<ChestData> = HashSet() /** * This method is creating a new chest and adding it to the field to a MutableSet * * @return Int 0 = Success, 1 = Chest_Already_Added, 2 = No_Selected_Item, 3 = No_Chest, 4 = Name_Already_In_Use */ fun registerChest(block: BlockSnapshot, player: Player, ChestName: String): Int { if (isRegistered(block)) { return 1 } if (block.state.type == BlockTypes.CHEST) { //Casting the tileEntity to a Chest for later use val chest = block.location.get().tileEntity.get() as Chest //Getting the hotbar of the player creating this Chest val selectedItem = player.getItemInHand(HandTypes.MAIN_HAND) //Check so that the selected slot isn't empty if (selectedItem.isPresent) { val key = selectedItem.get() key.quantity = 1 val itemStacks = ArrayList<ItemStackSnapshot>() for (slot in chest.inventory.slots<Slot>()) { //Adding empty slots if (!slot.peek().isPresent) { itemStacks.add(ItemStackSnapshot.NONE) continue } itemStacks.add(slot.peek().get().createSnapshot()) } if (list.add(ChestData(ChestName.toLowerCase(), block.location.get().blockPosition, key.createSnapshot(), itemStacks, RandomData()))) { return 0 } else { return 4 } } return 2 } return 3 } /** * Removes a chest by providing the matching block * * @return Boolean True := Chest got deleted, False:= There is no such Chest to be deleted */ fun removeChest(block: BlockSnapshot): Boolean { return list.remove(getChest(block)) } /** * Updates a ChestData Object */ fun updateChest(block: BlockSnapshot) { //Casting the tileEntity to a Chest for later use val chest = block.location.get().tileEntity.get() as Chest //IF null return val chestData = getChest(block) ?: return val itemStacks = ArrayList<ItemStackSnapshot>() for (slot in chest.inventory.slots<Slot>()) { //Adding empty slots if (!slot.peek().isPresent) { itemStacks.add(ItemStackSnapshot.NONE) continue } itemStacks.add(slot.peek().get().createSnapshot()) } chestData.items = itemStacks } /** * Searches for a ChestData object that matches the location of the parameter block * * @return ChestData The matching ChestData or returns null */ fun getChest(block: BlockSnapshot): ChestData? { //Short if null check return list.firstOrNull { it.loc == block.location.get().blockPosition } } /** * Searches for a ChestData object that matches a UUID * * @return ChestData The matching ChestData or returns null */ fun getChestByName(name: String): ChestData? { //Short if null check return list.firstOrNull { it.name.toLowerCase() == name.toLowerCase() } } /** * This Method fills the Inv of a Chest if one exists at the matching location provided by block parameter */ fun fillChest(block: BlockSnapshot, editMode: Boolean, previewMode: Boolean) { //IF null return val chest: ChestData = this.getChest(block) ?: return val chestBlock = block.location.get().tileEntity.get() as Chest val slots = chestBlock.inventory.slots<Slot>().toMutableList() as ArrayList<Slot> chestBlock.inventory.clear() //Random filler if (chest.randomData.mode > 0 && editMode == false && previewMode == false) { if (chest.randomData.mode == 1) { val list = RandomModes.averageStackRandom(chest) if (list.isEmpty()) return for (i in 0..(list.size - 1)) { slots[i].set(list[i].createStack()) } } if (chest.randomData.mode == 2) { val list = RandomModes.stackSizeRandom(chest) if (list.isEmpty()) return for (i in 0..(list.size - 1)) { slots[i].set(list[i].createStack()) } } return } for (i in 0..(chest.items.size - 1)) { slots[i].set(chest.items[i].createStack()) } } /** * Check if a Block is already registered as Chest * * @return Boolean True == Is registered, False == Is not registered or block does not exist */ fun isRegistered(block: BlockSnapshot): Boolean { if (block.location.isPresent) { list .filter { it.loc == block.location.get().blockPosition } .forEach { return true } } return false } }
apache-2.0
9421effe48c4561627ddb212dba1df2f
24
137
0.691762
3.463481
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreatePropertyDelegateAccessorsActionFactory.kt
3
4702
// 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.quickfix.createFromUsage.createCallable import com.intellij.util.SmartList import org.jetbrains.kotlin.builtins.ReflectionTypes import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.VariableAccessorDescriptor import org.jetbrains.kotlin.descriptors.VariableDescriptorWithAccessors import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.util.OperatorNameConventions object CreatePropertyDelegateAccessorsActionFactory : CreateCallableMemberFromUsageFactory<KtExpression>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtExpression? { return diagnostic.psiElement as? KtExpression } override fun extractFixData(element: KtExpression, diagnostic: Diagnostic): List<CallableInfo> { val context = element.analyze() fun isApplicableForAccessor(accessor: VariableAccessorDescriptor?): Boolean = accessor != null && context[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, accessor] == null val property = element.getNonStrictParentOfType<KtProperty>() ?: return emptyList() val propertyDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, property] as? VariableDescriptorWithAccessors ?: return emptyList() if (propertyDescriptor is LocalVariableDescriptor && !element.languageVersionSettings.supportsFeature(LanguageFeature.LocalDelegatedProperties) ) { return emptyList() } val propertyReceiver = propertyDescriptor.extensionReceiverParameter ?: propertyDescriptor.dispatchReceiverParameter val propertyType = propertyDescriptor.type val accessorReceiverType = TypeInfo(element, Variance.IN_VARIANCE) val builtIns = propertyDescriptor.builtIns val thisRefParam = ParameterInfo(TypeInfo(propertyReceiver?.type ?: builtIns.nullableNothingType, Variance.IN_VARIANCE)) val kPropertyStarType = ReflectionTypes.createKPropertyStarType(propertyDescriptor.module) ?: return emptyList() val metadataParam = ParameterInfo(TypeInfo(kPropertyStarType, Variance.IN_VARIANCE), "property") val callableInfos = SmartList<CallableInfo>() val psiFactory = KtPsiFactory(element) if (isApplicableForAccessor(propertyDescriptor.getter)) { val getterInfo = FunctionInfo( name = OperatorNameConventions.GET_VALUE.asString(), receiverTypeInfo = accessorReceiverType, returnTypeInfo = TypeInfo(propertyType, Variance.OUT_VARIANCE), parameterInfos = listOf(thisRefParam, metadataParam), modifierList = psiFactory.createModifierList(KtTokens.OPERATOR_KEYWORD) ) callableInfos.add(getterInfo) } if (propertyDescriptor.isVar && isApplicableForAccessor(propertyDescriptor.setter)) { val newValueParam = ParameterInfo(TypeInfo(propertyType, Variance.IN_VARIANCE)) val setterInfo = FunctionInfo( name = OperatorNameConventions.SET_VALUE.asString(), receiverTypeInfo = accessorReceiverType, returnTypeInfo = TypeInfo(builtIns.unitType, Variance.OUT_VARIANCE), parameterInfos = listOf(thisRefParam, metadataParam, newValueParam), modifierList = psiFactory.createModifierList(KtTokens.OPERATOR_KEYWORD) ) callableInfos.add(setterInfo) } return callableInfos } }
apache-2.0
37a028f7e98484927d913a1e6e20c521
52.431818
158
0.762867
5.678744
false
false
false
false
GunoH/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/quickfix/fixes/SpecifySuperTypeFixFactory.kt
4
4629
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.fixes import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.ListPopupStep import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.util.containers.toMutableSmartList import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic import org.jetbrains.kotlin.analysis.api.types.KtClassErrorType import org.jetbrains.kotlin.analysis.api.types.KtNonErrorClassType import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicatorInput import org.jetbrains.kotlin.idea.codeinsight.api.applicators.applicator import org.jetbrains.kotlin.idea.base.analysis.api.utils.shortenReferences import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.diagnosticFixFactory import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.withInput import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtSuperExpression import org.jetbrains.kotlin.renderer.render object SpecifySuperTypeFixFactory { class TypeStringWithoutArgs(val longTypeRepresentation: String, val shortTypeRepresentation: String) class Input(val superTypes: List<TypeStringWithoutArgs>) : KotlinApplicatorInput val applicator = applicator<KtSuperExpression, Input> { familyAndActionName(KotlinBundle.lazyMessage("intention.name.specify.supertype")) applyToWithEditorRequired { psi, input, project, editor -> when (input.superTypes.size) { 0 -> return@applyToWithEditorRequired 1 -> psi.specifySuperType(input.superTypes.single()) else -> JBPopupFactory .getInstance() .createListPopup(createListPopupStep(psi, input.superTypes)) .showInBestPositionFor(editor) } } } private fun KtSuperExpression.specifySuperType(superType: TypeStringWithoutArgs) { project.executeWriteCommand(KotlinBundle.message("intention.name.specify.supertype")) { val label = this.labelQualifier?.text ?: "" val replaced = replace(KtPsiFactory(this).createExpression("super<${superType.longTypeRepresentation}>$label")) as KtSuperExpression shortenReferences(replaced) } } private fun createListPopupStep(superExpression: KtSuperExpression, superTypes: List<TypeStringWithoutArgs>): ListPopupStep<*> { return object : BaseListPopupStep<TypeStringWithoutArgs>(KotlinBundle.getMessage("popup.title.choose.supertype"), superTypes) { override fun isAutoSelectionEnabled() = false override fun onChosen(selectedValue: TypeStringWithoutArgs, finalChoice: Boolean): PopupStep<*>? { if (finalChoice) { superExpression.specifySuperType(selectedValue) } return PopupStep.FINAL_CHOICE } override fun getTextFor(value: TypeStringWithoutArgs): String { return value.shortTypeRepresentation } } } val ambiguousSuper = diagnosticFixFactory(KtFirDiagnostic.AmbiguousSuper::class, applicator) { diagnostic -> val candidates = diagnostic.candidates.toMutableSmartList() // TODO: the following logic would become unnecessary if feature https://youtrack.jetbrains.com/issue/KT-49314 is accepted because // the candidate would not contain those being removed here. candidates.removeAll { superType -> candidates.any { otherSuperType -> superType != otherSuperType && otherSuperType isSubTypeOf superType } } if (candidates.isEmpty()) return@diagnosticFixFactory listOf() val superTypes = candidates.mapNotNull { superType -> when (superType) { is KtClassErrorType -> null is KtNonErrorClassType -> TypeStringWithoutArgs(superType.classId.asSingleFqName().render(), superType.classId.shortClassName.render()) else -> error("Expected KtClassType but ${superType::class} was found") } } listOf(diagnostic.psi withInput Input(superTypes)) } }
apache-2.0
5a5cc08bf810ea91b7f8551301b0e257
49.326087
138
0.715057
5.177852
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/stories/viewer/views/StoryViewsRepository.kt
1
1353
package org.thoughtcrime.securesms.stories.viewer.views import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.schedulers.Schedulers import org.thoughtcrime.securesms.database.DatabaseObserver import org.thoughtcrime.securesms.database.GroupReceiptDatabase import org.thoughtcrime.securesms.database.SignalDatabase import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.recipients.Recipient class StoryViewsRepository { fun getViews(storyId: Long): Observable<List<StoryViewItemData>> { return Observable.create<List<StoryViewItemData>> { emitter -> fun refresh() { emitter.onNext( SignalDatabase.groupReceipts.getGroupReceiptInfo(storyId).filter { it.status == GroupReceiptDatabase.STATUS_VIEWED }.map { StoryViewItemData( recipient = Recipient.resolved(it.recipientId), timeViewedInMillis = it.timestamp ) } ) } val observer = DatabaseObserver.MessageObserver { refresh() } ApplicationDependencies.getDatabaseObserver().registerMessageUpdateObserver(observer) emitter.setCancellable { ApplicationDependencies.getDatabaseObserver().unregisterObserver(observer) } refresh() }.subscribeOn(Schedulers.io()) } }
gpl-3.0
7b806fe781d3e1cc71e1d1e6d6b49ad8
35.567568
91
0.734664
5.067416
false
false
false
false
ktorio/ktor
ktor-io/common/src/io/ktor/utils/io/WriterSession.kt
1
3249
package io.ktor.utils.io import io.ktor.utils.io.bits.* import io.ktor.utils.io.core.* import io.ktor.utils.io.core.internal.* /** * Await for [desiredSpace] will be available for write and invoke [block] function providing [Memory] instance and * the corresponding range suitable for wiring in the memory. The block function should return number of bytes were * written, possibly 0. * * Similar to [ByteReadChannel.read], this function may invoke block function with lesser memory range when the * specified [desiredSpace] is bigger that the buffer's capacity * or when it is impossible to represent all [desiredSpace] bytes as a single memory range * due to internal implementation reasons. */ public suspend inline fun ByteWriteChannel.write( desiredSpace: Int = 1, block: (freeSpace: Memory, startOffset: Long, endExclusive: Long) -> Int ): Int { val buffer = requestWriteBuffer(desiredSpace) ?: Buffer.Empty var bytesWritten = 0 try { bytesWritten = block(buffer.memory, buffer.writePosition.toLong(), buffer.limit.toLong()) buffer.commitWritten(bytesWritten) return bytesWritten } finally { completeWriting(buffer, bytesWritten) } } @Suppress("DEPRECATION") @Deprecated("Use writeMemory instead.") public interface WriterSession { public fun request(min: Int): ChunkBuffer? public fun written(n: Int) public fun flush() } @Suppress("DEPRECATION") @Deprecated("Use writeMemory instead.") public interface WriterSuspendSession : WriterSession { public suspend fun tryAwait(n: Int) } @Suppress("DEPRECATION") internal interface HasWriteSession { public fun beginWriteSession(): WriterSuspendSession? public fun endWriteSession(written: Int) } @PublishedApi internal suspend fun ByteWriteChannel.requestWriteBuffer(desiredSpace: Int): Buffer? { val session = writeSessionFor() if (session != null) { val buffer = session.request(desiredSpace) if (buffer != null) { return buffer } return writeBufferSuspend(session, desiredSpace) } return writeBufferFallback() } @PublishedApi internal suspend fun ByteWriteChannel.completeWriting(buffer: Buffer, written: Int) { if (this is HasWriteSession) { endWriteSession(written) return } return completeWritingFallback(buffer) } @Suppress("DEPRECATION") private suspend fun ByteWriteChannel.completeWritingFallback(buffer: Buffer) { if (buffer is ChunkBuffer) { writeFully(buffer) buffer.release(ChunkBuffer.Pool) return } throw UnsupportedOperationException("Only ChunkBuffer instance is supported.") } @Suppress("DEPRECATION") private suspend fun writeBufferSuspend(session: WriterSuspendSession, desiredSpace: Int): Buffer? { session.tryAwait(desiredSpace) return session.request(desiredSpace) ?: session.request(1) } private fun writeBufferFallback(): Buffer = ChunkBuffer.Pool.borrow().also { it.resetForWrite() it.reserveEndGap(Buffer.ReservedSize) } @Suppress("DEPRECATION", "NOTHING_TO_INLINE") private inline fun ByteWriteChannel.writeSessionFor(): WriterSuspendSession? = when { this is HasWriteSession -> beginWriteSession() else -> null }
apache-2.0
ee513001de9bf0079810fbc503fcec16
30.543689
115
0.729763
4.384615
false
false
false
false
AoDevBlue/AnimeUltimeTv
app/src/main/java/blue/aodev/animeultimetv/presentation/screen/animedetails/DetailsDescriptionPresenter.kt
1
2798
package blue.aodev.animeultimetv.presentation.screen.animedetails import android.content.Context import android.support.v17.leanback.widget.Presenter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import android.widget.TextView import blue.aodev.animeultimetv.R import blue.aodev.animeultimetv.domain.model.Anime import blue.aodev.animeultimetv.domain.model.AnimeSummary import butterknife.BindView import butterknife.ButterKnife class DetailsDescriptionPresenter(private val context: Context) : Presenter() { override fun onCreateViewHolder(parent: ViewGroup): Presenter.ViewHolder { val view = LayoutInflater.from(context).inflate(R.layout.layout_details_description, null) return ViewHolder(view) } override fun onBindViewHolder(viewHolder: Presenter.ViewHolder, item: Any) { (viewHolder as ViewHolder).populate(item) } override fun onUnbindViewHolder(viewHolder: Presenter.ViewHolder) { // Nothing to do here. } inner class ViewHolder(view: View): Presenter.ViewHolder(view) { @BindView(R.id.primary_text) lateinit var primaryText: TextView @BindView(R.id.secondary_text_first) lateinit var secondaryText1: TextView @BindView(R.id.secondary_text_second) lateinit var secondaryText2: TextView @BindView(R.id.extra_text) lateinit var extraText: TextView @BindView(R.id.loading_progress) lateinit var loadingProgress: ProgressBar init { ButterKnife.bind(this, view) } fun populate(item: Any?) { if (item == null) return val resources = context.resources var title = "" var episodeCount = 0 if (item is AnimeSummary) { loadingProgress.visibility = View.VISIBLE title = item.title episodeCount = item.availableCount } else if (item is Anime) { loadingProgress.visibility = View.GONE title = item.title episodeCount = item.episodes.size extraText.text = item.synopsis val yearString = with (item.productionYears) { if (start == endInclusive) { start.toString() } else { resources.getString(R.string.details_productionYears, start, endInclusive) } } secondaryText2.text = yearString } primaryText.text = title secondaryText1.text = resources.getQuantityString( R.plurals.details_episodesCount, episodeCount, episodeCount) } } }
mit
e8e6518e9bad471275495224e4d89b05
33.9875
98
0.637956
5.014337
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceRangeStartEndInclusiveWithFirstLastInspection.kt
1
3197
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.intentions.isRange import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.dotQualifiedExpressionVisitor class ReplaceRangeStartEndInclusiveWithFirstLastInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return dotQualifiedExpressionVisitor(fun(expression: KtDotQualifiedExpression) { val selectorExpression = expression.selectorExpression ?: return if (selectorExpression.text != "start" && selectorExpression.text != "endInclusive") return val resolvedCall = expression.resolveToCall() ?: return val containing = resolvedCall.resultingDescriptor.containingDeclaration as? ClassDescriptor ?: return if (!containing.isRange()) return if (selectorExpression.text == "start") { holder.registerProblem( expression, KotlinBundle.message("could.be.replaced.with.unboxed.first"), ReplaceIntRangeStartWithFirstQuickFix() ) } else if (selectorExpression.text == "endInclusive") { holder.registerProblem( expression, KotlinBundle.message("could.be.replaced.with.unboxed.last"), ReplaceIntRangeEndInclusiveWithLastQuickFix() ) } }) } } class ReplaceIntRangeStartWithFirstQuickFix : LocalQuickFix { override fun getName() = KotlinBundle.message("replace.int.range.start.with.first.quick.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as KtDotQualifiedExpression val selector = element.selectorExpression ?: return selector.replace(KtPsiFactory(element).createExpression("first")) } } class ReplaceIntRangeEndInclusiveWithLastQuickFix : LocalQuickFix { override fun getName() = KotlinBundle.message("replace.int.range.end.inclusive.with.last.quick.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as KtDotQualifiedExpression val selector = element.selectorExpression ?: return selector.replace(KtPsiFactory(element).createExpression("last")) } }
apache-2.0
ab38266b244f131e278e8369c4faabcf
46.029412
120
0.732875
5.474315
false
false
false
false
airbnb/epoxy
epoxy-processor/src/main/java/com/airbnb/epoxy/processor/XProcessingUtils.kt
1
12421
package com.airbnb.epoxy.processor import androidx.room.compiler.processing.XAnnotation import androidx.room.compiler.processing.XAnnotationValue import androidx.room.compiler.processing.XElement import androidx.room.compiler.processing.XEnumEntry import androidx.room.compiler.processing.XExecutableElement import androidx.room.compiler.processing.XFieldElement import androidx.room.compiler.processing.XHasModifiers import androidx.room.compiler.processing.XMethodElement import androidx.room.compiler.processing.XType import androidx.room.compiler.processing.XTypeElement import androidx.room.compiler.processing.XVariableElement import androidx.room.compiler.processing.compat.XConverters.toJavac import androidx.room.compiler.processing.isVoid import androidx.room.compiler.processing.isVoidObject import com.airbnb.epoxy.processor.ClassNames.KOTLIN_ANY import com.airbnb.epoxy.processor.resourcescanning.getFieldWithReflection import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSAnnotation import com.google.devtools.ksp.symbol.KSDeclaration import com.google.devtools.ksp.symbol.KSFile import com.google.devtools.ksp.symbol.KSNode import com.google.devtools.ksp.symbol.KSPropertyDeclaration import com.google.devtools.ksp.symbol.Origin import com.squareup.javapoet.AnnotationSpec import com.squareup.javapoet.ClassName import com.squareup.javapoet.ParameterSpec import java.lang.Character.isISOControl import javax.lang.model.element.Modifier import kotlin.reflect.KClass /** * Look up enclosing type element if this is a field or function within a class. */ val XElement.enclosingTypeElement: XTypeElement? get() { return when (this) { is XExecutableElement -> enclosingElement as? XTypeElement is XFieldElement -> enclosingElement as? XTypeElement else -> null } } fun XTypeElement.hasOverload(element: XMethodElement, paramCount: Int): Boolean { return findOverload(element, paramCount) != null } fun XTypeElement.findOverload(element: XMethodElement, paramCount: Int): XMethodElement? { require(element.parameters.size != paramCount) { "Element $element already has param count $paramCount" } return getDeclaredMethods() .firstOrNull { it.parameters.size == paramCount && areOverloads(it, element) } } /** * True if the two elements represent overloads of the same function in a class. */ fun areOverloads(e1: XMethodElement, e2: XMethodElement): Boolean { return e1.parameters.size != e2.parameters.size && e1.name == e2.name && e1.enclosingElement == e2.enclosingElement && e1.returnType == e2.returnType && e1.isStatic() == e2.isStatic() && e1.isPrivate() == e2.isPrivate() } /** Return each of the classes in the class hierarchy, starting with the initial receiver and working upwards until Any. */ tailrec fun XElement.iterateClassHierarchy( classCallback: (classElement: XTypeElement) -> Unit ) { if (this !is XTypeElement) { return } classCallback(this) val superClazz = this.superType?.typeElement superClazz?.iterateClassHierarchy(classCallback) } /** Iterate each super class of the receiver, starting with the initial super class and going until Any. */ fun XElement.iterateSuperClasses( classCallback: (classElement: XTypeElement) -> Unit ) { iterateClassHierarchy { // Skip the original class so that only super classes are passed to the callback if (it != this) { classCallback(it) } } } /** * Returns a list of annotations specs representing annotations on the given type element. * * @param annotationFilter Return false to exclude annotations with the given class name. */ fun XTypeElement.buildAnnotationSpecs( annotationFilter: (ClassName) -> Boolean, memoizer: Memoizer ): List<AnnotationSpec> { val internalAnnotationFilter = { className: ClassName -> if (className.reflectionName() == "kotlin.Metadata") { // Don't include the generated kotlin metadata since it only applies to the original // kotlin class and is wrong to put on our generated java classes. false } else { annotationFilter(className) } } return getAllAnnotations() .map { it.toAnnotationSpec(memoizer) } .filter { internalAnnotationFilter(it.type as ClassName) } } fun XAnnotation.toAnnotationSpec(memoizer: Memoizer): AnnotationSpec { // Adapted from javapoet internals fun AnnotationSpec.Builder.addMemberForValue( memberName: String, value: Any?, memoizer: Memoizer ): AnnotationSpec.Builder { if (value is XType) { return if (value.isVoid() || value.isVoidObject()) { addMember(memberName, "Void.class") } else { addMember(memberName, "\$T.class", value.typeNameWithWorkaround(memoizer)) } } if (value is XEnumEntry) { return addMember(memberName, "\$T.\$L", value.enumTypeElement.className, value.name) } if (value is XAnnotation) { return addMember(memberName, "\$L", value.toAnnotationSpec(memoizer)) } if (value is XAnnotationValue) { return addMemberForValue(value.name, value.value, memoizer) } if (value is List<*>) { if (value.isEmpty()) { addMember(memberName, "{}") } else { value.forEach { listValue -> addMemberForValue( memberName, listValue ?: error("Unexpected null item in annotation value list"), memoizer ) } } return this } if (value is String) { return addMember(memberName, "\$S", value) } if (value is Float) { return addMember(memberName, "\$Lf", value) } if (value is Char) { return addMember( memberName, "'\$L'", characterLiteralWithoutSingleQuotes(value) ) } return addMember(memberName, "\$L", value) } return AnnotationSpec.builder(ClassName.get(packageName, name)).apply { annotationValues.forEach { annotationValue -> addMemberForValue(annotationValue.name, annotationValue.value, memoizer) } }.build() } fun XVariableElement.toParameterSpec(memoizer: Memoizer): ParameterSpec { val builder = ParameterSpec.builder( type.typeNameWithWorkaround(memoizer), name ) for (annotation in getAllAnnotations()) { builder.addAnnotation(annotation.toAnnotationSpec(memoizer)) } return builder.build() } fun characterLiteralWithoutSingleQuotes(c: Char): String { // see https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6 return when (c) { '\b' -> "\\b" /* \u0008: backspace (BS) */ '\t' -> "\\t" /* \u0009: horizontal tab (HT) */ '\n' -> "\\n" /* \u000a: linefeed (LF) */ '\r' -> "\\r" /* \u000d: carriage return (CR) */ '\"' -> "\"" /* \u0022: double quote (") */ '\'' -> "\\'" /* \u0027: single quote (') */ '\\' -> "\\\\" /* \u005c: backslash (\) */ else -> if (isISOControl(c)) String.format("\\u%04x", c.code) else c.toString() } } val XAnnotation.packageName: String get() = qualifiedName.substringBeforeLast(".$name") fun XTypeElement.isEpoxyModel(memoizer: Memoizer): Boolean { return isSubTypeOf(memoizer.epoxyModelClassElementUntyped) } fun XType.isEpoxyModel(memoizer: Memoizer): Boolean { return typeElement?.isEpoxyModel(memoizer) == true } fun XType.isDataBindingEpoxyModel(memoizer: Memoizer): Boolean { val databindingType = memoizer.epoxyDataBindingModelBaseClass?.type ?: return false return isSubTypeOf(databindingType) } fun XType.isEpoxyModelWithHolder(memoizer: Memoizer): Boolean { return isSubTypeOf(memoizer.epoxyModelWithHolderTypeUntyped) } fun XType.isEpoxyModelCollector(memoizer: Memoizer): Boolean { return isSubTypeOf(memoizer.epoxyModelCollectorType) } fun XTypeElement.isEpoxyController(memoizer: Memoizer): Boolean { return isSubTypeOf(memoizer.epoxyControllerType) } val XHasModifiers.javacModifiers: Set<Modifier> get() { return setOfNotNull( if (isPublic()) Modifier.PUBLIC else null, if (isProtected()) Modifier.PROTECTED else null, if (isAbstract()) Modifier.ABSTRACT else null, if (isPrivate()) Modifier.PRIVATE else null, if (isStatic()) Modifier.STATIC else null, if (isFinal()) Modifier.FINAL else null, if (isTransient()) Modifier.TRANSIENT else null, ) } val XElement.expectName: String get() = when (this) { is XVariableElement -> this.name is XMethodElement -> this.name is XTypeElement -> this.name else -> throw EpoxyProcessorException( "Expected this to be a variable or method $this", element = this ) } fun XType.isSubTypeOf(otherType: XType): Boolean { // Using the normal "isAssignableFrom" on XType doesn't always work correctly or predictably // with generics, so when we just want to check if something is a subclass without considering // that this is the simplest approach. // This is especially because we generally just use this to check class type hierarchies, not // parameter/field types. return otherType.rawType.isAssignableFrom(this) } fun XTypeElement.isSubTypeOf(otherType: XTypeElement): Boolean { return type.isSubTypeOf(otherType.type) } fun XTypeElement.isSubTypeOf(otherType: XType): Boolean { return type.isSubTypeOf(otherType) } fun XTypeElement.isInSamePackageAs(class2: XTypeElement): Boolean { return packageName == class2.packageName } fun XType.isObjectOrAny(): Boolean = typeName == KOTLIN_ANY || typeName == ClassName.OBJECT val KSAnnotation.containingPackage: String? get() = parent?.containingPackage val KSNode.containingPackage: String? get() { return when (this) { is KSFile -> packageName.asString() is KSDeclaration -> packageName.asString() else -> parent?.containingPackage } } fun XElement.isJavaSourceInKsp(): Boolean { return try { val declaration = getFieldWithReflection<KSAnnotated>("declaration") // If getting the declaration succeeded then we are in KSP and we can check the source origin. declaration.origin == Origin.JAVA || declaration.origin == Origin.JAVA_LIB } catch (e: Throwable) { // Not KSP false } } fun XElement.isKotlinSourceInKsp(): Boolean { return try { val declaration = getFieldWithReflection<KSAnnotated>("declaration") // If getting the declaration succeeded then we are in KSP and we can check the source origin. declaration.origin == Origin.KOTLIN_LIB || declaration.origin == Origin.KOTLIN } catch (e: Throwable) { // Not KSP false } } val XFieldElement.declaration: KSPropertyDeclaration get() = getFieldWithReflection("declaration") fun KSDeclaration.isKotlinOrigin(): Boolean { return when (origin) { Origin.KOTLIN -> true Origin.KOTLIN_LIB -> true Origin.JAVA -> false Origin.JAVA_LIB -> false Origin.SYNTHETIC -> false } } val XElement.isKsp: Boolean get() = try { toJavac() false } catch (e: Throwable) { true } fun XTypeElement.getElementsAnnotatedWith(annotationClass: KClass<out Annotation>): List<XElement> { return listOf(this).getElementsAnnotatedWith(annotationClass) } fun List<XTypeElement>.getElementsAnnotatedWith(annotationClass: KClass<out Annotation>): List<XElement> { return flatMap { typeElement -> (typeElement.getDeclaredMethods() + typeElement.getDeclaredFields()).filter { xElement -> xElement.hasAnnotation(annotationClass) } } } data class MethodInfoLight( val name: String, val docComment: String?, ) fun XTypeElement.getDeclaredMethodsLight(memoizer: Memoizer): List<MethodInfoLight> { return memoizer.getDeclaredMethodsLight(this) }
apache-2.0
6c05eada40a9725aa5dfbbbb841431f6
34.488571
123
0.674986
4.539839
false
false
false
false
taumechanica/ml
src/main/kotlin/ml/Ensemble.kt
1
1377
// Use of this source code is governed by The MIT License // that can be found in the LICENSE file. package taumechanica.ml open class Ensemble : Predictor { val predictors: Array<Predictor?> private val size: Int private val targetSize: Int private val compose: (DoubleArray) -> DoubleArray constructor(size: Int, targetSize: Int, method: String) { predictors = arrayOfNulls(size) this.size = size this.targetSize = targetSize compose = when (method) { "sum" -> ::sum "avg" -> ::avg else -> throw Exception( "Unknown composition method" ) } } override fun predict(values: DoubleArray) = compose(values) private fun sum(values: DoubleArray): DoubleArray { val scores = DoubleArray(targetSize, { 0.0 }) for (t in 0 until size) if (predictors[t] != null) { val prediction = predictors[t]!!.predict(values) for (k in 0 until targetSize) scores[k] += prediction[k] } return scores } private fun avg(values: DoubleArray): DoubleArray { val scores = sum(values) val actualSize = predictors.count({ it != null }) if (actualSize > 0) for (k in 0 until targetSize) { scores[k] = scores[k] / actualSize } return scores } }
mit
c7e695cbdf2a3b407cfbb762b6a55afe
28.934783
68
0.588235
4.343849
false
false
false
false
paplorinc/intellij-community
platform/diff-impl/tests/com/intellij/diff/comparison/ComparisonMergeUtilTestBase.kt
2
7561
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.comparison import com.intellij.diff.DiffTestCase import com.intellij.diff.fragments.MergeLineFragment import com.intellij.diff.util.IntPair import com.intellij.diff.util.MergeRange import com.intellij.diff.util.ThreeSide import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.util.Couple import com.intellij.util.containers.ContainerUtil import java.util.* abstract class ComparisonMergeUtilTestBase : DiffTestCase() { private fun doCharTest(texts: Trio<Document>, expected: List<Change>?, matchings: Trio<BitSet>?) { val iterable1 = ByChar.compare(texts.data2.charsSequence, texts.data1.charsSequence, INDICATOR) val iterable2 = ByChar.compare(texts.data2.charsSequence, texts.data3.charsSequence, INDICATOR) val fragments = ComparisonMergeUtil.buildSimple(iterable1, iterable2, INDICATOR) val actual = convertDiffFragments(fragments) checkConsistency(actual, texts) if (matchings != null) checkDiffMatching(actual, matchings) if (expected != null) checkDiffChanges(actual, expected) } private fun doLineDiffTest(texts: Trio<Document>, expected: List<Change>?, matchings: Trio<BitSet>?, policy: ComparisonPolicy) { val fragments = MANAGER.compareLines(texts.data1.charsSequence, texts.data2.charsSequence, texts.data3.charsSequence, policy, INDICATOR) val actual = convertMergeFragments(fragments) if (matchings != null) checkDiffMatching(actual, matchings) if (expected != null) checkDiffChanges(actual, expected) } private fun doLineMergeTest(texts: Trio<Document>, expected: List<Change>?, matchings: Trio<BitSet>?, policy: ComparisonPolicy) { val fragments = MANAGER.mergeLines(texts.data1.charsSequence, texts.data2.charsSequence, texts.data3.charsSequence, policy, INDICATOR) val actual = convertMergeFragments(fragments) if (matchings != null) checkDiffMatching(actual, matchings) if (expected != null) checkDiffChanges(actual, expected) } private fun checkConsistency(actual: List<Change>, texts: Trio<Document>) { var lasts = Trio(-1, -1, -1) for (change in actual) { val starts = change.starts val ends = change.ends var empty = true var squashed = true ThreeSide.values().forEach { val start = starts(it) val end = ends(it) val last = lasts(it) assertTrue(last <= start) assertTrue(start <= end) empty = empty && (start == end) squashed = squashed && (start == last) } assertTrue(!empty) assertTrue(!squashed) lasts = ends } } private fun checkDiffChanges(actual: List<Change>, expected: List<Change>) { assertOrderedEquals(expected, actual) } private fun checkDiffMatching(changes: List<Change>, matchings: Trio<BitSet>) { val sets = Trio(BitSet(), BitSet(), BitSet()) for (change in changes) { sets.forEach { set: BitSet, side: ThreeSide -> set.set(change.start(side), change.end(side)) } } assertSetsEquals(matchings.data1, sets.data1, "Left") assertSetsEquals(matchings.data2, sets.data2, "Base") assertSetsEquals(matchings.data3, sets.data3, "Right") } private fun convertDiffFragments(fragments: List<MergeRange>): List<Change> { return fragments.map { Change( it.start1, it.end1, it.start2, it.end2, it.start3, it.end3) } } private fun convertMergeFragments(fragments: List<MergeLineFragment>): List<Change> { return fragments.map { Change( it.getStartLine(ThreeSide.LEFT), it.getEndLine(ThreeSide.LEFT), it.getStartLine(ThreeSide.BASE), it.getEndLine(ThreeSide.BASE), it.getStartLine(ThreeSide.RIGHT), it.getEndLine(ThreeSide.RIGHT)) } } internal enum class TestType { CHAR, LINE_DIFF, LINE_MERGE } internal inner class MergeTestBuilder(val type: TestType) { private var isExecuted: Boolean = false private var texts: Trio<Document>? = null private var changes: List<Change>? = null private var matching: Trio<BitSet>? = null fun assertExecuted() { assertTrue(isExecuted) } fun test() { test(ComparisonPolicy.DEFAULT) } fun test(policy: ComparisonPolicy) { isExecuted = true assertTrue(changes != null || matching != null) when (type) { TestType.CHAR -> { assertEquals(policy, ComparisonPolicy.DEFAULT) doCharTest(texts!!, changes, matching) } TestType.LINE_DIFF -> { doLineDiffTest(texts!!, changes, matching, policy) } TestType.LINE_MERGE -> { doLineMergeTest(texts!!, changes, matching, policy) } } } operator fun String.minus(v: String): Couple<String> { return Couple(this, v) } operator fun Couple<String>.minus(v: String): Helper { return Helper(Trio(this.first, this.second, v)) } inner class Helper(val matchTexts: Trio<String>) { init { if (texts == null) { texts = matchTexts.map { it -> DocumentImpl(parseSource(it)) } } } fun matching() { assertNull(matching) if (type != TestType.CHAR) { matching = matchTexts.map { it, side -> parseLineMatching(it, texts!!(side)) } } else { matching = matchTexts.map { it, side -> parseMatching(it, texts!!(side)) } } } } fun changes(vararg expected: Change) { assertNull(changes) changes = ContainerUtil.list(*expected) } fun mod(line1: Int, line2: Int, line3: Int, count1: Int, count2: Int, count3: Int): Change { return Change(line1, line1 + count1, line2, line2 + count2, line3, line3 + count3) } } internal fun chars(f: MergeTestBuilder.() -> Unit) { doTest(TestType.CHAR, f) } internal fun lines_diff(f: MergeTestBuilder.() -> Unit) { doTest(TestType.LINE_DIFF, f) } internal fun lines_merge(f: MergeTestBuilder.() -> Unit) { doTest(TestType.LINE_MERGE, f) } internal fun doTest(type: TestType, f: MergeTestBuilder.() -> Unit) { val builder = MergeTestBuilder(type) builder.f() builder.assertExecuted() } class Change(start1: Int, end1: Int, start2: Int, end2: Int, start3: Int, end3: Int) : Trio<IntPair>(IntPair(start1, end1), IntPair(start2, end2), IntPair(start3, end3)) { val start1 = start(ThreeSide.LEFT) val start2 = start(ThreeSide.BASE) val start3 = start(ThreeSide.RIGHT) val end1 = end(ThreeSide.LEFT) val end2 = end(ThreeSide.BASE) val end3 = end(ThreeSide.RIGHT) val starts = Trio(start1, start2, start3) val ends = Trio(end1, end2, end3) fun start(side: ThreeSide): Int = this(side).val1 fun end(side: ThreeSide): Int = this(side).val2 override fun toString(): String { return "($start1, $end1) - ($start2, $end2) - ($start3, $end3)" } } }
apache-2.0
1f46c24e5d3a2af7a974427d276a8de1
30.504167
140
0.671472
4.045479
false
true
false
false
encircled/Joiner
joiner-kotlin/src/test/java/cz/encircled/joiner/kotlin/JoinerKtTest.kt
1
3753
package cz.encircled.joiner.kotlin import cz.encircled.joiner.exception.JoinerException import cz.encircled.joiner.kotlin.JoinerKtOps.eq import cz.encircled.joiner.kotlin.JoinerKtOps.innerJoin import cz.encircled.joiner.kotlin.JoinerKtOps.isIn import cz.encircled.joiner.kotlin.JoinerKtOps.leftJoin import cz.encircled.joiner.kotlin.JoinerKtOps.ne import cz.encircled.joiner.kotlin.JoinerKtOps.on import cz.encircled.joiner.kotlin.JoinerKtOps.or import cz.encircled.joiner.kotlin.JoinerKtQueryBuilder.all import cz.encircled.joiner.kotlin.JoinerKtQueryBuilder.countOf import cz.encircled.joiner.kotlin.JoinerKtQueryBuilder.from import cz.encircled.joiner.model.QAddress import cz.encircled.joiner.model.QGroup import cz.encircled.joiner.model.QStatus import cz.encircled.joiner.model.QUser import org.junit.jupiter.api.TestInfo import org.junit.jupiter.api.assertThrows import kotlin.test.* class JoinerKtTest : AbstractTest() { lateinit var joinerKt: JoinerKt @BeforeTest fun before(test: TestInfo) { super.beforeEach(test) joinerKt = JoinerKt(entityManager) } @Test fun getOne() { assertThrows<JoinerException> { joinerKt.getOne(QUser.user1 from QUser.user1 where { it.id eq -1 }) } } @Test fun testFindOne() { assertNull(joinerKt.findOne(QUser.user1 from QUser.user1 where { it.id eq -1 })) } @Test fun ktFindAllQueryIntegrationTest() { val find = joinerKt.find( QUser.user1 from QUser.user1 leftJoin QGroup.group leftJoin QStatus.status innerJoin QStatus.status where { it.name eq "user1" or it.id ne 1 or it.id isIn listOf(1) } asc QUser.user1.id ) QAddress.address from QAddress.address where { it.user.id eq (QUser.user1.id from QUser.user1) } assertNotNull(find) } @Test fun `left join on`() { val actual = (QGroup.group.all() leftJoin QUser.user1 on QUser.user1.name.eq("user1")).delegate.getJoin(QUser.user1).on assertEquals(QUser.user1.name.eq("user1"), actual) } @Test fun `inner join on`() { val actual = (QGroup.group.all() innerJoin QGroup.group.users on QUser.user1.name.eq("user1")).delegate.getJoin(QUser.user1).on assertEquals(QUser.user1.name.eq("user1"), actual) } @Test fun `tuple with count projection`() { val tuples = joinerKt.find( listOf(QUser.user1.count(), QUser.user1.id) from QUser.user1 groupBy QUser.user1.id ) assertEquals(tuples.size, joinerKt.getOne(QUser.user1.countOf()).toInt()) } @Test fun ktFindOneQueryIntegrationTest() { val find = joinerKt.findOne( QUser.user1 from QUser.user1 leftJoin QGroup.group leftJoin QStatus.status innerJoin QStatus.status where { it.name eq "user1" or it.id ne 1 or it.id isIn listOf(1) } limit 1 offset 0 asc QUser.user1.id ) assertNotNull(find) } @Test fun ktCountQuery() { assertEquals(7, joinerKt.findOne(QUser.user1.countOf())) } @Test fun ktCountQueryIntegrationTest() { val find = joinerKt.findOne( QUser.user1.countOf() leftJoin QGroup.group leftJoin QUser.user1.statuses innerJoin QStatus.status where { it.name eq "user1" or it.id ne 1 or it.id isIn listOf(1) } asc QUser.user1.id ) assertEquals(7, find) } }
apache-2.0
18424ff11e40b9272d4bde42386b12d2
29.770492
110
0.627764
3.626087
false
true
false
false
apache/isis
incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/to/ServiceTest.kt
2
2040
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.to import org.apache.causeway.client.kroviz.handler.ServiceHandler import org.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0.SO_MENU import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue class ServiceTest : ToTest() { @Test fun testSimpleObjectMenu() { val jsonStr = SO_MENU.str val service = ServiceHandler().parse(jsonStr) as Service assertEquals("Simple Objects", service.title) val actions: List<Member> = service.getMemberList() assertEquals(3, actions.size) assertTrue(service.containsMemberWith("listAll")) assertTrue(service.containsMemberWith("findByName")) assertTrue(service.containsMemberWith("create")) // jsonObj contains '"members": {}' not '"members": []' // this results in an unordered list (Map), // but intended is an ordered list (Array[]) //TODO use object-layout / menu layout instead } fun Service.containsMemberWith(id: String): Boolean { for (m in getMemberList()) { if (m.id == id) { return true } } return false } }
apache-2.0
e98ff8d608213ea2b23eb07f20070253
35.428571
74
0.686275
4.258873
false
true
false
false
RuneSuite/client
api/src/main/java/org/runestar/client/api/overlay/OverlayList.kt
1
4140
package org.runestar.client.api.overlay import org.kxtra.swing.geom.component1 import org.kxtra.swing.geom.component2 import java.awt.Dimension import java.awt.Graphics2D import kotlin.math.absoluteValue import kotlin.math.max class OverlayList( val overlays: Collection<Overlay>, val direction: Int, val alignment: Int, val spacing: Int ) : Overlay { companion object { const val CENTER = 0 const val UP = -1 const val DOWN = 1 const val LEFT = -2 const val RIGHT = 2 } init { require(spacing >= 0) val dv = direction.absoluteValue val av = alignment.absoluteValue require(dv in 1..2 && av in 0..2 && dv != av) } override fun draw(g: Graphics2D, size: Dimension) { when (overlays.size) { 0 -> return 1 -> return overlays.first().draw(g, size) } val (w, h) = size val tx = g.transform when (direction) { UP -> { g.translate(0, h) overlays.forEach { it.getSize(g, size) if (size.isZero) return@forEach val (ow, oh) = size var x = 0 when (alignment) { CENTER -> x = (w - ow) / 2 RIGHT -> x = w - ow } g.translate(x, -oh) it.draw(g, size) g.translate(-x, -spacing) } } DOWN -> { overlays.forEach { it.getSize(g, size) if (size.isZero) return@forEach val (ow, oh) = size var x = 0 when (alignment) { CENTER -> x = (w - ow) / 2 RIGHT -> x = w - ow } g.translate(x, 0) it.draw(g, size) g.translate(-x, oh + spacing) } } LEFT -> { g.translate(size.width, 0) overlays.forEach { it.getSize(g, size) if (size.isZero) return@forEach val (ow, oh) = size var y = 0 when (alignment) { CENTER -> y = (h - oh) / 2 DOWN -> y = h - oh } g.translate(-ow, y) it.draw(g, size) g.translate(-spacing, -y) } } RIGHT -> { overlays.forEach { it.getSize(g, size) if (size.isZero) return@forEach val (ow, oh) = size var y = 0 when (alignment) { CENTER -> y = (h - oh) / 2 DOWN -> y = h - oh } g.translate(0, y) it.draw(g, size) g.translate(ow + spacing, -y) } } } g.transform = tx } override fun getSize(g: Graphics2D, result: Dimension) { when (overlays.size) { 0 -> return result.setSize(0, 0) 1 -> return overlays.first().getSize(g, result) } var w = 0 var h = 0 when (direction) { UP, DOWN -> { overlays.forEach { it.getSize(g, result) w = max(w, result.width) h += result.height + spacing } h -= spacing } LEFT, RIGHT -> { overlays.forEach { it.getSize(g, result) w += result.width + spacing h = max(h, result.height) } w -= spacing } } result.setSize(w, h) } private val Dimension.isZero get() = width == 0 && height == 0 }
mit
aa091020703304d4ba21759d29057a38
29.674074
66
0.3843
4.6
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertRangeCheckToTwoComparisonsIntention.kt
1
2611
// 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.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention import org.jetbrains.kotlin.idea.util.RangeKtExpressionType.* import org.jetbrains.kotlin.idea.util.getRangeBinaryExpressionType import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class ConvertRangeCheckToTwoComparisonsIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>( KtBinaryExpression::class.java, KotlinBundle.lazyMessage("convert.to.comparisons") ) { private fun KtExpression?.isSimple() = this is KtConstantExpression || this is KtNameReferenceExpression override fun applyTo(element: KtBinaryExpression, editor: Editor?) { element.replace(convertToComparison(element)?.value ?: return) } override fun isApplicableTo(element: KtBinaryExpression) = convertToComparison(element) != null private fun convertToComparison(element: KtBinaryExpression): Lazy<KtExpression>? { if (element.operationToken != KtTokens.IN_KEYWORD) return null // ignore for-loop. for(x in 1..2) should not be convert to for(1<=x && x<=2) if (element.parent is KtForExpression) return null val rangeExpression = element.right ?: return null val arg = element.left ?: return null val (left, right) = rangeExpression.getArguments() ?: return null val context = lazy { rangeExpression.analyze(BodyResolveMode.PARTIAL) } if (!arg.isSimple() || left?.isSimple() != true || right?.isSimple() != true || setOf(arg.getType(context.value), left.getType(context.value), right.getType(context.value)).size != 1) return null val pattern = when (rangeExpression.getRangeBinaryExpressionType(context)) { RANGE_TO -> "$0 <= $1 && $1 <= $2" UNTIL, RANGE_UNTIL -> "$0 <= $1 && $1 < $2" DOWN_TO -> "$0 >= $1 && $1 >= $2" null -> return null } return lazy { val psiFactory = KtPsiFactory(element.project) psiFactory.createExpressionByPattern(pattern, left, arg, right, reformat = false) } } }
apache-2.0
f42993751733df339c9fc7d55d837d82
49.230769
158
0.716584
4.517301
false
false
false
false
apollographql/apollo-android
apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo3/gradle/api/Service.kt
1
17870
package com.apollographql.apollo3.gradle.api import com.android.build.gradle.api.BaseVariant import com.apollographql.apollo3.annotations.ApolloExperimental import com.apollographql.apollo3.compiler.OperationIdGenerator import com.apollographql.apollo3.compiler.OperationOutputGenerator import com.apollographql.apollo3.compiler.PackageNameGenerator import org.gradle.api.Action import org.gradle.api.Task import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.Directory import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.RegularFile import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.ListProperty import org.gradle.api.provider.MapProperty import org.gradle.api.provider.Property import org.gradle.api.provider.Provider import org.gradle.api.provider.SetProperty import org.gradle.api.tasks.TaskProvider /** * A [Service] represents a GraphQL schema and associated queries. * * The queries will be compiled and verified against the schema to generate the models. */ interface Service { val name: String /** * Operation files to include. * The values are interpreted as in [org.gradle.api.tasks.util.PatternFilterable] * * Default: listOf("**&#47;*.graphql", "**&#47;*.gql") */ val includes: ListProperty<String> /** * Operation files to exclude. * The values are interpreted as in [org.gradle.api.tasks.util.PatternFilterable] * * Default: emptyList() */ val excludes: ListProperty<String> /** * Where to look for GraphQL sources. * The plugin will look in "src/main/graphql/$sourceFolder" for Android/JVM projects and "src/commonMain/graphql/$sourceFolder" for multiplatform projects. * * For more control, see also [srcDir] */ val sourceFolder: Property<String> /** * Adds the given directory as a GraphQL source root * * Use [srcDir] if your files are outside "src/main/graphql" or to have them in multiple folders. * * @param directory the directory where the .graphql operation files are * [directory] is evaluated as in [Project.file](https://docs.gradle.org/current/javadoc/org/gradle/api/Project.html#file-java.lang.Object-) * Valid value include path Strings, File and RegularFileProperty * */ fun srcDir(directory: Any) /** * A shorthand property that will be used if [schemaFiles] is empty */ val schemaFile: RegularFileProperty /** * The schema files as either a ".json" introspection schema or a ".sdl|.graphqls" SDL schema. You might come across schemas named "schema.graphql", * these are SDL schemas most of the time that need to be renamed to "schema.graphqls" to be recognized properly. * * The compiler accepts multiple schema files in order to add extensions to specify key fields and other schema extensions. * * By default, the plugin collects all "schema.[json|sdl|graphqls]" file in the source roots */ val schemaFiles: ConfigurableFileCollection /** * Warn if using a deprecated field * * Default value: true */ val warnOnDeprecatedUsages: Property<Boolean> /** * Fail the build if there are warnings. This is not named `allWarningAsErrors` to avoid nameclashes with the Kotlin options * * Default value: false */ val failOnWarnings: Property<Boolean> /** * For custom scalar types like Date, map from the GraphQL type to the java/kotlin type. * * Default value: the empty map */ val customScalarsMapping: MapProperty<String, String> @Deprecated("customTypeMapping is a helper property to help migrating to 3.x " + "and will be removed in a future version", ReplaceWith("customScalarsMapping")) val customTypeMapping: MapProperty<String, String> /** * By default, Apollo uses `Sha256` hashing algorithm to generate an ID for the query. * To provide a custom ID generation logic, pass an `instance` that implements the [OperationIdGenerator]. How the ID is generated is * indifferent to the compiler. It can be a hashing algorithm or generated by a backend. * * Example Md5 hash generator: * ```groovy * import com.apollographql.apollo3.compiler.OperationIdGenerator * * apollo { * operationIdGenerator = new OperationIdGenerator() { * String apply(String operationDocument, String operationFilepath) { * return operationDocument.md5() * } * * /** * * Use this version override to indicate an update to the implementation. * * This invalidates the current cache. * */ * String version = "v1" * } * } * ``` * * Default value: [OperationIdGenerator.Sha256] */ val operationIdGenerator: Property<OperationIdGenerator> /** * A generator to generate the operation output from a list of operations. * OperationOutputGenerator is similar to [OperationIdGenerator] but can work on lists. This is useful if you need * to register/whitelist your operations on your server all at once. * * Example Md5 hash generator: * ```groovy * import com.apollographql.apollo3.compiler.OperationIdGenerator * * apollo { * operationOutputGenerator = new OperationIdGenerator() { * String apply(List<operation operationDocument, String operationFilepath) { * return operationDocument.md5() * } * * /** * * Use this version override to indicate an update to the implementation. * * This invalidates the current cache. * */ * String version = "v1" * } * } * ``` * * Default value: [OperationIdGenerator.Sha256] */ val operationOutputGenerator: Property<OperationOutputGenerator> /** * When true, the generated classes names will end with 'Query' or 'Mutation'. * If you write `query droid { ... }`, the generated class will be named 'DroidQuery'. * * Default value: true */ val useSemanticNaming: Property<Boolean> /** * The package name of the models. The compiler will generate classes in * * - $packageName/SomeQuery.kt * - $packageName/fragment/SomeFragment.kt * - $packageName/type/CustomScalar.kt * - $packageName/type/SomeInputObject.kt * - $packageName/type/SomeEnum.kt * * Default value: "" */ val packageName: Property<String> /** * Use [packageNameGenerator] to customize how to generate package names from file paths. * * See [PackageNameGenerator] for more details */ val packageNameGenerator: Property<PackageNameGenerator> /** * A helper method to configure a [PackageNameGenerator] that will use the file path * relative to the source roots to generate the packageNames * * @param rootPackageName: a root package name to prepend to the package names * * Example, with the below configuration: * * ``` * srcDir("src/main/graphql") * packageNamesFromFilePaths("com.example") * ``` * * an operation defined in `src/main/graphql/query/feature1` will use `com.example.query.feature1` * as package name * an input object defined in `src/main/graphql/schema/schema.graphqls` will use `com.example.schema.type` * as package name */ fun packageNamesFromFilePaths(rootPackageName: String? = null) /** * Whether to generate Kotlin models with `internal` visibility modifier. * * Default value: false */ val generateAsInternal: Property<Boolean> /** * Whether to generate Apollo metadata. Apollo metadata is used for multi-module support. Set this to true if you want other * modules to be able to re-use fragments and types from this module. * * This is currently experimental and this API might change in the future. * * Default value: false */ val generateApolloMetadata: Property<Boolean> /** * A list of [Regex] patterns for input/scalar/enum types that should be generated whether they are used by queries/fragments * in this module. When using multiple modules, Apollo Kotlin will generate all the types by default in the root module * because the root module doesn't know what types are going to be used by dependent modules. This can be prohibitive in terms * of compilation speed for large projects. If that's the case, opt-in the types that are used by multiple dependent modules here. * You don't need to add types that are used by a single dependent module. * * This is currently experimental and this API might change in the future. * * Default value: if (generateApolloMetadata) listOf(".*") else listOf() */ val alwaysGenerateTypesMatching: SetProperty<String> /** * Whether to generate default implementation classes for GraphQL fragments. * Default value is `false`, means only interfaces are been generated. * * Most of the time, fragment implementations are not needed because you can easily access fragments interfaces and read all * data from your queries. They are needed if you want to be able to build fragments outside an operation. For an exemple * to programmatically build a fragment that is reused in another part of your code or to read and write fragments to the cache. */ val generateFragmentImplementations: Property<Boolean> /** * Whether to generate Kotlin or Java models * Default to true if the Kotlin plugin is found */ val generateKotlinModels: Property<Boolean> /** * Target language version for the generated code. * * Only valid when [generateKotlinModels] is `true` * Must be either "1.4" or "1.5" * * Using an higher languageVersion allows generated code to use more language features like * sealed interfaces in Kotlin 1.5 for an example. * * See also https://kotlinlang.org/docs/gradle.html#attributes-common-to-jvm-and-js * * Default: use the version of the Kotlin plugin. */ val languageVersion: Property<String> /** * Whether to write the query document in models */ val generateQueryDocument: Property<Boolean> /** * Whether to generate the __Schema class. The __Schema class lists all composite * types in order to access __typename and/or possibleTypes */ val generateSchema: Property<Boolean> /** * Whether to generate operation variables as [com.apollographql.apollo3.api.Optional] * * Using [com.apollographql.apollo3.api.Optional] allows to omit the variables if needed but makes the * callsite more verbose in most cases. * * Default: true */ val generateOptionalOperationVariables: Property<Boolean> /** * Whether to generate the type safe Data builders. These are mainly used for tests but can also be used for other use * cases too. * * Only valid when [generateKotlinModels] is true */ @ApolloExperimental val generateTestBuilders: Property<Boolean> /** * What codegen to use. One of "operationBased", "responseBased" or "compat" * * Default value: "compat" */ val codegenModels: Property<String> /** * Whether to flatten the models. File paths are limited on MacOSX to 256 chars and flattening can help keeping the path length manageable * The drawback is that some classes may nameclash in which case they will be suffixed with a number * * Default value: false for "responseBased", true else */ val flattenModels: Property<Boolean> /** * The directory where the generated models will be written. It's called [outputDir] but this an "input" parameter for the compiler * If you want a [DirectoryProperty] that carries the task dependency, use [outputDirConnection] */ val outputDir: DirectoryProperty /** * The directory where the test builders will be written. * If you want a [DirectoryProperty] that carries the task dependency, use [outputDirConnection] */ val testDir: DirectoryProperty /** * Whether to generate the operationOutput.json * * Defaults value: false */ val generateOperationOutput: Property<Boolean> /** * The file where the operation output will be written. It's called [operationOutputFile] but this an "input" parameter for the compiler * If you want a [RegularFileProperty] that carries the task dependency, use [operationOutputConnection] */ val operationOutputFile: RegularFileProperty /** * A debug directory where the compiler will output intermediary results */ val debugDir: DirectoryProperty /** * A list of [Regex] patterns for GraphQL enums that should be generated as Kotlin sealed classes instead of the default Kotlin enums. * * Use this if you want your client to have access to the rawValue of the enum. This can be useful if new GraphQL enums are added but * the client was compiled against an older schema that doesn't have knowledge of the new enums. * * Default: emptyList() */ val sealedClassesForEnumsMatching: ListProperty<String> /** * A shorthand method that configures defaults that match Apollo Android 2.x codegen * * In practice, it does the following: * * ``` * packageNamesFromFilePaths(rootPackageName) * codegenModels.set(MODELS_COMPAT) * ``` * * See the individual options for a more complete description. * * This method is deprecated and provided for migration purposes only. It will be removed * in a future version */ @Deprecated("useVersion2Compat() is a helper function to help migrating to 3.x " + "and will be removed in a future version") fun useVersion2Compat(rootPackageName: String? = null) /** * Configures [Introspection] to download an introspection Json schema */ fun introspection(configure: Action<in Introspection>) /** * Configures [Registry] to download a SDL schema from a studio registry */ fun registry(configure: Action<in Registry>) /** * Configures the [Introspection] */ fun registerOperations(configure: Action<in RegisterOperationsConfig>) /** * overrides the way operationOutput is connected. * Use this if you want to connect the generated operationOutput. For an example * you can use this to send the modified queries to your backend for whitelisting * * By default, operationOutput is not connected */ fun operationOutputConnection(action: Action<in OperationOutputConnection>) class OperationOutputConnection( /** * The task that produces operationOutput */ val task: TaskProvider<out Task>, /** * A json file containing a [Map]<[String], [com.apollographql.apollo3.compiler.operationoutput.OperationDescriptor]> * * This file can be used to upload the queries exact content and their matching operation ID to a server for whitelisting * or persisted queries. */ val operationOutputFile: Provider<RegularFile>, ) /** * Overrides the way the generated models are connected. * Use this if you want to connect the generated models to another task than the default destination. * * By default, the generated sources are connected to: * - main sourceSet for Kotlin projects * - commonMain sourceSet for Kotlin multiplatform projects * - main sourceSet for Android projects */ fun outputDirConnection(action: Action<in DirectoryConnection>) /** * Overrides the way the generated test builders are connected. * Use this if you want to connect the generated test builders to another task than the default destination. * * By default, the generated sources are connected to: * - test sourceSet for Kotlin projects * - commonTest sourceSet for Kotlin multiplatform projects * - test *and* androidTest variants for Android projects */ fun testDirConnection(action: Action<in DirectoryConnection>) /** * A [DirectoryConnection] defines how the generated sources are connected to the rest of the * build. * * It provides helpers for the most common options as well as direct access to an output [Provider] * that will carry task dependency. * * It is valid to call multiple connectXyz() methods to connect the generated sources to multiple * downstream tasks */ interface DirectoryConnection { /** * Connects the generated sources to the given Kotlin source set. * Throws if the Kotlin plugin is not applied * * @param name: the name of the source set. For an example, "commonTest" */ fun connectToKotlinSourceSet(name: String) /** * Connects the generated sources to the given Java source set. * Throws if the Java plugin is not applied * * @param name: the name of the source set. For an example, "test" */ fun connectToJavaSourceSet(name: String) /** * Connects the generated sources to the given Android source set. * Throws if the Android plugin is not applied * * @param name: the name of the source set. For an example, "main", "test" or "androidTest" * You can also use more qualified source sets like "demo", "debug" or "demoDebug" */ fun connectToAndroidSourceSet(name: String) /** * Connects the generated sources to the given Android variant. This will * look up the most specific source set used by this variant. For an example, "demoDebug" * * @param variant: the [BaseVariant] to connect to. It is of type [Any] because [DirectoryConnection] * can be used in non-Android projects, and we don't want the class to fail during loading because * of a missing symbol in that case */ fun connectToAndroidVariant(variant: Any) /** * The directory where the generated models will be written. * This provider carries task dependency information. */ val outputDir: Provider<Directory> /** * The task that produces outputDir. Usually this is not needed as [outputDir] carries * task dependency. */ val task: TaskProvider<out Task> } }
mit
45755ed97ec4e7012c869990115a78bc
35.174089
157
0.711528
4.466383
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/ui/compose/deletefeed/DeleteFeedScreen.kt
1
5325
package com.nononsenseapps.feeder.ui.compose.deletefeed import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredHeightIn import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Checkbox import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.nononsenseapps.feeder.R import com.nononsenseapps.feeder.ui.compose.minimumTouchSize import com.nononsenseapps.feeder.ui.compose.utils.ImmutableHolder import com.nononsenseapps.feeder.ui.compose.utils.immutableListHolderOf @Composable fun DeleteFeedDialog( feeds: ImmutableHolder<List<DeletableFeed>>, onDismiss: () -> Unit, onDelete: (Iterable<Long>) -> Unit ) { var feedsToDelete by rememberSaveable { mutableStateOf(emptyMap<Long, Boolean>()) } DeleteFeedDialog( feeds = feeds, isChecked = { feedId -> feedsToDelete[feedId] ?: false }, onDismiss = onDismiss, onOk = { onDelete(feedsToDelete.filterValues { it }.keys) onDismiss() }, onToggleFeed = { feedId, checked -> feedsToDelete = feedsToDelete + (feedId to (checked ?: !feedsToDelete.contains(feedId))) } ) } @Composable fun DeleteFeedDialog( feeds: ImmutableHolder<List<DeletableFeed>>, isChecked: (Long) -> Boolean, onDismiss: () -> Unit, onOk: () -> Unit, onToggleFeed: (Long, Boolean?) -> Unit ) { AlertDialog( onDismissRequest = onDismiss, confirmButton = { Button(onClick = onOk) { Text(text = stringResource(id = android.R.string.ok)) } }, dismissButton = { Button(onClick = onDismiss) { Text(text = stringResource(id = android.R.string.cancel)) } }, title = { Text( text = stringResource(id = R.string.delete_feed), style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.Center, modifier = Modifier .padding(vertical = 8.dp) ) }, text = { LazyColumn( modifier = Modifier.fillMaxWidth() ) { items(feeds.item) { feed -> val stateLabel = if (isChecked(feed.id)) { stringResource(R.string.selected) } else { stringResource(R.string.not_selected) } Row( horizontalArrangement = Arrangement.Start, verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .requiredHeightIn(min = minimumTouchSize) .clickable { onToggleFeed(feed.id, !isChecked(feed.id)) } .semantics(mergeDescendants = true) { stateDescription = stateLabel } ) { Checkbox( checked = isChecked(feed.id), onCheckedChange = { checked -> onToggleFeed(feed.id, checked) }, modifier = Modifier.clearAndSetSemantics { } ) Spacer(modifier = Modifier.width(8.dp)) Text( text = feed.title, style = MaterialTheme.typography.titleMedium ) } } } } ) } @Immutable data class DeletableFeed( val id: Long, val title: String ) @Composable @Preview private fun preview() = DeleteFeedDialog( feeds = immutableListHolderOf( DeletableFeed(1, "A Feed"), DeletableFeed(2, "Another Feed") ), onDismiss = {}, onDelete = {} )
gpl-3.0
db3a67fb2226e1b8c4c6862b1c2b3092
34.264901
100
0.58892
5.185005
false
false
false
false
allotria/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/AbstractProjectModuleOperationProvider.kt
1
3976
package com.jetbrains.packagesearch.intellij.plugin.extensibility import com.intellij.buildsystem.model.OperationFailure import com.intellij.buildsystem.model.OperationItem import com.intellij.buildsystem.model.OperationType import com.intellij.buildsystem.model.unified.UnifiedDependency import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository import com.intellij.externalSystem.DependencyModifierService import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile abstract class AbstractProjectModuleOperationProvider : ProjectModuleOperationProvider { override fun addDependenciesToProject( operationMetadata: DependencyOperationMetadata, project: Project, virtualFile: VirtualFile ): List<OperationFailure<out OperationItem>> { val dependency = UnifiedDependency(operationMetadata.groupId, operationMetadata.artifactId, operationMetadata.version, operationMetadata.scope) try { DependencyModifierService.getInstance(project).declaredDependencies(operationMetadata.module.nativeModule) .firstOrNull { it.coordinates.groupId == dependency.coordinates.groupId && it.coordinates.artifactId == dependency.coordinates.artifactId } ?.also { DependencyModifierService.getInstance(project).updateDependency(operationMetadata.module.nativeModule, it.unifiedDependency, dependency) } ?: DependencyModifierService.getInstance(project).addDependency(operationMetadata.module.nativeModule, dependency) return emptyList() } catch (e: Exception) { return listOf(OperationFailure(OperationType.ADD, dependency, e)) } } override fun removeDependenciesFromProject( operationMetadata: DependencyOperationMetadata, project: Project, virtualFile: VirtualFile ): List<OperationFailure<out OperationItem>> { val dependency = UnifiedDependency(operationMetadata.groupId, operationMetadata.artifactId, operationMetadata.version, operationMetadata.scope) try { DependencyModifierService.getInstance(project).removeDependency(operationMetadata.module.nativeModule, dependency) return emptyList() } catch (e: Exception) { return listOf(OperationFailure(OperationType.REMOVE, dependency, e)) } } override fun listDependenciesInProject(project: Project, virtualFile: VirtualFile): Collection<UnifiedDependency> { val module = ModuleUtilCore.findModuleForFile(virtualFile, project) return module?.let { DependencyModifierService.getInstance(project).declaredDependencies(it).map { dep -> dep.unifiedDependency } } ?: emptyList() } @Suppress("ComplexMethod") override fun addRepositoriesToProject( repository: UnifiedDependencyRepository, project: Project, virtualFile: VirtualFile ): List<OperationFailure<out OperationItem>> { val module = ModuleUtilCore.findModuleForFile(virtualFile, project) if(module == null) { return listOf(OperationFailure(OperationType.ADD, repository, IllegalArgumentException())); } try { DependencyModifierService.getInstance(project).addRepository(module, repository) return emptyList() } catch (e: Exception) { return listOf(OperationFailure(OperationType.ADD, repository, e)) } } override fun listRepositoriesInProject(project: Project, virtualFile: VirtualFile): Collection<UnifiedDependencyRepository> { val module = ModuleUtilCore.findModuleForFile(virtualFile, project) return module?.let { DependencyModifierService.getInstance(project).declaredRepositories(it) } ?: emptyList() } }
apache-2.0
70eb1c129dbc4dbb5e82b0f8d526d2a0
40.852632
147
0.720573
5.943199
false
false
false
false
Skatteetaten/boober
src/main/kotlin/no/skatteetaten/aurora/boober/feature/ApplicationDeploymentFeature.kt
1
7918
package no.skatteetaten.aurora.boober.feature import com.fkorotkov.kubernetes.newObjectMeta import com.fkorotkov.kubernetes.newOwnerReference import io.fabric8.kubernetes.api.model.EnvVar import no.skatteetaten.aurora.boober.model.AuroraConfigFieldHandler import no.skatteetaten.aurora.boober.model.AuroraConfigFile import no.skatteetaten.aurora.boober.model.AuroraContextCommand import no.skatteetaten.aurora.boober.model.AuroraDeploymentSpec import no.skatteetaten.aurora.boober.model.AuroraResource import no.skatteetaten.aurora.boober.model.addEnvVarsToMainContainers import no.skatteetaten.aurora.boober.model.findSubKeys import no.skatteetaten.aurora.boober.model.findSubKeysExpanded import no.skatteetaten.aurora.boober.model.openshift.ApplicationDeployment import no.skatteetaten.aurora.boober.model.openshift.ApplicationDeploymentCommand import no.skatteetaten.aurora.boober.model.openshift.ApplicationDeploymentSpec import no.skatteetaten.aurora.boober.model.openshift.Notification import no.skatteetaten.aurora.boober.model.openshift.NotificationType import no.skatteetaten.aurora.boober.service.AuroraDeploymentSpecValidationException import no.skatteetaten.aurora.boober.utils.Instants import no.skatteetaten.aurora.boober.utils.addIfNotNull import no.skatteetaten.aurora.boober.utils.boolean import no.skatteetaten.aurora.boober.utils.durationString import no.skatteetaten.aurora.boober.utils.normalizeLabels import org.springframework.boot.convert.DurationStyle.SIMPLE import org.springframework.stereotype.Service import java.time.Duration import java.util.regex.Pattern import java.util.regex.Pattern.compile val AuroraDeploymentSpec.ttl: Duration? get() = this.getOrNull<String>("ttl")?.let { SIMPLE.parse(it) } private const val APPLICATION_DEPLOYMENT_COMMAND_CONTEXT_KEY = "applicationDeploymentCommand" private val FeatureContext.applicationDeploymentCommand: ApplicationDeploymentCommand get() = this.getContextKey( APPLICATION_DEPLOYMENT_COMMAND_CONTEXT_KEY ) val emailRegex: Pattern = compile( "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\@" + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\." + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+" ) const val emailNotificationsField = "notification/email" const val mattermostNotificationsField = "notification/mattermost" @Service class ApplicationDeploymentFeature : Feature { override fun handlers(header: AuroraDeploymentSpec, cmd: AuroraContextCommand): Set<AuroraConfigFieldHandler> { return setOf( AuroraConfigFieldHandler("message"), AuroraConfigFieldHandler("ttl", validator = { it.durationString() }) ) + findAllNotificationHandlers(cmd.applicationFiles) } override fun validate( adc: AuroraDeploymentSpec, fullValidation: Boolean, context: FeatureContext ): List<Exception> { return adc.getSubKeyValues(emailNotificationsField).mapNotNull { email -> if (!emailRegex.matcher(email).matches()) { AuroraDeploymentSpecValidationException("Email address '$email' is not a valid email address.") } else null } } override fun createContext(spec: AuroraDeploymentSpec, cmd: AuroraContextCommand, validationContext: Boolean): Map<String, Any> { return mapOf( APPLICATION_DEPLOYMENT_COMMAND_CONTEXT_KEY to ApplicationDeploymentCommand( cmd.overrideFiles, cmd.applicationDeploymentRef, cmd.auroraConfigRef ) ) } override fun generate(adc: AuroraDeploymentSpec, context: FeatureContext): Set<AuroraResource> { val ttl = adc.ttl?.let { val removeInstant = Instants.now + it "removeAfter" to removeInstant.epochSecond.toString() } val resource = ApplicationDeployment( spec = ApplicationDeploymentSpec( selector = mapOf("name" to adc.name), updatedAt = Instants.now.toString(), message = adc.getOrNull("message"), applicationDeploymentName = adc.name, applicationDeploymentId = adc.applicationDeploymentId, command = context.applicationDeploymentCommand, notifications = adc.findNotifications() ), _metadata = newObjectMeta { name = adc.name namespace = adc.namespace labels = mapOf("id" to adc.applicationDeploymentId).addIfNotNull(ttl).normalizeLabels() } ) return setOf(generateResource(resource)) } private fun AuroraDeploymentSpec.isNotificationLocationEnabled(notificationLocationField: String) = this.getOrNull<Boolean>(notificationLocationField) ?: this["$notificationLocationField/enabled"] private fun findAllNotificationHandlers(applicationFiles: List<AuroraConfigFile>): Set<AuroraConfigFieldHandler> { val mattermostHandlers = applicationFiles.findNotificationHandlers(mattermostNotificationsField) val emailHandlers = applicationFiles.findNotificationHandlers(emailNotificationsField) return emailHandlers + mattermostHandlers } private fun List<AuroraConfigFile>.findNotificationHandlers(notificationField: String) = this.findSubKeysExpanded(notificationField).flatMap { this.findNotificationHandler(it) }.toSet() private fun List<AuroraConfigFile>.findNotificationHandler( notificationLocationKey: String ): List<AuroraConfigFieldHandler> { val expandedMattermostKeys = this.findSubKeys(notificationLocationKey) return if (expandedMattermostKeys.isEmpty()) listOf( AuroraConfigFieldHandler( notificationLocationKey, validator = { it.boolean() } ) ) else listOf( AuroraConfigFieldHandler( "$notificationLocationKey/enabled", validator = { it.boolean() }, defaultValue = true ) ) } private fun AuroraDeploymentSpec.findNotificationsByType( field: String, type: NotificationType ): List<Notification> = this.getSubKeyValues(field).filter { isNotificationLocationEnabled(notificationLocationField = "$field/$it") }.map { Notification(it, type) } private fun AuroraDeploymentSpec.findNotifications(): Set<Notification>? { val notifications = this.findNotificationsByType(emailNotificationsField, NotificationType.Email) + this.findNotificationsByType(mattermostNotificationsField, NotificationType.Mattermost) if (notifications.isEmpty()) { return null } return notifications.toSet() } override fun modify( adc: AuroraDeploymentSpec, resources: Set<AuroraResource>, context: FeatureContext ) { resources.addEnvVarsToMainContainers( listOf( EnvVar("APPLICATION_DEPLOYMENT_ID", adc.applicationDeploymentId, null) ), this::class.java ) resources.forEach { if (it.resource.metadata.namespace != null && it.resource.kind !in listOf( "ApplicationDeployment", "RoleBinding", "PersistentVolumeClaim" ) ) { modifyResource(it, "Set owner reference to ApplicationDeployment") it.resource.metadata.ownerReferences = listOf( newOwnerReference { apiVersion = "skatteetaten.no/v1" kind = "ApplicationDeployment" name = adc.name uid = "123-123" } ) } } } }
apache-2.0
f31fdd7ec2b07304d692304095f972b7
39.605128
133
0.676181
5.121604
false
true
false
false
sdeleuze/mixit
src/main/kotlin/mixit/repository/TalkRepository.kt
1
2187
package mixit.repository import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import mixit.model.Talk import org.springframework.core.io.ClassPathResource import org.springframework.data.mongodb.core.ReactiveMongoTemplate import org.springframework.data.mongodb.core.query.Query import org.springframework.stereotype.Repository import reactor.core.publisher.Flux import mixit.util.* import org.slf4j.LoggerFactory import org.springframework.data.domain.Sort.* import org.springframework.data.domain.Sort.Direction.* import org.springframework.data.mongodb.core.query.Criteria.* @Repository class TalkRepository(val template: ReactiveMongoTemplate, val objectMapper: ObjectMapper) { private val logger = LoggerFactory.getLogger(this.javaClass) fun initData() { if (count().block() == 0L) { listOf(2012, 2013, 2014, 2015, 2016, 2017).forEach { year -> val talksResource = ClassPathResource("data/talks_$year.json") val talks: List<Talk> = objectMapper.readValue(talksResource.inputStream) talks.forEach { save(it).block() } } logger.info("Talks data initialization complete") } } fun count() = template.count<Talk>() fun findByEvent(eventId: String, topic: String? = null): Flux<Talk> { val criteria = where("event").`is`(eventId) if (topic != null) criteria.and("topic").`is`(topic) return template.find<Talk>(Query(criteria).with(by(Order(ASC, "start")))) } fun findAll(): Flux<Talk> = template.find<Talk>(Query().with(by(Order(ASC, "start")))) fun findOne(id: String) = template.findById<Talk>(id) fun findBySlug(slug: String) = template.findOne<Talk>(Query(where("slug").`is`(slug))) fun findByEventAndSlug(eventId: String, slug: String) = template.findOne<Talk>(Query(where("slug").`is`(slug).and("event").`is`(eventId))) fun deleteAll() = template.remove<Talk>(Query()) fun deleteOne(id: String) = template.remove<Talk>(Query(where("_id").`is`(id))) fun save(talk: Talk) = template.save(talk) }
apache-2.0
37486af399a2e5ab0f2cf806901c878f
35.45
94
0.683585
4.027624
false
false
false
false
code-helix/slatekit
src/apps/kotlin/slatekit-samples/src/main/kotlin/slatekit/samples/app/App.kt
1
2388
package slatekit.samples.app import slatekit.app.App import slatekit.app.AppOptions import slatekit.common.DateTimes import slatekit.context.Context import slatekit.common.args.ArgsSchema import slatekit.common.utils.B64Java8 import slatekit.common.crypto.Encryptor import slatekit.common.info.About /** * Slate Kit Application template * This provides support for command line args, environment selection, confs, life-cycle methods and help usage * @see https://www.slatekit.com/arch/app/ */ class App(ctx: Context) : App<Context>(ctx, AppOptions(showWelcome = true)) { companion object { // setup the command line arguments. // NOTE: // 1. These values can can be setup in the env.conf file // 2. If supplied on command line, they override the values in .conf file // 3. If any of these are required and not supplied, then an error is display and program exists // 4. Help text can be easily built from this schema. val schema = ArgsSchema() .text("","env", "the environment to run in", false, "dev", "dev", "dev1|qa1|stg1|pro") .text("","log.level", "the log level for logging", false, "info", "info", "debug|info|warn|error") /** * Default static info about the app. * This can be overriden in your env.conf file */ val about = About( company = "slatekit", area = "samples", name = "app", desc = "Sample Console Application with command line args, environments, logs, and help docs", region = "", url = "myapp.url", contact = "", tags = "app", examples = "" ) /** * Encryption support */ val encryptor = Encryptor("aksf2409bklja24b", "k3l4lkdfaoi97042", B64Java8) } override suspend fun init() { println("initializing") } override suspend fun exec(): Any? { val logger = ctx.logs.getLogger("app") val values = listOf("a" to 1, "b" to true, "c" to "kotlin", "d" to DateTimes.now()) logger.warn("test warn", values) println("executing") println("Your work should be done here...") return OK } override suspend fun done(result:Any?) { println("ending") } }
apache-2.0
83e722e6bf626df70b4874ceac49aad4
31.283784
114
0.595059
4.21164
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/openapi/roots/ui/distribution/FileChooserInfo.kt
9
1041
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.roots.ui.distribution import com.intellij.ide.macro.Macro import com.intellij.ide.macro.MacrosDialog import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.util.NlsContexts interface FileChooserInfo { val fileChooserTitle: @NlsContexts.DialogTitle String? val fileChooserDescription: @NlsContexts.Label String? val fileChooserDescriptor: FileChooserDescriptor val fileChooserMacroFilter: ((Macro) -> Boolean)? companion object { val ALL = { it: Macro -> MacrosDialog.Filters.ALL.test(it) } val NONE = { it: Macro -> MacrosDialog.Filters.NONE.test(it) } val ANY_PATH = { it: Macro -> MacrosDialog.Filters.ANY_PATH.test(it) } val DIRECTORY_PATH = { it: Macro -> MacrosDialog.Filters.DIRECTORY_PATH.test(it) } val FILE_PATH = { it: Macro -> MacrosDialog.Filters.FILE_PATH.test(it) } } }
apache-2.0
a4d2e5ab82562992b5c98b24b15776f9
46.363636
158
0.757925
3.988506
false
true
false
false
smmribeiro/intellij-community
platform/lang-api/src/com/intellij/refactoring/suggested/SuggestedRefactoringStateChanges.kt
4
8167
// 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.refactoring.suggested import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.refactoring.suggested.SuggestedRefactoringState.ErrorLevel import com.intellij.refactoring.suggested.SuggestedRefactoringState.ParameterMarker import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Signature /** * A service transforming a sequence of declaration states into [SuggestedRefactoringState]. */ abstract class SuggestedRefactoringStateChanges(protected val refactoringSupport: SuggestedRefactoringSupport) { /** * Extracts information from declaration and stores it in an instance of [Signature] class. * * For performance reasons, don't use any resolve in this method. More accurate information about changes can be obtained later * with use of [SuggestedRefactoringAvailability.refineSignaturesWithResolve]. * @param declaration declaration in its current state. * Only PsiElement's that are classified as declarations by [SuggestedRefactoringSupport.isDeclaration] may be passed to this parameter. * @param prevState previous state of accumulated signature changes, or *null* if the user is just about to start editing the signature. * @return An instance of [Signature] class, representing the current state of the declaration, * or *null* if the declaration is in an incorrect state and no signature can be created. */ abstract fun signature(declaration: PsiElement, prevState: SuggestedRefactoringState?): Signature? /** * Provides "marker ranges" for parameters in the declaration. * * Marker ranges are used to keep track of parameter identity when its name changes. * A good marker range must have high chances of staying the same while editing the signature (with help of a [RangeMarker], of course). * If the language has a fixed separator between parameter name and type such as ':' - use it as a marker. * A whitespace between the type and the name is not so reliable because it may change its length or temporarily disappear. * Parameter type range is also a good marker because it's unlikely to change at the same time as the name changes. * @param declaration declaration in its current state. * Only PsiElement's that are classified as declarations by [SuggestedRefactoringSupport.isDeclaration] may be passed to this parameter. * @return a list containing a marker range for each parameter, or *null* if no marker can be provided for this parameter */ abstract fun parameterMarkerRanges(declaration: PsiElement): List<TextRange?> open fun createInitialState(declaration: PsiElement): SuggestedRefactoringState? { val signature = signature(declaration, null) ?: return null val signatureRange = refactoringSupport.signatureRange(declaration) ?: return null val psiDocumentManager = PsiDocumentManager.getInstance(declaration.project) val file = declaration.containingFile val document = psiDocumentManager.getDocument(file)!! require(psiDocumentManager.isCommitted(document)) return SuggestedRefactoringState( declaration, refactoringSupport, errorLevel = ErrorLevel.NO_ERRORS, oldDeclarationText = document.getText(signatureRange), oldImportsText = refactoringSupport.importsRange(file) ?.extendWithWhitespace(document.charsSequence) ?.let { document.getText(it) }, oldSignature = signature, newSignature = signature, parameterMarkers = parameterMarkers(declaration, signature) ) } open fun updateState(state: SuggestedRefactoringState, declaration: PsiElement): SuggestedRefactoringState { val newSignature = signature(declaration, state) ?: return state.withDeclaration(declaration).withErrorLevel(ErrorLevel.SYNTAX_ERROR) val idsPresent = newSignature.parameters.map { it.id }.toSet() val disappearedParameters = state.disappearedParameters.entries .filter { (_, id) -> id !in idsPresent } .associate { it.key to it.value } .toMutableMap() for ((id, name) in state.newSignature.parameters) { if (id !in idsPresent && state.oldSignature.parameterById(id) != null) { disappearedParameters[name] = id // one more parameter disappeared } } val parameterMarkers = parameterMarkers(declaration, newSignature).toMutableList() val syntaxError = refactoringSupport.hasSyntaxError(declaration) if (syntaxError) { // when there is a syntax error inside the signature, there can be parameters which are temporarily not parsed as parameters // we must keep their markers in order to match them later for (marker in state.parameterMarkers) { if (marker.rangeMarker.isValid && newSignature.parameterById(marker.parameterId) == null) { parameterMarkers += marker } } } return state .withDeclaration(declaration) .withNewSignature(newSignature) .withErrorLevel(if (syntaxError) ErrorLevel.SYNTAX_ERROR else ErrorLevel.NO_ERRORS) .withParameterMarkers(parameterMarkers) .withDisappearedParameters(disappearedParameters) } protected fun matchParametersWithPrevState( signature: Signature, newDeclaration: PsiElement, prevState: SuggestedRefactoringState ): Signature { // first match all parameters by names (in prevState or in the history of changes) val ids = signature.parameters.map { guessParameterIdByName(it, prevState) }.toMutableList() // now match those that we could not match by name via marker ranges val markerRanges = parameterMarkerRanges(newDeclaration) for (index in signature.parameters.indices) { val markerRange = markerRanges[index] if (ids[index] == null && markerRange != null) { val id = guessParameterIdByMarkers(markerRange, prevState) if (id != null && id !in ids) { ids[index] = id } } } val newParameters = signature.parameters.zip(ids) { parameter, id -> parameter.copy(id = id ?: Any()/*new id*/) } return Signature.create(signature.name, signature.type, newParameters, signature.additionalData)!! } protected fun guessParameterIdByName(parameter: SuggestedRefactoringSupport.Parameter, prevState: SuggestedRefactoringState): Any? { prevState.newSignature.parameterByName(parameter.name) ?.let { return it.id } prevState.disappearedParameters[parameter.name] ?.let { return it } return null } protected open fun guessParameterIdByMarkers(markerRange: TextRange, prevState: SuggestedRefactoringState): Any? { return prevState.parameterMarkers.firstOrNull { it.rangeMarker.range == markerRange }?.parameterId } /** * Use this implementation of [SuggestedRefactoringStateChanges], if only Rename refactoring is supported for the language. */ class RenameOnly(refactoringSupport: SuggestedRefactoringSupport) : SuggestedRefactoringStateChanges(refactoringSupport) { override fun signature(declaration: PsiElement, prevState: SuggestedRefactoringState?): Signature? { val name = (declaration as? PsiNamedElement)?.name ?: return null return Signature.create(name, null, emptyList(), null)!! } override fun parameterMarkerRanges(declaration: PsiElement): List<TextRange?> { return emptyList() } } } fun SuggestedRefactoringStateChanges.parameterMarkers(declaration: PsiElement, signature: Signature): List<ParameterMarker> { val document = PsiDocumentManager.getInstance(declaration.project).getDocument(declaration.containingFile)!! val markerRanges = parameterMarkerRanges(declaration) require(markerRanges.size == signature.parameters.size) return markerRanges.zip(signature.parameters) .mapNotNull { (range, parameter) -> range?.let { ParameterMarker(document.createRangeMarker(it), parameter.id) } } }
apache-2.0
a450dbde27a360876557c9e52ce8c9ca
49.104294
140
0.751071
5.025846
false
false
false
false
smmribeiro/intellij-community
platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/avatar/CachingAvatarIconsProvider.kt
2
1557
// 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.collaboration.ui.codereview.avatar import com.github.benmanes.caffeine.cache.Caffeine import com.intellij.execution.process.ProcessIOExecutorService import com.intellij.ui.ScalingAsyncImageIcon import com.intellij.util.IconUtil import com.intellij.util.concurrency.AppExecutorUtil import java.awt.Image import java.time.Duration import java.time.temporal.ChronoUnit import java.util.concurrent.CompletableFuture import javax.swing.Icon abstract class CachingAvatarIconsProvider<T : Any>(private val defaultIcon: Icon) : AvatarIconsProvider<T> { private val iconsCache = Caffeine.newBuilder() .expireAfterAccess(Duration.of(5, ChronoUnit.MINUTES)) .build<Pair<T, Int>, Icon> { (key, size) -> ScalingAsyncImageIcon( size, defaultIcon, imageLoader = { CompletableFuture<Image?>().completeAsync({ loadImage(key) }, avatarLoadingExecutor) } ) } override fun getIcon(key: T?, iconSize: Int): Icon { if (key == null) return IconUtil.resizeSquared(defaultIcon, iconSize) return iconsCache.get(key to iconSize)!! } protected abstract fun loadImage(key: T): Image? companion object { internal val avatarLoadingExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor( "Collaboration Tools avatars loading executor", ProcessIOExecutorService.INSTANCE, 3 ) } }
apache-2.0
d748036e81c0eee7728aa9814d323f49
33.622222
140
0.7386
4.539359
false
false
false
false
Pattonville-App-Development-Team/Android-App
app/src/androidTest/java/org/pattonvillecs/pattonvilleapp/service/repository/news/NewsRepositoryTest.kt
1
3921
/* * Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ @file:Suppress("TestFunctionName") package org.pattonvillecs.pattonvilleapp.service.repository.news import android.arch.persistence.room.Room import android.support.test.InstrumentationRegistry import android.support.test.filters.MediumTest import android.support.test.runner.AndroidJUnit4 import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.hasSize import com.natpryce.hamkrest.should.shouldMatch import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.pattonvillecs.pattonvilleapp.service.model.DataSource import org.pattonvillecs.pattonvilleapp.service.model.news.ArticleSummary import org.pattonvillecs.pattonvilleapp.service.repository.AppDatabase import org.pattonvillecs.pattonvilleapp.service.repository.awaitValue import org.threeten.bp.Instant /** * Tests adding and removing articles from an in-memory database. * * @author Mitchell Skaggs * @since 1.4.0 */ @Suppress("TestFunctionName") @RunWith(AndroidJUnit4::class) @MediumTest class NewsRepositoryTest { private lateinit var appDatabase: AppDatabase private lateinit var newsRepository: NewsRepository @Before fun createDb() { val context = InstrumentationRegistry.getTargetContext() appDatabase = AppDatabase.init(Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)).build() newsRepository = NewsRepository(appDatabase) } @After fun closeDb() { appDatabase.close() } @Test fun Given_SourcedArticleSummary_When_UpsertAllCalled_Then_ReturnSameSourcedArticleSummary() { val sourcedArticleSummary = testSourcedArticleSummary() newsRepository.updateArticles(sourcedArticleSummary) val result = newsRepository.getArticlesByDataSources(DataSource.DISTRICT).awaitValue() result shouldMatch hasSize(equalTo(1)) result[0] shouldMatch equalTo(sourcedArticleSummary) } @Test fun Given_SourcedArticleSummaries_When_UpsertAllCalled_Then_ReturnSameSourcedArticleSummariesInCorrectOrder() { val sourcedArticleSummaryOlder = testSourcedArticleSummary(guid = "test_guid_old", pubDate = Instant.ofEpochMilli(0)) val sourcedArticleSummaryNewer = testSourcedArticleSummary(guid = "test_guid_new", pubDate = Instant.ofEpochMilli(1)) newsRepository.updateArticles(sourcedArticleSummaryOlder, sourcedArticleSummaryNewer) val result = newsRepository.getArticlesByDataSources(DataSource.DISTRICT).awaitValue() result shouldMatch hasSize(equalTo(2)) result shouldMatch equalTo(listOf(sourcedArticleSummaryNewer, sourcedArticleSummaryOlder)) } private fun testSourcedArticleSummary(title: String = "test_title", link: String = "test_link", pubDate: Instant = Instant.ofEpochMilli(0), guid: String = "test_guid", dataSource: DataSource = DataSource.DISTRICT): ArticleSummary { return ArticleSummary(title, link, pubDate, guid, dataSource) } }
gpl-3.0
173cf2532449753f61c219e8a0e1bc28
39.43299
125
0.740627
4.673421
false
true
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/math/spatial/KdTree.kt
1
3357
package de.fabmax.kool.math.spatial import de.fabmax.kool.math.MutableVec3f import de.fabmax.kool.math.partition /** * @author fabmax */ open class KdTree<T: Any>(items: List<T>, itemAdapter: ItemAdapter<T>, bucketSz: Int = 10) : SpatialTree<T>(itemAdapter) { override val root: KdNode override val size: Int get() = items.size private val items = MutableList(items.size, items::get) private val cmpX: (T, T) -> Int = { a, b -> itemAdapter.getMinX(a).compareTo(itemAdapter.getMinX(b)) } private val cmpY: (T, T) -> Int = { a, b -> itemAdapter.getMinY(a).compareTo(itemAdapter.getMinY(b)) } private val cmpZ: (T, T) -> Int = { a, b -> itemAdapter.getMinZ(a).compareTo(itemAdapter.getMinZ(b)) } init { @Suppress("LeakingThis") root = KdNode(items.indices, bucketSz) } override fun contains(element: T) = root.contains(element) override fun containsAll(elements: Collection<T>): Boolean { for (elem in elements) { if (!contains(elem)) { return false } } return true } override fun isEmpty() = items.isEmpty() override fun iterator() = items.iterator() inner class KdNode(override val nodeRange: IntRange, bucketSz: Int) : Node() { override val children = mutableListOf<KdNode>() override val size: Int override val items: List<T> get() = [email protected] init { val tmpVec = MutableVec3f() size = nodeRange.last - nodeRange.first + 1 bounds.batchUpdate { for (i in nodeRange) { val it = items[i] add(itemAdapter.getMin(it, tmpVec)) add(itemAdapter.getMax(it, tmpVec)) } } if (nodeRange.last - nodeRange.first > bucketSz) { var cmp = cmpX if (bounds.size.y > bounds.size.x && bounds.size.y > bounds.size.z) { cmp = cmpY } else if (bounds.size.z > bounds.size.x && bounds.size.z > bounds.size.y) { cmp = cmpZ } val k = nodeRange.first + (nodeRange.last - nodeRange.first) / 2 [email protected](nodeRange, k, cmp) children.add(KdNode(nodeRange.first..k, bucketSz)) children.add(KdNode((k+1)..nodeRange.last, bucketSz)) } else { // this is a leaf node for (i in nodeRange) { itemAdapter.setNode(items[i], this) } } } fun contains(item: T): Boolean { if (isLeaf) { for (i in nodeRange) { if (items[i] == item) { return true } } return false } else { return when { children[0].bounds.contains(itemAdapter.getMinX(item), itemAdapter.getMinY(item), itemAdapter.getMinZ(item)) -> children[0].contains(item) children[1].bounds.contains(itemAdapter.getMinX(item), itemAdapter.getMinY(item), itemAdapter.getMinZ(item)) -> children[1].contains(item) else -> false } } } } }
apache-2.0
eb79b55d09ef02add852902855b750f1
33.255102
158
0.526661
4.064165
false
false
false
false
MilosKozak/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt
3
17745
package info.nightscout.androidaps.plugins.constraints.objectives import android.graphics.Color import android.os.Bundle import android.os.Handler import android.os.Looper import android.os.SystemClock import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import android.widget.LinearLayout import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearSmoothScroller import androidx.recyclerview.widget.RecyclerView import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.constraints.objectives.activities.ObjectivesExamDialog import info.nightscout.androidaps.plugins.constraints.objectives.dialogs.NtpProgressDialog import info.nightscout.androidaps.plugins.constraints.objectives.events.EventNtpStatus import info.nightscout.androidaps.plugins.constraints.objectives.events.EventObjectivesUpdateGui import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective.ExamTask import info.nightscout.androidaps.receivers.NetworkChangeReceiver import info.nightscout.androidaps.setupwizard.events.EventSWUpdate import info.nightscout.androidaps.utils.* import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.objectives_fragment.* import org.slf4j.LoggerFactory class ObjectivesFragment : Fragment() { private val log = LoggerFactory.getLogger(L.CONSTRAINTS) private val objectivesAdapter = ObjectivesAdapter() private val handler = Handler(Looper.getMainLooper()) private var disposable: CompositeDisposable = CompositeDisposable() private val objectiveUpdater = object : Runnable { override fun run() { handler.postDelayed(this, (60 * 1000).toLong()) updateGUI() } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.objectives_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) objectives_recyclerview.layoutManager = LinearLayoutManager(view.context) objectives_recyclerview.adapter = objectivesAdapter objectives_fake.setOnClickListener { updateGUI() } objectives_reset.setOnClickListener { ObjectivesPlugin.reset() objectives_recyclerview.adapter?.notifyDataSetChanged() scrollToCurrentObjective() } scrollToCurrentObjective() startUpdateTimer() } @Synchronized override fun onResume() { super.onResume() disposable.add(RxBus .toObservable(EventObjectivesUpdateGui::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ objectives_recyclerview.adapter?.notifyDataSetChanged() }, { FabricPrivacy.logException(it) }) ) } @Synchronized override fun onPause() { super.onPause() disposable.clear() } @Synchronized override fun onDestroyView() { super.onDestroyView() handler.removeCallbacks(objectiveUpdater) } private fun startUpdateTimer() { handler.removeCallbacks(objectiveUpdater) for (objective in ObjectivesPlugin.objectives) { if (objective.isStarted && !objective.isAccomplished) { val timeTillNextMinute = (System.currentTimeMillis() - objective.startedOn) % (60 * 1000) handler.postDelayed(objectiveUpdater, timeTillNextMinute) break } } } private fun scrollToCurrentObjective() { activity?.runOnUiThread { for (i in 0 until ObjectivesPlugin.objectives.size) { val objective = ObjectivesPlugin.objectives[i] if (!objective.isStarted || !objective.isAccomplished) { context?.let { val smoothScroller = object : LinearSmoothScroller(it) { override fun getVerticalSnapPreference(): Int = SNAP_TO_START override fun calculateTimeForScrolling(dx: Int): Int = super.calculateTimeForScrolling(dx) * 4 } smoothScroller.targetPosition = i objectives_recyclerview.layoutManager?.startSmoothScroll(smoothScroller) } break } } } } private inner class ObjectivesAdapter : RecyclerView.Adapter<ObjectivesAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.objectives_item, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val objective = ObjectivesPlugin.objectives[position] holder.title.text = MainApp.gs(R.string.nth_objective, position + 1) if (objective.objective != 0) { holder.objective.visibility = View.VISIBLE holder.objective.text = MainApp.gs(objective.objective) } else holder.objective.visibility = View.GONE if (objective.gate != 0) { holder.gate.visibility = View.VISIBLE holder.gate.text = MainApp.gs(objective.gate) } else holder.gate.visibility = View.GONE if (!objective.isStarted) { holder.gate.setTextColor(-0x1) holder.verify.visibility = View.GONE holder.progress.visibility = View.GONE holder.accomplished.visibility = View.GONE holder.unFinish.visibility = View.GONE holder.unStart.visibility = View.GONE if (position == 0 || ObjectivesPlugin.objectives[position - 1].isAccomplished) holder.start.visibility = View.VISIBLE else holder.start.visibility = View.GONE } else if (objective.isAccomplished) { holder.gate.setTextColor(-0xb350b0) holder.verify.visibility = View.GONE holder.progress.visibility = View.GONE holder.start.visibility = View.GONE holder.accomplished.visibility = View.VISIBLE holder.unFinish.visibility = View.VISIBLE holder.unStart.visibility = View.GONE } else if (objective.isStarted) { holder.gate.setTextColor(-0x1) holder.verify.visibility = View.VISIBLE holder.verify.isEnabled = objective.isCompleted || objectives_fake.isChecked holder.start.visibility = View.GONE holder.accomplished.visibility = View.GONE holder.unFinish.visibility = View.GONE holder.unStart.visibility = View.VISIBLE holder.progress.visibility = View.VISIBLE holder.progress.removeAllViews() for (task in objective.tasks) { if (task.shouldBeIgnored()) continue // name val name = TextView(holder.progress.context) name.text = MainApp.gs(task.task) + ":" name.setTextColor(-0x1) holder.progress.addView(name, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) // hint task.hints.forEach { h -> if (!task.isCompleted) holder.progress.addView(h.generate(context)) } // state val state = TextView(holder.progress.context) state.setTextColor(-0x1) val basicHTML = "<font color=\"%1\$s\"><b>%2\$s</b></font>" val formattedHTML = String.format(basicHTML, if (task.isCompleted) "#4CAF50" else "#FF9800", task.progress) state.text = HtmlHelper.fromHtml(formattedHTML) state.gravity = Gravity.END holder.progress.addView(state, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) if (task is ExamTask) { state.setOnClickListener { val dialog = ObjectivesExamDialog() val bundle = Bundle() val taskPosition = objective.tasks.indexOf(task) bundle.putInt("currentTask", taskPosition) dialog.arguments = bundle ObjectivesExamDialog.objective = objective fragmentManager?.let { dialog.show(it, "ObjectivesFragment") } } } // horizontal line val separator = View(holder.progress.context) separator.setBackgroundColor(Color.DKGRAY) holder.progress.addView(separator, LinearLayout.LayoutParams.MATCH_PARENT, 2) } } holder.accomplished.text = MainApp.gs(R.string.accomplished, DateUtil.dateAndTimeString(objective.accomplishedOn)) holder.accomplished.setTextColor(-0x3e3e3f) holder.verify.setOnClickListener { NetworkChangeReceiver.grabNetworkStatus(context) if (objectives_fake.isChecked) { objective.accomplishedOn = DateUtil.now() scrollToCurrentObjective() startUpdateTimer() RxBus.send(EventObjectivesUpdateGui()) RxBus.send(EventSWUpdate(false)) } else { // move out of UI thread Thread { NtpProgressDialog().show((context as AppCompatActivity).supportFragmentManager, "NtpCheck") RxBus.send(EventNtpStatus(MainApp.gs(R.string.timedetection), 0)) SntpClient.ntpTime(object : SntpClient.Callback() { override fun run() { log.debug("NTP time: $time System time: ${DateUtil.now()}") SystemClock.sleep(300) if (!networkConnected) { RxBus.send(EventNtpStatus(MainApp.gs(R.string.notconnected), 99)) } else if (success) { if (objective.isCompleted(time)) { objective.accomplishedOn = time RxBus.send(EventNtpStatus(MainApp.gs(R.string.success), 100)) SystemClock.sleep(1000) RxBus.send(EventObjectivesUpdateGui()) RxBus.send(EventSWUpdate(false)) SystemClock.sleep(100) scrollToCurrentObjective() } else { RxBus.send(EventNtpStatus(MainApp.gs(R.string.requirementnotmet), 99)) } } else { RxBus.send(EventNtpStatus(MainApp.gs(R.string.failedretrievetime), 99)) } } }, NetworkChangeReceiver.isConnected()) }.start() } } holder.start.setOnClickListener { NetworkChangeReceiver.grabNetworkStatus(context) if (objectives_fake.isChecked) { objective.startedOn = DateUtil.now() scrollToCurrentObjective() startUpdateTimer() RxBus.send(EventObjectivesUpdateGui()) RxBus.send(EventSWUpdate(false)) } else // move out of UI thread Thread { NtpProgressDialog().show((context as AppCompatActivity).supportFragmentManager, "NtpCheck") RxBus.send(EventNtpStatus(MainApp.gs(R.string.timedetection), 0)) SntpClient.ntpTime(object : SntpClient.Callback() { override fun run() { log.debug("NTP time: $time System time: ${DateUtil.now()}") SystemClock.sleep(300) if (!networkConnected) { RxBus.send(EventNtpStatus(MainApp.gs(R.string.notconnected), 99)) } else if (success) { objective.startedOn = time RxBus.send(EventNtpStatus(MainApp.gs(R.string.success), 100)) SystemClock.sleep(1000) RxBus.send(EventObjectivesUpdateGui()) RxBus.send(EventSWUpdate(false)) SystemClock.sleep(100) scrollToCurrentObjective() } else { RxBus.send(EventNtpStatus(MainApp.gs(R.string.failedretrievetime), 99)) } } }, NetworkChangeReceiver.isConnected()) }.start() } holder.unStart.setOnClickListener { activity?.let { activity -> OKDialog.showConfirmation(activity, MainApp.gs(R.string.objectives), MainApp.gs(R.string.doyouwantresetstart), Runnable { objective.startedOn = 0 scrollToCurrentObjective() RxBus.send(EventObjectivesUpdateGui()) RxBus.send(EventSWUpdate(false)) }) } } holder.unFinish.setOnClickListener { objective.accomplishedOn = 0 scrollToCurrentObjective() RxBus.send(EventObjectivesUpdateGui()) RxBus.send(EventSWUpdate(false)) } if (objective.hasSpecialInput && !objective.isAccomplished && objective.isStarted && objective.specialActionEnabled()) { // generate random request code if none exists val request = SP.getString(R.string.key_objectives_request_code, String.format("%1$05d", (Math.random() * 99999).toInt())) SP.putString(R.string.key_objectives_request_code, request) holder.requestCode.text = MainApp.gs(R.string.requestcode, request) holder.requestCode.visibility = View.VISIBLE holder.enterButton.visibility = View.VISIBLE holder.input.visibility = View.VISIBLE holder.inputHint.visibility = View.VISIBLE holder.enterButton.setOnClickListener { val input = holder.input.text.toString() objective.specialAction(activity, input) RxBus.send(EventObjectivesUpdateGui()) } } else { holder.enterButton.visibility = View.GONE holder.input.visibility = View.GONE holder.inputHint.visibility = View.GONE holder.requestCode.visibility = View.GONE } } override fun getItemCount(): Int { return ObjectivesPlugin.objectives.size } inner class ViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) { val title: TextView = itemView.findViewById(R.id.objective_title) val objective: TextView = itemView.findViewById(R.id.objective_objective) val gate: TextView = itemView.findViewById(R.id.objective_gate) val accomplished: TextView = itemView.findViewById(R.id.objective_accomplished) val progress: LinearLayout = itemView.findViewById(R.id.objective_progress) val verify: Button = itemView.findViewById(R.id.objective_verify) val start: Button = itemView.findViewById(R.id.objective_start) val unFinish: Button = itemView.findViewById(R.id.objective_unfinish) val unStart: Button = itemView.findViewById(R.id.objective_unstart) val inputHint: TextView = itemView.findViewById(R.id.objective_inputhint) val input: EditText = itemView.findViewById(R.id.objective_input) val enterButton: Button = itemView.findViewById(R.id.objective_enterbutton) val requestCode: TextView = itemView.findViewById(R.id.objective_requestcode) } } fun updateGUI() { activity?.runOnUiThread { objectivesAdapter.notifyDataSetChanged() } } }
agpl-3.0
412a8c059746f46776af36da2eb944d0
49.845272
141
0.575937
5.413362
false
false
false
false
jotomo/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Set_History_Upload_Mode.kt
1
1102
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption class DanaRS_Packet_General_Set_History_Upload_Mode( injector: HasAndroidInjector, private var mode: Int = 0 ) : DanaRS_Packet(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__SET_HISTORY_UPLOAD_MODE aapsLogger.debug(LTag.PUMPCOMM, "New message: mode: $mode") } override fun getRequestParams(): ByteArray { val request = ByteArray(1) request[0] = (mode and 0xff).toByte() return request } override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false } else { aapsLogger.error("Result Error: $result") failed = true } } override fun getFriendlyName(): String { return "REVIEW__SET_HISTORY_UPLOAD_MODE" } }
agpl-3.0
bbf14032f5d7fdc7aa360594ab3fddd9
28.810811
83
0.65245
4.338583
false
false
false
false
mbrlabs/Mundus
editor/src/main/com/mbrlabs/mundus/editor/utils/TerrainUtils.kt
1
2533
/* * Copyright (c) 2016. See AUTHORS file. * * 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. */ @file:JvmName("TerrainUtils") package com.mbrlabs.mundus.editor.utils import com.badlogic.gdx.graphics.g3d.utils.MeshPartBuilder.VertexInfo import com.badlogic.gdx.math.Vector3 import com.badlogic.gdx.math.collision.Ray import com.badlogic.gdx.utils.Array import com.mbrlabs.mundus.commons.assets.TerrainAsset import com.mbrlabs.mundus.commons.scene3d.GameObject import com.mbrlabs.mundus.commons.scene3d.SceneGraph import com.mbrlabs.mundus.commons.shaders.TerrainShader import com.mbrlabs.mundus.editor.scene3d.components.PickableTerrainComponent import com.mbrlabs.mundus.editor.shader.Shaders private var tempVI = VertexInfo() fun createTerrainGO(sg: SceneGraph, shader: TerrainShader, goID: Int, goName: String, terrain: TerrainAsset): GameObject { val terrainGO = GameObject(sg, null, goID) terrainGO.name = goName terrain.terrain.setTransform(terrainGO.transform) val terrainComponent = PickableTerrainComponent(terrainGO, Shaders.terrainShader) terrainComponent.terrain = terrain terrainGO.components.add(terrainComponent) terrainComponent.shader = shader terrainComponent.encodeRaypickColorId() return terrainGO } fun getRayIntersection(terrains: Array<TerrainAsset>, ray: Ray, out: Vector3): Vector3? { for (terrain in terrains) { val terr = terrain.terrain terr.getRayIntersection(out, ray) if (terr.isOnTerrain(out.x, out.z)) { return out } } return null } fun getRayIntersectionAndUp(terrains: Array<TerrainAsset>, ray: Ray): VertexInfo? { for (terrain in terrains) { val terr = terrain.terrain terr.getRayIntersection(tempVI.position, ray) if (terr.isOnTerrain(tempVI.position.x, tempVI.position.z)) { tempVI.normal.set(terr.getNormalAtWordCoordinate(tempVI.position.x, tempVI.position.z)) return tempVI } } return null }
apache-2.0
422a86d1411c38e4e475f575676eeb0c
34.676056
99
0.736676
3.747041
false
false
false
false
leafclick/intellij-community
plugins/github/src/org/jetbrains/plugins/github/AbstractAuthenticatingGithubUrlGroupingAction.kt
1
3382
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import git4idea.DialogManager import git4idea.repo.GitRemote import git4idea.repo.GitRepository import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.ui.GithubChooseAccountDialog import org.jetbrains.plugins.github.util.GithubAccountsMigrationHelper import javax.swing.Icon /** * If it is not possible to automatically determine suitable account, [GithubChooseAccountDialog] dialog will be shown. */ abstract class AbstractAuthenticatingGithubUrlGroupingAction(text: String?, description: String?, icon: Icon?) : AbstractGithubUrlGroupingAction(text, description, icon) { override fun actionPerformed(e: AnActionEvent, project: Project, repository: GitRepository, remote: GitRemote, remoteUrl: String) { if (!service<GithubAccountsMigrationHelper>().migrate(project)) return val account = getAccount(project, remoteUrl) ?: return actionPerformed(e, project, repository, remote, remoteUrl, account) } private fun getAccount(project: Project, remoteUrl: String): GithubAccount? { val authenticationManager = service<GithubAuthenticationManager>() val accounts = authenticationManager.getAccounts().filter { it.server.matches(remoteUrl) } //only possible when remote is on github.com if (accounts.isEmpty()) { if (!GithubServerPath.DEFAULT_SERVER.matches(remoteUrl)) throw IllegalArgumentException("Remote $remoteUrl does not match ${GithubServerPath.DEFAULT_SERVER}") return authenticationManager.requestNewAccountForServer(GithubServerPath.DEFAULT_SERVER, project) } return accounts.singleOrNull() ?: accounts.find { it == authenticationManager.getDefaultAccount(project) } ?: chooseAccount(project, authenticationManager, remoteUrl, accounts) } private fun chooseAccount(project: Project, authenticationManager: GithubAuthenticationManager, remoteUrl: String, accounts: List<GithubAccount>): GithubAccount? { val dialog = GithubChooseAccountDialog(project, null, accounts, "Choose GitHub account for: $remoteUrl", false, true) DialogManager.show(dialog) if (!dialog.isOK) return null val account = dialog.account if (dialog.setDefault) authenticationManager.setDefaultAccount(project, account) return account } protected abstract fun actionPerformed(e: AnActionEvent, project: Project, repository: GitRepository, remote: GitRemote, remoteUrl: String, account: GithubAccount) }
apache-2.0
00f974cf0d57a8b266420a958c6a1819
51.046154
140
0.688054
5.590083
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/adapters/viewholders/PMMessageViewHolder.kt
1
3969
package io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders import android.util.TypedValue import android.view.View import android.widget.RelativeLayout import androidx.core.content.ContextCompat import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.glide.GlideApp import io.github.feelfreelinux.wykopmobilny.models.dataclass.PMMessage import io.github.feelfreelinux.wykopmobilny.ui.modules.NewNavigatorApi import io.github.feelfreelinux.wykopmobilny.utils.getActivityContext import io.github.feelfreelinux.wykopmobilny.utils.preferences.SettingsPreferencesApi import io.github.feelfreelinux.wykopmobilny.utils.textview.prepareBody import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.WykopLinkHandlerApi import kotlinx.android.synthetic.main.pmmessage_sent_layout.view.* class PMMessageViewHolder( val view: View, val linkHandlerApi: WykopLinkHandlerApi, val settingsPreferencesApi: SettingsPreferencesApi, val navigatorApi: NewNavigatorApi ) : RecyclableViewHolder(view) { fun bindView(message: PMMessage) { flipMessage(message.isSentFromUser) view.apply { date.text = message.date message.app?.let { date.text = message.date } body.prepareBody(message.body, { linkHandlerApi.handleUrl(it) }, null, settingsPreferencesApi.openSpoilersDialog) embedImage.forceDisableMinimizedMode = true embedImage.setEmbed(message.embed, settingsPreferencesApi, navigatorApi) } } /** * This function flips the message depending on the direction. */ private fun flipMessage(isSentFromUser: Boolean) { val cardViewParams = view.notificationItem.layoutParams as RelativeLayout.LayoutParams // Resolve colors from attr val theme = view.getActivityContext()!!.theme val usersMessageColor = TypedValue() theme?.resolveAttribute(R.attr.usersMessageColor, usersMessageColor, true) val usersMessageSubtextDirected = TypedValue() theme?.resolveAttribute(R.attr.usersMessageSubtextDirected, usersMessageSubtextDirected, true) val cardBackgroundColor = TypedValue() theme?.resolveAttribute(R.attr.yourMessageColor, cardBackgroundColor, true) val marginVertical = view.resources.getDimension(R.dimen.padding_dp_mini).toInt() val marginHorizontal = view.resources.getDimension(R.dimen.pmmessage_sent_layout_card_margin_horizontal).toInt() val marginFlip = view.resources.getDimension(R.dimen.pmmessage_sent_layout_card_margin_flip).toInt() if (isSentFromUser) { view.notificationItem.setCardBackgroundColor(usersMessageColor.data) view.notificationItem.date.setTextColor(usersMessageSubtextDirected.data) cardViewParams.setMargins(marginFlip, marginVertical, marginHorizontal, marginVertical) cardViewParams.apply { removeRule(RelativeLayout.ALIGN_PARENT_START) addRule(RelativeLayout.ALIGN_PARENT_END) height = RelativeLayout.LayoutParams.WRAP_CONTENT } } else { view.notificationItem.setCardBackgroundColor(cardBackgroundColor.data) view.notificationItem.date.setTextColor(ContextCompat.getColor(view.context, R.color.authorHeader_date_Dark)) cardViewParams.setMargins(marginHorizontal, marginVertical, marginFlip, marginVertical) cardViewParams.apply { removeRule(RelativeLayout.ALIGN_PARENT_END) addRule(RelativeLayout.ALIGN_PARENT_START) height = RelativeLayout.LayoutParams.WRAP_CONTENT } } view.notificationItem.layoutParams = cardViewParams } fun cleanRecycled() { view.apply { date.text = null body.text = null GlideApp.with(this).clear(embedImage) } } }
mit
8dc2f066d658d354a41f9043af5e473e
43.606742
125
0.723356
4.781928
false
false
false
false
JetBrains/kotlin-native
Interop/Runtime/src/main/kotlin/kotlinx/cinterop/Types.kt
3
17438
/* * Copyright 2010-2019 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 kotlinx.cinterop /** * The entity which has an associated native pointer. * Subtypes are supposed to represent interpretations of the pointed data or code. * * This interface is likely to be handled by compiler magic and shouldn't be subtyped by arbitrary classes. * * TODO: the behavior of [equals], [hashCode] and [toString] differs on Native and JVM backends. */ public open class NativePointed internal constructor(rawPtr: NonNullNativePtr) { var rawPtr = rawPtr.toNativePtr() internal set } // `null` value of `NativePointed?` is mapped to `nativeNullPtr`. public val NativePointed?.rawPtr: NativePtr get() = if (this != null) this.rawPtr else nativeNullPtr /** * Returns interpretation of entity with given pointer. * * @param T must not be abstract */ public inline fun <reified T : NativePointed> interpretPointed(ptr: NativePtr): T = interpretNullablePointed<T>(ptr)!! private class OpaqueNativePointed(rawPtr: NativePtr) : NativePointed(rawPtr.toNonNull()) public fun interpretOpaquePointed(ptr: NativePtr): NativePointed = interpretPointed<OpaqueNativePointed>(ptr) public fun interpretNullableOpaquePointed(ptr: NativePtr): NativePointed? = interpretNullablePointed<OpaqueNativePointed>(ptr) /** * Changes the interpretation of the pointed data or code. */ public inline fun <reified T : NativePointed> NativePointed.reinterpret(): T = interpretPointed(this.rawPtr) /** * C data or code. */ public abstract class CPointed(rawPtr: NativePtr) : NativePointed(rawPtr.toNonNull()) /** * Represents a reference to (possibly empty) sequence of C values. * It can be either a stable pointer [CPointer] or a sequence of immutable values [CValues]. * * [CValuesRef] is designed to be used as Kotlin representation of pointer-typed parameters of C functions. * When passing [CPointer] as [CValuesRef] to the Kotlin binding method, the C function receives exactly this pointer. * Passing [CValues] has nearly the same semantics as passing by value: the C function receives * the pointer to the temporary copy of these values, and the caller can't observe the modifications to this copy. * The copy is valid until the C function returns. * There are also other implementations of [CValuesRef] that provide temporary pointer, * e.g. Kotlin Native specific [refTo] functions to pass primitive arrays directly to native. */ public abstract class CValuesRef<T : CPointed> { /** * If this reference is [CPointer], returns this pointer, otherwise * allocate storage value in the scope and return it. */ public abstract fun getPointer(scope: AutofreeScope): CPointer<T> } /** * The (possibly empty) sequence of immutable C values. * It is self-contained and doesn't depend on native memory. */ public abstract class CValues<T : CVariable> : CValuesRef<T>() { /** * Copies the values to [placement] and returns the pointer to the copy. */ public override fun getPointer(scope: AutofreeScope): CPointer<T> { return place(interpretCPointer(scope.alloc(size, align).rawPtr)!!) } // TODO: optimize public override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is CValues<*>) return false val thisBytes = this.getBytes() val otherBytes = other.getBytes() if (thisBytes.size != otherBytes.size) { return false } for (index in 0 .. thisBytes.size - 1) { if (thisBytes[index] != otherBytes[index]) { return false } } return true } public override fun hashCode(): Int { var result = 0 for (byte in this.getBytes()) { result = result * 31 + byte } return result } public abstract val size: Int public abstract val align: Int /** * Copy the referenced values to [placement] and return placement pointer. */ public abstract fun place(placement: CPointer<T>): CPointer<T> } public fun <T : CVariable> CValues<T>.placeTo(scope: AutofreeScope) = this.getPointer(scope) /** * The single immutable C value. * It is self-contained and doesn't depend on native memory. * * TODO: consider providing an adapter instead of subtyping [CValues]. */ public abstract class CValue<T : CVariable> : CValues<T>() /** * C pointer. */ public class CPointer<T : CPointed> internal constructor(@PublishedApi internal val value: NonNullNativePtr) : CValuesRef<T>() { // TODO: replace by [value]. @Suppress("NOTHING_TO_INLINE") public inline val rawValue: NativePtr get() = value.toNativePtr() public override fun equals(other: Any?): Boolean { if (this === other) { return true // fast path } return (other is CPointer<*>) && (rawValue == other.rawValue) } public override fun hashCode(): Int { return rawValue.hashCode() } public override fun toString() = this.cPointerToString() public override fun getPointer(scope: AutofreeScope) = this } /** * Returns the pointer to this data or code. */ public val <T : CPointed> T.ptr: CPointer<T> get() = interpretCPointer(this.rawPtr)!! /** * Returns the corresponding [CPointed]. * * @param T must not be abstract */ public inline val <reified T : CPointed> CPointer<T>.pointed: T get() = interpretPointed<T>(this.rawValue) // `null` value of `CPointer?` is mapped to `nativeNullPtr` public val CPointer<*>?.rawValue: NativePtr get() = if (this != null) this.rawValue else nativeNullPtr public fun <T : CPointed> CPointer<*>.reinterpret(): CPointer<T> = interpretCPointer(this.rawValue)!! public fun <T : CPointed> CPointer<T>?.toLong() = this.rawValue.toLong() public fun <T : CPointed> Long.toCPointer(): CPointer<T>? = interpretCPointer(nativeNullPtr + this) /** * The [CPointed] without any specified interpretation. */ public abstract class COpaque(rawPtr: NativePtr) : CPointed(rawPtr) // TODO: should it correspond to COpaquePointer? /** * The pointer with an opaque type. */ public typealias COpaquePointer = CPointer<out CPointed> // FIXME /** * The variable containing a [COpaquePointer]. */ public typealias COpaquePointerVar = CPointerVarOf<COpaquePointer> /** * The C data variable located in memory. * * The non-abstract subclasses should represent the (complete) C data type and thus specify size and alignment. * Each such subclass must have a companion object which is a [Type]. */ public abstract class CVariable(rawPtr: NativePtr) : CPointed(rawPtr) { /** * The (complete) C data type. * * @param size the size in bytes of data of this type * @param align the alignments in bytes that is enough for this data type. * It may be greater than actually required for simplicity. */ @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") public open class Type(val size: Long, val align: Int) { init { require(size % align == 0L) } } } @Suppress("DEPRECATION") public inline fun <reified T : CVariable> sizeOf() = typeOf<T>().size @Suppress("DEPRECATION") public inline fun <reified T : CVariable> alignOf() = typeOf<T>().align /** * Returns the member of this [CStructVar] which is located by given offset in bytes. */ public inline fun <reified T : CPointed> CStructVar.memberAt(offset: Long): T { return interpretPointed<T>(this.rawPtr + offset) } public inline fun <reified T : CVariable> CStructVar.arrayMemberAt(offset: Long): CArrayPointer<T> { return interpretCPointer<T>(this.rawPtr + offset)!! } /** * The C struct-typed variable located in memory. */ public abstract class CStructVar(rawPtr: NativePtr) : CVariable(rawPtr) { @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") @Suppress("DEPRECATION") open class Type(size: Long, align: Int) : CVariable.Type(size, align) } /** * The C primitive-typed variable located in memory. */ sealed class CPrimitiveVar(rawPtr: NativePtr) : CVariable(rawPtr) { // aligning by size is obviously enough @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") @Suppress("DEPRECATION") open class Type(size: Int) : CVariable.Type(size.toLong(), align = size) } @Deprecated("Will be removed.") public interface CEnum { public val value: Any } public abstract class CEnumVar(rawPtr: NativePtr) : CPrimitiveVar(rawPtr) // generics below are used for typedef support // these classes are not supposed to be used directly, instead the typealiases are provided. @Suppress("FINAL_UPPER_BOUND") public class BooleanVarOf<T : Boolean>(rawPtr: NativePtr) : CPrimitiveVar(rawPtr) { @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") @Suppress("DEPRECATION") companion object : Type(1) } @Suppress("FINAL_UPPER_BOUND") public class ByteVarOf<T : Byte>(rawPtr: NativePtr) : CPrimitiveVar(rawPtr) { @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") @Suppress("DEPRECATION") companion object : Type(1) } @Suppress("FINAL_UPPER_BOUND") public class ShortVarOf<T : Short>(rawPtr: NativePtr) : CPrimitiveVar(rawPtr) { @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") @Suppress("DEPRECATION") companion object : Type(2) } @Suppress("FINAL_UPPER_BOUND") public class IntVarOf<T : Int>(rawPtr: NativePtr) : CPrimitiveVar(rawPtr) { @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") @Suppress("DEPRECATION") companion object : Type(4) } @Suppress("FINAL_UPPER_BOUND") public class LongVarOf<T : Long>(rawPtr: NativePtr) : CPrimitiveVar(rawPtr) { @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") @Suppress("DEPRECATION") companion object : Type(8) } @Suppress("FINAL_UPPER_BOUND") public class UByteVarOf<T : UByte>(rawPtr: NativePtr) : CPrimitiveVar(rawPtr) { @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") @Suppress("DEPRECATION") companion object : Type(1) } @Suppress("FINAL_UPPER_BOUND") public class UShortVarOf<T : UShort>(rawPtr: NativePtr) : CPrimitiveVar(rawPtr) { @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") @Suppress("DEPRECATION") companion object : Type(2) } @Suppress("FINAL_UPPER_BOUND") public class UIntVarOf<T : UInt>(rawPtr: NativePtr) : CPrimitiveVar(rawPtr) { @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") @Suppress("DEPRECATION") companion object : Type(4) } @Suppress("FINAL_UPPER_BOUND") public class ULongVarOf<T : ULong>(rawPtr: NativePtr) : CPrimitiveVar(rawPtr) { @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") @Suppress("DEPRECATION") companion object : Type(8) } @Suppress("FINAL_UPPER_BOUND") public class FloatVarOf<T : Float>(rawPtr: NativePtr) : CPrimitiveVar(rawPtr) { @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") @Suppress("DEPRECATION") companion object : Type(4) } @Suppress("FINAL_UPPER_BOUND") public class DoubleVarOf<T : Double>(rawPtr: NativePtr) : CPrimitiveVar(rawPtr) { @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") @Suppress("DEPRECATION") companion object : Type(8) } public typealias BooleanVar = BooleanVarOf<Boolean> public typealias ByteVar = ByteVarOf<Byte> public typealias ShortVar = ShortVarOf<Short> public typealias IntVar = IntVarOf<Int> public typealias LongVar = LongVarOf<Long> public typealias UByteVar = UByteVarOf<UByte> public typealias UShortVar = UShortVarOf<UShort> public typealias UIntVar = UIntVarOf<UInt> public typealias ULongVar = ULongVarOf<ULong> public typealias FloatVar = FloatVarOf<Float> public typealias DoubleVar = DoubleVarOf<Double> @Suppress("FINAL_UPPER_BOUND", "UNCHECKED_CAST") public var <T : Boolean> BooleanVarOf<T>.value: T get() { val byte = nativeMemUtils.getByte(this) return byte.toBoolean() as T } set(value) = nativeMemUtils.putByte(this, value.toByte()) @Suppress("NOTHING_TO_INLINE") public inline fun Boolean.toByte(): Byte = if (this) 1 else 0 @Suppress("NOTHING_TO_INLINE") public inline fun Byte.toBoolean() = (this.toInt() != 0) @Suppress("FINAL_UPPER_BOUND", "UNCHECKED_CAST") public var <T : Byte> ByteVarOf<T>.value: T get() = nativeMemUtils.getByte(this) as T set(value) = nativeMemUtils.putByte(this, value) @Suppress("FINAL_UPPER_BOUND", "UNCHECKED_CAST") public var <T : Short> ShortVarOf<T>.value: T get() = nativeMemUtils.getShort(this) as T set(value) = nativeMemUtils.putShort(this, value) @Suppress("FINAL_UPPER_BOUND", "UNCHECKED_CAST") public var <T : Int> IntVarOf<T>.value: T get() = nativeMemUtils.getInt(this) as T set(value) = nativeMemUtils.putInt(this, value) @Suppress("FINAL_UPPER_BOUND", "UNCHECKED_CAST") public var <T : Long> LongVarOf<T>.value: T get() = nativeMemUtils.getLong(this) as T set(value) = nativeMemUtils.putLong(this, value) @Suppress("FINAL_UPPER_BOUND", "UNCHECKED_CAST") public var <T : UByte> UByteVarOf<T>.value: T get() = nativeMemUtils.getByte(this).toUByte() as T set(value) = nativeMemUtils.putByte(this, value.toByte()) @Suppress("FINAL_UPPER_BOUND", "UNCHECKED_CAST") public var <T : UShort> UShortVarOf<T>.value: T get() = nativeMemUtils.getShort(this).toUShort() as T set(value) = nativeMemUtils.putShort(this, value.toShort()) @Suppress("FINAL_UPPER_BOUND", "UNCHECKED_CAST") public var <T : UInt> UIntVarOf<T>.value: T get() = nativeMemUtils.getInt(this).toUInt() as T set(value) = nativeMemUtils.putInt(this, value.toInt()) @Suppress("FINAL_UPPER_BOUND", "UNCHECKED_CAST") public var <T : ULong> ULongVarOf<T>.value: T get() = nativeMemUtils.getLong(this).toULong() as T set(value) = nativeMemUtils.putLong(this, value.toLong()) // TODO: ensure native floats have the appropriate binary representation @Suppress("FINAL_UPPER_BOUND", "UNCHECKED_CAST") public var <T : Float> FloatVarOf<T>.value: T get() = nativeMemUtils.getFloat(this) as T set(value) = nativeMemUtils.putFloat(this, value) @Suppress("FINAL_UPPER_BOUND", "UNCHECKED_CAST") public var <T : Double> DoubleVarOf<T>.value: T get() = nativeMemUtils.getDouble(this) as T set(value) = nativeMemUtils.putDouble(this, value) public class CPointerVarOf<T : CPointer<*>>(rawPtr: NativePtr) : CVariable(rawPtr) { @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") @Suppress("DEPRECATION") companion object : CVariable.Type(pointerSize.toLong(), pointerSize) } /** * The C data variable containing the pointer to `T`. */ public typealias CPointerVar<T> = CPointerVarOf<CPointer<T>> /** * The value of this variable. */ @Suppress("UNCHECKED_CAST") public inline var <P : CPointer<*>> CPointerVarOf<P>.value: P? get() = interpretCPointer<CPointed>(nativeMemUtils.getNativePtr(this)) as P? set(value) = nativeMemUtils.putNativePtr(this, value.rawValue) /** * The code or data pointed by the value of this variable. * * @param T must not be abstract */ public inline var <reified T : CPointed, reified P : CPointer<T>> CPointerVarOf<P>.pointed: T? get() = this.value?.pointed set(value) { this.value = value?.ptr as P? } public inline operator fun <reified T : CVariable> CPointer<T>.get(index: Long): T { val offset = if (index == 0L) { 0L // optimization for JVM impl which uses reflection for now. } else { index * sizeOf<T>() } return interpretPointed(this.rawValue + offset) } public inline operator fun <reified T : CVariable> CPointer<T>.get(index: Int): T = this.get(index.toLong()) @Suppress("NOTHING_TO_INLINE") @JvmName("plus\$CPointer") public inline operator fun <T : CPointerVarOf<*>> CPointer<T>?.plus(index: Long): CPointer<T>? = interpretCPointer(this.rawValue + index * pointerSize) @Suppress("NOTHING_TO_INLINE") @JvmName("plus\$CPointer") public inline operator fun <T : CPointerVarOf<*>> CPointer<T>?.plus(index: Int): CPointer<T>? = this + index.toLong() @Suppress("NOTHING_TO_INLINE") public inline operator fun <T : CPointer<*>> CPointer<CPointerVarOf<T>>.get(index: Int): T? = (this + index)!!.pointed.value @Suppress("NOTHING_TO_INLINE") public inline operator fun <T : CPointer<*>> CPointer<CPointerVarOf<T>>.set(index: Int, value: T?) { (this + index)!!.pointed.value = value } @Suppress("NOTHING_TO_INLINE") public inline operator fun <T : CPointer<*>> CPointer<CPointerVarOf<T>>.get(index: Long): T? = (this + index)!!.pointed.value @Suppress("NOTHING_TO_INLINE") public inline operator fun <T : CPointer<*>> CPointer<CPointerVarOf<T>>.set(index: Long, value: T?) { (this + index)!!.pointed.value = value } public typealias CArrayPointer<T> = CPointer<T> public typealias CArrayPointerVar<T> = CPointerVar<T> /** * The C function. */ public class CFunction<T : Function<*>>(rawPtr: NativePtr) : CPointed(rawPtr)
apache-2.0
93e6bc5210a59349a9270aa05af0c99b
33.462451
128
0.696869
3.832527
false
false
false
false
JetBrains/kotlin-native
runtime/src/main/kotlin/kotlin/random/Random.kt
4
1196
/* * Copyright 2010-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 kotlin.random import kotlin.native.concurrent.AtomicLong import kotlin.system.getTimeNanos /** * The default implementation of pseudo-random generator using the linear congruential generator. */ internal object NativeRandom : Random() { private const val MULTIPLIER = 0x5deece66dL private val _seed = AtomicLong(mult(getTimeNanos())) /** * Random generator seed value. */ private val seed: Long get() = _seed.value private fun mult(value: Long) = (value xor MULTIPLIER) and ((1L shl 48) - 1) private fun update(seed: Long): Unit { _seed.value = seed } override fun nextBits(bitCount: Int): Int { update((seed * MULTIPLIER + 0xbL) and ((1L shl 48) - 1)) return (seed ushr (48 - bitCount)).toInt() } override fun nextInt(): Int = nextBits(32) } internal actual fun defaultPlatformRandom(): Random = NativeRandom internal actual fun doubleFromParts(hi26: Int, low27: Int): Double = (hi26.toLong().shl(27) + low27) / (1L shl 53).toDouble()
apache-2.0
6f052e4db931f538c41e5c3d55cd93dd
28.9
101
0.673077
3.7375
false
false
false
false
josecefe/Rueda
src/es/um/josecefe/rueda/resolutor/Estadisticas.kt
1
1934
/* * Copyright (c) 2016-2017. Jose Ceferino Ortega Carretero * * 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 es.um.josecefe.rueda.resolutor import javafx.beans.property.DoubleProperty import javafx.beans.property.SimpleDoubleProperty import org.apache.commons.lang3.time.DurationFormatUtils /** * @author josec */ abstract class Estadisticas { protected val progreso: DoubleProperty = SimpleDoubleProperty(0.0) open var fitness: Int = 0 private var ti: Long = 0 // Para el tiempo inicial open var tiempo: Long = 0 protected set open fun inicia(): Estadisticas { ti = System.currentTimeMillis() // Tiempo inicial fitness = Integer.MAX_VALUE if (!progreso.isBound) progreso.set(0.0) return this } fun actualizaProgreso(): Estadisticas { tiempo = System.currentTimeMillis() - ti if (!progreso.isBound) progreso.set(completado) return this } val tiempoString: String get() = DurationFormatUtils.formatDurationHMS(tiempo) fun progresoProperty(): DoubleProperty { return progreso } /** * Indica el grado de completitud de la exploración de soluciones del algoritmo * * @return valor entre 0 y 1 indicando el grado de completitud */ abstract val completado: Double }
gpl-3.0
9da810a460010c64af3a7d848a2970c6
35.471698
242
0.705122
4.276549
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/block/copy/local/LocalBlockCopy.kt
2
1580
package com.github.kerubistan.kerub.planner.steps.storage.block.copy.local import com.fasterxml.jackson.annotation.JsonTypeName import com.github.kerubistan.kerub.model.StorageCapability import com.github.kerubistan.kerub.model.VirtualStorageDevice import com.github.kerubistan.kerub.model.dynamic.VirtualStorageAllocation import com.github.kerubistan.kerub.model.dynamic.VirtualStorageBlockDeviceAllocation import com.github.kerubistan.kerub.planner.reservations.Reservation import com.github.kerubistan.kerub.planner.reservations.UseHostReservation import com.github.kerubistan.kerub.planner.reservations.VirtualStorageReservation import com.github.kerubistan.kerub.planner.steps.storage.AbstractCreateVirtualStorage import com.github.kerubistan.kerub.planner.steps.storage.block.copy.AbstractBlockCopy @JsonTypeName("local-block-copy") data class LocalBlockCopy( override val sourceDevice: VirtualStorageDevice, override val targetDevice: VirtualStorageDevice, override val sourceAllocation: VirtualStorageBlockDeviceAllocation, override val allocationStep: AbstractCreateVirtualStorage<out VirtualStorageAllocation, out StorageCapability> ) : AbstractBlockCopy() { init { validate() check(sourceAllocation.hostId == allocationStep.host.id) { "source allocation host (${sourceAllocation.hostId}) must be the same as the target allocation " + "host (${allocationStep.host.id})" } } override fun reservations(): List<Reservation<*>> = listOf( UseHostReservation(host = allocationStep.host), VirtualStorageReservation(device = sourceDevice) ) }
apache-2.0
da6200a59892e93c02bf1f44df1da801
45.5
112
0.831646
4.527221
false
false
false
false
androidx/androidx
glance/glance-appwidget/integration-tests/template-demos/src/main/java/androidx/glance/appwidget/template/demos/DemoOverrideWidget.kt
3
4401
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.glance.appwidget.template.demos import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.sp import androidx.glance.GlanceModifier import androidx.glance.GlanceTheme import androidx.glance.ImageProvider import androidx.glance.appwidget.GlanceAppWidget import androidx.glance.appwidget.GlanceAppWidgetReceiver import androidx.glance.appwidget.template.GlanceTemplateAppWidget import androidx.glance.appwidget.template.SingleEntityTemplate import androidx.glance.background import androidx.glance.layout.Alignment import androidx.glance.layout.Column import androidx.glance.layout.fillMaxSize import androidx.glance.template.HeaderBlock import androidx.glance.template.ImageBlock import androidx.glance.template.LocalTemplateMode import androidx.glance.template.SingleEntityTemplateData import androidx.glance.template.TemplateImageWithDescription import androidx.glance.template.TemplateMode import androidx.glance.template.TemplateText import androidx.glance.template.TextBlock import androidx.glance.template.TextType import androidx.glance.text.Text import androidx.glance.text.TextAlign import androidx.glance.text.TextStyle import androidx.glance.unit.ColorProvider /** * A widget implementation that uses [SingleEntityTemplate] with a custom layout override for * [TemplateMode.Horizontal]. */ class DemoOverrideWidget : GlanceTemplateAppWidget() { @Composable override fun TemplateContent() { GlanceTheme { if (LocalTemplateMode.current == TemplateMode.Horizontal) { MyHorizontalContent() } else { SingleEntityTemplate( SingleEntityTemplateData( headerBlock = HeaderBlock( text = TemplateText("Single Entity Demo", TextType.Title), icon = TemplateImageWithDescription( ImageProvider(R.drawable.ic_widgets), "icon" ), ), textBlock = TextBlock( text1 = TemplateText("title", TextType.Title), text2 = TemplateText("Subtitle", TextType.Label), text3 = TemplateText( "Body Lorem ipsum dolor sit amet, consectetur adipiscing", TextType.Label ), priority = 0, ), imageBlock = ImageBlock( images = listOf( TemplateImageWithDescription( ImageProvider(R.drawable.palm_leaf), "image" ) ), priority = 1, ), ) ) } } } @Composable fun MyHorizontalContent() { Column( modifier = GlanceModifier.fillMaxSize().background(Color.Red), horizontalAlignment = Alignment.CenterHorizontally, verticalAlignment = Alignment.CenterVertically ) { Text( "User layout override for horizontal display", style = TextStyle( fontSize = 36.sp, color = ColorProvider(Color.White), textAlign = TextAlign.Center ) ) } } } class DemoOverrideWidgetReceiver : GlanceAppWidgetReceiver() { override val glanceAppWidget: GlanceAppWidget = DemoOverrideWidget() }
apache-2.0
731ceed4ba2669efdf13e131bea15ec9
37.946903
93
0.611906
5.563843
false
false
false
false
GunoH/intellij-community
plugins/gradle/java/testSources/execution/GradleRunnerUtilTest.kt
12
1132
// 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.gradle.execution import junit.framework.TestCase.assertEquals import org.jetbrains.plugins.gradle.execution.GradleRunnerUtil.parseComparisonMessage import org.junit.Test class GradleRunnerUtilTest { @Test fun `parse comparison message test`() { fun check(pattern: String, first: String, second: String) { parseComparisonMessage(pattern).let { assertEquals(first, it.first) assertEquals(second, it.second) } } check("expected:<[foo]> but was:<[Foo ]>", "[foo]", "[Foo ]") check("the problem ==> expected:<[foo]> but was:<[Foo ]>", "[foo]", "[Foo ]") check("expected: <foo> but was: <Foo >", "foo", "Foo ") check("the problem ==> expected: <foo> but was: <Foo >", "foo", "Foo ") check("expected same:<foo> was not:<Foo >", "foo", "Foo ") check("the problem ==> expected same:<foo> was not:<Foo >", "foo", "Foo ") check("the problem ==> expected: <foo> but was: <Foo >", "foo", "Foo ") } }
apache-2.0
f0b600a841536b570b5343ab997847fc
39.464286
140
0.64841
3.699346
false
true
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToScopeIntention.kt
2
14740
// 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.intentions import com.intellij.java.refactoring.JavaRefactoringBundle import com.intellij.openapi.editor.Editor import com.intellij.psi.* import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.PsiTreeUtil import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.util.CommonRefactoringUtil import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.intentions.ConvertToScopeIntention.ScopeFunction.* import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters import org.jetbrains.kotlin.idea.base.util.useScope import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.codeinsight.utils.getLeftMostReceiverExpression import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.utils.addToStdlib.safeAs sealed class ConvertToScopeIntention(private val scopeFunction: ScopeFunction) : SelfTargetingIntention<KtExpression>( KtExpression::class.java, KotlinBundle.lazyMessage("convert.to.0", scopeFunction.functionName) ) { enum class ScopeFunction(val functionName: String, val isParameterScope: Boolean) { ALSO(functionName = "also", isParameterScope = true), APPLY(functionName = "apply", isParameterScope = false), RUN(functionName = "run", isParameterScope = false), WITH(functionName = "with", isParameterScope = false); val receiver = if (isParameterScope) "it" else "this" } private data class RefactoringTargetAndItsValueExpression( val targetElement: PsiElement, val targetElementValue: PsiElement ) private data class ScopedFunctionCallAndBlock( val scopeFunctionCall: KtExpression, val block: KtBlockExpression ) override fun isApplicableTo(element: KtExpression, caretOffset: Int) = tryApplyTo(element, dryRun = true) override fun applyTo(element: KtExpression, editor: Editor?) { if (!tryApplyTo(element, dryRun = false)) { val message = RefactoringBundle.getCannotRefactorMessage( JavaRefactoringBundle.message("refactoring.is.not.supported.in.the.current.context", text) ) CommonRefactoringUtil.showErrorHint(element.project, editor, message, text, null) } } private fun KtExpression.childOfBlock(): KtExpression? = PsiTreeUtil.findFirstParent(this) { val parent = it.parent parent is KtBlockExpression || parent is KtValueArgument } as? KtExpression private fun KtExpression.tryGetExpressionToApply(referenceName: String): KtExpression? { val childOfBlock: KtExpression = childOfBlock() ?: return null return if (childOfBlock is KtProperty || childOfBlock.isTarget(referenceName)) childOfBlock else null } private fun tryApplyTo(element: KtExpression, dryRun: Boolean): Boolean { val invalidElementToRefactoring = when (element) { is KtProperty -> !element.isLocal is KtCallExpression -> false is KtDotQualifiedExpression -> false else -> true } if (invalidElementToRefactoring) return false val (referenceElement, referenceName) = element.tryExtractReferenceName() ?: return false val expressionToApply = element.tryGetExpressionToApply(referenceName) ?: return false val (firstTarget, lastTarget) = expressionToApply.collectTargetElementsRange(referenceName, greedy = !dryRun) ?: return false val refactoringTarget = tryGetFirstElementToRefactoring(expressionToApply, firstTarget, lastTarget, referenceElement) ?: return false if (dryRun) return true val psiFactory = KtPsiFactory(expressionToApply) val (scopeFunctionCall, block) = createScopeFunctionCall( psiFactory, refactoringTarget.targetElement ) ?: return false replaceReference(referenceElement, refactoringTarget.targetElementValue, lastTarget, psiFactory) block.addRange(refactoringTarget.targetElementValue, lastTarget) if (!scopeFunction.isParameterScope) { removeRedundantThisQualifiers(block) } with(firstTarget) { parent.addBefore(scopeFunctionCall, this) parent.deleteChildRange(this, lastTarget) } return true } private fun removeRedundantThisQualifiers(block: KtBlockExpression) { val thisDotSomethingExpressions = block.collectDescendantsOfType<KtDotQualifiedExpression> { it.receiverExpression is KtThisExpression && it.selectorExpression !== null } thisDotSomethingExpressions.forEach { thisDotSomethingExpression -> thisDotSomethingExpression.selectorExpression?.let { selector -> thisDotSomethingExpression.replace(selector) } } } private fun tryGetFirstElementToRefactoring( expressionToApply: KtExpression, firstTarget: PsiElement, lastTarget: PsiElement, referenceElement: PsiElement ): RefactoringTargetAndItsValueExpression? { val property = expressionToApply.prevProperty() val propertyOrFirst = when (scopeFunction) { ALSO, APPLY -> property RUN, WITH -> firstTarget } ?: return null val isCorrectFirstOrProperty = when (scopeFunction) { ALSO, APPLY -> propertyOrFirst is KtProperty && propertyOrFirst.name !== null && propertyOrFirst.initializer !== null RUN -> propertyOrFirst is KtDotQualifiedExpression WITH -> propertyOrFirst is KtDotQualifiedExpression } if (!isCorrectFirstOrProperty) return null val targetElementValue = property?.nextSibling?.takeIf { it.parent == referenceElement.parent && it.textOffset < lastTarget.textOffset } ?: firstTarget return RefactoringTargetAndItsValueExpression(propertyOrFirst, targetElementValue) } private fun replaceReference(element: PsiElement, firstTarget: PsiElement, lastTarget: PsiElement, psiFactory: KtPsiFactory) { val replacement by lazy(LazyThreadSafetyMode.NONE) { if (scopeFunction.isParameterScope) psiFactory.createSimpleName(scopeFunction.receiver) else psiFactory.createThisExpression() } val searchParameters = KotlinReferencesSearchParameters( element, element.useScope(), ignoreAccessScope = false ) val range = PsiTreeUtil.getElementsOfRange(firstTarget, lastTarget) ReferencesSearch.search(searchParameters) .mapNotNull { it.element as? KtNameReferenceExpression } .filter { reference -> range.any { rangeElement -> PsiTreeUtil.isAncestor(rangeElement, reference, /* strict = */ true) } } .forEach { referenceInRange -> referenceInRange.replace(replacement) } } private fun KtExpression.tryExtractReferenceName(): Pair<PsiElement, String>? { return when (scopeFunction) { ALSO, APPLY -> { val property = prevProperty() val name = property?.name if (name !== null) property to name else null } RUN, WITH -> { val receiver = safeAs<KtDotQualifiedExpression>()?.getLeftMostReceiverExpression() as? KtNameReferenceExpression val declaration = receiver?.mainReference?.resolve()?.takeUnless { it is PsiPackage } ?: return null val selector = receiver.getQualifiedExpressionForReceiver()?.selectorExpression ?.let { it.safeAs<KtCallExpression>()?.calleeExpression ?: it } as? KtNameReferenceExpression if (selector?.mainReference?.resolve() is KtClassOrObject) return null declaration to receiver.getReferencedName() } } } private fun KtExpression.collectTargetElementsRange(referenceName: String, greedy: Boolean): Pair<PsiElement, PsiElement>? { return when (scopeFunction) { ALSO, APPLY -> { val firstTarget = this as? KtProperty ?: this.prevProperty() ?: this val lastTargetSequence = firstTarget.collectTargetElements(referenceName, forward = true) val lastTarget = if (firstTarget === this) if (greedy) lastTargetSequence.lastOrNull() else lastTargetSequence.firstOrNull() else if (greedy) lastTargetSequence.lastWithPersistedElementOrNull(elementShouldPersist = this) else lastTargetSequence.firstOrNull { this === it } if (lastTarget !== null) firstTarget to lastTarget else null } RUN, WITH -> { val firstTarget = collectTargetElements(referenceName, forward = false).lastOrNull() ?: this val lastTarget = if (greedy) collectTargetElements(referenceName, forward = true).lastOrNull() ?: this else this firstTarget to lastTarget } } } private fun KtExpression.collectTargetElements(referenceName: String, forward: Boolean): Sequence<PsiElement> = siblings(forward, withItself = false) .filter { it !is PsiWhiteSpace && it !is PsiComment && !(it is LeafPsiElement && it.elementType == KtTokens.SEMICOLON) } .takeWhile { it.isTarget(referenceName) } private fun PsiElement.isTarget(referenceName: String): Boolean { when (this) { is KtDotQualifiedExpression -> { val callExpr = callExpression ?: return false if (callExpr.lambdaArguments.isNotEmpty() || callExpr.valueArguments.any { it.text == scopeFunction.receiver } ) return false val leftMostReceiver = getLeftMostReceiverExpression() if (leftMostReceiver.text != referenceName) return false if (leftMostReceiver.mainReference?.resolve() is PsiClass) return false } is KtCallExpression -> { val valueArguments = this.valueArguments if (valueArguments.none { it.getArgumentExpression()?.text == referenceName }) return false if (lambdaArguments.isNotEmpty() || valueArguments.any { it.text == scopeFunction.receiver }) return false } is KtBinaryExpression -> { val left = this.left ?: return false val right = this.right ?: return false if (left !is KtDotQualifiedExpression && left !is KtCallExpression && right !is KtDotQualifiedExpression && right !is KtCallExpression ) return false if ((left is KtDotQualifiedExpression || left is KtCallExpression) && !left.isTarget(referenceName)) return false if ((right is KtDotQualifiedExpression || right is KtCallExpression) && !right.isTarget(referenceName)) return false } else -> return false } return !anyDescendantOfType<KtNameReferenceExpression> { it.text == scopeFunction.receiver } } private fun KtExpression.prevProperty(): KtProperty? = childOfBlock() ?.siblings(forward = false, withItself = true) ?.firstOrNull { it is KtProperty && it.isLocal } as? KtProperty private fun createScopeFunctionCall(factory: KtPsiFactory, element: PsiElement): ScopedFunctionCallAndBlock? { val scopeFunctionName = scopeFunction.functionName val (scopeFunctionCall, callExpression) = when (scopeFunction) { ALSO, APPLY -> { if (element !is KtProperty) return null val propertyName = element.name ?: return null val initializer = element.initializer ?: return null val initializerPattern = when (initializer) { is KtDotQualifiedExpression, is KtCallExpression, is KtConstantExpression, is KtParenthesizedExpression -> initializer.text else -> "(${initializer.text})" } val property = factory.createProperty( name = propertyName, type = element.typeReference?.text, isVar = element.isVar, initializer = "$initializerPattern.$scopeFunctionName {}" ) val callExpression = (property.initializer as? KtDotQualifiedExpression)?.callExpression ?: return null property to callExpression } RUN -> { if (element !is KtDotQualifiedExpression) return null val scopeFunctionCall = factory.createExpressionByPattern( "$0.$scopeFunctionName {}", element.getLeftMostReceiverExpression() ) as? KtQualifiedExpression ?: return null val callExpression = scopeFunctionCall.callExpression ?: return null scopeFunctionCall to callExpression } WITH -> { if (element !is KtDotQualifiedExpression) return null val scopeFunctionCall = factory.createExpressionByPattern( "$scopeFunctionName($0) {}", element.getLeftMostReceiverExpression() ) as? KtCallExpression ?: return null scopeFunctionCall to scopeFunctionCall } } val body = callExpression.lambdaArguments .firstOrNull() ?.getLambdaExpression() ?.bodyExpression ?: return null return ScopedFunctionCallAndBlock(scopeFunctionCall, body) } } class ConvertToAlsoIntention : ConvertToScopeIntention(ALSO) class ConvertToApplyIntention : ConvertToScopeIntention(APPLY) class ConvertToRunIntention : ConvertToScopeIntention(RUN) class ConvertToWithIntention : ConvertToScopeIntention(WITH)
apache-2.0
b6004c286a0d0e47b5f66c32f6aaa9d5
44.493827
158
0.665265
5.922057
false
false
false
false
jwren/intellij-community
plugins/kotlin/completion/tests/testData/basic/common/ExtensionWithManyTypeParamsInReceiver.kt
8
595
// FIR_IDENTICAL // FIR_COMPARISON open class Base class ManySome<T, U> fun <P1, P2>ManySome<P1, P2>.testExactGeneralGeneral() = "Some" fun <P1, P2>ManySome<P1, Int>.testExactGeneralInt() = "Some" fun <P1, P2>ManySome<Int, Int>.testExactIntInt() = "Some" fun <P1 : Base, P2>ManySome<P1, Int>.testSubBaseIntInt() = "Some" fun <P1, P2, P3>ManySome<P1, P2>.testManyGeneralGeneral() = "Some" fun some() { ManySome<Int, Int>().test<caret> } // EXIST: testExactGeneralGeneral // EXIST: testExactGeneralInt // EXIST: testExactIntInt // EXIST: testManyGeneralGeneral // ABSENT: testSubBaseIntInt
apache-2.0
ab4cc9b2f66426663bf7786ae6358b31
28.75
66
0.715966
2.729358
false
true
false
false
JetBrains/kotlin-native
build-tools/src/main/kotlin/org/jetbrains/kotlin/ExecClang.kt
1
5636
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin import org.gradle.api.Action import groovy.lang.Closure import org.gradle.api.GradleException import org.gradle.api.Project import org.gradle.process.ExecResult import org.gradle.process.ExecSpec import org.gradle.util.ConfigureUtil import org.jetbrains.kotlin.konan.target.* import org.jetbrains.kotlin.konan.file.* class ExecClang(private val project: Project) { private val platformManager = project.rootProject.findProperty("platformManager") as PlatformManager private fun konanArgs(target: KonanTarget): List<String> { return platformManager.platform(target).clang.clangArgsForKonanSources.asList() } fun konanArgs(targetName: String?): List<String> { val target = platformManager.targetManager(targetName).target return konanArgs(target) } fun resolveExecutable(executableOrNull: String?): String { val executable = executableOrNull ?: "clang" if (listOf("clang", "clang++").contains(executable)) { val llvmDir = project.findProperty("llvmDir") return "${llvmDir}/bin/$executable" } else { throw GradleException("unsupported clang executable: $executable") } } fun resolveToolchainExecutable(target: KonanTarget, executableOrNull: String?): String { val executable = executableOrNull ?: "clang" if (listOf("clang", "clang++").contains(executable)) { // TODO: This is copied from `BitcodeCompiler`. Consider sharing the code instead. val platform = platformManager.platform(target) return if (target.family.isAppleFamily) { "${platform.absoluteTargetToolchain}/usr/bin/$executable" } else { "${platform.absoluteTargetToolchain}/bin/$executable" } } else { throw GradleException("unsupported clang executable: $executable") } } // The bare ones invoke clang with system default sysroot. fun execBareClang(action: Action<in ExecSpec>): ExecResult { return this.execClang(emptyList<String>(), action) } fun execBareClang(closure: Closure<in ExecSpec>): ExecResult { return this.execClang(emptyList<String>(), closure) } // The konan ones invoke clang with konan provided sysroots. // So they require a target or assume it to be the host. // The target can be specified as KonanTarget or as a // (nullable, which means host) target name. fun execKonanClang(target: String?, action: Action<in ExecSpec>): ExecResult { return this.execClang(konanArgs(target), action) } fun execKonanClang(target: KonanTarget, action: Action<in ExecSpec>): ExecResult { return this.execClang(konanArgs(target), action) } fun execKonanClang(target: String?, closure: Closure<in ExecSpec>): ExecResult { return this.execClang(konanArgs(target), closure) } fun execKonanClang(target: KonanTarget, closure: Closure<in ExecSpec>): ExecResult { return this.execClang(konanArgs(target), closure) } // The toolchain ones execute clang from the toolchain. fun execToolchainClang(target: String?, action: Action<in ExecSpec>): ExecResult { return this.execToolchainClang(platformManager.targetManager(target).target, action) } fun execToolchainClang(target: String?, closure: Closure<in ExecSpec>): ExecResult { return this.execToolchainClang(platformManager.targetManager(target).target, ConfigureUtil.configureUsing(closure)) } fun execToolchainClang(target: KonanTarget, action: Action<in ExecSpec>): ExecResult { val extendedAction = Action<ExecSpec> { execSpec -> action.execute(execSpec) execSpec.apply { executable = resolveToolchainExecutable(target, executable) } } return project.exec(extendedAction) } fun execToolchainClang(target: KonanTarget, closure: Closure<in ExecSpec>): ExecResult { return this.execToolchainClang(target, ConfigureUtil.configureUsing(closure)) } // These ones are private, so one has to choose either Bare or Konan. private fun execClang(defaultArgs: List<String>, closure: Closure<in ExecSpec>): ExecResult { return this.execClang(defaultArgs, ConfigureUtil.configureUsing(closure)) } private fun execClang(defaultArgs: List<String>, action: Action<in ExecSpec>): ExecResult { val extendedAction = Action<ExecSpec> { execSpec -> action.execute(execSpec) execSpec.apply { executable = resolveExecutable(executable) val hostPlatform = project.findProperty("hostPlatform") as Platform environment["PATH"] = project.files(hostPlatform.clang.clangPaths).asPath + java.io.File.pathSeparator + environment["PATH"] args = args + defaultArgs } } return project.exec(extendedAction) } }
apache-2.0
010b2e85ac68be3c4f55ea6a4277b993
38.138889
123
0.686125
4.700584
false
false
false
false
fkorotkov/k8s-kotlin-dsl
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/admission/v1beta1/ClassBuilders.kt
1
932
// GENERATE package com.fkorotkov.kubernetes.admission.v1beta1 import io.fabric8.kubernetes.api.model.admission.v1beta1.AdmissionRequest as v1beta1_AdmissionRequest import io.fabric8.kubernetes.api.model.admission.v1beta1.AdmissionResponse as v1beta1_AdmissionResponse import io.fabric8.kubernetes.api.model.admission.v1beta1.AdmissionReview as v1beta1_AdmissionReview fun newAdmissionRequest(block : v1beta1_AdmissionRequest.() -> Unit = {}): v1beta1_AdmissionRequest { val instance = v1beta1_AdmissionRequest() instance.block() return instance } fun newAdmissionResponse(block : v1beta1_AdmissionResponse.() -> Unit = {}): v1beta1_AdmissionResponse { val instance = v1beta1_AdmissionResponse() instance.block() return instance } fun newAdmissionReview(block : v1beta1_AdmissionReview.() -> Unit = {}): v1beta1_AdmissionReview { val instance = v1beta1_AdmissionReview() instance.block() return instance }
mit
067f8724c6f0ebd4f83aa2a5347a4607
32.285714
104
0.790773
3.340502
false
false
false
false
shabtaisharon/ds3_java_browser
dsb-gui/src/main/java/com/spectralogic/dsbrowser/gui/services/jobService/factories/RecoverJobFactory.kt
1
3300
/* * *************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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.spectralogic.dsbrowser.gui.services.jobService.factories import com.spectralogic.dsbrowser.api.services.logging.LoggingService import com.spectralogic.dsbrowser.gui.DeepStorageBrowserPresenter import com.spectralogic.dsbrowser.gui.components.interruptedjobwindow.EndpointInfo import com.spectralogic.dsbrowser.gui.services.JobWorkers import com.spectralogic.dsbrowser.gui.services.Workers import com.spectralogic.dsbrowser.gui.services.jobService.JobTask import com.spectralogic.dsbrowser.gui.services.jobService.JobTaskElement import com.spectralogic.dsbrowser.util.andThen import com.spectralogic.dsbrowser.gui.services.jobService.RecoverJob import com.spectralogic.dsbrowser.gui.services.jobinterruption.JobInterruptionStore import com.spectralogic.dsbrowser.gui.util.treeItem.SafeHandler import org.slf4j.Logger import org.slf4j.LoggerFactory import java.util.* import javax.inject.Inject class RecoverJobFactory @Inject constructor(private val jobTaskElementFactory: JobTaskElement.JobTaskElementFactory, private val jobWorkers: JobWorkers, private val loggingService: LoggingService, private val jobInterruptionStore: JobInterruptionStore, private val workers: Workers, private val deepStorageBrowserPresenter: DeepStorageBrowserPresenter) { private companion object { private val LOG: Logger = LoggerFactory.getLogger(this::class.java) private const val TYPE: String = "Recover" } public fun create(uuid: UUID, endpointInfo: EndpointInfo, refreshBehavior: () -> Unit) { val client = endpointInfo.client jobTaskElementFactory.create(client) .let { RecoverJob(uuid, endpointInfo, it, client) } .let { it.getTask() } .let { JobTask(it) } .apply { onCancelled = SafeHandler.logHandle(onCancelled(client, TYPE, LOG, loggingService, jobInterruptionStore, workers, deepStorageBrowserPresenter).andThen(refreshBehavior)) onFailed = SafeHandler.logHandle(onFailed(client, jobInterruptionStore, deepStorageBrowserPresenter, loggingService, LOG, workers, TYPE).andThen(refreshBehavior)) onSucceeded = SafeHandler.logHandle(onSucceeded(TYPE, LOG).andThen(refreshBehavior)) } .also { jobWorkers.execute(it) } } }
apache-2.0
38691b3ceece36013f8145119c63da72
55.913793
188
0.67303
5.045872
false
false
false
false
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/core/dialog/ConfirmationDialog.kt
1
1644
package com.ivanovsky.passnotes.presentation.core.dialog import android.app.AlertDialog import android.app.Dialog import android.content.DialogInterface import android.os.Bundle import androidx.fragment.app.DialogFragment class ConfirmationDialog : DialogFragment(), DialogInterface.OnClickListener { lateinit var onConfirmationLister: () -> Unit private lateinit var message: String private lateinit var positiveButtonText: String private lateinit var negativeButtonText: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null) { dismiss() } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return AlertDialog.Builder(context) .setMessage(message) .setPositiveButton(positiveButtonText, this) .setNegativeButton(negativeButtonText, this) .create() } override fun onClick(dialog: DialogInterface?, which: Int) { if (which == DialogInterface.BUTTON_POSITIVE) { onConfirmationLister.invoke() } } companion object { val TAG = ConfirmationDialog::class.qualifiedName fun newInstance( message: String, positiveButtonText: String, negativeButtonText: String ): ConfirmationDialog { val dialog = ConfirmationDialog() dialog.message = message dialog.positiveButtonText = positiveButtonText dialog.negativeButtonText = negativeButtonText return dialog } } }
gpl-2.0
58dfefea7007ecaf511e27c7624986d0
30.037736
78
0.672141
5.871429
false
false
false
false
aosp-mirror/platform_frameworks_support
core/ktx/src/main/java/androidx/core/text/Html.kt
1
1848
/* * Copyright (C) 2018 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.core.text import android.annotation.SuppressLint import android.text.Html import android.text.Html.FROM_HTML_MODE_LEGACY import android.text.Html.ImageGetter import android.text.Html.TO_HTML_PARAGRAPH_LINES_CONSECUTIVE import android.text.Html.TagHandler import android.text.Spanned /** * Returns a [Spanned] from parsing this string as HTML. * * @param flags Additional option to set the behavior of the HTML parsing. Default is set to * [Html.FROM_HTML_MODE_LEGACY] which was introduced in API 24. * @param imageGetter Returns displayable styled text from the provided HTML string. * @param tagHandler Notified when HTML tags are encountered a tag the parser does * not know how to interpret. * * @see Html.fromHtml */ fun String.parseAsHtml( @SuppressLint("InlinedApi") flags: Int = FROM_HTML_MODE_LEGACY, imageGetter: ImageGetter? = null, tagHandler: TagHandler? = null ): Spanned = HtmlCompat.fromHtml(this, flags, imageGetter, tagHandler) /** * Returns a string of HTML from the spans in this [Spanned]. * * @see Html.toHtml */ fun Spanned.toHtml( @SuppressLint("InlinedApi") option: Int = TO_HTML_PARAGRAPH_LINES_CONSECUTIVE ): String = HtmlCompat.toHtml(this, option)
apache-2.0
6f5050b4fafcc9283bbcaebd7fb02415
35.235294
92
0.750541
3.898734
false
false
false
false
ognev-zair/Kotlin-AgendaCalendarView
kotlin-agendacalendarview/src/main/java/com/ognev/kotlin/agendacalendarview/agenda/AgendaView.kt
1
5048
package com.ognev.kotlin.agendacalendarview.agenda import android.animation.Animator import android.animation.ObjectAnimator import android.content.Context import android.support.v4.widget.SwipeRefreshLayout import android.util.AttributeSet import android.view.* import android.widget.FrameLayout import com.ognev.kotlin.agendacalendarview.CalendarManager import com.ognev.kotlin.agendacalendarview.utils.BusProvider import com.ognev.kotlin.agendacalendarview.utils.Events import com.ognev.kotlin.agendacalendarview.R class AgendaView : FrameLayout { lateinit var agendaListView: AgendaListView private set private var mShadowView: View? = null constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { val inflater = context .getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater inflater.inflate(R.layout.view_agenda, this, true) (findViewById(R.id.refresh_layout) as SwipeRefreshLayout).isEnabled = false } override fun onFinishInflate() { super.onFinishInflate() agendaListView = findViewById(R.id.agenda_listview) as AgendaListView mShadowView = findViewById(R.id.view_shadow) BusProvider.instance.toObserverable() .subscribe({ event -> if (event is Events.DayClickedEvent) { val clickedEvent = event agendaListView.scrollToCurrentDate(clickedEvent.calendar) } else if (event is Events.CalendarScrolledEvent) { val offset = (3 * getResources().getDimension(R.dimen.day_cell_height)) translateList(offset.toInt()) } else if (event is Events.EventsFetched) { (agendaListView.adapter as AgendaAdapter).updateEvents() viewTreeObserver.addOnGlobalLayoutListener( object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { if (width !== 0 && height !== 0) { // display only two visible rows on the calendar view val layoutParams = layoutParams as ViewGroup.MarginLayoutParams val height = height val margin = (getContext().getResources().getDimension(R.dimen.calendar_header_height) + 2 * getContext().getResources().getDimension(R.dimen.day_cell_height)) layoutParams.height = height layoutParams.setMargins(0, margin.toInt(), 0, 0) setLayoutParams(layoutParams) //todo if (!CalendarManager.instance!!.events.isEmpty()) agendaListView.scrollToCurrentDate(CalendarManager.instance!!.today) viewTreeObserver.removeGlobalOnLayoutListener(this) } } } ) } else if (event is Events.ForecastFetched) { (agendaListView.adapter as AgendaAdapter).updateEvents() } }) } override fun dispatchTouchEvent(event: MotionEvent): Boolean { val eventaction = event.action when (eventaction) { MotionEvent.ACTION_DOWN -> // if the user touches the listView, we put it back to the top translateList(0) else -> { } } return super.dispatchTouchEvent(event) } fun translateList(targetY: Int) { if (targetY != translationY.toInt()) { val mover = ObjectAnimator.ofFloat(this, "translationY", targetY.toFloat()) mover.duration = 150 mover.addListener(object : Animator.AnimatorListener { override fun onAnimationStart(animation: Animator) { mShadowView!!.visibility = GONE } override fun onAnimationEnd(animation: Animator) { if (targetY == 0) { BusProvider.instance.send(Events.AgendaListViewTouchedEvent()) } mShadowView!!.visibility = VISIBLE } override fun onAnimationCancel(animation: Animator) { } override fun onAnimationRepeat(animation: Animator) { } }) mover.start() } } }
apache-2.0
77fc8970dd83255283b2d9857f6dd77c
39.384
203
0.533281
6.081928
false
false
false
false
AlmasB/Zephyria
src/main/kotlin/com/almasb/zeph/ui/MessagesView.kt
1
1835
package com.almasb.zeph.ui import com.almasb.fxgl.dsl.FXGL import com.almasb.fxgl.dsl.getUIFactoryService import com.almasb.fxgl.ui.FXGLScrollPane import com.almasb.fxgl.ui.FontType import javafx.geometry.Insets import javafx.scene.Parent import javafx.scene.layout.HBox import javafx.scene.paint.Color import javafx.scene.shape.Circle import javafx.scene.shape.Rectangle import javafx.scene.shape.Shape /** * UI for displaying in-game messages. * * @author Almas Baimagambetov ([email protected]) */ class MessagesView() : Parent() { private val BG_WIDTH = 450.0 private val BG_HEIGHT = 170.0 val minBtn = MinimizeButton("V", BG_WIDTH / 2.0 - 15.5, -22.0, 0.0, BG_HEIGHT - 5, this) private val text = getUIFactoryService().newText( "In-game messages area:\n", Color.WHITE, FontType.TEXT, 14.0 ) init { initView() initScrollPane() } private fun initView() { layoutX = 0.0 layoutY = FXGL.getAppHeight() - BG_HEIGHT + 5.toDouble() val border = Rectangle(BG_WIDTH, BG_HEIGHT) border.strokeWidth = 2.0 border.arcWidth = 10.0 border.arcHeight = 10.0 val borderShape = Shape.union(border, Circle(BG_WIDTH / 2.0, 0.0, 30.0)) borderShape.fill = Color.rgb(25, 25, 25, 0.8) borderShape.stroke = Color.WHITE children.addAll(borderShape, minBtn) } private fun initScrollPane() { text.wrappingWidth = BG_WIDTH - 50.0 val scrollPane = FXGLScrollPane(text) scrollPane.layoutX = 10.0 scrollPane.layoutY = 10.0 scrollPane.setPrefSize(BG_WIDTH - 20.0, BG_HEIGHT - 20.0) //scrollPane.padding = Insets(10.0) children += scrollPane } fun appendMessage(message: String) { text.text += "$message\n" } }
gpl-2.0
b0f0abe9ddf070d587f3d1fec13e593b
25.985294
92
0.646866
3.576998
false
false
false
false
YouriAckx/AdventOfCode
2017/src/day02/part02a.kt
1
577
package day02 import java.io.File // Day 2: Corruption Checksum fun main(args: Array<String>) { val checksum = File("src/day02/input.txt").readLines().sumBy { line -> val values = line.split("\t").map { it.toInt() } val v = fun(): Int { for (x in values) { for (y in values) { if (x != y && x % y == 0) { return x / y } } } throw IllegalStateException(values.toString()) }() v } println(checksum) }
gpl-3.0
697917f61ed3b5a7d40c5b9640686fd7
24.130435
74
0.441941
4.151079
false
false
false
false
savoirfairelinux/ring-client-android
ring-android/app/src/main/java/cx/ring/account/AccountEditionFragment.kt
1
10674
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Author: Alexandre Lision <[email protected]> * Alexandre Savard <[email protected]> * Adrien Béraud <[email protected]> * Loïc Siret <[email protected]> * AmirHossein Naghshzan <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cx.ring.account import android.app.Activity import android.content.Context import android.os.Bundle import android.view.* import android.view.ViewTreeObserver.OnScrollChangedListener import android.widget.FrameLayout import android.widget.LinearLayout import androidx.annotation.StringRes import androidx.fragment.app.* import androidx.recyclerview.widget.RecyclerView import cx.ring.R import cx.ring.client.HomeActivity import cx.ring.contactrequests.BlockListFragment import cx.ring.databinding.FragAccountSettingsBinding import cx.ring.fragments.AdvancedAccountFragment import cx.ring.fragments.GeneralAccountFragment import cx.ring.fragments.MediaPreferenceFragment import cx.ring.fragments.SecurityAccountFragment import cx.ring.interfaces.BackHandlerInterface import cx.ring.mvp.BaseSupportFragment import cx.ring.utils.DeviceUtils import dagger.hilt.android.AndroidEntryPoint import net.jami.account.AccountEditionPresenter import net.jami.account.AccountEditionView @AndroidEntryPoint class AccountEditionFragment : BaseSupportFragment<AccountEditionPresenter, AccountEditionView>(), BackHandlerInterface, AccountEditionView, OnScrollChangedListener { private var mBinding: FragAccountSettingsBinding? = null private var mIsVisible = false private var mAccountId: String? = null private var mAccountIsJami = false override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return FragAccountSettingsBinding.inflate(inflater, container, false).apply { mBinding = this }.root } override fun onDestroyView() { super.onDestroyView() mBinding = null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { setHasOptionsMenu(true) super.onViewCreated(view, savedInstanceState) mAccountId = requireArguments().getString(ACCOUNT_ID_KEY) val activity = activity as HomeActivity? if (activity != null && DeviceUtils.isTablet(activity)) { activity.setTabletTitle(R.string.navigation_item_account) } mBinding!!.fragmentContainer.viewTreeObserver.addOnScrollChangedListener(this) presenter.init(mAccountId!!) } override fun displaySummary(accountId: String) { toggleView(accountId, true) val fragmentManager = childFragmentManager val existingFragment = fragmentManager.findFragmentByTag(JamiAccountSummaryFragment.TAG) val args = Bundle() args.putString(ACCOUNT_ID_KEY, accountId) if (existingFragment == null) { val fragment = JamiAccountSummaryFragment() fragment.arguments = args fragmentManager.beginTransaction() .add(R.id.fragment_container, fragment, JamiAccountSummaryFragment.TAG) .commit() } else { if (existingFragment is JamiAccountSummaryFragment) { if (!existingFragment.isStateSaved) existingFragment.arguments = args existingFragment.setAccount(accountId) } } } override fun displaySIPView(accountId: String) { toggleView(accountId, false) } override fun initViewPager(accountId: String, isJami: Boolean) { mBinding?.apply { pager.offscreenPageLimit = 4 pager.adapter = PreferencesPagerAdapter(childFragmentManager, requireContext(), accountId, isJami) slidingTabs.setupWithViewPager(pager) } val existingFragment = childFragmentManager.findFragmentByTag(BlockListFragment.TAG) as BlockListFragment? if (existingFragment != null) { if (!existingFragment.isStateSaved) existingFragment.arguments = Bundle().apply { putString(ACCOUNT_ID_KEY, accountId) } existingFragment.setAccount(accountId) } } override fun goToBlackList(accountId: String) { val blockListFragment = BlockListFragment() blockListFragment.arguments = Bundle().apply { putString(ACCOUNT_ID_KEY, accountId) } childFragmentManager.beginTransaction() .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .addToBackStack(BlockListFragment.TAG) .replace(R.id.fragment_container, blockListFragment, BlockListFragment.TAG) .commit() mBinding?.apply { slidingTabs.visibility = View.GONE pager.visibility = View.GONE fragmentContainer.visibility = View.VISIBLE } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { menu.clear() } override fun onResume() { super.onResume() presenter.bindView(this) } override fun onPause() { super.onPause() setBackListenerEnabled(false) } override fun onBackPressed(): Boolean { if (mBinding == null) return false mIsVisible = false if (mBinding!!.fragmentContainer.visibility != View.VISIBLE) { toggleView(mAccountId, mAccountIsJami) return true } val summaryFragment = childFragmentManager.findFragmentByTag(JamiAccountSummaryFragment.TAG) as JamiAccountSummaryFragment? return if (summaryFragment != null && summaryFragment.onBackPressed()) true else childFragmentManager.popBackStackImmediate() } private fun toggleView(accountId: String?, isJami: Boolean) { mAccountId = accountId mAccountIsJami = isJami mBinding?.apply { slidingTabs.visibility = if (isJami) View.GONE else View.VISIBLE pager.visibility = if (isJami) View.GONE else View.VISIBLE fragmentContainer.visibility = if (isJami) View.VISIBLE else View.GONE } setBackListenerEnabled(isJami) } override fun exit() { activity?.onBackPressed() } private fun setBackListenerEnabled(enable: Boolean) { val activity: Activity? = activity if (activity is HomeActivity) activity.setAccountFragmentOnBackPressedListener(if (enable) this else null) } private class PreferencesPagerAdapter constructor( fm: FragmentManager, private val mContext: Context, private val accountId: String, private val isJamiAccount: Boolean ) : FragmentStatePagerAdapter(fm) { override fun getCount(): Int = if (isJamiAccount) 3 else 4 override fun getItem(position: Int): Fragment { return if (isJamiAccount) getJamiPanel(position) else getSIPPanel(position) } override fun getPageTitle(position: Int): CharSequence = mContext.getString(if (isJamiAccount) getRingPanelTitle(position) else getSIPPanelTitle(position)) private fun getJamiPanel(position: Int): Fragment = when (position) { 0 -> fragmentWithBundle(GeneralAccountFragment()) 1 -> fragmentWithBundle(MediaPreferenceFragment()) 2 -> fragmentWithBundle(AdvancedAccountFragment()) else -> throw IllegalArgumentException() } private fun getSIPPanel(position: Int): Fragment = when (position) { 0 -> GeneralAccountFragment.newInstance(accountId) 1 -> MediaPreferenceFragment.newInstance(accountId) 2 -> fragmentWithBundle(AdvancedAccountFragment()) 3 -> fragmentWithBundle(SecurityAccountFragment()) else -> throw IllegalArgumentException() } private fun fragmentWithBundle(result: Fragment): Fragment = result.apply { arguments = Bundle().apply { putString(ACCOUNT_ID_KEY, accountId) } } companion object { @StringRes private fun getRingPanelTitle(position: Int) = when (position) { 0 -> R.string.account_preferences_basic_tab 1 -> R.string.account_preferences_media_tab 2 -> R.string.account_preferences_advanced_tab else -> -1 } @StringRes private fun getSIPPanelTitle(position: Int) = when (position) { 0 -> R.string.account_preferences_basic_tab 1 -> R.string.account_preferences_media_tab 2 -> R.string.account_preferences_advanced_tab 3 -> R.string.account_preferences_security_tab else -> -1 } } } override fun onScrollChanged() { setupElevation() } private fun setupElevation() { val binding = mBinding ?: return if (!mIsVisible) return val activity: FragmentActivity = activity as? HomeActivity ?: return val ll = binding.pager.getChildAt(binding.pager.currentItem) as LinearLayout val rv = (ll.getChildAt(0) as FrameLayout).getChildAt(0) as RecyclerView val homeActivity = activity as HomeActivity if (rv.canScrollVertically(SCROLL_DIRECTION_UP)) { binding.slidingTabs.elevation = binding.slidingTabs.resources.getDimension(R.dimen.toolbar_elevation) homeActivity.setToolbarElevation(true) } else { binding.slidingTabs.elevation = 0f homeActivity.setToolbarElevation(false) } } companion object { private val TAG = AccountEditionFragment::class.simpleName val ACCOUNT_ID_KEY = AccountEditionFragment::class.qualifiedName + "accountId" val ACCOUNT_HAS_PASSWORD_KEY = AccountEditionFragment::class.qualifiedName + "hasPassword" private const val SCROLL_DIRECTION_UP = -1 } }
gpl-3.0
69cd66afacf30bfe1601df47d170a81e
39.89272
163
0.682065
4.94532
false
false
false
false
firebase/quickstart-android
firestore/app/src/main/java/com/google/firebase/example/fireeats/kotlin/RestaurantDetailFragment.kt
1
7975
package com.google.firebase.example.fireeats.kotlin import android.content.Context import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.bumptech.glide.Glide import com.google.android.gms.tasks.Task import com.google.android.material.snackbar.Snackbar import com.google.firebase.example.fireeats.R import com.google.firebase.example.fireeats.databinding.FragmentRestaurantDetailBinding import com.google.firebase.example.fireeats.kotlin.adapter.RatingAdapter import com.google.firebase.example.fireeats.kotlin.model.Rating import com.google.firebase.example.fireeats.kotlin.model.Restaurant import com.google.firebase.example.fireeats.kotlin.util.RestaurantUtil import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.EventListener import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.FirebaseFirestoreException import com.google.firebase.firestore.ListenerRegistration import com.google.firebase.firestore.Query import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.ktx.toObject import com.google.firebase.ktx.Firebase class RestaurantDetailFragment : Fragment(), EventListener<DocumentSnapshot>, RatingDialogFragment.RatingListener { private var ratingDialog: RatingDialogFragment? = null private lateinit var binding: FragmentRestaurantDetailBinding private lateinit var firestore: FirebaseFirestore private lateinit var restaurantRef: DocumentReference private lateinit var ratingAdapter: RatingAdapter private var restaurantRegistration: ListenerRegistration? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentRestaurantDetailBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Get restaurant ID from extras val restaurantId = RestaurantDetailFragmentArgs.fromBundle(requireArguments()).keyRestaurantId // Initialize Firestore firestore = Firebase.firestore // Get reference to the restaurant restaurantRef = firestore.collection("restaurants").document(restaurantId) // Get ratings val ratingsQuery = restaurantRef .collection("ratings") .orderBy("timestamp", Query.Direction.DESCENDING) .limit(50) // RecyclerView ratingAdapter = object : RatingAdapter(ratingsQuery) { override fun onDataChanged() { if (itemCount == 0) { binding.recyclerRatings.visibility = View.GONE binding.viewEmptyRatings.visibility = View.VISIBLE } else { binding.recyclerRatings.visibility = View.VISIBLE binding.viewEmptyRatings.visibility = View.GONE } } } binding.recyclerRatings.layoutManager = LinearLayoutManager(context) binding.recyclerRatings.adapter = ratingAdapter ratingDialog = RatingDialogFragment() binding.restaurantButtonBack.setOnClickListener { onBackArrowClicked() } binding.fabShowRatingDialog.setOnClickListener { onAddRatingClicked() } } public override fun onStart() { super.onStart() ratingAdapter.startListening() restaurantRegistration = restaurantRef.addSnapshotListener(this) } public override fun onStop() { super.onStop() ratingAdapter.stopListening() restaurantRegistration?.remove() restaurantRegistration = null } /** * Listener for the Restaurant document ([.restaurantRef]). */ override fun onEvent(snapshot: DocumentSnapshot?, e: FirebaseFirestoreException?) { if (e != null) { Log.w(TAG, "restaurant:onEvent", e) return } snapshot?.let { val restaurant = snapshot.toObject<Restaurant>() if (restaurant != null) { onRestaurantLoaded(restaurant) } } } private fun onRestaurantLoaded(restaurant: Restaurant) { binding.restaurantName.text = restaurant.name binding.restaurantRating.rating = restaurant.avgRating.toFloat() binding.restaurantNumRatings.text = getString(R.string.fmt_num_ratings, restaurant.numRatings) binding.restaurantCity.text = restaurant.city binding.restaurantCategory.text = restaurant.category binding.restaurantPrice.text = RestaurantUtil.getPriceString(restaurant) // Background image Glide.with(binding.restaurantImage.context) .load(restaurant.photo) .into(binding.restaurantImage) } private fun onBackArrowClicked() { findNavController().popBackStack() } private fun onAddRatingClicked() { ratingDialog?.show(childFragmentManager, RatingDialogFragment.TAG) } override fun onRating(rating: Rating) { // In a transaction, add the new rating and update the aggregate totals addRating(restaurantRef, rating) .addOnSuccessListener(requireActivity()) { Log.d(TAG, "Rating added") // Hide keyboard and scroll to top hideKeyboard() binding.recyclerRatings.smoothScrollToPosition(0) } .addOnFailureListener(requireActivity()) { e -> Log.w(TAG, "Add rating failed", e) // Show failure message and hide keyboard hideKeyboard() Snackbar.make( requireView().findViewById(android.R.id.content), "Failed to add rating", Snackbar.LENGTH_SHORT).show() } } private fun addRating(restaurantRef: DocumentReference, rating: Rating): Task<Void> { // Create reference for new rating, for use inside the transaction val ratingRef = restaurantRef.collection("ratings").document() // In a transaction, add the new rating and update the aggregate totals return firestore.runTransaction { transaction -> val restaurant = transaction.get(restaurantRef).toObject<Restaurant>() if (restaurant == null) { throw Exception("Resraurant not found at ${restaurantRef.path}") } // Compute new number of ratings val newNumRatings = restaurant.numRatings + 1 // Compute new average rating val oldRatingTotal = restaurant.avgRating * restaurant.numRatings val newAvgRating = (oldRatingTotal + rating.rating) / newNumRatings // Set new restaurant info restaurant.numRatings = newNumRatings restaurant.avgRating = newAvgRating // Commit to Firestore transaction.set(restaurantRef, restaurant) transaction.set(ratingRef, rating) null } } private fun hideKeyboard() { val view = requireActivity().currentFocus if (view != null) { (requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow(view.windowToken, 0) } } companion object { private const val TAG = "RestaurantDetail" const val KEY_RESTAURANT_ID = "key_restaurant_id" } }
apache-2.0
66e403fe5582287c5df91a9e96a97b9d
36.97619
116
0.676991
5.373989
false
false
false
false
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/api/remote/serialization/ParcelableSerializer.kt
1
1887
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.google.android.libraries.pcc.chronicle.api.remote.serialization import android.os.Parcelable import com.google.android.libraries.pcc.chronicle.api.remote.RemoteEntity import com.google.android.libraries.pcc.chronicle.api.remote.interpretParcelableEntity import com.google.android.libraries.pcc.chronicle.api.storage.WrappedEntity import kotlin.reflect.KClass /** * Implementation of [Serializer] dealing with [Parcelables][Parcelable] of type [T]. * * **Note:** Do not use parcelables without fully understanding the version skew and conditional * usage ramifications of doing so. */ class ParcelableSerializer<T : Parcelable> private constructor() : Serializer<T> { override fun <P : T> serialize(wrappedEntity: WrappedEntity<P>): RemoteEntity = RemoteEntity.fromParcelable( metadata = wrappedEntity.metadata, parcelable = wrappedEntity.entity ) override fun <P : T> deserialize(remoteEntity: RemoteEntity): WrappedEntity<P> = WrappedEntity( metadata = remoteEntity.metadata, entity = remoteEntity.interpretParcelableEntity() ) companion object { /** Creates a [Serializer] from the given [KClass] for a [Parcelable]. */ fun <T : Parcelable> createFrom(cls: KClass<T>): Serializer<T> = ParcelableSerializer() } }
apache-2.0
0c7f1aac04f5d538cb6df205ff779384
38.3125
96
0.749868
4.25
false
false
false
false
AlmasB/FXGL
fxgl/src/test/kotlin/com/almasb/fxgl/dsl/components/OffscreenCleanComponentTest.kt
1
2585
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.dsl.components import com.almasb.fxgl.app.scene.Viewport import com.almasb.fxgl.entity.Entity import com.almasb.fxgl.entity.GameWorld import com.almasb.fxgl.physics.BoundingShape import com.almasb.fxgl.physics.HitBox import javafx.util.Duration import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.contains import org.hamcrest.Matchers.lessThan import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test /** * * * @author Almas Baimagambetov ([email protected]) */ class OffscreenCleanComponentTest { private lateinit var viewport: Viewport @BeforeEach fun setUp() { viewport = Viewport(800.0, 600.0) } @Test fun `Entity is removed from world when entity moves offscreen`() { val e = Entity() e.addComponent(OffscreenCleanComponent(viewport)) val world = GameWorld() world.addEntity(e) assertThat(world.entities, contains(e)) world.onUpdate(0.016) assertThat(world.entities, contains(e)) e.x = -15.0 world.onUpdate(0.016) assertTrue(world.entities.isEmpty()) } @Test fun `Entity is removed from world when entity with bbox moves offscreen`() { val e = Entity() e.addComponent(OffscreenCleanComponent(viewport)) e.boundingBoxComponent.addHitBox(HitBox(BoundingShape.box(30.0, 30.0))) val world = GameWorld() world.addEntity(e) assertThat(world.entities, contains(e)) world.onUpdate(0.016) assertThat(world.entities, contains(e)) e.x = -25.0 world.onUpdate(0.016) assertThat(world.entities, contains(e)) e.x = -30.0 world.onUpdate(0.016) assertThat(world.entities, contains(e)) e.x = -31.0 world.onUpdate(0.016) assertTrue(world.entities.isEmpty()) } @Test fun `Entity is removed from world when viewport moves offscreen`() { val e = Entity() e.addComponent(OffscreenCleanComponent(viewport)) val world = GameWorld() world.addEntity(e) assertThat(world.entities, contains(e)) world.onUpdate(0.016) assertThat(world.entities, contains(e)) viewport.x = 5.0 world.onUpdate(0.016) assertTrue(world.entities.isEmpty()) } }
mit
2db5d217b0fa16c6d1de9db53887473a
24.352941
80
0.662282
3.928571
false
false
false
false
sproshev/tcity
app/src/main/kotlin/com/tcity/android/app/Preferences.kt
1
5272
/* * Copyright 2014 Semyon Proshev * * 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.tcity.android.app import android.content.Context import android.preference.PreferenceManager import android.util.Base64 import com.tcity.android.R import com.tcity.android.db.DBUtils import com.tcity.android.sync.SyncUtils public class Preferences(context: Context) { private val preferences = PreferenceManager.getDefaultSharedPreferences(context) private val syncKey = context.getString(R.string.sync_pref_key) private val syncWifiOnlyKey = context.getString(R.string.sync_wifi_only_pref_key) private val syncIntervalKey = context.getString(R.string.sync_interval_pref_key) private val archivedBuildLogKey = context.getString(R.string.archived_build_log_pref_key) class object { private val URL_KEY = "url" private val LOGIN_KEY = "login" private val AUTH_KEY = "auth" private val SYNC_RECEIVER_KEY = "sync_receiver" private val SYNC_SCHEDULED_KEY = "sync_scheduled" private val FAVOURITE_PROJECTS_LAST_UPDATE_KEY = "favourite_projects_last_update" private val SERVER_VERSION_KEY = "server_version" private val SERVER_VERSION_LAST_UPDATE_KEY = "server_version_last_update" } public fun isValid(): Boolean { return preferences.contains(URL_KEY) && preferences.contains(LOGIN_KEY) && preferences.contains(AUTH_KEY) } public fun getUrl(): String = preferences.getString(URL_KEY, null) public fun getLogin(): String = preferences.getString(LOGIN_KEY, null) public fun getAuth(): String = preferences.getString(AUTH_KEY, null) public fun isSyncEnabled(): Boolean = preferences.getBoolean(syncKey, true) public fun isSyncWifiOnly(): Boolean = preferences.getBoolean(syncWifiOnlyKey, true) public fun isSyncReceiverEnabled(): Boolean = preferences.getBoolean(SYNC_RECEIVER_KEY, false) public fun isSyncScheduled(): Boolean = preferences.getBoolean(SYNC_SCHEDULED_KEY, false) public fun isBuildLogArchived(): Boolean = preferences.getBoolean(archivedBuildLogKey, true) public fun getFavouriteProjectsLastUpdate(): Long { return preferences.getLong(FAVOURITE_PROJECTS_LAST_UPDATE_KEY, DBUtils.UNDEFINED_TIME) } public fun getSyncInterval(): Int { return preferences.getInt(syncIntervalKey, SyncUtils.DEFAULT_INTERVAL) } public fun getServerVersion(): String? = preferences.getString(SERVER_VERSION_KEY, null) public fun getServerVersionLastUpdate(): Long { return preferences.getLong(SERVER_VERSION_LAST_UPDATE_KEY, DBUtils.UNDEFINED_TIME) } public fun setUrl(url: String) { val editor = preferences.edit() editor.putString(URL_KEY, url) editor.apply() } public fun setAuth(login: String, password: String) { val editor = preferences.edit() editor.putString(LOGIN_KEY, login) editor.putString(AUTH_KEY, Base64.encodeToString("$login:$password".toByteArray(), Base64.NO_WRAP)) editor.apply() } public fun setSyncEnabled(enabled: Boolean) { val editor = preferences.edit() editor.putBoolean(syncKey, enabled) editor.apply() } public fun setSyncWifiOnly(wifiOnly: Boolean) { val editor = preferences.edit() editor.putBoolean(syncWifiOnlyKey, wifiOnly) editor.apply() } public fun setSyncReceiverEnabled(enabled: Boolean) { val editor = preferences.edit() editor.putBoolean(SYNC_RECEIVER_KEY, enabled) editor.apply() } public fun setSyncScheduled(scheduled: Boolean) { val editor = preferences.edit() editor.putBoolean(SYNC_SCHEDULED_KEY, scheduled) editor.apply() } public fun setFavouriteProjectsLastUpdate(time: Long) { val editor = preferences.edit() editor.putLong(FAVOURITE_PROJECTS_LAST_UPDATE_KEY, time) editor.apply() } public fun setSyncInterval(interval: Int) { val editor = preferences.edit() if (interval < SyncUtils.MIN_INTERVAL) { editor.putInt(syncIntervalKey, SyncUtils.MIN_INTERVAL) } else if (interval > SyncUtils.MAX_INTERVAL) { editor.putInt(syncIntervalKey, SyncUtils.MAX_INTERVAL) } else { editor.putInt(syncIntervalKey, interval) } editor.apply() } public fun setServerVersion(version: String) { val editor = preferences.edit(); editor.putString(SERVER_VERSION_KEY, version) editor.putLong(SERVER_VERSION_LAST_UPDATE_KEY, System.currentTimeMillis()) editor.apply() } public fun reset() { preferences.edit().clear().apply() } }
apache-2.0
8c69b2b12a67e53ec9f35be087f0a739
30.759036
113
0.694423
4.220977
false
false
false
false
arcao/Geocaching4Locus
geocaching-api/src/main/java/com/arcao/geocaching4locus/data/api/endpoint/GeocachingApiEndpoint.kt
1
5107
package com.arcao.geocaching4locus.data.api.endpoint import com.arcao.geocaching4locus.data.api.model.Geocache import com.arcao.geocaching4locus.data.api.model.GeocacheList import com.arcao.geocaching4locus.data.api.model.GeocacheLog import com.arcao.geocaching4locus.data.api.model.Image import com.arcao.geocaching4locus.data.api.model.Trackable import com.arcao.geocaching4locus.data.api.model.User import com.arcao.geocaching4locus.data.api.model.request.GeocacheExpand import com.arcao.geocaching4locus.data.api.model.request.GeocacheLogExpand import com.arcao.geocaching4locus.data.api.model.request.GeocacheSort import com.arcao.geocaching4locus.data.api.model.request.GeocacheTrackableExpand import com.arcao.geocaching4locus.data.api.model.request.query.GeocacheQuery import com.arcao.geocaching4locus.data.api.model.response.PagedList import kotlinx.coroutines.Deferred import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Path import retrofit2.http.Query interface GeocachingApiEndpoint { @GET("/v1/geocaches/search") fun searchAsync( @Query("q") q: GeocacheQuery, @Query("sort") sort: GeocacheSort? = null, @Query("lite") lite: Boolean = true, @Query("skip") skip: Int = 0, @Query("take") take: Int = 10, @Query("fields") fields: String = Geocache.FIELDS_LITE, @Query("expand") expand: GeocacheExpand = GeocacheExpand() ): Deferred<PagedList<Geocache>> @GET("/v1/geocaches") fun geocachesAsync( @Query("referenceCodes") referenceCodes: String, @Query("lite") lite: Boolean = true, @Query("fields") fields: String = Geocache.FIELDS_LITE, @Query("expand") expand: GeocacheExpand = GeocacheExpand() ): Deferred<List<Geocache>> @GET("/v1/geocaches/{referenceCode}") fun geocacheAsync( @Path("referenceCode") referenceCode: String, @Query("lite") lite: Boolean = true, @Query("fields") fields: String = Geocache.FIELDS_LITE, @Query("expand") expand: GeocacheExpand = GeocacheExpand() ): Deferred<Geocache> @GET("/v1/geocaches/{referenceCode}/images") fun geocacheImagesAsync( @Path("referenceCode") referenceCode: String, @Query("skip") skip: Int = 0, @Query("take") take: Int = 10, @Query("fields") fields: String = Image.FIELDS_ALL ): Deferred<PagedList<Image>> @GET("/v1/geocaches/{referenceCode}/geocacheLogs") fun geocacheLogsAsync( @Path("referenceCode") referenceCode: String, @Query("fields") fields: String = GeocacheLog.FIELDS_ALL, @Query("expand") expand: GeocacheLogExpand = GeocacheLogExpand(), @Query("skip") skip: Int = 0, @Query("take") take: Int = 10 ): Deferred<PagedList<GeocacheLog>> @GET("/v1/geocaches/{referenceCode}/trackables") fun geocacheTrackablesAsync( @Path("referenceCode") referenceCode: String, @Query("fields") fields: String = Trackable.FIELDS_ALL, @Query("expand") expand: GeocacheTrackableExpand = GeocacheTrackableExpand(), @Query("skip") skip: Int = 0, @Query("take") take: Int = 10 ): Deferred<PagedList<Trackable>> @POST("/v1/lists/") fun createListAsync( @Body list: GeocacheList, @Query("fields") fields: String = GeocacheList.FIELDS_ALL ): Deferred<GeocacheList> @PUT("/v1/lists/{referenceCode}") fun updateListAsync( @Path("referenceCode") referenceCode: String, @Body list: GeocacheList, @Query("fields") fields: String = GeocacheList.FIELDS_ALL ): Deferred<GeocacheList> @DELETE("/v1/lists/{referenceCode}") fun deleteListAsync( @Path("referenceCode") referenceCode: String ): Deferred<Void> @GET("/v1/lists/{referenceCode}/geocaches") fun listGeocachesAsync( @Path("referenceCode") referenceCode: String, @Query("fields") fields: String = Geocache.FIELDS_LITE, @Query("skip") skip: Int = 0, @Query("take") take: Int = 10, @Query("lite") lite: Boolean = true, @Query("expand") expand: GeocacheExpand = GeocacheExpand() ): Deferred<PagedList<Geocache>> @GET("/v1/users/{referenceCode}") fun userAsync( @Path("referenceCode") referenceCode: String = "me", @Query("fields") fields: String = User.FIELDS_ALL ): Deferred<User> @GET("/v1/users/{referenceCode}/lists") fun userListsAsync( @Path("referenceCode") referenceCode: String = "me", @Query("types") types: String = "bm", @Query("fields") fields: String = GeocacheList.FIELDS_ALL, @Query("skip") skip: Int = 0, @Query("take") take: Int = 10 ): Deferred<PagedList<GeocacheList>> @GET("/v1/friends") fun friendsAsync( @Query("skip") skip: Int = 0, @Query("take") take: Int = 10, @Query("fields") fields: String = User.FIELDS_ALL ): Deferred<PagedList<User>> @GET("/status/ping") fun pingAsync(): Deferred<Void> }
gpl-3.0
9876f820bc7851c8f3f5ec9b4e701d06
38.284615
85
0.672215
3.845633
false
false
false
false
commons-app/apps-android-commons
app/src/main/java/fr/free/nrw/commons/upload/FileProcessor.kt
2
7836
package fr.free.nrw.commons.upload import android.content.ContentResolver import android.content.Context import android.net.Uri import androidx.exifinterface.media.ExifInterface import fr.free.nrw.commons.R import fr.free.nrw.commons.kvstore.JsonKvStore import fr.free.nrw.commons.mwapi.CategoryApi import fr.free.nrw.commons.mwapi.OkHttpJsonApiClient import fr.free.nrw.commons.settings.Prefs import fr.free.nrw.commons.upload.structure.depictions.DepictModel import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import timber.log.Timber import java.io.File import java.io.IOException import java.util.* import javax.inject.Inject import javax.inject.Named /** * Processing of the image filePath that is about to be uploaded via ShareActivity is done here */ private const val DEFAULT_SUGGESTION_RADIUS_IN_METRES = 100 private const val MAX_SUGGESTION_RADIUS_IN_METRES = 1000 private const val RADIUS_STEP_SIZE_IN_METRES = 100 private const val MIN_NEARBY_RESULTS = 5 class FileProcessor @Inject constructor( private val context: Context, private val contentResolver: ContentResolver, private val gpsCategoryModel: GpsCategoryModel, private val depictsModel: DepictModel, @param:Named("default_preferences") private val defaultKvStore: JsonKvStore, private val apiCall: CategoryApi, private val okHttpJsonApiClient: OkHttpJsonApiClient ) { private val compositeDisposable = CompositeDisposable() fun cleanup() { compositeDisposable.clear() } /** * Processes filePath coordinates, either from EXIF data or user location */ fun processFileCoordinates(similarImageInterface: SimilarImageInterface, filePath: String?) : ImageCoordinates { val exifInterface: ExifInterface? = try { ExifInterface(filePath!!) } catch (e: IOException) { Timber.e(e) null } // Redact EXIF data as indicated in preferences. redactExifTags(exifInterface, getExifTagsToRedact()) Timber.d("Calling GPSExtractor") val originalImageCoordinates = ImageCoordinates(exifInterface) if (originalImageCoordinates.decimalCoords == null) { //Find other photos taken around the same time which has gps coordinates findOtherImages( File(filePath), similarImageInterface ) } else { prePopulateCategoriesAndDepictionsBy(originalImageCoordinates) } return originalImageCoordinates } /** * Gets EXIF Tags from preferences to be redacted. * * @return tags to be redacted */ fun getExifTagsToRedact(): Set<String> { val prefManageEXIFTags = defaultKvStore.getStringSet(Prefs.MANAGED_EXIF_TAGS) ?: emptySet() val redactTags: Set<String> = context.resources.getStringArray(R.array.pref_exifTag_values).toSet() return redactTags - prefManageEXIFTags } /** * Redacts EXIF metadata as indicated in preferences. * * @param exifInterface ExifInterface object * @param redactTags tags to be redacted */ fun redactExifTags(exifInterface: ExifInterface?, redactTags: Set<String>) { compositeDisposable.add( Observable.fromIterable(redactTags) .flatMap { Observable.fromArray(*FileMetadataUtils.getTagsFromPref(it)) } .subscribe( { redactTag(exifInterface, it) }, { Timber.d(it) }, { save(exifInterface) } ) ) } private fun save(exifInterface: ExifInterface?) { try { exifInterface?.saveAttributes() } catch (e: IOException) { Timber.w("EXIF redaction failed: %s", e.toString()) } } private fun redactTag(exifInterface: ExifInterface?, tag: String) { Timber.d("Checking for tag: %s", tag) exifInterface?.getAttribute(tag) ?.takeIf { it.isNotEmpty() } ?.let { attributeName -> exifInterface.setAttribute(tag, null).also { Timber.d("Exif tag $tag with value $attributeName redacted.") } } } /** * Find other images around the same location that were taken within the last 20 sec * * @param originalImageCoordinates * @param fileBeingProcessed * @param similarImageInterface */ private fun findOtherImages( fileBeingProcessed: File, similarImageInterface: SimilarImageInterface ) { val oneHundredAndTwentySeconds = 120 * 1000L //Time when the original image was created val timeOfCreation = fileBeingProcessed.lastModified() LongRange val timeOfCreationRange = timeOfCreation - oneHundredAndTwentySeconds..timeOfCreation + oneHundredAndTwentySeconds fileBeingProcessed.parentFile .listFiles() .asSequence() .filter { it.lastModified() in timeOfCreationRange } .map { Pair(it, readImageCoordinates(it)) } .firstOrNull { it.second?.decimalCoords != null } ?.let { fileCoordinatesPair -> similarImageInterface.showSimilarImageFragment( fileBeingProcessed.path, fileCoordinatesPair.first.absolutePath, fileCoordinatesPair.second ) } } private fun readImageCoordinates(file: File) = try { ImageCoordinates(contentResolver.openInputStream(Uri.fromFile(file))!!) } catch (e: IOException) { Timber.e(e) try { ImageCoordinates(file.absolutePath) } catch (ex: IOException) { Timber.e(ex) null } } /** * Initiates retrieval of image coordinates or user coordinates, and caching of coordinates. Then * initiates the calls to MediaWiki API through an instance of CategoryApi. * * @param imageCoordinates */ fun prePopulateCategoriesAndDepictionsBy(imageCoordinates: ImageCoordinates) { requireNotNull(imageCoordinates.decimalCoords) compositeDisposable.add( apiCall.request(imageCoordinates.decimalCoords) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.io()) .subscribe( gpsCategoryModel::setCategoriesFromLocation, { Timber.e(it) gpsCategoryModel.clear() } ) ) compositeDisposable.add( suggestNearbyDepictions(imageCoordinates) ) } private val radiiProgressionInMetres = (DEFAULT_SUGGESTION_RADIUS_IN_METRES..MAX_SUGGESTION_RADIUS_IN_METRES step RADIUS_STEP_SIZE_IN_METRES) private fun suggestNearbyDepictions(imageCoordinates: ImageCoordinates): Disposable { return Observable.fromIterable(radiiProgressionInMetres.map { it / 1000.0 }) .concatMap { Observable.fromCallable { okHttpJsonApiClient.getNearbyPlaces( imageCoordinates.latLng, Locale.getDefault().language, it, false ) } } .subscribeOn(Schedulers.io()) .filter { it.size >= MIN_NEARBY_RESULTS } .take(1) .subscribe( { depictsModel.nearbyPlaces.offer(it) }, { Timber.e(it) } ) } }
apache-2.0
9cf458dea3cb36dc40f31d0fb6103055
34.780822
110
0.624043
5.016645
false
false
false
false