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
herolynx/elepantry-android
app/src/main/java/com/herolynx/elepantry/ext/dropbox/drive/DropBoxFile.kt
1
1484
package com.herolynx.elepantry.ext.dropbox.drive import com.dropbox.core.v2.files.FileMetadata import com.dropbox.core.v2.files.FolderMetadata import com.dropbox.core.v2.files.Metadata import com.dropbox.core.v2.files.SearchMatch import com.herolynx.elepantry.core.generic.toISO8601 import com.herolynx.elepantry.drive.DriveType import com.herolynx.elepantry.resources.core.model.Resource import org.funktionale.option.Option internal fun Metadata.toResource(): Option<Resource> { if (this is FolderMetadata) return Option.None else return Option.Some((this as FileMetadata).toResource()) } internal fun FileMetadata.toResource(): Resource { val f = this return Resource( id = f.id, name = f.name, type = DriveType.DROP_BOX, extension = getExtension(), mimeType = "", tags = listOf(), createdTime = f.serverModified.toISO8601().getOrElse { "" }, lastModifiedDate = f.clientModified.toISO8601().getOrElse { "" }, webViewLink = f.pathLower, downloadLink = f.pathLower, thumbnailLink = f.pathLower, iconLink = null, version = f.rev ) } internal fun SearchMatch.toResource(): Option<Resource> = metadata.toResource() internal fun FileMetadata.getExtension(): String? { val nameExtIdx = name.lastIndexOf('.') if (nameExtIdx > 0) { return name.substring(nameExtIdx + 1) } return null }
gpl-3.0
3ad771e7fb8c77706f002b48cf77fcb1
32.75
79
0.672507
4.010811
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/ui/views/viewer/VolumeController.kt
1
4252
package com.pr0gramm.app.ui.views.viewer import android.content.Context import android.content.SharedPreferences import android.graphics.drawable.Drawable import android.media.AudioManager import android.widget.ImageView import androidx.appcompat.content.res.AppCompatResources import androidx.core.content.edit import com.google.android.exoplayer2.SimpleExoPlayer import com.pr0gramm.app.Duration import com.pr0gramm.app.Logger import com.pr0gramm.app.R import com.pr0gramm.app.Settings import com.pr0gramm.app.services.ThemeHelper import com.pr0gramm.app.ui.base.AsyncScope import com.pr0gramm.app.ui.base.launchIgnoreErrors import com.pr0gramm.app.util.AndroidUtility import com.pr0gramm.app.util.catchAll import com.pr0gramm.app.util.delay import com.pr0gramm.app.util.di.injector class VolumeController(val view: ImageView, private val exo: () -> SimpleExoPlayer?) { private val logger = Logger("VolumeController") private val preferences = view.context.injector.instance<SharedPreferences>() private val audioManager: AudioManager = view.context.getSystemService(Context.AUDIO_SERVICE) as AudioManager private val afChangeListener = object : AudioManager.OnAudioFocusChangeListener { override fun onAudioFocusChange(focusChange: Int) { if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT || focusChange == AudioManager.AUDIOFOCUS_LOSS) { audioManager.abandonAudioFocus(this) logger.info { "Lost audio focus, muting now." } setMuted(true) } } } init { view.setOnClickListener { toggle() } } fun abandonAudioFocusSoon() { AsyncScope.launchIgnoreErrors { delay(Duration.millis(500)) audioManager.abandonAudioFocus(afChangeListener) } } private fun toggle() { val exo = exo() ?: return val mutedCurrently = exo.volume < 0.1f setMuted(!mutedCurrently) } private fun setMuted(mute: Boolean): Unit = catchAll { val exo = exo() if (exo == null) { logger.debug { "No exo player found, abandon audio focus now." } audioManager.abandonAudioFocus(afChangeListener) return } val hasAudioFocus = if (mute) { logger.debug { "Mute requested, abandon audio focus" } audioManager.abandonAudioFocus(afChangeListener) false } else { logger.debug { "Request to get audio focus" } val result = audioManager.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC, audioFocusGain()) result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED } val icon: Drawable if (mute || !hasAudioFocus) { exo.volume = 0f storeUnmuteTime(0) icon = AppCompatResources.getDrawable(view.context, R.drawable.ic_video_mute_on)!! } else { exo.volume = 1f storeUnmuteTime(System.currentTimeMillis()) icon = AndroidUtility.getTintedDrawable(view.context, R.drawable.ic_video_mute_off, ThemeHelper.accentColor) } view.setImageDrawable(icon) } /** * Mute if not "unmuted" within the last 10 minutes. */ fun applyMuteState() { val now = System.currentTimeMillis() val lastUnmutedVideo = preferences.getLong(lastUnmutedTimeKey, 0L) val diffInSeconds = (now - lastUnmutedVideo) / 1000 setMuted(diffInSeconds > 10 * 60) } private fun storeUnmuteTime(time: Long) { preferences.edit { putLong(lastUnmutedTimeKey, time) } } private fun audioFocusGain(): Int { return if (Settings.audioFocusTransient) { AudioManager.AUDIOFOCUS_GAIN_TRANSIENT } else { AudioManager.AUDIOFOCUS_GAIN } } companion object { private const val lastUnmutedTimeKey = "VolumeController.lastUnmutedVideo" fun resetMuteTime(context: Context) { val prefs = context.injector.instance<SharedPreferences>() prefs.edit { putLong(lastUnmutedTimeKey, 0L) } } } }
mit
a0056fce831ed0b9c266c7b3c2e9190b
32.488189
119
0.654751
4.504237
false
false
false
false
android/animation-samples
MotionCompose/app/src/main/java/com/example/android/compose/motion/ui/Theme.kt
1
2709
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.compose.motion.ui import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260) private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 ) @Composable fun MotionComposeTheme( darkTheme: Boolean = isSystemInDarkTheme(), dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view)?.isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, content = content ) }
apache-2.0
e1448e3f348dfb727f3ca25c51b6dda6
32.036585
99
0.744555
4.383495
false
false
false
false
danrien/projectBlueWater
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/browsing/remote/GivenADifferentSearchQuery/WhenGettingItems.kt
1
3170
package com.lasthopesoftware.bluewater.client.browsing.remote.GivenADifferentSearchQuery import android.support.v4.media.MediaBrowserCompat import android.support.v4.media.MediaMetadataCompat import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.ProvideFiles import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.parameters.FileListParameters import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.parameters.SearchFileParameterProvider import com.lasthopesoftware.bluewater.client.browsing.library.access.session.ProvideSelectedLibraryId import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId import com.lasthopesoftware.bluewater.client.browsing.remote.GetMediaItemsFromServiceFiles import com.lasthopesoftware.bluewater.client.browsing.remote.MediaItemsBrowser import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture import com.namehillsoftware.handoff.promises.Promise import io.mockk.every import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class `When Getting Items` { companion object { private val serviceFileIds by lazy { listOf(702, 586, 516, 78) } private val expectedMediaItems by lazy { serviceFileIds.map { i -> MediaMetadataCompat.Builder() .apply { putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, "sf:$i") } .build() .let { metadata -> MediaBrowserCompat.MediaItem( metadata.description, MediaBrowserCompat.MediaItem.FLAG_PLAYABLE ) } } } private val mediaItems by lazy { val selectedLibraryId = mockk<ProvideSelectedLibraryId>() every { selectedLibraryId.selectedLibraryId } returns Promise(LibraryId(873)) val serviceFiles = mockk<GetMediaItemsFromServiceFiles>() for (id in serviceFileIds) { every { serviceFiles.promiseMediaItem(ServiceFile(id)) } returns Promise( MediaMetadataCompat.Builder() .apply { putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, "sf:$id") } .build() .let { metadata -> MediaBrowserCompat.MediaItem( metadata.description, MediaBrowserCompat.MediaItem.FLAG_PLAYABLE ) } ) } val provideFiles = mockk<ProvideFiles>() val parameters = SearchFileParameterProvider.getFileListParameters("king") every { provideFiles.promiseFiles(FileListParameters.Options.None, *parameters) } returns Promise( serviceFileIds.map(::ServiceFile) ) val mediaItemsBrowser = MediaItemsBrowser( selectedLibraryId, mockk(), provideFiles, mockk(), serviceFiles, ) mediaItemsBrowser .promiseItems("king") .toFuture() .get() } } @Test fun `then the media items are correct`() { assertThat(mediaItems?.map { i -> i.mediaId }).isEqualTo(expectedMediaItems.map { i -> i.mediaId }) } }
lgpl-3.0
275ed9eddee35ce93e68d56d2c153fbb
34.617978
117
0.74858
4.272237
false
false
false
false
Zephyrrus/ubb
YEAR 3/SEM 1/MOBILE/native/PhotoApp/app/src/main/java/com/example/zephy/photoapp/fragments/SubmissionsLessonFragment.kt
1
5005
package com.example.zephy.photoapp.fragments import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.zephy.photoapp.R import com.example.zephy.photoapp.activities.MainActivity import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Log import android.widget.ImageView import android.widget.TextView import android.widget.Toast import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.example.zephy.photoapp.activities.LessonActivity import com.example.zephy.photoapp.activities.LessonSubmission import com.example.zephy.photoapp.model.LessonSectionModel import com.example.zephy.photoapp.model.LessonSubmissionModel import com.example.zephy.photoapp.repository.MockLessonRepository import java.lang.Exception import java.util.ArrayList // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "lesson_id" /** * A simple [Fragment] subclass. * Use the [SubmissionsLessonFragment.newInstance] factory method to * create an instance of this fragment. * */ class SubmissionsLessonFragment : Fragment() { // TODO: Rename and change types of parameters private var lessonId: Int? = null internal var recyclerView: RecyclerView? = null internal var listitems = ArrayList<LessonSubmissionModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { lessonId = it.getInt(ARG_PARAM1) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_submissions_lesson, container, false) initializeList(lessonId) recyclerView = view.findViewById<View>(R.id.submission_recycle_view) as RecyclerView recyclerView!!.isNestedScrollingEnabled = false; recyclerView!!.setHasFixedSize(true) if ((listitems.size > 0) and (recyclerView != null)) { recyclerView!!.adapter = SubmissionRecycleAdapter(listitems) } val layoutManager = GridLayoutManager(activity, 2) recyclerView!!.layoutManager = layoutManager return view } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @return A new instance of fragment PageLessonFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: Int) = SubmissionsLessonFragment().apply { arguments = Bundle().apply { putInt(ARG_PARAM1, param1) } } } inner class SubmissionRecycleAdapter(private val list: ArrayList<LessonSubmissionModel>) : RecyclerView.Adapter<SubmissionRecycleHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SubmissionRecycleHolder { // create a new view val view = LayoutInflater.from(parent.context) .inflate(R.layout.fragment_submissions_lesson_recycle_item, parent, false) return SubmissionRecycleHolder(view) } override fun onBindViewHolder(holder: SubmissionRecycleHolder, position: Int) { Glide.with(context!!) .load(list[position].ImageURL) .apply(RequestOptions().fitCenter()) .into(holder.coverImageView) holder.coverImageView.setTag(R.id.image_tag, list[position].id) } override fun getItemCount(): Int { return list.size } } inner class SubmissionRecycleHolder(v: View) : RecyclerView.ViewHolder(v) { var coverImageView: ImageView = v.findViewById<View>(R.id.submission_image) as ImageView init { coverImageView.setOnClickListener() { val id = coverImageView.getTag(R.id.image_tag) val toast = Toast.makeText( activity, "You clicked on card " + id, Toast.LENGTH_SHORT ) toast.show() val intent = Intent(context, LessonSubmission::class.java) intent.putExtra("submissionId", id as Int) startActivity(intent) } } } fun initializeList(lessonid: Int?) { listitems.clear() MockLessonRepository().getSubmissionByLessonId(lessonId!!)!!.forEach{ listitems.add(it) } } }
mit
af4ac4f3182c16019efd5efeb9f763ad
34.75
144
0.671928
4.681946
false
false
false
false
m4gr3d/GAST
core/src/main/java/org/godotengine/plugin/gast/GastManager.kt
1
8489
@file:JvmName("GastManager") package org.godotengine.plugin.gast import android.app.Activity import android.os.Handler import android.os.Looper import android.util.Log import android.view.View import android.widget.FrameLayout import androidx.annotation.Keep import org.godotengine.godot.Godot import org.godotengine.godot.plugin.GodotPlugin import org.godotengine.plugin.gast.input.GastInputListener import org.godotengine.plugin.gast.input.HoverEventData import org.godotengine.plugin.gast.input.InputDispatcher import org.godotengine.plugin.gast.input.InputEventData import org.godotengine.plugin.gast.input.PressEventData import org.godotengine.plugin.gast.input.ReleaseEventData import org.godotengine.plugin.gast.input.ScrollEventData import org.godotengine.plugin.gast.input.action.GastActionListener import org.godotengine.plugin.gast.input.action.InputActionDispatcher import java.util.ArrayDeque import java.util.Queue import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.atomic.AtomicBoolean import javax.microedition.khronos.opengles.GL10 /** * GAST core plugin. * * Provides the functionality for rendering, interacting and manipulating content generated by the * Android system onto Godot textures. */ @Keep class GastManager(godot: Godot) : GodotPlugin(godot) { init { System.loadLibrary("gast") } private val gastRenderListeners = ConcurrentLinkedQueue<GastRenderListener>() private val gastInputListeners = ConcurrentLinkedQueue<GastInputListener>() private val gastActionListenersPerActions = ConcurrentHashMap<String, ArrayDeque<GastActionListener>>() private val mainThreadHandler = Handler(Looper.getMainLooper()) private val initialized = AtomicBoolean(false) /** * Root parent for all GAST views. */ var rootView : FrameLayout? = null companion object { private val TAG = GastManager::class.java.simpleName } override fun onGodotMainLoopStarted() { Log.d(TAG, "Initializing $pluginName manager") initialize() initialized.set(true) updateMonitoredInputActions() } override fun onMainCreate(activity: Activity): View? { rootView = FrameLayout(activity) return rootView } override fun onMainDestroy() { Log.d(TAG, "Shutting down $pluginName manager") // Ensure the 'rootView' is properly reset rootView = null runOnRenderThread { initialized.set(false) shutdown() } } public override fun runOnRenderThread(action: Runnable) { super.runOnRenderThread(action) } override fun onGLDrawFrame(gl: GL10) { for (listener in gastRenderListeners) { listener.onRenderDrawFrame() } } override fun getPluginName() = "gast-core" override fun getPluginGDNativeLibrariesPaths() = setOf("godot/plugin/v1/gast/gastlib.gdnlib") /** * Register a [GastRenderListener] instance to be notified of rendering related events. */ fun registerGastRenderListener(listener: GastRenderListener) { gastRenderListeners += listener } /** * Unregister a previously registered [GastRenderListener] instance. */ fun unregisterGastRenderListener(listener: GastRenderListener) { gastRenderListeners -= listener } /** * Register a [GastActionListener] instance to be notified of input action related events. */ fun registerGastActionListener(listener: GastActionListener) { val actionsToMonitor = listener.getInputActionsToMonitor() if (actionsToMonitor.isEmpty()) { return } for (action in actionsToMonitor) { val actionListeners = gastActionListenersPerActions.getOrPut(action) { ArrayDeque() } actionListeners.add(listener) } updateMonitoredInputActions() } /** * Unregister a previously registered [GastActionListener] instance. */ fun unregisterGastActionListener(listener: GastActionListener) { val monitoredActions = listener.getInputActionsToMonitor() if (monitoredActions.isEmpty()) { return } for (action in monitoredActions) { val actionListeners = gastActionListenersPerActions.get(action) ?: continue actionListeners.remove(listener) if (actionListeners.isEmpty()) { gastActionListenersPerActions.remove(action) } } updateMonitoredInputActions() } /** * Register a [GastInputListener] instance to be notified of input related events. */ fun registerGastInputListener(listener: GastInputListener) { gastInputListeners += listener } /** * Unregister a previously registered [GastInputListener] instance. */ fun unregisterGastInputListener(listener: GastInputListener) { gastInputListeners -= listener } /** * Update the visibility for the given node. */ fun updateVisibility(nodePath: String, visible: Boolean) { if (initialized.get()) { nativeUpdateNodeVisibility(nodePath, visible) } } private fun updateMonitoredInputActions() { if (initialized.get()) { // Update the list of input actions to monitor for the native code setInputActionsToMonitor(gastActionListenersPerActions.keys.toTypedArray()) } } private inline fun dispatchInputEvent( listeners: Queue<GastInputListener>?, eventDataProvider : () -> InputEventData ) { if (listeners.isNullOrEmpty()) { return } val dispatcher = InputDispatcher.acquireInputDispatcher( listeners, eventDataProvider() ) mainThreadHandler.post(dispatcher) } private fun dispatchInputActionEvent( listeners: Queue<GastActionListener>?, action: String, pressState: GastActionListener.InputPressState, strength: Float ) { if (listeners.isNullOrEmpty()) { return } val dispatcher = InputActionDispatcher.acquireInputActionDispatcher( listeners, action, pressState, strength ) mainThreadHandler.post(dispatcher) } private external fun initialize() private external fun nativeUpdateNodeVisibility(nodePath: String, visible: Boolean) private external fun shutdown() private external fun setInputActionsToMonitor(inputActions: Array<String>) private fun onRenderInputAction(action: String, pressStateIndex: Int, strength: Float) { val pressState = GastActionListener.InputPressState.fromIndex(pressStateIndex) if (pressState == GastActionListener.InputPressState.INVALID) { return } dispatchInputActionEvent( gastActionListenersPerActions[action], action, pressState, strength ) } private fun onRenderInputHover( nodePath: String, pointerId: String, xPercent: Float, yPercent: Float ) { dispatchInputEvent(gastInputListeners) { HoverEventData(nodePath, pointerId, xPercent, yPercent) } } private fun onRenderInputPress( nodePath: String, pointerId: String, xPercent: Float, yPercent: Float ) { dispatchInputEvent(gastInputListeners){ PressEventData(nodePath, pointerId, xPercent, yPercent) } } private fun onRenderInputRelease( nodePath: String, pointerId: String, xPercent: Float, yPercent: Float ) { dispatchInputEvent(gastInputListeners){ ReleaseEventData(nodePath, pointerId, xPercent, yPercent) } } private fun onRenderInputScroll( nodePath: String, pointerId: String, xPercent: Float, yPercent: Float, horizontalDelta: Float, verticalDelta: Float ) { dispatchInputEvent(gastInputListeners) { ScrollEventData( nodePath, pointerId, xPercent, yPercent, horizontalDelta, verticalDelta ) } } }
mit
54980c7db6972816cd79b1dfd3ad62be
28.272414
107
0.66168
4.839795
false
false
false
false
AoEiuV020/PaNovel
api/src/main/java/cc/aoeiuv020/panovel/api/site/ttkan.kt
1
3020
package cc.aoeiuv020.panovel.api.site import cc.aoeiuv020.base.jar.ownLinesString import cc.aoeiuv020.gson.GsonUtils import cc.aoeiuv020.panovel.api.NovelChapter import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext import cc.aoeiuv020.panovel.api.firstThreeIntPattern import com.google.gson.Gson import com.google.gson.JsonObject /** * Created by AoEiuV020 on 2018.06.08-19:09:23. */ class Ttkan : DslJsoupNovelContext() {init { site { name = "天天看小说" baseUrl = "https://cn.ttkan.co" logo = "text://天天看小说/?fc=ffffff&bc=1b2631" } search { get { url = "/novel/search" data { "q" to it } } document { items("div.frame_body > div.pure-g > div > ul") { name("> li:nth-child(1) > a") // 有作者名字空白,https://hk.ttkan.co/novel/chapters/yuanworuxingjunruyue author("> li:nth-child(2)", block = pickString("作者:(\\S*)")) } } } // https://www.ttkan.co/novel/chapters/shisiruguiweijunzi-pingceng bookIdRegex = "/novel/chapters/(.*)" detailPageTemplate = "/novel/chapters/%s" detail { _ -> document { novel { name("div.pure-g.novel_info > div:nth-child(2) > ul > li:nth-child(1) > h1") author("div.pure-g.novel_info > div:nth-child(2) > ul > li:nth-child(2) > a") } image("div.pure-g.novel_info > div:nth-child(1) > a > amp-img") introduction("div.description > div") } } chapters { val bookId = findBookId(it) get { url = "https://www.ttkan.co/api/nq/amp_novel_chapters?language=cn&novel_id=$bookId&__amp_source_origin=https%3A%2F%2Fwww.ttkan.co" } response { gson.fromJson(it, JsonObject::class.java) .getAsJsonArray("items").map { it.asJsonObject.let { val chapterName = it.getAsJsonPrimitive("chapter_name").asString val chapterId = it.getAsJsonPrimitive("chapter_id").asInt.toString() NovelChapter(chapterName, "${bookId}_$chapterId", null) } } } } // https://www.ttkan.co/novel/user/page_direct?novel_id=shisiruguiweijunzi-pingceng&page=2 // https://www.bg3.co/novel/pagea/shisiruguiweijunzi-pingceng_2.html contentPageTemplate = "//www.bg3.co/novel/pagea/%s.html" content { val bookIdAndChapterId = findBookIdWithChapterId(it) val (bookId, chapterId) = bookIdAndChapterId.split('_') get { url = "/novel/user/page_direct" data { "novel_id" to bookId "page" to chapterId } } document { items("div.content") } } } // 用来解析章节api, private val gson: Gson = GsonUtils.gson }
gpl-3.0
c67a89d25d4e4d5934b85d341aaf2177
33.091954
140
0.55091
3.586457
false
false
false
false
LachlanMcKee/gsonpath
compiler/standard/src/main/java/gsonpath/adapter/standard/factory/TypeAdapterFactoryGenerator.kt
1
5824
package gsonpath.adapter.standard.factory import com.google.gson.Gson import com.google.gson.TypeAdapter import com.google.gson.TypeAdapterFactory import com.google.gson.reflect.TypeToken import com.squareup.javapoet.ArrayTypeName import com.squareup.javapoet.ClassName import com.squareup.javapoet.TypeSpec import gsonpath.adapter.AdapterGenerationResult import gsonpath.adapter.Constants.GSON import gsonpath.adapter.Constants.NULL import gsonpath.adapter.util.writeFile import gsonpath.util.* import javax.lang.model.element.Modifier import javax.lang.model.element.TypeElement class TypeAdapterFactoryGenerator(private val fileWriter: FileWriter) { fun generate(factoryElement: TypeElement, generatedGsonAdapters: List<AdapterGenerationResult>) { val packageLocalHandleResults = TypeAdapterFactoryHandlersFactory .createResults(factoryElement, generatedGsonAdapters) for ((packageName, list) in packageLocalHandleResults) { createPackageLocalTypeAdapterLoaders(packageName, list) } createGsonTypeFactoryImpl(factoryElement, packageLocalHandleResults) } /** * Create the GsonPathLoader which is used by the GsonPathTypeAdapterFactory class. */ private fun createGsonTypeFactoryImpl( factoryElement: TypeElement, packageLocalAdapterGenerationResults: Map<String, List<AdapterGenerationResult>>) { val factoryClassName = ClassName.get(factoryElement) TypeSpecExt.finalClassBuilder(factoryClassName.simpleName() + "Impl") .addSuperinterface(factoryClassName) .gsonTypeFactoryImplContent(packageLocalAdapterGenerationResults) .writeFile(fileWriter, factoryClassName.packageName()) } private fun TypeSpec.Builder.gsonTypeFactoryImplContent( packageLocalAdapterGenerationResults: Map<String, List<AdapterGenerationResult>>): TypeSpec.Builder { field(PACKAGE_PRIVATE_LOADERS, ArrayTypeName.of(TypeAdapterFactory::class.java)) { addModifiers(Modifier.PRIVATE, Modifier.FINAL) } constructor { addModifiers(Modifier.PUBLIC) code { assignNew(PACKAGE_PRIVATE_LOADERS, "\$T[${packageLocalAdapterGenerationResults.size}]", TypeAdapterFactory::class.java) // Add the package local type adapter loaders to the hash map. for ((index, packageName) in packageLocalAdapterGenerationResults.keys.withIndex()) { assignNew("$PACKAGE_PRIVATE_LOADERS[$index]", "$packageName.$PACKAGE_PRIVATE_TYPE_ADAPTER_LOADER_CLASS_NAME()") } } } // // <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type); // overrideMethod("create") { returns(TypeAdapter::class.java) addParameter(Gson::class.java, GSON) addParameter(TypeToken::class.java, "type") code { `for`("int i = 0; i < $PACKAGE_PRIVATE_LOADERS.length; i++") { createVariable(TypeAdapter::class.java, TYPE_ADAPTER, "$PACKAGE_PRIVATE_LOADERS[i].create($GSON, type)") newLine() `if`("$TYPE_ADAPTER != $NULL") { `return`(TYPE_ADAPTER) } } `return`(NULL) } } return this } private fun createPackageLocalTypeAdapterLoaders( packageName: String, packageLocalGsonAdapters: List<AdapterGenerationResult>) { TypeSpecExt.finalClassBuilder(ClassName.get(packageName, PACKAGE_PRIVATE_TYPE_ADAPTER_LOADER_CLASS_NAME)) .addSuperinterface(TypeAdapterFactory::class.java) .packagePrivateTypeAdapterLoaderContent(packageLocalGsonAdapters) .writeFile(fileWriter, packageName) } // // <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type); // private fun TypeSpec.Builder.packagePrivateTypeAdapterLoaderContent( packageLocalGsonAdapters: List<AdapterGenerationResult>): TypeSpec.Builder { overrideMethod("create") { returns(TypeAdapter::class.java) addParameter(Gson::class.java, GSON) addParameter(TypeToken::class.java, "type") code { createVariable(Class::class.java, RAW_TYPE, "type.getRawType()") for ((currentAdapterIndex, result) in packageLocalGsonAdapters.withIndex()) { val condition = result.adapterGenericTypeClassNames .joinToString(separator = " || ") { "rawType.equals(\$T.class)" } if (currentAdapterIndex == 0) { ifWithoutClose(condition, *result.adapterGenericTypeClassNames) { `return`("new \$T($GSON)", result.adapterClassName) } } else { newLine() // New line for easier readability. elseIf(condition, *result.adapterGenericTypeClassNames) { `return`("new \$T($GSON)", result.adapterClassName) } } } endControlFlow() newLine() `return`(NULL) } } return this } private companion object { private const val PACKAGE_PRIVATE_TYPE_ADAPTER_LOADER_CLASS_NAME = "PackagePrivateTypeAdapterLoader" private const val PACKAGE_PRIVATE_LOADERS = "mPackagePrivateLoaders" private const val TYPE_ADAPTER = "typeAdapter" private const val RAW_TYPE = "rawType" } }
mit
e883cc7bc80a680a4c4e7668827b5e56
39.165517
124
0.621909
5.158547
false
false
false
false
ccampo133/NBodyJS
src/main/kotlin/me/ccampo/nbody/model/Vector.kt
1
804
package me.ccampo.nbody.model import kotlin.js.Math /** * A two dimensional Euclidean vector. Contains various methods for performing vector arithmetic. * * See [Wikipedia](https://en.wikipedia.org/wiki/Euclidean_vector) * * @param x The x coordinate in 2D space * @param y The y coordinate in 2D space */ data class Vector(val x: Double, val y: Double) { val len = Math.sqrt(this dot this) operator fun plus(other: Vector) = Vector(x + other.x, y + other.y) operator fun minus(other: Vector) = Vector(x - other.x, y - other.y) operator fun times(scalar: Double) = Vector(scalar * x, scalar * y) operator fun div(scalar: Double) = Vector(x / scalar, y / scalar) infix fun dot(other: Vector) = (x * other.x) + (y * other.y) companion object { val zero = Vector(0.0, 0.0) } }
mit
9e416420599359f18f6284d843a4a43a
32.5
97
0.680348
3.152941
false
false
false
false
equeim/tremotesf-android
app/src/main/kotlin/org/equeim/tremotesf/ui/utils/Keyboard.kt
1
1649
package org.equeim.tremotesf.ui.utils import android.app.Activity import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.EditText import androidx.core.content.getSystemService import androidx.fragment.app.Fragment import androidx.lifecycle.findViewTreeLifecycleOwner import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.delay import timber.log.Timber fun Activity.hideKeyboard() { currentFocus?.let { focus -> getSystemService<InputMethodManager>()?.hideSoftInputFromWindow(focus.windowToken, 0) } } fun Fragment.hideKeyboard() { activity?.hideKeyboard() } private const val IMM_IS_ACTIVE_CHECK_INTERVAL_MS = 50L fun EditText.showKeyboard() { val imm = context.getSystemService<InputMethodManager>() ?: return val lifecycleOwner = findViewTreeLifecycleOwner() ?: return val job = lifecycleOwner.lifecycleScope.launchWhenStarted { if (requestFocus()) { while (isFocused && !imm.isActive(this@showKeyboard)) { delay(IMM_IS_ACTIVE_CHECK_INTERVAL_MS) } if (isFocused) { imm.showSoftInput(this@showKeyboard, InputMethodManager.SHOW_IMPLICIT) } } else { Timber.w("showKeyboard: failed to request focus") } } val listener = object : View.OnAttachStateChangeListener { override fun onViewAttachedToWindow(v: View) = Unit override fun onViewDetachedFromWindow(v: View) = job.cancel() } job.invokeOnCompletion { removeOnAttachStateChangeListener(listener) } addOnAttachStateChangeListener(listener) }
gpl-3.0
40f6f97fa305420828be8976e870b741
32.653061
93
0.715585
4.922388
false
false
false
false
equeim/tremotesf-android
app/src/main/kotlin/org/equeim/tremotesf/ui/addtorrent/AddTorrentFileModel.kt
1
7701
/* * Copyright (C) 2017-2022 Alexey Rochev <[email protected]> * * This file is part of Tremotesf. * * Tremotesf 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. * * Tremotesf 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 org.equeim.tremotesf.ui.addtorrent import android.Manifest import android.app.Application import android.content.ContentResolver import android.content.Context import android.content.res.AssetFileDescriptor import android.net.Uri import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.equeim.tremotesf.R import org.equeim.tremotesf.rpc.GlobalRpc import org.equeim.tremotesf.torrentfile.* import org.equeim.tremotesf.torrentfile.rpc.Rpc import org.equeim.tremotesf.ui.utils.RuntimePermissionHelper import org.equeim.tremotesf.ui.utils.savedState import timber.log.Timber import java.io.FileNotFoundException import java.util.concurrent.atomic.AtomicReference interface AddTorrentFileModel { enum class ParserStatus { None, Loading, FileIsTooLarge, ReadingError, ParsingError, Loaded } data class FilePriorities( val unwantedFiles: List<Int>, val lowPriorityFiles: List<Int>, val highPriorityFiles: List<Int> ) data class ViewUpdateData( val parserStatus: ParserStatus, val rpcStatus: Rpc.Status, val hasStoragePermission: Boolean ) var rememberedPagerItem: Int val needStoragePermission: Boolean val storagePermissionHelper: RuntimePermissionHelper val parserStatus: StateFlow<ParserStatus> val viewUpdateData: Flow<ViewUpdateData> val filesTree: TorrentFilesTree val torrentName: String val renamedFiles: MutableMap<String, String> fun detachFd(): Int? fun getFilePriorities(): FilePriorities } class AddTorrentFileModelImpl( private val args: AddTorrentFileFragmentArgs, application: Application, private val savedStateHandle: SavedStateHandle ) : AndroidViewModel(application), AddTorrentFileModel { override var rememberedPagerItem: Int by savedState(savedStateHandle, -1) override val needStoragePermission = args.uri.scheme == ContentResolver.SCHEME_FILE override val storagePermissionHelper = RuntimePermissionHelper( Manifest.permission.READ_EXTERNAL_STORAGE, R.string.storage_permission_rationale_torrent ) override val parserStatus = MutableStateFlow(AddTorrentFileModel.ParserStatus.None) override val viewUpdateData = combine( parserStatus, GlobalRpc.status, storagePermissionHelper.permissionGranted ) { parserStatus, rpcStatus, hasPermission -> AddTorrentFileModel.ViewUpdateData( parserStatus, rpcStatus, hasPermission ) } private var fd: AssetFileDescriptor? = null override val filesTree = TorrentFilesTree(viewModelScope) override val torrentName: String get() = filesTree.rootNode.children.first().item.name override val renamedFiles = mutableMapOf<String, String>() private lateinit var files: List<TorrentFilesTree.FileNode> init { if (needStoragePermission) { viewModelScope.launch { storagePermissionHelper.permissionGranted.first { it } load() } } else { load() } } override fun onCleared() { fd?.closeQuietly() } private fun AssetFileDescriptor.closeQuietly() { try { Timber.i("closeQuietly: closing file descriptor") close() } catch (e: Exception) { Timber.e(e, "closeQuietly: failed to close file descriptor") } } private fun load() { Timber.i("load: loading ${args.uri}") if (parserStatus.value == AddTorrentFileModel.ParserStatus.None) { parserStatus.value = AddTorrentFileModel.ParserStatus.Loading viewModelScope.launch { doLoad(args.uri, getApplication()) } } } override fun detachFd(): Int? { Timber.i("detachFd() called") val fd = this.fd return if (fd != null) { Timber.i("detachFd: detaching file descriptor") this.fd = null fd.parcelFileDescriptor.detachFd() } else { Timber.e("detachFd: file descriptor is already detached") null } } override fun getFilePriorities(): AddTorrentFileModel.FilePriorities { val unwantedFiles = mutableListOf<Int>() val lowPriorityFiles = mutableListOf<Int>() val highPriorityFiles = mutableListOf<Int>() for (file in files) { val item = file.item val id = item.fileId if (item.wantedState == TorrentFilesTree.Item.WantedState.Unwanted) { unwantedFiles.add(id) } when (item.priority) { TorrentFilesTree.Item.Priority.Low -> lowPriorityFiles.add(id) TorrentFilesTree.Item.Priority.High -> highPriorityFiles.add(id) else -> { } } } return AddTorrentFileModel.FilePriorities( unwantedFiles, lowPriorityFiles, highPriorityFiles ) } private suspend fun doLoad(uri: Uri, context: Context) = withContext(Dispatchers.IO) { val fd = try { context.contentResolver.openAssetFileDescriptor(uri, "r") } catch (e: FileNotFoundException) { Timber.e(e, "Failed to open file descriptor") parserStatus.value = AddTorrentFileModel.ParserStatus.ReadingError return@withContext } if (fd == null) { Timber.e("File descriptor is null") parserStatus.value = AddTorrentFileModel.ParserStatus.ReadingError return@withContext } val fdAtomic = AtomicReference(fd) try { val (rootNode, files) = TorrentFileParser.createFilesTree(fd.fileDescriptor) withContext(Dispatchers.Main) { [email protected] = fd fdAtomic.set(null) [email protected] = files filesTree.init(rootNode, savedStateHandle) parserStatus.value = AddTorrentFileModel.ParserStatus.Loaded } } catch (error: FileReadException) { parserStatus.value = AddTorrentFileModel.ParserStatus.ReadingError return@withContext } catch (error: FileIsTooLargeException) { parserStatus.value = AddTorrentFileModel.ParserStatus.FileIsTooLarge return@withContext } catch (error: FileParseException) { parserStatus.value = AddTorrentFileModel.ParserStatus.ParsingError return@withContext } finally { fdAtomic.get()?.closeQuietly() } } }
gpl-3.0
1f3093949af655b8ac8fc9c83bafa814
32.193966
90
0.66368
4.908222
false
false
false
false
cashapp/sqldelight
dialects/postgresql/src/main/kotlin/app/cash/sqldelight/dialects/postgresql/grammar/mixins/AlterTableDropColumnMixin.kt
1
955
package app.cash.sqldelight.dialects.postgresql.grammar.mixins import app.cash.sqldelight.dialects.postgresql.grammar.psi.PostgreSqlAlterTableDropColumn import com.alecstrong.sql.psi.core.psi.AlterTableApplier import com.alecstrong.sql.psi.core.psi.LazyQuery import com.alecstrong.sql.psi.core.psi.SqlColumnName import com.alecstrong.sql.psi.core.psi.SqlCompositeElementImpl import com.intellij.lang.ASTNode internal abstract class AlterTableDropColumnMixin( node: ASTNode, ) : SqlCompositeElementImpl(node), PostgreSqlAlterTableDropColumn, AlterTableApplier { private val columnName get() = children.filterIsInstance<SqlColumnName>().single() override fun applyTo(lazyQuery: LazyQuery): LazyQuery { return LazyQuery( tableName = lazyQuery.tableName, query = { val columns = lazyQuery.query.columns.filter { it.element.text != columnName.name } lazyQuery.query.copy(columns = columns) }, ) } }
apache-2.0
1556b856c5d07b21a89b327d0f807e9e
34.37037
91
0.773822
3.979167
false
false
false
false
sksamuel/akka-patterns
rxhive-core/src/main/kotlin/com/sksamuel/rxhive/evolution/AdditiveSchemaEvolver.kt
1
1821
package com.sksamuel.rxhive.evolution import com.sksamuel.rxhive.DatabaseName import com.sksamuel.rxhive.Struct import com.sksamuel.rxhive.StructType import com.sksamuel.rxhive.TableName import com.sksamuel.rxhive.schemas.FromHiveSchema import com.sksamuel.rxhive.schemas.ToHiveSchema import org.apache.hadoop.hive.metastore.IMetaStoreClient /** * An implementation of [SchemaEvolver] that will update the metastore by * attempting to add new fields in a backwards compatible way. * * This can be accomplished if the new field is nullable (so that existing data * can return null for this field when queried). * * If any fields are missing from the metastore schema, but are not nullable, * then an exception will be thrown. */ object AdditiveSchemaEvolver : SchemaEvolver { override fun evolve(dbName: DatabaseName, tableName: TableName, metastoreSchema: StructType, struct: Struct, client: IMetaStoreClient): StructType { // find any fields that are not present in the metastore and attempt to // evolve the metastore to include them val toBeAdded = struct.schema.fields.filterNot { metastoreSchema.hasField(it.name) } val nonnull = toBeAdded.filter { !it.nullable } if (nonnull.isNotEmpty()) throw IllegalArgumentException("Cannot evolve schema when new field(s) $nonnull are not nullable") if (toBeAdded.isNotEmpty()) { val table = client.getTable(dbName.value, tableName.value) toBeAdded.forEach { val col = ToHiveSchema.toHiveSchema(it) table.sd.cols.add(col) } client.alter_table(dbName.value, tableName.value, table) } val table = client.getTable(dbName.value, tableName.value) return FromHiveSchema.fromHiveTable(table) } }
apache-2.0
42d7d68e6f7914b693e446469e6aea59
36.958333
104
0.717738
4.176606
false
false
false
false
BlurEngine/Blur
src/main/java/com/blurengine/blur/modules/stages/StageChangeData.kt
1
1685
/* * Copyright 2017 Ali Moghnieh * * 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.blurengine.blur.modules.stages import java.util.Collections import javax.annotation.Nonnull class StageChangeData(val reason: StageChangeReason) { private val _customData = HashMap<Class<*>, Any>() /** * Unmodifiable collection */ val customData: Collection<Any> = Collections.unmodifiableCollection(_customData.values) operator fun <T> get(dataClass: Class<T>) = _customData[dataClass] as? T @Nonnull fun <T> getOrCreate(dataClass: Class<T>): T { var data = get(dataClass) if (data == null) { data = dataClass.newInstance()!! put(data) } return data } inline fun <reified T : Any> get() = get(T::class.java) @Nonnull inline fun <reified T : Any> getOrCreate() = getOrCreate(T::class.java) fun put(data: Any) { require(data.javaClass !in _customData) { "${data.javaClass} is already registered." } _customData[data.javaClass] = data } fun remove(data: Any): Boolean { return _customData.remove(data.javaClass) == data } }
apache-2.0
f7134d97a805e8a3b93cd138d994acb7
30.203704
94
0.67003
4.099757
false
false
false
false
Yopu/OpenGrave
src/main/kotlin/opengrave/BlockGrave.kt
1
3520
package opengrave import net.minecraft.block.BlockContainer import net.minecraft.block.material.Material import net.minecraft.block.state.IBlockState import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.tileentity.TileEntity import net.minecraft.util.EnumBlockRenderType import net.minecraft.util.EnumFacing import net.minecraft.util.EnumHand import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.util.math.RayTraceResult import net.minecraft.world.Explosion import net.minecraft.world.IBlockAccess import net.minecraft.world.World import java.util.* object BlockGrave : BlockContainer(Material.ROCK) { init { setRegistryName("blockgrave") setHardness(5.0F) setResistance(6000000.0F) } override fun removedByPlayer(state: IBlockState?, worldIn: World?, pos: BlockPos?, player: EntityPlayer?, willHarvest: Boolean): Boolean { if (worldIn == null || pos == null || player == null || worldIn.isRemote) return super.removedByPlayer(state, worldIn, pos, player, willHarvest) val tileEntityGrave = worldIn.getTileEntity(pos) as? TileEntityGrave? tileEntityGrave?.returnPlayerItems(player) return super.removedByPlayer(state, worldIn, pos, player, willHarvest) } override fun breakBlock(worldIn: World?, pos: BlockPos?, state: IBlockState?) { val tileEntityGrave = worldIn?.getTileEntity(pos) as? TileEntityGrave? tileEntityGrave?.dropItems() super.breakBlock(worldIn, pos, state) } override fun onBlockActivated(worldIn: World?, pos: BlockPos?, state: IBlockState?, playerIn: EntityPlayer?, hand: EnumHand?, side: EnumFacing?, hitX: Float, hitY: Float, hitZ: Float): Boolean { if (worldIn == null || pos == null || hand == null || worldIn.isRemote || hand != EnumHand.MAIN_HAND) { return false } val tileEntityGrave = worldIn.getTileEntity(pos) as? TileEntityGrave? if (tileEntityGrave != null) { Debug.log.finest("${tileEntityGrave.entityPlayerID}\tInventory:\t${tileEntityGrave.inventory.joinToString()}") Debug.log.finest("${tileEntityGrave.entityPlayerID}\tBaubles:\t${tileEntityGrave.baubles.joinToString()}") tileEntityGrave.deathMessage?.let { playerIn?.sendStatusMessage(it, false) } } return false } override fun getPickBlock(p_getPickBlock_1_: IBlockState?, p_getPickBlock_2_: RayTraceResult?, p_getPickBlock_3_: World?, p_getPickBlock_4_: BlockPos?, p_getPickBlock_5_: EntityPlayer?): ItemStack { return ItemStack.EMPTY } override fun getItemDropped(state: IBlockState?, rand: Random?, fortune: Int) = null override fun canDropFromExplosion(explosionIn: Explosion?) = false override fun onBlockExploded(world: World?, pos: BlockPos?, explosion: Explosion?) { } override fun getRenderType(p_getRenderType_1_: IBlockState?): EnumBlockRenderType = EnumBlockRenderType.MODEL override fun isOpaqueCube(p_isOpaqueCube_1_: IBlockState?): Boolean = false override fun isFullCube(p_isFullCube_1_: IBlockState?): Boolean = false override fun getBoundingBox(state: IBlockState?, source: IBlockAccess?, pos: BlockPos?): AxisAlignedBB { return AxisAlignedBB(0.0625, 0.0, 0.375, 0.9375, 0.875, 0.625) } override fun createNewTileEntity(worldIn: World?, meta: Int): TileEntity = TileEntityGrave() }
mit
87c7d22063ae85c78d1e3883042bf707
43.56962
202
0.717614
4.141176
false
false
false
false
Ztiany/Repository
Kotlin/Kotlin-github/retroapollo-android/src/main/java/com/bennyhuo/retroapollo/rxjava/CallArbiter.kt
2
5304
/* * Copyright 2017 Bennyhuo * * 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.bennyhuo.retroapollo.rxjava import com.apollographql.apollo.ApolloCall import com.apollographql.apollo.api.Response import com.apollographql.apollo.exception.ApolloException import rx.Producer import rx.Subscriber import rx.Subscription import rx.exceptions.* import rx.plugins.RxJavaPlugins import java.util.concurrent.atomic.AtomicInteger /** * Created by benny on 8/6/17. */ class CallArbiter<T>(val apolloCall: ApolloCall<T>, val subscriber: Subscriber<in Response<T>>) : Subscription, Producer { companion object { private const val STATE_WAITING = 0 private const val STATE_REQUESTED = 1 private const val STATE_TERMINATED = 3 } val atomicState = AtomicInteger(STATE_WAITING) override fun isUnsubscribed() = apolloCall.isCanceled override fun unsubscribe() { apolloCall.cancel() } override fun request(n: Long) { if (n == 0L) return while (true) { val state = atomicState.get() when (state) { STATE_WAITING -> if (atomicState.compareAndSet(STATE_WAITING, STATE_REQUESTED)) { apolloCall.enqueue(object : ApolloCall.Callback<T>() { override fun onFailure(e: ApolloException) { Exceptions.throwIfFatal(e) emitError(e) } override fun onResponse(response: Response<T>) { if (atomicState.compareAndSet(STATE_REQUESTED, STATE_TERMINATED)) { deliverResponse(response) } } }) return } STATE_REQUESTED, STATE_TERMINATED -> return // Nothing to do. else -> throw IllegalStateException("Unknown state: " + atomicState.get()) } } } private fun deliverResponse(response: Response<T>) { try { if (!isUnsubscribed) { subscriber.onNext(response) } } catch (e: OnCompletedFailedException) { RxJavaPlugins.getInstance().errorHandler.handleError(e) return } catch (e: OnErrorFailedException) { RxJavaPlugins.getInstance().errorHandler.handleError(e) return } catch (e: OnErrorNotImplementedException) { RxJavaPlugins.getInstance().errorHandler.handleError(e) return } catch (t: Throwable) { Exceptions.throwIfFatal(t) try { subscriber.onError(t) } catch (e: OnCompletedFailedException) { RxJavaPlugins.getInstance().errorHandler.handleError(e) } catch (e: OnErrorFailedException) { RxJavaPlugins.getInstance().errorHandler.handleError(e) } catch (e: OnErrorNotImplementedException) { RxJavaPlugins.getInstance().errorHandler.handleError(e) } catch (inner: Throwable) { Exceptions.throwIfFatal(inner) val composite = CompositeException(t, inner) RxJavaPlugins.getInstance().errorHandler.handleError(composite) } return } try { if (!isUnsubscribed) { subscriber.onCompleted() } } catch (e: OnCompletedFailedException) { RxJavaPlugins.getInstance().errorHandler.handleError(e) } catch (e: OnErrorFailedException) { RxJavaPlugins.getInstance().errorHandler.handleError(e) } catch (e: OnErrorNotImplementedException) { RxJavaPlugins.getInstance().errorHandler.handleError(e) } catch (t: Throwable) { Exceptions.throwIfFatal(t) RxJavaPlugins.getInstance().errorHandler.handleError(t) } } fun emitError(t: Throwable) { atomicState.set(STATE_TERMINATED) if (!isUnsubscribed) { try { subscriber.onError(t) } catch (e: OnCompletedFailedException) { RxJavaPlugins.getInstance().errorHandler.handleError(e) } catch (e: OnErrorFailedException) { RxJavaPlugins.getInstance().errorHandler.handleError(e) } catch (e: OnErrorNotImplementedException) { RxJavaPlugins.getInstance().errorHandler.handleError(e) } catch (inner: Throwable) { Exceptions.throwIfFatal(inner) val composite = CompositeException(t, inner) RxJavaPlugins.getInstance().errorHandler.handleError(composite) } } } }
apache-2.0
800b33de7b2965949e5cbf84860a4d45
35.840278
122
0.598793
5.184751
false
false
false
false
sauloaguiar/githubcorecommitter
app/src/main/kotlin/com/sauloaguiar/githubcorecommitter/network/RestAPI.kt
1
1225
package com.sauloaguiar.githubcorecommitter.network import com.sauloaguiar.githubcorecommitter.model.GithubRepoWrapper import com.sauloaguiar.githubcorecommitter.model.GithubUser import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory /** * Created by sauloaguiar on 12/16/16. */ class RestAPI() { private val githubApi: GithubApi init { val interceptor = HttpLoggingInterceptor() interceptor.level = HttpLoggingInterceptor.Level.BODY val client = OkHttpClient.Builder().addInterceptor(interceptor).build() val retrofit = Retrofit.Builder() .baseUrl("https://api.github.com") .addConverterFactory(GsonConverterFactory.create()) .client(client) .build() githubApi = retrofit.create(GithubApi::class.java) } fun getTopRepos(criteria: String = "stars:>1"): Call<GithubRepoWrapper> { return githubApi.fetchRepos(criteria) } fun getContributors(repo: String): Call<List<GithubUser>> { return githubApi.fetchContributors("/repos/$repo/contributors") } }
gpl-3.0
cd320d9977d64a40b3aae73217151834
29.65
79
0.711837
4.422383
false
false
false
false
niranjan94/show-java
app/src/main/kotlin/com/njlabs/showjava/utils/UserPreferences.kt
1
3190
/* * Show Java - A java/apk decompiler for android * Copyright (c) 2018 Niranjan Rajendran * * 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 <https://www.gnu.org/licenses/>. */ package com.njlabs.showjava.utils import android.content.SharedPreferences import com.google.ads.consent.ConsentStatus /** * A thin-wrapper around [SharedPreferences] to expose preferences as getters. */ class UserPreferences(private val prefs: SharedPreferences) { companion object { const val NAME = "user_preferences" } interface DEFAULTS { companion object { const val CUSTOM_FONT = true const val DARK_MODE = false const val SHOW_MEMORY_USAGE = true const val SHOW_SYSTEM_APPS = false const val MEMORY_THRESHOLD = 80 const val IGNORE_LIBRARIES = true const val KEEP_INTERMEDIATE_FILES = false const val CHUNK_SIZE = 500 const val MAX_ATTEMPTS = 2 } } val ignoreLibraries: Boolean get() = prefs.getBoolean("ignoreLibraries", DEFAULTS.IGNORE_LIBRARIES) val keepIntermediateFiles: Boolean get() = prefs.getBoolean("keepIntermediateFiles", DEFAULTS.KEEP_INTERMEDIATE_FILES) val customFont: Boolean get() = prefs.getBoolean("customFont", DEFAULTS.CUSTOM_FONT) val darkMode: Boolean get() = prefs.getBoolean("darkMode", DEFAULTS.DARK_MODE) val showMemoryUsage: Boolean get() = prefs.getBoolean("showMemoryUsage", DEFAULTS.SHOW_MEMORY_USAGE) val showSystemApps: Boolean get() = prefs.getBoolean("showSystemApps", DEFAULTS.SHOW_SYSTEM_APPS) val chunkSize: Int get() = try { prefs.getString("chunkSize", DEFAULTS.CHUNK_SIZE.toString())?.trim()?.toInt() ?: DEFAULTS.CHUNK_SIZE } catch (ignored: Exception) { DEFAULTS.CHUNK_SIZE } val maxAttempts: Int get() = try { prefs.getString("maxAttempts", DEFAULTS.MAX_ATTEMPTS.toString())?.trim()?.toInt() ?: DEFAULTS.MAX_ATTEMPTS } catch (ignored: Exception) { DEFAULTS.MAX_ATTEMPTS } val memoryThreshold: Int get() = try { prefs.getString( "memoryThreshold", DEFAULTS.MEMORY_THRESHOLD.toString() )?.trim()?.toInt() ?: DEFAULTS.MEMORY_THRESHOLD } catch (ignored: Exception) { DEFAULTS.MEMORY_THRESHOLD } val consentStatus: Int get() = prefs.getInt("consentStatus", ConsentStatus.UNKNOWN.ordinal) }
gpl-3.0
63a8d85ce826eabe9191d876ab14299c
32.946809
93
0.641693
4.643377
false
false
false
false
shlusiak/Freebloks-Android
game/src/test/java/de/saschahlusiak/freebloks/model/BoardTest.kt
1
14521
package de.saschahlusiak.freebloks.model import de.saschahlusiak.freebloks.model.Board.Companion.FIELD_ALLOWED import de.saschahlusiak.freebloks.model.Board.Companion.FIELD_DENIED import de.saschahlusiak.freebloks.model.Board.Companion.FIELD_FREE import de.saschahlusiak.freebloks.model.GameMode.* import de.saschahlusiak.freebloks.utils.Point import org.junit.Assert.* import org.junit.Test class BoardTest { private fun Player.getAllTurns(board: Board) = sequence { for (x in 0 until board.width) for (y in 0 until board.height) { if (board.getFieldStatus(number, y, x) == FIELD_ALLOWED) { stones.forEach { if (it.isAvailable()) { for (turn in board.getTurnsInPosition(number, it.shape, y, x)) yield(turn) } } } } } private fun Board.playGame(picker: (List<Turn>) -> Turn): Turnpool { val turnPool = Turnpool() do { var moved = false for (number in 0..3) { val p = getPlayer(number) val turns = p.getAllTurns(this).toList() assertEquals(p.numberOfPossibleTurns, turns.size) if (turns.isNotEmpty()) { val turn = picker.invoke(turns) moved = true turnPool.add(turn) setStone(turn) } } } while (moved) return turnPool } /** * Sets the stone no 2 into the bottom left corner of a new game: * * X * XX */ @Test fun test_basic_stone() { val s = Board(20) s.startNewGame(GAMEMODE_4_COLORS_4_PLAYERS, GameConfig.DEFAULT_STONE_SET, 20, 20) assertEquals(20, s.width) assertEquals(20, s.height) val p = s.getPlayer(0) assertNotNull(p) assertEquals(58, p.numberOfPossibleTurns) val stone = p.getStone(2) assertEquals(1, stone.available) // start for blue is bottom left assertEquals(Point(0, 19), s.getPlayerSeed(0, GAMEMODE_4_COLORS_4_PLAYERS)) // that field is allowed (green) assertEquals(FIELD_ALLOWED, s.getFieldStatus(0, 19, 0)) // the field next to it is only free (blank) assertEquals(FIELD_FREE, s.getFieldStatus(0, 18, 0)) // but there is no player on that field yet assertEquals(FIELD_FREE, s.getFieldPlayer(19, 0)) assertFalse(s.isValidTurn(stone.shape, 0, 0, 0, Orientation.Default)) // X // XX val turn = Turn(0, stone.shape.number, 18, 0, Orientation(false, Rotation.Left)) assertTrue(s.isValidTurn(turn)) s.setStone(turn) assertEquals(0, stone.available) assertEquals(0, s.getFieldPlayer(19, 0)) assertEquals(0, s.getFieldPlayer(19, 1)) assertEquals(FIELD_FREE, s.getFieldPlayer(18, 0)) assertEquals(0, s.getFieldPlayer(18, 1)) assertEquals(FIELD_DENIED, s.getFieldStatus(0, 19, 0)) assertEquals(FIELD_DENIED, s.getFieldStatus(0, 19, 1)) // even though 18/0 is free, for this player it is denied, because it shares an edge assertEquals(FIELD_DENIED, s.getFieldStatus(0, 18, 0)) assertEquals(FIELD_DENIED, s.getFieldStatus(0, 18, 1)) assertEquals(FIELD_ALLOWED, s.getFieldStatus(0, 17, 0)) assertEquals(FIELD_DENIED, s.getFieldStatus(0, 17, 1)) assertEquals(FIELD_ALLOWED, s.getFieldStatus(0, 17, 2)) assertEquals(FIELD_FREE, s.getFieldStatus(0, 17, 3)) assertFalse(s.isValidTurn(turn)) s.refreshPlayerData() assertEquals(141, s.getPlayer(0).numberOfPossibleTurns) } @Test(expected = GameStateException::class) fun test_single_stone_not_available() { val board = Board() val turn = Turn(0, 0, 0, 0, Orientation()) board.setStone(turn) } @Test fun test_single_stone_next_to_each_other() { val board = Board() board.startNewGame(GAMEMODE_4_COLORS_4_PLAYERS, GameConfig.DEFAULT_STONE_SET, 20, 20) board.getPlayer(0).getStone(0).available = 2 val turn1 = Turn(0, 0, 19, 0, Orientation()) val turn2 = Turn(0, 0, 18, 0, Orientation()) assertTrue(board.isValidTurn(turn1)) board.setStone(turn1) assertFalse(board.isValidTurn(turn2)) // well, setStone does not actually verify whether the turn is legal, so this // would succeed. Nothing to see here. board.setStone(turn2) } @Test(expected = GameStateException::class) fun test_single_stone_twice() { val board = Board() board.getPlayer(0).getStone(0).available = 2 board.startNewGame(GAMEMODE_4_COLORS_4_PLAYERS, GameConfig.DEFAULT_STONE_SET, 20, 20) val turn = Turn(0, 0, 19, 0, Orientation()) assertTrue(board.isValidTurn(turn)) try { board.setStone(turn) } catch (e: GameStateException) { fail("Not expected here") } assertFalse(board.isValidTurn(turn)) // setting the same stone twice throws an Exception board.setStone(turn) } @Test fun test_seed_duo() { val board = Board(14, 14) assertEquals(Point(4, 9), board.getPlayerSeed(0, GAMEMODE_DUO)) assertEquals(Point(9, 4), board.getPlayerSeed(2, GAMEMODE_DUO)) } @Test fun test_seed_junior() { val board = Board(14, 14) assertEquals(Point(4, 9), board.getPlayerSeed(0, GAMEMODE_JUNIOR)) assertEquals(Point(9, 4), board.getPlayerSeed(2, GAMEMODE_JUNIOR)) } @Test fun test_seed_classic() { val board = Board() assertEquals(Point(0, 19), board.getPlayerSeed(0, GAMEMODE_4_COLORS_4_PLAYERS)) assertEquals(Point(0, 0), board.getPlayerSeed(1, GAMEMODE_4_COLORS_4_PLAYERS)) assertEquals(Point(19, 0), board.getPlayerSeed(2, GAMEMODE_4_COLORS_4_PLAYERS)) assertEquals(Point(19, 19), board.getPlayerSeed(3, GAMEMODE_4_COLORS_4_PLAYERS)) } @Test fun test_seed_2_color_2_players() { val board = Board(GameConfig.defaultSizeForMode(GAMEMODE_2_COLORS_2_PLAYERS)) assertEquals(Point(0, 14), board.getPlayerSeed(0, GAMEMODE_2_COLORS_2_PLAYERS)) assertEquals(Point(0, 0), board.getPlayerSeed(1, GAMEMODE_2_COLORS_2_PLAYERS)) assertEquals(Point(14, 0), board.getPlayerSeed(2, GAMEMODE_2_COLORS_2_PLAYERS)) assertEquals(Point(14, 14), board.getPlayerSeed(3, GAMEMODE_2_COLORS_2_PLAYERS)) } @Test fun test_full_game_4_4() { val s = Board(20) val mode = GAMEMODE_4_COLORS_4_PLAYERS s.startNewGame(mode, GameConfig.DEFAULT_STONE_SET, 20, 20) assertEquals(58, s.getPlayer(0).numberOfPossibleTurns) assertEquals(58, s.getPlayer(1).numberOfPossibleTurns) assertEquals(58, s.getPlayer(2).numberOfPossibleTurns) assertEquals(58, s.getPlayer(3).numberOfPossibleTurns) assertEquals(21, s.getPlayer(0).stonesLeft) assertEquals(21, s.getPlayer(1).stonesLeft) assertEquals(21, s.getPlayer(2).stonesLeft) assertEquals(21, s.getPlayer(3).stonesLeft) val turnpool = s.playGame { turns -> turns.last() } assertEquals(65, turnpool.size) assertEquals(3, s.getPlayer(0).stonesLeft) assertEquals(5, s.getPlayer(1).stonesLeft) assertEquals(4, s.getPlayer(2).stonesLeft) assertEquals(7, s.getPlayer(3).stonesLeft) assertEquals(78, s.getPlayer(0).totalPoints) assertEquals(69, s.getPlayer(1).totalPoints) assertEquals(75, s.getPlayer(2).totalPoints) assertEquals(61, s.getPlayer(3).totalPoints) assertEquals(0, s.getPlayer(0).numberOfPossibleTurns) assertEquals(0, s.getPlayer(1).numberOfPossibleTurns) assertEquals(0, s.getPlayer(2).numberOfPossibleTurns) assertEquals(0, s.getPlayer(3).numberOfPossibleTurns) // and backwards while (!turnpool.isEmpty()) { s.undo(turnpool, mode) } assertEquals(58, s.getPlayer(0).numberOfPossibleTurns) assertEquals(58, s.getPlayer(1).numberOfPossibleTurns) assertEquals(58, s.getPlayer(2).numberOfPossibleTurns) assertEquals(58, s.getPlayer(3).numberOfPossibleTurns) assertEquals(21, s.getPlayer(0).stonesLeft) assertEquals(21, s.getPlayer(1).stonesLeft) assertEquals(21, s.getPlayer(2).stonesLeft) assertEquals(21, s.getPlayer(3).stonesLeft) } @Test fun test_full_game_duo() { val s = Board() val mode = GAMEMODE_DUO // we have to make stones available before starting a new game, otherwise we won't get seeds set s.startNewGame(mode, GameConfig.DEFAULT_STONE_SET, 15, 15) assertEquals(309, s.getPlayer(0).numberOfPossibleTurns) assertEquals(0, s.getPlayer(1).numberOfPossibleTurns) assertEquals(309, s.getPlayer(2).numberOfPossibleTurns) assertEquals(0, s.getPlayer(3).numberOfPossibleTurns) assertEquals(21, s.getPlayer(0).stonesLeft) assertEquals(0, s.getPlayer(1).stonesLeft) assertEquals(21, s.getPlayer(2).stonesLeft) assertEquals(0, s.getPlayer(3).stonesLeft) val turnpool = s.playGame { turns -> turns.last() } assertEquals(34, turnpool.size) assertEquals(4, s.getPlayer(0).stonesLeft) assertEquals(0, s.getPlayer(1).stonesLeft) assertEquals(4, s.getPlayer(2).stonesLeft) assertEquals(0, s.getPlayer(3).stonesLeft) assertEquals(77, s.getPlayer(0).totalPoints) assertEquals(0, s.getPlayer(1).totalPoints) assertEquals(74, s.getPlayer(2).totalPoints) assertEquals(0, s.getPlayer(3).totalPoints) assertEquals(0, s.getPlayer(0).numberOfPossibleTurns) assertEquals(0, s.getPlayer(1).numberOfPossibleTurns) assertEquals(0, s.getPlayer(2).numberOfPossibleTurns) assertEquals(0, s.getPlayer(3).numberOfPossibleTurns) // and backwards while (!turnpool.isEmpty()) { s.undo(turnpool, mode) } assertEquals(309, s.getPlayer(0).numberOfPossibleTurns) assertEquals(0, s.getPlayer(1).numberOfPossibleTurns) assertEquals(309, s.getPlayer(2).numberOfPossibleTurns) assertEquals(0, s.getPlayer(3).numberOfPossibleTurns) assertEquals(21, s.getPlayer(0).stonesLeft) assertEquals(0, s.getPlayer(1).stonesLeft) assertEquals(21, s.getPlayer(2).stonesLeft) assertEquals(0, s.getPlayer(3).stonesLeft) } @Test fun test_full_game_junior() { val s = Board() val mode = GAMEMODE_JUNIOR s.startNewGame(mode, GameConfig.JUNIOR_STONE_SET, 14, 14) assertEquals(169, s.getPlayer(0).numberOfPossibleTurns) assertEquals(0, s.getPlayer(1).numberOfPossibleTurns) assertEquals(169, s.getPlayer(2).numberOfPossibleTurns) assertEquals(0, s.getPlayer(3).numberOfPossibleTurns) assertEquals(24, s.getPlayer(0).stonesLeft) assertEquals(0, s.getPlayer(1).stonesLeft) assertEquals(24, s.getPlayer(2).stonesLeft) assertEquals(0, s.getPlayer(3).stonesLeft) val turnpool = s.playGame { turns -> turns.last() } assertEquals(33, turnpool.size) assertEquals(8, s.getPlayer(0).stonesLeft) assertEquals(0, s.getPlayer(1).stonesLeft) assertEquals(7, s.getPlayer(2).stonesLeft) assertEquals(0, s.getPlayer(3).stonesLeft) assertEquals(61, s.getPlayer(0).totalPoints) assertEquals(0, s.getPlayer(1).totalPoints) assertEquals(64, s.getPlayer(2).totalPoints) assertEquals(0, s.getPlayer(3).totalPoints) assertEquals(0, s.getPlayer(0).numberOfPossibleTurns) assertEquals(0, s.getPlayer(1).numberOfPossibleTurns) assertEquals(0, s.getPlayer(2).numberOfPossibleTurns) assertEquals(0, s.getPlayer(3).numberOfPossibleTurns) // and backwards while (!turnpool.isEmpty()) { s.undo(turnpool, mode) } assertEquals(169, s.getPlayer(0).numberOfPossibleTurns) assertEquals(0, s.getPlayer(1).numberOfPossibleTurns) assertEquals(169, s.getPlayer(2).numberOfPossibleTurns) assertEquals(0, s.getPlayer(3).numberOfPossibleTurns) assertEquals(24, s.getPlayer(0).stonesLeft) assertEquals(0, s.getPlayer(1).stonesLeft) assertEquals(24, s.getPlayer(2).stonesLeft) assertEquals(0, s.getPlayer(3).stonesLeft) } @Test fun test_full_game_reversed() { val s = Board(20) val mode = GAMEMODE_4_COLORS_4_PLAYERS // we have to make stones available before starting a new game, otherwise we won't get seeds set s.startNewGame(GAMEMODE_4_COLORS_4_PLAYERS, GameConfig.DEFAULT_STONE_SET, 20, 20) assertEquals(58, s.getPlayer(0).numberOfPossibleTurns) assertEquals(58, s.getPlayer(1).numberOfPossibleTurns) assertEquals(58, s.getPlayer(2).numberOfPossibleTurns) assertEquals(58, s.getPlayer(3).numberOfPossibleTurns) val turnpool = s.playGame { turns -> turns.first() } assertEquals(63, turnpool.size) assertEquals(6, s.getPlayer(0).stonesLeft) assertEquals(6, s.getPlayer(1).stonesLeft) assertEquals(4, s.getPlayer(2).stonesLeft) assertEquals(5, s.getPlayer(3).stonesLeft) assertEquals(59, s.getPlayer(0).totalPoints) assertEquals(59, s.getPlayer(1).totalPoints) assertEquals(69, s.getPlayer(2).totalPoints) assertEquals(64, s.getPlayer(3).totalPoints) assertEquals(0, s.getPlayer(0).numberOfPossibleTurns) assertEquals(0, s.getPlayer(1).numberOfPossibleTurns) assertEquals(0, s.getPlayer(2).numberOfPossibleTurns) assertEquals(0, s.getPlayer(3).numberOfPossibleTurns) // and backwards while (!turnpool.isEmpty()) { s.undo(turnpool, mode) } assertEquals(58, s.getPlayer(0).numberOfPossibleTurns) assertEquals(58, s.getPlayer(1).numberOfPossibleTurns) assertEquals(58, s.getPlayer(2).numberOfPossibleTurns) assertEquals(58, s.getPlayer(3).numberOfPossibleTurns) assertEquals(21, s.getPlayer(0).stonesLeft) assertEquals(21, s.getPlayer(1).stonesLeft) assertEquals(21, s.getPlayer(2).stonesLeft) assertEquals(21, s.getPlayer(3).stonesLeft) } }
gpl-2.0
2d5a07b85a55019466c445383b190dba
38.037634
104
0.643895
3.825342
false
true
false
false
SapuSeven/BetterUntis
app/src/main/java/com/sapuseven/untis/activities/ErrorsActivity.kt
1
2833
package com.sapuseven.untis.activities import android.os.Bundle import android.view.View.GONE import androidx.constraintlayout.widget.ConstraintSet import androidx.recyclerview.widget.LinearLayoutManager import com.sapuseven.untis.R import com.sapuseven.untis.adapters.ErrorsAdapter import com.sapuseven.untis.dialogs.ErrorReportingDialog import com.sapuseven.untis.helpers.ZipUtils import com.sapuseven.untis.helpers.issues.GithubIssue import com.sapuseven.untis.helpers.issues.Issue import kotlinx.android.synthetic.main.activity_errors.* import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import java.io.File class ErrorsActivity : BaseActivity() { companion object { const val EXTRA_BOOLEAN_SHOW_CRASH_MESSAGE = "com.sapuseven.activities.errors.crashmessage" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_errors) if (!intent.getBooleanExtra(EXTRA_BOOLEAN_SHOW_CRASH_MESSAGE, false)) { textview_crash_title.visibility = GONE textview_crash_message.visibility = GONE with(ConstraintSet()) { clone(constraintlayout_root) connect(textview_errors_report.id, ConstraintSet.TOP, constraintlayout_root.id, ConstraintSet.TOP) applyTo(constraintlayout_root) } } button_dismiss.setOnClickListener { deleteLogFiles() finish() } loadErrorList() button_report.setOnClickListener { val zipFile = zipLogFiles() deleteLogFiles() GithubIssue(Issue.Type.CRASH, getString(R.string.errors_github_attach_file_message, zipFile.absolutePath)).launch(this) } } private fun deleteLogFiles() { File(filesDir, "logs").deleteRecursively() } private fun zipLogFiles(): File { return File(getExternalFilesDir(null), "logs-" + System.currentTimeMillis() + ".zip").also { ZipUtils.zip(File(filesDir, "logs"), it) } } private fun loadErrorList() { recyclerview_errors.layoutManager = LinearLayoutManager(this) recyclerview_errors.adapter = ErrorsAdapter(File(filesDir, "logs").listFiles()?.let { files -> files.sortedDescending() .map { val timestamp = it.name.replace(Regex("""^_?(\d+)(-\d+)?.log$"""), "$1").toLongOrNull() ErrorData( readCrashData(it), timestamp?.let { DateTime(timestamp).toString(DateTimeFormat.mediumDateTime()) } ?: "(unknown date)" // TODO: Extract string resource ) } .groupingBy { it } .eachCount() .map { ErrorData( it.key.log, if (it.value > 1) "${it.key.time} (${it.value})" else it.key.time ) } } ?: emptyList()) (recyclerview_errors.adapter as ErrorsAdapter).setOnItemClickListener { item -> ErrorReportingDialog(this).showGenericErrorDialog(item.log) } } data class ErrorData( val log: String, val time: String ) }
gpl-3.0
8e9a06a38f7446c76ecc26c3c1e258e6
29.462366
122
0.725732
3.722733
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/views/CustomDatePicker.kt
1
5594
package org.wikipedia.views import android.app.Dialog import android.content.DialogInterface import android.graphics.Typeface import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import org.wikipedia.R import org.wikipedia.databinding.DatePickerDialogBinding import org.wikipedia.databinding.ViewCustomCalendarDayBinding import org.wikipedia.util.DateUtil import org.wikipedia.util.ResourceUtil import java.util.* class CustomDatePicker : DialogFragment() { interface Callback { fun onDatePicked(month: Int, day: Int) } private var _binding: DatePickerDialogBinding? = null private val binding get() = _binding!! private val today = Calendar.getInstance() private val selectedDay = Calendar.getInstance() private val callbackDay = Calendar.getInstance() var callback: Callback? = null override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { _binding = DatePickerDialogBinding.inflate(LayoutInflater.from(requireContext())) setUpMonthGrid() setMonthString() setDayString() setPreviousMonthClickListener() setNextMonthClickListener() return AlertDialog.Builder(requireActivity()) .setView(binding.root) .setPositiveButton(R.string.custom_date_picker_dialog_ok_button_text) { _: DialogInterface?, _: Int -> callback?.onDatePicked(callbackDay[Calendar.MONTH], callbackDay[Calendar.DATE]) } .setNegativeButton(R.string.custom_date_picker_dialog_cancel_button_text) { dialog: DialogInterface, _: Int -> dialog.dismiss() } .create() } private fun setPreviousMonthClickListener() { binding.previousMonth.setOnClickListener { val currentMonth = selectedDay[Calendar.MONTH] selectedDay[LEAP_YEAR, if (currentMonth == 0) Calendar.DECEMBER else currentMonth - 1] = 1 setMonthString() } } private fun setNextMonthClickListener() { binding.nextMonth.setOnClickListener { val currentMonth = selectedDay[Calendar.MONTH] selectedDay[LEAP_YEAR, if (currentMonth == Calendar.DECEMBER) Calendar.JANUARY else currentMonth + 1] = 1 setMonthString() } } private fun setUpMonthGrid() { binding.calendarGrid.layoutManager = GridLayoutManager(requireContext(), MAX_COLUMN_SPAN) binding.calendarGrid.adapter = CustomCalendarAdapter() } private fun setMonthString() { binding.currentMonth.text = DateUtil.getMonthOnlyWithoutDayDateString(selectedDay.time) binding.calendarGrid.adapter!!.notifyDataSetChanged() } inner class CustomCalendarAdapter : RecyclerView.Adapter<CustomCalendarAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(ViewCustomCalendarDayBinding.inflate(LayoutInflater.from(requireContext()), parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.setFields(position + 1) } override fun getItemCount(): Int { return selectedDay.getActualMaximum(Calendar.DAY_OF_MONTH) } inner class ViewHolder internal constructor(private val binding: ViewCustomCalendarDayBinding) : RecyclerView.ViewHolder(binding.root) { init { binding.root.setOnClickListener { selectedDay[Calendar.DATE] = bindingAdapterPosition + 1 callbackDay[LEAP_YEAR, selectedDay[Calendar.MONTH]] = bindingAdapterPosition + 1 setDayString() notifyItemRangeChanged(0, itemCount) } } fun setFields(position: Int) { if (position == today[Calendar.DATE] && today[Calendar.MONTH] == selectedDay[Calendar.MONTH]) { binding.dayText.setTextColor(ResourceUtil.getThemedColor(requireContext(), R.attr.colorAccent)) } else { binding.dayText.setTextColor(ResourceUtil.getThemedColor(requireContext(), R.attr.primary_text_color)) } if (position == callbackDay[Calendar.DATE] && selectedDay[Calendar.MONTH] == callbackDay[Calendar.MONTH]) { binding.dayText.setTextColor(ResourceUtil.getThemedColor(requireContext(), R.attr.paper_color)) binding.dayText.typeface = Typeface.DEFAULT_BOLD binding.dayCircleBackground.visibility = View.VISIBLE } else { binding.dayText.typeface = Typeface.DEFAULT binding.dayCircleBackground.visibility = View.GONE } binding.dayText.text = String.format(Locale.getDefault(), "%d", position) } } } private fun setDayString() { binding.calendarDay.text = DateUtil.getFeedCardShortDateString(selectedDay) } fun setSelectedDay(month: Int, day: Int) { selectedDay[LEAP_YEAR, month] = day callbackDay[LEAP_YEAR, month] = day } override fun onDestroyView() { _binding = null super.onDestroyView() } companion object { private const val MAX_COLUMN_SPAN = 7 const val LEAP_YEAR = 2016 } }
apache-2.0
dbe2b1595906a5ef984bc917c4c129c8
39.536232
200
0.668573
5.026056
false
false
false
false
stripe/stripe-android
stripe-core/src/main/java/com/stripe/android/core/networking/RequestHeadersFactory.kt
1
7447
package com.stripe.android.core.networking import android.os.Build import android.system.Os import androidx.annotation.RestrictTo import com.stripe.android.core.ApiVersion import com.stripe.android.core.AppInfo import com.stripe.android.core.version.StripeSdkVersion import java.util.Locale @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) sealed class RequestHeadersFactory { /** * Creates a map for headers attached to all requests. */ fun create(): Map<String, String> { return extraHeaders.plus( mapOf( HEADER_USER_AGENT to userAgent, HEADER_ACCEPT_CHARSET to CHARSET, HEADER_X_STRIPE_USER_AGENT to xStripeUserAgent ) ) } /** * Creates a map for headers attached to POST requests. Return am empty map if this factory is * used for request that doesn't have POST options. */ fun createPostHeader(): Map<String, String> { return postHeaders } protected abstract val userAgent: String protected abstract val extraHeaders: Map<String, String> protected open var postHeaders: Map<String, String> = emptyMap() protected abstract val xStripeUserAgent: String protected fun defaultXStripeUserAgentMap() = mutableMapOf<String, String?>( LANG to KOTLIN, AnalyticsFields.BINDINGS_VERSION to StripeSdkVersion.VERSION_NAME, AnalyticsFields.OS_VERSION to "${Build.VERSION.SDK_INT}", TYPE to "${Build.MANUFACTURER}_${Build.BRAND}_${Build.MODEL}", MODEL to Build.MODEL ) @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) open class BaseApiHeadersFactory( private val optionsProvider: () -> ApiRequest.Options, private val appInfo: AppInfo? = null, private val locale: Locale = Locale.getDefault(), private val apiVersion: String = ApiVersion.get().code, private val sdkVersion: String = StripeSdkVersion.VERSION ) : RequestHeadersFactory() { private val stripeClientUserAgentHeaderFactory = StripeClientUserAgentHeaderFactory() private val languageTag: String? get() { return locale.toLanguageTag() .takeIf { it.isNotBlank() && it != UNDETERMINED_LANGUAGE } } override val userAgent: String get() { return listOfNotNull( getUserAgent(sdkVersion), appInfo?.toUserAgent() ).joinToString(" ") } override val xStripeUserAgent: String get() { val paramMap = defaultXStripeUserAgentMap() appInfo?.let { paramMap.putAll(it.toParamMap()) } return "{" + paramMap.map { (key, value) -> "\"$key\":\"$value\"" }.joinToString(",") + "}" } override val extraHeaders: Map<String, String> get() { val apiRequestOptions = optionsProvider() return mapOf( HEADER_ACCEPT to "application/json", HEADER_STRIPE_VERSION to apiVersion, HEADER_AUTHORIZATION to "Bearer ${apiRequestOptions.apiKey}" ).plus( stripeClientUserAgentHeaderFactory.create(appInfo) ).plus( if (apiRequestOptions.apiKeyIsUserKey) { val isLiveMode = Os.getenv("Stripe-Livemode") != "false" mapOf(HEADER_STRIPE_LIVEMODE to isLiveMode.toString()) } else { emptyMap() } ).plus( apiRequestOptions.stripeAccount?.let { mapOf(HEADER_STRIPE_ACCOUNT to it) }.orEmpty() ).plus( apiRequestOptions.idempotencyKey?.let { mapOf(HEADER_IDEMPOTENCY_KEY to it) }.orEmpty() ).plus( languageTag?.let { mapOf(HEADER_ACCEPT_LANGUAGE to it) }.orEmpty() ) } } /** * Factory for [ApiRequest]. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class Api( options: ApiRequest.Options, appInfo: AppInfo? = null, locale: Locale = Locale.getDefault(), apiVersion: String = ApiVersion.get().code, sdkVersion: String = StripeSdkVersion.VERSION ) : BaseApiHeadersFactory( { options }, appInfo, locale, apiVersion, sdkVersion ) { override var postHeaders = mapOf( HEADER_CONTENT_TYPE to "${StripeRequest.MimeType.Form}; charset=$CHARSET" ) } /** * Factory for [FileUploadRequest]. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class FileUpload( options: ApiRequest.Options, appInfo: AppInfo? = null, locale: Locale = Locale.getDefault(), apiVersion: String = ApiVersion.get().code, sdkVersion: String = StripeSdkVersion.VERSION, boundary: String ) : BaseApiHeadersFactory( { options }, appInfo, locale, apiVersion, sdkVersion ) { override var postHeaders = mapOf( HEADER_CONTENT_TYPE to "${StripeRequest.MimeType.MultipartForm.code}; boundary=$boundary" ) } /** * Factory for [FraudDetectionDataRequest]. * TODO(ccen) Move FraudDetection to payments-core. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class FraudDetection( guid: String ) : RequestHeadersFactory() { override val extraHeaders = mapOf(HEADER_COOKIE to "m=$guid") override val userAgent = getUserAgent(StripeSdkVersion.VERSION) @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) companion object { const val HEADER_COOKIE = "Cookie" } override var postHeaders = mapOf( HEADER_CONTENT_TYPE to "${StripeRequest.MimeType.Json}; charset=$CHARSET" ) override val xStripeUserAgent: String get() { val paramMap = defaultXStripeUserAgentMap() return "{" + paramMap.map { (key, value) -> "\"$key\":\"$value\"" }.joinToString(",") + "}" } } /** * Factory for [AnalyticsRequest]. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) object Analytics : RequestHeadersFactory() { override val userAgent = getUserAgent(StripeSdkVersion.VERSION) override val extraHeaders = emptyMap<String, String>() override val xStripeUserAgent: String get() { val paramMap = defaultXStripeUserAgentMap() return "{" + paramMap.map { (key, value) -> "\"$key\":\"$value\"" }.joinToString(",") + "}" } } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) companion object { fun getUserAgent( sdkVersion: String = StripeSdkVersion.VERSION ) = "Stripe/v1 $sdkVersion" val CHARSET: String = Charsets.UTF_8.name() const val UNDETERMINED_LANGUAGE = "und" const val LANG = "lang" const val KOTLIN = "kotlin" const val TYPE = "type" const val MODEL = "model" } }
mit
8efef531fa10c2d1b6eee4c32248df5e
32.696833
101
0.570028
5.038566
false
false
false
false
thanksmister/androidthings-mqtt-alarm-panel
app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/ui/fragments/ControlsFragment.kt
1
13151
/* * <!-- * ~ Copyright (c) 2017. ThanksMister 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.thanksmister.iot.mqtt.alarmpanel.ui.fragments import android.content.Context import android.os.Bundle import android.support.v7.app.AlertDialog import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import com.thanksmister.iot.mqtt.alarmpanel.BaseActivity import com.thanksmister.iot.mqtt.alarmpanel.BaseFragment import com.thanksmister.iot.mqtt.alarmpanel.R import com.thanksmister.iot.mqtt.alarmpanel.network.MQTTOptions import com.thanksmister.iot.mqtt.alarmpanel.ui.Configuration import com.thanksmister.iot.mqtt.alarmpanel.ui.activities.SettingsActivity import com.thanksmister.iot.mqtt.alarmpanel.ui.views.AlarmDisableView import com.thanksmister.iot.mqtt.alarmpanel.ui.views.AlarmPendingView import com.thanksmister.iot.mqtt.alarmpanel.ui.views.ArmOptionsView import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_ARM_AWAY import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_ARM_AWAY_PENDING import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_ARM_HOME import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_ARM_HOME_PENDING import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_ARM_PENDING import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_AWAY_TRIGGERED_PENDING import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_DISARM import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_HOME_TRIGGERED_PENDING import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils.Companion.MODE_TRIGGERED_PENDING import com.thanksmister.iot.mqtt.alarmpanel.utils.DialogUtils import com.thanksmister.iot.mqtt.alarmpanel.viewmodel.MainViewModel import com.thanksmister.iot.mqtt.alarmpanel.viewmodel.MessageViewModel import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.fragment_controls.* import timber.log.Timber import javax.inject.Inject class ControlsFragment : BaseFragment() { @Inject lateinit var mqttOptions: MQTTOptions @Inject lateinit var dialogUtils: DialogUtils @Inject lateinit var configuration: Configuration private var alarmPendingView: AlarmPendingView? = null private var mListener: OnControlsFragmentListener? = null /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. */ interface OnControlsFragmentListener { fun publishArmedHome() fun publishArmedAway() fun publishDisarmed() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) lifecycle.addObserver(dialogUtils) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) observeViewModel(viewModel) // TODO this may not be needed since we pick up the state from the mqtt service if (viewModel.isArmed()) { if (viewModel.getAlarmMode() == MODE_ARM_AWAY) { setArmedAwayView() } else if (viewModel.getAlarmMode() == MODE_ARM_HOME) { setArmedHomeView() } } else { setDisarmedView() } } override fun onAttach(context: Context?) { super.onAttach(context) if (context is OnControlsFragmentListener) { mListener = context } else { throw RuntimeException(context!!.toString() + " must implement OnControlsFragmentListener") } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_controls, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) alarmPendingView = view.findViewById<AlarmPendingView>(R.id.pendingView) alarmView.setOnClickListener { if (!hasNetworkConnectivity()) { // we can't change the alarm state without network connection. handleNetworkDisconnect() } else if (mqttOptions.isValid) { if (viewModel.getAlarmMode() == MODE_DISARM) { showArmOptionsDialog() } else { showAlarmDisableDialog(false, viewModel.getDisableDialogTime()) } } else { if (isAdded) { dialogUtils.showAlertDialog(activity as BaseActivity, getString(R.string.text_error_no_alarm_setup)) } } } } override fun onDetach() { super.onDetach() mListener = null } private fun observeViewModel(viewModel: MessageViewModel) { disposable.add(viewModel.getAlarmState() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ state -> Timber.d("Alarm state: " + state) Timber.d("Alarm mode: " + viewModel.getAlarmMode()) activity?.runOnUiThread { when (state) { AlarmUtils.STATE_ARM_AWAY -> { dialogUtils.clearDialogs() hideAlarmPendingView() viewModel.setAlarmMode(MODE_ARM_AWAY) setArmedAwayView() } AlarmUtils.STATE_ARM_HOME -> { dialogUtils.clearDialogs() hideAlarmPendingView() viewModel.setAlarmMode(MODE_ARM_HOME) setArmedHomeView() } AlarmUtils.STATE_DISARM -> { dialogUtils.clearDialogs() viewModel.setAlarmMode(MODE_DISARM) hideAlarmPendingView() setDisarmedView() } AlarmUtils.STATE_PENDING -> if (configuration.isAlarmPendingMode()) { if (viewModel.getAlarmMode() == MODE_ARM_HOME_PENDING || viewModel.getAlarmMode() == MODE_HOME_TRIGGERED_PENDING) { setArmedHomeView() } else if (viewModel.getAlarmMode() == MODE_ARM_AWAY_PENDING || viewModel.getAlarmMode() == MODE_AWAY_TRIGGERED_PENDING) { setArmedAwayView() } } else if (viewModel.getAlarmMode() != MODE_ARM_HOME && viewModel.getAlarmMode() != MODE_ARM_AWAY && viewModel.getAlarmMode() != MODE_TRIGGERED_PENDING) { setPendingView(MODE_ARM_PENDING) } AlarmUtils.STATE_ERROR -> { viewModel.setAlarmMode(MODE_DISARM) hideAlarmPendingView() setDisarmedView() } } } }, { error -> Timber.e("Unable to get message: " + error) })) } private fun setArmedAwayView() { alarmText.setText(R.string.text_armed_away) alarmText.setTextColor(resources.getColor(R.color.red)) alarmButtonBackground.setBackgroundDrawable(resources.getDrawable(R.drawable.button_round_red)) } private fun setArmedHomeView() { alarmText.setText(R.string.text_armed_home) alarmText.setTextColor(resources.getColor(R.color.yellow)) alarmButtonBackground.setBackgroundDrawable(resources.getDrawable(R.drawable.button_round_yellow)) } /** * We want to show a pending countdown view for the given * mode which can be arm home, arm away, or arm pending (from HASS). * @param mode PREF_ARM_HOME_PENDING, PREF_ARM_AWAY_PENDING, PREF_ARM_PENDING */ private fun setPendingView(mode: String) { Timber.d("setPendingView: " + mode) viewModel.isArmed(true) viewModel.setAlarmMode(mode) if (MODE_ARM_HOME_PENDING == mode) { alarmText.setText(R.string.text_armed_home) alarmText.setTextColor(resources.getColor(R.color.yellow)) alarmButtonBackground.setBackgroundDrawable(resources.getDrawable(R.drawable.button_round_yellow)) showAlarmPendingView(configuration.pendingHomeTime) } else if (MODE_ARM_AWAY_PENDING == mode) { alarmText.setText(R.string.text_armed_away) alarmText.setTextColor(resources.getColor(R.color.red)) alarmButtonBackground.setBackgroundDrawable(resources.getDrawable(R.drawable.button_round_red)) showAlarmPendingView(configuration.pendingAwayTime) } else if (MODE_ARM_PENDING == mode) { alarmText.setText(R.string.text_alarm_pending) alarmText.setTextColor(resources.getColor(R.color.gray)) alarmButtonBackground.setBackgroundDrawable(resources.getDrawable(R.drawable.button_round_gray)) showAlarmPendingView(configuration.pendingTime) Toast.makeText(activity, getString(R.string.text_alarm_set_externally), Toast.LENGTH_LONG).show() } } private fun setDisarmedView() { viewModel.isArmed(false) viewModel.setAlarmMode(MODE_DISARM) alarmText.setText(R.string.text_disarmed) alarmText.setTextColor(resources.getColor(R.color.green)) alarmButtonBackground.setBackgroundDrawable(resources.getDrawable(R.drawable.button_round_green)) } private fun showAlarmPendingView(pendingTime : Int) { if (alarmPendingLayout.isShown || pendingTime == 0) { return } alarmPendingLayout.visibility = View.VISIBLE alarmPendingView!!.alarmListener = (object : AlarmPendingView.ViewListener { override fun onTimeOut() { hideAlarmPendingView() } }) alarmPendingView!!.startCountDown(pendingTime) } private fun hideAlarmPendingView() { alarmPendingLayout.visibility = View.GONE alarmPendingView!!.stopCountDown() } private fun showArmOptionsDialog() { dialogUtils.showArmOptionsDialog(activity as BaseActivity, object : ArmOptionsView.ViewListener { override fun onArmHome() { mListener!!.publishArmedHome() setPendingView(MODE_ARM_HOME_PENDING) dialogUtils.clearDialogs() } override fun onArmAway() { mListener!!.publishArmedAway() setPendingView(MODE_ARM_AWAY_PENDING) dialogUtils.clearDialogs() } }) } /** * Shows a count down dialog before setting alarm to away */ private fun showAlarmDisableDialog(beep: Boolean, timeRemaining: Int) { dialogUtils.showAlarmDisableDialog(activity as BaseActivity, object : AlarmDisableView.ViewListener { override fun onComplete(code: Int) { mListener!!.publishDisarmed() dialogUtils.clearDialogs() } override fun onError() { Toast.makeText(activity, R.string.toast_code_invalid, Toast.LENGTH_SHORT).show() } override fun onCancel() { Timber.d("onCancel") dialogUtils.clearDialogs() } }, viewModel.getAlarmCode(), beep, timeRemaining) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. */ fun newInstance(): ControlsFragment { return ControlsFragment() } } }
apache-2.0
bb803b6c3585ad425b89691123560424
42.986622
158
0.625048
4.571081
false
false
false
false
satamas/fortran-plugin
src/main/kotlin/org/jetbrains/fortran/lang/parser/FortranParserDefinitionBase.kt
1
1120
package org.jetbrains.fortran.lang.parser import com.intellij.lang.ASTNode import com.intellij.lang.ParserDefinition import com.intellij.lang.PsiParser import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.tree.TokenSet import org.jetbrains.fortran.lang.FortranTypes import org.jetbrains.fortran.lang.psi.FortranTokenSets abstract class FortranParserDefinitionBase : ParserDefinition { override fun createParser(project: Project) : PsiParser = FortranParser() override fun getWhitespaceTokens(): TokenSet = FortranTokenSets.WHITE_SPACES override fun getCommentTokens(): TokenSet = FortranTokenSets.COMMENTS override fun getStringLiteralElements(): TokenSet = FortranTokenSets.STRINGS override fun createElement(astNode: ASTNode): PsiElement = FortranManualPsiElementFactory.createElement(astNode) ?: FortranTypes.Factory.createElement(astNode) override fun spaceExistenceTypeBetweenTokens(astNode: ASTNode, astNode1: ASTNode): ParserDefinition.SpaceRequirements = ParserDefinition.SpaceRequirements.MAY }
apache-2.0
b94cae27d97fe22bfb2cb72e096068b9
40.518519
123
0.805357
5.209302
false
false
false
false
kiruto/debug-bottle
components/src/main/kotlin/com/exyui/android/debugbottle/components/injector/InjectorActivity.kt
1
2298
//package com.exyui.android.debugbottle.components.injector // //import android.support.v7.app.AppCompatActivity //import android.os.Bundle //import android.text.Editable //import android.text.TextWatcher //import android.widget.EditText //import android.widget.ListView //import com.exyui.android.debugbottle.components.R //import com.exyui.android.debugbottle.components.SearchableListViewHelper //import com.exyui.android.debugbottle.components.injector.* // //@Deprecated("") //internal class InjectorActivity : AppCompatActivity() { // // companion object { // val TYPE = "type" // val TYPE_RUNNABLE = 0x11 // val TYPE_INTENT = 0x22 // val TYPE_ALL_ACTIVITIES = 0x33 // } // // private val type by lazy { intent.extras.getInt(TYPE) } // // private val adapter by lazy { // val injectable = when (type) { // TYPE_RUNNABLE -> RunnableInjector // TYPE_INTENT -> { // IntentInjector.setActivity(this) // IntentInjector // } // TYPE_ALL_ACTIVITIES -> AllActivities(this) // else -> throw NotImplementedError("$type is not implemented") // } // InjectableAdapter(injectable) // } // // private val editText by lazy { // val result = findViewById(R.id.edit_text) as EditText // result.addTextChangedListener(object: TextWatcher { // override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { // // } // // override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { // // } // // override fun afterTextChanged(s: Editable?) { // val pattern = SearchableListViewHelper.getPattern(s.toString()) // adapter.highlight(pattern, s.toString()) // } // }) // result // } // // private val list by lazy { // val result = findViewById(R.id.list_view) as ListView // result.adapter = adapter // result.onItemClickListener = adapter // result // } // // override fun onCreate(savedInstanceState: Bundle?) { // super.onCreate(savedInstanceState) // setContentView(R.layout.__activity_injector) // list; editText // } //}
apache-2.0
478c056d073a45f069bc546b01f67097
32.304348
100
0.611836
4.031579
false
false
false
false
hotpodata/redchain
mobile/src/main/java/com/hotpodata/redchain/adapter/viewholder/ChainTodayWithStatsVh.kt
1
2665
package com.hotpodata.redchain.adapter.viewholder import android.support.v7.widget.CardView import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import android.widget.TextView import com.hotpodata.redchain.R import com.hotpodata.redchain.view.XView /** * Created by jdrotos on 9/17/15. */ class ChainTodayWithStatsVh(val v: View) : RecyclerView.ViewHolder(v) { var cardview: CardView var sceneRoot: ViewGroup var contentContainer: ViewGroup var xview: XView var todayTitleTv: TextView //Unchecked mode var motivationBlurbTv: TextView? //Checked mode var timeTv: TextView? var statsContainer: ViewGroup? var currentDayCountTv: TextView? var currentDayLabelTv: TextView? var bestInChainCountTv: TextView? var bestAllChainsCountTv: TextView? init { cardview = v.findViewById(R.id.cardview) as CardView sceneRoot = v.findViewById(R.id.scene_root) as ViewGroup contentContainer = v.findViewById(R.id.content_container) as ViewGroup xview = v.findViewById(R.id.xview) as XView todayTitleTv = v.findViewById(R.id.today_title_tv) as TextView motivationBlurbTv = v.findViewById(R.id.motivation_blurb) as TextView? statsContainer = v.findViewById(R.id.stats_container) as ViewGroup? timeTv = v.findViewById(R.id.time) as TextView? currentDayCountTv = v.findViewById(R.id.current_day_count_tv) as TextView? currentDayLabelTv = v.findViewById(R.id.current_day_count_label_tv) as TextView? bestInChainCountTv = v.findViewById(R.id.best_in_chain_tv) as TextView? bestAllChainsCountTv = v.findViewById(R.id.all_chains_best_count_tv) as TextView? } fun rebindViews(){ cardview = v.findViewById(R.id.cardview) as CardView sceneRoot = v.findViewById(R.id.scene_root) as ViewGroup contentContainer = v.findViewById(R.id.content_container) as ViewGroup xview = v.findViewById(R.id.xview) as XView todayTitleTv = v.findViewById(R.id.today_title_tv) as TextView motivationBlurbTv = v.findViewById(R.id.motivation_blurb) as TextView? statsContainer = v.findViewById(R.id.stats_container) as ViewGroup? timeTv = v.findViewById(R.id.time) as TextView? currentDayCountTv = v.findViewById(R.id.current_day_count_tv) as TextView? currentDayLabelTv = v.findViewById(R.id.current_day_count_label_tv) as TextView? bestInChainCountTv = v.findViewById(R.id.best_in_chain_tv) as TextView? bestAllChainsCountTv = v.findViewById(R.id.all_chains_best_count_tv) as TextView? } }
apache-2.0
be24edc69d1ca01d100671786e8da3e1
39.393939
89
0.720826
3.645691
false
false
false
false
jean79/yested
src/main/docsite/layout/containers.kt
2
4398
package layout import net.yested.* import net.yested.bootstrap.* import net.yested.layout.* import net.yested.layout.containers.horizontalContainer import net.yested.layout.containers.verticalContainer fun createHorizontalLayoutSection(): Div { return div { row { col(Medium(12)) { pageHeader { h3 { +"Layout" } } } } row { col(Medium(4)) { h4 { +"Demo" } panel { heading { +"Sample Panel" } content { horizontalContainer(width = 100.pct()) { column(width = 100.pct()) { div { scrollPane(width = 100.pct(), horizontal = Overflow.AUTO) { div { +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFHHF" } } } } column(width = 70.px()) { +"CCC" } } } } panel { heading { +"Sample Panel" } content { div { "style".."height: 200px" scrollPane(horizontal = Overflow.AUTO, vertical = Overflow.AUTO) { div { +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFffffffffffffffffffffffffffffffffHHF" } } } } } panel { heading { +"Sample Panel" } content { verticalContainer(width = 100.pct(), height = 300.px()) { row(height = 100.pct(), width = 100.pct()) { scrollPane(horizontal = Overflow.AUTO, vertical = Overflow.AUTO) { div { +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFHHF<br>" +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFHHF<br>" +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFHHF<br>" +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFHHF<br>" +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFHHF<br>" +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFHHF<br>" +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFHHF<br>" +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFHHF<br>" +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFHHF<br>" +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFHHF<br>" +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFHHF<br>" +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFHHF<br>" +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFHHF<br>" +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFHHF<br>" +"BBBCCCDDDEEEFFFGGGHHHJJJKKKFFFSASAEEERTTYUUJDFHFHFHFHFHHF<br>" } } } this.row(height = 20.px()) { div { +"CCC" } } } } } } col(Medium(8)) { h4 { +"Code" } code(lang = "kotlin", content= """TODO:""") } } } }
mit
3a1036995305429d6fd155f6969d85ad
45.797872
128
0.399955
4.663839
false
false
false
false
Soya93/Extract-Refactoring
plugins/settings-repository/src/ReadOnlySourcesManager.kt
5
2062
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository import com.intellij.util.SmartList import com.intellij.util.exists import org.eclipse.jgit.lib.Repository import org.eclipse.jgit.storage.file.FileRepositoryBuilder import org.jetbrains.annotations.TestOnly import java.nio.file.Path class ReadOnlySourcesManager(private val settings: IcsSettings, val rootDir: Path) { private var _repositories: List<Repository>? = null val repositories: List<Repository> get() { var r = _repositories if (r == null) { if (settings.readOnlySources.isEmpty()) { r = emptyList() } else { r = SmartList<Repository>() for (source in settings.readOnlySources) { try { val path = source.path ?: continue val dir = rootDir.resolve(path) if (dir.exists()) { r.add(FileRepositoryBuilder().setBare().setGitDir(dir.toFile()).build()) } else { LOG.warn("Skip read-only source ${source.url} because dir doesn't exists") } } catch (e: Exception) { LOG.error(e) } } } _repositories = r } return r } fun setSources(sources: List<ReadonlySource>) { settings.readOnlySources = sources _repositories = null } @TestOnly fun sourceToDir(source: ReadonlySource) = rootDir.resolve(source.path!!) }
apache-2.0
60b865c192baa71a53012deae843794e
31.234375
90
0.63967
4.387234
false
false
false
false
Chong-OS/PolygonGraph
app/src/main/java/com/chongos/polygongraphsample/MainActivity.kt
1
1853
package com.chongos.polygongraphsample import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import com.chongos.polygongraph.PolygonGraphView /** * @author ChongOS * @since 30-Jun-2017 */ class MainActivity : AppCompatActivity() { private var graph: PolygonGraphView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) bindView() setupView() } private fun bindView() { graph = findViewById(R.id.graph) as PolygonGraphView? } private fun setupView() { val values = listOf( PolygonGraphView.ValueHolder(getString(R.string.fit_cognitive), 0.8f, R.color.fitCognitive.toIntColor()), PolygonGraphView.ValueHolder(getString(R.string.fit_coping), 0.9f, R.color.fitCoping.toIntColor()), PolygonGraphView.ValueHolder(getString(R.string.fit_behavioral), 0.9f, R.color.fitBehavioral.toIntColor()), PolygonGraphView.ValueHolder(getString(R.string.fit_positive_psychology), 0.85f, R.color.fitPositivePsychology.toIntColor()), PolygonGraphView.ValueHolder(getString(R.string.fit_assertiveness), 0.75f, R.color.fitAssertiveness.toIntColor()), PolygonGraphView.ValueHolder(getString(R.string.fit_goal_setting), 0.5f, R.color.fitGoalSetting.toIntColor())) val adapter = object : PolygonGraphView.Adapter<PolygonGraphView.ValueHolder>() { override fun getSize(): Int = values.size override fun onCreateValueHolder(pos: Int): PolygonGraphView.ValueHolder = values[pos] } graph?.setAdapter(adapter) } private fun Int.toIntColor(): Int = ContextCompat.getColor(this@MainActivity, this) }
mit
8bdd32f3f9635c10608b894ff39a4064
39.282609
141
0.702105
4.099558
false
false
false
false
Tvede-dk/CommonsenseAndroidKotlin
base/src/main/kotlin/com/commonsense/android/kotlin/base/debug/PrettyPrint.kt
1
654
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate") package com.commonsense.android.kotlin.base.debug import com.commonsense.android.kotlin.base.extensions.* import com.commonsense.android.kotlin.base.extensions.collections.* /** * */ fun Map<String, String>.toPrettyString(name: String = "map"): String { return "$name content" + map { "${it.key.wrapInQuotes()} = ${it.value.wrapInQuotes()} " }.prettyStringContent() } fun List<String>.prettyStringContent(ifNotEmpty: String = "", ifEmpty: String = "", prefix: String = "\n\t"): String = isNotEmpty().map(ifNotEmpty, ifEmpty) + prefix + joinToString("\n\t")
mit
d22af6c792a8775a2d17404a243145ec
37.529412
118
0.712538
3.674157
false
false
false
false
wordpress-mobile/AztecEditor-Android
app/src/androidTest/kotlin/org/wordpress/aztec/demo/Matchers.kt
1
2370
package org.wordpress.aztec.demo import android.view.View import android.widget.EditText import org.hamcrest.Description import org.hamcrest.Matcher import org.hamcrest.TypeSafeMatcher import org.wordpress.aztec.AztecText import org.wordpress.aztec.source.Format import org.wordpress.aztec.source.SourceViewEditText object Matchers { fun withRegex(expected: Regex): Matcher<View> { return object : TypeSafeMatcher<View>() { override fun describeTo(description: Description) { description.appendText("EditText matches $expected") } public override fun matchesSafely(view: View): Boolean { if (view is EditText) { val regex = Regex(">\\s+<") val strippedText = view.text.toString().replace(regex, "><") return strippedText.matches(expected) } return false } } } fun withStrippedText(expected: String): Matcher<View> { return object : TypeSafeMatcher<View>() { override fun describeTo(description: Description) { description.appendText("EditText matches $expected") } public override fun matchesSafely(view: View): Boolean { if (view is EditText) { val expectedHtml = Format.removeSourceEditorFormatting(expected, false) val actualHtml = Format.removeSourceEditorFormatting(view.text.toString(), false) return actualHtml == expectedHtml } return false } } } fun hasContentChanges(shouldHaveChanges: AztecText.EditorHasChanges): TypeSafeMatcher<View> { return object : TypeSafeMatcher<View>() { override fun describeTo(description: Description) { description.appendText("User has made changes to the post: $shouldHaveChanges") } public override fun matchesSafely(view: View): Boolean { if (view is SourceViewEditText) { return view.hasChanges() == shouldHaveChanges } if (view is AztecText) { return view.hasChanges() == shouldHaveChanges } return false } } } }
mpl-2.0
323dbc649829f5963af189eb97048c7a
33.347826
101
0.586076
5.486111
false
false
false
false
inorichi/tachiyomi-extensions
src/it/mangaworld/src/eu/kanade/tachiyomi/extension/it/mangaworld/Mangaworld.kt
1
12361
package eu.kanade.tachiyomi.extension.it.mangaworld import eu.kanade.tachiyomi.annotations.Nsfw 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.MangasPage 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 eu.kanade.tachiyomi.util.asJsoup import okhttp3.Headers import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.ParseException import java.text.SimpleDateFormat import java.util.Locale @Nsfw class Mangaworld : ParsedHttpSource() { override val name = "Mangaworld" override val baseUrl = "https://www.mangaworld.io" override val lang = "it" override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient override fun popularMangaRequest(page: Int): Request { return GET("$baseUrl/archive?sort=most_read&page=$page", headers) } override fun latestUpdatesRequest(page: Int): Request { return GET("$baseUrl/archive?sort=newest&page=$page", headers) } // LIST SELECTOR override fun popularMangaSelector() = "div.comics-grid .entry" override fun latestUpdatesSelector() = popularMangaSelector() override fun searchMangaSelector() = popularMangaSelector() // ELEMENT override fun popularMangaFromElement(element: Element): SManga = searchMangaFromElement(element) override fun latestUpdatesFromElement(element: Element): SManga = searchMangaFromElement(element) // NEXT SELECTOR // Not needed override fun popularMangaNextPageSelector(): String? = null override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector() override fun searchMangaNextPageSelector() = popularMangaNextPageSelector() // //////////////// override fun latestUpdatesParse(response: Response): MangasPage { val document = response.asJsoup() val mangas = document.select(popularMangaSelector()).map { element -> popularMangaFromElement(element) } // nextPage is not possible because pagination is loaded after via Javascript // 16 is the default manga-per-page. If it is less than 16 then there's no next page val hasNextPage = mangas.size == 16 return MangasPage(mangas, hasNextPage) } override fun popularMangaParse(response: Response): MangasPage { return latestUpdatesParse(response) } override fun searchMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.thumbnail_url = element.select("a.thumb img").attr("src") element.select("a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.attr("title") } return manga } override fun searchMangaParse(response: Response): MangasPage { return latestUpdatesParse(response) } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val url = "$baseUrl/archive?page=$page".toHttpUrlOrNull()!!.newBuilder() val q = query if (query.isNotEmpty()) { url.addQueryParameter("keyword", q) } else { url.addQueryParameter("keyword", "") } var orderBy = "" (if (filters.isEmpty()) getFilterList() else filters).forEach { filter -> when (filter) { is GenreList -> { val genreInclude = mutableListOf<String>() filter.state.forEach { if (it.state == 1) { genreInclude.add(it.id) } } if (genreInclude.isNotEmpty()) { genreInclude.forEach { genre -> url.addQueryParameter("genre", genre) } } } is StatusList -> { val statuses = mutableListOf<String>() filter.state.forEach { if (it.state == 1) { statuses.add(it.id) } } if (statuses.isNotEmpty()) { statuses.forEach { status -> url.addQueryParameter("status", status) } } } is MTypeList -> { val typeslist = mutableListOf<String>() filter.state.forEach { if (it.state == 1) { typeslist.add(it.id) } } if (typeslist.isNotEmpty()) { typeslist.forEach { mtype -> url.addQueryParameter("type", mtype) } } } is SortBy -> { orderBy = filter.toUriPart() url.addQueryParameter("sort", orderBy) } is TextField -> url.addQueryParameter(filter.key, filter.state) } } return GET(url.toString(), headers) } override fun mangaDetailsParse(document: Document): SManga { val infoElement = document.select("div.comic-info") val metaData = document.select("div.comic-info").first() val manga = SManga.create() manga.author = infoElement.select("a[href^=https://www.mangaworld.io/archive?author=]").first()?.text() manga.artist = infoElement.select("a[href^=https://www.mangaworld.io/archive?artist=]")?.text() val genres = mutableListOf<String>() metaData.select("div.meta-data a.badge").forEach { element -> val genre = element.text() genres.add(genre) } manga.genre = genres.joinToString(", ") manga.status = parseStatus(infoElement.select("a[href^=https://www.mangaworld.io/archive?status=]").first().attr("href")) manga.description = document.select("div#noidungm")?.text() manga.thumbnail_url = document.select(".comic-info .thumb > img").attr("src") return manga } private fun parseStatus(element: String): Int = when { element.toLowerCase().contains("ongoing") -> SManga.ONGOING element.toLowerCase().contains("completed") -> SManga.COMPLETED else -> SManga.UNKNOWN } override fun chapterListSelector() = ".chapters-wrapper .chapter" override fun chapterFromElement(element: Element): SChapter { val urlElement = element.select("a.chap").first() val chapter = SChapter.create() chapter.setUrlWithoutDomain(getUrl(urlElement)) chapter.name = urlElement.select("span.d-inline-block").first().text() chapter.date_upload = element.select(".chap-date").last()?.text()?.let { try { SimpleDateFormat("dd MMMM yyyy", Locale.ITALY).parse(it).time } catch (e: ParseException) { SimpleDateFormat("H", Locale.ITALY).parse(it).time } } ?: 0 return chapter } private fun getUrl(urlElement: Element): String { var url = urlElement.attr("href") return when { url.endsWith("?style=list") -> url else -> "$url?style=list" } } override fun prepareNewChapter(chapter: SChapter, manga: SManga) { val basic = Regex("""Capitolo\s([0-9]+)""") when { basic.containsMatchIn(chapter.name) -> { basic.find(chapter.name)?.let { chapter.chapter_number = it.groups[1]?.value!!.toFloat() } } } } override fun pageListParse(document: Document): List<Page> { val pages = mutableListOf<Page>() var i = 0 document.select("div#page img.page-image").forEach { element -> val url = element.attr("src") i++ if (url.length != 0) { pages.add(Page(i, "", url)) } } return pages } override fun imageUrlParse(document: Document) = "" override fun imageRequest(page: Page): Request { val imgHeader = Headers.Builder().apply { add("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.1.1; en-gb; Build/KLP) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30") add("Referer", baseUrl) }.build() return GET(page.imageUrl!!, imgHeader) } // private class Status : Filter.TriState("Completed") private class TextField(name: String, val key: String) : Filter.Text(name) private class SortBy : UriPartFilter( "Ordina per", arrayOf( Pair("Rilevanza", ""), Pair("Più recenti", "newest"), Pair("Meno recenti", "oldest"), Pair("A-Z", "a-z"), Pair("Z-A", "z-a"), Pair("Più letti", "most_read"), Pair("Meno letti", "less_read") ) ) private class Genre(name: String, val id: String = name) : Filter.TriState(name) private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Generi", genres) private class MType(name: String, val id: String = name) : Filter.TriState(name) private class MTypeList(types: List<MType>) : Filter.Group<MType>("Tipologia", types) private class Status(name: String, val id: String = name) : Filter.TriState(name) private class StatusList(statuses: List<Status>) : Filter.Group<Status>("Stato", statuses) override fun getFilterList() = FilterList( TextField("Anno di rilascio", "year"), SortBy(), StatusList(getStatusList()), GenreList(getGenreList()), MTypeList(getTypesList()) ) private fun getStatusList() = listOf( Status("In corso", "ongoing"), Status("Finito", "completed"), Status("Droppato", "dropped"), Status("In pausa", "paused"), Status("Cancellato", "canceled") ) private fun getTypesList() = listOf( MType("Manga", "manga"), MType("Manhua", "manhua"), MType("Manhwa", "manhwa"), MType("Oneshot", "oneshot"), MType("Thai", "thai"), MType("Vietnamita", "vietnamese") ) private fun getGenreList() = listOf( Genre("Adulti", "adulti"), Genre("Arti Marziali", "arti-marziali"), Genre("Avventura", "avventura"), Genre("Azione", "azione"), Genre("Commedia", "commedia"), Genre("Doujinshi", "doujinshi"), Genre("Drammatico", "drammatico"), Genre("Ecchi", "ecchi"), Genre("Fantasy", "fantasy"), Genre("Gender Bender", "gender-bender"), Genre("Harem", "harem"), Genre("Hentai", "hentai"), Genre("Horror", "horror"), Genre("Josei", "josei"), Genre("Lolicon", "lolicon"), Genre("Maturo", "maturo"), Genre("Mecha", "mecha"), Genre("Mistero", "mistero"), Genre("Psicologico", "psicologico"), Genre("Romantico", "romantico"), Genre("Sci-fi", "sci-fi"), Genre("Scolastico", "scolastico"), Genre("Seinen", "seinen"), Genre("Shotacon", "shotacon"), Genre("Shoujo", "shoujo"), Genre("Shoujo Ai", "shoujo-ai"), Genre("Shounen", "shounen"), Genre("Shounen Ai", "shounen-ai"), Genre("Slice of Life", "slice-of-life"), Genre("Smut", "smut"), Genre("Soprannaturale", "soprannaturale"), Genre("Sport", "sport"), Genre("Storico", "storico"), Genre("Tragico", "tragico"), Genre("Yaoi", "yaoi"), Genre("Yuri", "yuri") ) private open class UriPartFilter(displayName: String, val vals: Array<Pair<String, String>>) : Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) { fun toUriPart() = vals[state].second } }
apache-2.0
553b4f1ca11853f089033680664ee227
37.381988
153
0.578445
4.49909
false
false
false
false
y2k/JoyReactor
core/src/main/kotlin/y2k/joyreactor/services/requests/LikePostRequest.kt
1
1689
package y2k.joyreactor.services.requests import org.jsoup.nodes.Document import org.jsoup.nodes.Element import rx.Single import y2k.joyreactor.common.ajax import y2k.joyreactor.common.http.HttpClient import y2k.joyreactor.common.http.getAsync import y2k.joyreactor.model.MyLike /** * Created by y2k on 4/24/16. */ /** * http://joyreactor.cc/post_vote/add/2596695/plus?token=9448cab044c0ce6f24b4ffb7e828b9f6&abyss=0 * http://joyreactor.cc/post_vote/add/2596695/minus?token=9448cab044c0ce6f24b4ffb7e828b9f6&abyss=0 * * <span>8.2<div class="vote-plus vote-change"></div> <div class="vote-minus "></div></span> * <span>8.8<div class="vote-plus "></div> <div class="vote-minus vote-change"></div></span> */ class LikePostRequest( private val httpClient: HttpClient, private val requestToken: () -> Single<String>, private val parseLike: (Element) -> MyLike) { operator fun invoke(id: Long, like: Boolean): Single<Pair<Float, MyLike>> { return requestToken() .map { token -> createUrl(id, token, like) } .flatMap { httpClient .buildRequest() .ajax("http://joyreactor.cc/") .getAsync(it) } .map { Pair(getNewRating(it), parseLike(it.body())) } } private fun createUrl(id: Long, token: String, like: Boolean) = "http://joyreactor.cc/post_vote/add/$id/${action(like)}?token=$token&abyss=0" private fun action(like: Boolean) = if (like) "plus" else "minus" private fun getNewRating(likeResponse: Document): Float { return likeResponse.select("span").first().childNodes()[0].outerHtml().toFloat() } }
gpl-2.0
5e9c29ca93eff8e1bcafe40c051f917b
35.73913
98
0.654233
3.331361
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/filter/FilterMenuAdapter.kt
1
2655
package com.intfocus.template.dashboard.mine.adapter import android.content.Context import android.support.v4.content.ContextCompat import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.RelativeLayout import android.widget.TextView import com.intfocus.template.R import com.intfocus.template.model.response.filter.MenuItem import com.intfocus.template.util.Utils /** * Created by CANC on 2017/8/3. */ class FilterMenuAdapter(val context: Context, var menuDatas: List<MenuItem>?, var listener: FilterMenuListener) : RecyclerView.Adapter<FilterMenuAdapter.FilterMenuHolder>() { var inflater = LayoutInflater.from(context)!! fun setData(data: List<MenuItem>?) { this.menuDatas = data notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FilterMenuHolder { val contentView = inflater.inflate(R.layout.item_filter_menu, parent, false) return FilterMenuHolder(contentView) } override fun onBindViewHolder(holder: FilterMenuHolder, position: Int) { holder.contentView.setBackgroundResource(R.drawable.recycler_bg) if (menuDatas != null) { holder.rlFilter.layoutParams.width = Utils.getScreenWidth(context) / 4 holder.tvFilterName.text = menuDatas!![position].category holder.tvFilterName.text = menuDatas!![position].category if (menuDatas!![position].arrorDirection) { holder.ivArrow.setImageResource(R.drawable.ic_arrow_up) holder.tvFilterName.setTextColor(ContextCompat.getColor(context, R.color.co1_syr)) } else { holder.ivArrow.setImageResource(R.drawable.ic_arrow_down) holder.tvFilterName.setTextColor(ContextCompat.getColor(context, R.color.co3_syr)) } holder.rlFilter.setOnClickListener { listener.itemClick(position) } } } override fun getItemCount(): Int { return if (menuDatas == null) 0 else menuDatas!!.size } class FilterMenuHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var contentView = itemView var rlFilter = itemView.findViewById<RelativeLayout>(R.id.rl_filter) var tvFilterName = itemView.findViewById<TextView>(R.id.tv_filter_name) var ivArrow = itemView.findViewById<ImageView>(R.id.iv_arrow) } interface FilterMenuListener { fun itemClick(position: Int) } }
gpl-3.0
1a219748004936fa7e5ca0bff840392c
38.626866
120
0.692655
4.395695
false
false
false
false
campos20/tnoodle
webscrambles/src/main/kotlin/org/worldcubeassociation/tnoodle/server/webscrambles/wcif/model/RegistrationStatus.kt
1
892
package org.worldcubeassociation.tnoodle.server.webscrambles.wcif.model import org.worldcubeassociation.tnoodle.server.serial.SingletonStringEncoder import org.worldcubeassociation.tnoodle.server.webscrambles.exceptions.BadWcifParameterException enum class RegistrationStatus(val wcaString: String) { ACCEPTED("accepted"), PENDING("pending"), DELETED("deleted"); companion object : SingletonStringEncoder<RegistrationStatus>("RegistrationStatus") { fun fromWCAString(wcaString: String) = values().find { it.wcaString == wcaString } override fun encodeInstance(instance: RegistrationStatus) = instance.wcaString override fun makeInstance(deserialized: String) = fromWCAString(deserialized) ?: BadWcifParameterException.error("Unknown WCIF spec RegistrationStatus: '$deserialized'. Valid types: ${values().map { it.wcaString }}") } }
gpl-3.0
83ba07c1153dabec9615f31e398fc054
48.555556
150
0.767937
4.744681
false
false
false
false
PublicXiaoWu/XiaoWuMySelf
app/src/main/java/com/xiaowu/myself/utils/ImageUtils.kt
1
3755
package com.xiaowu.myself.utils import android.content.Context import android.content.res.Resources import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.drawable.BitmapDrawable import android.support.v4.content.ContextCompat import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream /** * Created by xiaowumac on 2017/9/12. */ object ImageUtils { fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int { // 源图片的高度和宽度 val height = options.outHeight val width = options.outWidth var inSampleSize = 1 if (height > reqHeight || width > reqWidth) { // 计算出实际宽高和目标宽高的比率 val heightRatio = Math.round(height.toFloat() / reqHeight.toFloat()) val widthRatio = Math.round(width.toFloat() / reqWidth.toFloat()) // 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高 // 一定都会大于等于目标的宽和高。 inSampleSize = if (heightRatio > widthRatio) heightRatio else widthRatio } return inSampleSize } fun decodeSampledBitmapFromResource(res: Resources, resId: Int, reqWidth: Int, reqHeight: Int): Bitmap { // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小 val options = BitmapFactory.Options() options.inJustDecodeBounds = true BitmapFactory.decodeResource(res, resId, options) // 调用上面定义的方法计算inSampleSize值 options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight) // 使用获取到的inSampleSize值再次解析图片 options.inJustDecodeBounds = false return BitmapFactory.decodeResource(res, resId, options) } fun getBitmapByResource(context: Context, resId: Int): Bitmap { val drawable = ContextCompat.getDrawable(context, resId) val bd = drawable as BitmapDrawable return bd.bitmap } fun decodeSampledBitmapFromPath(path: String, reqWidth: Int, reqHeight: Int): Bitmap { // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小 val options = BitmapFactory.Options() options.inJustDecodeBounds = true BitmapFactory.decodeFile(path, options) // 调用上面定义的方法计算inSampleSize值 options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight) // 使用获取到的inSampleSize值再次解析图片 options.inJustDecodeBounds = false return BitmapFactory.decodeFile(path, options) } /** * @param image * @param percent 压缩百分比 * @return * @方法说明:质量压缩方法 * @方法名称:compressImage * @返回值:Bitmap */ fun compressImage(image: Bitmap, percent: Int): Bitmap { val baos = ByteArrayOutputStream() image.compress(Bitmap.CompressFormat.JPEG, percent, baos)// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 var options = 60 while (baos.toByteArray().size / 1024 > 80) { // 循环判断如果压缩后图片是否大于80kb,大于继续压缩 baos.reset()// 重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, options, baos)// 这里压缩options%,把压缩后的数据存放到baos中 options -= 10// 每次都减少10 } val isBm = ByteArrayInputStream(baos.toByteArray())// 把压缩后的数据baos存放到ByteArrayInputStream中 return BitmapFactory.decodeStream(isBm, null, null) } }
apache-2.0
98bcb145b6c7aca6853cdfd3dc116095
37.082353
108
0.686747
4.04625
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/lesson/ui/delegate/LessonInfoTooltipDelegate.kt
2
5523
package org.stepik.android.view.lesson.ui.delegate import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.widget.LinearLayout import android.widget.PopupWindow import androidx.annotation.DrawableRes import androidx.annotation.PluralsRes import androidx.annotation.StringRes import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.widget.AppCompatTextView import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.DrawableCompat import androidx.core.view.doOnPreDraw import androidx.core.widget.PopupWindowCompat import kotlinx.android.synthetic.main.tooltip_lesson_info.view.* import org.stepic.droid.R import org.stepik.android.view.progress.ui.mapper.ProgressTextMapper class LessonInfoTooltipDelegate( private val view: View ) { fun showLessonInfoTooltip( stepScore: Float, stepCost: Long, lessonTimeToCompleteInSeconds: Long, certificateThreshold: Long, isExam: Boolean ) { val anchorView = view .findViewById<View>(R.id.lesson_menu_item_info) ?: return val popupView = LayoutInflater .from(anchorView.context) .inflate(R.layout.tooltip_lesson_info, null) if (stepScore > 0f) { popupView .stepWorth .setItem(stepScore, stepCost, R.string.lesson_info_points_with_score, R.string.lesson_info_points_with_score_fraction, R.plurals.points, R.drawable.ic_check_rounded) } else { if (isExam) { popupView .stepWorth .setItem(R.string.lesson_info_is_exam, R.drawable.ic_check_rounded) } else { popupView .stepWorth .setItem(stepCost, R.string.lesson_info_points, R.plurals.points, R.drawable.ic_check_rounded) } } val (timeValue, @PluralsRes timeUnitPlural) = if (lessonTimeToCompleteInSeconds in 0 until 3600) { lessonTimeToCompleteInSeconds / 60 to R.plurals.minutes } else { lessonTimeToCompleteInSeconds / 3600 to R.plurals.hours } popupView .lessonTimeToComplete .setItem(timeValue, R.string.lesson_info_time_to_complete, timeUnitPlural, R.drawable.ic_duration) popupView .certificateThreshold .setItem(certificateThreshold, R.string.lesson_info_certificate_threshold, R.plurals.points, R.drawable.ic_lesson_info) val popupWindow = PopupWindow(popupView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT) popupWindow.animationStyle = R.style.PopupAnimations popupWindow.isOutsideTouchable = true popupWindow.setBackgroundDrawable(ColorDrawable()) // workaround to make isOutsideTouchable work on Android 4 popupView.setOnClickListener { popupWindow.dismiss() } popupView.doOnPreDraw { popupView.arrowView?.x = calcArrowHorizontalOffset(anchorView, popupView, popupView.arrowView) } anchorView.post { if (anchorView.windowToken != null) { PopupWindowCompat.showAsDropDown(popupWindow, anchorView, 0, 0, Gravity.CENTER) } } } private fun AppCompatTextView.setItem(@StringRes stringRes: Int, @DrawableRes drawableRes: Int) { setItemDrawable(drawableRes) text = context.getString(stringRes) visibility = View.VISIBLE } private fun AppCompatTextView.setItem( value: Long, @StringRes stringRes: Int, @PluralsRes pluralRes: Int, @DrawableRes drawableRes: Int ) { if (value > 0) { setItemDrawable(drawableRes) text = context.getString(stringRes, resources.getQuantityString(pluralRes, value.toInt(), value)) visibility = View.VISIBLE } else { visibility = View.GONE } } // 'StepProgress.score' points out of 'StepProgress.cost' (for step) private fun AppCompatTextView.setItem( stepScore: Float, stepCost: Long, @StringRes stringRes: Int, @StringRes fractionRes: Int, @PluralsRes pluralRes: Int, @DrawableRes drawableRes: Int ) { setItemDrawable(drawableRes) text = ProgressTextMapper.mapProgressToText(context, stepScore, stepCost, stringRes, fractionRes, pluralRes) visibility = View.VISIBLE } private fun AppCompatTextView.setItemDrawable(@DrawableRes drawableRes: Int) { val iconDrawable = AppCompatResources .getDrawable(context, drawableRes) ?.let(DrawableCompat::wrap) ?.let(Drawable::mutate) ?: return DrawableCompat.setTint(iconDrawable, ContextCompat.getColor(context, android.R.color.white)) setCompoundDrawablesWithIntrinsicBounds(iconDrawable, null, null, null) } private fun calcArrowHorizontalOffset(anchorView: View, popupView: View, arrowView: View): Float { val pos = IntArray(2) anchorView.getLocationOnScreen(pos) val anchorOffset = pos[0] + anchorView.measuredWidth / 2 popupView.getLocationOnScreen(pos) return anchorOffset.toFloat() - pos[0] - arrowView.measuredWidth / 2 } }
apache-2.0
4d54a6636eab14af4081b3fa047feb81
37.096552
181
0.66721
4.716482
false
false
false
false
Commit451/GitLabAndroid
app/src/main/java/com/commit451/gitlab/adapter/LabelAdapter.kt
2
2216
package com.commit451.gitlab.adapter import androidx.recyclerview.widget.RecyclerView import android.view.ViewGroup import com.commit451.gitlab.R import com.commit451.gitlab.model.api.Label import com.commit451.gitlab.viewHolder.LabelViewHolder import com.commit451.gitlab.viewHolder.ProjectMemberFooterViewHolder import java.util.* /** * Shows a bunch of labels */ class LabelAdapter(private val listener: Listener) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { companion object { private const val TYPE_ITEM = 0 } private val items: ArrayList<Label> = ArrayList() fun getItem(position: Int): Label { return items[position] } fun setItems(data: Collection<Label>?) { items.clear() if (data != null) { items.addAll(data) } notifyDataSetChanged() } fun addLabel(label: Label) { items.add(0, label) notifyItemInserted(0) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { when (viewType) { TYPE_ITEM -> { val holder = LabelViewHolder.inflate(parent) holder.itemView.setOnClickListener { v -> val position = v.getTag(R.id.list_position) as Int listener.onLabelClicked(getItem(position), holder) } return holder } } throw IllegalStateException("No idea what to inflate with view type of $viewType") } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder is ProjectMemberFooterViewHolder) { // } else if (holder is LabelViewHolder) { val label = getItem(position) holder.bind(label) holder.itemView.setTag(R.id.list_position, position) holder.itemView.setTag(R.id.list_view_holder, holder) } } override fun getItemCount(): Int { return items.size } override fun getItemViewType(position: Int): Int { return TYPE_ITEM } interface Listener { fun onLabelClicked(label: Label, viewHolder: LabelViewHolder) } }
apache-2.0
4a627ed4b338a454d6106b8227d579c6
28.157895
102
0.633123
4.607069
false
false
false
false
MrSugarCaney/DirtyArrows
src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/RoundBow.kt
1
2647
package nl.sugcube.dirtyarrows.bow.ability import nl.sugcube.dirtyarrows.DirtyArrows import nl.sugcube.dirtyarrows.bow.BowAbility import nl.sugcube.dirtyarrows.bow.DefaultBow import nl.sugcube.dirtyarrows.util.applyBowEnchantments import nl.sugcube.dirtyarrows.util.copyOf import nl.sugcube.dirtyarrows.util.rotateAlongYAxis import org.bukkit.GameMode import org.bukkit.Material import org.bukkit.enchantments.Enchantment import org.bukkit.entity.Arrow import org.bukkit.entity.Player import org.bukkit.event.entity.ProjectileLaunchEvent import org.bukkit.inventory.ItemStack import kotlin.math.PI /** * Shoots 30 arrows around the player. * * @author SugarCaney */ open class RoundBow(plugin: DirtyArrows) : BowAbility( plugin = plugin, type = DefaultBow.ROUND, canShootInProtectedRegions = true, removeArrow = false, description = "Shoots arrows all around you." ) { /** * The amount of arrows that get fired. */ val arrowCount = config.getInt("$node.arrow-count") init { check(arrowCount >= 0) { "$node.arrow-count cannot be negative, got <$arrowCount>" } } override fun launch(player: Player, arrow: Arrow, event: ProjectileLaunchEvent) { // First arrow is already shot by default. repeat(arrowCount - 1) { if (player.checkHasArrow().not()) return val initialDirection = arrow.velocity.copyOf().normalize() val angle = 2.0 * PI * (it + 1.0) / arrowCount.toDouble() val direction = initialDirection.rotateAlongYAxis(angle) val initialVelocity = direction.multiply(arrow.velocity.length()) player.world.spawn(arrow.location, Arrow::class.java).apply { shooter = player velocity = initialVelocity applyBowEnchantments(player.bowItem()) if (player.gameMode == GameMode.CREATIVE) { pickupStatus = Arrow.PickupStatus.CREATIVE_ONLY } } } unregisterArrow(arrow) } /** * Checks if the player has an arrow available, and removes it if it is. * * @return `true` if there is an arrow available, `false` if not. */ private fun Player.checkHasArrow(): Boolean { if (gameMode == GameMode.CREATIVE) return true val bow = bowItem() ?: return false if (bow.containsEnchantment(Enchantment.ARROW_INFINITE)) return true if (inventory.contains(Material.ARROW, 1)) { inventory.removeItem(ItemStack(Material.ARROW, 1)) return true } return false } }
gpl-3.0
9d58f9bf654107c95b9f5edac2e6c235
32.1
92
0.656592
4.411667
false
false
false
false
DevJake/SaltBot-2.0
src/test/kotlin/me/salt/entities/cmd/CommandListenerTest.kt
1
4524
/* * Copyright 2017 DevJake * * 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 me.salt.entities.cmd import com.winterbe.expekt.should import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.context import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import org.junit.Assert class CommandListenerTest : Spek({ var listener = CommandListener() val cmdP0A0 = CommandBuilder("0", "").build() val cmdP0A1 = CommandBuilder("0", "").addAliases("2").build() val cmdP0A2 = CommandBuilder("0", "").addAliases("2", "3").build() val cmdP1A0 = CommandBuilder("1", "").build() val cmdP1A1 = CommandBuilder("1", "").addAliases("2").build() val cmdP1A2 = CommandBuilder("1", "").addAliases("2", "3").build() //Test using prefix "1" and aliases "2 3" beforeEachTest { listener = CommandListener() } context("filterByCommandPrefix") { on("filtering a list of commands where one contains our prefix") { val result = listOf(cmdP0A0, cmdP1A0, cmdP0A0).filterByCommandPrefix("1", false) it("should return a list with size 1") { result.size.should.equal(1) } it("should contain our expected command") { result.first().should.equal(cmdP1A0) } } on("filtering a list of commands where multiple contains our prefix") { val result = listOf(cmdP0A0, cmdP1A0, cmdP1A0).filterByCommandPrefix("1", false) it("should return a list with size 2") { result.size.should.equal(2) } it("should contain our expected command") { Assert.assertTrue(result[0] == cmdP1A0 && result[1] == cmdP1A0) } } on("filtering a list of commands where none contains our prefix") { val result = listOf(cmdP0A0, cmdP1A0, cmdP1A0).filterByCommandPrefix("2", false) it("should return a list with size 0") { result.size.should.equal(0) } } on("filtering a list of commands where one contains our prefix in the aliases") { val result = listOf(cmdP0A0, cmdP1A0, cmdP0A1).filterByCommandPrefix("2", true) it("should return a list with size 1") { result.size.should.equal(1) } it("should contain our expected command") { result.first().should.equal(cmdP0A1) } } on("filtering a list of commands where multiple contains our prefix in the aliases") { val result = listOf(cmdP0A0, cmdP0A1, cmdP0A2).filterByCommandPrefix("2", true) it("should return a list with size 2") { result.size.should.equal(2) } it("should contain our expected command") { Assert.assertTrue(result[0] == cmdP0A1 && result[1] == cmdP0A2) } } on("filtering a list of commands where none contains our prefix in the aliases") { val result = listOf(cmdP0A0, cmdP0A1, cmdP0A1).filterByCommandPrefix("3", true) it("should return a list with size 0") { result.size.should.equal(0) } } on("filtering a list of commands where none contains our prefix in the aliases and the prefix") { val result = listOf(cmdP0A0, cmdP0A1, cmdP0A0).filterByCommandPrefix("3", true) it("should return a list with size 0") { result.size.should.equal(0) } } on("filtering a list of commands where checkAliases false and the aliases contains our prefix") { val result = listOf(cmdP1A1, cmdP1A1, cmdP1A1).filterByCommandPrefix("2", false) it("should return a list with size 2") { result.size.should.equal(0) } } } })
apache-2.0
34a8db55fa75765b5552e53b87956448
38.053097
105
0.595049
4.00354
false
false
false
false
TeamMeanMachine/meanlib
src/main/kotlin/org/team2471/frc/lib/framework/Events.kt
1
2117
package org.team2471.frc.lib.framework import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.launch import org.team2471.frc.lib.coroutines.MeanlibDispatcher object Events { private val functions = hashSetOf<() -> Unit>() @Synchronized internal fun process() = functions.forEach { it() } @Synchronized fun whenActive(condition: () -> Boolean, action: suspend () -> Unit) { var prevState = false var job: Job? = null functions.add { val state = condition() if (state && !prevState) { val prevJob = job job = GlobalScope.launch(MeanlibDispatcher) { prevJob?.cancelAndJoin() action() } } prevState = state } } @Synchronized fun whileActive(condition: () -> Boolean, action: suspend () -> Unit) { var prevState = false var job: Job? = null functions.add { val state = condition() if (state && !prevState) { val prevJob = job job = GlobalScope.launch(MeanlibDispatcher) { prevJob?.cancelAndJoin() action() } } else if (!state && prevState) { job?.cancel() } prevState = state } } @Synchronized fun toggleWhenActive(condition: () -> Boolean, action: suspend () -> Unit) { var prevState = false var job: Job? = null functions.add { val state = condition() val prevJob = job if (state && !prevState) { if (prevJob != null && prevJob.isActive) { job!!.cancel() } else { job = GlobalScope.launch(MeanlibDispatcher) { prevJob?.join() action() } } } prevState = state } } }
unlicense
0ac09241c1cc9538e92c29d3fc1859dc
24.829268
80
0.489844
5.113527
false
false
false
false
just-4-fun/holomorph
src/main/kotlin/just4fun/holomorph/types/schema.kt
1
13022
package just4fun.holomorph.types import just4fun.holomorph.* import just4fun.kotlinkit.Result import just4fun.holomorph.forms.SchemaConsumerN import just4fun.holomorph.forms.SchemaConsumerV import just4fun.holomorph.forms.SchemaFactory import just4fun.holomorph.forms.SchemaProvider import kotlin.reflect.* import just4fun.holomorph.Property.Companion.visibilityBound import just4fun.holomorph.PropertyVisibility.PRIVATE import kotlin.reflect.full.* /** Represents the schema of the underlying [typeKlas]. Responsible for selecting a constructor and serializable properties of the [typeKlas]. Provides production and utility methods for objects of type [T]. * [See this guide for details.](https://just-4-fun.github.io/holomorph/#tuning-the-schema) * @constructor Creates the schema of the class [typeKlas] with optional [argTypes], [propsNames] and [nameless] parameters. */ class SchemaType<T: Any>(override val typeKlas: KClass<T>, argTypes: Array<out Type<*>>? = null, propsNames: Array<String>? = null, nameless: Boolean = false, useAccessors: Boolean = true): Type<T>, Producer<T>, EntryHelperDefault<T> { /** The list of serializable properties of the [typeKlas] */ val properties: List<Property<Any>> = mutableListOf() /** The map of serializable properties of the [typeKlas] with their names as the key.*/ val propertiesMap: Map<String, Property<*>> = mutableMapOf() private var params: List<Param>? = null internal var paramsMap: MutableMap<String, Param>? = null internal var allSize = 0 internal var paramsSize = 0 private lateinit var constructor: KFunction<T> internal val emptyConstr get() = paramsSize == 0 /** Indicates the serialization mode. Can be set explicitly. Otherwise is set to true only if ordinal indexes of properties are positive and distinct. */ var nameless = nameless; private set(v) = run { field = v } /** Optimization param indicating class properties have accessors, otherwise properties are accessed via Java field which is 2-3 times faster.*/ var useAccessors = useAccessors; private set(v) = run { field = v } /** The [ProduceFactory] can be used with [Producer] methods and other which require [EntryProviderFactory] and [EntryConsumerFactory] as parameters. */ val produceFactory by lazy { SchemaFactory(this) } private val listType by lazy { Types.getOrAddType(MutableList::class, this) { ListType(this) } } init { try { if (argTypes == null) { Types.setType(typeKlas) { this } init(propsNames, null) } else { Types.setType(typeKlas, argTypes) { this } init(propsNames, Types.typeArgTypes(typeKlas, argTypes)) } } catch (x: Throwable) { Types.removeType(this) throw x } } @Suppress("UNCHECKED_CAST") private fun init(propsNames: Array<String>?, typeArgs: Map<String, Type<*>>?) { if (typeKlas.isInner) throw Exception("Failed to schemify $typeKlas since it is inner.") // val props = properties as MutableList<PropImpl<Any>> val propsMap = propertiesMap as MutableMap<String, PropImpl<*>> fun <T: Any> addRealProp(kProp: KProperty1<*, *>, index: Int, name: String, nullable: Boolean, type: Type<T>, rType: KType) { val prop = PropImpl(index, name, type, this, nullable) as PropImpl<Any> prop.rType = rType prop.initAccessors(kProp) props.add(prop) propsMap[name] = prop } fun initProps(visibility: Int) { var annotated = false var maxIndex = -1 for (kProp in typeKlas.memberProperties) { var pAnn: Opt? = null var sAnn: DefineSchema? = null var tAnn: DefineType? = null var iAnn: Intercept? = null kProp.annotations.forEach { if (it is Opt) pAnn = it if (it is Intercept) iAnn = it if (it is DefineSchema) sAnn = it else if (it is DefineType) tAnn = it } if (pAnn == null && (annotated || kProp.visibility.let { it == null || it.ordinal > visibility })) continue val rType = kProp.returnType // println("Discovering prop '${kProp.typeName}': ${rType}; tp? ${rType.classifier is KTypeParameter}") val klas = rType.classifier val type0 = if (klas is KClass<*>) Types.resolve(rType, klas, typeArgs, tAnn?.typeKlas, sAnn?.properties, sAnn?.nameless == true, sAnn?.useAccessors == true) else if (typeArgs != null && klas is KTypeParameter) typeArgs[klas.name] else null if (type0 == null) throw Exception("Failed detecting the Type of ${kProp.name}: $rType of $typeKlas ")// TODO specific val type = iAnn?.let { val icpr = it.interceptorKlas.createInstance() as? ValueInterceptor<*> ?: throw Exception("Failed creating the ${ValueInterceptor::class.simpleName} of '${kProp.name}' of $typeKlas from ${it.interceptorKlas}")// TODO specific InterceptorType(type0 as Type<Any>, icpr as ValueInterceptor<Any>) } ?: type0 val index = pAnn?.let { if (!annotated) run { props.clear(); annotated = true } if (it.ordinal > maxIndex) maxIndex = it.ordinal it.ordinal } ?: props.size // addRealProp(kProp, index, kProp.name, rType.isMarkedNullable, type, rType) } // check order if (maxIndex > -1) { if (maxIndex == props.size - 1) { props.sortBy { it.ordinal } nameless = props.all { it.ordinal == ++maxIndex - props.size } } else if (maxIndex >= props.size) { val array = arrayOfNulls<Property<*>>(maxIndex + 1) nameless = props.all { if (array[it.ordinal] == null) run { array[it.ordinal] = it; true } else false } if (nameless) array.forEachIndexed { ix, p -> val prop = (p ?: PropImpl(ix, "", UnitType, this, true)) as PropImpl<Any> if (ix < props.size) props[ix] = prop else props.add(prop) } } if (!nameless) { (props as List<PropImpl<*>>).forEachIndexed { ix, p -> p.ordinal = ix } System.err.println("Properties order of $typeKlas is inconsistent. To be nameless properties should be annotated with '@${Opt::class.simpleName}' and ordinal should be explicitly set, zero-based and distinct.") } } } fun initTargetProps(propNames: Array<String>) { for (name in propNames) { val kProp = typeKlas.memberProperties.find { it.name == name } ?: throw Exception("Property [$name] isn't found within $typeKlas. ")// TODO specific val rType = kProp.returnType val type = Types.resolve(rType, rType.classifier as KClass<*>) ?: throw Exception("Failed detecting the Type of $typeKlas.${kProp.name}: $rType ")// TODO specific addRealProp(kProp, props.size, name, rType.isMarkedNullable, type, rType) } } fun initConstructor() { // find most appropriate constructor var minPmsConstr: KFunction<T>? = null// min num of params var maxMatchConstr: KFunction<T>? = null// max matches with props var lastSize = 0 var maxMatch = -1 var minPms = 10000 for (constr in typeKlas.constructors) { if (constr.findAnnotation<Opt>() != null) { minPmsConstr = constr; maxMatchConstr = constr; break } val size = constr.parameters.size var count = 0 constr.parameters.forEach { if (propsMap[it.name]?.rType == it.type) count++ } if (maxMatch < count || (maxMatch == count && lastSize > size)) run { maxMatch = count; lastSize = size; maxMatchConstr = constr } if (size < minPms) run { minPms = size; minPmsConstr = constr } // println("SELECTING... maxMatch=$maxMatch; minPms= $minPms; actualPms= ${constr.parameters.size}") } //prefer one with max matches OR if no matches prefer one with min num of params val constr = (if (maxMatch == 0) minPmsConstr else maxMatchConstr) ?: throw Exception("$typeKlas has no constructor.") constructor = constr if (constr.parameters.isEmpty()) return val prmMap = mutableMapOf<String, Param>() val prms = constr.parameters.map { val prop = propsMap[it.name] val type = if (prop?.rType == it.type) prop.type else Types.resolve(it.type, it.type.classifier as KClass<*>) ?: throw Exception("Failed detecting the Type of $typeKlas constructor parameter '${it.name}: ${it.type} ")// TODO specific val param = Param(it.index, it.name!!, type, it.isOptional, it.type.isMarkedNullable) prmMap[param.name] = param param } paramsSize = prms.size params = prms paramsMap = prmMap } // println("Schemifying: ${typeKlas}; ${typeKlas.typeParameters.map { "${it.typeName}: ${it.upperBounds}" }}; typeMap: $typeArgsMap") val names = typeKlas.findAnnotation<DefineSchema>()?.let { useAccessors = it.useAccessors nameless = it.nameless; it.properties } ?: propsNames // process properties if (names == null) initProps(visibilityBound.ordinal) else if (names.isEmpty()) initProps(PRIVATE.ordinal) else initTargetProps(names) allSize += props.size if (props.size == 0) throw Exception("Failed detecting any public or annotated with '@${Opt::class.simpleName}' property in $typeKlas.")// TODO specific // println("$this properties: $properties") // process constructor initConstructor()// TODO optimize . consumes 65% if (params != null) allSize += paramsSize // println("$this params: $params") props.forEach { it.rType = null } } override fun newInstance(): T = if (paramsSize == 0) typeKlas.java.newInstance() else newInstance(Array(allSize) {}) internal fun newInstance(values: Array<Any?>): T { val params = this.params!! val constrVals = values.copyOf(paramsSize) constrVals.forEachIndexed { ix, v -> if (v == Unit || v == null) constrVals[ix] = params[ix].default// TODO can throw here } // val obj = constructor.javaConstructor!!.newInstance(*constrVals) val obj = constructor.call(*constrVals) for (n in paramsSize until allSize) { val v = values[n] if (v != Unit) properties[n - paramsSize].setChecked(obj, v) } return obj } fun <D: Any> instanceUpdateFrom(inst: T, input: D, factory: EntryProviderFactory<D>): Result<T> = Produce(factory(input), SchemaConsumerN(this, instance = inst)) override fun <D: Any> instanceFrom(input: D, factory: EntryProviderFactory<D>): Result<T> = Produce(factory(input), if (paramsSize == 0) SchemaConsumerN(this) else SchemaConsumerV(this)) override fun <D: Any> instanceTo(input: T, factory: EntryConsumerFactory<D>): Result<D> = Produce(SchemaProvider(input, this), factory()) fun <D: Any> instanceTo(input: T, factory: EntryConsumerFactory<D>, props: List<Property<*>>?, nameless: Boolean? = null): Result<D> = Produce(SchemaProvider(input, this, props, nameless), factory()) fun <D: Any> instancesFrom(input: D, factory: EntryProviderFactory<D>): Result<MutableList<T>> = listType.instanceFrom(input, factory) fun <D: Any> instancesTo(input: List<T>, factory: EntryConsumerFactory<D>): Result<D> = listType.instanceTo(input as MutableList<T>, factory) override fun fromEntries(subEntries: EnclosedEntries, expectNames: Boolean) = subEntries.intercept(if (paramsSize == 0) SchemaConsumerN(this, false) else SchemaConsumerV(this, false)) override fun toEntry(value: T, name: String?, entryBuilder: EntryBuilder): Entry { val named = entryBuilder.context.nameless == false || (entryBuilder.context.nameless == null && !nameless) return entryBuilder.StartEntry(name, named, SchemaProvider(value, this, null, null, false)) } override fun isInstance(v: Any): Boolean { return super.isInstance(v) || typeKlas.java.isAssignableFrom(v.javaClass) } override fun toString(v: T?, sequenceSizeLimit: Int): String { if (v == null) return "{}" val text = StringBuilder("{") val propsSize = properties.size properties.forEachIndexed { ix, p -> val value = p.type.toString(p[v], sequenceSizeLimit) text.append("${p.name}=").append("$value") if (ix < propsSize - 1) text.append(", ") } text.append("}") return text.toString() } private fun equalProps(v1: T, v2: T): Boolean = properties.all { p -> val r = p.type.equal(p[v1], p[v2]) //todo for test // if (!r) println("NonEQ: ${typeKlas.simpleName}.${p.typeName}; PType= ${p.type}; V1:${p[v1]?.javaClass?.typeName}= ${p.type.toString(p[v1])}; V2:${p[v2]?.javaClass?.typeName}= ${p.type.toString(p[v2])}") r } override fun equal(v1: T?, v2: T?): Boolean = v1 === v2 || (v1 != null && v2 != null && equalProps(v1, v2)) override fun copy(v: T?, deep: Boolean): T? = if (v == null) null else { @Suppress("UNCHECKED_CAST") if (paramsSize == 0) newInstance().also { for (p in properties) p.setChecked(it, if (deep) p.type.copy(p[v], true) else p[v]) } else { val values = Array<Any?>(allSize) {} val params = paramsMap!! for (p in properties) { val value = if (deep) p.type.copy(p[v], true) else p[v] values[params[p.name]?.run { index } ?: (paramsSize + p.ordinal)] = value } newInstance(values) } } override fun hashCode(v: T): Int { var code = 1 properties.forEach { p -> val pv = p[v] code = code * 31 + if (pv == null) 0 else p.type.hashCode(pv) } return code } override fun toString() = typeName override fun hashCode(): Int = typeKlas.hashCode() override fun equals(other: Any?) = this === other || (other is SchemaType<*> && typeKlas == other.typeKlas) }
apache-2.0
630f193a6038c185e72ad46fad408442
47.954887
237
0.690063
3.400888
false
false
false
false
duncte123/SkyBot
src/main/kotlin/ml/duncte123/skybot/commands/music/QueueCommand.kt
1
3058
/* * Skybot, a multipurpose discord bot * Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32" * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ml.duncte123.skybot.commands.music import com.sedmelluq.discord.lavaplayer.track.AudioTrack import me.duncte123.botcommons.messaging.EmbedUtils import me.duncte123.botcommons.messaging.MessageUtils.sendEmbed import ml.duncte123.skybot.objects.command.CommandContext import ml.duncte123.skybot.objects.command.MusicCommand import ml.duncte123.skybot.utils.AudioUtils.getTimestamp import org.apache.commons.lang3.StringUtils import java.util.* import kotlin.math.min class QueueCommand : MusicCommand() { init { this.name = "list" this.aliases = arrayOf("queue", "q") this.help = "Shows the current queue" } override fun run(ctx: CommandContext) { val event = ctx.event val mng = ctx.audioUtils.getMusicManager(event.guild) val scheduler = mng.scheduler val queue: Queue<AudioTrack> = scheduler.queue val playingTrack = mng.player.playingTrack synchronized(queue) { val playing = if (playingTrack == null) "Nothing" else "${playingTrack.info.title} by ${playingTrack.info.author}" val current = "**Currently playing:** $playing" if (queue.isEmpty()) { sendEmbed(ctx, EmbedUtils.embedMessage("$current\n**Queue:** Empty")) } else { val queueLength = queue.sumOf { it.duration } val maxTracks = 10 val queueText = buildString { appendLine(current) appendLine("**Queue:** Showing **${min(maxTracks, queue.size)}**/**${queue.size}** tracks") for ((index, track) in queue.withIndex()) { if (index == maxTracks) { break } appendLine(StringUtils.abbreviate("`[${getTimestamp(track.duration)}]` ${track.info.title}", 60)) } appendLine("Total Queue Time Length: ${getTimestamp(queueLength)}") appendLine("Hint: Use `${ctx.prefix}save` to save the current queue to a file that you can re-import") } sendEmbed(ctx, EmbedUtils.embedMessage(queueText)) } } } }
agpl-3.0
3ff3b1fce20e81ae23de513385f213a9
39.773333
126
0.636037
4.47076
false
false
false
false
DankBots/GN4R
src/main/java/com/gmail/hexragon/gn4rBot/command/general/RemindMeCommand.kt
1
2655
package com.gmail.hexragon.gn4rBot.command.general import com.gmail.hexragon.gn4rBot.GnarBot import com.gmail.hexragon.gn4rBot.managers.commands.CommandExecutor import com.gmail.hexragon.gn4rBot.managers.commands.annotations.Command import com.gmail.hexragon.gn4rBot.managers.directMessage.PMCommandManager import com.gmail.hexragon.gn4rBot.managers.guildMessage.GuildCommandManager import com.gmail.hexragon.gn4rBot.util.GnarMessage import com.gmail.hexragon.gn4rBot.util.GnarQuotes import java.util.concurrent.TimeUnit @Command(aliases = arrayOf("remindme", "remind"), usage = "(#) (unit) (msg)") class RemindMeCommand : CommandExecutor() { override fun execute(message : GnarMessage?, args : Array<out String>?) { if (args!!.size >= 3) { val string = args.copyOfRange(2, args.size).joinToString(" ") val time = try { args[0].toInt() } catch (e : NumberFormatException) { message?.reply("The time number was not an integer.") return } val timeUnit = try { TimeUnit.valueOf(args[1].toUpperCase()) } catch (e : IllegalArgumentException) { message?.reply("The specified time unit was invalid.") return } if (time > 0) { message?.reply("**${GnarQuotes.getRandomQuote()}** I'll be reminding you in __$time ${timeUnit.toString().toLowerCase()}__.") if (commandManager.javaClass == GuildCommandManager::class.java) GnarBot.scheduler.schedule({ message?.author?.privateChannel?.sendMessage("**REMINDER:** You requested to be reminded about this __$time ${timeUnit.toString().toLowerCase()}__ ago on the server **__${guild.name}__**:\n```\n$string```") }, time.toLong(), timeUnit) else if (commandManager.javaClass == PMCommandManager::class.java) GnarBot.scheduler.schedule({ message?.author?.privateChannel?.sendMessage("**REMINDER:** You requested to be reminded about this __$time ${timeUnit.toString().toLowerCase()}__ ago:\n```\n$string```") }, time.toLong(), timeUnit) } else { message?.reply("Number must be more than 0.") } } else { message?.reply("Insufficient amount of arguments.") } } }
mit
56c1b2734481f36bbc1020f2d1b7857d
39.861538
230
0.561959
4.585492
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/model/CloseableInfoHolder.kt
1
1528
package forpdateam.ru.forpda.model import android.content.SharedPreferences import com.jakewharton.rxrelay2.BehaviorRelay import forpdateam.ru.forpda.entity.app.CloseableInfo import io.reactivex.Observable class CloseableInfoHolder( private val preferences: SharedPreferences, private val schedulers: SchedulersProvider ) { companion object { const val item_other_menu_drag = 10 const val item_notes_sync = 11 val ALL_ITEMS = arrayOf( item_other_menu_drag, item_notes_sync ) } private val relay = BehaviorRelay.create<List<CloseableInfo>>() init { val closedIds: List<Int> = preferences.getString("closeable_info_closed_ids", null)?.let { savedIds -> savedIds.split(',').map { it.toInt() } } ?: emptyList() val allItems = ALL_ITEMS.map { CloseableInfo(it, closedIds.contains(it)) } relay.accept(allItems) } fun observe(): Observable<List<CloseableInfo>> = relay .subscribeOn(schedulers.io()) .observeOn(schedulers.ui()); fun get(): List<CloseableInfo> = relay.value!! fun close(item: CloseableInfo) { val currentItems = get() currentItems.firstOrNull { it.id == item.id }?.isClosed = true val closedItems = currentItems.filter { it.isClosed } preferences.edit().putString("closeable_info_closed_ids", closedItems.joinToString(",") { it.id.toString() }).apply() relay.accept(currentItems) } }
gpl-3.0
92212e16ec605e204f67e07551116293
29.58
125
0.647906
4.328612
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeVariableMutabilityFix.kt
1
2128
// 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 org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory1 import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable.CreatePropertyDelegateAccessorsActionFactory import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtValVarKeywordOwner import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.util.OperatorNameConventions class ReassignmentActionFactory(val factory: DiagnosticFactory1<*, DeclarationDescriptor>) : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val propertyDescriptor = factory.cast(diagnostic).a val declaration = DescriptorToSourceUtils.descriptorToDeclaration(propertyDescriptor) as? KtValVarKeywordOwner ?: return null return ChangeVariableMutabilityFix(declaration, true) } } object DelegatedPropertyValFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val element = Errors.DELEGATE_SPECIAL_FUNCTION_MISSING.cast(diagnostic).psiElement val property = element.getStrictParentOfType<KtProperty>() ?: return null val info = CreatePropertyDelegateAccessorsActionFactory.extractFixData(property, diagnostic).singleOrNull() ?: return null if (info.name != OperatorNameConventions.SET_VALUE.asString()) return null return ChangeVariableMutabilityFix(property, makeVar = false, actionText = KotlinBundle.message("change.to.val")) } }
apache-2.0
d8bb8a7d08f2bab29c10d6c5a95eac0f
58.138889
158
0.81438
5.202934
false
false
false
false
PKRoma/PocketHub
app/src/main/java/com/github/pockethub/android/ui/issue/SearchIssueListFragment.kt
5
4774
/* * Copyright (c) 2015 PocketHub * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pockethub.android.ui.issue import android.app.SearchManager.APP_DATA import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.github.pockethub.android.Intents.EXTRA_REPOSITORY import com.github.pockethub.android.ui.helpers.ItemListHandler import com.github.pockethub.android.ui.helpers.PagedListFetcher import com.github.pockethub.android.ui.helpers.PagedScrollListener import com.github.pockethub.android.R import com.github.pockethub.android.ui.base.BaseFragment import com.github.pockethub.android.ui.item.issue.IssueItem import com.github.pockethub.android.util.AvatarLoader import com.github.pockethub.android.util.InfoUtils import com.github.pockethub.android.util.ToastUtils import com.meisolsson.githubsdk.model.Issue import com.meisolsson.githubsdk.model.Page import com.meisolsson.githubsdk.model.Repository import com.meisolsson.githubsdk.service.search.SearchService import com.xwray.groupie.Item import com.xwray.groupie.OnItemClickListener import io.reactivex.Single import kotlinx.android.synthetic.main.fragment_item_list.view.* import retrofit2.Response import javax.inject.Inject /** * Fragment to display a list of [Issue] instances */ class SearchIssueListFragment : BaseFragment() { @Inject protected lateinit var service: SearchService @Inject protected lateinit var avatars: AvatarLoader lateinit var pagedListFetcher: PagedListFetcher<Issue> private lateinit var itemListHandler: ItemListHandler private var repository: Repository? = null private var query: String? = null protected val errorMessage: Int get() = R.string.error_issues_load override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val appData = activity!!.intent.getBundleExtra(APP_DATA) if (appData != null) { repository = appData.getParcelable(EXTRA_REPOSITORY) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_item_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) itemListHandler = ItemListHandler( view.list, view.empty, lifecycle, activity, OnItemClickListener(this::onItemClick) ) pagedListFetcher = PagedListFetcher( view.swipe_item, lifecycle, itemListHandler, { t -> ToastUtils.show(activity, errorMessage) }, this::loadData, this::createItem ) view.list.addOnScrollListener( PagedScrollListener(itemListHandler.mainSection, pagedListFetcher) ) itemListHandler.setEmptyText(R.string.no_issues) } /** * @param query * @return this fragment */ fun setQuery(query: String): SearchIssueListFragment { this.query = query return this } fun onItemClick(item: Item<*>, view: View) { if (item is IssueItem) { val searchIssue = item.issue startActivity(IssuesViewActivity.createIntent(searchIssue, repository!!)) } } private fun loadData(page: Int): Single<Response<Page<Issue>>> { val searchQuery = query + "+repo:" + InfoUtils.createRepoId(repository!!) return service.searchIssues(searchQuery, null, null, page.toLong()) .map { response -> val issueSearchPage = response.body()!! Response.success(Page.builder<Issue>() .first(issueSearchPage.first()) .last(issueSearchPage.last()) .next(issueSearchPage.next()) .prev(issueSearchPage.prev()) .items(issueSearchPage.items()) .build()) } } private fun createItem(item: Issue): Item<*> { return IssueItem(avatars, item, false) } }
apache-2.0
815f56a3dbfe64f0f9fffda2bc7c2c1a
32.619718
85
0.684122
4.657561
false
false
false
false
mdaniel/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/actions/ShowCommitOptionsAction.kt
2
1366
// 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.openapi.vcs.actions import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.vcs.commit.ChangesViewCommitWorkflowHandler import com.intellij.vcs.commit.NonModalCommitWorkflowHandler class ShowCommitOptionsAction : DumbAwareAction() { init { templatePresentation.icon = AllIcons.Ide.Notification.Gear templatePresentation.hoveredIcon = AllIcons.Ide.Notification.GearHover } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = when (val workflowHandler = e.getContextCommitWorkflowHandler()) { is ChangesViewCommitWorkflowHandler -> workflowHandler.isActive is NonModalCommitWorkflowHandler<*, *> -> true else -> false } } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } override fun actionPerformed(e: AnActionEvent) { val workflowHandler = e.getContextCommitWorkflowHandler() as NonModalCommitWorkflowHandler<*, *> workflowHandler.showCommitOptions(e.isFromActionToolbar, e.dataContext) } }
apache-2.0
fe7e2b5f37c2e76eb81e2b2fe529a603
39.205882
140
0.787701
5.21374
false
false
false
false
androidstarters/androidstarters.com
templates/buffer-clean-architecture-components-kotlin/remote/src/main/java/org/buffer/android/boilerplate/remote/BufferooRemoteImpl.kt
1
1225
package <%= appPackage %>.remote import io.reactivex.Flowable import io.reactivex.Observable import <%= appPackage %>.data.model.BufferooEntity import <%= appPackage %>.data.repository.BufferooRemote import <%= appPackage %>.remote.mapper.BufferooEntityMapper import javax.inject.Inject /** * Remote implementation for retrieving Bufferoo instances. This class implements the * [BufferooRemote] from the Data layer as it is that layers responsibility for defining the * operations in which data store implementation layers can carry out. */ class BufferooRemoteImpl @Inject constructor(private val bufferooService: BufferooService, private val entityMapper: BufferooEntityMapper): BufferooRemote { /** * Retrieve a list of [BufferooEntity] instances from the [BufferooService]. */ override fun getBufferoos(): Flowable<List<BufferooEntity>> { return bufferooService.getBufferoos() .map { it.team } .map { val entities = mutableListOf<BufferooEntity>() it.forEach { entities.add(entityMapper.mapFromRemote(it)) } entities } } }
mit
0d177936d1cf5180d47671aec01f0ada
37.3125
93
0.665306
5.396476
false
false
false
false
bkmioa/NexusRss
app/src/main/java/io/github/bkmioa/nexusrss/ui/viewModel/OptionViewModel.kt
1
2144
package io.github.bkmioa.nexusrss.ui.viewModel import android.view.View import android.widget.CheckBox import android.widget.ImageView import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyModelClass import com.airbnb.epoxy.EpoxyModelWithHolder import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import io.github.bkmioa.nexusrss.R import io.github.bkmioa.nexusrss.base.BaseEpoxyHolder import io.github.bkmioa.nexusrss.base.GlideApp import io.github.bkmioa.nexusrss.model.Option import kotlinx.android.synthetic.main.option_item.view.* @EpoxyModelClass(layout = R.layout.option_item) abstract class OptionViewModel( @EpoxyAttribute @JvmField val option: Option, @EpoxyAttribute @JvmField val selected: Boolean) : EpoxyModelWithHolder<OptionViewModel.ViewHolder>() { init { id(option.key) } @EpoxyAttribute(hash = false) lateinit var onOptionCheckedListener: OnOptionCheckedListener override fun bind(holder: ViewHolder) { super.bind(holder) with(holder) { checkBox.text = option.des if (option.img != null) { checkBox.text = null imageView.visibility = View.VISIBLE GlideApp.with(holder.itemView.context) .load(option.img) .transition(DrawableTransitionOptions.withCrossFade()) .into(imageView) } else { imageView.visibility = View.GONE } itemView.setOnClickListener { checkBox.performClick() } checkBox.setOnCheckedChangeListener(null) checkBox.isChecked = selected checkBox.setOnCheckedChangeListener { _, isChecked -> onOptionCheckedListener.onChecked(option, isChecked) } } } class ViewHolder : BaseEpoxyHolder() { val checkBox: CheckBox by lazy { itemView.checkBox } val imageView: ImageView by lazy { itemView.imageView } } interface OnOptionCheckedListener { fun onChecked(option: Option, isChecked: Boolean) } }
apache-2.0
545b79d9bd149d2fbd9df70d583bcf54
32.5
78
0.671175
4.917431
false
false
false
false
android/nowinandroid
core/database/src/main/java/com/google/samples/apps/nowinandroid/core/database/dao/AuthorDao.kt
1
2150
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.core.database.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update import androidx.room.Upsert import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity import kotlinx.coroutines.flow.Flow /** * DAO for [AuthorEntity] access */ @Dao interface AuthorDao { @Query( value = """ SELECT * FROM authors WHERE id = :authorId """ ) fun getAuthorEntityStream(authorId: String): Flow<AuthorEntity> @Query(value = "SELECT * FROM authors") fun getAuthorEntitiesStream(): Flow<List<AuthorEntity>> /** * Inserts [authorEntities] into the db if they don't exist, and ignores those that do */ @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertOrIgnoreAuthors(authorEntities: List<AuthorEntity>): List<Long> /** * Updates [entities] in the db that match the primary key, and no-ops if they don't */ @Update suspend fun updateAuthors(entities: List<AuthorEntity>) /** * Inserts or updates [entities] in the db under the specified primary keys */ @Upsert suspend fun upsertAuthors(entities: List<AuthorEntity>) /** * Deletes rows in the db matching the specified [ids] */ @Query( value = """ DELETE FROM authors WHERE id in (:ids) """ ) suspend fun deleteAuthors(ids: List<String>) }
apache-2.0
4a3ea0246dd0fceb200b3f58e633c4e0
28.861111
90
0.694419
4.308617
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/MyPoliApp.kt
1
4890
package io.ipoli.android import android.annotation.SuppressLint import android.app.Application import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.net.Uri import android.os.Build import com.amplitude.api.Amplitude import com.crashlytics.android.Crashlytics import com.evernote.android.job.JobManager import com.jakewharton.threetenabp.AndroidThreeTen import io.fabric.sdk.android.Fabric import io.ipoli.android.common.di.* import io.ipoli.android.common.job.myPoliJobCreator import space.traversal.kapsule.transitive import timber.log.Timber /** * Created by Venelin Valkov <[email protected]> * on 7/7/17. */ class MyPoliApp : Application() { @Volatile private var uiModule: UIModule? = null @Volatile private var backgroundModule: BackgroundModule? = null companion object { lateinit var instance: MyPoliApp fun uiModule(context: Context): UIModule { val appInstance = context.applicationContext as MyPoliApp return appInstance.uiModule ?: synchronized(context.applicationContext) { appInstance.uiModule = UIModule( androidModule = MainAndroidModule(context), useCaseModule = MainUseCaseModule(context), stateStoreModule = AndroidStateStoreModule() ).transitive() appInstance.uiModule!! } } fun backgroundModule(context: Context): BackgroundModule { val appInstance = context.applicationContext as MyPoliApp return appInstance.backgroundModule ?: synchronized(context.applicationContext) { appInstance.backgroundModule = BackgroundModule( androidModule = MainAndroidModule(context), useCaseModule = MainUseCaseModule(context) ).transitive() appInstance.backgroundModule!! } } } @SuppressLint("NewApi") override fun onCreate() { super.onCreate() AndroidThreeTen.init(this) Amplitude.getInstance().initialize(applicationContext, AnalyticsConstants.AMPLITUDE_KEY) if (!BuildConfig.DEBUG) { Fabric.with( Fabric.Builder(this) .kits(Crashlytics()) .debuggable(BuildConfig.DEBUG) .build() ) } else { Amplitude.getInstance().setOptOut(true) Timber.plant(Timber.DebugTree()) } JobManager.create(this).addJobCreator(myPoliJobCreator()) instance = this if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val channels = notificationManager.notificationChannels if (channels.firstOrNull { it.id == Constants.REMINDERS_NOTIFICATION_CHANNEL_ID } == null) { notificationManager.createNotificationChannel(createReminderChannel()) } if (channels.firstOrNull { it.id == Constants.PLAN_DAY_NOTIFICATION_CHANNEL_ID } == null) { notificationManager.createNotificationChannel(createPlanDayChannel()) } } } @SuppressLint("NewApi") private fun createPlanDayChannel(): NotificationChannel { val channel = NotificationChannel( Constants.PLAN_DAY_NOTIFICATION_CHANNEL_ID, Constants.PLAN_DAY_NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT ) channel.description = "Notifications to plan your day" channel.enableLights(true) channel.enableVibration(true) channel.setSound( Uri.parse("android.resource://" + packageName + "/" + R.raw.notification), Notification.AUDIO_ATTRIBUTES_DEFAULT ) channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC return channel } @SuppressLint("NewApi") private fun createReminderChannel(): NotificationChannel { val channel = NotificationChannel( Constants.REMINDERS_NOTIFICATION_CHANNEL_ID, Constants.REMINDERS_NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH ) channel.description = "Reminder notifications" channel.enableLights(true) channel.enableVibration(true) channel.setSound( Uri.parse("android.resource://" + packageName + "/" + R.raw.notification), Notification.AUDIO_ATTRIBUTES_DEFAULT ) channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC return channel } }
gpl-3.0
ff99ed0fec7bbab12ffbcf1ac4922a9e
34.18705
104
0.641104
5.326797
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/stories/viewer/reply/group/StoryGroupReplyFragment.kt
1
20320
package org.thoughtcrime.securesms.stories.viewer.reply.group import android.content.ClipData import android.os.Bundle import android.view.KeyEvent import android.view.MotionEvent import android.view.View import android.widget.Toast import androidx.annotation.ColorInt import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.bottomsheet.BottomSheetBehaviorHack import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.dialog.MaterialAlertDialogBuilder import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.kotlin.subscribeBy import org.signal.core.util.concurrent.SignalExecutors import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.FixedRoundedCornerBottomSheetDialogFragment import org.thoughtcrime.securesms.components.emoji.MediaKeyboard import org.thoughtcrime.securesms.components.mention.MentionAnnotation import org.thoughtcrime.securesms.components.settings.DSLConfiguration import org.thoughtcrime.securesms.components.settings.configure import org.thoughtcrime.securesms.conversation.MarkReadHelper import org.thoughtcrime.securesms.conversation.colors.Colorizer import org.thoughtcrime.securesms.conversation.ui.error.SafetyNumberChangeDialog import org.thoughtcrime.securesms.conversation.ui.mentions.MentionsPickerFragment import org.thoughtcrime.securesms.conversation.ui.mentions.MentionsPickerViewModel import org.thoughtcrime.securesms.database.model.Mention import org.thoughtcrime.securesms.database.model.MessageId import org.thoughtcrime.securesms.database.model.MessageRecord import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.jobs.RetrieveProfileJob import org.thoughtcrime.securesms.keyboard.KeyboardPage import org.thoughtcrime.securesms.keyboard.KeyboardPagerViewModel import org.thoughtcrime.securesms.keyboard.emoji.EmojiKeyboardCallback import org.thoughtcrime.securesms.mediasend.v2.UntrustedRecords import org.thoughtcrime.securesms.notifications.v2.ConversationId import org.thoughtcrime.securesms.reactions.any.ReactWithAnyEmojiBottomSheetDialogFragment import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.recipients.RecipientId import org.thoughtcrime.securesms.recipients.ui.bottomsheet.RecipientBottomSheetDialogFragment import org.thoughtcrime.securesms.sms.MessageSender import org.thoughtcrime.securesms.stories.viewer.reply.StoryViewsAndRepliesPagerChild import org.thoughtcrime.securesms.stories.viewer.reply.StoryViewsAndRepliesPagerParent import org.thoughtcrime.securesms.stories.viewer.reply.composer.StoryReactionBar import org.thoughtcrime.securesms.stories.viewer.reply.composer.StoryReplyComposer import org.thoughtcrime.securesms.util.DeleteDialog import org.thoughtcrime.securesms.util.FragmentDialogs.displayInDialogAboveAnchor import org.thoughtcrime.securesms.util.LifecycleDisposable import org.thoughtcrime.securesms.util.ServiceUtil import org.thoughtcrime.securesms.util.ViewUtil import org.thoughtcrime.securesms.util.adapter.mapping.PagingMappingAdapter import org.thoughtcrime.securesms.util.fragments.findListener import org.thoughtcrime.securesms.util.fragments.requireListener import org.thoughtcrime.securesms.util.visible /** * Fragment which contains UI to reply to a group story */ class StoryGroupReplyFragment : Fragment(R.layout.stories_group_replies_fragment), StoryViewsAndRepliesPagerChild, StoryReplyComposer.Callback, EmojiKeyboardCallback, ReactWithAnyEmojiBottomSheetDialogFragment.Callback, SafetyNumberChangeDialog.Callback { companion object { private val TAG = Log.tag(StoryGroupReplyFragment::class.java) private const val ARG_STORY_ID = "arg.story.id" private const val ARG_GROUP_RECIPIENT_ID = "arg.group.recipient.id" private const val ARG_IS_FROM_NOTIFICATION = "is_from_notification" private const val ARG_GROUP_REPLY_START_POSITION = "group_reply_start_position" fun create(storyId: Long, groupRecipientId: RecipientId, isFromNotification: Boolean, groupReplyStartPosition: Int): Fragment { return StoryGroupReplyFragment().apply { arguments = Bundle().apply { putLong(ARG_STORY_ID, storyId) putParcelable(ARG_GROUP_RECIPIENT_ID, groupRecipientId) putBoolean(ARG_IS_FROM_NOTIFICATION, isFromNotification) putInt(ARG_GROUP_REPLY_START_POSITION, groupReplyStartPosition) } } } } private val viewModel: StoryGroupReplyViewModel by viewModels( factoryProducer = { StoryGroupReplyViewModel.Factory(storyId, StoryGroupReplyRepository()) } ) private val mentionsViewModel: MentionsPickerViewModel by viewModels( factoryProducer = { MentionsPickerViewModel.Factory() }, ownerProducer = { requireActivity() } ) private val keyboardPagerViewModel: KeyboardPagerViewModel by viewModels( ownerProducer = { requireActivity() } ) private val recyclerListener: RecyclerView.OnItemTouchListener = object : RecyclerView.SimpleOnItemTouchListener() { override fun onInterceptTouchEvent(view: RecyclerView, e: MotionEvent): Boolean { recyclerView.isNestedScrollingEnabled = view == recyclerView composer.emojiPageView?.isNestedScrollingEnabled = view == composer.emojiPageView val dialog = (parentFragment as FixedRoundedCornerBottomSheetDialogFragment).dialog as BottomSheetDialog BottomSheetBehaviorHack.setNestedScrollingChild(dialog.behavior, view) dialog.findViewById<View>(R.id.design_bottom_sheet)?.invalidate() return false } } private val colorizer = Colorizer() private val lifecycleDisposable = LifecycleDisposable() private val storyId: Long get() = requireArguments().getLong(ARG_STORY_ID) private val groupRecipientId: RecipientId get() = requireArguments().getParcelable(ARG_GROUP_RECIPIENT_ID)!! private val isFromNotification: Boolean get() = requireArguments().getBoolean(ARG_IS_FROM_NOTIFICATION, false) private val groupReplyStartPosition: Int get() = requireArguments().getInt(ARG_GROUP_REPLY_START_POSITION, -1) private lateinit var recyclerView: RecyclerView private lateinit var adapter: PagingMappingAdapter<MessageId> private lateinit var dataObserver: RecyclerView.AdapterDataObserver private lateinit var composer: StoryReplyComposer private var markReadHelper: MarkReadHelper? = null private var currentChild: StoryViewsAndRepliesPagerParent.Child? = null private var resendBody: CharSequence? = null private var resendMentions: List<Mention> = emptyList() private var resendReaction: String? = null override fun onViewCreated(view: View, savedInstanceState: Bundle?) { SignalExecutors.BOUNDED.execute { RetrieveProfileJob.enqueue(groupRecipientId) } recyclerView = view.findViewById(R.id.recycler) composer = view.findViewById(R.id.composer) lifecycleDisposable.bindTo(viewLifecycleOwner) val emptyNotice: View = requireView().findViewById(R.id.empty_notice) adapter = PagingMappingAdapter<MessageId>().apply { setPagingController(viewModel.pagingController) } val layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false) recyclerView.layoutManager = layoutManager recyclerView.adapter = adapter recyclerView.itemAnimator = null StoryGroupReplyItem.register(adapter) composer.callback = this onPageSelected(findListener<StoryViewsAndRepliesPagerParent>()?.selectedChild ?: StoryViewsAndRepliesPagerParent.Child.REPLIES) var firstSubmit = true viewModel.state .observeOn(AndroidSchedulers.mainThread()) .subscribeBy { state -> if (markReadHelper == null && state.threadId > 0L) { if (isResumed) { ApplicationDependencies.getMessageNotifier().setVisibleThread(ConversationId(state.threadId, storyId)) } markReadHelper = MarkReadHelper(ConversationId(state.threadId, storyId), requireContext(), viewLifecycleOwner) if (isFromNotification) { markReadHelper?.onViewsRevealed(System.currentTimeMillis()) } } emptyNotice.visible = state.noReplies && state.loadState == StoryGroupReplyState.LoadState.READY colorizer.onNameColorsChanged(state.nameColors) adapter.submitList(getConfiguration(state.replies).toMappingModelList()) { if (firstSubmit && (groupReplyStartPosition >= 0 && adapter.hasItem(groupReplyStartPosition))) { firstSubmit = false recyclerView.post { recyclerView.scrollToPosition(groupReplyStartPosition) } } } } dataObserver = GroupDataObserver() adapter.registerAdapterDataObserver(dataObserver) initializeMentions() if (savedInstanceState == null) { ViewUtil.focusAndShowKeyboard(composer) } recyclerView.addOnScrollListener(GroupReplyScrollObserver()) } override fun onResume() { super.onResume() val threadId = viewModel.stateSnapshot.threadId if (threadId != 0L) { ApplicationDependencies.getMessageNotifier().setVisibleThread(ConversationId(threadId, storyId)) } } override fun onPause() { super.onPause() ApplicationDependencies.getMessageNotifier().setVisibleThread(null) } override fun onDestroyView() { super.onDestroyView() composer.input.setMentionQueryChangedListener(null) composer.input.setMentionValidator(null) } private fun postMarkAsReadRequest() { if (adapter.itemCount == 0 || markReadHelper == null) { return } val lastVisibleItem = (recyclerView.layoutManager as LinearLayoutManager).findLastVisibleItemPosition() val adapterItem = adapter.getItem(lastVisibleItem) if (adapterItem == null || adapterItem !is StoryGroupReplyItem.Model) { return } markReadHelper?.onViewsRevealed(adapterItem.replyBody.sentAtMillis) } private fun getConfiguration(pageData: List<ReplyBody>): DSLConfiguration { return configure { pageData.forEach { when (it) { is ReplyBody.Text -> { customPref( StoryGroupReplyItem.TextModel( text = it, nameColor = it.sender.getStoryGroupReplyColor(), onCopyClick = { s -> onCopyClick(s) }, onMentionClick = { recipientId -> RecipientBottomSheetDialogFragment .create(recipientId, null) .show(childFragmentManager, null) }, onDeleteClick = { m -> onDeleteClick(m) }, onTapForDetailsClick = { m -> onTapForDetailsClick(m) } ) ) } is ReplyBody.Reaction -> { customPref( StoryGroupReplyItem.ReactionModel( reaction = it, nameColor = it.sender.getStoryGroupReplyColor(), onCopyClick = { s -> onCopyClick(s) }, onDeleteClick = { m -> onDeleteClick(m) }, onTapForDetailsClick = { m -> onTapForDetailsClick(m) } ) ) } is ReplyBody.RemoteDelete -> { customPref( StoryGroupReplyItem.RemoteDeleteModel( remoteDelete = it, nameColor = it.sender.getStoryGroupReplyColor(), onDeleteClick = { m -> onDeleteClick(m) }, onTapForDetailsClick = { m -> onTapForDetailsClick(m) } ) ) } } } } } private fun onCopyClick(textToCopy: CharSequence) { val clipData = ClipData.newPlainText(requireContext().getString(R.string.app_name), textToCopy) ServiceUtil.getClipboardManager(requireContext()).setPrimaryClip(clipData) Toast.makeText(requireContext(), R.string.StoryGroupReplyFragment__copied_to_clipboard, Toast.LENGTH_SHORT).show() } private fun onDeleteClick(messageRecord: MessageRecord) { lifecycleDisposable += DeleteDialog.show(requireActivity(), setOf(messageRecord)).subscribe { didDeleteThread -> if (didDeleteThread) { throw AssertionError("We should never end up deleting a Group Thread like this.") } } } private fun onTapForDetailsClick(messageRecord: MessageRecord) { if (messageRecord.isRemoteDelete) { // TODO [cody] Android doesn't support resending remote deletes yet return } if (messageRecord.isIdentityMismatchFailure) { SafetyNumberChangeDialog.show(requireContext(), childFragmentManager, messageRecord) } else if (messageRecord.hasFailedWithNetworkFailures()) { MaterialAlertDialogBuilder(requireContext()) .setMessage(R.string.conversation_activity__message_could_not_be_sent) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(R.string.conversation_activity__send) { _, _ -> SignalExecutors.BOUNDED.execute { MessageSender.resend(requireContext(), messageRecord) } } .show() } } override fun onPageSelected(child: StoryViewsAndRepliesPagerParent.Child) { currentChild = child updateNestedScrolling() } private fun updateNestedScrolling() { recyclerView.isNestedScrollingEnabled = currentChild == StoryViewsAndRepliesPagerParent.Child.REPLIES && !(mentionsViewModel.isShowing.value ?: false) } override fun onSendActionClicked() { val (body, mentions) = composer.consumeInput() performSend(body, mentions) } override fun onPickReactionClicked() { displayInDialogAboveAnchor(composer.reactionButton, R.layout.stories_reaction_bar_layout) { dialog, view -> view.findViewById<StoryReactionBar>(R.id.reaction_bar).apply { callback = object : StoryReactionBar.Callback { override fun onTouchOutsideOfReactionBar() { dialog.dismiss() } override fun onReactionSelected(emoji: String) { dialog.dismiss() sendReaction(emoji) } override fun onOpenReactionPicker() { dialog.dismiss() ReactWithAnyEmojiBottomSheetDialogFragment.createForStory().show(childFragmentManager, null) } } animateIn() } } } override fun onEmojiSelected(emoji: String?) { composer.onEmojiSelected(emoji) } private fun sendReaction(emoji: String) { lifecycleDisposable += StoryGroupReplySender.sendReaction(requireContext(), storyId, emoji) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onError = { error -> if (error is UntrustedRecords.UntrustedRecordsException) { resendReaction = emoji SafetyNumberChangeDialog.show(childFragmentManager, error.untrustedRecords) } else { Log.w(TAG, "Failed to send reply", error) val context = context if (context != null) { Toast.makeText(context, R.string.message_details_recipient__failed_to_send, Toast.LENGTH_SHORT).show() } } } ) } override fun onKeyEvent(keyEvent: KeyEvent?) = Unit override fun onInitializeEmojiDrawer(mediaKeyboard: MediaKeyboard) { keyboardPagerViewModel.setOnlyPage(KeyboardPage.EMOJI) mediaKeyboard.setFragmentManager(childFragmentManager) } override fun onShowEmojiKeyboard() { requireListener<Callback>().requestFullScreen(true) recyclerView.addOnItemTouchListener(recyclerListener) composer.emojiPageView?.addOnItemTouchListener(recyclerListener) } override fun onHideEmojiKeyboard() { recyclerView.removeOnItemTouchListener(recyclerListener) composer.emojiPageView?.removeOnItemTouchListener(recyclerListener) requireListener<Callback>().requestFullScreen(false) } override fun openEmojiSearch() { composer.openEmojiSearch() } override fun closeEmojiSearch() { composer.closeEmojiSearch() } override fun onReactWithAnyEmojiDialogDismissed() = Unit override fun onReactWithAnyEmojiSelected(emoji: String) { sendReaction(emoji) } private fun initializeMentions() { Recipient.live(groupRecipientId).observe(viewLifecycleOwner) { recipient -> mentionsViewModel.onRecipientChange(recipient) composer.input.setMentionQueryChangedListener { query -> if (recipient.isPushV2Group) { ensureMentionsContainerFilled() mentionsViewModel.onQueryChange(query) } } composer.input.setMentionValidator { annotations -> if (!recipient.isPushV2Group) { annotations } else { val validRecipientIds: Set<String> = recipient.participants .map { r -> MentionAnnotation.idToMentionAnnotationValue(r.id) } .toSet() annotations .filter { !validRecipientIds.contains(it.value) } .toList() } } } mentionsViewModel.selectedRecipient.observe(viewLifecycleOwner) { recipient -> composer.input.replaceTextWithMention(recipient.getDisplayName(requireContext()), recipient.id) } mentionsViewModel.isShowing.observe(viewLifecycleOwner) { updateNestedScrolling() } } private fun ensureMentionsContainerFilled() { val mentionsFragment = childFragmentManager.findFragmentById(R.id.mentions_picker_container) if (mentionsFragment == null) { childFragmentManager .beginTransaction() .replace(R.id.mentions_picker_container, MentionsPickerFragment()) .commitNowAllowingStateLoss() } } private fun performSend(body: CharSequence, mentions: List<Mention>) { lifecycleDisposable += StoryGroupReplySender.sendReply(requireContext(), storyId, body, mentions) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onError = { if (it is UntrustedRecords.UntrustedRecordsException) { resendBody = body resendMentions = mentions SafetyNumberChangeDialog.show(childFragmentManager, it.untrustedRecords) } else { Log.w(TAG, "Failed to send reply", it) val context = context if (context != null) { Toast.makeText(context, R.string.message_details_recipient__failed_to_send, Toast.LENGTH_SHORT).show() } } } ) } override fun onSendAnywayAfterSafetyNumberChange(changedRecipients: MutableList<RecipientId>) { val resendBody = resendBody val resendReaction = resendReaction if (resendBody != null) { performSend(resendBody, resendMentions) } else if (resendReaction != null) { sendReaction(resendReaction) } } override fun onMessageResentAfterSafetyNumberChange() { Log.i(TAG, "Message resent") } override fun onCanceled() { resendBody = null resendMentions = emptyList() resendReaction = null } @ColorInt private fun Recipient.getStoryGroupReplyColor(): Int { return colorizer.getIncomingGroupSenderColor(requireContext(), this) } private inner class GroupReplyScrollObserver : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { postMarkAsReadRequest() } override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { postMarkAsReadRequest() } } private inner class GroupDataObserver : RecyclerView.AdapterDataObserver() { override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { if (itemCount == 0) { return } val item = adapter.getItem(positionStart) if (positionStart == adapter.itemCount - 1 && item is StoryGroupReplyItem.Model) { val isOutgoing = item.replyBody.sender == Recipient.self() if (isOutgoing || (!isOutgoing && !recyclerView.canScrollVertically(1))) { recyclerView.post { recyclerView.scrollToPosition(positionStart) } } } } } interface Callback { fun onStartDirectReply(recipientId: RecipientId) fun requestFullScreen(fullscreen: Boolean) } }
gpl-3.0
677c517d852b184959dff604bccd6e76
36.769517
166
0.726526
5.173116
false
false
false
false
filestack/filestack-java
src/test/java/com/filestack/ClientTest.kt
1
7697
package com.filestack import com.filestack.internal.NetworkClient import com.filestack.internal.TestServiceFactory.Companion.baseService import com.filestack.internal.TestServiceFactory.Companion.cdnService import com.filestack.internal.TestServiceFactory.Companion.cloudService import com.filestack.internal.TestServiceFactory.Companion.uploadService import com.google.gson.Gson import okhttp3.OkHttpClient import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import okhttp3.mockwebserver.RecordedRequest import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test private const val UPLOAD_ID = "iacwRXloJVbO78XMR7vQqiiKJRIr2.geEepw4aUG" private const val API_KEY = "iowjr230942nn2" @Suppress("MemberVisibilityCanBePrivate") class ClientTest { @get:Rule val server = MockWebServer() val okHttpClient = OkHttpClient.Builder().build() val gson = Gson() val networkClient = NetworkClient(okHttpClient, gson) val cdnService = cdnService(networkClient, server.url("/")) val baseService = baseService(networkClient, server.url("/")) val uploadService = uploadService(networkClient, server.url("/")) val cloudService = cloudService(networkClient, gson, server.url("/")) val config = Config(API_KEY, "policy", "signature") val client = Client(config, cdnService, baseService, uploadService, cloudService) @Test fun `regular upload - single part`() { val file = tempFile(sizeInBytes = 1024) server.enqueue(MockResponse().setBody("""{ "uri": "/filestack-uploads/${file.name}", "region": "eu-west-1", "upload_id": "$UPLOAD_ID", "location_url": "upload-eu-west.com", "upload_type": "intelligent_ingestion" }""")) server.enqueue(MockResponse().setBody("""{ "url": "${server.url("/s3_upload_url")}", "headers": { "Authorization": "s3_authorization_token", "Content-Md5": "KSiCLGZTaJerQ9kDUi8zCg==", "x-amz-content-sha256": "UNSIGNED-PAYLOAD", "x-amz-date": "20180912T090547Z" }, "location_url": "upload-eu-west.com" }""")) //upload to S3 returns only 200 server.enqueue(MockResponse()) server.enqueue(MockResponse().setBody("""{ "handle": "Ekf5elTQeed8SG549RP", "url": "https://cdn.filestackcontent.com/Ekf5elTQeed8SG549RP", "filename": "some_file.txt", "size": ${file.length()}, "mimetype": "text/plain", "status": "Complete" } """)) val fileLink = client.upload(file.path, false) assertEquals("Ekf5elTQeed8SG549RP", fileLink.handle) server.takeRequest().assertThat { isPost() pathIs("/multipart/start") bodyField("apikey", API_KEY) bodyField("size", file.length().toString()) bodyField("filename", file.name) bodyField("store_location", "s3") noField("multipart") } server.takeRequest().assertThat { isPost() pathIs("/multipart/upload") bodyField("apikey", API_KEY) bodyField("part", 1) bodyField("size", file.length().toString()) bodyField("region", "eu-west-1") bodyField("store_location", "s3") bodyField("upload_id", UPLOAD_ID) noField("upload_type") } server.takeRequest().assertThat { isPut() pathIs("/s3_upload_url") header("Authorization", "s3_authorization_token") header("Content-MD5", "KSiCLGZTaJerQ9kDUi8zCg==") header("x-amz-content-sha256", "UNSIGNED-PAYLOAD") header("x-amz-date", "20180912T090547Z") } server.takeRequest().assertThat { isPost() pathIs("/multipart/complete") bodyField("apikey", API_KEY) bodyField("upload_id", UPLOAD_ID) bodyField("region", "eu-west-1") } } @Test fun `regular upload - few parts`() { val file = tempFile(sizeInBytes = 16 * 1024 * 1024) val dispatcher = object : RequestStoringDispatcher() { override fun dispatchFor(request: RecordedRequest): MockResponse = when (request.path) { "/multipart/start" -> MockResponse().setBody("""{ "uri": "/filestack-uploads/${file.name}", "region": "eu-west-1", "upload_id": "$UPLOAD_ID", "location_url": "upload-eu-west.com", "upload_type": "intelligent_ingestion" }""") "/multipart/upload" -> uploadResponse(request) "/s3_upload_url?partNumber=1&uploadId=upload_id_for_part_1", "/s3_upload_url?partNumber=2&uploadId=upload_id_for_part_2", "/s3_upload_url?partNumber=3&uploadId=upload_id_for_part_3", "/s3_upload_url?partNumber=4&uploadId=upload_id_for_part_4" -> MockResponse() "/multipart/complete" -> MockResponse().setBody("""{ "handle": "Ekf5elTQeed8SG549RP", "url": "https://cdn.filestackcontent.com/Ekf5elTQeed8SG549RP", "filename": "some_file.txt", "size": ${file.length()}, "mimetype": "text/plain", "status": "Complete" } """) else -> MockResponse().setResponseCode(403) } private fun uploadResponse(request: RecordedRequest): MockResponse { val part = request.bodyParams()["part"] return MockResponse().setBody("""{ "url": "${server.url("/s3_upload_url")}?partNumber=$part\u0026uploadId=upload_id_for_part_$part", "headers": { "Authorization": "s3_authorization_token", "Content-Md5": "Hp1M87g6X56soslQBkSlhQ==", "x-amz-content-sha256": "UNSIGNED-PAYLOAD", "x-amz-date": "20180912T145703Z" }, "location_url": "upload-eu-west-1.filestackapi.com" } """) } } server.setDispatcher(dispatcher) val fileLink = client.upload(file.path, false) assertEquals("Ekf5elTQeed8SG549RP", fileLink.handle) dispatcher.assertThat { totalRequests(10) requestTo("/multipart/start") { bodyField("apikey", API_KEY); bodyField("filename", file.name) bodyField("size", file.length()) } onlyOneRequest("/s3_upload_url?partNumber=1&uploadId=upload_id_for_part_1") onlyOneRequest("/s3_upload_url?partNumber=2&uploadId=upload_id_for_part_2") onlyOneRequest("/s3_upload_url?partNumber=3&uploadId=upload_id_for_part_3") onlyOneRequest("/s3_upload_url?partNumber=4&uploadId=upload_id_for_part_4") } } }
apache-2.0
8647907f06bbbed3eb266193fd1c6934
38.270408
123
0.534884
4.278488
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/shadow/UnusedShadowMethodPrefixInspection.kt
1
1495
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection.shadow import com.demonwav.mcdev.platform.mixin.inspection.MixinInspection import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.SHADOW import com.demonwav.mcdev.util.constantStringValue import com.demonwav.mcdev.util.findAnnotation import com.demonwav.mcdev.util.quickfix.RemoveAnnotationAttributeQuickFix import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.JavaElementVisitor import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiMethod class UnusedShadowMethodPrefixInspection : MixinInspection() { override fun getStaticDescription() = "Reports unused prefixes of @Shadow methods" override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder) private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() { override fun visitMethod(method: PsiMethod) { val shadow = method.findAnnotation(SHADOW) ?: return val prefixValue = shadow.findDeclaredAttributeValue("prefix") ?: return val prefix = prefixValue.constantStringValue ?: return if (!method.name.startsWith(prefix)) { holder.registerProblem(prefixValue, "Unused @Shadow prefix", RemoveAnnotationAttributeQuickFix("@Shadow", "prefix")) } } } }
mit
58ccf02ff00e199b004ff1619b9114d4
35.463415
132
0.753846
4.885621
false
false
false
false
mdanielwork/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/parser/parserUtils.kt
1
16335
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("GroovyParserUtils") @file:Suppress("UNUSED_PARAMETER", "LiftReturnOrAssignment") package org.jetbrains.plugins.groovy.lang.parser import com.intellij.codeInsight.completion.CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED import com.intellij.lang.PsiBuilder import com.intellij.lang.PsiBuilder.Marker import com.intellij.lang.PsiBuilderUtil.parseBlockLazy import com.intellij.lang.parser.GeneratedParserUtilBase.* import com.intellij.openapi.util.Key import com.intellij.openapi.util.KeyWithDefaultValue import com.intellij.openapi.util.text.StringUtil.contains import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import org.jetbrains.plugins.groovy.GroovyBundle import org.jetbrains.plugins.groovy.lang.lexer.GroovyLexer import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.* import org.jetbrains.plugins.groovy.lang.psi.GroovyTokenSets.* import org.jetbrains.plugins.groovy.util.get import org.jetbrains.plugins.groovy.util.set import org.jetbrains.plugins.groovy.util.withKey import java.util.* private val PsiBuilder.groovyParser: GroovyParser get() = (this as Builder).parser as GroovyParser private val collapseHook = Hook<IElementType> { _, marker: Marker?, elementType: IElementType -> marker ?: return@Hook null val newMarker = marker.precede() marker.drop() newMarker.collapse(elementType) newMarker } fun parseBlockLazy(builder: PsiBuilder, level: Int, deepParser: Parser, elementType: IElementType): Boolean { return if (builder.groovyParser.parseDeep()) { deepParser.parse(builder, level + 1) } else { register_hook_(builder, collapseHook, elementType) parseBlockLazy(builder, T_LBRACE, T_RBRACE, elementType) != null } } fun extendedStatement(builder: PsiBuilder, level: Int): Boolean = builder.groovyParser.parseExtendedStatement(builder) fun extendedSeparator(builder: PsiBuilder, level: Int): Boolean = builder.advanceIf { builder.groovyParser.isExtendedSeparator(tokenType) } private val currentClassNames: Key<Deque<String>> = KeyWithDefaultValue.create("groovy.parse.class.name") { LinkedList<String>() } private val parseDiamonds: Key<Boolean> = Key.create("groovy.parse.diamonds") private val parseArguments: Key<Boolean> = Key.create("groovy.parse.arguments") private val parseApplicationArguments: Key<Boolean> = Key.create("groovy.parse.application.arguments") private val parseAnyTypeElement: Key<Boolean> = Key.create("groovy.parse.any.type.element") private val parseQualifiedName: Key<Boolean> = Key.create("groovy.parse.qualified.name") private val parseCapitalizedCodeReference: Key<Boolean> = Key.create("groovy.parse.capitalized") private val parseDefinitelyTypeElement: Key<Boolean> = Key.create("groovy.parse.definitely.type.element") private val referenceWasCapitalized: Key<Boolean> = Key.create("groovy.parse.ref.was.capitalized") private val typeWasPrimitive: Key<Boolean> = Key.create("groovy.parse.type.was.primitive") private val referenceHadTypeArguments: Key<Boolean> = Key.create("groovy.parse.ref.had.type.arguments") private val referenceWasQualified: Key<Boolean> = Key.create("groovy.parse.ref.was.qualified") fun classIdentifier(builder: PsiBuilder, level: Int): Boolean { if (builder.tokenType === IDENTIFIER) { builder[currentClassNames]!!.push(builder.tokenText) builder.advanceLexer() return true } else { return false } } fun popClassIdentifier(builder: PsiBuilder, level: Int): Boolean { builder[currentClassNames]!!.pop() return true } fun constructorIdentifier(builder: PsiBuilder, level: Int): Boolean { return builder.advanceIf { tokenType === IDENTIFIER && tokenText == this[currentClassNames]!!.peek() } } fun allowDiamond(builder: PsiBuilder, level: Int, parser: Parser): Boolean { return builder.withKey(parseDiamonds, true) { parser.parse(builder, level) } } fun isDiamondAllowed(builder: PsiBuilder, level: Int): Boolean = builder[parseDiamonds] fun anyTypeElement(builder: PsiBuilder, level: Int, typeElement: Parser): Boolean { return builder.withKey(parseAnyTypeElement, true) { typeElement.parse(builder, level + 1) } } private val PsiBuilder.anyTypeElementParsing get() = this[parseAnyTypeElement] fun qualifiedName(builder: PsiBuilder, level: Int, parser: Parser): Boolean { return builder.withKey(parseQualifiedName, true) { parser.parse(builder, level) } } fun isQualifiedName(builder: PsiBuilder, level: Int): Boolean = builder[parseQualifiedName] fun capitalizedTypeElement(builder: PsiBuilder, level: Int, typeElement: Parser, check: Parser): Boolean { try { return builder.withKey(parseCapitalizedCodeReference, true) { typeElement.parse(builder, level) && check.parse(builder, level) } } finally { builder[referenceWasCapitalized] = null } } private val PsiBuilder.capitalizedReferenceParsing get() = this[parseCapitalizedCodeReference] && !anyTypeElementParsing fun refWasCapitalized(builder: PsiBuilder, level: Int): Boolean = builder[referenceWasCapitalized] fun codeReferenceIdentifier(builder: PsiBuilder, level: Int, identifier: Parser): Boolean { if (builder.capitalizedReferenceParsing) { val capitalized = builder.isNextTokenCapitalized() val result = identifier.parse(builder, level) if (result) { builder[referenceWasCapitalized] = capitalized } else { builder[referenceWasCapitalized] = null } return result } return identifier.parse(builder, level) } private fun PsiBuilder.isNextTokenCapitalized(): Boolean { val text = tokenText return text != null && text.isNotEmpty() && text != DUMMY_IDENTIFIER_TRIMMED && text.first().isUpperCase() } fun definitelyTypeElement(builder: PsiBuilder, level: Int, typeElement: Parser, check: Parser): Boolean { val result = builder.withKey(parseDefinitelyTypeElement, true) { typeElement.parse(builder, level) } && (builder.wasDefinitelyTypeElement() || check.parse(builder, level)) builder.clearTypeInfo() return result } private val PsiBuilder.definitelyTypeElementParsing get() = this[parseDefinitelyTypeElement] && !anyTypeElementParsing private fun PsiBuilder.wasDefinitelyTypeElement(): Boolean { return this[typeWasPrimitive] || this[referenceHadTypeArguments] || this[referenceWasQualified] } private fun PsiBuilder.clearTypeInfo() { this[typeWasPrimitive] = null this[referenceHadTypeArguments] = null this[referenceWasQualified] = null } fun setTypeWasPrimitive(builder: PsiBuilder, level: Int): Boolean { if (builder.definitelyTypeElementParsing) { builder[typeWasPrimitive] = true } return true } fun setRefWasQualified(builder: PsiBuilder, level: Int): Boolean { if (builder.definitelyTypeElementParsing) { builder[referenceWasQualified] = true } return true } fun setRefHadTypeArguments(builder: PsiBuilder, level: Int): Boolean { if (builder.definitelyTypeElementParsing) { builder[referenceHadTypeArguments] = true } return true } fun parseArgument(builder: PsiBuilder, level: Int, argumentParser: Parser): Boolean { return builder.withKey(parseArguments, true) { argumentParser.parse(builder, level) } } fun isArguments(builder: PsiBuilder, level: Int): Boolean = builder[parseArguments] fun applicationArguments(builder: PsiBuilder, level: Int, parser: Parser): Boolean { return builder.withKey(parseApplicationArguments, true) { parser.parse(builder, level) } } fun notApplicationArguments(builder: PsiBuilder, level: Int, parser: Parser): Boolean { return builder.withKey(parseApplicationArguments, null) { parser.parse(builder, level) } } fun isApplicationArguments(builder: PsiBuilder, level: Int): Boolean = builder[parseApplicationArguments] fun closureArgumentSeparator(builder: PsiBuilder, level: Int, closureArguments: Parser): Boolean { if (builder.tokenType === NL) { if (isApplicationArguments(builder, level)) { return false } builder.advanceLexer() } return closureArguments.parse(builder, level) } /** *``` * foo a // ref <- application * foo a ref // application <- ref * foo a(ref) * foo a.ref * foo a[ref] * foo a ref c // ref <- application * foo a ref(c) // ref <- call * foo a ref[c] // ref <- index * foo a ref[c] ref // index <- ref * foo a ref[c] (a) // index <- call * foo a ref[c] {} // index <- call * foo a ref(c) ref // call <- ref * foo a ref(c)(c) // call <- call * foo a ref(c)[c] // call <- index *``` */ fun parseApplication(builder: PsiBuilder, level: Int, refParser: Parser, applicationParser: Parser, callParser: Parser, indexParser: Parser): Boolean { val wrappee = builder.latestDoneMarker ?: return false val nextLevel = level + 1 return when (wrappee.tokenType) { APPLICATION_EXPRESSION -> { refParser.parse(builder, nextLevel) } METHOD_CALL_EXPRESSION -> { indexParser.parse(builder, nextLevel) || callParser.parse(builder, nextLevel) || refParser.parse(builder, nextLevel) } REFERENCE_EXPRESSION -> { indexParser.parse(builder, nextLevel) || callParser.parse(builder, nextLevel) || applicationParser.parse(builder, nextLevel) } APPLICATION_INDEX -> { callParser.parse(builder, nextLevel) || refParser.parse(builder, nextLevel) } else -> applicationParser.parse(builder, nextLevel) } } fun parseExpressionOrMapArgument(builder: PsiBuilder, level: Int, expression: Parser): Boolean { val argumentMarker = builder.mark() val labelMarker = builder.mark() if (expression.parse(builder, level + 1)) { if (T_COLON === builder.tokenType) { labelMarker.done(ARGUMENT_LABEL) builder.advanceLexer() report_error_(builder, expression.parse(builder, level + 1)) argumentMarker.done(NAMED_ARGUMENT) } else { labelMarker.drop() argumentMarker.drop() } return true } else { labelMarker.drop() argumentMarker.rollbackTo() return false } } fun parseKeyword(builder: PsiBuilder, level: Int): Boolean = builder.advanceIf(KEYWORDS) fun parsePrimitiveType(builder: PsiBuilder, level: Int): Boolean = builder.advanceIf(primitiveTypes) fun assignmentOperator(builder: PsiBuilder, level: Int): Boolean = builder.advanceIf(ASSIGNMENTS) fun equalityOperator(builder: PsiBuilder, level: Int): Boolean = builder.advanceIf(EQUALITY_OPERATORS) fun error(builder: PsiBuilder, level: Int, key: String): Boolean { val marker = builder.latestDoneMarker ?: return false val elementType = marker.tokenType val newMarker = (marker as Marker).precede() marker.drop() builder.error(GroovyBundle.message(key)) newMarker.done(elementType) return true } fun unexpected(builder: PsiBuilder, level: Int, key: String): Boolean { return unexpected(builder, level, Parser { b, _ -> b.any() }, key) } fun unexpected(builder: PsiBuilder, level: Int, parser: Parser, key: String): Boolean { val marker = builder.mark() if (parser.parse(builder, level)) { marker.error(GroovyBundle.message(key)) } else { marker.drop() } return true } fun parseTailLeftFlat(builder: PsiBuilder, level: Int, head: Parser, tail: Parser): Boolean { val marker = builder.mark() if (!head.parse(builder, level)) { marker.drop() return false } else { if (!tail.parse(builder, level)) { marker.drop() report_error_(builder, false) } else { val tailMarker = builder.latestDoneMarker!! val elementType = tailMarker.tokenType (tailMarker as Marker).drop() marker.done(elementType) } return true } } private fun <T> PsiBuilder.lookahead(action: PsiBuilder.() -> T): T { val marker = mark() val result = action() marker.rollbackTo() return result } private fun PsiBuilder.any(): Boolean = advanceIf { true } private fun PsiBuilder.advanceIf(tokenSet: TokenSet): Boolean = advanceIf { tokenType in tokenSet } private inline fun PsiBuilder.advanceIf(crossinline condition: PsiBuilder.() -> Boolean): Boolean { if (condition()) { advanceLexer() return true } else { return false } } fun noMatch(builder: PsiBuilder, level: Int): Boolean = false fun addVariant(builder: PsiBuilder, level: Int, variant: String): Boolean { addVariant(builder, "<$variant>") return true } fun clearVariants(builder: PsiBuilder, level: Int): Boolean { val state = builder.state state.clearVariants(state.currentFrame) return true } fun replaceVariants(builder: PsiBuilder, level: Int, variant: String): Boolean { return clearVariants(builder, level) && addVariant(builder, level, variant) } fun clearError(builder: PsiBuilder, level: Int): Boolean { builder.state.currentFrame.errorReportedAt = -1 return true } fun withProtectedLastVariantPos(builder: PsiBuilder, level: Int, parser: Parser): Boolean { val state = builder.state val prev = state.currentFrame.lastVariantAt if (parser.parse(builder, level)) { return true } else { state.currentFrame.lastVariantAt = prev return false } } private val PsiBuilder.state: ErrorState get() = ErrorState.get(this) fun newLine(builder: PsiBuilder, level: Int): Boolean { builder.eof() // force skip whitespaces val prevStart = builder.rawTokenTypeStart(-1) val currentStart = builder.rawTokenTypeStart(0) return contains(builder.originalText, prevStart, currentStart, '\n') } fun noNewLine(builder: PsiBuilder, level: Int): Boolean = !newLine(builder, level) fun castOperandCheck(builder: PsiBuilder, level: Int): Boolean { return builder.tokenType !== T_LPAREN || builder.lookahead { castOperandCheckInner(this) } } private fun castOperandCheckInner(builder: PsiBuilder): Boolean { var parenCount = 0 while (!builder.eof()) { builder.advanceLexer() val tokenType = builder.tokenType when { tokenType === T_LPAREN -> { parenCount++ } tokenType === T_RPAREN -> { if (parenCount == 0) { // we discovered closing parenthesis and didn't find any commas return true } parenCount-- } tokenType === T_COMMA -> { if (parenCount == 0) { // comma on the same level of parentheses means we are in argument list return false } } } } return false } private val explicitLeftMarker = Key.create<Marker>("groovy.parse.left.marker") /** * Stores [PsiBuilder.getLatestDoneMarker] in user data to be able to use it later in [wrapLeft]. */ fun markLeft(builder: PsiBuilder, level: Int): Boolean { builder[explicitLeftMarker] = builder.latestDoneMarker as? Marker return true } /** * Let sequence `a b c d` result in the following tree: `(a) (b) (c) (d)`. * Then `a b <<markLeft>> c d <<wrapLeft>>` will result in: `(a) ((b) (c) d)` */ fun wrapLeft(builder: PsiBuilder, level: Int): Boolean { val explicitLeft = builder[explicitLeftMarker] ?: return false val latest = builder.latestDoneMarker ?: return false explicitLeft.precede().done(latest.tokenType) (latest as? Marker)?.drop() return true } fun choice(builder: PsiBuilder, level: Int, vararg parsers: Parser): Boolean { assert(parsers.size > 1) for (parser in parsers) { if (parser.parse(builder, level)) return true } return false } fun isBlockParseable(text: CharSequence): Boolean { val lexer = GroovyLexer().apply { start(text) } if (lexer.tokenType !== T_LBRACE) return false lexer.advance() val leftStack = LinkedList<IElementType>().apply { push(T_LBRACE) } while (true) { val type = lexer.tokenType ?: return leftStack.isEmpty() if (leftStack.isEmpty()) { return false } when (type) { T_LBRACE, T_LPAREN -> leftStack.push(type) T_RBRACE -> { if (leftStack.isEmpty() || leftStack.pop() != T_LBRACE) { return false } } T_RPAREN -> { if (leftStack.isEmpty() || leftStack.pop() != T_LPAREN) { return false } } } lexer.advance() } }
apache-2.0
20dc3d3eee0f96559c795d9f69c5afe4
31.539841
140
0.710438
3.972519
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/analytics/aggregated/internal/evaluator/EventDataItemSQLEvaluator.kt
1
14101
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator import javax.inject.Inject import org.hisp.dhis.android.core.analytics.AnalyticsException import org.hisp.dhis.android.core.analytics.aggregated.Dimension import org.hisp.dhis.android.core.analytics.aggregated.DimensionItem import org.hisp.dhis.android.core.analytics.aggregated.MetadataItem import org.hisp.dhis.android.core.analytics.aggregated.internal.AnalyticsServiceEvaluationItem import org.hisp.dhis.android.core.arch.db.access.DatabaseAdapter import org.hisp.dhis.android.core.arch.db.querybuilders.internal.WhereClauseBuilder import org.hisp.dhis.android.core.common.AggregationType import org.hisp.dhis.android.core.enrollment.EnrollmentTableInfo import org.hisp.dhis.android.core.event.EventTableInfo import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValueTableInfo import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValueTableInfo.Columns as tavColumns import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValueTableInfo import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValueTableInfo.Columns as dvColumns internal class EventDataItemSQLEvaluator @Inject constructor( private val databaseAdapter: DatabaseAdapter ) : AnalyticsEvaluator { override fun evaluate( evaluationItem: AnalyticsServiceEvaluationItem, metadata: Map<String, MetadataItem> ): String? { val sqlQuery = getSql(evaluationItem, metadata) return databaseAdapter.rawQuery(sqlQuery)?.use { c -> c.moveToFirst() c.getString(0) } } @Suppress("LongMethod") override fun getSql( evaluationItem: AnalyticsServiceEvaluationItem, metadata: Map<String, MetadataItem> ): String { val items = AnalyticsDimensionHelper.getItemsByDimension(evaluationItem) val eventDataItem = getEventDataItems(evaluationItem)[0] val aggregator = getAggregator(evaluationItem, eventDataItem, metadata) val (valueColumn, fromClause) = getEventDataItemSQLItems(eventDataItem) val whereClause = WhereClauseBuilder().apply { items.entries.forEach { entry -> when (entry.key) { is Dimension.Data -> appendDataWhereClause(entry.value, this) is Dimension.Period -> appendPeriodWhereClause(entry.value, this, metadata, aggregator) is Dimension.OrganisationUnit -> appendOrgunitWhereClause(entry.value, this, metadata) is Dimension.Category -> appendCategoryWhereClause(entry.value, this, metadata) } } appendKeyNumberValue("$eventAlias.${EventTableInfo.Columns.DELETED}", 0) }.build() return when (aggregator) { AggregationType.AVERAGE, AggregationType.SUM, AggregationType.COUNT, AggregationType.MIN, AggregationType.MAX -> { "SELECT ${aggregator.sql}($valueColumn) " + "FROM $fromClause " + "WHERE $whereClause" } AggregationType.AVERAGE_SUM_ORG_UNIT -> { "SELECT SUM($valueColumn) " + "FROM (" + "SELECT AVG($valueColumn) as $valueColumn " + "FROM $fromClause " + "WHERE $whereClause " + "GROUP BY $eventAlias.${EventTableInfo.Columns.ORGANISATION_UNIT}" + ")" } AggregationType.FIRST -> { "SELECT SUM($valueColumn) " + "FROM (${firstOrLastValueClauseByOrunit(valueColumn, fromClause, whereClause, "MIN")})" } AggregationType.FIRST_AVERAGE_ORG_UNIT -> { "SELECT AVG(${dvColumns.VALUE}) " + "FROM (${firstOrLastValueClauseByOrunit(valueColumn, fromClause, whereClause, "MIN")})" } AggregationType.LAST, AggregationType.LAST_IN_PERIOD -> { "SELECT SUM(${dvColumns.VALUE}) " + "FROM (${firstOrLastValueClauseByOrunit(valueColumn, fromClause, whereClause, "MAX")})" } AggregationType.LAST_AVERAGE_ORG_UNIT, AggregationType.LAST_IN_PERIOD_AVERAGE_ORG_UNIT -> { "SELECT AVG(${dvColumns.VALUE}) " + "FROM (${firstOrLastValueClauseByOrunit(valueColumn, fromClause, whereClause, "MAX")})" } AggregationType.CUSTOM, AggregationType.STDDEV, AggregationType.VARIANCE, AggregationType.DEFAULT, AggregationType.NONE -> throw AnalyticsException.UnsupportedAggregationType(aggregator) } } private fun getEventDataItemSQLItems( eventDataItem: DimensionItem.DataItem.EventDataItem ): Pair<String, String> { return when (eventDataItem) { is DimensionItem.DataItem.EventDataItem.DataElement -> Pair(dvColumns.VALUE, dataValueFromClauseWithJoins) is DimensionItem.DataItem.EventDataItem.Attribute -> Pair(tavColumns.VALUE, attributeValueFromClauseWithJoins) } } private val dataValueFromClauseWithJoins = "${TrackedEntityDataValueTableInfo.TABLE_INFO.name()} $dataValueAlias " + "INNER JOIN ${EventTableInfo.TABLE_INFO.name()} $eventAlias " + "ON $dataValueAlias.${dvColumns.EVENT} = " + "$eventAlias.${EventTableInfo.Columns.UID} " private val attributeValueFromClauseWithJoins = "${TrackedEntityAttributeValueTableInfo.TABLE_INFO.name()} $attAlias " + "INNER JOIN ${EnrollmentTableInfo.TABLE_INFO.name()} $enrollmentAlias " + "ON $attAlias.${tavColumns.TRACKED_ENTITY_INSTANCE} = " + "$enrollmentAlias.${EnrollmentTableInfo.Columns.TRACKED_ENTITY_INSTANCE} " + "INNER JOIN ${EventTableInfo.TABLE_INFO.name()} $eventAlias " + "ON $enrollmentAlias.${EnrollmentTableInfo.Columns.UID} = " + "$eventAlias.${EventTableInfo.Columns.ENROLLMENT} " private fun firstOrLastValueClauseByOrunit( valueColumn: String, fromClause: String, whereClause: String, minOrMax: String ): String { val firstOrLastValueClause = "SELECT " + "$valueColumn, " + "$eventAlias.${EventTableInfo.Columns.ORGANISATION_UNIT}, " + "$minOrMax($eventAlias.${EventTableInfo.Columns.EVENT_DATE}) " + "FROM $fromClause " + "WHERE $whereClause " + "AND $eventAlias.${EventTableInfo.Columns.EVENT_DATE} IS NOT NULL " + "GROUP BY $eventAlias.${EventTableInfo.Columns.ORGANISATION_UNIT}, " + "$eventAlias.${EventTableInfo.Columns.ATTRIBUTE_OPTION_COMBO}" return "SELECT SUM($valueColumn) AS $valueColumn " + "FROM ($firstOrLastValueClause) " + "GROUP BY ${EventTableInfo.Columns.ORGANISATION_UNIT}" } private fun appendDataWhereClause( items: List<DimensionItem>, builder: WhereClauseBuilder ): WhereClauseBuilder { val innerClause = items.map { it as DimensionItem.DataItem } .foldRight(WhereClauseBuilder()) { item, innerBuilder -> when (item) { is DimensionItem.DataItem.EventDataItem.DataElement -> { val operandClause = WhereClauseBuilder() .appendKeyStringValue( "$dataValueAlias.${TrackedEntityDataValueTableInfo.Columns.DATA_ELEMENT}", item.dataElement ) .appendKeyStringValue( "$eventAlias.${EventTableInfo.Columns.PROGRAM}", item.program ) .build() innerBuilder.appendOrComplexQuery(operandClause) } is DimensionItem.DataItem.EventDataItem.Attribute -> { val operandClause = WhereClauseBuilder() .appendKeyStringValue( "$attAlias.${TrackedEntityAttributeValueTableInfo.Columns.TRACKED_ENTITY_ATTRIBUTE}", item.attribute ) .appendKeyStringValue( "$eventAlias.${EventTableInfo.Columns.PROGRAM}", item.program ) .build() innerBuilder.appendOrComplexQuery(operandClause) } else -> throw AnalyticsException.InvalidArguments( "Invalid arguments: unexpected " + "dataItem ${item.javaClass.name} in EventDataItem Evaluator." ) } }.build() return builder.appendComplexQuery(innerClause) } private fun appendPeriodWhereClause( items: List<DimensionItem>, builder: WhereClauseBuilder, metadata: Map<String, MetadataItem>, aggregation: AggregationType ): WhereClauseBuilder { val reportingPeriods = AnalyticsEvaluatorHelper.getReportingPeriods(items, metadata) return if (reportingPeriods.isEmpty()) { builder } else { val eventDateColumn = "$eventAlias.${EventTableInfo.Columns.EVENT_DATE}" val periods = AnalyticsEvaluatorHelper.getReportingPeriodsForAggregationType(reportingPeriods, aggregation) val innerClause = periods.joinToString(" OR ") { "(${ AnalyticsEvaluatorHelper.getPeriodWhereClause( columnStart = eventDateColumn, columnEnd = eventDateColumn, period = it ) })" } builder.appendComplexQuery(innerClause) } } private fun appendOrgunitWhereClause( items: List<DimensionItem>, builder: WhereClauseBuilder, metadata: Map<String, MetadataItem> ): WhereClauseBuilder { return AnalyticsEvaluatorHelper.appendOrgunitWhereClause( columnName = "$eventAlias.${EventTableInfo.Columns.ORGANISATION_UNIT}", items = items, builder = builder, metadata = metadata ) } private fun appendCategoryWhereClause( items: List<DimensionItem>, builder: WhereClauseBuilder, metadata: Map<String, MetadataItem> ): WhereClauseBuilder { return AnalyticsEvaluatorHelper.appendCategoryWhereClause( attributeColumnName = "$eventAlias.${EventTableInfo.Columns.ATTRIBUTE_OPTION_COMBO}", disaggregationColumnName = null, items = items, builder = builder, metadata = metadata ) } private fun getEventDataItems( evaluationItem: AnalyticsServiceEvaluationItem, ): List<DimensionItem.DataItem.EventDataItem> { return AnalyticsDimensionHelper.getSingleItemByDimension(evaluationItem) } private fun getAggregator( evaluationItem: AnalyticsServiceEvaluationItem, item: DimensionItem.DataItem.EventDataItem, metadata: Map<String, MetadataItem> ): AggregationType { return if (evaluationItem.aggregationType != AggregationType.DEFAULT) { evaluationItem.aggregationType } else { val aggregationType = when (val metadataItem = metadata[item.id]) { is MetadataItem.EventDataElementItem -> metadataItem.item.aggregationType() is MetadataItem.EventAttributeItem -> metadataItem.item.aggregationType()?.name else -> throw AnalyticsException.InvalidArguments("Invalid arguments: invalid event data item ${item.id}.") } AnalyticsEvaluatorHelper.getElementAggregator(aggregationType) } } companion object { private const val eventAlias = "ev" private const val dataValueAlias = "tdv" private const val attAlias = "av" private const val enrollmentAlias = "en" } }
bsd-3-clause
dd77d1d5b40dfea49c9af1d9643119a3
44.340836
119
0.62648
5.291182
false
false
false
false
AshishKayastha/Movie-Guide
app/src/main/kotlin/com/ashish/movieguide/ui/people/list/PeopleFragment.kt
1
1615
package com.ashish.movieguide.ui.people.list import android.content.Intent import com.ashish.movieguide.R import com.ashish.movieguide.data.models.Person import com.ashish.movieguide.di.modules.FragmentModule import com.ashish.movieguide.di.multibindings.fragment.FragmentComponentBuilderHost import com.ashish.movieguide.ui.base.recyclerview.BaseRecyclerViewFragment import com.ashish.movieguide.ui.base.recyclerview.BaseRecyclerViewMvpView import com.ashish.movieguide.ui.people.detail.PersonDetailActivity import com.ashish.movieguide.utils.Constants.ADAPTER_TYPE_PERSON /** * Created by Ashish on Dec 31. */ class PeopleFragment : BaseRecyclerViewFragment<Person, BaseRecyclerViewMvpView<Person>, PeoplePresenter>() { companion object { @JvmStatic fun newInstance() = PeopleFragment() } override fun injectDependencies(builderHost: FragmentComponentBuilderHost) { builderHost.getFragmentComponentBuilder(PeopleFragment::class.java, PeopleComponent.Builder::class.java) .withModule(FragmentModule(activity)) .build() .inject(this) } override fun getAdapterType() = ADAPTER_TYPE_PERSON override fun getEmptyTextId() = R.string.no_people_available override fun getEmptyImageId() = R.drawable.ic_people_white_100dp override fun getTransitionNameId(position: Int) = R.string.transition_person_profile override fun getDetailIntent(position: Int): Intent? { val people = recyclerViewAdapter.getItem<Person>(position) return PersonDetailActivity.createIntent(activity, people) } }
apache-2.0
bb0081a87858bd2ff33e59dd397867d1
37.47619
112
0.765325
4.562147
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/DefaultFrameHeader.kt
3
2107
// 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.openapi.wm.impl.customFrameDecorations.header import com.intellij.openapi.wm.impl.customFrameDecorations.ResizableCustomFrameTitleButtons import com.intellij.openapi.wm.impl.customFrameDecorations.header.titleLabel.CustomDecorationTitle import com.intellij.ui.awt.RelativeRectangle import com.intellij.util.ui.JBUI import com.jetbrains.CustomWindowDecoration.* import net.miginfocom.swing.MigLayout import java.awt.Frame import javax.swing.JFrame internal class DefaultFrameHeader(frame: JFrame) : FrameHeader(frame) { private val customDecorationTitle = CustomDecorationTitle(frame) init { layout = MigLayout("novisualpadding, ins 0, fillx, gap 0", "[min!][][pref!]") updateCustomDecorationHitTestSpots() productIcon.border = JBUI.Borders.empty(V, H, V, H) customDecorationTitle.view.border = JBUI.Borders.empty(V, 0, V, H) add(productIcon) add(customDecorationTitle.view, "wmin 0, left, growx, center") add(buttonPanes.getView(), "top, wmin pref") setCustomFrameTopBorder({ myState != Frame.MAXIMIZED_VERT && myState != Frame.MAXIMIZED_BOTH }) } override fun updateActive() { customDecorationTitle.setActive(myActive) super.updateActive() } override fun getHitTestSpots(): List<Pair<RelativeRectangle, Int>> { val buttons = buttonPanes as ResizableCustomFrameTitleButtons val hitTestSpots = ArrayList<Pair<RelativeRectangle, Int>>() hitTestSpots.add(Pair(RelativeRectangle(productIcon), OTHER_HIT_SPOT)) hitTestSpots.add(Pair(RelativeRectangle(buttons.minimizeButton), MINIMIZE_BUTTON)) hitTestSpots.add(Pair(RelativeRectangle(buttons.maximizeButton), MAXIMIZE_BUTTON)) hitTestSpots.add(Pair(RelativeRectangle(buttons.restoreButton), MAXIMIZE_BUTTON)) hitTestSpots.add(Pair(RelativeRectangle(buttons.closeButton), CLOSE_BUTTON)) hitTestSpots.addAll(customDecorationTitle.getBoundList().map { Pair(it, OTHER_HIT_SPOT) }) return hitTestSpots } }
apache-2.0
4d8d0a7a925a022656008c9894bef4a3
43.829787
140
0.777409
4.123288
false
true
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/service/graduate/design/DefenseTimeServiceImpl.kt
1
1951
package top.zbeboy.isy.service.graduate.design import org.jooq.DSLContext import org.jooq.Record import org.jooq.Result import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Propagation import org.springframework.transaction.annotation.Transactional import top.zbeboy.isy.domain.Tables.DEFENSE_TIME import top.zbeboy.isy.domain.tables.pojos.DefenseTime import top.zbeboy.isy.domain.tables.records.DefenseTimeRecord /** * Created by zbeboy 2018-02-06 . **/ @Service("defenseTimeService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) open class DefenseTimeServiceImpl @Autowired constructor(dslContext: DSLContext) :DefenseTimeService { private val create: DSLContext = dslContext override fun findByDefenseArrangementId(defenseArrangementId: String): Result<Record> { return create.select() .from(DEFENSE_TIME) .where(DEFENSE_TIME.DEFENSE_ARRANGEMENT_ID.eq(defenseArrangementId)) .orderBy(DEFENSE_TIME.SORT_TIME) .fetch() } @Transactional(propagation = Propagation.REQUIRED, readOnly = false) override fun save(defenseTime: DefenseTime) { create.insertInto<DefenseTimeRecord>(DEFENSE_TIME) .set(DEFENSE_TIME.DEFENSE_ARRANGEMENT_ID, defenseTime.defenseArrangementId) .set(DEFENSE_TIME.DAY_DEFENSE_START_TIME, defenseTime.dayDefenseStartTime) .set(DEFENSE_TIME.DAY_DEFENSE_END_TIME, defenseTime.dayDefenseEndTime) .set(DEFENSE_TIME.SORT_TIME, defenseTime.sortTime) .execute() } override fun deleteByDefenseArrangementId(defenseArrangementId: String) { create.deleteFrom<DefenseTimeRecord>(DEFENSE_TIME) .where(DEFENSE_TIME.DEFENSE_ARRANGEMENT_ID.eq(defenseArrangementId)) .execute() } }
mit
f010db6c76454518db76fd323f5e895f
40.531915
102
0.72937
4.124736
false
false
false
false
skydoves/ElasticViews
elasticviews/src/main/java/com/skydoves/elasticviews/ElasticAnimation.kt
1
4419
/* * The MIT License (MIT) * * Copyright (c) 2017 skydoves * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ @file:Suppress("unused") package com.skydoves.elasticviews import android.view.View import android.view.ViewGroup import android.view.animation.CycleInterpolator import androidx.core.view.ViewCompat import androidx.core.view.ViewPropertyAnimatorListener import com.skydoves.elasticviews.Definitions.DEFAULT_ANIMATION_ANCHOR import com.skydoves.elasticviews.Definitions.DEFAULT_DURATION import com.skydoves.elasticviews.Definitions.DEFAULT_SCALE_X import com.skydoves.elasticviews.Definitions.DEFAULT_SCALE_Y /** ElasticAnimation implements elastic animations for android views or view groups. */ class ElasticAnimation(private val view: View) { @JvmField @set:JvmSynthetic var scaleX = DEFAULT_SCALE_X @JvmField @set:JvmSynthetic var scaleY = DEFAULT_SCALE_Y @JvmField @set:JvmSynthetic var duration = DEFAULT_DURATION @JvmField @set:JvmSynthetic var listener: ViewPropertyAnimatorListener? = null @JvmField @set:JvmSynthetic var finishListener: ElasticFinishListener? = null var isAnimating: Boolean = false private set /** Sets a target elastic scale-x size of the animation. */ fun setScaleX(scaleX: Float): ElasticAnimation = apply { this.scaleX = scaleX } /** Sets a target elastic scale-y size of the animation. */ fun setScaleY(scaleY: Float): ElasticAnimation = apply { this.scaleY = scaleY } /** Sets a duration of the animation. */ fun setDuration(duration: Int): ElasticAnimation = apply { this.duration = duration } /** Sets an animator listener of the animation. */ fun setListener(listener: ViewPropertyAnimatorListener): ElasticAnimation = apply { this.listener = listener } /** An animator listener of the animation. */ fun setOnFinishListener(finishListener: ElasticFinishListener?): ElasticAnimation = apply { this.finishListener = finishListener } /** An [ElasticFinishListener] listener of the animation. */ @JvmSynthetic inline fun setOnFinishListener(crossinline block: () -> Unit): ElasticAnimation = apply { this.finishListener = ElasticFinishListener { block() } } /** starts elastic animation. */ fun doAction() { if (!isAnimating && view.scaleX == 1f) { val animatorCompat = ViewCompat.animate(view) .setDuration(duration.toLong()) .scaleX(scaleX) .scaleY(scaleY) .setInterpolator(CycleInterpolator(DEFAULT_ANIMATION_ANCHOR)).apply { listener?.let { setListener(it) } ?: setListener(object : ViewPropertyAnimatorListener { override fun onAnimationCancel(view: View?) = Unit override fun onAnimationStart(view: View?) { isAnimating = true } override fun onAnimationEnd(view: View?) { finishListener?.onFinished() isAnimating = false } }) } if (view is ViewGroup) { (0 until view.childCount).map { view.getChildAt(it) }.forEach { child -> ViewCompat.animate(child) .setDuration(duration.toLong()) .scaleX(scaleX) .scaleY(scaleY) .setInterpolator(CycleInterpolator(DEFAULT_ANIMATION_ANCHOR)) .withLayer() .start() } } animatorCompat.withLayer().start() } } }
mit
adc42289a7dc46d3a26a4e1233b076ae
34.926829
98
0.708079
4.736334
false
false
false
false
paplorinc/intellij-community
platform/credential-store/src/keePass/KeePassCredentialStore.kt
1
4792
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.credentialStore.keePass import com.intellij.credentialStore.* import com.intellij.credentialStore.kdbx.IncorrectMasterPasswordException import com.intellij.credentialStore.kdbx.KdbxPassword import com.intellij.credentialStore.kdbx.KeePassDatabase import com.intellij.credentialStore.kdbx.loadKdbx import com.intellij.ide.passwordSafe.PasswordStorage import com.intellij.openapi.application.PathManager import com.intellij.openapi.util.io.setOwnerPermissions import com.intellij.util.io.delete import com.intellij.util.io.exists import com.intellij.util.io.writeSafe import org.jetbrains.annotations.TestOnly import java.nio.file.Path import java.nio.file.Paths import java.security.SecureRandom import java.util.* import java.util.concurrent.atomic.AtomicBoolean internal const val DB_FILE_NAME = "c.kdbx" internal fun getDefaultKeePassBaseDirectory() = Paths.get(PathManager.getConfigPath()) internal fun getDefaultMasterPasswordFile() = getDefaultKeePassBaseDirectory().resolve(MASTER_KEY_FILE_NAME) /** * preloadedMasterKey [MasterKey.value] will be cleared */ internal class KeePassCredentialStore constructor(internal val dbFile: Path, private val masterKeyStorage: MasterKeyFileStorage, preloadedDb: KeePassDatabase? = null) : BaseKeePassCredentialStore() { constructor(dbFile: Path, masterKeyFile: Path) : this(dbFile, MasterKeyFileStorage(masterKeyFile), null) private val isNeedToSave: AtomicBoolean override var db: KeePassDatabase = if (preloadedDb == null) { isNeedToSave = AtomicBoolean(false) when { dbFile.exists() -> { val masterPassword = masterKeyStorage.load() ?: throw IncorrectMasterPasswordException(isFileMissed = true) loadKdbx(dbFile, KdbxPassword.createAndClear(masterPassword)) } else -> KeePassDatabase() } } else { isNeedToSave = AtomicBoolean(true) preloadedDb } val masterKeyFile: Path get() = masterKeyStorage.passwordFile @Synchronized @TestOnly fun reload() { val key = masterKeyStorage.load()!! val kdbxPassword = KdbxPassword(key) key.fill(0) db = loadKdbx(dbFile, kdbxPassword) isNeedToSave.set(false) } @Synchronized fun save(masterKeyEncryptionSpec: EncryptionSpec) { if (!isNeedToSave.compareAndSet(true, false) && !db.isDirty) { return } try { val secureRandom = createSecureRandom() val masterKey = masterKeyStorage.load() val kdbxPassword: KdbxPassword if (masterKey == null) { val key = generateRandomMasterKey(masterKeyEncryptionSpec, secureRandom) kdbxPassword = KdbxPassword(key.value!!) masterKeyStorage.save(key) } else { kdbxPassword = KdbxPassword(masterKey) masterKey.fill(0) } dbFile.writeSafe { db.save(kdbxPassword, it, secureRandom) } dbFile.setOwnerPermissions() } catch (e: Throwable) { // schedule save again isNeedToSave.set(true) LOG.error("Cannot save password database", e) } } @Synchronized fun isNeedToSave() = isNeedToSave.get() || db.isDirty @Synchronized fun deleteFileStorage() { try { dbFile.delete() } finally { masterKeyStorage.save(null) } } fun clear() { db.rootGroup.removeGroup(ROOT_GROUP_NAME) isNeedToSave.set(db.isDirty) } @TestOnly fun setMasterPassword(masterKey: MasterKey, secureRandom: SecureRandom) { // KdbxPassword hashes value, so, it can be cleared before file write (to reduce time when master password exposed in memory) saveDatabase(dbFile, db, masterKey, masterKeyStorage, secureRandom) } override fun markDirty() { isNeedToSave.set(true) } } class InMemoryCredentialStore : BaseKeePassCredentialStore(), PasswordStorage { override val db = KeePassDatabase() override fun markDirty() { } } internal fun generateRandomMasterKey(masterKeyEncryptionSpec: EncryptionSpec, secureRandom: SecureRandom): MasterKey { val bytes = secureRandom.generateBytes(512) return MasterKey(Base64.getEncoder().withoutPadding().encode(bytes), isAutoGenerated = true, encryptionSpec = masterKeyEncryptionSpec) } internal fun saveDatabase(dbFile: Path, db: KeePassDatabase, masterKey: MasterKey, masterKeyStorage: MasterKeyFileStorage, secureRandom: SecureRandom) { val kdbxPassword = KdbxPassword(masterKey.value!!) masterKeyStorage.save(masterKey) dbFile.writeSafe { db.save(kdbxPassword, it, secureRandom) } dbFile.setOwnerPermissions() } internal fun copyTo(from: Map<CredentialAttributes, Credentials>, store: CredentialStore) { for ((k, v) in from) { store.set(k, v) } }
apache-2.0
e934b99adf40bfc2ef1eb3216d1aca20
31.385135
199
0.741235
4.478505
false
false
false
false
paplorinc/intellij-community
plugins/git4idea/src/git4idea/stash/GitStashUtils.kt
7
4322
/* * Copyright 2000-2014 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. */ @file:JvmName("GitStashUtils") package git4idea.stash import com.intellij.dvcs.DvcsUtil import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Consumer import git4idea.commands.* import git4idea.config.GitConfigUtil import git4idea.merge.GitConflictResolver import git4idea.ui.StashInfo import git4idea.util.GitUIUtil import git4idea.util.GitUntrackedFilesHelper import git4idea.util.LocalChangesWouldBeOverwrittenHelper import git4idea.util.StringScanner import java.nio.charset.Charset /** * Unstash the given root, handling common error scenarios. */ fun unstash(project: Project, root: VirtualFile, handler: GitLineHandler, conflictResolver: GitConflictResolver) { unstash(project, listOf(root), { handler }, conflictResolver) } /** * Unstash the given roots one by one, handling common error scenarios. * * If there's an error in one of the roots, stop and show the error. * If there's a conflict, show the merge dialog, and if the conflicts get resolved, continue with other roots. */ fun unstash(project: Project, roots: Collection<VirtualFile>, handlerProvider: (VirtualFile) -> GitLineHandler, conflictResolver: GitConflictResolver) { DvcsUtil.workingTreeChangeStarted(project, "Unstash").use { for (root in roots) { val handler = handlerProvider(root) val conflictDetector = GitSimpleEventDetector(GitSimpleEventDetector.Event.MERGE_CONFLICT_ON_UNSTASH) val untrackedFilesDetector = GitUntrackedFilesOverwrittenByOperationDetector(root) val localChangesDetector = GitLocalChangesWouldBeOverwrittenDetector(root, GitLocalChangesWouldBeOverwrittenDetector.Operation.MERGE) handler.addLineListener(conflictDetector) handler.addLineListener(untrackedFilesDetector) handler.addLineListener(localChangesDetector) val result = Git.getInstance().runCommand { handler } VfsUtil.markDirtyAndRefresh(false, true, false, root) if (conflictDetector.hasHappened()) { val conflictsResolved = conflictResolver.merge() if (!conflictsResolved) return } else if (untrackedFilesDetector.wasMessageDetected()) { GitUntrackedFilesHelper.notifyUntrackedFilesOverwrittenBy(project, root, untrackedFilesDetector.relativeFilePaths, "unstash", null) return } else if (localChangesDetector.wasMessageDetected()) { LocalChangesWouldBeOverwrittenHelper.showErrorNotification(project, root, "unstash", localChangesDetector.relativeFilePaths) return } else if (!result.success()) { VcsNotifier.getInstance(project).notifyError("Unstash Failed", result.errorOutputAsHtmlString) return } } } } fun loadStashStack(project: Project, root: VirtualFile, consumer: Consumer<StashInfo>) { loadStashStack(project, root, Charset.forName(GitConfigUtil.getLogEncoding(project, root)), consumer) } private fun loadStashStack(project: Project, root: VirtualFile, charset: Charset, consumer: Consumer<StashInfo>) { val h = GitLineHandler(project, root, GitCommand.STASH.readLockingCommand()) h.setSilent(true) h.addParameters("list") val out: String try { h.charset = charset out = Git.getInstance().runCommand(h).getOutputOrThrow() } catch (e: VcsException) { GitUIUtil.showOperationError(project, e, h.printableCommandLine()) return } val s = StringScanner(out) while (s.hasMoreData()) { consumer.consume(StashInfo(s.boundedToken(':'), s.boundedToken(':'), s.line().trim { it <= ' ' })) } }
apache-2.0
0f38fbf345d112d4cb0533418a3619a7
37.936937
139
0.752429
4.249754
false
false
false
false
neilellis/kontrol
api/src/main/kotlin/kontrol/api/MachineGroup.kt
1
16491
/* * Copyright 2014 Cazcade Limited (http://cazcade.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kontrol.api import kontrol.api.sensors.SensorArray import java.util.SortedSet import kontrol.ext.collections.avgAsDouble import kontrol.ext.collections.median import kontrol.api.sensors.GroupSensorArray /** * @author <a href="http://uk.linkedin.com/in/neilellis">Neil Ellis</a> * @todo document. */ public trait MachineGroup : Monitorable<MachineGroupState> { val controller: Controller val postmortems: List<Postmortem> val upStreamKonfigurator: UpStreamKonfigurator? val downStreamKonfigurator: DownStreamKonfigurator? val stateMachine: StateMachine<MachineGroupState> val sensors: SensorArray; val groupSensors: GroupSensorArray; val defaultMachineRules: StateMachineRules<MachineState> val monitor: Monitor<MachineGroupState, MachineGroup> val machineMonitorRules: SortedSet<MonitorRule<MachineState, Machine>> val groupMonitorRules: SortedSet<MonitorRule<MachineGroupState, MachineGroup>> val upstreamGroups: MutableList<MachineGroup> val downStreamGroups: MutableList<MachineGroup> val min: Int val max: Int val hardMax: Int override fun id(): String = name() override fun state(): MachineGroupState? { return stateMachine.state() } override fun transition(state: MachineGroupState?) { stateMachine.transition(state) } override fun name(): String fun machines(): List<Machine> fun workingSize(): Int = workingMachines().size(); fun activeSize(): Int = enabledMachines().filter { !(it.state() in listOf(MachineState.FAILED, MachineState.STOPPED, MachineState.DEAD, MachineState.BROKEN, MachineState.UPGRADE_FAILED)) }.size(); fun enabledMachines(): List<Machine> = machines().filter { it.enabled } fun brokenMachines(): List<Machine> = machines().filter { it.enabled && it.state() in listOf(MachineState.FAILED, MachineState.DEAD, MachineState.BROKEN, MachineState.UPGRADE_FAILED) } fun deadMachines(): List<Machine> = machines().filter { it.enabled && it.state() in listOf(MachineState.FAILED, MachineState.DEAD) } fun failedMachines(): List<Machine> = machines().filter { it.enabled && it.state() in listOf(MachineState.FAILED) } fun overloadedMachines(): List<Machine> = machines().filter { it.enabled && it.state() in listOf(MachineState.OVERLOADED) } fun workingMachines(): List<Machine> = enabledMachines().filter { it.state() in listOf(MachineState.OK, MachineState.STALE, MachineState.OVERLOADED) } fun workingAndReadyMachines(): List<Machine> = enabledMachines().filter { it.state() in listOf(MachineState.OK, MachineState.STALE) } fun get(value: String): Double? { val groupSensorValue = groupSensors[this, value] if (groupSensorValue != null) { return groupSensorValue.D(); } else { val values = machines() map { it[value] } val average = values.map { it?.D() }.avgAsDouble() val median = values.map { it?.D() }.median() //The average should be within a factor of 5 of the median, if not we use the median instead val result = when { average == null -> null median == null -> null average!! > median!! * 5 -> { median } average!! < median!! / 5 -> { median } else -> { average } } // println("$value was $result") return result; } } fun clearState(machine: Machine) { machine.transition(null); } fun postmortem(machine: Machine): List<PostmortemResult> { val list = postmortems.map { // try { it.perform(machine) // } catch(e: Exception) { // e.printStackTrace(); null // } } return list.filterNotNull() } fun startMonitoring() { println("Started monitoring ${name()}") machines().forEach { it.startMonitoring(machineMonitorRules) } monitor.start(this, stateMachine, groupMonitorRules); } fun stopMonitoring() { monitor.stop(); machines().forEach { it.stopMonitoring() } } fun other(machine: Machine): Machine? { val list = workingAndReadyMachines().filter { it != machine } return if (list.size() > 0) { list.first() } else { null } } fun failAction(machine: Machine, action: (Machine) -> Unit) { println("**** Fail Action for Machine ${machine.ip()}"); try { failover(machine); action(machine); } catch(e: Exception) { e.printStackTrace(); } } fun failover(machine: Machine): MachineGroup { if (other(machine) == null) { throw IllegalStateException("No machine to take over cannot failover") } else { println("**** Failover Machine ${machine.ip()}"); try { downStreamKonfigurator?.onMachineFail(machine, this); upStreamKonfigurator?.onMachineFail(machine, this) upstreamGroups.forEach { it.downstreamFailover(machine, this) } } catch (e: Exception) { throw e } return this; } } fun failback(machine: Machine): MachineGroup { println("**** Failback Machine ${machine.ip()}"); machine.enable() downStreamKonfigurator?.onMachineUnfail(machine, this); upStreamKonfigurator?.onMachineUnfail(machine, this) upstreamGroups.forEach { it.downstreamFailback(machine, this) } return this; } fun downstreamFailover(machine: Machine, machineGroup: MachineGroup) { println("**** Downstream Failover Machine ${machine.ip()} for Group ${machineGroup.name()}"); downStreamKonfigurator?.onDownStreamMachineFail(machine, machineGroup, this) downStreamKonfigurator?.configureDownStream(this) } fun downstreamFailback(machine: Machine, machineGroup: MachineGroup) { println("**** Downstream Failback Machine ${machine.ip()} for Group ${machineGroup.name()}"); downStreamKonfigurator?.onDownStreamMachineUnfail(machine, machineGroup, this) downStreamKonfigurator?.configureDownStream(this) } fun costPerHourInDollars(): Double fun costPerMonthInDollars(): Double = costPerHourInDollars() * 24 * 30 fun configure(): MachineGroup { println("**** Configure ${name()}"); upStreamKonfigurator?.configureUpStream(this) downStreamKonfigurator?.configureDownStream(this) return this; } fun configure(machine: Machine): Machine { println("**** Configure ${name()}"); upStreamKonfigurator?.configureUpStream(this) downStreamKonfigurator?.configureDownStream(this, machine) return machine; } fun expand(): Machine { println("**** Expand ${name()}"); throw UnsupportedOperationException() } fun contract(): MachineGroup { println("**** Contract ${name()}"); return this; } fun rebuild(machine: Machine): MachineGroup { println("**** Re Image Machine ${machine.name()}(${machine.id()})"); return this; } fun fix(machine: Machine): MachineGroup { println("**** Re Start Machine ${machine.name()}(${machine.id()})"); return this; } fun destroy(machine: Machine): MachineGroup { println("**** Destroy Machine ${machine.name()}(${machine.id()})"); return this; } fun on(oldState: MachineState? = null, newState: MachineState, action: ((Machine) -> Unit)? = null): MachineGroup { defaultMachineRules.on(oldState, newState, action) return this } fun allow(oldState: MachineState, newState: MachineState): MachineGroup { defaultMachineRules.allow(oldState, newState) return this } fun allowMachine(pair: Pair<MachineState, MachineState>): MachineGroup { defaultMachineRules.allow(pair.first, pair.second) return this } fun allow(pair: Pair<MachineGroupState, MachineGroupState>): MachineGroup { stateMachine.rules?.allow(pair.first, pair.second) return this } fun onGroup(oldState: MachineGroupState? = null, newState: MachineGroupState, action: (MachineGroup) -> Unit): MachineGroup { stateMachine.rules?.on(oldState, newState, action) return this } override public fun toString(): String { var string: String = "${name()} [${stateMachine.state()}]\n"; for (machine in machines()) { string += "$machine\n"; } string += "Rules:" machineMonitorRules.forEach { string += "$it\n" } return string; } public enum class Recheck { THEN } public class RuleBuilder1(val machineGroup: MachineGroup, val newState: MachineState?) { var controller: Controller? = null; var recheck = false; fun recheck(b: Recheck): RuleBuilder1 { recheck = b == Recheck.THEN; return this; } fun tell(registry: Controller): RuleBuilder1 { this.controller = registry; return this; } fun takeAction(vararg actions: Action): MachineGroup { machineGroup.defaultMachineRules.on<Machine>(null, newState, { machine -> if (!recheck || machine.fsm.state() == newState) { actions.forEach { action -> println("**** TAKING ACTION $action ****");controller?.execute(machineGroup, machine, { true }, action) } } else { println("RECHECK FAILED for $actions") } }); return machineGroup; } fun takeActions(actions: List<Action>): MachineGroup { machineGroup.defaultMachineRules.on<Machine>(null, newState, { machine -> if (!recheck || machine.fsm.state() == newState) { actions.forEach { action -> println("**** TAKING ACTION $action ON ${machine.id()} ****"); controller?.execute(machineGroup, machine, { true }, action) } } else { println("RECHECK FAILED for $actions") } }); return machineGroup; } } class RuleBuilder2(val machineGroup: MachineGroup, val newState: MachineGroupState) { public val yes: Boolean = true; var condition: (MachineGroup) -> Boolean = { true }; var registry: Controller? = null; var recheck = false; fun recheck(b: Recheck): RuleBuilder2 { recheck = b == Recheck.THEN; return this; } fun andTest(condition: (MachineGroup) -> Boolean): RuleBuilder2 { this.condition = condition; return this; } fun use(registry: Controller): RuleBuilder2 { this.registry = registry; return this; } fun takeActions(actions: List<GroupAction>): MachineGroup { actions.forEach { takeAction(it) } return machineGroup; } fun takeAction(action: GroupAction): MachineGroup { machineGroup.stateMachine.rules?.on<MachineGroup>(null, newState, { if (!recheck || !condition(machineGroup) || machineGroup.stateMachine.state() == newState) { registry?.execute(machineGroup, { true }, action) } else { println("RECHECK FAILED for $action") } }); return machineGroup; } } class MachineStateRuleBuilder(val machineGroup: MachineGroup, val state: MachineState?) { var condition: (Machine) -> Boolean = { true }; var confirms = 0; var previousStates = hashSetOf<MachineState?>() fun andTest(condition: (Machine) -> Boolean): MachineStateRuleBuilder { this.condition = condition; return this; } fun after(seconds: Int): MachineStateRuleBuilder { this.confirms = seconds / machineGroup.controller.frequency; return this; } fun ifStateIn(states: List<MachineState?>): MachineStateRuleBuilder { previousStates.addAll(states) return this; } fun seconds(name: String) { machineGroup.machineMonitorRules.add(MonitorRule(state, condition, confirms, name, previousStates)) println("Added rule for $name") } } class MachineGroupStateRuleBuilder(val machineGroup: MachineGroup, val state: MachineGroupState) { var condition: (MachineGroup) -> Boolean = { true }; var confirms = 0; var previousStates = hashSetOf<MachineGroupState?>() fun andTest(condition: (MachineGroup) -> Boolean): MachineGroupStateRuleBuilder { this.condition = condition; return this; } fun after(seconds: Int): MachineGroupStateRuleBuilder { this.confirms = seconds / machineGroup.controller.frequency; return this; } fun ifStateIn(states: List<MachineGroupState?>): MachineGroupStateRuleBuilder { previousStates.addAll(states) return this; } fun seconds(name: String) { machineGroup.groupMonitorRules.add(MonitorRule(state, condition, confirms, name, previousStates)) println("Added rule for $name") } } fun whenMachine(newState: MachineState): RuleBuilder1 { return RuleBuilder1(this, newState); } fun whenGroup(newState: MachineGroupState): RuleBuilder2 { return RuleBuilder2(this, newState); } fun memberIs(state: MachineState?): MachineStateRuleBuilder { return MachineStateRuleBuilder(this, state); } fun becomes(state: MachineGroupState): MachineGroupStateRuleBuilder { return MachineGroupStateRuleBuilder(this, state); } } /* fun List<SensorValue?>.sumSensors(): Double? { return if (this.size() > 0) this.map { if (it?.v != null) it?.D() else null } .reduce { x, y -> when { x == null -> y y == null -> x else -> x + y } } else null } fun List<SensorValue?>.median(): Double { val sorted = this .map { if (it?.v != null) it?.D() else null } .filterNotNull() .sortBy { it } if (sorted.size() > 0) { return sorted.get(sorted.size() / 2) } else { return 0.0; } } fun List<SensorValue?>.avg(): Double? { val sum = this.sumSensors() val size = this.filterNotNull().size return when { sum == null -> null size == 0 -> 0.0 else -> sum / size }; } fun List<SensorValue?>.max(): Double? { return if (this.size() > 0) this.map { if (it?.v != null) it?.v.toString().toDouble() else null } .reduce { x, y -> when { x == null -> y y == null -> x x!! > y!! -> x else -> y } } else null } fun List<SensorValue?>.min(): Double? { return if (this.size() > 0) this.map { if (it?.v != null) it?.v.toString().toDouble() else null } .reduce { x, y -> when { x == null -> y y == null -> x x!! < y!! -> x else -> y } } else null } */
apache-2.0
bbcc7b7c7d9a8828730f9538cbecdb28
33.07438
200
0.589049
4.486126
false
false
false
false
PlanBase/PdfLayoutMgr2
src/main/java/com/planbase/pdf/lm2/attributes/DimAndPageNums.kt
1
2136
// Copyright 2017 PlanBase Inc. // // This file is part of PdfLayoutMgr2 // // PdfLayoutMgr is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // PdfLayoutMgr is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with PdfLayoutMgr. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>. // // If you wish to use this code with proprietary software, // contact PlanBase Inc. <https://planbase.com> to purchase a commercial license. package com.planbase.pdf.lm2.attributes import com.planbase.pdf.lm2.utils.Dim import kotlin.math.max import kotlin.math.min /** The dimensions of a rendered item plus the start and end page numbers */ open class DimAndPageNums(val dim:Dim, val pageNums:IntRange) { fun maxExtents(nums: IntRange): IntRange = maxExtents(pageNums, nums) override fun hashCode(): Int = dim.hashCode() + pageNums.hashCode() override fun equals(other: Any?): Boolean = (other != null) && (other is DimAndPageNums) && (dim == other.dim) && (pageNums == other.pageNums) override fun toString(): String = "DimAndPageNums($dim, $pageNums)" companion object { // const val INVALID_PAGE_NUM = Int.MIN_VALUE @JvmField val INVALID_PAGE_RANGE = IntRange.EMPTY fun maxExtents(nums1: IntRange, nums2: IntRange): IntRange = when { nums1 === INVALID_PAGE_RANGE -> nums2 nums2 === INVALID_PAGE_RANGE -> nums1 nums1 == nums2 -> nums1 else -> IntRange(min(nums1.start, nums2.start), max(nums1.endInclusive, nums2.endInclusive)) } } }
agpl-3.0
c447515b9f6c64abbe0bed83ba5ef78f
36.491228
112
0.66339
4.25498
false
false
false
false
google/intellij-community
jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/junit/HamcrestAssertionsConverterInspection.kt
3
10753
// 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.codeInspection.test.junit import com.intellij.analysis.JvmAnalysisBundle import com.intellij.codeInspection.* import com.intellij.codeInspection.test.junit.HamcrestCommonClassNames.* import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.CommonClassNames.* import com.intellij.uast.UastHintedVisitorAdapter import com.intellij.util.castSafelyTo import com.siyeh.ig.junit.JUnitCommonClassNames.* import com.siyeh.ig.psiutils.TypeUtils import org.jetbrains.uast.* import org.jetbrains.uast.generate.UastElementFactory import org.jetbrains.uast.generate.getUastElementFactory import org.jetbrains.uast.generate.importMemberOnDemand import org.jetbrains.uast.generate.replace import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor import javax.swing.JComponent class HamcrestAssertionsConverterInspection : AbstractBaseUastLocalInspectionTool() { @JvmField var importMemberOnDemand = true override fun createOptionsPanel(): JComponent = SingleCheckboxOptionsPanel( JvmAnalysisBundle.message("jvm.inspections.migrate.assert.to.matcher.option"), this, "importMemberOnDemand" ) override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { val matcherFqn = JavaPsiFacade.getInstance(holder.project).findClass(ORG_HAMCREST_MATCHERS, holder.file.resolveScope)?.qualifiedName ?: JavaPsiFacade.getInstance(holder.project).findClass(ORG_HAMCREST_CORE_MATCHERS, holder.file.resolveScope)?.qualifiedName ?: return PsiElementVisitor.EMPTY_VISITOR return UastHintedVisitorAdapter.create( holder.file.language, HamcrestAssertionsConverterVisitor(holder, matcherFqn, importMemberOnDemand), arrayOf(UCallExpression::class.java), directOnly = true ) } } private class HamcrestAssertionsConverterVisitor( private val holder: ProblemsHolder, private val matcherFqn: String, private val importMemberOnDemand: Boolean, ) : AbstractUastNonRecursiveVisitor() { private fun isBooleanAssert(methodName: String) = methodName == "assertTrue" || methodName == "assertFalse" override fun visitCallExpression(node: UCallExpression): Boolean { val methodName = node.methodName ?: return true if (!JUNIT_ASSERT_METHODS.contains(methodName)) return true val method = node.resolveToUElement() ?: return true val methodClass = method.getContainingUClass() ?: return true if (methodClass.qualifiedName != ORG_JUNIT_ASSERT && methodClass.qualifiedName != JUNIT_FRAMEWORK_ASSERT) return true if (isBooleanAssert(methodName)) { val args = node.valueArguments val resolveScope = node.sourcePsi?.resolveScope ?: return true val psiFacade = JavaPsiFacade.getInstance(holder.project) if (args.last() is UBinaryExpression && psiFacade.findClass(ORG_HAMCREST_NUMBER_ORDERING_COMPARISON, resolveScope) == null) return true } val message = JvmAnalysisBundle.message("jvm.inspections.migrate.assert.to.matcher.description", "assertThat()") holder.registerUProblem(node, message, MigrateToAssertThatQuickFix(matcherFqn, importMemberOnDemand)) return true } companion object { private val JUNIT_ASSERT_METHODS = listOf( "assertArrayEquals", "assertEquals", "assertNotEquals", "assertSame", "assertNotSame", "assertNotNull", "assertNull", "assertTrue", "assertFalse" ) } } private class MigrateToAssertThatQuickFix(private val matcherClassFqn: String, private val importMemberOnDemand: Boolean) : LocalQuickFix { override fun getFamilyName(): String = CommonQuickFixBundle.message("fix.replace.with.x", "assertThat()") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement ?: return val call = element.getUastParentOfType<UCallExpression>() ?: return val factory = call.getUastElementFactory(project) ?: return val methodName = call.methodName ?: return val arguments = call.valueArguments.toMutableList() val method = call.resolveToUElement()?.castSafelyTo<UMethod>() ?: return val message = if (TypeUtils.typeEquals(JAVA_LANG_STRING, method.uastParameters.first().type)) { arguments.removeFirst() } else null val (left, right) = when (methodName) { "assertTrue", "assertFalse" -> { val conditionArgument = arguments.lastOrNull() ?: return when (conditionArgument) { is UBinaryExpression -> { val operator = conditionArgument.operator.normalize(methodName) val matchExpression = factory.buildMatchExpression(operator, conditionArgument.rightOperand) ?: return conditionArgument.leftOperand to matchExpression } is UQualifiedReferenceExpression -> { val conditionCall = conditionArgument.selector.castSafelyTo<UCallExpression>() ?: return val conditionMethodName = conditionCall.methodName ?: return val matchExpression = if (methodName.contains("False")) { factory.createMatchExpression( "not", factory.buildMatchExpression(conditionMethodName, conditionArgument.receiver, conditionCall.valueArguments.first()) ) } else { factory.buildMatchExpression(conditionMethodName, conditionArgument.receiver, conditionCall.valueArguments.first()) } ?: return conditionArgument.receiver to matchExpression } else -> return } } "assertEquals", "assertArrayEquals" -> { val matchExpression = factory.createMatchExpression("is", arguments.first()) ?: return arguments.last() to matchExpression } "assertNotEquals" -> { val matchExpression = factory.createMatchExpression( "not", factory.createMatchExpression("is", arguments.first()) ) ?: return arguments.last() to matchExpression } "assertSame" -> { val matchExpression = factory.createMatchExpression("sameInstance", arguments.first()) ?: return arguments.last() to matchExpression } "assertNotSame" -> { val matchExpression = factory.createMatchExpression( "not", factory.createMatchExpression("sameInstance", arguments.first()) ) ?: return arguments.last() to matchExpression } "assertNull" -> { val matchExpression = factory.createMatchExpression("nullValue") ?: return arguments.first() to matchExpression } "assertNotNull" -> { val matchExpression = factory.createMatchExpression("notNullValue") ?: return arguments.first() to matchExpression } else -> return } if (importMemberOnDemand) { val assertThatCall = factory.createAssertThat(listOfNotNull(message, left, right)) ?: return val replaced = call.getQualifiedParentOrThis().replace(assertThatCall)?.castSafelyTo<UQualifiedReferenceExpression>() ?: return var toImport = replaced while (true) { val imported = toImport.importMemberOnDemand()?.castSafelyTo<UCallExpression>() ?: return toImport = imported.valueArguments.lastOrNull()?.castSafelyTo<UQualifiedReferenceExpression>() ?: return } } } private fun UastElementFactory.createAssertThat(params: List<UExpression>): UExpression? { val matchAssert = createQualifiedReference(ORG_HAMCREST_MATCHER_ASSERT, null) ?: return null return createCallExpression(matchAssert, "assertThat", params, null, UastCallKind.METHOD_CALL) ?.getQualifiedParentOrThis() } private fun UastElementFactory.createMatchExpression(name: String, parameter: UExpression? = null): UExpression? { val paramList = if (parameter == null) emptyList() else listOf(parameter) val matcher = createQualifiedReference(matcherClassFqn, null) ?: return null return createCallExpression(matcher, name, paramList, null, UastCallKind.METHOD_CALL)?.getQualifiedParentOrThis() } private fun UExpression.isPrimitiveType() = getExpressionType() is PsiPrimitiveType private fun UastElementFactory.createIdEqualsExpression(param: UExpression) = if (param.isPrimitiveType()) createMatchExpression("is", param) else createMatchExpression("sameInstance", param) private fun UastBinaryOperator.inverse(): UastBinaryOperator = when (this) { UastBinaryOperator.EQUALS -> UastBinaryOperator.NOT_EQUALS UastBinaryOperator.NOT_EQUALS -> UastBinaryOperator.EQUALS UastBinaryOperator.IDENTITY_EQUALS -> UastBinaryOperator.IDENTITY_NOT_EQUALS UastBinaryOperator.IDENTITY_NOT_EQUALS -> UastBinaryOperator.IDENTITY_EQUALS UastBinaryOperator.GREATER -> UastBinaryOperator.LESS_OR_EQUALS UastBinaryOperator.LESS -> UastBinaryOperator.GREATER_OR_EQUALS UastBinaryOperator.GREATER_OR_EQUALS -> UastBinaryOperator.LESS UastBinaryOperator.LESS_OR_EQUALS -> UastBinaryOperator.GREATER else -> this } fun UastBinaryOperator.normalize(methodName: String): UastBinaryOperator = if (methodName.contains("False")) inverse() else this private fun UastElementFactory.buildMatchExpression(operator: UastBinaryOperator, param: UExpression): UExpression? = when (operator) { UastBinaryOperator.EQUALS -> createMatchExpression("is", param) UastBinaryOperator.NOT_EQUALS -> createMatchExpression("not", createMatchExpression("is", param)) UastBinaryOperator.IDENTITY_EQUALS -> createIdEqualsExpression(param) UastBinaryOperator.IDENTITY_NOT_EQUALS -> createMatchExpression("not", createIdEqualsExpression(param)) UastBinaryOperator.GREATER -> createMatchExpression("greaterThan", param) UastBinaryOperator.LESS -> createMatchExpression("lessThan", param) UastBinaryOperator.GREATER_OR_EQUALS -> createMatchExpression("greaterThanOrEqualTo", param) UastBinaryOperator.LESS_OR_EQUALS -> createMatchExpression("lessThanOrEqualTo", param) else -> null } private fun UastElementFactory.buildMatchExpression(methodName: String, receiver: UExpression, param: UExpression): UExpression? { return when (methodName) { "contains" -> { if (receiver.getExpressionType()?.isInheritorOf(JAVA_UTIL_COLLECTION) == true) { return createMatchExpression("hasItem", param) } if (TypeUtils.typeEquals(JAVA_LANG_STRING, param.getExpressionType())) { return createMatchExpression("containsString", param) } return createMatchExpression("contains", param) } "equals" -> createMatchExpression("is", param) else -> null } } }
apache-2.0
f25c9c571c61810fc4be898c2ff7176e
48.557604
141
0.738678
5.108314
false
false
false
false
fedepaol/BikeSharing
app/src/main/java/com/whiterabbit/pisabike/screens/favs/StationsFavsPresenterImpl.kt
1
3086
package com.whiterabbit.pisabike.screens.list import android.location.Location import com.whiterabbit.pisabike.model.Station import com.whiterabbit.pisabike.schedule.SchedulersProvider import com.whiterabbit.pisabike.storage.BikesProvider import pl.charmas.android.reactivelocation.ReactiveLocationProvider import rx.Observable import rx.subscriptions.CompositeSubscription import java.util.concurrent.TimeUnit import kotlin.comparisons.compareBy class StationsFavsPresenterImpl(val provider : BikesProvider, val schedulers : SchedulersProvider, val locationProvider : ReactiveLocationProvider) : StationsFavsPresenter { var data : ListData? = null lateinit var subscription : CompositeSubscription var view : StationsFavsView? = null data class ListData(var list : List<Station>, var location : Location) override fun attachToView(v: StationsFavsView) { view = v subscription = CompositeSubscription() val favsStations = provider.stationsObservables.map({stations -> stations.filter { s -> s.isFavourite }}) val sub = Observable.combineLatest(locationProvider.lastKnownLocation.take(1), favsStations, { l: Location, stations: List<Station> -> ListData(stations, l) }).subscribeOn(schedulers.provideBackgroundScheduler()) .observeOn(schedulers.provideMainThreadScheduler()) .subscribe { d -> data = d updateStations(d.list, d.location) } subscription.add(sub) val sub1 = v.getStationSelectedObservable().subscribeOn(schedulers.provideMainThreadScheduler()) .observeOn(schedulers.provideMainThreadScheduler()) .subscribe { s -> view?.displayStationOnMap(s)} subscription.add(sub1) val sub2 = v.preferredToggledObservable() .subscribeOn(schedulers.provideBackgroundScheduler()) .flatMap { station -> provider.changePreferredStatus(station.name, !station.isFavourite) } .observeOn(schedulers.provideBackgroundScheduler()) .subscribe({} , {_ : Throwable -> run {} }) subscription.add(sub2) } fun updateStations(stations : List<Station>, location : Location) { view?.displayStations(stations, location) if (stations.isNotEmpty()) { view?.toggleListVisibility(true) view?.toggleEmptyListVisibility(false) } else { view?.toggleListVisibility(false) view?.toggleEmptyListVisibility(true) } } override fun detachFromView() { subscription.unsubscribe() view = null } }
gpl-3.0
3ba96b2154c10651b2ab5c5aa33e6404
40.146667
106
0.594621
5.757463
false
false
false
false
JetBrains/intellij-community
platform/lang-impl/src/com/intellij/tools/ToolEditorDialogPanel.kt
1
4319
// 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.tools import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.ui.RawCommandLineEditor import com.intellij.ui.components.JBCheckBox import com.intellij.ui.dsl.builder.AlignX import com.intellij.ui.dsl.builder.BottomGap import com.intellij.ui.dsl.builder.MAX_LINE_LENGTH_NO_WRAP import com.intellij.ui.dsl.builder.panel import com.intellij.ui.layout.selected import javax.swing.JPanel import javax.swing.JTextField private const val ADVANCED_OPTIONS_EXPANDED_KEY = "ExternalToolDialog.advanced.expanded" private const val ADVANCED_OPTIONS_EXPANDED_DEFAULT = false internal class ToolEditorDialogPanel { @JvmField val panel = panel { row(ToolsBundle.message("label.tool.name")) { nameField = textField() .align(AlignX.FILL) .resizableColumn() .focused() .component groupCombo = comboBox(emptyList<String>()) .align(AlignX.FILL) .resizableColumn() .label(ToolsBundle.message("label.tool.group")) .applyToComponent { isEditable = true } .component } row(ToolsBundle.message("label.tool.description")) { descriptionField = textField() .align(AlignX.FILL) .component } group(ToolsBundle.message("border.title.tool.settings")) { row(ToolsBundle.message("label.tool.program")) { programField = textFieldWithBrowseButton() .align(AlignX.FILL) .component } row(ToolsBundle.message("label.tool.arguments")) { argumentsField = cell(RawCommandLineEditor()) .align(AlignX.FILL) .component } row(ToolsBundle.message("label.tool.working.directory")) { workingDirField = textFieldWithBrowseButton() .align(AlignX.FILL) .component } }.bottomGap(BottomGap.NONE) row { additionalOptionsPanel = cell(JPanel()) .align(AlignX.FILL) .component } collapsibleGroup(ToolsBundle.message("dialog.separator.advanced.options")) { row { synchronizedAfterRunCheckbox = checkBox(ToolsBundle.message("checkbox.synchronize.files.after.execution")) .component } row { useConsoleCheckbox = checkBox(ToolsBundle.message("checkbox.open.console.for.tool.output")) .component } indent { row { showConsoleOnStdOutCheckbox = checkBox(ToolsBundle.message("checkbox.make.console.active.on.message.in.stdout")) .component } row { showConsoleOnStdErrCheckbox = checkBox(ToolsBundle.message("checkbox.make.console.active.on.message.in.stderr")) .component } }.enabledIf(useConsoleCheckbox.selected) row(ToolsBundle.message("label.output.filters")) { outputFilterField = cell(RawCommandLineEditor(ToolEditorDialog.OUTPUT_FILTERS_SPLITTER, ToolEditorDialog.OUTPUT_FILTERS_JOINER)) .comment(ToolsBundle.message("label.each.line.is.a.regex.available.macros.file.path.line.and.column"), maxLineLength = MAX_LINE_LENGTH_NO_WRAP) .align(AlignX.FILL) .component } }.apply { expanded = PropertiesComponent.getInstance().getBoolean(ADVANCED_OPTIONS_EXPANDED_KEY, ADVANCED_OPTIONS_EXPANDED_DEFAULT) packWindowHeight = true addExpandedListener { PropertiesComponent.getInstance().setValue(ADVANCED_OPTIONS_EXPANDED_KEY, it, ADVANCED_OPTIONS_EXPANDED_DEFAULT) } } } lateinit var nameField: JTextField lateinit var groupCombo: ComboBox<String> lateinit var descriptionField: JTextField lateinit var programField: TextFieldWithBrowseButton lateinit var argumentsField: RawCommandLineEditor lateinit var workingDirField: TextFieldWithBrowseButton lateinit var additionalOptionsPanel: JPanel lateinit var synchronizedAfterRunCheckbox: JBCheckBox lateinit var useConsoleCheckbox: JBCheckBox lateinit var showConsoleOnStdOutCheckbox: JBCheckBox lateinit var showConsoleOnStdErrCheckbox: JBCheckBox lateinit var outputFilterField: RawCommandLineEditor }
apache-2.0
97239de5291277c06431689297197b4a
35.601695
136
0.709192
4.575212
false
false
false
false
vvv1559/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/DefaultListOrMapTypeCalculator.kt
2
4475
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.lang.typing import com.intellij.openapi.util.RecursionManager.doPreventingRecursion import com.intellij.psi.CommonClassNames import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClassType import com.intellij.psi.PsiType import com.intellij.psi.util.InheritanceUtil.isInheritor import com.intellij.psi.util.PsiUtil.substituteTypeParameter import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrSpreadArgument import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression import org.jetbrains.plugins.groovy.lang.psi.impl.GrMapType import org.jetbrains.plugins.groovy.lang.psi.impl.GrTupleType import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames class DefaultListOrMapTypeCalculator : GrTypeCalculator<GrListOrMap> { override fun getType(expression: GrListOrMap): PsiType? { if (expression.isMap) { return getMapTypeFromDiamond(expression) ?: GrMapType.createFromNamedArgs(expression, expression.namedArguments) } else { return getListTypeFromDiamond(expression) ?: getTupleType(expression) } } private fun getMapTypeFromDiamond(expression: GrListOrMap): PsiType? { val namedArgs = expression.namedArguments if (namedArgs.isNotEmpty()) return null val lType = PsiImplUtil.inferExpectedTypeForDiamond(expression) ?: return null if (lType !is PsiClassType || !isInheritor(lType, CommonClassNames.JAVA_UTIL_MAP)) return null val scope = expression.resolveScope val facade = JavaPsiFacade.getInstance(expression.project) val hashMap = facade.findClass(GroovyCommonClassNames.JAVA_UTIL_LINKED_HASH_MAP, scope) ?: return null return facade.elementFactory.createType( hashMap, substituteTypeParameter(lType, CommonClassNames.JAVA_UTIL_MAP, 0, false), substituteTypeParameter(lType, CommonClassNames.JAVA_UTIL_MAP, 1, false) ) } private fun getListTypeFromDiamond(expression: GrListOrMap): PsiType? { val initializers = expression.initializers if (initializers.isNotEmpty()) return null val lType = PsiImplUtil.inferExpectedTypeForDiamond(expression) if (lType !is PsiClassType || !isInheritor(lType, CommonClassNames.JAVA_UTIL_LIST)) return null val scope = expression.resolveScope val facade = JavaPsiFacade.getInstance(expression.project) val arrayList = facade.findClass(CommonClassNames.JAVA_UTIL_ARRAY_LIST, scope) ?: facade.findClass(CommonClassNames.JAVA_UTIL_LIST, scope) ?: return null return facade.elementFactory.createType( arrayList, substituteTypeParameter(lType, CommonClassNames.JAVA_UTIL_LIST, 0, false) ) } private fun getTupleType(expression: GrListOrMap): PsiType? { val initializers = expression.initializers return object : GrTupleType(expression.resolveScope, JavaPsiFacade.getInstance(expression.project)) { override fun inferComponents(): Array<PsiType?> { return initializers.flatMap { doGetComponentTypes(it) ?: return PsiType.EMPTY_ARRAY }.toTypedArray() } private fun doGetComponentTypes(initializer: GrExpression): Collection<PsiType>? { return doPreventingRecursion(initializer, false) { if (initializer is GrSpreadArgument) { (initializer.argument.type as? GrTupleType)?.componentTypes?.toList() } else { TypesUtil.boxPrimitiveType(initializer.type, initializer.manager, initializer.resolveScope)?.let { listOf(it) } } } } override fun isValid(): Boolean = initializers.all { it.isValid } } } }
apache-2.0
549783474d4ad6a7ac6ba384a76a7a02
41.216981
123
0.75486
4.524772
false
false
false
false
googlemaps/android-places-demos
snippets/app/src/main/java/com/google/places/kotlin/CurrentPlaceActivity.kt
1
2592
package com.google.places.kotlin import android.Manifest.permission import android.content.pm.PackageManager import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import com.google.android.gms.common.api.ApiException import com.google.android.libraries.places.api.model.Place import com.google.android.libraries.places.api.model.PlaceLikelihood import com.google.android.libraries.places.api.net.FindCurrentPlaceRequest import com.google.android.libraries.places.api.net.PlacesClient class CurrentPlaceActivity : AppCompatActivity() { private lateinit var placesClient: PlacesClient override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // [START maps_places_current_place] // Use fields to define the data types to return. val placeFields: List<Place.Field> = listOf(Place.Field.NAME) // Use the builder to create a FindCurrentPlaceRequest. val request: FindCurrentPlaceRequest = FindCurrentPlaceRequest.newInstance(placeFields) // Call findCurrentPlace and handle the response (first check that the user has granted permission). if (ContextCompat.checkSelfPermission(this, permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { val placeResponse = placesClient.findCurrentPlace(request) placeResponse.addOnCompleteListener { task -> if (task.isSuccessful) { val response = task.result for (placeLikelihood: PlaceLikelihood in response?.placeLikelihoods ?: emptyList()) { Log.i( TAG, "Place '${placeLikelihood.place.name}' has likelihood: ${placeLikelihood.likelihood}" ) } } else { val exception = task.exception if (exception is ApiException) { Log.e(TAG, "Place not found: ${exception.statusCode}") } } } } else { // A local method to request required permissions; // See https://developer.android.com/training/permissions/requesting getLocationPermission() } // [END maps_places_current_place] } private fun getLocationPermission() { TODO() } companion object { private val TAG = CurrentPlaceActivity::class.java.simpleName } }
apache-2.0
206c580b49f93969a9dfd9f3b1870736
38.892308
113
0.646605
5.072407
false
false
false
false
scenerygraphics/scenery
src/main/kotlin/graphics/scenery/backends/vulkan/VulkanDevice.kt
1
37882
package graphics.scenery.backends.vulkan import graphics.scenery.backends.vulkan.VulkanDevice.DescriptorPool.Companion.maxSets import graphics.scenery.utils.LazyLogger import org.lwjgl.system.MemoryStack.stackPush import org.lwjgl.system.MemoryUtil import org.lwjgl.system.MemoryUtil.memUTF8 import org.lwjgl.vulkan.* import org.lwjgl.vulkan.EXTDebugUtils.VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT import org.lwjgl.vulkan.EXTDebugUtils.vkSetDebugUtilsObjectNameEXT import org.lwjgl.vulkan.VK10.* import org.lwjgl.vulkan.VK11.VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM import org.lwjgl.vulkan.VK11.VK_FORMAT_G8B8G8R8_422_UNORM import java.util.* import java.util.concurrent.ConcurrentHashMap typealias QueueIndexWithProperties = Pair<Int, VkQueueFamilyProperties> /** * Describes a Vulkan device attached to an [instance] and a [physicalDevice]. * * @author Ulrik Guenther <[email protected]> */ open class VulkanDevice( val instance: VkInstance, val physicalDevice: VkPhysicalDevice, val deviceData: DeviceData, extensionsQuery: (VkPhysicalDevice) -> Array<String> = { arrayOf() }, validationLayers: Array<String> = arrayOf(), val headless: Boolean = false, val debugEnabled: Boolean = false ) { protected val logger by LazyLogger() /** Stores available memory types on the device. */ val memoryProperties: VkPhysicalDeviceMemoryProperties /** Stores the Vulkan-internal device. */ val vulkanDevice: VkDevice /** Stores available queue indices. */ val queues: Queues /** Stores available extensions */ val extensions = ArrayList<String>() private val descriptorPools = ArrayList<DescriptorPool>(5) /** * Enum class for GPU device types. Can be unknown, other, integrated, discrete, virtual or CPU. */ enum class DeviceType { Unknown, Other, IntegratedGPU, DiscreteGPU, VirtualGPU, CPU } /** * Class to store device-specific metadata. * * @property[vendor] The vendor name of the device. * @property[name] The name of the device. * @property[driverVersion] The driver version as represented as string. * @property[apiVersion] The Vulkan API version supported by the device, represented as string. * @property[type] The [DeviceType] of the GPU. */ data class DeviceData(val vendor: String, val name: String, val driverVersion: String, val apiVersion: String, val type: DeviceType, val properties: VkPhysicalDeviceProperties, val formats: Map<Int, VkFormatProperties>) { fun toFullString() = "$vendor $name ($type, driver version $driverVersion, Vulkan API $apiVersion)" } /** * Data class to store device-specific queue indices. * * @property[presentQueue] The index of the present queue * @property[graphicsQueue] The index of the graphics queue * @property[computeQueue] The index of the compute queue */ data class Queues(val presentQueue: QueueIndexWithProperties, val transferQueue: QueueIndexWithProperties, val graphicsQueue: QueueIndexWithProperties, val computeQueue: QueueIndexWithProperties) init { val result = stackPush().use { stack -> val pQueueFamilyPropertyCount = stack.callocInt(1) vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount, null) val queueCount = pQueueFamilyPropertyCount.get(0) val queueProps = VkQueueFamilyProperties.calloc(queueCount) vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount, queueProps) var graphicsQueueFamilyIndex = 0 var transferQueueFamilyIndex = 0 var computeQueueFamilyIndex = 0 val presentQueueFamilyIndex = 0 var index = 0 while (index < queueCount) { if (queueProps.get(index).queueFlags() and VK_QUEUE_GRAPHICS_BIT != 0) { graphicsQueueFamilyIndex = index } if (queueProps.get(index).queueFlags() and VK_QUEUE_TRANSFER_BIT != 0) { transferQueueFamilyIndex = index } if (queueProps.get(index).queueFlags() and VK_QUEUE_COMPUTE_BIT != 0) { computeQueueFamilyIndex = index } index++ } val requiredFamilies = listOf( graphicsQueueFamilyIndex, transferQueueFamilyIndex, computeQueueFamilyIndex) .groupBy { it } logger.info("Creating ${requiredFamilies.size} distinct queue groups") /** * Adjusts the queue count of a [VkDeviceQueueCreateInfo] struct to [num]. */ fun VkDeviceQueueCreateInfo.queueCount(num: Int): VkDeviceQueueCreateInfo { VkDeviceQueueCreateInfo.nqueueCount(this.address(), num) return this } val queueCreateInfo = VkDeviceQueueCreateInfo.calloc(requiredFamilies.size, stack) requiredFamilies.entries.forEachIndexed { i, (familyIndex, group) -> val size = minOf(queueProps.get(familyIndex).queueCount(), group.size) logger.debug("Adding queue with familyIndex=$familyIndex, size=$size") val pQueuePriorities = stack.callocFloat(group.size) for(pr in 0 until group.size) { pQueuePriorities.put(pr, 1.0f) } queueCreateInfo[i] .sType(VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO) .queueFamilyIndex(familyIndex) .pQueuePriorities(pQueuePriorities) .queueCount(size) } val extensionsRequested = extensionsQuery.invoke(physicalDevice) logger.debug("Requested extensions: ${extensionsRequested.joinToString(", ")} ${extensionsRequested.size}") val utf8Exts = extensionsRequested.map { stack.UTF8(it) } // allocate enough pointers for required extensions, plus the swapchain extension // if we are not running in headless mode val extensions = if(!headless) { val e = stack.callocPointer(1 + extensionsRequested.size) e.put(stack.UTF8(KHRSwapchain.VK_KHR_SWAPCHAIN_EXTENSION_NAME)) e } else { stack.callocPointer(extensionsRequested.size) } utf8Exts.forEach { extensions.put(it) } extensions.flip() if(validationLayers.isNotEmpty()) { logger.warn("Enabled Vulkan API validations. Expect degraded performance.") } val ppEnabledLayerNames = stack.callocPointer(validationLayers.size) var i = 0 while (i < validationLayers.size) { ppEnabledLayerNames.put(memUTF8(validationLayers[i])) i++ } ppEnabledLayerNames.flip() // all enabled features here have >99% availability according to http://vulkan.gpuinfo.org/listfeatures.php val enabledFeatures = VkPhysicalDeviceFeatures.calloc(stack) vkGetPhysicalDeviceFeatures(physicalDevice, enabledFeatures) if(!enabledFeatures.samplerAnisotropy() || !enabledFeatures.largePoints() // || !enabledFeatures.geometryShader() || !enabledFeatures.fillModeNonSolid()) { throw IllegalStateException("Device does not support required features.") } val deviceCreateInfo = VkDeviceCreateInfo.calloc(stack) .sType(VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO) .pNext(MemoryUtil.NULL) .pQueueCreateInfos(queueCreateInfo) .ppEnabledExtensionNames(extensions) .ppEnabledLayerNames(ppEnabledLayerNames) .pEnabledFeatures(enabledFeatures) logger.debug("Creating device...") val pDevice = stack.callocPointer(1) val err = vkCreateDevice(physicalDevice, deviceCreateInfo, null, pDevice) val device = pDevice.get(0) if (err != VK_SUCCESS) { throw IllegalStateException("Failed to create device: " + VU.translate(err)) } logger.debug("Device successfully created.") val memoryProperties = VkPhysicalDeviceMemoryProperties.calloc() vkGetPhysicalDeviceMemoryProperties(physicalDevice, memoryProperties) VulkanRenderer.DeviceAndGraphicsQueueFamily(VkDevice(device, physicalDevice, deviceCreateInfo), graphicsQueueFamilyIndex, computeQueueFamilyIndex, presentQueueFamilyIndex, transferQueueFamilyIndex, memoryProperties) Triple(VkDevice(device, physicalDevice, deviceCreateInfo), Queues( presentQueue = presentQueueFamilyIndex to queueProps[presentQueueFamilyIndex], transferQueue = transferQueueFamilyIndex to queueProps[transferQueueFamilyIndex], computeQueue = computeQueueFamilyIndex to queueProps[computeQueueFamilyIndex], graphicsQueue = graphicsQueueFamilyIndex to queueProps[graphicsQueueFamilyIndex]), memoryProperties ) } vulkanDevice = result.first queues = result.second memoryProperties = result.third extensions.addAll(extensionsQuery.invoke(physicalDevice)) extensions.add(KHRSwapchain.VK_KHR_SWAPCHAIN_EXTENSION_NAME) descriptorPools.add(createDescriptorPool()) logger.debug("Created logical Vulkan device on ${deviceData.vendor} ${deviceData.name}") } /** * Returns if a given format [feature] is supported for a given [format]. * Assume [optimalTiling], otherwise optimal tiling. */ fun formatFeatureSupported(format: Int, feature: Int, optimalTiling: Boolean): Boolean { val properties = deviceData.formats[format] ?: return false return if(!optimalTiling) { properties.linearTilingFeatures() and feature != 0 } else { properties.optimalTilingFeatures() and feature != 0 } } /** * Returns the available memory types on this devices that * bear [typeBits] and [flags]. May return an empty list in case * the device does not support the given types and flags. */ fun getMemoryType(typeBits: Int, flags: Int): List<Int> { var bits = typeBits val types = ArrayList<Int>(5) for (i in 0 until memoryProperties.memoryTypeCount()) { if (bits and 1 == 1) { if ((memoryProperties.memoryTypes(i).propertyFlags() and flags) == flags) { types.add(i) } } bits = bits shr 1 } if(types.isEmpty()) { logger.warn("Memory type $flags not found for device $this (${vulkanDevice.address().toHexString()}") } return types } /** * Creates a command pool with a given [queueNodeIndex] for this device. */ fun createCommandPool(queueNodeIndex: Int): Long { return stackPush().use { stack -> val cmdPoolInfo = VkCommandPoolCreateInfo.calloc(stack) .sType(VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO) .queueFamilyIndex(queueNodeIndex) .flags(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) val pCmdPool = stack.callocLong(1) val err = vkCreateCommandPool(vulkanDevice, cmdPoolInfo, null, pCmdPool) val commandPool = pCmdPool.get(0) if (err != VK_SUCCESS) { throw IllegalStateException("Failed to create command pool: " + VU.translate(err)) } logger.debug("Created command pool ${commandPool.toHexString()}") commandPool } } /** * Destroys the command pool given by [commandPool]. */ fun destroyCommandPool(commandPool: Long) { vkDestroyCommandPool(vulkanDevice, commandPool, null) } /** * Returns a string representation of this device. */ override fun toString(): String { return "${deviceData.vendor} ${deviceData.name}" } /** * Destroys this device, waiting for all operations to finish before. */ fun close() { logger.debug("Closing device ${deviceData.vendor} ${deviceData.name}...") deviceData.formats.forEach { (_, props) -> props.free() } vkDeviceWaitIdle(vulkanDevice) descriptorSetLayouts.forEach { removeDescriptorSetLayout(it.value) } descriptorPools.forEach { vkDestroyDescriptorPool(vulkanDevice, it.handle, null) } descriptorPools.clear() vkDestroyDevice(vulkanDevice, null) logger.debug("Device closed.") memoryProperties.free() } fun createSemaphore(): Long { return stackPush().use { stack -> val semaphoreCreateInfo = VkSemaphoreCreateInfo.calloc(stack) .sType(VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO) .pNext(MemoryUtil.NULL) .flags(0) val semaphore = VU.getLong("vkCreateSemaphore", { vkCreateSemaphore([email protected], semaphoreCreateInfo, null, this) }, {}) logger.debug("Created semaphore {}", semaphore.toHexString().lowercase()) semaphore } } fun removeSemaphore(semaphore: Long) { logger.debug("Removing semaphore {}", semaphore.toHexString().lowercase()) vkDestroySemaphore(this.vulkanDevice, semaphore, null) } data class DescriptorPool(val handle: Long, var free: Int = maxTextures + maxUBOs + maxInputAttachments + maxUBOs) { companion object { val maxTextures = 2048 * 16 val maxUBOs = 2048 val maxInputAttachments = 32 val maxSets = maxUBOs * 2 + maxInputAttachments + maxTextures } } private fun createDescriptorPool(): DescriptorPool { return stackPush().use { stack -> // We need to tell the API the number of max. requested descriptors per type val typeCounts = VkDescriptorPoolSize.calloc(5, stack) typeCounts[0] .type(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER) .descriptorCount(DescriptorPool.maxTextures) typeCounts[1] .type(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) .descriptorCount(DescriptorPool.maxUBOs) typeCounts[2] .type(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) .descriptorCount(DescriptorPool.maxInputAttachments) typeCounts[3] .type(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) .descriptorCount(DescriptorPool.maxUBOs) typeCounts[4] .type(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) .descriptorCount(DescriptorPool.maxTextures) // Create the global descriptor pool // All descriptors used in this example are allocated from this pool val descriptorPoolInfo = VkDescriptorPoolCreateInfo.calloc(stack) .sType(VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO) .pNext(MemoryUtil.NULL) .pPoolSizes(typeCounts) .maxSets(maxSets)// Set the max. number of sets that can be requested .flags(VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT) val handle = VU.getLong("vkCreateDescriptorPool", { vkCreateDescriptorPool(vulkanDevice, descriptorPoolInfo, null, this) }, {}) DescriptorPool(handle, maxSets) } } /** * Creates a new descriptor set with default type uniform buffer. */ fun createDescriptorSet( descriptorSetLayout: Long, bindingCount: Int, ubo: VulkanUBO.UBODescriptor, type: Int = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER ): Long { val pool = findAvailableDescriptorPool() pool.free -= 1 logger.debug("Creating descriptor set with $bindingCount bindings, DSL=$descriptorSetLayout") return stackPush().use { stack -> val pDescriptorSetLayout = stack.callocLong(1).put(0, descriptorSetLayout) val allocInfo = VkDescriptorSetAllocateInfo.calloc(stack) .sType(VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO) .pNext(MemoryUtil.NULL) .descriptorPool(findAvailableDescriptorPool().handle) .pSetLayouts(pDescriptorSetLayout) val descriptorSet = VU.getLong("createDescriptorSet", { vkAllocateDescriptorSets(vulkanDevice, allocInfo, this) }, {}) val d = VkDescriptorBufferInfo.calloc(1, stack) .buffer(ubo.buffer) .range(ubo.range) .offset(ubo.offset) val writeDescriptorSet = VkWriteDescriptorSet.calloc(bindingCount, stack) (0 until bindingCount).forEach { i -> writeDescriptorSet[i] .sType(VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET) .pNext(MemoryUtil.NULL) .dstSet(descriptorSet) .dstBinding(i) .pBufferInfo(d) .descriptorType(type) .descriptorCount(1) } vkUpdateDescriptorSets(vulkanDevice, writeDescriptorSet, null) descriptorSet } } /** * Creates a new dynamic descriptor set. */ fun createDescriptorSetDynamic( descriptorSetLayout: Long, bindingCount: Int, buffer: VulkanBuffer, size: Long = 2048L ): Long { val pool = findAvailableDescriptorPool() pool.free -= 1 logger.debug("Creating dynamic descriptor set with $bindingCount bindings, DSL=${descriptorSetLayout.toHexString()}") return stackPush().use { stack -> val pDescriptorSetLayout = stack.callocLong(1).put(0, descriptorSetLayout) val allocInfo = VkDescriptorSetAllocateInfo.calloc() .sType(VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO) .pNext(MemoryUtil.NULL) .descriptorPool(findAvailableDescriptorPool().handle) .pSetLayouts(pDescriptorSetLayout) val descriptorSet = VU.getLong("createDescriptorSet", { vkAllocateDescriptorSets(vulkanDevice, allocInfo, this) }, {}) val d = VkDescriptorBufferInfo.calloc(1, stack) .buffer(buffer.vulkanBuffer) .range(size) .offset(0L) val writeDescriptorSet = VkWriteDescriptorSet.calloc(bindingCount, stack) (0 until bindingCount).forEach { i -> writeDescriptorSet[i] .sType(VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET) .pNext(MemoryUtil.NULL) .dstSet(descriptorSet) .dstBinding(i) .dstArrayElement(0) .pBufferInfo(d) .descriptorType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) .descriptorCount(1) } vkUpdateDescriptorSets(vulkanDevice, writeDescriptorSet, null) descriptorSet } } /** * Updates an existing [descriptorSet] to use a [newBuffer] for backing. */ fun updateBufferForDescriptorSetDynamic( descriptorSet: Long, bindingCount: Int, newBuffer: VulkanBuffer ): Long { logger.debug("Updating dynamic descriptor set {} with {} bindings, to use backing buffer {}}", descriptorSet.toHexString(), bindingCount, newBuffer.vulkanBuffer.toHexString()) return stackPush().use { stack -> val d = VkDescriptorBufferInfo.calloc(1, stack) .buffer(newBuffer.vulkanBuffer) .range(2048) .offset(0L) val writeDescriptorSet = VkWriteDescriptorSet.calloc(bindingCount, stack) (0 until bindingCount).forEach { i -> writeDescriptorSet[i] .sType(VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET) .pNext(MemoryUtil.NULL) .dstSet(descriptorSet) .dstBinding(i) .dstArrayElement(0) .pBufferInfo(d) .descriptorType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) .descriptorCount(1) } vkUpdateDescriptorSets(vulkanDevice, writeDescriptorSet, null) descriptorSet } } /** * Creates and returns a new descriptor set layout on this device with the members declared in [types], which is * a [List] of a Pair of a type, associated with a count (e.g. Dynamic UBO to 1). The base binding can be set with [binding]. * The shader stages to which the DSL should be visible can be set via [shaderStages]. */ fun createDescriptorSetLayout(types: List<Pair<Int, Int>>, binding: Int = 0, shaderStages: Int): Long { val current = descriptorSetLayouts[DescriptorSetLayout(types, binding, shaderStages)] if( current != null) { return current } return stackPush().use { stack -> val layoutBinding = VkDescriptorSetLayoutBinding.calloc(types.size, stack) types.forEachIndexed { i, (type, count) -> layoutBinding[i] .binding(i + binding) .descriptorType(type) .descriptorCount(count) .stageFlags(shaderStages) .pImmutableSamplers(null) } val descriptorLayout = VkDescriptorSetLayoutCreateInfo.calloc(stack) .sType(VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO) .pNext(MemoryUtil.NULL) .pBindings(layoutBinding) val descriptorSetLayout = VU.getLong("vkCreateDescriptorSetLayout", { vkCreateDescriptorSetLayout(vulkanDevice, descriptorLayout, null, this) }, {}) logger.debug("Created DSL ${descriptorSetLayout.toHexString()} with ${types.size} descriptors.") descriptorSetLayouts[DescriptorSetLayout(types, binding, shaderStages)] = descriptorSetLayout descriptorSetLayout } } data class DescriptorSetLayout(val types: List<Pair<Int, Int>>, val binding: Int, val stages: Int) private val descriptorSetLayouts = ConcurrentHashMap<DescriptorSetLayout, Long>() /** * Destroys a given descriptor set layout. */ fun removeDescriptorSetLayout(dsl: Long) { val current = descriptorSetLayouts.filterValues { it == dsl }.toList() if(current.isEmpty()) { return } logger.debug("Removing ${current.size} known descriptor set layout (${dsl.toHexString().lowercase()})") current.forEach { vkDestroyDescriptorSetLayout(this.vulkanDevice, it.second, null) descriptorSetLayouts.remove(it.first) } } /** * Creates and returns a new descriptor set layout on this device with one member of [type], which is by default a * dynamic uniform buffer. The [binding] and number of descriptors ([descriptorNum], [descriptorCount]) can be * customized, as well as the shader stages to which the DSL should be visible ([shaderStages]). */ fun createDescriptorSetLayout(type: Int = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, binding: Int = 0, descriptorNum: Int = 1, descriptorCount: Int = 1, shaderStages: Int = VK_SHADER_STAGE_ALL): Long { val types = (0 until descriptorNum).map { type to descriptorCount }.toList() return createDescriptorSetLayout(types, binding, shaderStages) } /** * Creates and returns a new descriptor set for a framebuffer given as [target]. The set will be * allocated on this device, from the first available descriptor ppol, and conforms to an * existing descriptor set layout [descriptorSetLayout]. Additional * metadata about the framebuffer needs to be given via [rt], and a subset of the framebuffer can * be selected by setting [onlyFor] to the respective name of the attachment. */ fun createRenderTargetDescriptorSet( descriptorSetLayout: Long, target: VulkanFramebuffer, imageLoadStore: Boolean = false, onlyFor: List<VulkanFramebuffer.VulkanFramebufferAttachment>? = null ): Long { val pool = findAvailableDescriptorPool() pool.free -= 1 return stackPush().use { stack -> val (type, layout) = if (!imageLoadStore) { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER to VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL } else { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE to VK_IMAGE_LAYOUT_GENERAL } val pDescriptorSetLayout = stack.callocLong(1).put(0, descriptorSetLayout) val allocInfo = VkDescriptorSetAllocateInfo.calloc(stack) .sType(VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO) .pNext(MemoryUtil.NULL) .descriptorPool(findAvailableDescriptorPool().handle) .pSetLayouts(pDescriptorSetLayout) val descriptorSet = VU.getLong("createDescriptorSet", { vkAllocateDescriptorSets(vulkanDevice, allocInfo, this) }, {}) val targets = onlyFor ?: target.attachments.values.toList() val writeDescriptorSet = VkWriteDescriptorSet.calloc(targets.size, stack) targets.forEachIndexed { i, attachment -> val d = VkDescriptorImageInfo.calloc(1, stack) d .imageView(attachment.imageView.get(0)) .sampler(target.framebufferSampler.get(0)) .imageLayout(layout) writeDescriptorSet[i] .sType(VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET) .pNext(MemoryUtil.NULL) .dstSet(descriptorSet) .dstBinding(i) .dstArrayElement(0) .pImageInfo(d) .descriptorType(type) .descriptorCount(1) } vkUpdateDescriptorSets(vulkanDevice, writeDescriptorSet, null) logger.debug("Creating framebuffer attachment descriptor $descriptorSet set with ${ if (onlyFor != null) { 1 } else { target.attachments.size } } bindings, DSL=$descriptorSetLayout") descriptorSet } } /** * Finds and returns the first available descriptor pool that can provide at least * [requiredSets] descriptor sets. * * Creates a new pool if necessary. */ fun findAvailableDescriptorPool(requiredSets: Int = 1): DescriptorPool { val available = descriptorPools.firstOrNull { it.free >= requiredSets } return if(available == null) { descriptorPools.add(createDescriptorPool()) descriptorPools.first { it.free >= requiredSets } } else { available } } /* Translated from public static final int VK_OBJECT_TYPE_UNKNOWN = 0; public static final int VK_OBJECT_TYPE_INSTANCE = 1; public static final int VK_OBJECT_TYPE_PHYSICAL_DEVICE = 2; public static final int VK_OBJECT_TYPE_DEVICE = 3; public static final int VK_OBJECT_TYPE_QUEUE = 4; public static final int VK_OBJECT_TYPE_SEMAPHORE = 5; public static final int VK_OBJECT_TYPE_COMMAND_BUFFER = 6; public static final int VK_OBJECT_TYPE_FENCE = 7; public static final int VK_OBJECT_TYPE_DEVICE_MEMORY = 8; public static final int VK_OBJECT_TYPE_BUFFER = 9; public static final int VK_OBJECT_TYPE_IMAGE = 10; public static final int VK_OBJECT_TYPE_EVENT = 11; public static final int VK_OBJECT_TYPE_QUERY_POOL = 12; public static final int VK_OBJECT_TYPE_BUFFER_VIEW = 13; public static final int VK_OBJECT_TYPE_IMAGE_VIEW = 14; public static final int VK_OBJECT_TYPE_SHADER_MODULE = 15; public static final int VK_OBJECT_TYPE_PIPELINE_CACHE = 16; public static final int VK_OBJECT_TYPE_PIPELINE_LAYOUT = 17; public static final int VK_OBJECT_TYPE_RENDER_PASS = 18; public static final int VK_OBJECT_TYPE_PIPELINE = 19; public static final int VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT = 20; public static final int VK_OBJECT_TYPE_SAMPLER = 21; public static final int VK_OBJECT_TYPE_DESCRIPTOR_POOL = 22; public static final int VK_OBJECT_TYPE_DESCRIPTOR_SET = 23; public static final int VK_OBJECT_TYPE_FRAMEBUFFER = 24; public static final int VK_OBJECT_TYPE_COMMAND_POOL = 25; */ enum class VulkanObjectType { Unknown, Instance, PhysicalDevice, Device, Queue, Semaphore, CommandBuffer, Fence, DeviceMemory, Buffer, Image, Event, QueryPool, BufferView, ImageView, ShaderModule, PipelineCache, PipelineLayout, RenderPass, Pipeline, DescriptorSetLayout, Sampler, DescriptorPool, DescriptorSet, Framebuffer, CommandPool } fun tag(obj: Long, type: VulkanObjectType, name: String) { if(!debugEnabled) { return } stackPush().use { stack -> val nameInfo = VkDebugUtilsObjectNameInfoEXT.calloc(stack) val nameBuffer = stack.UTF8(name) nameInfo.sType(VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT) .objectHandle(obj) .objectType(type.ordinal) .pObjectName(nameBuffer) vkSetDebugUtilsObjectNameEXT(this.vulkanDevice, nameInfo ) } } /** * Utility functions for [VulkanDevice]. */ companion object { val logger by LazyLogger() /** * Data class for defining device/driver-specific workarounds. * * @property[filter] A lambda to define the condition to trigger this workaround, must return a boolean. * @property[description] A string description of the cause and effects of the workaround * @property[workaround] A lambda that will be executed if this [DeviceWorkaround] is triggered. */ data class DeviceWorkaround(val filter: (DeviceData) -> Boolean, val description: String, val workaround: (DeviceData) -> Any) val deviceWorkarounds: List<DeviceWorkaround> = listOf( // DeviceWorkaround( // { it.vendor == "Nvidia" && it.driverVersion.substringBefore(".").toInt() >= 396 }, // "Nvidia 396.xx series drivers are unsupported due to crashing bugs in the driver") { // if(System.getenv("__GL_NextGenCompiler") == null) { // logger.warn("The graphics driver version you are using (${it.driverVersion}) contains a bug that prevents scenery's Vulkan renderer from functioning correctly.") // logger.warn("Please set the environment variable __GL_NextGenCompiler to 0 and restart the application to work around this issue.") // logger.warn("For this session, scenery will fall back to the OpenGL renderer in 20 seconds.") // Thread.sleep(20000) // // throw RuntimeException("Bug in graphics driver, falling back to OpenGL") // } // } ) private fun toDeviceType(vkDeviceType: Int): DeviceType { return when(vkDeviceType) { 0 -> DeviceType.Other 1 -> DeviceType.IntegratedGPU 2 -> DeviceType.DiscreteGPU 3 -> DeviceType.VirtualGPU 4 -> DeviceType.CPU else -> DeviceType.Unknown } } private fun vendorToString(vendor: Int): String = when(vendor) { 0x1002 -> "AMD" 0x10DE -> "Nvidia" 0x8086 -> "Intel" 0x106B -> "🍎" else -> "(Unknown vendor)" } private fun decodeDriverVersion(version: Int) = Triple( version and 0xFFC00000.toInt() shr 22, version and 0x003FF000 shr 12, version and 0x00000FFF ) /** * Gets the supported format ranges for image formats, * adapted from https://github.com/KhronosGroup/Vulkan-Tools/blob/master/vulkaninfo/vulkaninfo.h * * Ranges are additive! */ private val supportedFormatRanges = hashMapOf( (1 to 0) to (VK_FORMAT_UNDEFINED..VK_FORMAT_ASTC_12x12_SRGB_BLOCK), (1 to 1) to (VK_FORMAT_G8B8G8R8_422_UNORM..VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM) ) private fun driverVersionToString(version: Int) = decodeDriverVersion(version).toList().joinToString(".") /** * Creates a [VulkanDevice] in a given [instance] from a physical device, requesting extensions * given by [additionalExtensions]. The device selection is done in a fuzzy way by [physicalDeviceFilter], * such that one can filter for certain vendors, e.g. */ @JvmStatic fun fromPhysicalDevice(instance: VkInstance, physicalDeviceFilter: (Int, DeviceData) -> Boolean, additionalExtensions: (VkPhysicalDevice) -> Array<String> = { arrayOf() }, validationLayers: Array<String> = arrayOf(), headless: Boolean = false, debugEnabled: Boolean = false): VulkanDevice { val physicalDeviceCount = VU.getInt("Enumerate physical devices") { vkEnumeratePhysicalDevices(instance, this, null) } if (physicalDeviceCount < 1) { throw IllegalStateException("No Vulkan-compatible devices found!") } val physicalDevices = VU.getPointers("Getting Vulkan physical devices", physicalDeviceCount) { vkEnumeratePhysicalDevices(instance, intArrayOf(physicalDeviceCount), this) } var devicePreference = 0 logger.info("Physical devices: ") val deviceList = ArrayList<DeviceData>(10) for (i in 0 until physicalDeviceCount) { val device = VkPhysicalDevice(physicalDevices.get(i), instance) val properties: VkPhysicalDeviceProperties = VkPhysicalDeviceProperties.calloc() vkGetPhysicalDeviceProperties(device, properties) val apiVersion = with(decodeDriverVersion(properties.apiVersion())) { this.first to this.second } val formatRanges = (0 .. apiVersion.second).mapNotNull { minor -> supportedFormatRanges[1 to minor] } val formats = formatRanges.flatMap { range -> range.map { format -> val formatProperties = VkFormatProperties.calloc() vkGetPhysicalDeviceFormatProperties(device, format, formatProperties) format to formatProperties } }.toMap() val deviceData = DeviceData( vendor = vendorToString(properties.vendorID()), name = properties.deviceNameString(), driverVersion = driverVersionToString(properties.driverVersion()), apiVersion = driverVersionToString(properties.apiVersion()), type = toDeviceType(properties.deviceType()), properties = properties, formats = formats) if(physicalDeviceFilter.invoke(i, deviceData)) { logger.debug("Device filter matches device $i, $deviceData") devicePreference = i } deviceList.add(deviceData) } deviceList.forEachIndexed { i, device -> val selected = if (devicePreference == i) { "(selected)" } else { device.properties.free() "" } logger.info(" $i: ${device.toFullString()} $selected") } val selectedDevice = physicalDevices.get(devicePreference) val selectedDeviceData = deviceList[devicePreference] if(System.getProperty("scenery.DisableDeviceWorkarounds", "false")?.toBoolean() != true) { deviceWorkarounds.forEach { if (it.filter.invoke(selectedDeviceData)) { logger.warn("Workaround activated: ${it.description}") it.workaround.invoke(selectedDeviceData) } } } else { logger.warn("Device-specific workarounds disabled upon request, expect weird things to happen.") } val physicalDevice = VkPhysicalDevice(selectedDevice, instance) physicalDevices.free() return VulkanDevice(instance, physicalDevice, selectedDeviceData, additionalExtensions, validationLayers, headless, debugEnabled) } } }
lgpl-3.0
d0553bc6582e1c66d45ce5b0be4134a8
39.512299
225
0.61018
4.914883
false
false
false
false
dinosaurwithakatana/Google-I-O-Bingo
app/src/main/kotlin/butterknife/KotterKnife.kt
2
5066
package butterknife import android.app.Activity import android.app.Dialog import android.app.Fragment import android.support.v4.app.Fragment as SupportFragment import android.support.v7.widget.RecyclerView.ViewHolder import android.view.View import android.view.ViewGroup import kotlin.properties.ReadOnlyProperty public fun <T : View> ViewGroup.bindView(id: Int): ReadOnlyProperty<Any, T> = ViewBinding(id) public fun <T : View> Activity.bindView(id: Int): ReadOnlyProperty<Any, T> = ViewBinding(id) public fun <T : View> Dialog.bindView(id: Int): ReadOnlyProperty<Any, T> = ViewBinding(id) public fun <T : View> Fragment.bindView(id: Int): ReadOnlyProperty<Any, T> = ViewBinding(id) public fun <T : View> SupportFragment.bindView(id: Int): ReadOnlyProperty<Any, T> = ViewBinding(id) public fun <T : View> ViewHolder.bindView(id: Int): ReadOnlyProperty<Any, T> = ViewBinding(id) public fun <T : View> ViewGroup.bindOptionalView(id: Int): ReadOnlyProperty<Any, T?> = OptionalViewBinding(id) public fun <T : View> Activity.bindOptionalView(id: Int): ReadOnlyProperty<Any, T?> = OptionalViewBinding(id) public fun <T : View> Dialog.bindOptionalView(id: Int): ReadOnlyProperty<Any, T?> = OptionalViewBinding(id) public fun <T : View> Fragment.bindOptionalView(id: Int): ReadOnlyProperty<Any, T?> = OptionalViewBinding(id) public fun <T : View> SupportFragment.bindOptionalView(id: Int): ReadOnlyProperty<Any, T?> = OptionalViewBinding(id) public fun <T : View> ViewHolder.bindOptionalView(id: Int): ReadOnlyProperty<Any, T?> = OptionalViewBinding(id) public fun <T : View> ViewGroup.bindViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = ViewListBinding(ids) public fun <T : View> Activity.bindViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = ViewListBinding(ids) public fun <T : View> Dialog.bindViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = ViewListBinding(ids) public fun <T : View> Fragment.bindViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = ViewListBinding(ids) public fun <T : View> SupportFragment.bindViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = ViewListBinding(ids) public fun <T : View> ViewHolder.bindViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = ViewListBinding(ids) public fun <T : View> ViewGroup.bindOptionalViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = OptionalViewListBinding(ids) public fun <T : View> Activity.bindOptionalViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = OptionalViewListBinding(ids) public fun <T : View> Dialog.bindOptionalViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = OptionalViewListBinding(ids) public fun <T : View> Fragment.bindOptionalViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = OptionalViewListBinding(ids) public fun <T : View> SupportFragment.bindOptionalViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = OptionalViewListBinding(ids) public fun <T : View> ViewHolder.bindOptionalViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = OptionalViewListBinding(ids) private fun findView<T : View>(thisRef: Any, id: Int): T? { [suppress("UNCHECKED_CAST")] return when (thisRef) { is View -> thisRef.findViewById(id) is Activity -> thisRef.findViewById(id) is Dialog -> thisRef.findViewById(id) is Fragment -> thisRef.getView().findViewById(id) is SupportFragment -> thisRef.getView().findViewById(id) is ViewHolder -> thisRef.itemView.findViewById(id) else -> throw IllegalStateException("Unable to find views on type.") } as T? } private class ViewBinding<T : View>(val id: Int) : ReadOnlyProperty<Any, T> { private val lazy = Lazy<T>() override fun get(thisRef: Any, desc: PropertyMetadata): T = lazy.get { findView<T>(thisRef, id) ?: throw IllegalStateException("View ID $id for '${desc.name}' not found.") } } private class OptionalViewBinding<T : View>(val id: Int) : ReadOnlyProperty<Any, T?> { private val lazy = Lazy<T?>() override fun get(thisRef: Any, desc: PropertyMetadata): T? = lazy.get { findView<T>(thisRef, id) } } private class ViewListBinding<T : View>(val ids: IntArray) : ReadOnlyProperty<Any, List<T>> { private var lazy = Lazy<List<T>>() override fun get(thisRef: Any, desc: PropertyMetadata): List<T> = lazy.get { ids.map { id -> findView<T>(thisRef, id) ?: throw IllegalStateException("View ID $id for '${desc.name}' not found.") } } } private class OptionalViewListBinding<T : View>(val ids: IntArray) : ReadOnlyProperty<Any, List<T>> { private var lazy = Lazy<List<T>>() override fun get(thisRef: Any, desc: PropertyMetadata): List<T> = lazy.get { ids.map { id -> findView<T>(thisRef, id) }.filterNotNull() } } private class Lazy<T> { private object EMPTY private var value: Any? = EMPTY fun get(initializer: () -> T): T { if (value == EMPTY) { value = initializer.invoke() } [suppress("UNCHECKED_CAST")] return value as T } }
mit
d10c9e24c3b9884a8572a357b2fb3932
50.181818
135
0.710225
3.876052
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-apis/src/main/kotlin/slatekit/apis/Access.kt
1
1676
package slatekit.apis import slatekit.apis.setup.Parentable /* ktlint-disable */ object AccessLevel { /** * Reference to a parent value * e.g. If set on Action, this refers to its parent API */ const val PARENT = ApiConstants.parent /** * For external clients * NOTES: * 1. Client SDK enabled * 2. API Discovery enabled */ const val PUBLIC = "public" /** * For internal company / server to server use. * NOTES: * 1. Client SDK disabled * 2. API Discovery enabled */ const val INTERNAL = "internal" /** * PRIVATE : No docs will be generated, discovery is prevented * NOTES: * 1. Client SDK disabled * 2. API Discovery disabled * 3. Additional API key required */ const val PRIVATE = "private" } sealed class Access(val value:Int, override val name:String) : Parentable<Access> { object Private : Access(0, AccessLevel.PRIVATE) object Internal : Access(1, AccessLevel.INTERNAL) object Public : Access(2, AccessLevel.PUBLIC) object Parent : Access(3, AccessLevel.PARENT) fun min(other:Access?):Access { return if(other != null && other.value < this.value) other else this } companion object { fun parse(name:String): Access { return when(name) { AccessLevel.INTERNAL -> Access.Internal AccessLevel.PARENT -> Access.Parent AccessLevel.PRIVATE -> Access.Private AccessLevel.PUBLIC -> Access.Public else -> Access.Private } } } } /* ktlint-enable */
apache-2.0
20d1d9fbac364b516b74decc38f41258
24.014925
84
0.589499
4.445623
false
false
false
false
leafclick/intellij-community
platform/indexing-impl/src/com/intellij/index/PrebuiltIndexProvider.kt
1
4230
// 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.index import com.google.common.hash.HashCode import com.intellij.openapi.Disposable import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import com.intellij.psi.stubs.FileContentHashing import com.intellij.psi.stubs.HashCodeDescriptor import com.intellij.psi.stubs.PrebuiltStubsProviderBase import com.intellij.util.SystemProperties import com.intellij.util.indexing.FileContent import com.intellij.util.io.DataExternalizer import com.intellij.util.io.PersistentHashMap import java.io.File import java.io.FileFilter import java.io.IOException abstract class PrebuiltIndexProvider<Value>: Disposable { private val myFileContentHashing = FileContentHashing() private var myPrebuiltIndexStorage: PersistentHashMap<HashCode, Value>? = null protected abstract val dirName: String protected abstract val indexName: String protected abstract val indexExternalizer: DataExternalizer<Value> companion object { private val LOG = Logger.getInstance("#com.intellij.index.PrebuiltIndexProviderBase") @JvmField val DEBUG_PREBUILT_INDICES: Boolean = SystemProperties.getBooleanProperty("debug.prebuilt.indices", false) } init { init() } internal fun init() : Boolean { if (Registry.`is`("use.prebuilt.indices")) { var indexesRoot = findPrebuiltIndicesRoot() try { if (indexesRoot != null && indexesRoot.exists()) { // we should copy prebuilt indexes to a writable folder indexesRoot = copyPrebuiltIndicesToIndexRoot(indexesRoot) // otherwise we can get access denied error, because persistent hash map opens file for read and write myPrebuiltIndexStorage = openIndexStorage(indexesRoot) LOG.info("Using prebuilt $indexName from " + myPrebuiltIndexStorage?.baseFile?.toAbsolutePath()) } else { LOG.info("Prebuilt $indexName indices are missing for $dirName") } } catch (e: ProcessCanceledException) { throw e } catch (e: Exception) { myPrebuiltIndexStorage = null LOG.warn("Prebuilt indices can't be loaded at " + indexesRoot!!, e) } } return myPrebuiltIndexStorage != null } fun get(fileContent: FileContent): Value? { if (myPrebuiltIndexStorage != null) { val hashCode = myFileContentHashing.hashString(fileContent) try { return myPrebuiltIndexStorage!!.get(hashCode) } catch (e: Exception) { LOG.error("Error reading prebuilt stubs from " + myPrebuiltIndexStorage!!.baseFile, e) myPrebuiltIndexStorage = null } } return null } open fun openIndexStorage(indexesRoot: File): PersistentHashMap<HashCode, Value>? { return object : PersistentHashMap<HashCode, Value>( File(indexesRoot, "$indexName.input"), HashCodeDescriptor.instance, indexExternalizer) { override fun isReadOnly(): Boolean { return true } } } protected abstract fun getIndexRoot(): File @Throws(IOException::class) private fun copyPrebuiltIndicesToIndexRoot(prebuiltIndicesRoot: File): File { val indexRoot = getIndexRoot() FileUtil.copyDir(prebuiltIndicesRoot, indexRoot, FileFilter { f -> f.name.startsWith(indexName) }) return indexRoot } private fun findPrebuiltIndicesRoot(): File? { val path: String? = System.getProperty(PrebuiltStubsProviderBase.PREBUILT_INDICES_PATH_PROPERTY) if (path != null && File(path).exists()) { return File(path, dirName) } val f = indexRoot() return if (f.exists()) f else null } open fun indexRoot(): File = File(PathManager.getHomePath(), "index/$dirName") // compiled binary override fun dispose() { if (myPrebuiltIndexStorage != null) { try { myPrebuiltIndexStorage!!.close() } catch (e: IOException) { LOG.error(e) } } } }
apache-2.0
1e9fcd15fe92e72eadbcf5139c8c94ac
32.307087
140
0.711111
4.607843
false
false
false
false
room-15/ChatSE
app/src/main/java/com/tristanwiley/chatse/event/ChatEvent.kt
1
5097
package com.tristanwiley.chatse.event import com.fasterxml.jackson.annotation.JsonProperty import org.jsoup.Jsoup import org.unbescape.html.HtmlEscape /** * ChatEvent class that is used for all new messages, contains all parameters that gets json mapped to it * * @property eventType: An integer which signifies what type of event an object is * @property timeStamp: When the event occurred * @property roomId: ID of the room in which the event occurred * @property userId: The ID of the user that did the event * @property userName: The user's username * @property messageId: The ID of the message (if eventType is equal to 1) * @property showParent: Unused * @property parentId: Parent's ID * @property id = ID of event * @property roomName: Name of Room that event occurred * @property contents: Content of event * @property messageEdits: Number of times the message was edited * @property messageStars: Number of times the message was starred * @property messageOwnerStars: Unused * @property targetUserId: Unused * @property messageOnebox: If the message is oneboxed (an image, wikipedia article, SO/SE post, etc.) * @property oneboxType: Type of oneboxed content * @property oneboxExtra: Extra data from onebox * @property messageStarred: If the message is starred * @property isForUsersList: If the message is for the list of users in MessageEventPresentor * @property emailHash: Email hash used for profile picture */ class ChatEvent { @JsonProperty("message_owner_stars") private var messageOwnerStars = 0 @JsonProperty("target_user_id") private var targetUserId = -1 @JsonProperty("show_parent") private var showParent = false @JsonProperty("message_starred") var messageStarred = false @JsonProperty("message_onebox") var messageOnebox = false @JsonProperty("onebox_content") var oneboxContent = "" @JsonProperty("star_timestamp") var starTimestamp = "" @JsonProperty("onebox_extra") var oneboxExtra = "" @JsonProperty("onebox_type") var oneboxType = "" @JsonProperty("email_hash") var emailHash = "" @JsonProperty("user_name") var userName = "" @JsonProperty("room_name") var roomName = "" @JsonProperty("message_edits") var messageEdits = 0 @JsonProperty("message_stars") var messageStars = 0 @JsonProperty("time_stamp") var timeStamp = 0L @JsonProperty("event_type") var eventType = 0 @JsonProperty("message_id") var messageId = 0 @JsonProperty("parent_id") var parentId = -1 @JsonProperty("room_id") var roomId = 0 @JsonProperty("user_id") var userId = 0 var id = -1 var contents: String = "" var isForUsersList = false fun setContent(content: String) { val doc = Jsoup.parse(content, "http://chat.stackexchange.com/") val elements = doc.select("div") var shouldSetContent = true if (elements.size != 0) { val obType = elements[0].className() when { obType.contains("ob-message") -> println("This is a quote") obType.contains("ob-youtube") -> { shouldSetContent = false messageOnebox = true oneboxType = "youtube" this.contents = elements[0].child(0).getElementsByClass("ob-youtube-title").text() oneboxContent = elements.select("img").attr("src") oneboxExtra = elements[0].child(0).attr("href") } obType.contains("ob-wikipedia") -> println("This is Wikipedia") obType.contains("ob-image") -> { val url = elements.select("img").first().absUrl("src") messageOnebox = true oneboxType = "image" oneboxContent = url } obType.contains("ob-tweet") -> { messageOnebox = true oneboxType = "tweet" val status = elements[2] val writtenBy = elements[4] oneboxContent = "" oneboxContent += "<p>" + status.childNode(0).toString() + "</p>" oneboxContent += "<p>" + writtenBy.toString() + "</p>" shouldSetContent = false this.contents = oneboxContent } else -> { messageOnebox = false oneboxType = "" oneboxContent = "" } } } if (shouldSetContent) { this.contents = HtmlEscape.unescapeHtml(content) } } /** * Different types of event types and their ID */ companion object { const val EVENT_TYPE_MESSAGE = 1 const val EVENT_TYPE_EDIT = 2 const val EVENT_TYPE_JOIN = 3 const val EVENT_TYPE_LEAVE = 4 const val EVENT_TYPE_STAR = 6 const val EVENT_TYPE_MENTION = 8 const val EVENT_TYPE_DELETE = 10 } }
apache-2.0
649e3bc85eadc77ab15a56db9d3173cf
34.643357
105
0.599372
4.345269
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantNullableReturnTypeInspection.kt
1
6914
// 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.inspections 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.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.core.isOverridable import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.idea.util.isEffectivelyActual import org.jetbrains.kotlin.idea.util.isExpectDeclaration import org.jetbrains.kotlin.idea.util.textRangeIn import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory import org.jetbrains.kotlin.resolve.jvm.annotations.TRANSIENT_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isNullable class RedundantNullableReturnTypeInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() { override fun visitNamedFunction(function: KtNamedFunction) { check(function) } override fun visitProperty(property: KtProperty) { if (property.isVar) return check(property) } private fun check(declaration: KtCallableDeclaration) { val typeReference = declaration.typeReference ?: return val typeElement = typeReference.typeElement as? KtNullableType ?: return if (typeElement.innerType == null) return val questionMark = typeElement.questionMarkNode as? LeafPsiElement ?: return if (declaration.isOverridable() || declaration.isExpectDeclaration() || declaration.isEffectivelyActual()) return val (body, targetDeclaration) = when (declaration) { is KtNamedFunction -> { val body = declaration.bodyExpression if (body != null) body to declaration else null } is KtProperty -> { val initializer = declaration.initializer val getter = declaration.accessors.singleOrNull { it.isGetter } val getterBody = getter?.bodyExpression when { initializer != null -> initializer to declaration getterBody != null -> getterBody to getter else -> null } } else -> null } ?: return val context = body.analyze() val declarationDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, targetDeclaration] ?: return if (declarationDescriptor.hasJvmTransientAnnotation()) return val actualReturnTypes = body.actualReturnTypes(context, declarationDescriptor) if (actualReturnTypes.isEmpty() || actualReturnTypes.any { it.isNullable() }) return val declarationName = declaration.nameAsSafeName.asString() val description = if (declaration is KtProperty) { KotlinBundle.message("0.is.always.non.null.type", declarationName) } else { KotlinBundle.message("0.always.returns.non.null.type", declarationName) } holder.registerProblem( typeReference, questionMark.textRangeIn(typeReference), description, MakeNotNullableFix() ) } } private fun DeclarationDescriptor.hasJvmTransientAnnotation() = (this as? PropertyDescriptor)?.backingField?.annotations?.findAnnotation(TRANSIENT_ANNOTATION_FQ_NAME) != null @OptIn(FrontendInternals::class) private fun KtExpression.actualReturnTypes(context: BindingContext, declarationDescriptor: DeclarationDescriptor): List<KotlinType> { val dataFlowValueFactory = getResolutionFacade().frontendService<DataFlowValueFactory>() val moduleDescriptor = findModuleDescriptor() val languageVersionSettings = languageVersionSettings val returnTypes = collectDescendantsOfType<KtReturnExpression> { it.labelQualifier == null && it.getTargetFunctionDescriptor(context) == declarationDescriptor }.flatMap { it.returnedExpression.types(context, dataFlowValueFactory, moduleDescriptor, languageVersionSettings) } return if (this is KtBlockExpression) { returnTypes } else { returnTypes + types(context, dataFlowValueFactory, moduleDescriptor, languageVersionSettings) } } private fun KtExpression?.types( context: BindingContext, dataFlowValueFactory: DataFlowValueFactory, moduleDescriptor: ModuleDescriptor, languageVersionSettings: LanguageVersionSettings ): List<KotlinType> { if (this == null) return emptyList() val type = context.getType(this) ?: return emptyList() val dataFlowInfo = context[BindingContext.EXPRESSION_TYPE_INFO, this]?.dataFlowInfo ?: return emptyList() val dataFlowValue = dataFlowValueFactory.createDataFlowValue(this, type, context, moduleDescriptor) val stableTypes = dataFlowInfo.getStableTypes(dataFlowValue, languageVersionSettings) return if (stableTypes.isNotEmpty()) stableTypes.toList() else listOf(type) } private class MakeNotNullableFix : LocalQuickFix { override fun getName() = KotlinBundle.message("make.not.nullable") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val typeReference = descriptor.psiElement as? KtTypeReference ?: return val typeElement = typeReference.typeElement as? KtNullableType ?: return val innerType = typeElement.innerType ?: return typeElement.replace(innerType) } } }
apache-2.0
2e281c231c6596e001f2d3969510934b
48.741007
158
0.706827
5.737759
false
false
false
false
smmribeiro/intellij-community
plugins/laf/win10/src/com/intellij/laf/win10/WinIconLookup.kt
5
1025
package com.intellij.laf.win10 import com.intellij.icons.AllIcons import com.intellij.util.ui.DirProvider import com.intellij.util.ui.LafIconLookup import javax.swing.Icon private class WinDirProvider : DirProvider() { override fun dir(): String = "/icons/" } object WinIconLookup { @JvmStatic @JvmOverloads fun getIcon(name: String, selected: Boolean = false, focused: Boolean = false, enabled: Boolean = true, editable: Boolean = false, pressed: Boolean = false): Icon { return LafIconLookup.findIcon(name, selected = selected, focused = focused, enabled = enabled, editable = editable, pressed = pressed, isThrowErrorIfNotFound = true, dirProvider = WinDirProvider()) ?: AllIcons.Actions.Stub } }
apache-2.0
cc8aaa806b638a9ef92759f1b3d62789
32.096774
90
0.529756
5.25641
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/blocks/CameraData.kt
1
3670
package de.fabmax.kool.modules.ksl.blocks import de.fabmax.kool.KoolContext import de.fabmax.kool.modules.ksl.KslShader import de.fabmax.kool.modules.ksl.KslShaderListener import de.fabmax.kool.modules.ksl.lang.* import de.fabmax.kool.pipeline.* import de.fabmax.kool.pipeline.drawqueue.DrawCommand fun KslProgram.cameraData(): CameraData { return (dataBlocks.find { it is CameraData } as? CameraData) ?: CameraData(this) } class CameraData(program: KslProgram) : KslDataBlock, KslShaderListener { override val name = NAME val position: KslUniformVector<KslTypeFloat3, KslTypeFloat1> val direction: KslUniformVector<KslTypeFloat3, KslTypeFloat1> val clip: KslUniformVector<KslTypeFloat2, KslTypeFloat1> val viewMat: KslUniformMatrix<KslTypeMat4, KslTypeFloat4> val projMat: KslUniformMatrix<KslTypeMat4, KslTypeFloat4> val viewProjMat: KslUniformMatrix<KslTypeMat4, KslTypeFloat4> val viewport: KslUniformVector<KslTypeFloat4, KslTypeFloat1> val clipNear: KslExprFloat1 get() = clip.x val clipFar: KslExprFloat1 get() = clip.y // todo: implement shared ubos val camUbo = KslUniformBuffer("CameraUniforms", program, false).apply { viewMat = uniformMat4(UNIFORM_NAME_VIEW_MAT) projMat = uniformMat4(UNIFORM_NAME_PROJ_MAT) viewProjMat = uniformMat4(UNIFORM_NAME_VIEW_PROJ_MAT) viewport = uniformFloat4(UNIFORM_NAME_VIEWPORT) position = uniformFloat3(UNIFORM_NAME_CAM_POSITION) direction = uniformFloat3(UNIFORM_NAME_CAM_DIRECTION) clip = uniformFloat2(UNIFORM_NAME_CAM_CLIP) } private var uPosition: Uniform3f? = null private var uDirection: Uniform3f? = null private var uClip: Uniform2f? = null private var uViewMat: UniformMat4f? = null private var uProjMat: UniformMat4f? = null private var uViewProjMat: UniformMat4f? = null private var uViewport: Uniform4f? = null init { program.shaderListeners += this program.dataBlocks += this program.uniformBuffers += camUbo } override fun onShaderCreated(shader: KslShader, pipeline: Pipeline, ctx: KoolContext) { uPosition = shader.uniforms[UNIFORM_NAME_CAM_POSITION] as Uniform3f? uDirection = shader.uniforms[UNIFORM_NAME_CAM_DIRECTION] as Uniform3f? uClip = shader.uniforms[UNIFORM_NAME_CAM_CLIP] as Uniform2f? uViewMat = shader.uniforms[UNIFORM_NAME_VIEW_MAT] as UniformMat4f? uProjMat = shader.uniforms[UNIFORM_NAME_PROJ_MAT] as UniformMat4f? uViewProjMat = shader.uniforms[UNIFORM_NAME_VIEW_PROJ_MAT] as UniformMat4f? uViewport = shader.uniforms[UNIFORM_NAME_VIEWPORT] as Uniform4f? } override fun onUpdate(cmd: DrawCommand) { val cam = cmd.renderPass.camera val vp = cmd.renderPass.viewport uPosition?.value?.set(cam.globalPos) uDirection?.value?.set(cam.globalLookDir) uClip?.value?.set(cam.clipNear, cam.clipFar) uViewMat?.value?.set(cam.view) uProjMat?.value?.set(cam.proj) uViewProjMat?.value?.set(cam.viewProj) uViewport?.value?.set(vp.x.toFloat(), vp.y.toFloat(), vp.width.toFloat(), vp.height.toFloat()) } companion object { const val NAME = "CameraData" const val UNIFORM_NAME_CAM_POSITION = "uCamPos" const val UNIFORM_NAME_CAM_DIRECTION = "uCamDir" const val UNIFORM_NAME_CAM_CLIP = "uCamClip" const val UNIFORM_NAME_VIEW_MAT = "uViewMat" const val UNIFORM_NAME_PROJ_MAT = "uProjMat" const val UNIFORM_NAME_VIEW_PROJ_MAT = "uViewProjMat" const val UNIFORM_NAME_VIEWPORT = "uViewport" } }
apache-2.0
5d77e2dab68765f5636c1ddb492619b1
38.053191
102
0.705177
3.619329
false
false
false
false
fabmax/kool
kool-physics/src/jvmMain/kotlin/de/fabmax/kool/physics/vehicle/SingleVehicleUpdater.kt
1
2690
package de.fabmax.kool.physics.vehicle import de.fabmax.kool.math.Vec3f import de.fabmax.kool.physics.* import physx.common.PxVec3 import physx.physics.PxBatchQuery import physx.support.Vector_PxVehicleWheels import physx.support.Vector_PxWheelQueryResult import physx.vehicle.PxVehicleTopLevelFunctions import physx.vehicle.PxVehicleWheelQueryResult actual class SingleVehicleUpdater actual constructor(vehicle: Vehicle, private val world: PhysicsWorld) : VehicleUpdater { private val vehicleAsVector: Vector_PxVehicleWheels private val wheelQueryResults: Vector_PxWheelQueryResult private val vehicleWheelQueryResult: PxVehicleWheelQueryResult private val queryData: VehicleQueryData private val query: PxBatchQuery private var frictionPairs = Physics.defaultSurfaceFrictions actual var vehicleGravity: Vec3f? = null private val pxGravity = PxVec3() init { Physics.checkIsLoaded() queryData = VehicleQueryData(4) query = queryData.setupSceneQuery(world.pxScene) vehicleAsVector = Vector_PxVehicleWheels() vehicleAsVector.push_back(vehicle.pxVehicle) wheelQueryResults = Vector_PxWheelQueryResult(vehicle.vehicleProps.numWheels) vehicleWheelQueryResult = PxVehicleWheelQueryResult() vehicleWheelQueryResult.nbWheelQueryResults = wheelQueryResults.size() vehicleWheelQueryResult.wheelQueryResults = wheelQueryResults.data() } override fun updateVehicle(vehicle: Vehicle, timeStep: Float) { val grav = vehicleGravity?.toPxVec3(pxGravity) ?: world.pxScene.gravity PxVehicleTopLevelFunctions.PxVehicleSuspensionRaycasts(query, vehicleAsVector, queryData.numQueriesPerBatch, queryData.raycastResults.data()) PxVehicleTopLevelFunctions.PxVehicleUpdates(timeStep, grav, frictionPairs.frictionPairs, vehicleAsVector, vehicleWheelQueryResult) for (i in 0 until 4) { val wheelInfo = vehicle.wheelInfos[i] wheelQueryResults.at(i).apply { localPose.toMat4f(wheelInfo.transform) wheelInfo.lateralSlip = lateralSlip wheelInfo.longitudinalSlip = longitudinalSlip } } } override fun setSurfaceFrictions(frictionPairs: Map<Material, Float>) { this.frictionPairs = FrictionPairs(frictionPairs) } override fun release() { vehicleAsVector.destroy() wheelQueryResults.destroy() vehicleWheelQueryResult.destroy() pxGravity.destroy() queryData.release() query.release() if (frictionPairs != Physics.defaultSurfaceFrictions) { frictionPairs.release() } } }
apache-2.0
4016782c7053d687d5dde3916d7fb5e8
37.442857
149
0.734201
4.711033
false
false
false
false
Pattonville-App-Development-Team/Android-App
app/src/main/java/org/pattonvillecs/pattonvilleapp/service/model/calendar/event/PinnableCalendarEvent.kt
1
3598
/* * 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/>. */ package org.pattonvillecs.pattonvilleapp.service.model.calendar.event import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Embedded import android.arch.persistence.room.Ignore import android.arch.persistence.room.Relation import android.os.Parcel import android.os.Parcelable import com.google.errorprone.annotations.Immutable import org.pattonvillecs.pattonvilleapp.service.model.DataSource import org.pattonvillecs.pattonvilleapp.service.model.calendar.DataSourceMarker /** * Created by Mitchell on 10/5/2017. */ @Immutable data class PinnableCalendarEvent @JvmOverloads constructor(@field:Embedded val calendarEvent: CalendarEvent, @field:ColumnInfo(name = "pinned") val pinned: Boolean, @field:Relation(parentColumn = "uid", entityColumn = "uid", entity = DataSourceMarker::class) var dataSourceMarkers: Set<DataSourceMarker> = setOf()) : ICalendarEvent by calendarEvent, Parcelable { @delegate:Ignore val dataSources: Set<DataSource> by lazy { dataSourceMarkers.mapTo(mutableSetOf(), { it.dataSource }) } constructor(parcel: Parcel) : this( parcel.readParcelable(CalendarEvent::class.java.classLoader), parcel.readByte() != 0.toByte(), parcel.readParcelableArray(DataSourceMarker::class.java.classLoader).mapTo(mutableSetOf(), { it as DataSourceMarker })) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as PinnableCalendarEvent if (calendarEvent != other.calendarEvent) return false if (dataSourceMarkers != other.dataSourceMarkers) return false return true } override fun hashCode(): Int { var result = calendarEvent.hashCode() result = 31 * result + dataSourceMarkers.hashCode() return result } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeParcelable(calendarEvent, flags) parcel.writeByte(if (pinned) 1 else 0) parcel.writeParcelableArray(dataSourceMarkers.toTypedArray(), flags) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<PinnableCalendarEvent> { override fun createFromParcel(parcel: Parcel): PinnableCalendarEvent { return PinnableCalendarEvent(parcel) } override fun newArray(size: Int): Array<PinnableCalendarEvent?> { return arrayOfNulls(size) } } }
gpl-3.0
54bb1f2b87abf9efb1df8b22235d7535
40.356322
162
0.668427
5.053371
false
false
false
false
jotomo/AndroidAPS
app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Delivery_CompleteTest.kt
1
2106
package info.nightscout.androidaps.danars.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.danars.DanaRSPlugin import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.`when` import org.mockito.Mockito.anyDouble import org.mockito.Mockito.anyInt import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) @PrepareForTest(RxBusWrapper::class, DanaRSPlugin::class) class DanaRS_Packet_Notify_Delivery_CompleteTest : DanaRSTestBase() { @Mock lateinit var danaRSPlugin: DanaRSPlugin @Mock lateinit var activePlugin: ActivePluginProvider private val packetInjector = HasAndroidInjector { AndroidInjector { if (it is DanaRS_Packet_Notify_Delivery_Complete) { it.aapsLogger = aapsLogger it.rxBus = rxBus it.resourceHelper = resourceHelper it.danaPump = danaPump } if (it is Treatment) { it.defaultValueHelper = defaultValueHelper it.resourceHelper = resourceHelper it.profileFunction = profileFunction it.activePlugin = activePlugin } } } @Test fun runTest() { `when`(resourceHelper.gs(anyInt(), anyDouble())).thenReturn("SomeString") danaPump.bolusingTreatment = Treatment(packetInjector) val packet = DanaRS_Packet_Notify_Delivery_Complete(packetInjector) // test params Assert.assertEquals(null, packet.requestParams) // test message decoding packet.handleMessage(createArray(17, 0.toByte())) Assert.assertEquals(true, danaPump.bolusDone) Assert.assertEquals("NOTIFY__DELIVERY_COMPLETE", packet.friendlyName) } }
agpl-3.0
893ef576bdaa979238fee5eebdf659b0
37.309091
81
0.716049
4.943662
false
true
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBTDevice.kt
1
3783
package info.nightscout.androidaps.plugins.general.automation.triggers import android.bluetooth.BluetoothAdapter import android.content.Context import android.widget.LinearLayout import com.google.common.base.Optional import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.events.EventBTChange import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin import info.nightscout.androidaps.plugins.general.automation.elements.ComparatorConnect import info.nightscout.androidaps.plugins.general.automation.elements.InputDropdownMenu import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel import info.nightscout.androidaps.utils.JsonHelper import org.json.JSONObject import java.util.* import javax.inject.Inject class TriggerBTDevice(injector: HasAndroidInjector) : Trigger(injector) { @Inject lateinit var context: Context @Inject lateinit var automationPlugin: AutomationPlugin var btDevice = InputDropdownMenu(injector, "") var comparator: ComparatorConnect = ComparatorConnect(injector) private constructor(injector: HasAndroidInjector, triggerBTDevice: TriggerBTDevice) : this(injector) { comparator = ComparatorConnect(injector, triggerBTDevice.comparator.value) btDevice.value = triggerBTDevice.btDevice.value } @Synchronized override fun shouldRun(): Boolean { if (eventExists()) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) return true } return false } @Synchronized override fun toJSON(): String { val data = JSONObject() .put("comparator", comparator.value.toString()) .put("name", btDevice.value) return JSONObject() .put("type", this::class.java.name) .put("data", data) .toString() } override fun fromJSON(data: String): Trigger { val d = JSONObject(data) btDevice.value = JsonHelper.safeGetString(d, "name")!! comparator.value = ComparatorConnect.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")!!) return this } override fun friendlyName(): Int = R.string.btdevice override fun friendlyDescription(): String = resourceHelper.gs(R.string.btdevicecompared, btDevice.value, resourceHelper.gs(comparator.value.stringRes)) override fun icon(): Optional<Int?> = Optional.of(R.drawable.ic_bluetooth_white_48dp) override fun duplicate(): Trigger = TriggerBTDevice(injector, this) override fun generateDialog(root: LinearLayout) { val pairedDevices = devicesPaired() btDevice.setList(pairedDevices) LayoutBuilder() .add(StaticLabel(injector, R.string.btdevice, this)) .add(btDevice) .add(comparator) .build(root) } // Get the list of paired BT devices to use in dropdown menu private fun devicesPaired(): ArrayList<CharSequence> { val s = ArrayList<CharSequence>() BluetoothAdapter.getDefaultAdapter()?.bondedDevices?.forEach { s.add(it.name) } return s } private fun eventExists(): Boolean { automationPlugin.btConnects.forEach { if (btDevice.value == it.deviceName) { if (comparator.value == ComparatorConnect.Compare.ON_CONNECT && it.state == EventBTChange.Change.CONNECT) return true if (comparator.value == ComparatorConnect.Compare.ON_DISCONNECT && it.state == EventBTChange.Change.DISCONNECT) return true } } return false } }
agpl-3.0
eca5ca2b4b2a4888294b58370d5ee399
39.255319
139
0.712133
4.636029
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/promo/SubscriptionBuyGemsPromoView.kt
1
1046
package com.habitrpg.android.habitica.ui.views.promo import android.content.Context import android.util.AttributeSet import android.widget.RelativeLayout import androidx.core.content.ContextCompat import androidx.core.os.bundleOf import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.extensions.inflate import com.habitrpg.android.habitica.helpers.MainNavigationController import kotlinx.android.synthetic.main.promo_subscription_buy_gems.view.* class SubscriptionBuyGemsPromoView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : RelativeLayout(context, attrs, defStyleAttr) { init { inflate(R.layout.promo_subscription_buy_gems, true) setBackgroundColor(ContextCompat.getColor(context, R.color.gray_700)) clipToPadding = false clipChildren = false clipToOutline = false button.setOnClickListener { MainNavigationController.navigate(R.id.gemPurchaseActivity, bundleOf(Pair("openSubscription", true))) } } }
gpl-3.0
9f8e27f9135cc34286a11c1a3fe39cce
40.88
139
0.782983
4.48927
false
false
false
false
michaelkourlas/voipms-sms-client
voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/database/entities/Archived.kt
1
1353
/* * VoIP.ms SMS * Copyright (C) 2021 Michael Kourlas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.kourlas.voipms_sms.database.entities import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = Archived.TABLE_NAME) class Archived( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = COLUMN_DATABASE_ID) val databaseId: Long = 0, @ColumnInfo(name = COLUMN_DID) val did: String, @ColumnInfo(name = COLUMN_CONTACT) val contact: String, @ColumnInfo(name = COLUMN_ARCHIVED) val archived: Int ) { companion object { const val TABLE_NAME = "archived" const val COLUMN_DATABASE_ID = "DatabaseId" const val COLUMN_DID = "Did" const val COLUMN_CONTACT = "Contact" const val COLUMN_ARCHIVED = "Archived" } }
apache-2.0
d5e682e1d1b56721489dc7f4c97cc26e
32.85
75
0.713969
4.014837
false
false
false
false
siosio/intellij-community
platform/platform-impl/src/com/intellij/ide/NewModuleStep.kt
1
2356
// 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.ide import com.intellij.ide.util.projectWizard.ModuleWizardStep import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.ui.DialogPanel import com.intellij.ui.UIBundle import com.intellij.ui.layout.* import com.intellij.util.SystemProperties import java.nio.file.Files import java.nio.file.Paths import javax.swing.JComponent abstract class NewModuleStep<T> : ModuleWizardStep() { abstract val panel: JComponent abstract var settings: T var baseSettings = BaseNewProjectSettings(SystemProperties.getUserHome()) final override fun updateDataModel() { if (panel is DialogPanel) (panel as DialogPanel).apply() } final override fun getComponent() = panel fun LayoutBuilder.nameAndPath() { row(UIBundle.message("label.project.wizard.new.project.name")) { textField(baseSettings::name) }.largeGapAfter() row(UIBundle.message("label.project.wizard.new.project.location")) { textFieldWithBrowseButton(baseSettings::path, UIBundle.message("dialog.title.project.name"), /*context.project*/null, FileChooserDescriptorFactory.createSingleFolderDescriptor()) }.largeGapAfter() } fun LayoutBuilder.gitCheckbox() { row { checkBox(UIBundle.message("label.project.wizard.new.project.git.checkbox"), baseSettings::git) }.largeGapAfter() } companion object { fun RowBuilder.twoColumnRow(column1: InnerCell.() -> Unit, column2: InnerCell.() -> Unit): Row = row { cell { column1() } cell { column2() } placeholder().constraints(growX, pushX) } fun findNonExistingFileName(searchDirectory: String, preferredName: String, extension: String): String { var idx = 0 while (true) { val fileName = (if (idx > 0) preferredName + idx else preferredName) + extension if (!Files.exists(Paths.get(searchDirectory, fileName))) { return fileName } idx++ } } } } class BaseNewProjectSettings(initPath: String) { var path: String = initPath var name: String = NewModuleStep.findNonExistingFileName(initPath, "untitled", "") var git: Boolean = false }
apache-2.0
468524b0b5ec862e9d4a907328469c49
32.197183
140
0.705857
4.322936
false
false
false
false
siosio/intellij-community
plugins/kotlin/jvm-debugger/test/testData/stepping/custom/functionBreakpoints.kt
4
1324
package functionBreakpoints //FunctionBreakpoint! class A //FunctionBreakpoint! class B() //FunctionBreakpoint! class C {} //FunctionBreakpoint! class D(val a: Int) //FunctionBreakpoint! class E( val a: Int ) class F( //Breakpoint! val a: Int ) class G { //FunctionBreakpoint! constructor(a: Int) {} //FunctionBreakpoint! constructor(a: String) {} } //FunctionBreakpoint! class H(val a: String) { //FunctionBreakpoint! constructor(a: Int) : this("f") } //FunctionBreakpoint! class K { //FunctionBreakpoint! fun a() {} //FunctionBreakpoint! fun b() { } //FunctionBreakpoint! fun c(a: Int) { b() } } //FunctionBreakpoint! fun topLevel1() {} //FunctionBreakpoint! fun topLevel2( a: Int ) {} //FunctionBreakpoint! fun topLevel3(a: Int = foo()) {} //FunctionBreakpoint! fun foo() = 3 class L { val a: Int //FunctionBreakpoint! get() = 1 var b: Int //FunctionBreakpoint! get() = 1 //FunctionBreakpoint! set(v) { topLevel2(v) } } fun main() { A() B() C() D(0) E(0) F(0) G(0) G("") H(0) H("") val k = K() k.a() k.b() k.c(0) topLevel1() topLevel2(0) topLevel3() val l = L() l.a l.b l.b = 2 }
apache-2.0
f52a346c211dd3cb1a1ff2512f5035c5
11.619048
35
0.544562
3.152381
false
false
false
false
siosio/intellij-community
plugins/gradle/gradle-dependency-updater/src/org/jetbrains/plugins/gradle/dsl/GradleDependencyModificator.kt
1
9183
// 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.dsl import com.android.tools.idea.gradle.dsl.api.GradleBuildModel import com.android.tools.idea.gradle.dsl.api.ProjectBuildModel import com.android.tools.idea.gradle.dsl.api.dependencies.ArtifactDependencySpec import com.android.tools.idea.gradle.dsl.api.dependencies.DependenciesModel import com.android.tools.idea.gradle.dsl.api.ext.PropertyType import com.android.tools.idea.gradle.dsl.api.ext.ResolvedPropertyModel import com.android.tools.idea.gradle.dsl.model.repositories.UrlBasedRepositoryModelImpl import com.intellij.buildsystem.model.DeclaredDependency import com.intellij.buildsystem.model.unified.UnifiedDependency import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository import com.intellij.externalSystem.ExternalDependencyModificator import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import org.jetbrains.annotations.NotNull import org.jetbrains.annotations.Nullable import org.jetbrains.plugins.gradle.util.GradleBundle import org.jetbrains.plugins.gradle.util.GradleConstants.SYSTEM_ID // Note: this code assumes that UnifiedCoordinates are never code references, only "hardcoded" values. // If you ever wanted to support code references here, you'd need to make UnifiedCoordinates aware of // the difference. class GradleDependencyModificator(private val myProject: Project) : ExternalDependencyModificator { override fun supports(module: Module): Boolean = ExternalSystemModulePropertyManager.getInstance(module).getExternalSystemId() == SYSTEM_ID.id override fun addDependency(module: Module, descriptor: UnifiedDependency) { checkDescriptor(descriptor) val artifactSpec = ArtifactDependencySpec.create(descriptor.coordinates.artifactId!!, descriptor.coordinates.groupId, descriptor.coordinates.version) val model = ProjectBuildModel.get(module.project).getModuleBuildModel(module) ?: throwFailToModify(module) val configurationName = getConfigurationName(descriptor) val dependencies: DependenciesModel = model.dependencies() dependencies.addArtifact(configurationName, artifactSpec) applyChanges(model) } private fun checkDescriptor(descriptor: UnifiedDependency) { requireNotNull(descriptor.coordinates.artifactId) { GradleBundle.message("gradle.dsl.artifactid.is.null") } requireNotNull(descriptor.coordinates.groupId) { GradleBundle.message("gradle.dsl.groupid.is.null") } requireNotNull(descriptor.coordinates.version) { GradleBundle.message("gradle.dsl.version.is.null") } requireNotNull(descriptor.scope) { GradleBundle.message("gradle.dsl.scope.is.null") } } private fun getConfigurationName(descriptor: UnifiedDependency): String = descriptor.scope ?: "implementation" override fun updateDependency(module: Module, oldDescriptor: UnifiedDependency, newDescriptor: UnifiedDependency) { checkDescriptor(newDescriptor) val model = ProjectBuildModel.get(module.project).getModuleBuildModel(module) ?: throwFailToModify(module) val artifactModel = model.dependencies().artifacts().find { it.group().valueAsString() == oldDescriptor.coordinates.groupId && it.name().valueAsString() == oldDescriptor.coordinates.artifactId && it.version().valueAsString() == oldDescriptor.coordinates.version && it.configurationName() == oldDescriptor.scope } if (artifactModel == null) { logger<GradleDependencyModificator>().warn("Unable to update dependency '$oldDescriptor': not found in module ${module.name}") return } if (oldDescriptor.coordinates.groupId != newDescriptor.coordinates.groupId) { updateVariableOrValue(artifactModel.group(), newDescriptor.coordinates.groupId!!) } if (oldDescriptor.coordinates.artifactId != newDescriptor.coordinates.artifactId) { updateVariableOrValue(artifactModel.name(), newDescriptor.coordinates.artifactId!!) } if (oldDescriptor.coordinates.version != newDescriptor.coordinates.version) { updateVariableOrValue(artifactModel.version(), newDescriptor.coordinates.version!!) } if (oldDescriptor.scope != newDescriptor.scope && newDescriptor.scope != null) { artifactModel.setConfigurationName(newDescriptor.scope!!) } applyChanges(model) } private fun updateVariableOrValue(model: ResolvedPropertyModel, value: String) { if (model.dependencies.size == 1) { val dependencyPropertyModel = model.dependencies[0] if (dependencyPropertyModel.propertyType == PropertyType.VARIABLE || dependencyPropertyModel.propertyType == PropertyType.REGULAR || dependencyPropertyModel.propertyType == PropertyType.PROPERTIES_FILE ) { if (dependencyPropertyModel.valueAsString().equals(model.valueAsString())) { // not partial injection, like "${version}-SNAPSHOT" dependencyPropertyModel.setValue(value) return } } } model.setValue(value) } override fun removeDependency(module: Module, descriptor: UnifiedDependency) { checkDescriptor(descriptor) val model = ProjectBuildModel.get(module.project).getModuleBuildModel(module) ?: throwFailToModify(module) val dependencies: DependenciesModel = model.dependencies() for (artifactModel in dependencies.artifacts()) { if (artifactModel.group().valueAsString() == descriptor.coordinates.groupId && artifactModel.name().valueAsString() == descriptor.coordinates.artifactId && artifactModel.version().valueAsString() == descriptor.coordinates.version ) { dependencies.remove(artifactModel) break } } return applyChanges(model) } override fun addRepository(module: Module, repository: UnifiedDependencyRepository) { val model = ProjectBuildModel.get(module.project).getModuleBuildModel(module) ?: throwFailToModify(module) val repositoryModel = model.repositories() val trimmedUrl = repository.url?.trimLastSlash() if (trimmedUrl == null || repositoryModel.containsMavenRepositoryByUrl(trimmedUrl)) { return } val methodName = RepositoriesWithShorthandMethods.findByUrlLenient(trimmedUrl)?.methodName if (methodName != null) { if (repositoryModel.containsMethodCall(methodName)) { return } repositoryModel.addRepositoryByMethodName(methodName) } else { repositoryModel.addMavenRepositoryByUrl(trimmedUrl, repository.name) } applyChanges(model) } override fun deleteRepository(module: Module, repository: UnifiedDependencyRepository) { val model = ProjectBuildModel.get(module.project).getModuleBuildModel(module) ?: throwFailToModify(module) val repositoryModel = model.repositories() val repositoryUrl = repository.url ?: return repositoryModel.removeRepositoryByUrl(repositoryUrl) repositoryModel.removeRepositoryByUrl(repositoryUrl.trimLastSlash()) applyChanges(model) } override fun declaredDependencies(module: @NotNull Module): List<DeclaredDependency> { val model = ProjectBuildModel.get(module.project).getModuleBuildModel(module) ?: throwFailToModify(module) return model.dependencies().artifacts().map { val dataContext = DataContext { dataId -> if (CommonDataKeys.PSI_ELEMENT.`is`(dataId)) it.psiElement else null } DeclaredDependency(groupId = it.group().valueAsString(), artifactId = it.name().valueAsString(), version = it.version().valueAsString(), configuration = it.configurationName(), dataContext = dataContext) } } override fun declaredRepositories(module: Module): List<UnifiedDependencyRepository> { val model = ProjectBuildModel.get(module.project).getModuleBuildModel(module) ?: throwFailToModify(module) return model.repositories().repositories() .mapNotNull { it as? UrlBasedRepositoryModelImpl } .mapNotNull { m -> m.url().valueAsString()?.let { UnifiedDependencyRepository(id = RepositoriesWithShorthandMethods.findByRepoType(m.type)?.repositoryId, name = m.name().valueAsString(), url = it) } } } private fun throwFailToModify(module: Module): Nothing { throw IllegalStateException(GradleBundle.message("gradle.dsl.model.fail.to.build", module.name)) } private fun applyChanges(model: @Nullable GradleBuildModel) { WriteCommandAction.writeCommandAction(myProject, model.psiFile).run<Throwable> { model.applyChanges() } } private fun String.trimLastSlash(): String = this.trimEnd { it == '/' } }
apache-2.0
f3171dc0b493b7a660c0d4e81fc67f5e
48.370968
140
0.744855
4.953074
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/widget/preference/MangaSyncLoginDialog.kt
2
2261
package eu.kanade.tachiyomi.widget.preference import android.os.Bundle import android.view.View import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.mangasync.MangaSyncManager import eu.kanade.tachiyomi.data.mangasync.MangaSyncService import eu.kanade.tachiyomi.util.toast import kotlinx.android.synthetic.main.pref_account_login.view.* import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import uy.kohesive.injekt.injectLazy class MangaSyncLoginDialog : LoginDialogPreference() { companion object { fun newInstance(sync: MangaSyncService): LoginDialogPreference { val fragment = MangaSyncLoginDialog() val bundle = Bundle(1) bundle.putInt("key", sync.id) fragment.arguments = bundle return fragment } } val syncManager: MangaSyncManager by injectLazy() lateinit var sync: MangaSyncService override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val syncId = arguments.getInt("key") sync = syncManager.getService(syncId)!! } override fun setCredentialsOnView(view: View) = with(view) { dialog_title.text = getString(R.string.login_title, sync.name) username.setText(sync.getUsername()) password.setText(sync.getPassword()) } override fun checkLogin() { requestSubscription?.unsubscribe() v?.apply { if (username.text.length == 0 || password.text.length == 0) return login.progress = 1 val user = username.text.toString() val pass = password.text.toString() requestSubscription = sync.login(user, pass) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ sync.saveCredentials(user, pass) dialog.dismiss() context.toast(R.string.login_success) }, { error -> sync.logout() login.progress = -1 login.setText(R.string.unknown_error) }) } } }
gpl-3.0
d49925ab28878826da67ae7ce00930db
30.84507
72
0.612561
4.904555
false
false
false
false
3sidedcube/react-native-navigation
lib/android/app/src/main/java/com/reactnativenavigation/views/element/finder/ExistingViewFinder.kt
1
2145
package com.reactnativenavigation.views.element.finder import android.view.View import android.widget.ImageView import androidx.core.view.doOnPreDraw import com.facebook.drawee.generic.RootDrawable import com.facebook.react.uimanager.util.ReactFindViewUtil import com.reactnativenavigation.viewcontrollers.viewcontroller.ViewController import kotlin.coroutines.Continuation import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class ExistingViewFinder : ViewFinder { private val bailoutTime = 100L private var timeElapsedWaitingForActualImageToLoad = 0L override suspend fun find(root: ViewController<*>, nativeId: String) = suspendCoroutine<View?> { cont -> when (val view = ReactFindViewUtil.findView(root.view, nativeId)) { null -> cont.resume(null) is ImageView -> { if (hasMeasuredDrawable(view)) { resume(view, cont) } else { resumeOnImageLoad(view, cont) } } else -> cont.resume(view) } } private fun resume(view: ImageView, cont: Continuation<View?>) { if (view.drawable is RootDrawable) { view.post { cont.resume(view) } } else { cont.resume(view) } } private fun resumeOnImageLoad(view: ImageView, cont: Continuation<View?>) { val t1 = System.currentTimeMillis() view.doOnPreDraw { if (hasMeasuredDrawable(view)) { view.post { cont.resume(view) } } else { timeElapsedWaitingForActualImageToLoad += (System.currentTimeMillis() - t1) if (timeElapsedWaitingForActualImageToLoad < bailoutTime) { resumeOnImageLoad(view, cont) } else { cont.resume(null) } } } } private fun hasMeasuredDrawable(view: ImageView) = when (view.drawable) { is RootDrawable -> true else -> with(view.drawable) { intrinsicWidth != -1 && intrinsicHeight != -1 } } }
mit
e61e8b261855e6015d3b68f13ee182ff
34.180328
108
0.608858
4.787946
false
false
false
false
vovagrechka/fucking-everything
attic/photlin/src/org/jetbrains/kotlin/js/translate/declaration/DelegationTranslator.kt
1
9918
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.js.translate.declaration import photlinc.* import org.jetbrains.kotlin.backend.common.CodegenUtil import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.js.backend.ast.* import org.jetbrains.kotlin.js.naming.NameSuggestion import org.jetbrains.kotlin.js.translate.context.Namer import org.jetbrains.kotlin.js.translate.context.TranslationContext import org.jetbrains.kotlin.js.translate.general.AbstractTranslator import org.jetbrains.kotlin.js.translate.general.Translation import org.jetbrains.kotlin.js.translate.utils.* import org.jetbrains.kotlin.js.translate.utils.TranslationUtils.simpleReturnFunction import org.jetbrains.kotlin.js.translate.utils.TranslationUtils.translateFunctionAsEcma5PropertyDescriptor import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtDelegatedSuperTypeEntry import org.jetbrains.kotlin.psi.KtSuperTypeListEntry import org.jetbrains.kotlin.resolve.DelegationResolver import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.descriptorUtil.isExtensionProperty class DelegationTranslator( classDeclaration: KtClassOrObject, context: TranslationContext ) : AbstractTranslator(context) { private val classDescriptor: ClassDescriptor = BindingUtils.getClassDescriptor(context.bindingContext(), classDeclaration) private val delegationBySpecifiers = classDeclaration.superTypeListEntries.filterIsInstance<KtDelegatedSuperTypeEntry>() private class Field (val name: JsName, val generateField: Boolean) private val fields = mutableMapOf<KtDelegatedSuperTypeEntry, Field>() init { for (specifier in delegationBySpecifiers) { val expression = specifier.delegateExpression ?: throw IllegalArgumentException("delegate expression should not be null: ${specifier.text}") val propertyDescriptor = CodegenUtil.getDelegatePropertyIfAny(expression, classDescriptor, bindingContext()) if (CodegenUtil.isFinalPropertyWithBackingField(propertyDescriptor, bindingContext())) { val delegateName = context.getNameForDescriptor(propertyDescriptor!!) fields[specifier] = Field(delegateName, false) } else { val classFqName = DescriptorUtils.getFqName(classDescriptor) val idForMangling = classFqName.asString() val suggestedName = NameSuggestion.getStableMangledName(Namer.getDelegatePrefix(), idForMangling) val delegateName = context.getScopeForDescriptor(classDescriptor).declareFreshName("${suggestedName}_0") fields[specifier] = Field(delegateName, true) } } } fun addInitCode(statements: MutableList<JsStatement>) { for (specifier in delegationBySpecifiers) { val field = fields[specifier]!! if (field.generateField) { val expression = specifier.delegateExpression!! val context = context().innerBlock() val delegateInitExpr = Translation.translateAsExpression(expression, context) statements += context.dynamicContext().jsBlock().statements val lhs = JsAstUtils.pureFqn(field.name, phpThisRef()) statements += JsAstUtils.assignment(lhs, delegateInitExpr).makeStmt() } } } fun generateDelegated() { for (specifier in delegationBySpecifiers) { generateDelegates(getSuperClass(specifier), fields[specifier]!!) } } private fun getSuperClass(specifier: KtSuperTypeListEntry): ClassDescriptor = CodegenUtil.getSuperClassBySuperTypeListEntry(specifier, bindingContext()) private fun generateDelegates(toClass: ClassDescriptor, field: Field) { for ((descriptor, overriddenDescriptor) in DelegationResolver.getDelegates(classDescriptor, toClass)) { when (descriptor) { is PropertyDescriptor -> generateDelegateCallForPropertyMember(descriptor, field.name) is FunctionDescriptor -> generateDelegateCallForFunctionMember(descriptor, overriddenDescriptor as FunctionDescriptor, field.name) else -> throw IllegalArgumentException("Expected property or function $descriptor") } } } private fun generateDelegateCallForPropertyMember( descriptor: PropertyDescriptor, delegateName: JsName ) { val propertyName: String = descriptor.name.asString() fun generateDelegateGetterFunction(getterDescriptor: PropertyGetterDescriptor): JsFunction { val delegateRef = JsNameRef(delegateName, phpThisRef()) val returnExpression: JsExpression = if (DescriptorUtils.isExtension(descriptor)) { val getterName = context().getNameForDescriptor(getterDescriptor) val receiver = Namer.getReceiverParameterName() JsInvocation(JsNameRef(getterName, delegateRef), JsNameRef(receiver)) } else { JsNameRef(propertyName, delegateRef) } val jsFunction = simpleReturnFunction(context().getScopeForDescriptor(getterDescriptor.containingDeclaration), returnExpression) if (DescriptorUtils.isExtension(descriptor)) { val receiverName = jsFunction.scope.declareName(Namer.getReceiverParameterName()) jsFunction.parameters.add(JsParameter(receiverName)) } return jsFunction } fun generateDelegateSetterFunction(setterDescriptor: PropertySetterDescriptor): JsFunction { val jsFunction = JsFunction(context().program().rootScope, "setter for " + setterDescriptor.name.asString()) assert(setterDescriptor.valueParameters.size == 1) { "Setter must have 1 parameter" } val defaultParameter = JsParameter(jsFunction.scope.declareTemporary()) val defaultParameterRef = defaultParameter.name.makeRef() val delegateRef = JsNameRef(delegateName, phpThisRef()) // TODO: remove explicit type annotation when Kotlin compiler works this out val setExpression: JsExpression = if (DescriptorUtils.isExtension(descriptor)) { val setterName = context().getNameForDescriptor(setterDescriptor) val setterNameRef = JsNameRef(setterName, delegateRef) val extensionFunctionReceiverName = jsFunction.scope.declareName(Namer.getReceiverParameterName()) jsFunction.parameters.add(JsParameter(extensionFunctionReceiverName)) JsInvocation(setterNameRef, JsNameRef(extensionFunctionReceiverName), defaultParameterRef) } else { val propertyNameRef = JsNameRef(propertyName, delegateRef) JsAstUtils.assignment(propertyNameRef, defaultParameterRef) } jsFunction.parameters.add(defaultParameter) jsFunction.body = JsBlock(setExpression.makeStmt()) return jsFunction } fun generateDelegateAccessor(accessorDescriptor: PropertyAccessorDescriptor, function: JsFunction): JsPropertyInitializer = translateFunctionAsEcma5PropertyDescriptor(function, accessorDescriptor, context()) fun generateDelegateGetter(): JsPropertyInitializer { val getterDescriptor = descriptor.getter ?: throw IllegalStateException("Getter descriptor should not be null") return generateDelegateAccessor(getterDescriptor, generateDelegateGetterFunction(getterDescriptor)) } fun generateDelegateSetter(): JsPropertyInitializer { val setterDescriptor = descriptor.setter ?: throw IllegalStateException("Setter descriptor should not be null") return generateDelegateAccessor(setterDescriptor, generateDelegateSetterFunction(setterDescriptor)) } // TODO: same logic as in AbstractDeclarationVisitor if (descriptor.isExtensionProperty || TranslationUtils.shouldAccessViaFunctions(descriptor)) { val getter = descriptor.getter!! context().addFunctionToPrototype(classDescriptor, getter, generateDelegateGetterFunction(getter)) if (descriptor.isVar) { val setter = descriptor.setter!! context().addFunctionToPrototype(classDescriptor, setter, generateDelegateSetterFunction(setter)) } } else { val literal = JsObjectLiteral(true) literal.propertyInitializers.addGetterAndSetter(descriptor, ::generateDelegateGetter, ::generateDelegateSetter) context().addAccessorsToPrototype(classDescriptor, descriptor, literal) } } private fun generateDelegateCallForFunctionMember( descriptor: FunctionDescriptor, overriddenDescriptor: FunctionDescriptor, delegateName: JsName ) { val delegateRef = JsNameRef(delegateName, phpThisRef()) generateDelegateCall(classDescriptor, descriptor, overriddenDescriptor, delegateRef, context()) } }
apache-2.0
a971a7bff8962ed1c74d9f2a3e912474
48.59
140
0.701452
5.568782
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplacePutWithAssignmentInspection.kt
2
5167
// 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.inspections import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.DefaultBuiltIns import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.util.calleeTextRangeInThis import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.util.getExplicitReceiverValue import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf import org.jetbrains.kotlin.resolve.descriptorUtil.overriddenTreeAsSequence import org.jetbrains.kotlin.utils.addToStdlib.safeAs class ReplacePutWithAssignmentInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>( KtDotQualifiedExpression::class.java ) { override fun isApplicable(element: KtDotQualifiedExpression): Boolean { if (element.receiverExpression is KtSuperExpression) return false val callExpression = element.callExpression if (callExpression?.valueArguments?.size != 2) return false val calleeExpression = callExpression.calleeExpression as? KtNameReferenceExpression ?: return false if (calleeExpression.getReferencedName() !in compatibleNames) return false val context = element.analyze() if (element.isUsedAsExpression(context)) return false // This fragment had to be added because of incorrect behaviour of isUsesAsExpression // TODO: remove it after fix of KT-25682 val binaryExpression = element.getStrictParentOfType<KtBinaryExpression>() val right = binaryExpression?.right if (binaryExpression?.operationToken == KtTokens.ELVIS && right != null && (right == element || KtPsiUtil.deparenthesize(right) == element) ) return false val resolvedCall = element.getResolvedCall(context) val receiverType = resolvedCall?.getExplicitReceiverValue()?.type ?: return false val receiverClass = receiverType.constructor.declarationDescriptor as? ClassDescriptor ?: return false if (!receiverClass.isSubclassOf(DefaultBuiltIns.Instance.mutableMap)) return false val overriddenTree = resolvedCall.resultingDescriptor.safeAs<CallableMemberDescriptor>()?.overriddenTreeAsSequence(true) ?: return false if (overriddenTree.none { it.fqNameOrNull() == mutableMapPutFqName }) return false val assignment = createAssignmentExpression(element) ?: return false val newContext = assignment.analyzeAsReplacement(element, context) return assignment.left.getResolvedCall(newContext)?.resultingDescriptor?.fqNameOrNull() == collectionsSetFqName } override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) { val assignment = createAssignmentExpression(element) ?: return element.replace(assignment) } private fun createAssignmentExpression(element: KtDotQualifiedExpression): KtBinaryExpression? { val valueArguments = element.callExpression?.valueArguments ?: return null val firstArg = valueArguments[0]?.getArgumentExpression() ?: return null val secondArg = valueArguments[1]?.getArgumentExpression() ?: return null val label = if (secondArg is KtLambdaExpression) { val returnLabel = secondArg.findDescendantOfType<KtReturnExpression>()?.getLabelName() compatibleNames.firstOrNull { it == returnLabel }?.plus("@") ?: "" } else "" return KtPsiFactory(element).createExpressionByPattern( "$0[$1] = $label$2", element.receiverExpression, firstArg, secondArg, reformat = false ) as? KtBinaryExpression } override fun inspectionHighlightRangeInElement(element: KtDotQualifiedExpression) = element.calleeTextRangeInThis() override fun inspectionText(element: KtDotQualifiedExpression): String = KotlinBundle.message("map.put.should.be.converted.to.assignment") override val defaultFixText get() = KotlinBundle.message("convert.put.to.assignment") companion object { private val compatibleNames = setOf("put") private val collectionsSetFqName = FqName("kotlin.collections.set") private val mutableMapPutFqName = FqName("kotlin.collections.MutableMap.put") } }
apache-2.0
6ab178eb8564d95331a0cf1158b7f6c7
51.734694
158
0.764467
5.502662
false
false
false
false
vovagrechka/fucking-everything
alraune/alraune/src/main/java/alraune/AdHocPage.kt
1
2590
package alraune import alraune.entity.* import com.esotericsoftware.kryo.io.Input import com.esotericsoftware.kryo.io.Output import pieces100.* import vgrechka.* import java.sql.Timestamp object AdHocPage { val pathPrefix = "/adhoc-" interface Serde { fun serialize(record: AdHocPageRecord, spit: () -> Unit) fun deserialize(record: AdHocPageRecord): () -> Unit } object XStreamSerde : Serde { override fun serialize(record: AdHocPageRecord, spit: () -> Unit) { val xml = AlGlobal0.xstream.toXML(spit) // AlDebug3.writeTempTextFile_openVim(xml) record.textData = xml } override fun deserialize(record: AdHocPageRecord): () -> Unit { val xml = record.textData!! // AlDebug.writeTempTextFile_openVim(xml) return AlGlobal0.xstream.fromXML(xml).cast() } } object KryoSerde : Serde { private val bufferSize = 4096 private val maxBufferSize = 40960 override fun serialize(record: AdHocPageRecord, spit: () -> Unit) { // Log.TRACE() val kryo = AlGlobal.kryo.get() val out = Output(bufferSize, maxBufferSize) kryo.writeClassAndObject(out, spit) out.close() record.byteData = out.buffer } override fun deserialize(record: AdHocPageRecord): () -> Unit { Input(record.byteData).use {input-> return AlGlobal.kryo.get().readClassAndObject(input).cast() } } } fun maybeSpit(path: String): Boolean { if (path.startsWith(pathPrefix)) { val uuid = path.substring(pathPrefix.length) val record = dbSelectMaybeAdHocPageRecordByUuid(uuid) if (record == null) { bailOutToLittleErrorPage(t("TOTE", "Нет нихера такой страницы (либо была, но протухла)")) } else { val spit = record.serde.deserialize(record) spit() return true } } return false } fun makeAdHocPageHref(serde: Serde = XStreamSerde, spit: () -> Unit): String { val uuid = uuid() val page = AdHocPageRecord().fill( uuid = uuid, createdAt = Timestamp(System.currentTimeMillis()), userId = rctx0.al.maybeUser()?.id, serde = serde, textData = null, byteData = null) serde.serialize(page, spit) rctx0.al.db.insertEntity(page) return AdHocPage.pathPrefix + uuid } }
apache-2.0
60ea448e274be36b58f7a5163dbce0b1
30.875
110
0.589804
4.10628
false
false
false
false
holgerbrandl/opencards
src/info/opencards/md/MarkdownParser.kt
1
4419
package info.opencards.md import info.opencards.Utils import info.opencards.ui.preferences.AdvancedSettings.* import org.intellij.markdown.ast.ASTNode import org.intellij.markdown.flavours.gfm.GFMFlavourDescriptor import org.intellij.markdown.html.HtmlGenerator import org.intellij.markdown.parser.LinkMap import org.intellij.markdown.parser.MarkdownParser import java.io.File import java.io.IOException import java.net.URI import java.nio.charset.Charset import java.nio.file.Files import java.nio.file.Paths fun main(args: Array<String>) { // parseMD(File("/Users/holger/projects/opencards/oc2/testdata/markdown/kotlin_qa.md")) val exampleMarkdown = """ ## This is a header blabla > some citation """.trimIndent() val markdownParser = MarkdownParser(GFMFlavourDescriptor()) val parsedTree = markdownParser.buildMarkdownTreeFromString(exampleMarkdown) val htmlGeneratingProviders = GFMFlavourDescriptor().createHtmlGeneratingProviders(LinkMap.buildLinkMap(parsedTree, exampleMarkdown), null) val html = HtmlGenerator(exampleMarkdown, parsedTree, htmlGeneratingProviders, true).generateHtml() print(html) } data class MarkdownFlashcard(val question: String, val answer: String) fun parseMD(file: File, useSelector: Boolean = false): List<MarkdownFlashcard> { val text = readFile(file.absolutePath, Charset.defaultCharset()) val markdownParser = MarkdownParser(GFMFlavourDescriptor()) val parsedTree = markdownParser.buildMarkdownTreeFromString(text) // parsedTree.children[0] // val html = makeHtml(parsedTree, text, file.toURI()) // System.err.println("html is :\n" + html) // parsedTree.children.filter { it is CompositeASTNode }.forEach { println("$it : ${makeHtml(it, text, file.toURI())}") } var blockCounter = 0 val sections = parsedTree.children.map { makeHtml(it, text, file.toURI()) }.groupBy { if (it.contains("^<h[123]{1}".toRegex())) { blockCounter += 1 } blockCounter }.map { it.value } // check if some are tagged as [qa] // val qaSelector = "[qa]" // see http://stackoverflow.com/questions/1140268/how-to-escape-a-square-bracket-for-pattern-compilation // val qaSelector = Pattern.quote("[qa]") // val qaSelector= "\\Q[qa]\\E".toRegex() val qaSelector = Utils.getPrefs().get(MARKDOWN_QA_SELECTOR, MARKDOWN_QA_SELECTOR_DEFAULT).toRegex() // we could auto-detect selector usage here but since there is a checkbox for it we better don't do so // val isQA = useSelector && sections.find { it.first().contains(qaSelector) } != null val isQA = useSelector //&& sections.find { it.first().contains(qaSelector) } != null // Slide title example |<h2 md-src-pos="0..28">best question ever4? [qa]</h2> // Slide title example <h2 md-src-pos="48..66">what is kotlin?</h2> val removeSelectorFromTitle = Utils.getPrefs().getBoolean(MARKDOWN_REMOVE_SELECTOR, MARKDOWN_REMOVE_SELECTOR_DEFAULT) // try to extract the questions val cards = sections. // rermove empty sections filter { it.size > 1 }. // remove non-QA elements when being in qa mode filter { !isQA || it.first().contains(qaSelector) }. // create question to answer map map { var question = it.first() // optionally remove selector question = if (removeSelectorFromTitle) question.replace(qaSelector, "") else question // normalize question size to be h2 question = question.replace("<h[1234]".toRegex(), "<h1").replace("h[1234]>".toRegex(), "h1>").trim() val answer = it.drop(1).takeWhile { !it.startsWith("<hr") }.joinToString("\n") MarkdownFlashcard(question, answer) } return cards } internal fun makeHtml(parsedTree: ASTNode, text: String, baseURI: URI): String { val htmlGeneratingProviders = GFMFlavourDescriptor().createHtmlGeneratingProviders(LinkMap.buildLinkMap(parsedTree, text), baseURI) val html = HtmlGenerator(text, parsedTree, htmlGeneratingProviders, true).generateHtml() return html } @Throws(IOException::class) internal fun readFile(path: String, encoding: Charset): String { val encoded = Files.readAllBytes(Paths.get(path)) return String(encoded, encoding) }
bsd-2-clause
181492e4ee50878f55a0adfb0de69777
35.825
143
0.68296
4.054128
false
false
false
false
androidx/androidx
datastore/datastore-core/src/commonMain/kotlin/androidx/datastore/core/SingleProcessDataStore.kt
3
12541
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.datastore.core import androidx.datastore.core.handlers.NoOpCorruptionHandler import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.completeWith import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.dropWhile import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlin.coroutines.CoroutineContext import kotlin.coroutines.coroutineContext /** * Single process implementation of DataStore. This is NOT multi-process safe. */ internal class SingleProcessDataStore<T>( private val storage: Storage<T>, /** * The list of initialization tasks to perform. These tasks will be completed before any data * is published to the data and before any read-modify-writes execute in updateData. If * any of the tasks fail, the tasks will be run again the next time data is collected or * updateData is called. Init tasks should not wait on results from data - this will * result in deadlock. */ initTasksList: List<suspend (api: InitializerApi<T>) -> Unit> = emptyList(), private val corruptionHandler: CorruptionHandler<T> = NoOpCorruptionHandler<T>(), private val scope: CoroutineScope = CoroutineScope(ioDispatcher() + SupervisorJob()) ) : DataStore<T> { val connection: StorageConnection<T> by lazy { storage.createConnection() } override val data: Flow<T> = flow { /** * If downstream flow is UnInitialized, no data has been read yet, we need to trigger a new * read then start emitting values once we have seen a new value (or exception). * * If downstream flow has a ReadException, there was an exception last time we tried to read * data. We need to trigger a new read then start emitting values once we have seen a new * value (or exception). * * If downstream flow has Data, we should just start emitting from downstream flow. * * If Downstream flow is Final, the scope has been cancelled so the data store is no * longer usable. We should just propagate this exception. * * State always starts at null. null can transition to ReadException, Data or * Final. ReadException can transition to another ReadException, Data or Final. * Data can transition to another Data or Final. Final will not change. */ val currentDownStreamFlowState = downstreamFlow.value if (currentDownStreamFlowState !is Data) { // We need to send a read request because we don't have data yet. actor.offer(Message.Read(currentDownStreamFlowState)) } emitAll( downstreamFlow.dropWhile { if (currentDownStreamFlowState is Data<T> || currentDownStreamFlowState is Final<T> ) { // We don't need to drop any Data or Final values. false } else { // we need to drop the last seen state since it was either an exception or // wasn't yet initialized. Since we sent a message to actor, we *will* see a // new value. it === currentDownStreamFlowState } }.map { when (it) { is ReadException<T> -> throw it.readException is Final<T> -> throw it.finalException is Data<T> -> it.value is UnInitialized -> error( "This is a bug in DataStore. Please file a bug at: " + "https://issuetracker.google.com/issues/new?" + "component=907884&template=1466542" ) } } ) } override suspend fun updateData(transform: suspend (t: T) -> T): T { /** * The states here are the same as the states for reads. Additionally we send an ack that * the actor *must* respond to (even if it is cancelled). */ val ack = CompletableDeferred<T>() val currentDownStreamFlowState = downstreamFlow.value val updateMsg = Message.Update(transform, ack, currentDownStreamFlowState, coroutineContext) actor.offer(updateMsg) return ack.await() } @Suppress("UNCHECKED_CAST") private val downstreamFlow = MutableStateFlow(UnInitialized as State<T>) private var initTasks: List<suspend (api: InitializerApi<T>) -> Unit>? = initTasksList.toList() private val actor = SimpleActor<Message<T>>( scope = scope, onComplete = { it?.let { downstreamFlow.value = Final(it) } // We expect it to always be non-null but we will leave the alternative as a no-op // just in case. connection.close() }, onUndeliveredElement = { msg, ex -> if (msg is Message.Update) { // TODO(rohitsat): should we instead use scope.ensureActive() to get the original // cancellation cause? Should we instead have something like // UndeliveredElementException? msg.ack.completeExceptionally( ex ?: CancellationException( "DataStore scope was cancelled before updateData could complete" ) ) } } ) { msg -> when (msg) { is Message.Read -> { handleRead(msg) } is Message.Update -> { handleUpdate(msg) } } } private suspend fun handleRead(read: Message.Read<T>) { when (val currentState = downstreamFlow.value) { is Data -> { // We already have data so just return... } is ReadException -> { if (currentState === read.lastState) { readAndInitOrPropagateFailure() } // Someone else beat us but also failed. The collector has already // been signalled so we don't need to do anything. } UnInitialized -> { readAndInitOrPropagateFailure() } is Final -> error("Can't read in final state.") // won't happen } } private suspend fun handleUpdate(update: Message.Update<T>) { // All branches of this *must* complete ack either successfully or exceptionally. // We must *not* throw an exception, just propagate it to the ack. update.ack.completeWith( runCatching { when (val currentState = downstreamFlow.value) { is Data -> { // We are already initialized, we just need to perform the update transformAndWrite(update.transform, update.callerContext) } is ReadException, is UnInitialized -> { if (currentState === update.lastState) { // we need to try to read again readAndInitOrPropagateAndThrowFailure() // We've successfully read, now we need to perform the update transformAndWrite(update.transform, update.callerContext) } else { // Someone else beat us to read but also failed. We just need to // signal the writer that is waiting on ack. // This cast is safe because we can't be in the UnInitialized // state if the state has changed. throw (currentState as ReadException).readException } } is Final -> throw currentState.finalException // won't happen } } ) } private suspend fun readAndInitOrPropagateAndThrowFailure() { try { readAndInit() } catch (throwable: Throwable) { downstreamFlow.value = ReadException(throwable) throw throwable } } private suspend fun readAndInitOrPropagateFailure() { try { readAndInit() } catch (throwable: Throwable) { downstreamFlow.value = ReadException(throwable) } } private suspend fun readAndInit() { // This should only be called if we don't already have cached data. check(downstreamFlow.value == UnInitialized || downstreamFlow.value is ReadException) val updateLock = Mutex() var initData = readDataOrHandleCorruption() var initializationComplete: Boolean = false // TODO(b/151635324): Consider using Context Element to throw an error on re-entrance. val api = object : InitializerApi<T> { override suspend fun updateData(transform: suspend (t: T) -> T): T { return updateLock.withLock() { if (initializationComplete) { throw IllegalStateException( "InitializerApi.updateData should not be " + "called after initialization is complete." ) } val newData = transform(initData) if (newData != initData) { connection.writeData(newData) initData = newData } initData } } } initTasks?.forEach { it(api) } initTasks = null // Init tasks have run successfully, we don't need them anymore. updateLock.withLock { initializationComplete = true } downstreamFlow.value = Data(initData, initData.hashCode()) } private suspend fun readDataOrHandleCorruption(): T { try { return connection.readData() } catch (ex: CorruptionException) { val newData: T = corruptionHandler.handleCorruption(ex) try { connection.writeData(newData) } catch (writeEx: IOException) { // If we fail to write the handled data, add the new exception as a suppressed // exception. ex.addSuppressed(writeEx) throw ex } // If we reach this point, we've successfully replaced the data on disk with newData. return newData } } // downstreamFlow.value must be successfully set to data before calling this private suspend fun transformAndWrite( transform: suspend (t: T) -> T, callerContext: CoroutineContext ): T { // value is not null or an exception because we must have the value set by now so this cast // is safe. val curDataAndHash = downstreamFlow.value as Data<T> curDataAndHash.checkHashCode() val curData = curDataAndHash.value val newData = withContext(callerContext) { transform(curData) } // Check that curData has not changed... curDataAndHash.checkHashCode() return if (curData == newData) { curData } else { connection.writeData(newData) downstreamFlow.value = Data(newData, newData.hashCode()) newData } } }
apache-2.0
27f2f39b9892c6fd95eb474411289fad
37.947205
100
0.58241
5.203734
false
false
false
false
androidx/androidx
work/work-inspection/src/main/java/androidx/work/inspection/WorkManagerInspector.kt
3
11690
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.work.inspection import android.app.Application import android.os.Handler import android.os.Looper import androidx.inspection.Connection import androidx.inspection.Inspector import androidx.inspection.InspectorEnvironment import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import androidx.work.WorkManager import androidx.work.impl.WorkContinuationImpl import androidx.work.impl.WorkManagerImpl import androidx.work.impl.model.WorkSpec import androidx.work.inspection.WorkManagerInspectorProtocol.Command import androidx.work.inspection.WorkManagerInspectorProtocol.Command.OneOfCase.CANCEL_WORK import androidx.work.inspection.WorkManagerInspectorProtocol.Command.OneOfCase.TRACK_WORK_MANAGER import androidx.work.inspection.WorkManagerInspectorProtocol.ErrorResponse import androidx.work.inspection.WorkManagerInspectorProtocol.Event import androidx.work.inspection.WorkManagerInspectorProtocol.Response import androidx.work.inspection.WorkManagerInspectorProtocol.TrackWorkManagerResponse import androidx.work.inspection.WorkManagerInspectorProtocol.WorkAddedEvent import androidx.work.inspection.WorkManagerInspectorProtocol.WorkRemovedEvent import androidx.work.inspection.WorkManagerInspectorProtocol.WorkUpdatedEvent import java.util.UUID import java.util.concurrent.CountDownLatch import java.util.concurrent.Executor /** * Inspector to work with WorkManager */ class WorkManagerInspector( connection: Connection, environment: InspectorEnvironment ) : Inspector(connection), LifecycleOwner { private val lifecycleRegistry = LifecycleRegistry(this) private val workManager: WorkManagerImpl private val executor = environment.executors().primary() private val stackTraceMap = mutableMapOf<String, List<StackTraceElement>>() private val mainHandler = Handler(Looper.getMainLooper()) init { workManager = environment.artTooling().findInstances(Application::class.java).first() .let { application -> WorkManager.getInstance(application) as WorkManagerImpl } mainHandler.post { lifecycleRegistry.currentState = Lifecycle.State.STARTED } environment.artTooling().registerEntryHook( WorkContinuationImpl::class.java, "enqueue()Landroidx/work/Operation;" ) { obj, _ -> val stackTrace = Throwable().stackTrace executor.execute { (obj as? WorkContinuationImpl)?.allIds?.forEach { id -> stackTraceMap[id] = stackTrace.toList().prune() } } } } override fun onReceiveCommand(data: ByteArray, callback: CommandCallback) { val command = Command.parseFrom(data) when (command.oneOfCase) { TRACK_WORK_MANAGER -> { val response = Response.newBuilder() .setTrackWorkManager(TrackWorkManagerResponse.getDefaultInstance()) .build() workManager .workDatabase .workSpecDao() .getAllWorkSpecIdsLiveData() .safeObserveWhileNotNull(this, executor) { oldList, newList -> updateWorkIdList(oldList ?: listOf(), newList) } callback.reply(response.toByteArray()) } CANCEL_WORK -> { val response = Response.newBuilder() .setTrackWorkManager(TrackWorkManagerResponse.getDefaultInstance()) .build() workManager.cancelWorkById(UUID.fromString(command.cancelWork.id)).result .addListener(Runnable { callback.reply(response.toByteArray()) }, executor) } else -> { val errorResponse = ErrorResponse.newBuilder() .setContent("Unrecognised command type: ONEOF_NOT_SET") .build() val response = Response.newBuilder() .setError(errorResponse) .build() callback.reply(response.toByteArray()) } } } /** * Allows to observe LiveDatas from non-main thread. * <p> * Observation will last until "null" value is dispatched, then * observer will be automatically removed. */ private fun <T> LiveData<T>.safeObserveWhileNotNull( owner: LifecycleOwner, executor: Executor, listener: (oldValue: T?, newValue: T) -> Unit ) { mainHandler.post { observe( owner, object : Observer<T> { private var lastValue: T? = null override fun onChanged(t: T) { if (t == null) { removeObserver(this) } else { executor.execute { listener(lastValue, t) lastValue = t } } } } ) } } /** * Prune internal [StackTraceElement]s above [WorkContinuationImpl.enqueue] or from * work manager libraries. */ private fun List<StackTraceElement>.prune(): List<StackTraceElement> { val entryHookIndex = indexOfFirst { it.className.startsWith("androidx.work.impl.WorkContinuationImpl") && it.methodName == "enqueue" } if (entryHookIndex != -1) { return subList(entryHookIndex + 1, size) .dropWhile { it.className.startsWith("androidx.work") } } return this } private fun createWorkInfoProto(id: String): WorkManagerInspectorProtocol.WorkInfo? { // work can be removed by the time we try to access it, so if null was return let's just // skip it val workSpec = workManager.workDatabase.workSpecDao().getWorkSpec(id) ?: return null val workInfoBuilder = WorkManagerInspectorProtocol.WorkInfo.newBuilder() workInfoBuilder.id = id workInfoBuilder.state = workSpec.state.toProto() workInfoBuilder.workerClassName = workSpec.workerClassName workInfoBuilder.data = workSpec.output.toProto() workInfoBuilder.runAttemptCount = workSpec.runAttemptCount workInfoBuilder.isPeriodic = workSpec.isPeriodic workInfoBuilder.constraints = workSpec.constraints.toProto() workManager.getWorkInfoById(UUID.fromString(id)).let { workInfoBuilder.addAllTags(it.get().tags) } val workStackBuilder = WorkManagerInspectorProtocol.CallStack.newBuilder() stackTraceMap[id]?.let { stack -> workStackBuilder.addAllFrames(stack.map { it.toProto() }) } workInfoBuilder.callStack = workStackBuilder.build() workInfoBuilder.scheduleRequestedAt = WorkSpec.SCHEDULE_NOT_REQUESTED_YET workManager.workDatabase.dependencyDao().getPrerequisites(id).let { workInfoBuilder.addAllPrerequisites(it) } workManager.workDatabase.dependencyDao().getDependentWorkIds(id).let { workInfoBuilder.addAllDependents(it) } workManager.workDatabase.workNameDao().getNamesForWorkSpecId(id).let { workInfoBuilder.addAllNames(it) } return workInfoBuilder.build() } private fun observeWorkUpdates(id: String) { val workInfoLiveData = workManager.getWorkInfoByIdLiveData(UUID.fromString(id)) workInfoLiveData.safeObserveWhileNotNull(this, executor) { oldWorkInfo, newWorkInfo -> if (oldWorkInfo?.state != newWorkInfo.state) { val updateWorkEvent = WorkUpdatedEvent.newBuilder() .setId(id) .setState( WorkManagerInspectorProtocol.WorkInfo.State .forNumber(newWorkInfo.state.ordinal + 1) ) .build() connection.sendEvent( Event.newBuilder().setWorkUpdated(updateWorkEvent).build().toByteArray() ) } if (oldWorkInfo?.runAttemptCount != newWorkInfo.runAttemptCount) { val updateWorkEvent = WorkUpdatedEvent.newBuilder() .setId(id) .setRunAttemptCount(newWorkInfo.runAttemptCount) .build() connection.sendEvent( Event.newBuilder().setWorkUpdated(updateWorkEvent).build().toByteArray() ) } if (oldWorkInfo?.outputData != newWorkInfo.outputData) { val updateWorkEvent = WorkUpdatedEvent.newBuilder() .setId(id) .setData(newWorkInfo.outputData.toProto()) .build() connection.sendEvent( Event.newBuilder().setWorkUpdated(updateWorkEvent).build().toByteArray() ) } } workManager.workDatabase .workSpecDao() .getScheduleRequestedAtLiveData(id) .safeObserveWhileNotNull(this, executor) { _, newScheduledTime -> val updateWorkEvent = WorkUpdatedEvent.newBuilder() .setId(id) .setScheduleRequestedAt(newScheduledTime) .build() connection.sendEvent( Event.newBuilder().setWorkUpdated(updateWorkEvent).build().toByteArray() ) } } private fun updateWorkIdList(oldWorkIds: List<String>, newWorkIds: List<String>) { for (removedId in oldWorkIds.minus(newWorkIds)) { val removeEvent = WorkRemovedEvent.newBuilder().setId(removedId).build() val event = Event.newBuilder().setWorkRemoved(removeEvent).build() connection.sendEvent(event.toByteArray()) } for (addedId in newWorkIds.minus(oldWorkIds)) { val workInfoProto = createWorkInfoProto(addedId) ?: continue val addEvent = WorkAddedEvent.newBuilder().setWork(workInfoProto) .build() val event = Event.newBuilder().setWorkAdded(addEvent).build() connection.sendEvent(event.toByteArray()) observeWorkUpdates(addedId) } } override fun onDispose() { super.onDispose() val latch = CountDownLatch(1) mainHandler.post { lifecycleRegistry.currentState = Lifecycle.State.DESTROYED latch.countDown() } // await to make sure that all observers that registered by inspector are gone // otherwise they can post message to "disposed" inspector latch.await() } override fun getLifecycle(): Lifecycle { return lifecycleRegistry } }
apache-2.0
e50404c5b2db0d43bb3f6c72c7aff213
39.731707
97
0.626861
5.299184
false
false
false
false
YutaKohashi/FakeLineApp
app/src/main/java/jp/yuta/kohashi/fakelineapp/fragments/MainFragment.kt
1
2827
package jp.yuta.kohashi.fakelineapp.fragments import android.content.Intent import android.graphics.Bitmap import android.graphics.Color import android.os.Bundle import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.ImageView import jp.yuta.kohashi.fakelineapp.R import jp.yuta.kohashi.fakelineapp.activities.ImagesActivity import jp.yuta.kohashi.fakelineapp.activities.TalkSettingsActivity import jp.yuta.kohashi.fakelineapp.utils.Util import kotlinx.android.synthetic.main.fragment_main.* /** * Author : yutakohashi * Project name : FakeLineApp * Date : 19 / 08 / 2017 */ class MainFragment: BaseFragment(){ private val FILE_NAME_HACKER_100 = "hacker_100.jpg" private val FILE_NAME_HACKER_070 = "hacker_70.jpg" private val FILE_NAME_HACKER_050 = "hacker_50.jpg" override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment return inflater!!.inflate(R.layout.fragment_main, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val bmp: Bitmap? = Util.loadBitmapFromAssets(FILE_NAME_HACKER_100) ?:Util.loadBitmapFromAssets(FILE_NAME_HACKER_070) ?:Util.loadBitmapFromAssets(FILE_NAME_HACKER_050) bmp?.let { imageView.setImageBitmap(it) imageView.scaleType = ImageView.ScaleType.CENTER_CROP } } override fun setEvent() { // 新規作成 createNewView.setOnClickListener{ startActivity(Intent(activity, TalkSettingsActivity::class.java)) activity.overridePendingTransition(R.anim.anim_fade_in, R.anim.anim_fade_out) } captureSavedFiles.setOnClickListener { startActivity(Intent(activity, ImagesActivity::class.java)) } settingsButton.setOnClickListener{ AboutDialogFragment().show(fragmentManager, MainFragment::class.java.simpleName) } createNewView.setOnTouchListener { _, motionEvent -> when(motionEvent.action){ MotionEvent.ACTION_DOWN -> icEditImageView.setColorFilter(Color.LTGRAY) MotionEvent.ACTION_UP -> icEditImageView.setColorFilter(Color.WHITE) } false } captureSavedFiles.setOnTouchListener { _, motionEvent -> when(motionEvent.action){ MotionEvent.ACTION_DOWN -> icSaveImageView.setColorFilter(Color.LTGRAY) MotionEvent.ACTION_UP -> icSaveImageView.setColorFilter(Color.WHITE) } false } } }
mit
92e8a3f95c0cf9a061035586564f2a65
34.25
92
0.681093
4.418495
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantVisibilityModifierInspection.kt
1
4161
// 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.inspections import com.intellij.codeInspection.* import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.config.AnalysisFlags import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.descriptors.DescriptorVisibility import org.jetbrains.kotlin.config.ExplicitApiMode import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.implicitVisibility import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.quickfix.RemoveModifierFix import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtPropertyAccessor import org.jetbrains.kotlin.psi.declarationVisitor import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.isPrivate import org.jetbrains.kotlin.psi.psiUtil.visibilityModifier import org.jetbrains.kotlin.resolve.descriptorUtil.isEffectivelyPublicApi import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult class RedundantVisibilityModifierInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return declarationVisitor(fun(declaration: KtDeclaration) { val isInApiMode = declaration.languageVersionSettings.getFlag(AnalysisFlags.explicitApiMode) != ExplicitApiMode.DISABLED if (declaration is KtPropertyAccessor && declaration.isGetter) return // There is a quick fix for REDUNDANT_MODIFIER_IN_GETTER val visibilityModifier = declaration.visibilityModifier() ?: return val implicitVisibility = declaration.implicitVisibility() if (isInApiMode && (declaration.resolveToDescriptorIfAny() as? DeclarationDescriptorWithVisibility)?.isEffectivelyPublicApi == true) return@declarationVisitor val redundantVisibility = when { visibilityModifier.node.elementType == implicitVisibility -> implicitVisibility declaration.hasModifier(KtTokens.INTERNAL_KEYWORD) && declaration.containingClassOrObject?.let { it.isLocal || it.isPrivate() } == true -> KtTokens.INTERNAL_KEYWORD else -> null } ?: return if (redundantVisibility == KtTokens.PUBLIC_KEYWORD && declaration is KtProperty && declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD) && declaration.isVar && declaration.setterVisibility().let { it != null && it != DescriptorVisibilities.PUBLIC } ) return holder.registerProblem( visibilityModifier, KotlinBundle.message("redundant.visibility.modifier"), ProblemHighlightType.LIKE_UNUSED_SYMBOL, IntentionWrapper(RemoveModifierFix(declaration, redundantVisibility, isRedundant = true)) ) }) } private fun KtProperty.setterVisibility(): DescriptorVisibility? { val descriptor = descriptor as? PropertyDescriptor ?: return null if (setter?.visibilityModifier() != null) { val visibility = descriptor.setter?.visibility if (visibility != null) return visibility } return (descriptor as? CallableMemberDescriptor) ?.overriddenDescriptors ?.firstNotNullResult { (it as? PropertyDescriptor)?.setter } ?.visibility } }
apache-2.0
ea43e0b7aa321d76b1065efeb85f3f24
51.670886
170
0.732276
5.630582
false
false
false
false
mglukhikh/intellij-community
uast/uast-common/src/org/jetbrains/uast/expressions/UCallExpression.kt
2
3560
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast import com.intellij.psi.PsiMethod import com.intellij.psi.PsiType import org.jetbrains.uast.internal.acceptList import org.jetbrains.uast.internal.log import org.jetbrains.uast.visitor.UastTypedVisitor import org.jetbrains.uast.visitor.UastVisitor /** * Represents a call expression (method/constructor call, array initializer). */ interface UCallExpression : UExpression, UResolvable { /** * Returns the call kind. */ val kind: UastCallKind /** * Returns the called method name, or null if the call is not a method call. * This property should return the actual resolved function name. */ val methodName: String? /** * Returns the expression receiver. * For example, for call `a.b.[c()]` the receiver is `a.b`. */ val receiver: UExpression? /** * Returns the receiver type, or null if the call has not a receiver. */ val receiverType: PsiType? /** * Returns the function reference expression if the call is a non-constructor method call, null otherwise. */ val methodIdentifier: UIdentifier? /** * Returns the class reference if the call is a constructor call, null otherwise. */ val classReference: UReferenceExpression? /** * Returns the value argument count. * * Retrieving the argument count could be faster than getting the [valueArguments.size], * because there is no need to create actual [UExpression] instances. */ val valueArgumentCount: Int /** * Returns the list of value arguments. */ val valueArguments: List<UExpression> /** * Returns the type argument count. */ val typeArgumentCount: Int /** * Returns the type arguments for the call. */ val typeArguments: List<PsiType> /** * Returns the return type of the called function, or null if the call is not a function call. */ val returnType: PsiType? /** * Resolve the called method. * * @return the [PsiMethod], or null if the method was not resolved. * Note that the [PsiMethod] is an unwrapped [PsiMethod], not a [UMethod]. */ override fun resolve(): PsiMethod? override fun accept(visitor: UastVisitor) { if (visitor.visitCallExpression(this)) return annotations.acceptList(visitor) methodIdentifier?.accept(visitor) classReference?.accept(visitor) valueArguments.acceptList(visitor) visitor.afterVisitCallExpression(this) } override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D) = visitor.visitCallExpression(this, data) override fun asLogString() = log("kind = $kind, argCount = $valueArgumentCount)") override fun asRenderString(): String { val ref = classReference?.asRenderString() ?: methodName ?: methodIdentifier?.asRenderString() ?: "<noref>" return ref + "(" + valueArguments.joinToString { it.asRenderString() } + ")" } } interface UCallExpressionEx : UCallExpression { fun getArgumentForParameter(i: Int): UExpression? }
apache-2.0
e77f06e153692829ea0be3ff16123796
28.675
111
0.711236
4.42236
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/authentication/ui/GithubChooseAccountDialog.kt
2
3946
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.github.authentication.ui import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo import com.intellij.ui.ColoredListCellRenderer import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.JBList import com.intellij.ui.components.JBScrollPane import com.intellij.util.ui.* import org.jetbrains.annotations.Nls import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.i18n.GithubBundle import java.awt.Component import java.awt.Dimension import javax.swing.JComponent import javax.swing.JList import javax.swing.JTextArea import javax.swing.ListSelectionModel class GithubChooseAccountDialog @JvmOverloads constructor(project: Project?, parentComponent: Component?, accounts: Collection<GithubAccount>, @Nls(capitalization = Nls.Capitalization.Sentence) descriptionText: String?, showHosts: Boolean, allowDefault: Boolean, @Nls(capitalization = Nls.Capitalization.Title) title: String = GithubBundle.message( "account.choose.title"), @Nls(capitalization = Nls.Capitalization.Title) okText: String = GithubBundle.message( "account.choose.button")) : DialogWrapper(project, parentComponent, false, IdeModalityType.PROJECT) { private val description: JTextArea? = descriptionText?.let { JTextArea().apply { minimumSize = Dimension(0, 0) font = StartupUiUtil.getLabelFont() text = it lineWrap = true wrapStyleWord = true isEditable = false isFocusable = false isOpaque = false border = null margin = JBInsets.emptyInsets() } } private val accountsList: JBList<GithubAccount> = JBList<GithubAccount>(accounts).apply { selectionMode = ListSelectionModel.SINGLE_SELECTION cellRenderer = object : ColoredListCellRenderer<GithubAccount>() { override fun customizeCellRenderer(list: JList<out GithubAccount>, value: GithubAccount, index: Int, selected: Boolean, hasFocus: Boolean) { append(value.name) if (showHosts) { append(" ") append(value.server.toString(), SimpleTextAttributes.GRAYED_ATTRIBUTES) } border = JBUI.Borders.empty(0, UIUtil.DEFAULT_HGAP) } } } private val setDefaultCheckBox: JBCheckBox? = if (allowDefault) JBCheckBox(GithubBundle.message("account.choose.as.default")) else null init { this.title = title setOKButtonText(okText) init() accountsList.selectedIndex = 0 } override fun getDimensionServiceKey() = "Github.Dialog.Accounts.Choose" override fun doValidate(): ValidationInfo? { return if (accountsList.selectedValue == null) ValidationInfo(GithubBundle.message("account.choose.not.selected"), accountsList) else null } val account: GithubAccount get() = accountsList.selectedValue val setDefault: Boolean get() = setDefaultCheckBox?.isSelected ?: false override fun createCenterPanel(): JComponent? { return JBUI.Panels.simplePanel(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP) .apply { description?.run(::addToTop) } .addToCenter(JBScrollPane(accountsList).apply { preferredSize = JBDimension(150, 20 * (accountsList.itemsCount + 1)) }) .apply { setDefaultCheckBox?.run(::addToBottom) } } override fun getPreferredFocusedComponent() = accountsList }
apache-2.0
486fc509eabed75a56f6e12c9219dcfc
40.989362
137
0.678409
5.071979
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/highlighter/FunctionsHighlightingVisitor.kt
2
3795
// 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.highlighter import com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder import com.intellij.psi.PsiElement import org.jetbrains.kotlin.builtins.isFunctionTypeOrSubtype import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingColors.* import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall import org.jetbrains.kotlin.resolve.calls.tasks.isDynamic import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.serialization.deserialization.KOTLIN_SUSPEND_BUILT_IN_FUNCTION_FQ_NAME import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult internal class FunctionsHighlightingVisitor(holder: HighlightInfoHolder, bindingContext: BindingContext) : AfterAnalysisHighlightingVisitor(holder, bindingContext) { override fun visitBinaryExpression(expression: KtBinaryExpression) { if (expression.operationReference.getIdentifier() != null) { expression.getResolvedCall(bindingContext)?.let { resolvedCall -> highlightCall(expression.operationReference, resolvedCall) } } super.visitBinaryExpression(expression) } override fun visitCallExpression(expression: KtCallExpression) { val callee = expression.calleeExpression val resolvedCall = expression.getResolvedCall(bindingContext) if (callee is KtReferenceExpression && callee !is KtCallExpression && resolvedCall != null) { highlightCall(callee, resolvedCall) } super.visitCallExpression(expression) } private fun highlightCall(callee: PsiElement, resolvedCall: ResolvedCall<out CallableDescriptor>) { val calleeDescriptor = resolvedCall.resultingDescriptor val extensions = HighlighterExtension.EP_NAME.extensionList (extensions.firstNotNullResult { extension -> extension.highlightCall(callee, resolvedCall) } ?: when { calleeDescriptor.fqNameOrNull() == KOTLIN_SUSPEND_BUILT_IN_FUNCTION_FQ_NAME -> KEYWORD calleeDescriptor.isDynamic() -> DYNAMIC_FUNCTION_CALL calleeDescriptor is FunctionDescriptor && calleeDescriptor.isSuspend -> SUSPEND_FUNCTION_CALL resolvedCall is VariableAsFunctionResolvedCall -> { val container = calleeDescriptor.containingDeclaration val containedInFunctionClassOrSubclass = container is ClassDescriptor && container.defaultType.isFunctionTypeOrSubtype if (containedInFunctionClassOrSubclass) VARIABLE_AS_FUNCTION_CALL else VARIABLE_AS_FUNCTION_LIKE_CALL } calleeDescriptor is ConstructorDescriptor -> CONSTRUCTOR_CALL calleeDescriptor !is FunctionDescriptor -> null calleeDescriptor.extensionReceiverParameter != null -> EXTENSION_FUNCTION_CALL DescriptorUtils.isTopLevelDeclaration(calleeDescriptor) -> PACKAGE_FUNCTION_CALL else -> FUNCTION_CALL })?.let { key -> highlightName(callee, key) } } }
apache-2.0
a9c6cec9d32ff2427f46697c22c764df
50.283784
158
0.748353
5.613905
false
false
false
false