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
googlemaps/android-samples
ApiDemos/kotlin/app/src/gms/java/com/example/kotlindemos/SplitStreetViewPanoramaAndMapDemoActivity.kt
1
3587
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.kotlindemos import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener import com.google.android.gms.maps.StreetViewPanorama import com.google.android.gms.maps.StreetViewPanorama.OnStreetViewPanoramaChangeListener import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.SupportStreetViewPanoramaFragment import com.google.android.gms.maps.model.* /** * This shows how to create a simple activity with streetview and a map */ class SplitStreetViewPanoramaAndMapDemoActivity : AppCompatActivity(), OnMarkerDragListener, OnStreetViewPanoramaChangeListener { var streetViewPanorama: StreetViewPanorama? = null var marker: Marker? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.split_street_view_panorama_and_map_demo) val markerPosition = savedInstanceState?.getParcelable(MARKER_POSITION_KEY) ?: SYDNEY val streetViewPanoramaFragment = supportFragmentManager.findFragmentById(R.id.streetviewpanorama) as SupportStreetViewPanoramaFragment? streetViewPanoramaFragment?.getStreetViewPanoramaAsync { panorama -> streetViewPanorama = panorama streetViewPanorama?.setOnStreetViewPanoramaChangeListener( this@SplitStreetViewPanoramaAndMapDemoActivity ) // Only need to set the position once as the streetview fragment will maintain // its state. savedInstanceState ?: streetViewPanorama?.setPosition(SYDNEY) } val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment? mapFragment?.getMapAsync { map -> map.setOnMarkerDragListener(this@SplitStreetViewPanoramaAndMapDemoActivity) // Creates a draggable marker. Long press to drag. marker = map.addMarker( MarkerOptions() .position(markerPosition) .icon(BitmapDescriptorFactory.fromResource(R.drawable.pegman)) .draggable(true) ) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelable( MARKER_POSITION_KEY, marker?.position ) } override fun onStreetViewPanoramaChange(location: StreetViewPanoramaLocation) { marker?.position = location.position } override fun onMarkerDragStart(marker: Marker) {} override fun onMarkerDragEnd(marker: Marker) { streetViewPanorama?.setPosition(marker.position, 150) } override fun onMarkerDrag(marker: Marker) {} companion object { private const val MARKER_POSITION_KEY = "MarkerPosition" // George St, Sydney private val SYDNEY = LatLng(-33.87365, 151.20689) } }
apache-2.0
ab007fc76956370a78f36d492f0c16eb
39.772727
114
0.713131
5.161151
false
false
false
false
google/chromeosnavigationdemo
app/src/main/java/com/emilieroberts/chromeosnavigationdemo/ImageViewerFragment.kt
1
2511
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.emilieroberts.chromeosnavigationdemo import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentStatePagerAdapter import androidx.lifecycle.ViewModelProviders import androidx.viewpager.widget.ViewPager class ImageViewerFragment : Fragment() { lateinit var viewModel : AdaptableDemoViewModel //Remember our header is in the array list so we need to skip the first element override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { val mainView: View = inflater.inflate(R.layout.image_viewer, container, false) viewModel = ViewModelProviders.of(requireActivity()).get(AdaptableDemoViewModel::class.java) val fileSource = viewModel.getFileSource().value val listOfFiles = FileStore.getFilesForSource(fileSource!!) val selectedFileIndex = listOfFiles.indexOfFirst { file -> file.imageId == viewModel.getCurrentPhotoId().value } val pager = mainView.findViewById<ViewPager>(R.id.pager_imageviewer) val pagerAdapter = ImagePagerAdapter(requireFragmentManager(), listOfFiles) pager.adapter = pagerAdapter pager.setCurrentItem(selectedFileIndex - 1, true) return mainView } private inner class ImagePagerAdapter(fragmentManager: FragmentManager, val listOfFiles: List<PhotoFile>) : FragmentStatePagerAdapter(fragmentManager) { override fun getCount(): Int { //Note: we ignore the first element (header) so real size is size - 1 return listOfFiles.size - 1 } override fun getItem(position: Int): Fragment { return ImageFragment.newInstance(listOfFiles[position + 1].imageId) } } }
apache-2.0
ede82f019e98f6d2784412c0cfef59b7
37.646154
156
0.73636
4.83815
false
false
false
false
sedovalx/xodus-entity-browser
entity-browser-app/src/main/kotlin/com/lehvolk/xodus/web/XodusStore.kt
1
2237
package com.lehvolk.xodus.web import com.lehvolk.xodus.web.db.Databases import java.io.FileInputStream import java.io.IOException import java.io.InputStream import java.util.* object XodusStore { val LOCATION_KEY = "entity.browser.store.location"; val STORE_ACCESS_KEY = "entity.browser.store.key"; val FILE_KEY = "entity.browser.config"; fun from(pathToFile: String?): XodusStoreRequisites? { if (pathToFile == null) { return null } try { return from(FileInputStream(pathToFile)) } catch (e: IOException) { //ignore parsing or loading file exceptions } return null } fun from(inputStream: InputStream): XodusStoreRequisites? { try { val properties = Properties() properties.load(inputStream) val location = properties.getProperty(LOCATION_KEY); val key = properties.getProperty(STORE_ACCESS_KEY); if (location != null && key != null) { return XodusStoreRequisites(location, key) } } catch (e: IOException) { //ignore parsing exceptions } finally { try { inputStream.close() } catch(e: Exception) { // ignore } } return null } fun fromSystem(): XodusStoreRequisites? { val location = System.getProperty(LOCATION_KEY); val key = System.getProperty(STORE_ACCESS_KEY); if (location != null && key != null) { return XodusStoreRequisites(location, key) } return null } fun lookupRequisites(): XodusStoreRequisites? { val file = System.getProperty(FILE_KEY); var result = fromSystem() ?: from(file) if (result == null) { val lastRecent = Databases.allRecent().lastOrNull() if (lastRecent != null) { result = XodusStoreRequisites(lastRecent.location!!, lastRecent.key!!) } } return result } } class XodusStoreRequisites(val location: String, val key: String) fun DBSummary.asRequisites(): XodusStoreRequisites = XodusStoreRequisites(location!!, key!!)
apache-2.0
e86fca10fb15fc1d4862bd55d8c08660
28.447368
92
0.590076
4.35214
false
false
false
false
KotlinBy/awesome-kotlin
src/main/kotlin/link/kotlin/scripts/model/Dto.kt
1
1544
package link.kotlin.scripts.model import link.kotlin.scripts.dsl.Category import link.kotlin.scripts.dsl.PlatformType import link.kotlin.scripts.dsl.Subcategory /** * Representation for frontend */ data class LinkDto( val name: String, val href: String, val desc: String, val platforms: List<PlatformType>, val tags: Set<String>, val star: Int? = null, val update: String? = null, val state: LinkStateDto ) enum class LinkStateDto { AWESOME, UNSUPPORTED, ARCHIVED, DEFAULT } private fun Link.toDto(): LinkDto { val state = when { awesome -> LinkStateDto.AWESOME archived -> LinkStateDto.ARCHIVED unsupported -> LinkStateDto.UNSUPPORTED else -> LinkStateDto.DEFAULT } return LinkDto( name = name ?: error("Link should have a name [$this]"), href = href ?: error("Link should have a href [$this]"), desc = desc ?: "", platforms = platforms, tags = tags.toSet(), star = star, update = update, state = state ) } data class SubcategoryDto( val name: String, val links: List<LinkDto> ) data class CategoryDto( val name: String, val subcategories: List<SubcategoryDto> ) fun Category.toDto(): CategoryDto { return CategoryDto( name = name, subcategories = subcategories.map { it.toDto() } ) } private fun Subcategory.toDto(): SubcategoryDto { return SubcategoryDto( name = name, links = links.map { it.toDto() } ) }
apache-2.0
a3e210c50341ad922d9700f9ab839590
21.057143
64
0.628238
3.948849
false
false
false
false
AdamMc331/SwipeDeck2
swipedeck/src/main/java/com/daprlabs/aaron/swipedeck/layouts/SwipeCoordinatorLayout.kt
1
1179
package com.daprlabs.aaron.swipedeck.layouts import android.content.Context import android.support.design.widget.CoordinatorLayout import android.util.AttributeSet import android.view.View import com.daprlabs.aaron.swipedeck.SwipeDeck /** * Base CoordinatorLayout for a swipe deck. */ class SwipeCoordinatorLayout(context: Context, attributeSet: AttributeSet? = null): CoordinatorLayout(context, attributeSet) { init { clipChildren = false } // This is so that versions of Android pre-lollipop will render // the card stack above everything else within the layout. override fun onFinishInflate() { super.onFinishInflate() val children = ArrayList<View>() var swipeDeck: View? = null (0..childCount - 1) .map { getChildAt(it) } .forEach { if (it is SwipeDeck) swipeDeck = it else children.add(it) } removeAllViews() removeAllViewsInLayout() children.forEach { addViewInLayout(it, -1, it.layoutParams, true) } if (swipeDeck != null) addViewInLayout(swipeDeck, -1, swipeDeck?.layoutParams, true) invalidate() requestLayout() } }
mit
956eaabfa0c32a593e954183d76d9e18
30.052632
126
0.681086
4.449057
false
false
false
false
travisobregon/kotlin-koans
src/v_builders/n39HtmlBuilders.kt
1
1541
package v_builders import util.TODO import util.doc39 import v_builders.data.getProducts import v_builders.htmlLibrary.* fun getTitleColor() = "#b9c9fe" fun getCellColor(row: Int, column: Int) = if ((row + column) %2 == 0) "#dce4ff" else "#eff2ff" fun todoTask39(): Nothing = TODO( """ Task 39. 1) Fill the table with the proper values from products. 2) Color the table like a chess board (using getTitleColor() and getCellColor() functions above). Pass a color as an argument to functions 'tr', 'td'. You can call the 'main' function in the 'htmlDemo.kt' to see the rendered table. """, documentation = doc39() ) fun renderProductTable(): String { return html { table { tr(color = getTitleColor()) { td { text("Product") } td { text("Price") } td { text("Popularity") } } for ((row, product) in getProducts().withIndex()) { tr { td(color = getCellColor(row, 0)) { text(product.description) } td(color = getCellColor(row, 1)) { text(product.price) } td(color = getCellColor(row, 2)) { text(product.popularity) } } } } }.toString() }
mit
cffd28767f61f4ce8c60d6c1cd176e98
29.215686
105
0.469176
4.58631
false
false
false
false
JanYoStudio/WhatAnime
app/src/main/java/pw/janyo/whatanime/module/DatabaseModule.kt
1
4066
package pw.janyo.whatanime.module import androidx.room.Room import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import org.koin.android.ext.koin.androidContext import org.koin.dsl.module import pw.janyo.whatanime.repository.local.db.DB import pw.janyo.whatanime.repository.local.service.HistoryService import pw.janyo.whatanime.repository.local.service.HistoryServiceImpl private const val DATABASE_NAME = "db_what_anime" private val MIGRATION_1_2: Migration = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("alter table tb_animation_history rename to _tb_animation_history") database.execSQL("CREATE TABLE IF NOT EXISTS `tb_animation_history` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `origin_path` TEXT NOT NULL, `cache_path` TEXT NOT NULL, `animation_result` TEXT NOT NULL, `animation_time` INTEGER NOT NULL, `animation_title` TEXT NOT NULL, `animation_filter` TEXT , `base64` TEXT NOT NULL)") database.execSQL("insert into tb_animation_history select *,' ' from _tb_animation_history") database.execSQL("drop table _tb_animation_history") } } private val MIGRATION_2_3: Migration = object : Migration(2, 3) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("alter table tb_animation_history rename to _tb_animation_history") database.execSQL("CREATE TABLE IF NOT EXISTS `tb_animation_history` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `origin_path` TEXT, `cache_path` TEXT, `animation_result` TEXT, `animation_time` INTEGER NOT NULL, `animation_title` TEXT, `animation_filter` TEXT)") database.execSQL("insert into tb_animation_history select id, origin_path, cache_path, animation_result, animation_time, animation_title, animation_filter from _tb_animation_history") database.execSQL("drop table _tb_animation_history") } } private val MIGRATION_3_4: Migration = object : Migration(3, 4) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("alter table tb_animation_history rename to _tb_animation_history") database.execSQL("CREATE TABLE IF NOT EXISTS `tb_animation_history` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `origin_path` TEXT NOT NULL, `cache_path` TEXT NOT NULL, `animation_result` TEXT NOT NULL, `animation_time` INTEGER NOT NULL, `animation_title` TEXT NOT NULL, `animation_filter` TEXT)") database.execSQL("insert into tb_animation_history select id, origin_path, cache_path, animation_result, animation_time, animation_title, animation_filter from _tb_animation_history") database.execSQL("drop table _tb_animation_history") } } private val MIGRATION_4_5: Migration = object : Migration(4, 5) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("alter table tb_animation_history rename to _tb_animation_history") database.execSQL("CREATE TABLE IF NOT EXISTS `tb_animation_history` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `origin_path` TEXT NOT NULL, `cache_path` TEXT NOT NULL, `animation_result` TEXT NOT NULL, `animation_time` INTEGER NOT NULL, `animation_title` TEXT NOT NULL, `animation_anilist_id` INTEGER NOT NULL, `animation_episode` TEXT NOT NULL, `animation_similarity` REAL NOT NULL)") database.execSQL("insert into tb_animation_history select id, origin_path, cache_path, animation_result, animation_time, animation_title, 0, 'old', 0 from _tb_animation_history") database.execSQL("drop table _tb_animation_history") } } val databaseModule = module { single { Room.databaseBuilder(androidContext().applicationContext, DB::class.java, DATABASE_NAME) .addMigrations(MIGRATION_1_2) .addMigrations(MIGRATION_2_3) .addMigrations(MIGRATION_3_4) .addMigrations(MIGRATION_4_5) .build() } single { get<DB>().getHistoryDao() } single<HistoryService> { HistoryServiceImpl() } }
apache-2.0
8b9b853854f1de416f9c7c891bb7e781
64.596774
400
0.731185
4.053838
false
false
false
false
msebire/intellij-community
platform/platform-impl/src/com/intellij/openapi/application/async/RescheduleAttemptLimitAwareDispatcher.kt
1
2811
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.application.async import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Runnable import kotlinx.coroutines.cancel import java.util.* import kotlin.coroutines.CoroutineContext // must be the ContinuationInterceptor in order to work properly internal class RescheduleAttemptLimitAwareDispatcher(dispatchers: Array<CoroutineDispatcher>, private val dispatchLater: (Runnable) -> Unit, private val myLimit: Int = 3000) : BaseAsyncExecutionSupport.CompositeDispatcher(dispatchers) { private var myAttemptCount: Int = 0 private val myLogLimit: Int = 30 private val myLastDispatchers: Deque<CoroutineDispatcher> = ArrayDeque(myLogLimit) override fun dispatch(context: CoroutineContext, block: Runnable) { resetAttemptCount() super.dispatch(context, block) } override fun retryDispatch(context: CoroutineContext, block: Runnable, causeDispatcher: CoroutineDispatcher) { if (checkHaveMoreRescheduleAttempts(causeDispatcher)) { super.dispatch(context, block) } else BaseAsyncExecutionSupport.run { try { processUncaughtException(TooManyRescheduleAttemptsException(myLastDispatchers)) } finally { context.cancel() // The continuation block MUST be invoked at some point in order to give the coroutine a chance // to handle the cancellation exception and exit gracefully. // At this point we can only provide a guarantee to resume it on EDT with a proper modality state. dispatchLater(block) } } } private fun resetAttemptCount() { myLastDispatchers.clear() myAttemptCount = 0 } private fun checkHaveMoreRescheduleAttempts(dispatcher: CoroutineDispatcher): Boolean { with(myLastDispatchers) { if (isNotEmpty() && size >= myLogLimit) removeFirst() addLast(dispatcher) } return ++myAttemptCount < myLimit } /** * Thrown at a cancellation point when the executor is unable to arrange the requested context after a reasonable number of attempts. * * WARNING: The exception thrown is handled in a fallback context as a last resort, * The fallback context is EDT with a proper modality state, no other guarantee is made. */ internal class TooManyRescheduleAttemptsException internal constructor(lastConstraints: Collection<CoroutineDispatcher>) : Exception("Too many reschedule requests, probably constraints can't be satisfied all together: " + lastConstraints.joinToString()) }
apache-2.0
86decd6c333dda0c2850779a765092eb
40.970149
140
0.709356
5.195933
false
false
false
false
lewinskimaciej/planner
app/src/main/java/com/atc/planner/presentation/base/BaseMvpActivity.kt
1
2785
package com.atc.planner.presentation.base import android.content.Intent import android.os.Bundle import android.support.annotation.LayoutRes import android.support.design.widget.Snackbar import android.support.v4.app.Fragment import android.support.v7.app.AlertDialog import android.view.ViewGroup import android.widget.Toast import com.atc.planner.R import com.hannesdorfmann.mosby3.mvp.MvpActivity import dagger.android.AndroidInjection import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.HasFragmentInjector import dagger.android.support.HasSupportFragmentInjector import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject abstract class BaseMvpActivity<V : BaseView, P : BaseMvpPresenter<V>> : MvpActivity<V, P>(), HasFragmentInjector, HasSupportFragmentInjector, BaseView { @get:LayoutRes protected abstract val layoutResId: Int? private var disposables = CompositeDisposable() @Inject lateinit var supportFragmentInjector: DispatchingAndroidInjector<Fragment> @Inject lateinit var frameworkFragmentInjector: DispatchingAndroidInjector<android.app.Fragment> override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) if (layoutResId != null) { setContentView(layoutResId as Int) } onViewCreated(savedInstanceState) presenter?.onViewCreated(intent.extras?.getSerializable(BaseDictionary.KEY_SERIALIZABLE)) } override fun onNewIntent(intent: Intent) { val extras = intent.extras?.getSerializable(BaseDictionary.KEY_SERIALIZABLE) presenter?.onNewBundle(extras) super.onNewIntent(intent) } override fun onDestroy() { super.onDestroy() disposables.clear() } override fun fragmentInjector(): AndroidInjector<android.app.Fragment> = frameworkFragmentInjector override fun supportFragmentInjector(): AndroidInjector<Fragment> = supportFragmentInjector override fun showAlertDialog(title: String, message: String) { AlertDialog.Builder(this, R.style.AppTheme) .setMessage(message) .setTitle(title) .setPositiveButton(R.string.common_dialog_ok, { dialog, _ -> dialog.dismiss() }) } override fun showErrorToast() { Toast.makeText(this, getString(R.string.unexpected_error), Toast.LENGTH_SHORT).show() } override fun showOfflineSnackbar() { val rootView = this.findViewById<ViewGroup>(android.R.id.content).getChildAt(0) Snackbar.make(rootView, getString(R.string.no_internet_connection), Snackbar.LENGTH_LONG) } }
mit
17e14826bd76168a26bb63eb43f32147
32.97561
102
0.731418
4.991039
false
false
false
false
openMF/self-service-app
app/src/main/java/org/mifos/mobile/models/templates/loans/AllowAttributeOverrides.kt
1
1108
package org.mifos.mobile.models.templates.loans import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** * Created by Rajan Maurya on 16/07/16. */ @Parcelize data class AllowAttributeOverrides( @SerializedName("amortizationType") var amortizationType: Boolean? = null, @SerializedName("interestType") var interestType: Boolean? = null, @SerializedName("transactionProcessingStrategyId") var transactionProcessingStrategyId: Boolean? = null, @SerializedName("interestCalculationPeriodType") var interestCalculationPeriodType: Boolean? = null, @SerializedName("inArrearsTolerance") var inArrearsTolerance: Boolean? = null, @SerializedName("repaymentEvery") var repaymentEvery: Boolean? = null, @SerializedName("graceOnPrincipalAndInterestPayment") var graceOnPrincipalAndInterestPayment: Boolean? = null, @SerializedName("graceOnArrearsAgeing") var graceOnArrearsAgeing: Boolean? = null ) : Parcelable
mpl-2.0
92241328f0fbb4ce60351d86e6577e7a
27.435897
64
0.718412
4.817391
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/filterer/ExpansionStatusFilterer.kt
1
1084
package com.boardgamegeek.filterer import android.content.Context import com.boardgamegeek.R import com.boardgamegeek.entities.CollectionItemEntity class ExpansionStatusFilterer(context: Context) : CollectionFilterer(context) { var selectedSubtype = ALL override val typeResourceId = R.string.collection_filter_type_subtype override fun inflate(data: String) { selectedSubtype = data.toIntOrNull() ?: ALL } override fun deflate() = selectedSubtype.toString() override val iconResourceId: Int get() = R.drawable.ic_baseline_flip_to_back_24 override fun chipText() = getFromArray(R.array.expansion_status_filter) override fun filter(item: CollectionItemEntity): Boolean { val value = getFromArray(R.array.expansion_status_filter_values) return if (value.isNotEmpty()) item.subType == value else true } private fun getFromArray(resId: Int): String { return context.resources.getStringArray(resId).getOrNull(selectedSubtype).orEmpty() } companion object { const val ALL = 0 } }
gpl-3.0
4dfca1127b6b770c761a137ff35613e0
29.971429
91
0.722325
4.442623
false
false
false
false
agdiaz/github-explorer-app
app/src/main/java/com/diazadriang/apiexample/GithubRepositoryAdapter.kt
1
1575
package com.diazadriang.apiexample import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView /** * Created by diazadriang on 8/1/17. */ class GithubRepositoryAdapter(repos: List<GithubRepository>) : RecyclerView.Adapter<GithubRepositoryHolder>() { private val mRepos : List<GithubRepository> = repos override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): GithubRepositoryHolder { val inflatedView = LayoutInflater.from(parent?.context) .inflate(R.layout.layout_repository_item, parent, false) return GithubRepositoryHolder(inflatedView) } override fun getItemCount(): Int { return mRepos.size } override fun onBindViewHolder(holder: GithubRepositoryHolder?, position: Int) { holder?.bindRepository(mRepos[position]) } } class GithubRepositoryHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val mTitle = itemView.findViewById<TextView>(R.id.textViewRepositoryTitle) private val mDescription = itemView.findViewById<TextView>(R.id.textViewRepositoryDescription) private val mLanguage = itemView.findViewById<TextView>(R.id.textViewRepositoryLanguage) private val mPrivate = itemView.findViewById<TextView>(R.id.textViewRepositoryPrivate) fun bindRepository(repo: GithubRepository){ mTitle.text = repo.full_name mDescription.text = repo.description mLanguage.text = "Written in ${repo.language}" mPrivate.text = if (repo.private) "Private" else "Public" } }
mit
3a24e9d4abd3b083cfb2ad00ec949e20
34.795455
111
0.777143
4.22252
false
false
false
false
herolynx/elepantry-android
app/src/main/java/com/herolynx/elepantry/drive/NotConnectedDrive.kt
1
1597
package com.herolynx.elepantry.drive import android.app.Activity import com.herolynx.elepantry.R import com.herolynx.elepantry.core.Result import com.herolynx.elepantry.resources.core.model.Resource import com.herolynx.elepantry.resources.core.service.ResourcePage import com.herolynx.elepantry.resources.core.service.ResourceView import com.herolynx.elepantry.resources.core.service.SearchCriteria import org.funktionale.tries.Try import rx.Observable import java.io.InputStream internal class NotConnectedDrive(private val driveType: DriveType) : CloudDrive { override fun driveView(): ResourceView = NotConnectedResourceView override fun type(): DriveType = driveType override fun cloudResource(r: Resource): Try<CloudResource> = Try { NotConnectedResource(r) } } private class NotConnectedResource(private val r: Resource) : CloudResource { override fun thumbnail(): Observable<InputStream> = Observable.empty() override fun metaInfo(): Resource = r private fun notSupportedOperation(activity: Activity): Try<Result> = Try { Result(false, activity.getString(R.string.error_drive_not_connected)) } override fun preview(activity: Activity, beforeAction: () -> Unit, afterAction: () -> Unit) = notSupportedOperation(activity) override fun download(activity: Activity, beforeAction: () -> Unit, afterAction: () -> Unit) = notSupportedOperation(activity) } private object NotConnectedResourceView : ResourceView { override fun search(c: SearchCriteria): Try<out ResourcePage> = Try.Failure(RuntimeException("Drive is not connected")) }
gpl-3.0
b9f8cf0589f4df5a0ff0f9d8d2ef7285
37.047619
130
0.778334
4.316216
false
false
false
false
Mauin/detekt
detekt-generator/src/main/kotlin/io/gitlab/arturbosch/detekt/generator/collection/RuleVisitor.kt
1
7060
package io.gitlab.arturbosch.detekt.generator.collection import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.DetektVisitor import io.gitlab.arturbosch.detekt.api.ThresholdRule import io.gitlab.arturbosch.detekt.formatting.FormattingRule import io.gitlab.arturbosch.detekt.generator.collection.exception.InvalidCodeExampleDocumentationException import io.gitlab.arturbosch.detekt.generator.collection.exception.InvalidDocumentationException import io.gitlab.arturbosch.detekt.generator.collection.exception.InvalidIssueDeclaration import io.gitlab.arturbosch.detekt.rules.empty.EmptyRule import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtSuperTypeList import org.jetbrains.kotlin.psi.KtValueArgument import org.jetbrains.kotlin.psi.psiUtil.containingClass import org.jetbrains.kotlin.psi.psiUtil.getSuperNames import java.lang.reflect.Modifier /** * @author Marvin Ramin * @author Artur Bosch * @author schalkms */ internal class RuleVisitor : DetektVisitor() { val containsRule get() = classesMap.any { it.value } private var description = "" private var nonCompliant = "" private var compliant = "" private var name = "" private var active = false private var autoCorrect = false private var severity = "" private var debt = "" private var aliases: String? = null private var parent = "" private val configuration = mutableListOf<Configuration>() private val classesMap = mutableMapOf<String, Boolean>() fun getRule(): Rule { if (description.isEmpty()) { throw InvalidDocumentationException("Rule $name is missing a description in its KDoc.") } return Rule(name, description, nonCompliant, compliant, active, severity, debt, aliases, parent, configuration, autoCorrect) } override fun visitSuperTypeList(list: KtSuperTypeList) { val isRule = list.entries ?.map { it.typeAsUserType?.referencedName } ?.any { ruleClasses.contains(it) } ?: false val containingClass = list.containingClass() val className = containingClass?.name if (containingClass != null && className != null && !classesMap.containsKey(className)) { classesMap[className] = isRule parent = containingClass.getSuperNames().firstOrNull { ruleClasses.contains(it) } ?: "" extractIssueDocumentation(containingClass) } super.visitSuperTypeList(list) } override fun visitClassOrObject(classOrObject: KtClassOrObject) { super.visitClassOrObject(classOrObject) if (classesMap[classOrObject.name] != true) { return } name = classOrObject.name?.trim() ?: "" active = classOrObject.kDocSection()?.findTagByName(TAG_ACTIVE) != null autoCorrect = classOrObject.kDocSection()?.findTagByName(TAG_AUTO_CORRECT) != null val comment = classOrObject.kDocSection()?.getContent()?.trim() ?: return extractRuleDocumentation(comment) configuration.addAll(classOrObject.parseConfigurationTags()) } private fun extractRuleDocumentation(comment: String) { val nonCompliantIndex = comment.indexOf(TAG_NONCOMPLIANT) val compliantIndex = comment.indexOf(TAG_COMPLIANT) when { nonCompliantIndex != -1 -> { extractNonCompliantDocumentation(comment, nonCompliantIndex) extractCompliantDocumentation(comment, compliantIndex) } compliantIndex != -1 -> throw InvalidCodeExampleDocumentationException( "Rule $name contains a compliant without a noncompliant code definition.") else -> description = comment } } private fun extractNonCompliantDocumentation(comment: String, nonCompliantIndex: Int) { val nonCompliantEndIndex = comment.indexOf(ENDTAG_NONCOMPLIANT) if (nonCompliantEndIndex == -1) { throw InvalidCodeExampleDocumentationException( "Rule $name contains a incorrect noncompliant code definition.") } description = comment.substring(0, nonCompliantIndex).trim() nonCompliant = comment.substring(nonCompliantIndex + TAG_NONCOMPLIANT.length, nonCompliantEndIndex) .trimStartingLineBreaks() .trimEnd() } private fun extractCompliantDocumentation(comment: String, compliantIndex: Int) { val compliantEndIndex = comment.indexOf(ENDTAG_COMPLIANT) if (compliantIndex != -1) { if (compliantEndIndex == -1) { throw InvalidCodeExampleDocumentationException( "Rule $name contains a incorrect compliant code definition.") } compliant = comment.substring(compliantIndex + TAG_COMPLIANT.length, compliantEndIndex) .trimStartingLineBreaks() .trimEnd() } } private fun extractIssueDocumentation(klass: KtClass) { val issueProperty = klass.getProperties().singleOrNull { it.name == "issue" } val initializer = issueProperty?.initializer as? KtCallExpression if (initializer != null) { val arguments = initializer.valueArguments if (arguments.size >= ISSUE_ARGUMENT_SIZE) { extractIssueSeverityAndDebt(arguments) extractIssueAliases(arguments) } } } private fun extractIssueSeverityAndDebt(arguments: List<KtValueArgument>) { severity = getArgument(arguments[1], "Severity") val debtName = getArgument(arguments[DEBT_ARGUMENT_INDEX], "Debt") val debtDeclarations = Debt::class.java.declaredFields.filter { Modifier.isStatic(it.modifiers) } val debtDeclaration = debtDeclarations.singleOrNull { it.name == debtName } if (debtDeclaration != null) { debtDeclaration.isAccessible = true debt = debtDeclaration.get(Debt::class.java).toString() } } private fun extractIssueAliases(arguments: List<KtValueArgument>) { if (arguments.size > ISSUE_ARGUMENT_SIZE) { val aliasArgument = arguments[arguments.size - 1].text val index = aliasArgument.indexOf(SETOF) if (index == -1) { throw InvalidIssueDeclaration("aliases") } val argumentString = aliasArgument.substring(index + SETOF.length, aliasArgument.length - 1) aliases = argumentString .split(',') .joinToString(", ") { it.trim().replace("\"", "") } } } private fun getArgument(argument: KtValueArgument, name: String): String { val text = argument.text val type = text.split('.') if (text.startsWith(name, true) && type.size == 2) { return type[1] } throw InvalidIssueDeclaration(name) } companion object { private val ruleClasses = listOf( io.gitlab.arturbosch.detekt.api.Rule::class.simpleName, FormattingRule::class.simpleName, ThresholdRule::class.simpleName, EmptyRule::class.simpleName ) private const val TAG_ACTIVE = "active" private const val TAG_AUTO_CORRECT = "autoCorrect" private const val TAG_NONCOMPLIANT = "<noncompliant>" private const val ENDTAG_NONCOMPLIANT = "</noncompliant>" private const val TAG_COMPLIANT = "<compliant>" private const val ENDTAG_COMPLIANT = "</compliant>" private const val ISSUE_ARGUMENT_SIZE = 4 private const val DEBT_ARGUMENT_INDEX = 3 private const val SETOF = "setOf(" } } private fun String.trimStartingLineBreaks(): String { var i = 0 while (i < this.length && (this[i] == '\n' || this[i] == '\r')) { i++ } return this.substring(i) }
apache-2.0
91757c06fb052c706bcab945774991f5
35.580311
106
0.751133
3.857923
false
false
false
false
googlesamples/mlkit
android/smartreply/app/src/main/java/com/google/mlkit/samples/nl/smartreply/kotlin/chat/ReplyChipAdapter.kt
1
2157
/* * Copyright 2020 Google LLC. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mlkit.samples.nl.smartreply.kotlin.chat import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.google.mlkit.nl.smartreply.SmartReplySuggestion import com.google.mlkit.samples.nl.smartreply.R import java.util.ArrayList class ReplyChipAdapter( private val listener: ClickListener ) : RecyclerView.Adapter<ReplyChipAdapter.ViewHolder>() { private val suggestions = ArrayList<SmartReplySuggestion>() interface ClickListener { fun onChipClick(chipText: String) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val v = LayoutInflater.from(parent.context).inflate(R.layout.smart_reply_chip, parent, false) return ViewHolder(v) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val suggestion = suggestions[position] holder.bind(suggestion) } override fun getItemCount(): Int { return suggestions.size } fun setSuggestions(suggestions: List<SmartReplySuggestion>) { this.suggestions.clear() this.suggestions.addAll(suggestions) notifyDataSetChanged() } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val text: TextView = itemView.findViewById(R.id.smartReplyText) fun bind(suggestion: SmartReplySuggestion) { text.text = suggestion.text itemView.setOnClickListener { listener.onChipClick(suggestion.text) } } } }
apache-2.0
c5472f80969e6e3391f45e762927f774
30.720588
97
0.759388
4.271287
false
false
false
false
eraga/rxusb
serial/src/main/kotlin/net/eraga/rxusb/serial/UsbSerial.kt
1
2392
package net.eraga.rxusb.serial /** * Interface to handle a serial port * @author felhr ([email protected]) */ interface UsbSerial { // Common Usb Serial Operations (I/O Asynchronous) fun open(): Boolean fun write(buffer: ByteArray) fun read(mCallback: UsbReadCallback): Int fun close() // Common Usb Serial Operations (I/O Synchronous) fun syncOpen(): Boolean fun syncWrite(buffer: ByteArray, timeout: Int): Int fun syncRead(buffer: ByteArray, timeout: Int): Int fun syncClose() // Serial port configuration fun setBaudRate(baudRate: Int) fun setDataBits(dataBits: Int) fun setStopBits(stopBits: Int) fun setParity(parity: Int) fun setFlowControl(flowControl: Int) // Flow control commands and interface callback fun setRTS(state: Boolean) fun setDTR(state: Boolean) fun getCTS(ctsCallback: UsbCTSCallback) fun getDSR(dsrCallback: UsbDSRCallback) // Status methods fun getBreak(breakCallback: UsbBreakCallback) fun getFrame(frameCallback: UsbFrameCallback) fun getOverrun(overrunCallback: UsbOverrunCallback) fun getParity(parityCallback: UsbParityCallback) interface UsbCTSCallback { fun onCTSChanged(state: Boolean) } interface UsbDSRCallback { fun onDSRChanged(state: Boolean) } // Error signals callbacks interface UsbBreakCallback { fun onBreakInterrupt() } interface UsbFrameCallback { fun onFramingError() } interface UsbOverrunCallback { fun onOverrunError() } interface UsbParityCallback { fun onParityError() } // Usb Read Callback interface UsbReadCallback { fun onReceivedData(data: ByteArray) } companion object { // Common values const val DATA_BITS_5 = 5 const val DATA_BITS_6 = 6 const val DATA_BITS_7 = 7 const val DATA_BITS_8 = 8 const val STOP_BITS_1 = 1 const val STOP_BITS_15 = 3 const val STOP_BITS_2 = 2 const val PARITY_NONE = 0 const val PARITY_ODD = 1 const val PARITY_EVEN = 2 const val PARITY_MARK = 3 const val PARITY_SPACE = 4 const val FLOW_CONTROL_OFF = 0 const val FLOW_CONTROL_RTS_CTS = 1 const val FLOW_CONTROL_DSR_DTR = 2 const val FLOW_CONTROL_XON_XOFF = 3 } }
apache-2.0
ab1d1358aa0fa4e506c4b422465c0c11
23.408163
55
0.65092
3.921311
false
false
false
false
pedroSG94/rtmp-streamer-java
rtmp/src/main/java/com/pedro/rtmp/amf/v0/AmfBoolean.kt
2
1330
/* * Copyright (C) 2021 pedroSG94. * * 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.pedro.rtmp.amf.v0 import java.io.IOException import java.io.InputStream import java.io.OutputStream import kotlin.jvm.Throws /** * Created by pedro on 20/04/21. * * Only 1 byte of size where 0 is false and another value is true */ class AmfBoolean(private var value: Boolean = false): AmfData() { @Throws(IOException::class) override fun readBody(input: InputStream) { val b = input.read() this.value = b != 0 } @Throws(IOException::class) override fun writeBody(output: OutputStream) { output.write(if (value) 1 else 0) } override fun getType(): AmfType = AmfType.BOOLEAN override fun getSize(): Int = 1 override fun toString(): String { return "AmfBoolean value: $value" } }
apache-2.0
668bbbf46aa4dd42b26b97b53cb682ec
26.163265
75
0.715038
3.832853
false
false
false
false
renard314/textfairy
app/src/main/java/com/googlecode/tesseract/android/OCR.kt
1
13430
/* * Copyright (C) 2012,2013 Renard Wellnitz. * * 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.googlecode.tesseract.android import android.app.Application import android.content.Context import android.content.res.Resources import android.graphics.Rect import androidx.annotation.StringRes import androidx.annotation.WorkerThread import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations.map import androidx.test.espresso.idling.concurrent.IdlingScheduledThreadPoolExecutor import com.googlecode.leptonica.android.Boxa import com.googlecode.leptonica.android.Pix import com.googlecode.leptonica.android.Pixa import com.googlecode.tesseract.android.OcrProgress.* import com.googlecode.tesseract.android.TessBaseAPI.OEM_LSTM_ONLY import com.googlecode.tesseract.android.TessBaseAPI.PageSegMode import com.renard.ocr.R import com.renard.ocr.TextFairyApplication import com.renard.ocr.analytics.CrashLogger import com.renard.ocr.documents.creation.crop.CropImageScaler import com.renard.ocr.main_menu.language.OcrLanguage import com.renard.ocr.main_menu.language.OcrLanguageDataStore.deleteLanguage import com.renard.ocr.util.AppStorage import com.renard.ocr.util.MemoryInfo import java.io.File import java.util.concurrent.atomic.AtomicBoolean import kotlin.math.roundToInt sealed class OcrProgress { data class Message(@StringRes val message: Int) : OcrProgress() data class LayoutElements(val columns: Pixa, val images: Pixa, val pageWidth: Int, val pageHeight: Int, val language: String) : OcrProgress() data class Progress(val percent: Int, val wordBounds: Rect, val rectBounds: Rect, val pageWidth: Int, val pageHeight: Int) : OcrProgress() data class Result(val pix: Pix, val utf8Text: String, val hocrText: String, val accuracy: Int, val language: String) : OcrProgress() data class Error(@StringRes val message: Int) : OcrProgress() } class OCR(application: Application) : AndroidViewModel(application) { private val mAnalytics get() = getApplication<TextFairyApplication>().analytics private val mCrashLogger get() = getApplication<TextFairyApplication>().crashLogger private val mNativeBinding: NativeBinding = NativeBinding() private val mStopped = AtomicBoolean(false) private var mCompleted = AtomicBoolean(false) private val mExecutorService = IdlingScheduledThreadPoolExecutor("Ocr Thread Pool", 1) { r -> Thread(r) } private var lastPreview: Pix? = null private val ocrProgress: MutableLiveData<OcrProgress> = MutableLiveData() private val _preview = MutableLiveData<Pix>() val preview: LiveData<Pix> get() = map(_preview) { lastPreview?.recycle() lastPreview = it it } fun getOcrProgress(): LiveData<OcrProgress> { return ocrProgress } override fun onCleared() { super.onCleared() lastPreview?.recycle() mCrashLogger.logMessage("OCR#onCleared") mStopped.set(true) mNativeBinding.destroy() if (!mCompleted.get()) { mCrashLogger.logMessage("ocr cancelled") mAnalytics.sendOcrCancelled() } } /** * native code takes care of the Pix, do not use it after calling this * function **/ fun startLayoutAnalysis(pix: Pix, language: String) { setupImageProcessingCallback(pix.width, pix.height, language) mExecutorService.execute { mNativeBinding.analyseLayout(pix) } } private fun setupImageProcessingCallback(width: Int, height: Int, language: String) { mNativeBinding.setProgressCallBack(object : NativeBinding.ProgressCallBack { @WorkerThread override fun onProgressImage(nativePix: Long) { sendPreview(Pix(nativePix)) } @WorkerThread override fun onProgressText(@StringRes message: Int) { ocrProgress.postValue(Message(message)) } @WorkerThread override fun onLayoutAnalysed(nativePixaText: Long, nativePixaImages: Long) { ocrProgress.postValue( LayoutElements( Pixa(nativePixaText, 0, 0), Pixa(nativePixaImages, 0, 0), width, height, language ) ) } }) } /** * native code takes care of both Pixa, do not use them after calling this * function * * @param pixaText must contain the binary text parts * @param pixaImages pixaImages must contain the image parts */ fun startOCRForComplexLayout(context: Context, pixaText: Pixa, pixaImages: Pixa, selectedTexts: IntArray, selectedImages: IntArray, lang: String) { mExecutorService.execute { mCrashLogger.logMessage("startOCRForComplexLayout") var pixOcr: Pix? = null var boxa: Boxa? = null try { logMemory(context) val columnData = mNativeBinding.combinePixa(pixaText.nativePixa, pixaImages.nativePixa, selectedTexts, selectedImages) pixaText.recycle() pixaImages.recycle() val pixOrgPointer = columnData[0] pixOcr = Pix(columnData[1]) boxa = Boxa(columnData[2]) sendPreview(pixOcr) ocrProgress.postValue(Message(R.string.progress_ocr)) val tessApi = initTessApi(getApplication(), lang, mCrashLogger) { progressValues -> ocrProgress.postValue( Progress( percent = progressValues.percent, wordBounds = progressValues.currentWordRect, rectBounds = progressValues.currentRect, pageWidth = pixOcr.width, pageHeight = pixOcr.height ) ) } if (tessApi == null) { ocrProgress.postValue(Error(R.string.error_tess_init)) } tessApi?.use { tess -> tess.pageSegMode = PageSegMode.PSM_SINGLE_BLOCK tess.setImage(pixOcr) if (mStopped.get()) { return@use } var accuracy = 0f val geometry = IntArray(4) val hocrText = StringBuilder() val htmlText = StringBuilder() for (i in 0 until boxa.count) { if (!boxa.getGeometry(i, geometry)) { continue } tess.setRectangle(geometry[0], geometry[1], geometry[2], geometry[3]) hocrText.append(tess.getHOCRText(0)) htmlText.append(tess.htmlText) accuracy += tess.meanConfidence().toFloat() if (mStopped.get()) { return@use } } val totalAccuracy = (accuracy / boxa.count).roundToInt() ocrProgress.postValue(Result( Pix(pixOrgPointer), htmlText.toString(), hocrText.toString(), totalAccuracy, lang )) } } finally { pixOcr?.recycle() boxa?.recycle() mCompleted.set(true) mCrashLogger.logMessage("startOCRForComplexLayout finished") } } } /** * native code takes care of the Pix, do not use it after calling this * function * * @param context used to access the file system * @param pix source pix to do ocr on */ fun startOCRForSimpleLayout(context: Context, pix: Pix, lang: String) { setupImageProcessingCallback(pix.width, pix.height, lang) mExecutorService.execute { mCrashLogger.logMessage("startOCRForSimpleLayout") try { logMemory(context) sendPreview(pix) val pixText = Pix(mNativeBinding.convertBookPage(pix)) sendPreview(pixText) pix.recycle() if (mStopped.get()) { pixText.recycle() return@execute } ocrProgress.postValue(Message(R.string.progress_ocr)) val tessApi = initTessApi(getApplication(), lang, mCrashLogger) { progressValues -> ocrProgress.postValue( Progress( percent = progressValues.percent, wordBounds = progressValues.currentWordRect, rectBounds = progressValues.currentRect, pageWidth = pixText.width, pageHeight = pixText.height ) ) } if(tessApi==null){ ocrProgress.postValue(Error(R.string.error_tess_init)) } tessApi?.use scan@{ tess -> tess.pageSegMode = PageSegMode.PSM_AUTO tess.setImage(pixText) var hocrText = tess.getHOCRText(0) var accuracy = tess.meanConfidence() val utf8Text = tess.utF8Text if (!mStopped.get() && utf8Text.isEmpty()) { mCrashLogger.logMessage("No words found. Looking for sparse text.") tess.pageSegMode = PageSegMode.PSM_SPARSE_TEXT tess.setImage(pixText) hocrText = tess.getHOCRText(0) accuracy = tess.meanConfidence() } if (mStopped.get()) { return@scan } val htmlText = tess.htmlText if (accuracy == 95) { accuracy = 0 } ocrProgress.postValue(Result(pixText, htmlText.toString(), hocrText.toString(), accuracy, lang)) } } finally { mCompleted.set(true) mCrashLogger.logMessage("startOCRForSimpleLayout finished") } } } private fun sendPreview(it: Pix) { val widthPixels = Resources.getSystem().displayMetrics.widthPixels val heightPixels = Resources.getSystem().displayMetrics.heightPixels val scale = CropImageScaler().scale(it, widthPixels, heightPixels) _preview.postValue(scale.pix) } private fun logMemory(context: Context) { val freeMemory = MemoryInfo.getFreeMemory(context) mCrashLogger.setLong("Memory", freeMemory) } companion object { const val FILE_NAME = "last_scan" fun savePixToCacheDir(context: Context, pix: Pix) { val dir = File(context.cacheDir, context.getString(R.string.config_share_file_dir)) SavePixTask(pix, dir).execute() } fun getLastOriginalImageFromCache(context: Context): File { val dir = File(context.cacheDir, context.getString(R.string.config_share_file_dir)) return File(dir, "$FILE_NAME.png") } } private fun <T> Pix.use(block: (Pix) -> T) = block(this).also { recycle() } } fun initTessApi(context: Context, lang: String, crashLogger: CrashLogger, onProgress: (TessBaseAPI.ProgressValues) -> Unit): TessBaseAPI? { val mTess = TessBaseAPI(onProgress) val tessDir = AppStorage.getTrainingDataDir(context)?.path ?: return null with(crashLogger) { setString( tag = "page seg mode", value = "OEM_LSTM_ONLY" ) setString("ocr language", lang) } val result = mTess.init(tessDir, lang, OEM_LSTM_ONLY) if (!result) { crashLogger.logMessage("init failed. deleting $lang") deleteLanguage(lang, context) OcrLanguage(lang).installLanguage(context) return null } crashLogger.logMessage("init succeeded") mTess.setVariable(TessBaseAPI.VAR_CHAR_BLACKLIST, "fffiflffifflſtst") return mTess } public fun TessBaseAPI.use(block: (TessBaseAPI) -> Unit) { block(this) this.end() }
apache-2.0
bf437ea8be4bfdb2e75b55820d2c7027
38.692308
151
0.57655
4.653486
false
false
false
false
arturbosch/detekt
detekt-rules-exceptions/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/InstanceOfCheckForExceptionSpec.kt
1
2700
package io.gitlab.arturbosch.detekt.rules.exceptions import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext import org.assertj.core.api.Assertions.assertThat import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class InstanceOfCheckForExceptionSpec : Spek({ setupKotlinEnvironment() val env: KotlinCoreEnvironment by memoized() val subject by memoized { InstanceOfCheckForException() } describe("InstanceOfCheckForException rule") { it("has is and as checks") { val code = """ fun x() { try { } catch(e: Exception) { if (e is IllegalArgumentException || (e as IllegalArgumentException) != null) { return } } } """ assertThat(subject.compileAndLintWithContext(env, code)).hasSize(2) } it("has nested is and as checks") { val code = """ fun x() { try { } catch(e: Exception) { if (1 == 1) { val b = e !is IllegalArgumentException || (e as IllegalArgumentException) != null } } } """ assertThat(subject.compileAndLintWithContext(env, code)).hasSize(2) } it("has no instance of check") { val code = """ fun x() { try { } catch(e: Exception) { val s = "" if (s is String || (s as String) != null) { val other: Exception? = null val b = other !is IllegalArgumentException || (other as IllegalArgumentException) != null } } } """ assertThat(subject.compileAndLintWithContext(env, code)).isEmpty() } it("has no checks for the subtype of an exception") { val code = """ interface I fun foo() { try { } catch(e: Exception) { if (e is I || (e as I) != null) { } } } """ assertThat(subject.compileAndLintWithContext(env, code)).isEmpty() } } })
apache-2.0
66ee92e372ad386db0b093f9eb30dc52
33.615385
117
0.464815
5.708245
false
false
false
false
nickthecoder/paratask
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/fields/FileField.kt
1
3179
/* ParaTask Copyright (C) 2017 Nick Robinson 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 uk.co.nickthecoder.paratask.parameters.fields import javafx.event.EventHandler import javafx.scene.control.TextField import javafx.scene.layout.BorderPane import javafx.stage.DirectoryChooser import javafx.stage.FileChooser import javafx.stage.Stage import uk.co.nickthecoder.paratask.parameters.FileParameter import java.io.File class FileField(val fileParameter: FileParameter) : FileFieldBase(fileParameter) { override fun createControl(): BorderPane { if (FileParameter.showOpenButton) { openButton.onAction = EventHandler { onOpen() } iconContainer.children.add(0, openButton) } return super.createControl() } override fun buildTextField(): TextField { super.buildTextField() textField.textProperty().bindBidirectional(fileParameter.valueProperty, fileParameter.converter) return textField } override fun getFile(): File? = fileParameter.value override fun setFile(file: File?) { fileParameter.value = file textField.positionCaret(textField.text.length) } override fun updateEnabled() { super.updateEnabled() openButton.isDisable = !parameter.enabled } fun onOpen() { if (fileParameter.expectFile == false) { val dirChooser = DirectoryChooser() dirChooser.title = "Choose Directory" fileParameter.value?.let { dirChooser.initialDirectory = it } val file = dirChooser.showDialog(Stage()) file?.let { fileParameter.value = file } } else { val fileChooser = FileChooser() fileChooser.title = "Choose File" fileParameter.extensions?.let { it.forEach { fileChooser.extensionFilters.add(FileChooser.ExtensionFilter("*.$it", it)) } } fileParameter.value?.let { if (it.isDirectory) { fileChooser.initialDirectory = it } else { fileChooser.initialDirectory = it.parentFile fileChooser.initialFileName = it.name } } val file: File? if (fileParameter.mustExist == true) { file = fileChooser.showOpenDialog(Stage()) } else { file = fileChooser.showSaveDialog(Stage()) } file?.let { fileParameter.value = file } } } }
gpl-3.0
5bb497098fd92903a268f16a056d18d7
31.773196
104
0.641397
4.860856
false
false
false
false
arturbosch/detekt
detekt-gradle-plugin/src/main/kotlin/io/gitlab/arturbosch/detekt/report/SarifReportMerger.kt
1
671
package io.gitlab.arturbosch.detekt.report import io.github.detekt.sarif4k.SarifSerializer import java.io.File /** * A naive implementation to merge SARIF assuming all inputs are written by detekt. */ object SarifReportMerger { fun merge(inputs: Collection<File>, output: File) { val sarifs = inputs.filter { it.exists() }.map { SarifSerializer.fromJson(it.readText()) } val mergedResults = sarifs.flatMap { it.runs.single().results.orEmpty() } val mergedSarif = sarifs[0].copy(runs = listOf(sarifs[0].runs.single().copy(results = mergedResults))) output.writeText(SarifSerializer.toJson(mergedSarif)) } }
apache-2.0
06de1bb9f0e99a12dd6f40501d15a487
34.315789
110
0.694486
3.748603
false
false
false
false
liceoArzignano/app_bold
app/src/main/kotlin/it/liceoarzignano/bold/news/NewsHandler.kt
1
3558
package it.liceoarzignano.bold.news import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import it.liceoarzignano.bold.database.DBHandler import java.util.* class NewsHandler private constructor(context: Context) : DBHandler<News>(context, DB_NAME, DB_VERSION) { override fun onCreate(db: SQLiteDatabase) = db.execSQL("CREATE TABLE $tableName (" + "$KEY_ID INTEGER PRIMARY KEY, " + "$KEY_TITLE TEXT, " + "$KEY_DATE INTEGER, " + "$KEY_DESCRIPTION TEXT, " + "$KEY_URL TEXT)") // Update this when db table will be changed override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) = Unit public override val all: MutableList<News> get() { val list = ArrayList<News>() val db = readableDatabase val cursor = db.rawQuery("SELECT * FROM $tableName ORDER BY $KEY_DATE DESC", null) if (cursor.moveToFirst()) { do { list.add(News( cursor.getString(0).toLong(), cursor.getString(1), cursor.getString(2).toLong(), cursor.getString(3), cursor.getString(4))) } while (cursor.moveToNext()) } cursor.close() return list } override fun get(id: Long): News? { val db = readableDatabase val cursor = db.rawQuery("SELECT * FROM $tableName WHERE ${DBHandler.KEY_ID} = ?", arrayOf(id.toString())) var news: News? = null if (cursor.moveToFirst()) { news = News( cursor.getString(0).toLong(), cursor.getString(1), cursor.getString(2).toLong(), cursor.getString(3), cursor.getString(4)) } cursor.close() return news } override fun getValues(item: News, withId: Boolean): ContentValues { val values = ContentValues() values.put(KEY_TITLE, item.title) values.put(KEY_DATE, item.date) values.put(KEY_DESCRIPTION, item.description) values.put(KEY_URL, item.url) if (withId) { values.put(DBHandler.KEY_ID, item.id) } return values } override val tableName: String get() = "news" fun getByQuery(query: String?): List<News> { var list = all if (query != null) { list = list.filter { val title = it.title.toLowerCase() val message = it.description.toLowerCase() val date = Date(it.date).toString().toLowerCase() title.contains(query) || date.contains(query) || message.contains(query) }.toMutableList() } return list } companion object { private const val DB_NAME = "NewsDatabase.db" private const val DB_VERSION = 1 private const val KEY_TITLE = "title" private const val KEY_DATE = "date" private const val KEY_DESCRIPTION = "description" private const val KEY_URL = "url" // Singleton @Volatile private var INSTANCE: NewsHandler? = null fun getInstance(context: Context): NewsHandler = INSTANCE ?: synchronized(this) { INSTANCE ?: NewsHandler(context).also { INSTANCE = it } } } }
lgpl-3.0
900512c15f214b9ecd740fd49262c5dc
32.252336
105
0.546936
4.687747
false
false
false
false
nickbutcher/plaid
test_shared/src/main/java/io/plaidapp/test/shared/FakeAppInjection.kt
1
1739
/* * Copyright 2018 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.plaidapp.test.shared import io.plaidapp.core.data.CoroutinesDispatcherProvider import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestCoroutineDispatcher @ExperimentalCoroutinesApi fun provideFakeCoroutinesDispatcherProvider( main: CoroutineDispatcher? = null, computation: CoroutineDispatcher? = null, io: CoroutineDispatcher? = null ): CoroutinesDispatcherProvider { val sharedTestCoroutineDispatcher = TestCoroutineDispatcher() return CoroutinesDispatcherProvider( main ?: sharedTestCoroutineDispatcher, computation ?: sharedTestCoroutineDispatcher, io ?: sharedTestCoroutineDispatcher) } @ExperimentalCoroutinesApi fun provideFakeCoroutinesDispatcherProvider( dispatcher: TestCoroutineDispatcher? ): CoroutinesDispatcherProvider { val sharedTestCoroutineDispatcher = TestCoroutineDispatcher() return CoroutinesDispatcherProvider( dispatcher ?: sharedTestCoroutineDispatcher, dispatcher ?: sharedTestCoroutineDispatcher, dispatcher ?: sharedTestCoroutineDispatcher) }
apache-2.0
440e9df2723a3ea59a6cc31edf27e274
36.804348
75
0.784934
5.573718
false
true
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/RsLiteralKind.kt
1
7039
package org.rust.lang.core.psi import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiErrorElement import org.rust.lang.core.lexer.RustEscapesLexer import org.rust.lang.core.psi.RsElementTypes.* import org.rust.lang.utils.unescapeRust interface RsComplexLiteral { val node: ASTNode val offsets: LiteralOffsets } interface RsLiteralWithSuffix : RsComplexLiteral { val suffix: String? get() = offsets.suffix?.substring(node.text) val validSuffixes: List<String> } interface RsTextLiteral { val value: String? val hasUnpairedQuotes: Boolean } sealed class RsLiteralKind(val node: ASTNode) { class Boolean(node: ASTNode) : RsLiteralKind(node) { val value: kotlin.Boolean = node.chars == "true" } class Integer(node: ASTNode) : RsLiteralKind(node), RsLiteralWithSuffix { override val validSuffixes: List<kotlin.String> get() = listOf("u8", "i8", "u16", "i16", "u32", "i32", "u64", "i64", "u128", "i128", "isize", "usize") override val offsets: LiteralOffsets by lazy { offsetsForNumber(node) } } class Float(node: ASTNode) : RsLiteralKind(node), RsLiteralWithSuffix { override val validSuffixes: List<kotlin.String> get() = listOf("f32", "f64") val value: Double? get() = offsets.value?.substring(node.text) ?.filter { it != '_' } ?.let { try { it.toDouble() } catch(e: NumberFormatException) { null } } override val offsets: LiteralOffsets by lazy { offsetsForNumber(node) } } class String(node: ASTNode) : RsLiteralKind(node), RsLiteralWithSuffix, RsTextLiteral { override val offsets: LiteralOffsets by lazy { offsetsForText(node) } override val validSuffixes: List<kotlin.String> get() = emptyList() override val hasUnpairedQuotes: kotlin.Boolean get() = offsets.openDelim == null || offsets.closeDelim == null override val value: kotlin.String? get() { val rawValue = offsets.value?.substring(node.text) return if (node.elementType in RS_RAW_LITERALS) rawValue else rawValue?.unescapeRust(RustEscapesLexer.of(node.elementType)) } } class Char(node: ASTNode) : RsLiteralKind(node), RsLiteralWithSuffix, RsTextLiteral { override val offsets: LiteralOffsets by lazy { offsetsForText(node) } override val validSuffixes: List<kotlin.String> get() = emptyList() override val hasUnpairedQuotes: kotlin.Boolean get() = offsets.openDelim == null || offsets.closeDelim == null override val value: kotlin.String? get() = offsets.value?.substring(node.text) ?.unescapeRust(RustEscapesLexer.of(node.elementType)) } companion object { fun fromAstNode(node: ASTNode): RsLiteralKind? = when (node.elementType) { BOOL_LITERAL -> Boolean(node) INTEGER_LITERAL -> Integer(node) FLOAT_LITERAL -> Float(node) STRING_LITERAL, RAW_STRING_LITERAL, BYTE_STRING_LITERAL, RAW_BYTE_STRING_LITERAL -> String(node) CHAR_LITERAL, BYTE_LITERAL -> Char(node) else -> null } } } val RsLitExpr.kind: RsLiteralKind? get() { val literal = firstChild if (literal is PsiErrorElement) return null return RsLiteralKind.fromAstNode(literal.node) ?: error("Unknown literal: $firstChild (`$text`)") } fun offsetsForNumber(node: ASTNode): LiteralOffsets { val (start, digits) = when (node.text.take(2)) { "0b" -> 2 to "01" "0o" -> 2 to "012345678" "0x" -> 2 to "0123456789abcdefABCDEF" else -> 0 to "0123456789" } var hasExponent = false node.text.substring(start).forEachIndexed { i, ch -> if (!hasExponent && ch in "eE") { hasExponent = true } else if (ch !in digits && ch !in "+-_.") { return LiteralOffsets( value = TextRange.create(0, i + start), suffix = TextRange(i + start, node.textLength)) } } return LiteralOffsets(value = TextRange.allOf(node.text)) } fun offsetsForText(node: ASTNode): LiteralOffsets { when (node.elementType) { RAW_STRING_LITERAL, RAW_BYTE_STRING_LITERAL -> return offsetsForRawText(node) } val text = node.text val quote = when (node.elementType) { BYTE_LITERAL, CHAR_LITERAL -> '\'' else -> '"' } val prefixEnd = locatePrefix(node) val openDelimEnd = doLocate(node, prefixEnd) { assert(text[it] == quote) { "expected open delimiter `$quote` but found `${text[it]}`" } it + 1 } val valueEnd = doLocate(node, openDelimEnd, fun(start: Int): Int { var escape = false text.substring(start).forEachIndexed { i, ch -> if (escape) { escape = false } else when (ch) { '\\' -> escape = true quote -> return i + start } } return node.textLength }) val closeDelimEnd = doLocate(node, valueEnd) { assert(text[it] == quote) { "expected close delimiter `$quote` but found `${text[it]}`" } it + 1 } return LiteralOffsets.fromEndOffsets(prefixEnd, openDelimEnd, valueEnd, closeDelimEnd, node.textLength) } private fun offsetsForRawText(node: ASTNode): LiteralOffsets { val text = node.text val textLength = node.textLength val prefixEnd = locatePrefix(node) val hashes = run { var pos = prefixEnd while (pos < textLength && text[pos] == '#') { pos++ } pos - prefixEnd } val openDelimEnd = doLocate(node, prefixEnd) { assert(textLength - it >= 1 + hashes && text[it] == '#' || text[it] == '"') { "expected open delim" } it + 1 + hashes } val valueEnd = doLocate(node, openDelimEnd, fun(start: Int): Int { text.substring(start).forEachIndexed { i, ch -> if (start + i + hashes < textLength && ch == '"' && text.subSequence(start + i + 1, start + i + 1 + hashes).all { it == '#' }) { return i + start } } return textLength }) val closeDelimEnd = doLocate(node, valueEnd) { assert(textLength - it >= 1 + hashes && text[it] == '"') { "expected close delim" } it + 1 + hashes } return LiteralOffsets.fromEndOffsets(prefixEnd, openDelimEnd, valueEnd, closeDelimEnd, textLength) } private fun locatePrefix(node: ASTNode): Int { node.text.forEachIndexed { i, ch -> if (!ch.isLetter()) { return i } } return node.textLength } private inline fun doLocate(node: ASTNode, start: Int, locator: (Int) -> Int): Int = if (start >= node.textLength) start else locator(start)
mit
f447acdbb7be3bc8ef96b8720c7bd6c4
30.707207
114
0.596392
4.121194
false
false
false
false
iovation/launchkey-android-whitelabel-sdk
demo-app/app/src/kotlinApp/java/com/launchkey/android/authenticator/demo/util/Utils.kt
2
3451
package com.launchkey.android.authenticator.demo.util import android.app.Dialog import android.content.Context import android.view.View import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import com.google.android.material.snackbar.Snackbar import com.launchkey.android.authenticator.sdk.core.exception.* object Utils { fun show(d: Dialog?) { if (d != null && !d.isShowing) { d.show() } } fun dismiss(d: Dialog?) { if (d != null && d.isShowing) { d.dismiss() } } fun getMessageForBaseError(e: Exception?): String? { var m: String? = "" if (e == null) { return m } m = if (e is NoInternetConnectivityException) { "No internet connectivity--check your connection" } else if (e is RequestArgumentException) { "Problem setting things up. Details=" + e.message } else if (e is CommunicationException) { "Error contacting service ($e)" } else if (e is DeviceNotLinkedException) { "Device is yet to be linked or it has been marked as unlinked by the service" } else if (e is DeviceNotFoundException) { "Could not find device to delete" } else if (e is MalformedLinkingCodeException) { "The linking code is invalid" } else if (e is AuthRequestNotFoundException) { "Auth Request has expired" } else if (e is LaunchKeyApiException) { getMessageForApiError(e as LaunchKeyApiException?) } else if (e is UnexpectedCertificateException) { "Your Internet traffic could be monitored. Make sure you are on a reliable network." } else { "Unknown error=" + e.message } return m } fun getMessageForApiError(e: LaunchKeyApiException?): String? { if (e == null) { return null } return if (e is DeviceNameAlreadyUsedException) { "The device name you chose is already assigned to another device associated with your account. Please choose an alternative name or unlink the conflicting device, and then try again." } else if (e is IncorrectSdkKeyException) { "Mobile SDK key incorrect. Please check with your service provider." } else if (e is InvalidLinkingCodeException) { "Invalid linking code used." } else { """ Extras: ${e.message} """.trimIndent() } } fun simpleSnackbarForBaseError(v: View?, e: Exception?) { if (v == null || e == null) { return } val m = getMessageForBaseError(e) simpleSnackbar(v, m, Snackbar.LENGTH_INDEFINITE) } @JvmOverloads fun simpleSnackbar(v: View?, m: String?, duration: Int = Snackbar.LENGTH_LONG) { Snackbar.make(v!!, m!!, duration).show() } fun finish(f: Fragment?) { if (f != null && f.activity != null && !f.activity!!.isFinishing) { f.activity!!.finish() } } fun alert(context: Context?, title: String?, message: String?) { if (context == null || message == null) { return } AlertDialog.Builder(context) .setTitle(title) .setMessage(message) .setPositiveButton("OK", null) .create() .show() } }
mit
4fa69f3136d55f0c85dcf51e8be692ed
33.178218
196
0.585627
4.511111
false
false
false
false
langara/MyIntent
myintent/src/main/java/pl/mareklangiewicz/myintent/REGroupsAdapter.kt
1
3967
package pl.mareklangiewicz.myintent import android.annotation.SuppressLint import android.view.View import android.view.View.inflate import android.view.ViewGroup import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.customview.customView import com.afollestad.materialdialogs.customview.getCustomView import kotlinx.android.synthetic.main.mi_re_group_details.view.* import kotlinx.android.synthetic.main.mi_re_group_layout.view.* import pl.mareklangiewicz.myloggers.MY_DEFAULT_ANDRO_LOGGER import pl.mareklangiewicz.myutils.REGroup import pl.mareklangiewicz.myutils.RERule import pl.mareklangiewicz.myutils.inflate import pl.mareklangiewicz.myutils.str import java.util.* /** * Created by Marek Langiewicz on 14.10.15. */ class REGroupsAdapter() : RecyclerView.Adapter<REGroupsAdapter.ViewHolder>(), View.OnClickListener { val RE_GROUP_VIEW_TAG_HOLDER = R.id.mi_re_group_view_tag_holder val log = MY_DEFAULT_ANDRO_LOGGER var groups: List<REGroup>? = null set(value) { field = value notifyDataSetChanged() } init { setHasStableIds(false) } constructor(groups: List<REGroup>) : this() { this.groups = groups } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val v = parent.inflate<View>(R.layout.mi_re_group_layout)!! v.setOnClickListener(this) val holder = ViewHolder(v) v.setTag(RE_GROUP_VIEW_TAG_HOLDER, holder) return holder } override fun onViewRecycled(holder: ViewHolder) { holder.resetRulesRecyclerView() } @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: ViewHolder, position: Int) { val group = groups?.get(position) ?: throw IllegalStateException() holder.itemView.group_header_view.text = "group ${group.name}:\n\"${group.match}\"" holder.resetRulesRecyclerView() val rules = if(group.editable) group.rules else Collections.unmodifiableList(group.rules) holder.setupRulesRecyclerView(rules) } override fun getItemCount(): Int = groups?.size ?: 0 override fun onClick(v: View) { val tag = v.getTag(RE_GROUP_VIEW_TAG_HOLDER) ?: return val pos = (tag as ViewHolder).adapterPosition val group = groups?.get(pos) ?: return MaterialDialog(v.context) .title(text = "RE Group " + (pos + 1).str) .customView(R.layout.mi_re_group_details, scrollable = true) .icon(R.mipmap.mi_ic_launcher) .show { getCustomView().apply { re_group_name.text = group.name re_group_description.text = group.description re_group_match.text = group.match } } } class ViewHolder(v: View) : RecyclerView.ViewHolder(v) { var ithelper: ItemTouchHelper? = null fun resetRulesRecyclerView() { if (ithelper != null) { ithelper!!.attachToRecyclerView(null) ithelper = null } itemView.group_rules_view.adapter = null } fun setupRulesRecyclerView(rules: MutableList<RERule>) { resetRulesRecyclerView() val adapter = RERulesAdapter() adapter.rules = rules itemView.group_rules_view.adapter = adapter // TODO SOMEDAY: Maybe I should disable item animations on tablets (when linearlayout is used instead of drawer) // because it has some layout issues, but.. maybe google will fix it soon... // itemView.group_rules_view.itemAnimator = null ithelper = ItemTouchHelper(RERulesTouchHelperCallback(adapter)).apply { attachToRecyclerView(itemView.group_rules_view) } } } }
apache-2.0
590bf9e2cc3c3289882d4af051d706c6
30.736
133
0.660953
4.417595
false
false
false
false
whoww/SneakPeek
app/src/main/java/de/sneakpeek/service/BackendParser.kt
1
1905
package de.sneakpeek.service import de.sneakpeek.data.ActualMovie import de.sneakpeek.data.MoviePrediction import de.sneakpeek.data.PredictedStudios import de.sneakpeek.data.Prediction class BackendParser { fun parseActualMovies(response: String): List<ActualMovie> { return response .split(System.getProperty("line.separator")) .map { it.trim() } .filter { !it.isEmpty() } .map {it.split("###") } // Splits Date .map { ActualMovie(week = it[0], title = it[1]) } .toList() } fun parseStudios(response: String): List<PredictedStudios> { return response .split(System.getProperty("line.separator")) .map { it.trim() } .filter { !it.isEmpty() } .map { it.split("###") } .map { PredictedStudios(it[0], it.subList(1, it.size).map { it.substring(1) }) } .toList() } fun parsePrediction(response: String): List<Prediction> { val predictions = ArrayList<Prediction>(30) val allPredictions = response .split(System.getProperty("line.separator")) .map { it.trim() } .filter { !it.isEmpty() } for (prediction in allPredictions) { val movieWithStudiosSplit = prediction.split("###") val positionOfSpace = movieWithStudiosSplit[0].indexOf(" ") val week = movieWithStudiosSplit[0] .substring(positionOfSpace + 1) val movies = movieWithStudiosSplit .subList(1, movieWithStudiosSplit.size) .map { it.split("-", limit = 2) } .map { MoviePrediction(it[1], it[0].toInt()) } predictions.add(Prediction(week, movies = movies)) } return predictions } }
mit
dae45084e1c43edf17124dd53131af08
31.844828
96
0.549081
4.2713
false
false
false
false
pushtorefresh/storio
storio-common-annotations-processor/src/test/kotlin/com/pushtorefresh/storio3/common/annotations/processor/introspection/StorIOTypeMetaTest.kt
3
2762
package com.pushtorefresh.storio3.common.annotations.processor.introspection import com.nhaarman.mockito_kotlin.mock import com.squareup.javapoet.ClassName import nl.jqno.equalsverifier.EqualsVerifier import nl.jqno.equalsverifier.Warning import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import javax.lang.model.element.Element class StorIOTypeMetaTest { private lateinit var annotationMock: Annotation @Before fun setUp() { annotationMock = mock() } @Test fun constructor() { // when val nonNullAnnotationClass = ClassName.get("androidx.core.content.ContextCompat", "NonNull") val typeMeta = StorIOTestTypeMeta("TEST", "TEST", annotationMock, true, nonNullAnnotationClass) // then assertThat(typeMeta.simpleName).isEqualTo("TEST") assertThat(typeMeta.packageName).isEqualTo("TEST") assertThat(typeMeta.storIOType).isEqualTo(annotationMock) assertThat(typeMeta.needsCreator).isEqualTo(true) } @Test fun equalsAndHashCode() { EqualsVerifier.forClass(StorIOTypeMeta::class.java) .suppress(Warning.REFERENCE_EQUALITY) .usingGetClass() .verify() } @Test fun toStringValitadion() { // given val nonNullAnnotationClass = ClassName.get("androidx.core.content.ContextCompat", "NonNull") val typeMeta = StorIOTestTypeMeta("TEST", "TEST", annotationMock, true, nonNullAnnotationClass) val expectedString = "StorIOTypeMeta(simpleName='TEST', packageName='TEST'," + " storIOType=$annotationMock, needsCreator=true, creator=null," + " columns=${typeMeta.columns})" // when val toString = typeMeta.toString() // then assertThat(expectedString).isEqualTo(toString) } } class StorIOTestColumnMeta(enclosingElement: Element, element: Element, elementName: String, javaType: JavaType, storIOColumn: Annotation) : StorIOColumnMeta<Annotation>( enclosingElement, element, elementName, javaType, storIOColumn) class StorIOTestTypeMeta(simpleName: String, packageName: String, storIOType: Annotation, needCreator: Boolean, nonNullAnnotationClass: ClassName ) : StorIOTypeMeta<Annotation, StorIOTestColumnMeta>( simpleName, packageName, storIOType, needCreator, nonNullAnnotationClass ) { override val generateTableClass: Boolean get() = false }
apache-2.0
4651175bf22588b913f237f168c03d34
31.127907
103
0.638668
4.932143
false
true
false
false
arturbosch/TiNBo
tinbo-plugin-api/src/main/kotlin/io/gitlab/arturbosch/tinbo/api/commands/NoopCommands.kt
1
966
package io.gitlab.arturbosch.tinbo.api.commands import io.gitlab.arturbosch.tinbo.api.marker.Command import io.gitlab.arturbosch.tinbo.api.marker.Editable import io.gitlab.arturbosch.tinbo.api.marker.Summarizable import org.springframework.stereotype.Component /** * @author Artur Bosch */ @Component open class NoopCommands(override val id: String = "noop") : Editable, Summarizable, Command { override fun load(name: String): String = "" override fun edit(index: Int): String = "" override fun sum(categories: Set<String>, categoryFilters: Set<String>): String = "" override fun add(): String = "" override fun list(categoryName: String, all: Boolean): String = "" override fun cancel(): String = "" override fun save(name: String): String = "" override fun delete(indexPattern: String): String = "" override fun changeCategory(oldName: String, newName: String): String = "" override fun categories(): String = "" override fun data(): String = "" }
apache-2.0
5e33f7f4603ae892f6991120b1ce5be1
39.25
93
0.738095
3.80315
false
false
false
false
wbrawner/SimpleMarkdown
app/src/main/java/com/wbrawner/simplemarkdown/viewmodel/MarkdownViewModel.kt
1
7067
package com.wbrawner.simplemarkdown.viewmodel import android.content.Context import android.content.SharedPreferences import android.net.Uri import androidx.core.content.edit import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.preference.PreferenceManager import com.wbrawner.simplemarkdown.utility.getName import com.wbrawner.simplemarkdown.view.fragment.MainFragment import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import timber.log.Timber import java.io.File import java.io.FileInputStream import java.io.Reader import java.util.concurrent.atomic.AtomicBoolean const val PREF_KEY_AUTOSAVE_URI = "autosave.uri" class MarkdownViewModel(val timber: Timber.Tree = Timber.asTree()) : ViewModel() { val fileName = MutableLiveData<String?>("Untitled.md") val markdownUpdates = MutableLiveData<String>() val editorActions = MutableLiveData<EditorAction>() val uri = MutableLiveData<Uri?>() private val isDirty = AtomicBoolean(false) private val saveMutex = Mutex() fun updateMarkdown(markdown: String?) { this.markdownUpdates.postValue(markdown ?: "") isDirty.set(true) } suspend fun load( context: Context, uri: Uri?, sharedPrefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) ): Boolean { if (uri == null) { timber.i("No URI provided to load, attempting to load last autosaved file") sharedPrefs.getString(PREF_KEY_AUTOSAVE_URI, null) ?.let { Timber.d("Using uri from shared preferences: $it") return load(context, Uri.parse(it), sharedPrefs) } ?: return false } return withContext(Dispatchers.IO) { try { context.contentResolver.openFileDescriptor(uri, "r")?.use { val fileInput = FileInputStream(it.fileDescriptor) val fileName = uri.getName(context) val content = fileInput.reader().use(Reader::readText) if (content.isBlank()) { // If we don't get anything back, then we can assume that reading the file failed timber.i("Ignoring load for empty file $fileName from $fileInput") return@withContext false } editorActions.postValue(EditorAction.Load(content)) markdownUpdates.postValue(content) [email protected](fileName) [email protected](uri) timber.i("Loaded file $fileName from $fileInput") timber.v("File contents:\n$content") isDirty.set(false) timber.i("Persisting autosave uri in shared prefs: $uri") sharedPrefs.edit() .putString(PREF_KEY_AUTOSAVE_URI, uri.toString()) .apply() true } ?: run { timber.w("Open file descriptor returned null for uri: $uri") false } } catch (e: Exception) { timber.e(e, "Failed to open file descriptor for uri: $uri") false } } } suspend fun save( context: Context, givenUri: Uri? = null, sharedPrefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) ): Boolean = saveMutex.withLock { val uri = givenUri?.let { timber.i("Saving file with given uri: $it") it } ?: this.uri.value?.let { timber.i("Saving file with cached uri: $it") it } ?: run { timber.w("Save called with no uri") return@save false } return withContext(Dispatchers.IO) { try { val fileName = uri.getName(context) context.contentResolver.openOutputStream(uri, "rwt") ?.writer() ?.use { it.write(markdownUpdates.value ?: "") } ?: run { timber.w("Open output stream returned null for uri: $uri") return@withContext false } [email protected](fileName) [email protected](uri) isDirty.set(false) timber.i("Saved file $fileName to uri $uri") timber.i("Persisting autosave uri in shared prefs: $uri") sharedPrefs.edit() .putString(PREF_KEY_AUTOSAVE_URI, uri.toString()) .apply() true } catch (e: Exception) { timber.e(e, "Failed to save file at uri: $uri") false } } } suspend fun autosave(context: Context, sharedPrefs: SharedPreferences) { if (saveMutex.isLocked) { timber.i("Ignoring autosave since manual save is already in progress") return } val isAutoSaveEnabled = sharedPrefs.getBoolean(MainFragment.KEY_AUTOSAVE, true) timber.d("Autosave called. isEnabled? $isAutoSaveEnabled") if (!isDirty.get() || !isAutoSaveEnabled) { timber.i("Ignoring call to autosave. Contents haven't changed or autosave not enabled") return } if (save(context)) { timber.i("Autosave with cached uri succeeded: ${uri.value}") } else { // The user has left the app, with autosave enabled, and we don't already have a // Uri for them or for some reason we were unable to save to the original Uri. In // this case, we need to just save to internal file storage so that we can recover val fileUri = Uri.fromFile(File(context.filesDir, fileName.value ?: "Untitled.md")) timber.i("No cached uri for autosave, saving to $fileUri instead") save(context, fileUri) } } fun reset(untitledFileName: String, sharedPrefs: SharedPreferences) { timber.i("Resetting view model to default state") fileName.postValue(untitledFileName) uri.postValue(null) markdownUpdates.postValue("") editorActions.postValue(EditorAction.Load("")) isDirty.set(false) timber.i("Removing autosave uri from shared prefs") sharedPrefs.edit { remove(PREF_KEY_AUTOSAVE_URI) } } fun shouldPromptSave() = isDirty.get() sealed class EditorAction { val consumed = AtomicBoolean(false) data class Load(val markdown: String) : EditorAction() } }
apache-2.0
de9840ff2a63aa86137fcf322fc2c941
40.327485
105
0.578605
5.033476
false
false
false
false
pokk/KotlinKnifer
kotlinknifer/src/main/java/com/devrapid/kotlinknifer/Bitmap.kt
1
6245
@file:Suppress("NOTHING_TO_INLINE") package com.devrapid.kotlinknifer import android.content.Context import android.content.res.Resources import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.BitmapRegionDecoder import android.graphics.BitmapShader import android.graphics.Canvas import android.graphics.ComposeShader import android.graphics.Paint import android.graphics.PorterDuff import android.graphics.Rect import android.graphics.Shader import android.graphics.drawable.BitmapDrawable import android.renderscript.Allocation import android.renderscript.Element import android.renderscript.RenderScript import android.renderscript.ScriptIntrinsicBlur import android.util.Size import androidx.annotation.DrawableRes import androidx.palette.graphics.Palette import java.io.ByteArrayOutputStream fun Resources.createBitmap( drawableResId: Int, opts: BitmapFactory.Options? = null, rect: Rect? = null, ): Bitmap? { var bitmap: Bitmap? = null openRawResource(drawableResId).use { bitmap = BitmapFactory.decodeStream(it, rect, opts) } return bitmap } /** * Obtain the width and the height of the resource image without loading into the memory. * * @param drawableResId drawable resource id. * @return [Size] with width and height of the image. */ fun Resources.obtainBitmapSize(drawableResId: Int): Size { val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true } createBitmap(drawableResId, opts) return Size(opts.outWidth, opts.outHeight) } fun Bitmap.scale(width: Int, height: Int): Bitmap { val bmp = Bitmap.createScaledBitmap(this, width, height, false) safeRecycle() return bmp } fun Bitmap.scale(widthRatio: Float, heightRatio: Float): Bitmap { val (scaledWidth, scaledHeight) = width * widthRatio to height * heightRatio val bmp = Bitmap.createScaledBitmap(this, scaledWidth.toInt(), scaledHeight.toInt(), false) safeRecycle() return bmp } fun Bitmap.scale(ratio: Float) = scale(ratio, ratio) fun Resources.createCompressedBitmap( @DrawableRes drawableResId: Int, simpleSize: Int = 1, bitmapConf: Bitmap.Config? = null, ): Bitmap { val opts = BitmapFactory.Options().apply { inJustDecodeBounds = false inSampleSize = simpleSize inPreferredConfig = bitmapConf } return requireNotNull(createBitmap(drawableResId, opts)) } fun Resources.createScaledBitmap(@DrawableRes drawableResId: Int, width: Int, height: Int) = requireNotNull(createBitmap(drawableResId)?.scale(width, height)) fun Resources.createScaledBitmap(@DrawableRes drawableResId: Int, widthRatio: Float, heightRatio: Float) = requireNotNull(createBitmap(drawableResId)?.scale(widthRatio, heightRatio)) fun Resources.createScaledBitmap(@DrawableRes drawableResId: Int, ratio: Float) = createScaledBitmap(drawableResId, ratio, ratio) fun Resources.createRegionBitmap( drawableResId: Int, rect: Rect, opts: BitmapFactory.Options = BitmapFactory.Options(), ) = openRawResource(drawableResId).use { // Create a region decoder. val decoder = BitmapRegionDecoder.newInstance(it, false) decoder.decodeRegion(rect, opts) } inline fun Bitmap.toDrawable(context: Context) = BitmapDrawable(context.resources, this) inline fun Bitmap.palette() = Palette.from(this) inline fun Bitmap.palette(maxColorCount: Int) = Palette.from(this).maximumColorCount(maxColorCount).generate() fun Bitmap.toBytes(format: Bitmap.CompressFormat = Bitmap.CompressFormat.PNG, quality: Int = 100) = run { val stream = ByteArrayOutputStream() compress(format, quality, stream) stream.toByteArray() } fun Bitmap.resizeImageAsRatio(aspectRatio: Double): Bitmap = also { val ratio: Double = it.width.toDouble() / it.height.toDouble() if (ratio > aspectRatio) { it.width = (aspectRatio * it.height).toInt() } else { it.height = (it.width / aspectRatio).toInt() } } fun Bitmap?.safeRecycle() { if (this != null && !isRecycled) { recycle() } } fun Bitmap.decorateGradientMask(shaderDst: Shader): Bitmap { val res = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) val canvas = Canvas(res) // Create the source shader bitmap. val shaderSrc = BitmapShader(this, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) val paint = Paint().apply { shader = ComposeShader(shaderDst, shaderSrc, PorterDuff.Mode.SRC_IN) } canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint) return res } fun Context.blurBitmap(image: Bitmap, radius: Float = 25f, scale: Float = 0.4f): Bitmap { val width = Math.round(image.width * scale) val height = Math.round(image.height * scale) // Because of the blurring, we don't have to use original bitmap to blur. It's able to reduce cost. val scaledBitmap = Bitmap.createScaledBitmap(image, width, height, false) // Create a image for blurring. val blurBitmap = Bitmap.createBitmap(scaledBitmap) val rs = RenderScript.create(this) // RenderScript doesn't use VM to allocate memory, we have to do it by ourselves. val tmpIn = Allocation.createFromBitmap(rs, scaledBitmap) // The created Allocation is empty actually, copyTo() is necessary to fill the date. val tmpOut = Allocation.createFromBitmap(rs, blurBitmap) ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)).apply { setRadius(radius) setInput(tmpIn) forEach(tmpOut) } tmpOut.copyTo(blurBitmap) return blurBitmap } object ImageUtils { /** * @param originWidth the width of the origin bitmap * @param originHeight the height of the origin bitmap * @param desWidth the max width of the desired bitmap * @param desHeight the max height of the desired bitmap * @return the optimal sample size to make sure the size of bitmap is not more than the desired. */ fun calculateSampleSize(originWidth: Int, originHeight: Int, desWidth: Int, desHeight: Int): Int { var sampleSize = 1 while ((originWidth / sampleSize) > desWidth && (originHeight / sampleSize) > desHeight) { sampleSize *= 2 } return sampleSize } }
apache-2.0
9536b3c0b2733e95c1631d6edb4c7c74
33.313187
110
0.726341
4.196909
false
false
false
false
simia-tech/epd-kotlin
src/test/kotlin/com/anyaku/test/integration/SignerTest.kt
1
1407
package com.anyaku.test.integration import com.anyaku.epd.structure.Factory import com.anyaku.epd.Signer import com.anyaku.json.parseJson import com.anyaku.map.stringify import com.anyaku.test.integration.javascript.runInWorker import java.util.HashMap import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test class SignerTest() { val signer = Signer() val mapper = Factory.latest.buildLockedMapper() [ Test suppress("UNCHECKED_CAST") ] fun testFreshlyGeneratedProfile() { runInWorker("var profile = epdRoot.Generator.generate(512);" + "profile.sections.open.modules['build_in:com.anyaku.Basic'].content = { name: 'Mr Test', gravata: undefined, country: 'NON' };" + "var lockedProfile = epdRoot.Locker.lock(profile, password, function (id) { return id === profile.id ? profile.publicKey : null; });") val profileJson = runInWorker("JSON.stringify(lockedProfile);") as String val profileMap = parseJson(profileJson) as MutableMap<String, Any?> val profile = mapper.signedDocumentFromMap(HashMap(profileMap)) val serializedProfile = runInWorker("delete(lockedProfile.signature); epdRoot.Object.stringify(lockedProfile);") as String profileMap.remove("signature") assertEquals(serializedProfile, stringify(profileMap)) assertTrue(signer.verify(profile)) } }
lgpl-3.0
871f7dda968a3ab9a9f6729d0ab6dfd7
40.382353
146
0.72779
4.031519
false
true
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/task/DestroyUserBlockTask.kt
1
3896
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.task import android.content.ContentValues import android.content.Context import android.widget.Toast import de.vanita5.microblog.library.MicroBlog import de.vanita5.microblog.library.MicroBlogException import de.vanita5.microblog.library.mastodon.Mastodon import de.vanita5.twittnuker.R import de.vanita5.twittnuker.annotation.AccountType import de.vanita5.twittnuker.constant.nameFirstKey import de.vanita5.twittnuker.extension.model.api.mastodon.toParcelable import de.vanita5.twittnuker.extension.model.api.toParcelable import de.vanita5.twittnuker.extension.model.newMicroBlogInstance import de.vanita5.twittnuker.model.AccountDetails import de.vanita5.twittnuker.model.ParcelableUser import de.vanita5.twittnuker.model.event.FriendshipTaskEvent import de.vanita5.twittnuker.provider.TwidereDataStore.CachedRelationships class DestroyUserBlockTask(context: Context) : AbsFriendshipOperationTask(context, FriendshipTaskEvent.Action.UNBLOCK) { @Throws(MicroBlogException::class) override fun perform(details: AccountDetails, args: Arguments): ParcelableUser { when (details.type) { AccountType.MASTODON -> { val mastodon = details.newMicroBlogInstance(context, Mastodon::class.java) mastodon.unblockUser(args.userKey.id) return mastodon.getAccount(args.userKey.id).toParcelable(details) } AccountType.FANFOU -> { val fanfou = details.newMicroBlogInstance(context, MicroBlog::class.java) return fanfou.destroyFanfouBlock(args.userKey.id).toParcelable(details, profileImageSize = profileImageSize) } else -> { val twitter = details.newMicroBlogInstance(context, MicroBlog::class.java) return twitter.destroyBlock(args.userKey.id).toParcelable(details, profileImageSize = profileImageSize) } } } override fun succeededWorker(details: AccountDetails, args: Arguments, user: ParcelableUser) { val resolver = context.contentResolver // I bet you don't want to see this user in your auto complete list. val values = ContentValues() values.put(CachedRelationships.ACCOUNT_KEY, args.accountKey.toString()) values.put(CachedRelationships.USER_KEY, args.userKey.toString()) values.put(CachedRelationships.BLOCKING, false) values.put(CachedRelationships.FOLLOWING, false) values.put(CachedRelationships.FOLLOWED_BY, false) resolver.insert(CachedRelationships.CONTENT_URI, values) } override fun showSucceededMessage(params: AbsFriendshipOperationTask.Arguments, user: ParcelableUser) { val nameFirst = kPreferences[nameFirstKey] val message = context.getString(R.string.unblocked_user, manager.getDisplayName(user, nameFirst)) Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } }
gpl-3.0
1723adfdfa8ddbaacb4ef0934f1b7a97
44.847059
120
0.728953
4.627078
false
false
false
false
AndroidX/androidx
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/TextFieldImpl.kt
3
14506
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3 import androidx.compose.animation.animateColor import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween import androidx.compose.animation.core.updateTransition import androidx.compose.foundation.interaction.InteractionSource import androidx.compose.foundation.interaction.collectIsFocusedAsState import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.material3.Strings.Companion.DefaultErrorMessage import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.takeOrElse import androidx.compose.ui.layout.IntrinsicMeasurable import androidx.compose.ui.layout.LayoutIdParentData import androidx.compose.ui.layout.Placeable import androidx.compose.ui.layout.layoutId import androidx.compose.ui.semantics.error import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.lerp import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.dp internal enum class TextFieldType { Filled, Outlined } /** * Implementation of the [TextField] and [OutlinedTextField] */ @OptIn(ExperimentalMaterial3Api::class) @Composable internal fun CommonDecorationBox( type: TextFieldType, value: String, innerTextField: @Composable () -> Unit, visualTransformation: VisualTransformation, label: @Composable (() -> Unit)?, placeholder: @Composable (() -> Unit)? = null, leadingIcon: @Composable (() -> Unit)? = null, trailingIcon: @Composable (() -> Unit)? = null, supportingText: @Composable (() -> Unit)? = null, singleLine: Boolean = false, enabled: Boolean = true, isError: Boolean = false, interactionSource: InteractionSource, contentPadding: PaddingValues, colors: TextFieldColors, container: @Composable () -> Unit, ) { val transformedText = remember(value, visualTransformation) { visualTransformation.filter(AnnotatedString(value)) }.text.text val isFocused = interactionSource.collectIsFocusedAsState().value val inputState = when { isFocused -> InputPhase.Focused transformedText.isEmpty() -> InputPhase.UnfocusedEmpty else -> InputPhase.UnfocusedNotEmpty } val labelColor: @Composable (InputPhase) -> Color = { colors.labelColor(enabled, isError, interactionSource).value } val typography = MaterialTheme.typography val bodyLarge = typography.bodyLarge val bodySmall = typography.bodySmall val shouldOverrideTextStyleColor = (bodyLarge.color == Color.Unspecified && bodySmall.color != Color.Unspecified) || (bodyLarge.color != Color.Unspecified && bodySmall.color == Color.Unspecified) TextFieldTransitionScope.Transition( inputState = inputState, focusedTextStyleColor = with(MaterialTheme.typography.bodySmall.color) { if (shouldOverrideTextStyleColor) this.takeOrElse { labelColor(inputState) } else this }, unfocusedTextStyleColor = with(MaterialTheme.typography.bodyLarge.color) { if (shouldOverrideTextStyleColor) this.takeOrElse { labelColor(inputState) } else this }, contentColor = labelColor, showLabel = label != null ) { labelProgress, labelTextStyleColor, labelContentColor, placeholderAlphaProgress -> val decoratedLabel: @Composable (() -> Unit)? = label?.let { @Composable { val labelTextStyle = lerp( MaterialTheme.typography.bodyLarge, MaterialTheme.typography.bodySmall, labelProgress ).let { if (shouldOverrideTextStyleColor) it.copy(color = labelTextStyleColor) else it } Decoration(labelContentColor, labelTextStyle, it) } } val decoratedPlaceholder: @Composable ((Modifier) -> Unit)? = if (placeholder != null && transformedText.isEmpty()) { @Composable { modifier -> Box(modifier.alpha(placeholderAlphaProgress)) { Decoration( contentColor = colors.placeholderColor(enabled).value, typography = MaterialTheme.typography.bodyLarge, content = placeholder ) } } } else null // Developers need to handle invalid input manually. But since we don't provide error // message slot API, we can set the default error message in case developers forget about // it. val defaultErrorMessage = getString(DefaultErrorMessage) val decorationBoxModifier = Modifier.semantics { if (isError) error(defaultErrorMessage) } val leadingIconColor = colors.leadingIconColor(enabled, isError, interactionSource).value val decoratedLeading: @Composable (() -> Unit)? = leadingIcon?.let { @Composable { Decoration(contentColor = leadingIconColor, content = it) } } val trailingIconColor = colors.trailingIconColor(enabled, isError, interactionSource).value val decoratedTrailing: @Composable (() -> Unit)? = trailingIcon?.let { @Composable { Decoration(contentColor = trailingIconColor, content = it) } } val supportingTextColor = colors.supportingTextColor(enabled, isError, interactionSource).value val decoratedSupporting: @Composable (() -> Unit)? = supportingText?.let { @Composable { Decoration(contentColor = supportingTextColor, typography = bodySmall, content = it) } } when (type) { TextFieldType.Filled -> { val containerWithId: @Composable () -> Unit = { Box(Modifier.layoutId(ContainerId), propagateMinConstraints = true) { container() } } TextFieldLayout( modifier = decorationBoxModifier, textField = innerTextField, placeholder = decoratedPlaceholder, label = decoratedLabel, leading = decoratedLeading, trailing = decoratedTrailing, container = containerWithId, supporting = decoratedSupporting, singleLine = singleLine, animationProgress = labelProgress, paddingValues = contentPadding ) } TextFieldType.Outlined -> { // Outlined cutout val labelSize = remember { mutableStateOf(Size.Zero) } val borderContainerWithId: @Composable () -> Unit = { Box( Modifier .layoutId(ContainerId) .outlineCutout(labelSize.value, contentPadding), propagateMinConstraints = true ) { container() } } OutlinedTextFieldLayout( modifier = decorationBoxModifier, textField = innerTextField, placeholder = decoratedPlaceholder, label = decoratedLabel, leading = decoratedLeading, trailing = decoratedTrailing, supporting = decoratedSupporting, singleLine = singleLine, onLabelMeasured = { val labelWidth = it.width * labelProgress val labelHeight = it.height * labelProgress if (labelSize.value.width != labelWidth || labelSize.value.height != labelHeight ) { labelSize.value = Size(labelWidth, labelHeight) } }, animationProgress = labelProgress, container = borderContainerWithId, paddingValues = contentPadding ) } } } } /** * Set content color, typography and emphasis for [content] composable */ @Composable internal fun Decoration( contentColor: Color, typography: TextStyle? = null, content: @Composable () -> Unit ) { val contentWithColor: @Composable () -> Unit = @Composable { CompositionLocalProvider( LocalContentColor provides contentColor, content = content ) } if (typography != null) ProvideTextStyle(typography, contentWithColor) else contentWithColor() } internal fun widthOrZero(placeable: Placeable?) = placeable?.width ?: 0 internal fun heightOrZero(placeable: Placeable?) = placeable?.height ?: 0 private object TextFieldTransitionScope { @Composable fun Transition( inputState: InputPhase, focusedTextStyleColor: Color, unfocusedTextStyleColor: Color, contentColor: @Composable (InputPhase) -> Color, showLabel: Boolean, content: @Composable ( labelProgress: Float, labelTextStyleColor: Color, labelContentColor: Color, placeholderOpacity: Float ) -> Unit ) { // Transitions from/to InputPhase.Focused are the most critical in the transition below. // UnfocusedEmpty <-> UnfocusedNotEmpty are needed when a single state is used to control // multiple text fields. val transition = updateTransition(inputState, label = "TextFieldInputState") val labelProgress by transition.animateFloat( label = "LabelProgress", transitionSpec = { tween(durationMillis = AnimationDuration) } ) { when (it) { InputPhase.Focused -> 1f InputPhase.UnfocusedEmpty -> 0f InputPhase.UnfocusedNotEmpty -> 1f } } val placeholderOpacity by transition.animateFloat( label = "PlaceholderOpacity", transitionSpec = { if (InputPhase.Focused isTransitioningTo InputPhase.UnfocusedEmpty) { tween( durationMillis = PlaceholderAnimationDelayOrDuration, easing = LinearEasing ) } else if (InputPhase.UnfocusedEmpty isTransitioningTo InputPhase.Focused || InputPhase.UnfocusedNotEmpty isTransitioningTo InputPhase.UnfocusedEmpty ) { tween( durationMillis = PlaceholderAnimationDuration, delayMillis = PlaceholderAnimationDelayOrDuration, easing = LinearEasing ) } else { spring() } } ) { when (it) { InputPhase.Focused -> 1f InputPhase.UnfocusedEmpty -> if (showLabel) 0f else 1f InputPhase.UnfocusedNotEmpty -> 0f } } val labelTextStyleColor by transition.animateColor( transitionSpec = { tween(durationMillis = AnimationDuration) }, label = "LabelTextStyleColor" ) { when (it) { InputPhase.Focused -> focusedTextStyleColor else -> unfocusedTextStyleColor } } val labelContentColor by transition.animateColor( transitionSpec = { tween(durationMillis = AnimationDuration) }, label = "LabelContentColor", targetValueByState = contentColor ) content( labelProgress, labelTextStyleColor, labelContentColor, placeholderOpacity ) } } /** * An internal state used to animate a label and an indicator. */ private enum class InputPhase { // Text field is focused Focused, // Text field is not focused and input text is empty UnfocusedEmpty, // Text field is not focused but input text is not empty UnfocusedNotEmpty } internal val IntrinsicMeasurable.layoutId: Any? get() = (parentData as? LayoutIdParentData)?.layoutId internal const val TextFieldId = "TextField" internal const val PlaceholderId = "Hint" internal const val LabelId = "Label" internal const val LeadingId = "Leading" internal const val TrailingId = "Trailing" internal const val SupportingId = "Supporting" internal const val ContainerId = "Container" internal val ZeroConstraints = Constraints(0, 0, 0, 0) internal const val AnimationDuration = 150 private const val PlaceholderAnimationDuration = 83 private const val PlaceholderAnimationDelayOrDuration = 67 internal val TextFieldPadding = 16.dp internal val HorizontalIconPadding = 12.dp internal val SupportingTopPadding = 4.dp internal val IconDefaultSizeModifier = Modifier.defaultMinSize(48.dp, 48.dp)
apache-2.0
3f28883bcc98f7ed07915f0e80b66d8c
37.997312
100
0.625534
5.422804
false
false
false
false
pyamsoft/padlock
padlock-model/src/main/java/com/pyamsoft/padlock/model/ForegroundEvent.kt
1
1017
/* * Copyright 2019 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.pyamsoft.padlock.model import androidx.annotation.CheckResult data class ForegroundEvent( val packageName: String, val className: String ) { companion object { @JvmField val EMPTY = ForegroundEvent("", "") @JvmStatic @CheckResult fun isEmpty(event: ForegroundEvent): Boolean = event.packageName == EMPTY.packageName || event.className == EMPTY.className } }
apache-2.0
9da8916078bd99130357b96b2a1514fb
26.486486
82
0.72468
4.32766
false
false
false
false
AndroidX/androidx
datastore/datastore-compose-samples/src/main/java/com/example/datastorecomposesamples/data/CountRepository.kt
3
4581
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.datastorecomposesamples.data import android.content.Context import android.util.Log import androidx.datastore.core.DataStore import androidx.datastore.core.DataStoreFactory import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.emptyPreferences import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.example.datastorecomposesamples.CountPreferences import java.io.File import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.map import java.io.IOException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch data class CountState(val count: Int) private const val COUNT_STATE_NAME = "count_state" private val Context.preferencesDataStore by preferencesDataStore( name = COUNT_STATE_NAME ) /** * Repository class for managing the DataStores. */ class CountRepository private constructor( private val dataStore: DataStore<Preferences>, private val protoDataStore: DataStore<CountPreferences> ) { companion object { private val PROTO_STORE_FILE_NAME = "datastore_compose_test_app.pb" private var instance: CountRepository? = null fun getInstance(context: Context): CountRepository { instance?.let { return it } synchronized(this) { instance?.let { return it } val protoDataStore = DataStoreFactory.create(serializer = CountSerializer) { File(context.filesDir, PROTO_STORE_FILE_NAME) } return CountRepository(context.preferencesDataStore, protoDataStore).also { instance = it } } } } private val TAG: String = "CountStateRepo" private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) private object PreferencesKeys { val COUNT = intPreferencesKey("count") } val countStateFlow: Flow<CountState> = dataStore.data .catch { exception -> if (exception is IOException) { Log.e(TAG, "Error reading preferences.", exception) emit(emptyPreferences()) } else { throw exception } }.map { preferences -> CountState(preferences[PreferencesKeys.COUNT] ?: 0) } val countProtoStateFlow: Flow<CountState> = protoDataStore.data .catch { exception -> if (exception is IOException) { Log.e(TAG, "Error reading proto.", exception) emit(CountPreferences.getDefaultInstance()) } else { throw exception } }.map { proto -> CountState(proto.count) } fun incrementPreferenceCount() { scope.launch { dataStore.edit { preferences -> val count = preferences[PreferencesKeys.COUNT] ?: 0 preferences[PreferencesKeys.COUNT] = count + 1 } } } fun decrementPreferenceCount() { scope.launch { dataStore.edit { preferences -> val count = preferences[PreferencesKeys.COUNT] ?: 0 preferences[PreferencesKeys.COUNT] = count - 1 } } } fun incrementProtoCount() { scope.launch { protoDataStore.updateData { preferences -> preferences.toBuilder().setCount(preferences.count + 1).build() } } } fun decrementProtoCount() { scope.launch { protoDataStore.updateData { preferences -> preferences.toBuilder().setCount(preferences.count - 1).build() } } } }
apache-2.0
d919f5e067934ce5ae1379c590ef3f1b
32.202899
91
0.649858
4.899465
false
false
false
false
JoachimR/Bible2net
app/src/main/java/de/reiss/bible2net/theword/DaysPositionUtil.kt
1
1219
package de.reiss.bible2net.theword import de.reiss.bible2net.theword.util.extensions.maxDayTime import java.util.Calendar import java.util.Date object DaysPositionUtil { private const val DURATION_ONE_DAY = 86400000; // (24h * 60m * 60s * 1000ms) private val FIRST_DAY_OF_TIME: Calendar = Calendar.getInstance().apply { set(1900, Calendar.JANUARY, 1) } const val DAYS_OF_TIME = 73413 // (Dec 31st 2100) - (Jan 1st 1900) @Throws(IllegalArgumentException::class) fun dayFor(position: Int): Calendar = Calendar.getInstance().apply { if (position < 0) { throw IllegalArgumentException("position cannot be negative") } time = FIRST_DAY_OF_TIME.time add(Calendar.DAY_OF_YEAR, position) } fun positionFor(calendar: Calendar) = calcPosition(calendar.time) private fun positionFor(date: Date) = calcPosition(date) private fun calcPosition(date: Date) = Math.round((millisSinceFirstDay(date) / DURATION_ONE_DAY).toFloat()) private fun millisSinceFirstDay(date: Date) = Calendar.getInstance().apply { time = date maxDayTime() }.timeInMillis - FIRST_DAY_OF_TIME.timeInMillis }
gpl-3.0
73c942756eafd4b45d4ea88d5af0c9d3
31.078947
80
0.672683
3.894569
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/lang/core/completion/RsMacroBracketCompletionTest.kt
2
3665
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.completion import org.intellij.lang.annotations.Language import org.rust.ProjectDescriptor import org.rust.WithDependencyRustProjectDescriptor class RsMacroBracketCompletionTest : RsCompletionTestBase() { fun `test default bracket`() = doTest(""" $MACRO_PLACEHOLDER fn main() { foo/*caret*/ } """, """ $MACRO_PLACEHOLDER fn main() { foo!(/*caret*/) } """) fun `test bracket from documentation`() = doTest(""" /// `foo![]` /// /// ``` /// foo![]; /// bar_foo!(); /// foo(); /// ``` /// /// `foo!()` /// $MACRO_PLACEHOLDER fn main() { foo/*caret*/ } """, """ /// `foo![]` /// /// ``` /// foo![]; /// bar_foo!(); /// foo(); /// ``` /// /// `foo!()` /// $MACRO_PLACEHOLDER fn main() { foo![/*caret*/] } """) fun `test insert space for before braces`() = doTest(""" /// `foo! {}` $MACRO_PLACEHOLDER fn main() { foo/*caret*/ } """, """ /// `foo! {}` $MACRO_PLACEHOLDER fn main() { foo! {/*caret*/} } """) fun `test raw macro calls`() = doTest(""" /// `r#foo![]` /// /// ``` /// foo!(); /// foo![]; /// ``` /// $MACRO_PLACEHOLDER fn main() { foo/*caret*/ } """, """ /// `r#foo![]` /// /// ``` /// foo!(); /// foo![]; /// ``` /// $MACRO_PLACEHOLDER fn main() { foo![/*caret*/] } """) fun `test do not mess with other macro calls`() = doTest(""" /// ``` /// foo![]; /// assert!(true); /// assert!(true); /// ``` /// $MACRO_PLACEHOLDER fn main() { foo/*caret*/ } """, """ /// ``` /// foo![]; /// assert!(true); /// assert!(true); /// ``` /// $MACRO_PLACEHOLDER fn main() { foo![/*caret*/] } """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test bracket from documentation (proc macro)`() = doSingleCompletionByFileTree(""" //- dep-proc-macro/lib.rs /// ``` /// foo! {} /// ``` #[proc_macro] pub fn foo(input: TokenStream) -> TokenStream { input } //- lib.rs fn main() { foo/*caret*/ } """, """ use dep_proc_macro::foo; fn main() { foo! {/*caret*/} } """) /** * Checks completion for both macro 1.0 and macro 2.0. * It substitutes [MACRO_PLACEHOLDER] with actual macro definition of macro `foo` */ private fun doTest(@Language("Rust") before: String, @Language("Rust") after: String) { fun doTest(macroDefinition: String) { doSingleCompletion( before.replace(MACRO_PLACEHOLDER, macroDefinition), after.replace(MACRO_PLACEHOLDER, macroDefinition) ) } // macro 1.0 doTest("macro_rules! foo { () => {}; }") // macro 2.0 doTest("macro foo() {}") } companion object { private const val MACRO_PLACEHOLDER = "%macro_definition%" } }
mit
1e15bc403fb68d0bf64ac148dba98876
21.484663
91
0.412005
4.513547
false
true
false
false
TeamWizardry/LibrarianLib
modules/glitter/src/main/kotlin/com/teamwizardry/librarianlib/glitter/modules/SpriteRenderModule.kt
1
20958
package com.teamwizardry.librarianlib.glitter.modules import com.teamwizardry.librarianlib.albedo.base.state.BaseRenderStates import com.teamwizardry.librarianlib.albedo.base.state.DefaultRenderStates import com.teamwizardry.librarianlib.albedo.buffer.Primitive import com.teamwizardry.librarianlib.albedo.state.RenderState import com.teamwizardry.librarianlib.core.util.Client import com.teamwizardry.librarianlib.core.util.kotlin.builder import com.teamwizardry.librarianlib.glitter.GlitterLightingCache import com.teamwizardry.librarianlib.glitter.ParticleRenderModule import com.teamwizardry.librarianlib.glitter.ParticleUpdateModule import com.teamwizardry.librarianlib.glitter.ReadParticleBinding import com.teamwizardry.librarianlib.glitter.bindings.ConstantBinding import com.teamwizardry.librarianlib.math.floorInt import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderContext import net.minecraft.client.util.math.MatrixStack import net.minecraft.util.Identifier import net.minecraft.util.math.MathHelper import net.minecraft.util.math.Vec3f import java.awt.Color /** * The bread-and-butter render module, a simple billboarded sprite. * * Particles are drawn as dynamically sized/colored sprites that are either billboarded or with an arbitrary facing * defined by [facingVector] (if any of facingVector's components are NaN the player's look vector will be used). * The particles are drawn as rectangles [size] blocks to a side and centered on the the particle's position. * One thing of note is that for some particle effects, particularly ones that should look consistent, * disabling interpolation by passing the current position for both [previousPosition] and [position] can make * the particles rock solid in their positions as opposed to jittering about slightly. */ public class SpriteRenderModule private constructor( /** * The [SpriteRenderOptions] configuring the rendering of the particles. */ public var renderOptions: SpriteRenderOptions, /** * The current position of the particle */ public val position: ReadParticleBinding, /** * The position of the particle last tick, used to interpolate between ticks */ public val previousPosition: ReadParticleBinding?, /** * The OpenGL color of the particle */ public val color: ReadParticleBinding, /** * The width and height of the particle in meters. If this is a 1D binding the value is used for both width and * height, if it's a 2D binding the two axes are used as the width and height. Note that this does not affect UV * coordinates, so if you set this to non-square and have a square texture it will be distorted. */ public val size: ReadParticleBinding, /** * If present, an artificial facing vector used instead of the player's look vector. This vector _does not need * to be normalized._ */ public val facingVector: ReadParticleBinding?, /** * The alpha multiplier for the color. Defaults to 1 if not present. */ public val alphaMultiplier: ReadParticleBinding, /** * The size of the sprite sheet (must be a power of 2) */ public val spriteSheetSize: Int, /** * The sprite index (indexed left-to-right, top-to-bottom) */ public val spriteIndex: ReadParticleBinding, /** * If present, an artificial direction for the particle's "up" axis. This vector _does not need to be normalized._ */ public val upVector: ReadParticleBinding?, /** * If present, an artificial U/V texture size. When used in combination with sprite sheets, this will be a size * within the particle's specific sprite. */ public val uvSize: ReadParticleBinding?, /** * If present, an offset to apply to the UV coordinates of the sprite. When used in combination with sprite sheets, * this will be an offset within the particle's specific sprite. */ public val uvOffset: ReadParticleBinding?, ) : ParticleRenderModule { @Suppress("LocalVariableName") override fun renderDirect( context: WorldRenderContext, particles: List<DoubleArray>, prepModules: List<ParticleUpdateModule> ) { if(particles.isEmpty()) return val profiler = context.profiler() val stack = MatrixStack() val viewPos = Client.minecraft.gameRenderer.camera.pos stack.translate(-viewPos.x, -viewPos.y, -viewPos.z) val modelViewMatrix = stack.peek().model val normalMatrix = context.matrixStack().peek().normal val camera = Client.minecraft.gameRenderer.camera val cameraX = camera.pos.x val cameraY = camera.pos.y val cameraZ = camera.pos.z val lookRightVec = Vec3f(-1f, 0f, 0f) val lookUpVec = Vec3f(0f, 1f, 0f) val lookVec = Vec3f(0f, 0f, -1f) lookRightVec.rotate(camera.rotation) lookUpVec.rotate(camera.rotation) lookVec.rotate(camera.rotation) val lookUpX = lookUpVec.x.toDouble() val lookUpY = lookUpVec.y.toDouble() val lookUpZ = lookUpVec.z.toDouble() val lookX = lookVec.x.toDouble() val lookY = lookVec.y.toDouble() val lookZ = lookVec.z.toDouble() val spriteSize = 1f / spriteSheetSize val spriteIndexMask = spriteSheetSize - 1 val spriteSheetBits = MathHelper.log2(spriteSheetSize) val widthSizeIndex: Int = if (this.size.contents.size == 2) 1 else 0 val renderBuffer = SpriteRenderBuffer.SHARED renderBuffer.worldMatrix.set(modelViewMatrix) renderBuffer.normalMatrix.set(normalMatrix) renderBuffer.texture.set(renderOptions.sprite) renderBuffer.upDominant.set(upVector != null) renderBuffer.enableDiffuseLighting.set(renderOptions.diffuseLight) renderBuffer.enableDiffuseBackface.set(renderOptions.diffuseLight && !renderOptions.cull) renderBuffer.enableLightmap.set(renderOptions.worldLight) profiler.push("Buffer assembly") for(particle in particles) { for (i in prepModules.indices) { prepModules[i].update(particle) } position.load(particle) var posX = position.contents[0] var posY = position.contents[1] var posZ = position.contents[2] if (previousPosition != null) { previousPosition.load(particle) posX = Client.worldTime.interp(previousPosition.contents[0], posX) posY = Client.worldTime.interp(previousPosition.contents[1], posY) posZ = Client.worldTime.interp(previousPosition.contents[2], posZ) } var upX = lookUpX var upY = lookUpY var upZ = lookUpZ var facingX = lookX var facingY = lookY var facingZ = lookZ // compute local axes if (upVector != null) { upVector.load(particle) upX = upVector.contents[0] upY = upVector.contents[1] upZ = upVector.contents[2] if(facingVector == null) { facingX = cameraX - posX facingY = cameraY - posY facingZ = cameraZ - posZ } } if (facingVector != null) { facingVector.load(particle) facingX = facingVector.contents[0] facingY = facingVector.contents[1] facingZ = facingVector.contents[2] if(upVector == null && !(facingX == 0.0 && facingZ == 0.0)) { upX = 0.0 upY = 1.0 upZ = 0.0 } } size.load(particle) val width = size.contents[0] / 2 val height = size.contents[widthSizeIndex] / 2 color.load(particle) alphaMultiplier.load(particle) val r = color.contents[0].toFloat() val g = color.contents[1].toFloat() val b = color.contents[2].toFloat() val a = color.contents[3].toFloat() * alphaMultiplier.contents[0].toFloat() var minU = 0f var minV = 0f var uSize = 1f var vSize = 1f if (spriteSheetSize > 1) { spriteIndex.load(particle) val index = spriteIndex.contents[0].toInt() val uIndex = index and spriteIndexMask val vIndex = index ushr spriteSheetBits minU = spriteSize * uIndex minV = spriteSize * vIndex uSize = spriteSize vSize = spriteSize } if (uvOffset != null) { uvOffset.load(particle) minU += uSize * uvOffset.contents[0].toFloat() minV += vSize * uvOffset.contents[1].toFloat() } if (uvSize != null) { uvSize.load(particle) uSize *= uvSize.contents[0].toFloat() vSize *= uvSize.contents[1].toFloat() } val maxU = minU + uSize val maxV = minV + vSize val lightmap = if(renderOptions.worldLight) { val blockX = floorInt(posX) val blockY = floorInt(posY) val blockZ = floorInt(posZ) GlitterLightingCache.getCombinedLight(blockX, blockY, blockZ) } else { 0 } renderBuffer.position(posX, posY, posZ) .up(upX, upY, upZ) .facing(facingX, facingY, facingZ) .color(r, g, b, a) .size(width, height) .tex(minU, minV, maxU, maxV) .light(lightmap) .endVertex() } profiler.pop() renderOptions.renderState.apply() renderBuffer.draw(Primitive.POINTS, profiler) renderOptions.renderState.cleanup() } public companion object { /** * @param renderOptions The [SpriteRenderOptions] configuring the rendering of the particles * @param position The position binding for the particle (3D) */ @JvmStatic public fun build(renderOptions: SpriteRenderOptions, position: ReadParticleBinding): Builder { return Builder(renderOptions, position) } /** * @param sprite The sprite texture to use. This defaults to normal blending and writing depth * @param position The position binding for the particle (3D) */ @JvmStatic public fun build(sprite: Identifier, position: ReadParticleBinding): Builder { return Builder(SpriteRenderOptions.build(sprite).build(), position) } } /** * @param renderOptions The [SpriteRenderOptions] configuring the rendering of the particles * @param position The position binding for the particle (3D) */ public class Builder(private val renderOptions: SpriteRenderOptions, private val position: ReadParticleBinding) { init { position.require(3) } private var previousPosition: ReadParticleBinding? = null private var color: ReadParticleBinding = ConstantBinding(1.0, 1.0, 1.0, 1.0) private var size: ReadParticleBinding = ConstantBinding(1.0) private var facingVector: ReadParticleBinding? = null private var upVector: ReadParticleBinding? = null private var alphaMultiplier: ReadParticleBinding = ConstantBinding(1.0) private var spriteSheetSize: Int = 1 private var spriteIndex: ReadParticleBinding = ConstantBinding(0.0) private var uvSize: ReadParticleBinding? = null private var uvOffset: ReadParticleBinding? = null /** * The position of the particle last tick, used to interpolate between ticks */ public fun previousPosition(value: ReadParticleBinding): Builder = builder { value.require(3) previousPosition = value } /** * The tint color of the particle */ public fun color(value: ReadParticleBinding): Builder = builder { value.require(4) color = value } /** * The tint color of the particle */ public fun color(value: Color): Builder = builder { color = ConstantBinding(value.red / 255.0, value.green / 255.0, value.blue / 255.0, value.alpha / 255.0) } /** * The tint color of the particle */ public fun color(red: Double, green: Double, blue: Double, alpha: Double): Builder = builder { color = ConstantBinding(red, green, blue, alpha) } /** * The width and height of the particle in meters. If this is a 1D binding the value is used for both width and * height, if it's a 2D binding the two axes are used as the width and height. Note that this does not affect UV * coordinates, so if you set this to non-square and have a square texture it will be distorted. */ public fun size(value: ReadParticleBinding): Builder = builder { value.require(1, 2) size = value } /** * The size of the particle in meters. */ public fun size(value: Double): Builder = builder { size = ConstantBinding(value) } /** * The width and height of the particle in meters. Note that this does not affect UV coordinates, so if you set * this to non-square and have a square texture it will be distorted. */ public fun size(width: Double, height: Double): Builder = builder { size = ConstantBinding(width, height) } /** * If present, an artificial facing vector used instead of the player's look vector. This vector _does not need * to be normalized._ */ public fun facingVector(value: ReadParticleBinding): Builder = builder { value.require(3) facingVector = value } /** * If present, an artificial direction for the particle's "up" axis. This vector _does not need to be normalized._ */ public fun upVector(value: ReadParticleBinding): Builder = builder { value.require(3) upVector = value } /** * The alpha multiplier for the color. Defaults to 1 if not present. */ public fun alphaMultiplier(value: ReadParticleBinding): Builder = builder { value.require(1) alphaMultiplier = value } /** * Configures the sprite sheet. * * @param size The size of the sprite sheet (must be a power of 2) * @param index A binding for the sprite index (indexed left-to-right, top-to-bottom) */ public fun spriteSheet(size: Int, index: ReadParticleBinding): Builder = builder { if (size and (size - 1) != 0) { throw IllegalArgumentException("Sprite sheet size $size is not a power of 2") } spriteSheetSize = size index.require(1) spriteIndex = index } /** * If present, an artificial U/V texture size. When used in combination with sprite sheets, this will be a size * within the particle's specific sprite. */ public fun uvSize(value: ReadParticleBinding): Builder = builder { value.require(2) uvSize = value } /** * If present, an offset to apply to the UV coordinates of the sprite. When used in combination with sprite sheets, * this will be an offset within the particle's specific sprite. */ public fun uvOffset(value: ReadParticleBinding): Builder = builder { value.require(2) uvOffset = value } public fun build(): SpriteRenderModule { return SpriteRenderModule( renderOptions, position, previousPosition, color, size, facingVector, alphaMultiplier, spriteSheetSize, spriteIndex, upVector, uvSize, uvOffset ) } } } public class SpriteRenderOptions private constructor( public val sprite: Identifier, public val renderState: RenderState, public val cull: Boolean, public val worldLight: Boolean, public val diffuseLight: Boolean, ) { public companion object { @JvmStatic public fun build(sprite: Identifier): Builder { return Builder(sprite) } private val defaultState: RenderState = RenderState( DefaultRenderStates.Blend.DEFAULT, DefaultRenderStates.Cull.ENABLED, DefaultRenderStates.DepthTest.LEQUAL, ) } public class Builder(private val sprite: Identifier) { private val renderState = defaultState.extend() private var blur: Boolean = false private var cull: Boolean = true private var worldLight: Boolean = false private var diffuseLight: Boolean = false public fun addState(state: RenderState.State): Builder = builder { renderState.add(state) } /** * Disable OpenGL blending */ public fun disableBlending(): Builder = addState(DefaultRenderStates.Blend.DISABLED) /** * Use additive blending */ public fun additiveBlending(): Builder = addState(DefaultRenderStates.Blend.ADDITIVE) /** * Whether to write to the depth buffer */ public fun writeDepth(value: Boolean): Builder = addState(BaseRenderStates.WriteMask(value, true)) /** * Whether to blur the texture (i.e. interpolate colors vs. use nearest-neighbor scaling) */ public fun blur(value: Boolean): Builder = builder { blur = value } /** * Whether to enable backface culling (defaults to true) */ public fun cull(value: Boolean): Builder = builder { cull = value } /** * Whether to apply world light (i.e. block and sky light) to the particles. Note: At large scales this may have * some performance impact. */ public fun worldLight(value: Boolean): Builder = builder { worldLight = value } /** * Whether to apply diffuse lighting (e.g. particles appear darker from below) to the particles. Note: At large * scales this may have some performance impact. */ public fun diffuseLight(value: Boolean): Builder = builder { diffuseLight = value } public fun build(): SpriteRenderOptions { // val renderState = RenderLayer.MultiPhaseParameters.builder() // .texture(RenderPhase.Texture(sprite, blur, false)) // .alpha(DefaultRenderPhases.ONE_TENTH_ALPHA) // // if (cull || diffuseLight) { // // when using diffuse lighting we always cull. If culling is disabled we render two quads with different normals // renderState.cull(DefaultRenderPhases.ENABLE_CULLING) // } else { // renderState.cull(DefaultRenderPhases.DISABLE_CULLING) // } // // blendMode?.let { blendMode -> // renderState.transparency(RenderPhase.Transparency("particle_transparency", { // RenderSystem.enableBlend() // blendMode.glApply() // }, { // RenderSystem.disableBlend() // RenderSystem.defaultBlendFunc() // })) // } // // if (worldLight) renderState.lightmap(DefaultRenderPhases.ENABLE_LIGHTMAP) // if (diffuseLight) renderState.diffuseLighting(DefaultRenderPhases.ENABLE_DIFFUSE_LIGHTING) // if (!writeDepth) renderState.writeMaskState(DefaultRenderPhases.COLOR_MASK) // // extraConfig?.accept(renderState) // // val renderType = SimpleRenderLayers.makeType( // "particle_type", // vertexFormatForLighting(worldLight, diffuseLight), // GL11.GL_QUADS, // 256, // false, // false, // renderState.build(false) // ) addState(BaseRenderStates.Cull(cull || diffuseLight)) return SpriteRenderOptions(sprite, renderState.build(), cull, worldLight, diffuseLight) } } }
lgpl-3.0
6f6a88c3821b12e6d2193e18d3e5b56c
36.967391
130
0.605067
4.639805
false
false
false
false
DUBULEE/spring-kotlin-sample
src/main/java/testkotlin/configs/SpringConfigs.kt
1
2905
package humantalks.configs import org.springframework.context.annotation.* import org.springframework.web.servlet.config.annotation.* import org.springframework.transaction.annotation.EnableTransactionManagement import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean import org.springframework.jdbc.datasource.SimpleDriverDataSource import javax.sql.DataSource import com.ninja_squad.dbsetup.DbSetup import com.ninja_squad.dbsetup.destination.DataSourceDestination import com.ninja_squad.dbsetup.Operations.* import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter import humantalks.domain.* /** * Entry point of the configuration. * * By default the configuration use the memory implementation of the repo * by setting the spring.profiles.default in web.xml. * * The JPA implementation is activated with the "database" spring profile * To use the JPA implementation add -Dspring.profiles.active=database when * launching the JVM. */ EnableWebMvc Configuration ComponentScan(basePackages = array("humantalks.configs", "humantalks.rest")) open class WebConfig : WebMvcConfigurerAdapter(){ /** * DefaultServletHandler enabled for static resources (angular, css, ...) */ override fun configureDefaultServletHandling( configurer: DefaultServletHandlerConfigurer?) { configurer!!.enable() } } Configuration Profile("memory") open class Repositories{ Bean open fun memoryRepo():HumanRepo{ return MemoryHumanRepoImpl() } } Configuration EnableTransactionManagement Profile("database") open class DataConfig { Bean open fun jpaRepo():HumanRepo{ return JPAHumanRepoImpl() } Bean open fun entityManagerFactory():LocalContainerEntityManagerFactoryBean{ var emf = LocalContainerEntityManagerFactoryBean() emf.setDataSource(dataSource()) emf.setPackagesToScan("humantalks.domain") var vendorAdapter = HibernateJpaVendorAdapter() emf.setJpaVendorAdapter(vendorAdapter) return emf } Bean open fun dataSource():DataSource { val datasource = SimpleDriverDataSource( org.h2.Driver(), "jdbc:h2:mem:test;MODE=Oracle;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE", "sa","") DbSetup(DataSourceDestination(datasource), initialLoadOperation()) .launch() return datasource } fun initialLoadOperation() = sequenceOf( sql("create table humans (id INT, name varchar(100), age INT)"), insertInto("humans")!! .columns("id", "name", "age")!! .values(1,"Bjarne Stroustrup", 63)!! .values(2,"James Gosling" , 58)!! .values(3,"Martin Odersky" , 53)!! .values(4,"Andrey Breslav" , 29)!! .build() ) }
apache-2.0
3c0dbc1b223c50aae5a1476f8d0aa6f9
31.640449
88
0.68778
4.435115
false
true
false
false
androidx/androidx
navigation/navigation-safe-args-generator/src/test/kotlin/androidx/navigation/safe/args/generator/InvalidXmlTest.kt
3
4961
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation.safe.args.generator import androidx.navigation.safe.args.generator.NavParserErrors.UNNAMED_DESTINATION import androidx.navigation.safe.args.generator.NavParserErrors.defaultNullButNotNullable import androidx.navigation.safe.args.generator.NavParserErrors.deprecatedTypeAttrUsed import androidx.navigation.safe.args.generator.NavParserErrors.invalidDefaultValue import androidx.navigation.safe.args.generator.NavParserErrors.invalidDefaultValueReference import androidx.navigation.safe.args.generator.NavParserErrors.invalidId import androidx.navigation.safe.args.generator.NavParserErrors.invalidNavReference import androidx.navigation.safe.args.generator.NavParserErrors.nullDefaultValueReference import androidx.navigation.safe.args.generator.NavParserErrors.sameSanitizedNameActions import androidx.navigation.safe.args.generator.NavParserErrors.sameSanitizedNameArguments import androidx.navigation.safe.args.generator.NavParserErrors.typeIsNotNullable import androidx.navigation.safe.args.generator.models.Action import androidx.navigation.safe.args.generator.models.Argument import androidx.navigation.safe.args.generator.models.ResReference import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) class InvalidXmlTest(private val testCase: ErrorMessage) { companion object { @JvmStatic @Parameterized.Parameters(name = "({0})") fun data() = listOf( ErrorMessage("unnamed_destination_with_action.xml", 25, 5, UNNAMED_DESTINATION), ErrorMessage( "invalid_default_value_reference.xml", 23, 9, invalidDefaultValueReference("foo/") ), ErrorMessage( "null_default_value_reference.xml", 23, 9, nullDefaultValueReference("myarg1") ), ErrorMessage( "invalid_default_value_int.xml", 24, 9, invalidDefaultValue("101034f", IntType) ), ErrorMessage("invalid_id_action.xml", 22, 44, invalidId("@+fppid/finish")), ErrorMessage("invalid_id_destination.xml", 17, 1, invalidId("@1234234+id/foo")), ErrorMessage("action_no_id.xml", 22, 5, mandatoryAttrMissingError("action", "id")), ErrorMessage( "same_name_args.xml", 23, 9, sameSanitizedNameArguments( "myArg", listOf( Argument("my_arg", StringType), Argument("my.arg", StringType) ) ) ), ErrorMessage( "same_name_actions.xml", 22, 5, sameSanitizedNameActions( "NextAction", listOf( Action( ResReference("a.b", "id", "next_action"), ResReference("a.b", "id", "first_screen") ), Action( ResReference("a.b", "id", "nextAction"), ResReference("a.b", "id", "first_screen") ) ) ) ), ErrorMessage("null_but_not_nullable.xml", 24, 13, defaultNullButNotNullable("myArg")), ErrorMessage("type_is_not_nullable.xml", 24, 13, typeIsNotNullable("integer")), ErrorMessage("invalid_deprecated_type.xml", 24, 9, deprecatedTypeAttrUsed("myarg1")), ErrorMessage("invalid_include_tag.xml", 30, 5, NavParserErrors.MISSING_GRAPH_ATTR), ErrorMessage( "invalid_include_graph_attr.xml", 30, 5, invalidNavReference("to_include_login_test") ) ) } @Test fun invalidXml() { val context = Context() val navigationXml = testData("invalid_xmls/${testCase.path}") val expectedError = testCase.copy(path = navigationXml.path) NavParser.parseNavigationFile(navigationXml, "a.b", "foo.app", context) val messages = context.logger.allMessages() assertThat(messages.size, `is`(1)) assertThat(messages.first(), `is`(expectedError)) } }
apache-2.0
3fca21c086ba8a41369ba7d4d536c342
45.364486
98
0.643016
4.505904
false
true
false
false
androidx/androidx
activity/activity-compose/src/main/java/androidx/activity/compose/ActivityResultRegistry.kt
3
6376
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.activity.compose import androidx.activity.result.ActivityResultCaller import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.ActivityResultRegistryOwner import androidx.activity.result.contract.ActivityResultContract import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.ProvidedValue import androidx.compose.runtime.State import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.platform.LocalContext import androidx.core.app.ActivityOptionsCompat import java.util.UUID /** * Provides a [ActivityResultRegistryOwner] that can be used by Composables hosted in a * [androidx.activity.ComponentActivity]. */ public object LocalActivityResultRegistryOwner { private val LocalComposition = compositionLocalOf<ActivityResultRegistryOwner?> { null } /** * Returns current composition local value for the owner or `null` if one has not * been provided nor is one available by looking at the [LocalContext]. */ public val current: ActivityResultRegistryOwner? @Composable get() = LocalComposition.current ?: findOwner<ActivityResultRegistryOwner>(LocalContext.current) /** * Associates a [LocalActivityResultRegistryOwner] key to a value in a call to * [CompositionLocalProvider]. */ public infix fun provides(registryOwner: ActivityResultRegistryOwner): ProvidedValue<ActivityResultRegistryOwner?> { return LocalComposition.provides(registryOwner) } } /** * Register a request to [Activity#startActivityForResult][start an activity for result], * designated by the given [ActivityResultContract][contract]. * * This creates a record in the [ActivityResultRegistry][registry] associated with this * caller, managing request code, as well as conversions to/from [Intent] under the hood. * * This *must* be called unconditionally, as part of initialization path. * * You should *not* call [ActivityResultLauncher.unregister] on the returned * [ActivityResultLauncher]. Attempting to do so will result in an [IllegalStateException]. * * @sample androidx.activity.compose.samples.RememberLauncherForActivityResult * * @param contract the contract, specifying conversions to/from [Intent]s * @param onResult the callback to be called on the main thread when activity result * is available * * @return the launcher that can be used to start the activity. */ @Composable public fun <I, O> rememberLauncherForActivityResult( contract: ActivityResultContract<I, O>, onResult: (O) -> Unit ): ManagedActivityResultLauncher<I, O> { // Keep track of the current contract and onResult listener val currentContract = rememberUpdatedState(contract) val currentOnResult = rememberUpdatedState(onResult) // It doesn't really matter what the key is, just that it is unique // and consistent across configuration changes val key = rememberSaveable { UUID.randomUUID().toString() } val activityResultRegistry = checkNotNull(LocalActivityResultRegistryOwner.current) { "No ActivityResultRegistryOwner was provided via LocalActivityResultRegistryOwner" }.activityResultRegistry val realLauncher = remember { ActivityResultLauncherHolder<I>() } val returnedLauncher = remember { ManagedActivityResultLauncher(realLauncher, currentContract) } // DisposableEffect ensures that we only register once // and that we unregister when the composable is disposed DisposableEffect(activityResultRegistry, key, contract) { realLauncher.launcher = activityResultRegistry.register(key, contract) { currentOnResult.value(it) } onDispose { realLauncher.unregister() } } return returnedLauncher } /** * A launcher for a previously-[prepared call][ActivityResultCaller.registerForActivityResult] * to start the process of executing an [ActivityResultContract]. * * This launcher does not support the [unregister] function. Attempting to use [unregister] will * result in an [IllegalStateException]. * * @param I type of the input required to launch */ public class ManagedActivityResultLauncher<I, O> internal constructor( private val launcher: ActivityResultLauncherHolder<I>, private val contract: State<ActivityResultContract<I, O>> ) : ActivityResultLauncher<I>() { /** * This function should never be called and doing so will result in an * [UnsupportedOperationException]. * * @throws UnsupportedOperationException if this function is called. */ @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated("Registration is automatically handled by rememberLauncherForActivityResult") override fun unregister() { throw UnsupportedOperationException( "Registration is automatically handled by rememberLauncherForActivityResult" ) } override fun launch(input: I, options: ActivityOptionsCompat?) { launcher.launch(input, options) } @Suppress("UNCHECKED_CAST") override fun getContract(): ActivityResultContract<I, *> = contract.value } internal class ActivityResultLauncherHolder<I> { var launcher: ActivityResultLauncher<I>? = null fun launch(input: I?, options: ActivityOptionsCompat?) { launcher?.launch(input, options) ?: error("Launcher has not been initialized") } fun unregister() { launcher?.unregister() ?: error("Launcher has not been initialized") } }
apache-2.0
9b54e275983eb54756c1429fddac13f4
38.85
96
0.749373
5.125402
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/ARB_vertex_shader.kt
1
15345
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengl.templates import org.lwjgl.generator.* import org.lwjgl.opengl.* import org.lwjgl.opengl.BufferType.* val ARB_vertex_shader = "ARBVertexShader".nativeClassGL("ARB_vertex_shader", postfix = ARB) { documentation = """ Native bindings to the $registryLink extension. This extension adds programmable vertex level processing to OpenGL. The application can write vertex shaders in a high level language as defined in the OpenGL Shading Language specification. A vertex shader replaces the transformation, texture coordinate generation and lighting parts of OpenGL, and it also adds texture access at the vertex level. Furthermore, management of vertex shader objects and loading generic attributes are discussed. A vertex shader object, attached to a program object, can be compiled and linked to produce an executable that runs on the vertex processor in OpenGL. This extension also defines how such an executable interacts with the fixed functionality vertex processing of OpenGL 1.4. ${GL20.promoted} """ IntConstant( "Accepted by the {@code shaderType} argument of CreateShaderObjectARB and returned by the {@code params} parameter of GetObjectParameter{if}vARB.", "VERTEX_SHADER_ARB"..0x8B31 ) IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.", "MAX_VERTEX_UNIFORM_COMPONENTS_ARB"..0x8B4A, "MAX_VARYING_FLOATS_ARB"..0x8B4B, "MAX_VERTEX_ATTRIBS_ARB"..0x8869, "MAX_TEXTURE_IMAGE_UNITS_ARB"..0x8872, "MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB"..0x8B4C, "MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB"..0x8B4D, "MAX_TEXTURE_COORDS_ARB"..0x8871 ) IntConstant( """ Accepted by the {@code cap} parameter of Disable, Enable, and IsEnabled, and by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev. """, "VERTEX_PROGRAM_POINT_SIZE_ARB"..0x8642, "VERTEX_PROGRAM_TWO_SIDE_ARB"..0x8643 ) IntConstant( "Accepted by the {@code pname} parameter GetObjectParameter{if}vARB.", "OBJECT_ACTIVE_ATTRIBUTES_ARB"..0x8B89, "OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB"..0x8B8A ) val VERTEX_ATTRIBUTES = IntConstant( "Accepted by the {@code pname} parameter of GetVertexAttrib{dfi}vARB.", "VERTEX_ATTRIB_ARRAY_ENABLED_ARB"..0x8622, "VERTEX_ATTRIB_ARRAY_SIZE_ARB"..0x8623, "VERTEX_ATTRIB_ARRAY_STRIDE_ARB"..0x8624, "VERTEX_ATTRIB_ARRAY_TYPE_ARB"..0x8625, "VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB"..0x886A, "CURRENT_VERTEX_ATTRIB_ARB"..0x8626 ).javaDocLinks IntConstant( "Accepted by the {@code pname} parameter of GetVertexAttribPointervARB.", "VERTEX_ATTRIB_ARRAY_POINTER_ARB"..0x8645 ) IntConstant( "Returned by the {@code type} parameter of GetActiveAttribARB.", "FLOAT_VEC2_ARB"..0x8B50, "FLOAT_VEC3_ARB"..0x8B51, "FLOAT_VEC4_ARB"..0x8B52, "FLOAT_MAT2_ARB"..0x8B5A, "FLOAT_MAT3_ARB"..0x8B5B, "FLOAT_MAT4_ARB"..0x8B5C ) // Vertex attrib functions javadoc val vertexAttribIndex = "the index of the generic vertex attribute to be modified" val vertexAttribX = "the vertex attribute x component" val vertexAttribY = "the vertex attribute y component" val vertexAttribZ = "the vertex attribute z component" val vertexAttribW = "the vertex attribute w component" val vertexAttribBuffer = "the vertex attribute buffer" void( "VertexAttrib1fARB", "Specifies the value of a generic vertex attribute. The y and z components are implicitly set to 0.0f and w to 1.0f.", GLuint.IN("index", vertexAttribIndex), GLfloat.IN("v0", vertexAttribX) ) void("VertexAttrib1sARB", "Short version of #VertexAttrib1fARB().", GLuint.IN("index", vertexAttribIndex), GLshort.IN("v0", vertexAttribX)) void("VertexAttrib1dARB", "Double version of #VertexAttrib1fARB().", GLuint.IN("index", vertexAttribIndex), GLdouble.IN("v0", vertexAttribX)) void( "VertexAttrib2fARB", "Specifies the value of a generic vertex attribute. The y component is implicitly set to 0.0f and w to 1.0f.", GLuint.IN("index", vertexAttribIndex), GLfloat.IN("v0", vertexAttribX), GLfloat.IN("v1", vertexAttribY) ) void("VertexAttrib2sARB", "Short version of #VertexAttrib2fARB().", GLuint.IN("index", vertexAttribIndex), GLshort.IN("v0", vertexAttribX), GLshort.IN("v1", vertexAttribY)) void("VertexAttrib2dARB", "Double version of #VertexAttrib2fARB().", GLuint.IN("index", vertexAttribIndex), GLdouble.IN("v0", vertexAttribX), GLdouble.IN("v1", vertexAttribY)) void( "VertexAttrib3fARB", "Specifies the value of a generic vertex attribute. The w is implicitly set to 1.0f.", GLuint.IN("index", vertexAttribIndex), GLfloat.IN("v0", vertexAttribX), GLfloat.IN("v1", vertexAttribY), GLfloat.IN("v2", vertexAttribZ) ) void("VertexAttrib3sARB", "Short version of #VertexAttrib3fARB().", GLuint.IN("index", vertexAttribIndex), GLshort.IN("v0", vertexAttribX), GLshort.IN("v1", vertexAttribY), GLshort.IN("v2", vertexAttribZ)) void("VertexAttrib3dARB", "Double version of #VertexAttrib3fARB().", GLuint.IN("index", vertexAttribIndex), GLdouble.IN("v0", vertexAttribX), GLdouble.IN("v1", vertexAttribY), GLdouble.IN("v2", vertexAttribZ)) void( "VertexAttrib4fARB", "Specifies the value of a generic vertex attribute.", GLuint.IN("index", vertexAttribIndex), GLfloat.IN("v0", vertexAttribX), GLfloat.IN("v1", vertexAttribY), GLfloat.IN("v2", vertexAttribZ), GLfloat.IN("v3", vertexAttribW) ) void("VertexAttrib4sARB", "Short version of #VertexAttrib4fARB().", GLuint.IN("index", vertexAttribIndex), GLshort.IN("v0", vertexAttribX), GLshort.IN("v1", vertexAttribY), GLshort.IN("v2", vertexAttribZ), GLshort.IN("v3", vertexAttribW)) void("VertexAttrib4dARB", "Double version of #VertexAttrib4fARB().", GLuint.IN("index", vertexAttribIndex), GLdouble.IN("v0", vertexAttribX), GLdouble.IN("v1", vertexAttribY), GLdouble.IN("v2", vertexAttribZ), GLdouble.IN("v3", vertexAttribW)) void("VertexAttrib4NubARB", "Normalized unsigned byte version of #VertexAttrib4fARB().", GLuint.IN("index", vertexAttribIndex), GLubyte.IN("x", vertexAttribX), GLubyte.IN("y", vertexAttribY), GLubyte.IN("z", vertexAttribZ), GLubyte.IN("w", vertexAttribW)) void("VertexAttrib1fvARB", "Pointer version of #VertexAttrib1fARB().", GLuint.IN("index", vertexAttribIndex), Check(1)..const..GLfloat_p.IN("v", vertexAttribBuffer)) void("VertexAttrib1svARB", "Pointer version of #VertexAttrib1sARB().", GLuint.IN("index", vertexAttribIndex), Check(1)..const..GLshort_p.IN("v", vertexAttribBuffer)) void("VertexAttrib1dvARB", "Pointer version of #VertexAttrib1dARB().", GLuint.IN("index", vertexAttribIndex), Check(1)..const..GLdouble_p.IN("v", vertexAttribBuffer)) void("VertexAttrib2fvARB", "Pointer version of #VertexAttrib2fARB().", GLuint.IN("index", vertexAttribIndex), Check(2)..const..GLfloat_p.IN("v", vertexAttribBuffer)) void("VertexAttrib2svARB", "Pointer version of #VertexAttrib2sARB().", GLuint.IN("index", vertexAttribIndex), Check(2)..const..GLshort_p.IN("v", vertexAttribBuffer)) void("VertexAttrib2dvARB", "Pointer version of #VertexAttrib2dARB().", GLuint.IN("index", vertexAttribIndex), Check(2)..const..GLdouble_p.IN("v", vertexAttribBuffer)) void("VertexAttrib3fvARB", "Pointer version of #VertexAttrib3fARB().", GLuint.IN("index", vertexAttribIndex), Check(3)..const..GLfloat_p.IN("v", vertexAttribBuffer)) void("VertexAttrib3svARB", "Pointer version of #VertexAttrib3sARB().", GLuint.IN("index", vertexAttribIndex), Check(3)..const..GLshort_p.IN("v", vertexAttribBuffer)) void("VertexAttrib3dvARB", "Pointer version of #VertexAttrib3dARB().", GLuint.IN("index", vertexAttribIndex), Check(3)..const..GLdouble_p.IN("v", vertexAttribBuffer)) void("VertexAttrib4fvARB", "Pointer version of #VertexAttrib4fARB().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLfloat_p.IN("v", vertexAttribBuffer)) void("VertexAttrib4svARB", "Pointer version of #VertexAttrib4sARB().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLshort_p.IN("v", vertexAttribBuffer)) void("VertexAttrib4dvARB", "Pointer version of #VertexAttrib4dARB().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLdouble_p.IN("v", vertexAttribBuffer)) void("VertexAttrib4ivARB", "Integer pointer version of #VertexAttrib4fARB().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLint_p.IN("v", vertexAttribBuffer)) void("VertexAttrib4bvARB", "Byte pointer version of #VertexAttrib4fARB().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLbyte_p.IN("v", vertexAttribBuffer)) void("VertexAttrib4ubvARB", "Pointer version of #VertexAttrib4NubARB().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLubyte_p.IN("v", vertexAttribBuffer)) void("VertexAttrib4usvARB", "Unsigned short pointer version of #VertexAttrib4fARB().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLushort_p.IN("v", vertexAttribBuffer)) void("VertexAttrib4uivARB", "Unsigned int pointer version of #VertexAttrib4fARB().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLuint_p.IN("v", vertexAttribBuffer)) void("VertexAttrib4NbvARB", "Normalized byte pointer version of #VertexAttrib4fARB().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLbyte_p.IN("v", vertexAttribBuffer)) void("VertexAttrib4NsvARB", "Normalized short pointer version of #VertexAttrib4fARB().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLshort_p.IN("v", vertexAttribBuffer)) void("VertexAttrib4NivARB", "Normalized int pointer version of #VertexAttrib4fARB().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLint_p.IN("v", vertexAttribBuffer)) void("VertexAttrib4NubvARB", "Normalized unsigned byte pointer version of #VertexAttrib4fARB().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLubyte_p.IN("v", vertexAttribBuffer)) void("VertexAttrib4NusvARB", "Normalized unsigned short pointer version of #VertexAttrib4fARB().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLushort_p.IN("v", vertexAttribBuffer)) void("VertexAttrib4NuivARB", "Normalized unsigned int pointer version of #VertexAttrib4fARB().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLuint_p.IN("v", vertexAttribBuffer)) void( "VertexAttribPointerARB", "Specifies the location and organization of a vertex attribute array.", GLuint.IN("index", vertexAttribIndex), GLint.IN("size", "the number of values per vertex that are stored in the array. The initial value is 4", "1 2 3 4 GL12#BGRA"), GLenum.IN( "type", "the data type of each component in the array. The initial value is GL_FLOAT", """ GL11#BYTE GL11#UNSIGNED_BYTE GL11#SHORT GL11#UNSIGNED_SHORT GL11#INT GL11#UNSIGNED_INT GL30#HALF_FLOAT GL11#FLOAT GL11#DOUBLE GL12#UNSIGNED_INT_2_10_10_10_REV GL33#INT_2_10_10_10_REV GL41#FIXED """ ), GLboolean.IN("normalized", "whether fixed-point data values should be normalized or converted directly as fixed-point values when they are accessed"), GLsizei.IN( "stride", """ the byte offset between consecutive generic vertex attributes. If stride is 0, the generic vertex attributes are understood to be tightly packed in the array. The initial value is 0. """ ), ARRAY_BUFFER..MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT )..const..void_p.IN( "pointer", """ the vertex attribute data or the offset of the first component of the first generic vertex attribute in the array in the data store of the buffer currently bound to the GL15#ARRAY_BUFFER target. The initial value is 0. """ ) ) void( "EnableVertexAttribArrayARB", "Enables a generic vertex attribute array.", GLuint.IN("index", "the index of the generic vertex attribute to be enabled") ) void( "DisableVertexAttribArrayARB", "Disables a generic vertex attribute array.", GLuint.IN("index", "the index of the generic vertex attribute to be disabled") ) void( "BindAttribLocationARB", "Associates a generic vertex attribute index with a named attribute variable.", GLhandleARB.IN("programObj", "the handle of the program object in which the association is to be made"), GLuint.IN("index", "the index of the generic vertex attribute to be bound"), const..GLcharASCII_p.IN("name", "a null terminated string containing the name of the vertex shader attribute variable to which {@code index} is to be bound") ) void( "GetActiveAttribARB", "Returns information about an active attribute variable for the specified program object.", GLhandleARB.IN("programObj", "the program object to be queried"), GLuint.IN("index", "the index of the attribute variable to be queried"), AutoSize("name")..GLsizei.IN("maxLength", "the maximum number of characters OpenGL is allowed to write in the character buffer indicated by {@code name}"), Check(1)..nullable..GLsizei_p.OUT( "length", """ the number of characters actually written by OpenGL in the string indicated by {@code name} (excluding the null terminator) if a value other than $NULL is passed """ ), Check(1)..GLint_p.OUT("size", "the size of the attribute variable"), Check(1)..GLenum_p.OUT("type", "the data type of the attribute variable"), Return( "length", "ARBShaderObjects.glGetObjectParameteriARB(programObj, GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB)" )..GLcharASCII_p.OUT("name", "a null terminated string containing the name of the attribute variable") ) GLint( "GetAttribLocationARB", "Returns the location of an attribute variable.", GLhandleARB.IN("programObj", "the program object to be queried"), const..GLcharASCII_p.IN("name", "a null terminated string containing the name of the attribute variable whose location is to be queried") ) void( "GetVertexAttribivARB", "Returns the integer value of a generic vertex attribute parameter.", GLuint.IN("index", "the generic vertex attribute parameter to be queried"), GLenum.IN( "pname", "the symbolic name of the vertex attribute parameter to be queried", "GL15#VERTEX_ATTRIB_ARRAY_BUFFER_BINDING $VERTEX_ATTRIBUTES GL30#VERTEX_ATTRIB_ARRAY_INTEGER GL33#VERTEX_ATTRIB_ARRAY_DIVISOR" ), Check(1)..ReturnParam..GLint_p.OUT("params", "returns the requested data") ) void( "GetVertexAttribfvARB", "Float version of #GetVertexAttribivARB().", GLuint.IN("index", "the generic vertex attribute parameter to be queried"), GLenum.IN("pname", "the symbolic name of the vertex attribute parameter to be queried"), Check(4)..GLfloat_p.OUT("params", "returns the requested data") ) void( "GetVertexAttribdvARB", "Double version of #GetVertexAttribivARB().", GLuint.IN("index", "the generic vertex attribute parameter to be queried"), GLenum.IN("pname", "the symbolic name of the vertex attribute parameter to be queried"), Check(4)..GLdouble_p.OUT("params", "returns the requested data") ) void( "GetVertexAttribPointervARB", "Returns the address of the specified generic vertex attribute pointer.", GLuint.IN("index", "the generic vertex attribute parameter to be queried"), GLenum.IN("pname", "the symbolic name of the generic vertex attribute parameter to be returned", "#VERTEX_ATTRIB_ARRAY_POINTER_ARB"), Check(1)..ReturnParam..void_pp.OUT("pointer", "the pointer value") ) }
bsd-3-clause
a2fe6b577d14c70c785e3bb59ff4761e
49.983389
256
0.741023
3.546337
false
false
false
false
jonnyzzz/kotlin.xml.bind
jdom/src/test/kotlin/org/jonnyzzz/kotlin/xml/bind/jdom/XBindTest.kt
1
20557
@file:Suppress("unused") package org.jonnyzzz.kotlin.xml.bind.jdom import org.jdom2.Element import org.jdom2.output.Format import org.jdom2.output.XMLOutputter import org.jonnyzzz.kotlin.xml.bind.* import org.jonnyzzz.kotlin.xml.bind.jdom.impl.JDOMIMPL import org.jonnyzzz.kotlin.xml.dsl.XWriter import org.jonnyzzz.kotlin.xml.dsl.jdom.jdom import org.junit.Assert import org.junit.Ignore import org.junit.Test class XBindTest { @Test fun test_copy_XML() { class M(val x : String) { var Y : String? by JXML / XText } val m1 = M("z").apply { Y = "aaa" } val m2 = M("q").apply { JDOM.copy(m1, this) } Assert.assertEquals(m1.Y, m2.Y) } @Test fun test_bind_XML() { class M(val x : String) { var Y : String? by JXML / XText } val m1 = M("z").apply { JDOM.bind(jdom("aaa") { text("yohoho") }, this) } Assert.assertEquals("yohoho", m1.Y) } @Test fun test_can_read_text_from_XML() { class Data { var X : String? by JXML / XText } val d : Data = JDOM.load(jdom("text") { text("hohoho")}, Data::class.java) Assert.assertEquals(d.X, "hohoho") } @Test fun test_can_read_text_from_XML_newlines() { class Data { var X : String? by JXML / XText } val d : Data = JDOM.load(jdom("text") { text("\nhohoho\n\n")}, Data::class.java) Assert.assertEquals(d.X, "\nhohoho\n\n") } @Test fun test_can_read_sub_text_from_XML() { class Data { var X : String? by JXML / "a" / "b" / XText } val d : Data = JDOM.load(jdom("text") { element("a") { element("b") { text("f777") } }; text("hohoho")}, Data::class.java) Assert.assertEquals(d.X, "f777") } @Test fun test_can_read_CDATA_from_XML() { class Data { var X : String? by JXML / XCDATA } val d : Data = JDOM.load(jdom("text") { cdata("hohoho")}, Data::class.java) Assert.assertEquals(d.X, "hohoho") } @Test fun test_can_read_CDATA_from_XML_newlines() { class Data { var X : String? by JXML / XCDATA } val d : Data = JDOM.load(jdom("text") { cdata("\nhohoho\n\n")}, Data::class.java) Assert.assertEquals(d.X, "\nhohoho\n\n") } @Test fun test_can_read_attribute_from_XML() { class Data { var X : String? by JXML / XAttribute("a") } val d : Data = JDOM.load(jdom("aaa") { attribute("a", "42")} , Data::class.java) Assert.assertEquals(d.X, "42") } @Test fun test_can_sub_read_attribute_from_XML() { class Data { var X : String? by JXML / "a" / XAttribute("a") } val d : Data = JDOM.load(jdom("aaa") {element("a") { attribute("a", "42")}} , Data::class.java) Assert.assertEquals(d.X, "42") } @Test fun test_can_read_sub_attribute_from_XML() { class Inner { var Y by JXML / "q" / XText } class Data { var X by JXML / "a" / XSub(Inner::class.java) } val d : Data = JDOM.load(jdom("aaa") {element("a") {element("q") { text("42")}}} , Data::class.java) Assert.assertEquals(d.X?.Y, "42") val d2 : Data = JDOM.load(jdom("aaa") {element("aZ") {element("q") { text("42")}}} , Data::class.java) Assert.assertNull(d2.X) } @Test fun test_can_read_unknown_attribute_from_XML() { class Data { var X by JXML / "a" / XUnknown } fun XWriter.q() = element("a") {element("q") { text("42")}} val d : Data = JDOM.load(jdom("aaa") { q() } , Data::class.java) Assert.assertEquals(d.X.dump(), jdom("aaa") { q()}.getChild("a").dump()) } @Test fun test_can_read_list_elements() { class Data { var X by JXML / "parameters" / XElements("param") / XAttribute("name") } val el = jdom("aaa") { element("parameters") { for(i in 1..5) { element("param") { attribute("name", "$i")} } } } val d : Data = JDOM.load(el , Data::class.java) Assert.assertEquals(d.X, listOf("1", "2", "3", "4", "5")) } @Test fun test_can_read_any_element() { class Inner { var N by JXML / XName var Y by JXML / XText } class Data { var X by JXML / "parameters" / XAnyElement / XSub(Inner::class.java) } val el = jdom("aaa") { element("parameters") { element("param") { text("yohoho")} } } val d : Data = JDOM.load(el , Data::class.java) Assert.assertEquals(d.X?.N, "param") Assert.assertEquals(d.X?.Y, "yohoho") } @Test fun test_can_read_any_elements() { class Inner { var N by JXML / XName var Y by JXML / XText } class Data { var X by JXML / "parameters" / XAnyElements / XSub(Inner::class.java) } val el = jdom("aaa") { element("parameters") { element("param") { text("yohoho")} element("qqq") { text("123")} element("ppp") { text("www")} } } val d : Data = JDOM.load(el , Data::class.java) Assert.assertEquals(d.X?.size, 3) Assert.assertEquals(d.X?.get(0)?.N, "param") Assert.assertEquals(d.X?.get(0)?.Y, "yohoho") Assert.assertEquals(d.X?.get(1)?.N, "qqq") Assert.assertEquals(d.X?.get(1)?.Y, "123") Assert.assertEquals(d.X?.get(2)?.N, "ppp") Assert.assertEquals(d.X?.get(2)?.Y, "www") } @Test fun test_read_any_element_does_not_include_parsed() { class Data { var X by JXML / "x" / XUnknown var Y by JXML / "Y" / XUnknown var Z by JXML / XAnyElements / XUnknown } val el = jdom("aaa") { element("x") { text("yohoho")} element("Y") { text("123")} element("z") { text("www")} element("p") { text("www")} } val d : Data = JDOM.load(el , Data::class.java) Assert.assertEquals(d.Z?.size, 2) Assert.assertEquals(d.Z?.get(0)?.name, "z") Assert.assertEquals(d.Z?.get(1)?.name, "p") } @Test @Ignore fun test_read_any_sub_element_does_not_include_parsed() { class Data { var X by JXML / "a" / "x" / XUnknown var Y by JXML / "a" / "Y" / XUnknown var Z by JXML / "a" / XAnyElements / XUnknown } val el = jdom("aaa") { element("a") { element("x") { text("yohoho") } element("Y") { text("123") } element("z") { text("www") } element("p") { text("www") } } } val d : Data = JDOM.load(el , Data::class.java) Assert.assertEquals(d.Z?.size, 2) Assert.assertEquals(d.Z?.get(0)?.name, "z") Assert.assertEquals(d.Z?.get(1)?.name, "p") } @Test fun test_read_ReadOnly() { class Data { var X by JXML / XText - XReadOnly } val el = jdom("aaa") { text("ddd") } val d : Data = JDOM.load(el , Data::class.java) Assert.assertEquals(d.X, "ddd") } @Test fun test_read_onLoaded() { class Data { var X by JXML / XText - XReadOnly - XCallback<String>(onLoaded = { a -> (a ?: "") + "_OnLoaded"}) } val el = jdom("aaa") { text("ddd") } val d : Data = JDOM.load(el , Data::class.java) Assert.assertEquals(d.X, "ddd_OnLoaded") } @Test fun test_read_XNameList() { class Data { var Name by JXML / XName var Value by JXML / XAttribute("x") } class Values { val Foo by JXML / "r" / XAnyElements / XSub(Data::class.java) } val el = jdom("aaa") { element("r") { element("a") { attribute("x", "aq") } element("a") { attribute("x", "ab") } element("b") { attribute("x", "bb") } element("c") { attribute("x", "cc") } element("c") { attribute("x", "rr") } } } val d = JDOM.load(el , Values::class.java) println(d) Assert.assertEquals(d.Foo?.size, 5) Assert.assertEquals(d.Foo?.get(0)?.Name, "a") Assert.assertEquals(d.Foo?.get(0)?.Value, "aq") Assert.assertEquals(d.Foo?.get(1)?.Name, "a") Assert.assertEquals(d.Foo?.get(1)?.Value, "ab") Assert.assertEquals(d.Foo?.get(2)?.Name, "b") Assert.assertEquals(d.Foo?.get(2)?.Value, "bb") Assert.assertEquals(d.Foo?.get(3)?.Name, "c") Assert.assertEquals(d.Foo?.get(3)?.Value, "cc") Assert.assertEquals(d.Foo?.get(4)?.Name, "c") Assert.assertEquals(d.Foo?.get(4)?.Value, "rr") saveLoadTest(d, { Foo?.flatMap { listOf("z", "n" + it.Name, "v" + it.Value) } ?: listOf()}) } @Test fun test_can_write_text_from_XML() { class Data { var X : String? by JXML / XText } val d = Data().apply { X = "42"} val element = JDOMIMPL.save("aaa", d) Assert.assertEquals(element.name, "aaa") Assert.assertEquals(element.textTrim, "42") } @Test fun test_can_write_sub_text_from_XML() { class Data { var X : String? by JXML / "q" / XText } val d = Data().apply { X = "42"} val element = JDOMIMPL.save("aaa", d) Assert.assertEquals(element.name, "aaa") Assert.assertEquals(element.getChild("q")?.textTrim, "42") } @Test fun test_can_write_cdata_from_XML() { class Data { var X : String? by JXML / XCDATA } val d = Data().apply { X = "42"} val element = JDOMIMPL.save("aaa", d) Assert.assertEquals(element.name, "aaa") Assert.assertEquals(element.textTrim, "42") } @Test fun test_can_write_cdata_from_XML_newline() { class Data { var X : String? by JXML / XCDATA } val d = Data().apply { X = "\n\n42\n\n"} val element = JDOMIMPL.save("aaa", d) Assert.assertEquals(element.name, "aaa") Assert.assertEquals(element.text, "\n\n42\n\n") } @Test fun test_can_write_attribute_from_XML() { class Data { var X : String? by JXML / XAttribute("a") } val d = Data().apply { X = "42"} val element = JDOMIMPL.save("aaa", d) Assert.assertEquals(element.name, "aaa") Assert.assertEquals(element.getAttributeValue("a"), "42") } @Test fun test_can_sub_write_attribute_from_XML() { class Data { var X : String? by JXML / "bbb"/ XAttribute("a") } val d = Data().apply { X = "42"} val element = JDOMIMPL.save("aaa", d) Assert.assertEquals(element.name, "aaa") Assert.assertEquals(element.getChild("bbb")?.getAttributeValue("a"), "42") } @Test fun test_can_sub_write_attribute_in_order() { class Data { var A by JXML[2] / XAttribute("a") - "a" var B by JXML[1] / XAttribute("b") - "b" var C by JXML[3] / XAttribute("c") - "c" } val d = Data().apply { } val element = JDOMIMPL.save("aaa", d) Assert.assertEquals(element.name, "aaa") Assert.assertEquals(element.attributes?.size, 3) Assert.assertEquals(element.attributes?.get(0)?.name, "b") Assert.assertEquals(element.attributes?.get(1)?.name, "a") Assert.assertEquals(element.attributes?.get(2)?.name, "c") } @Test fun test_can_sub_write_attribute_in_order_inherit() { open class DataBase { var B by JXML[1] / XAttribute("b") - "b" } open class DataInner : DataBase() class Data : DataInner() { var A by JXML[2] / XAttribute("a") - "a" var C by JXML[3] / XAttribute("c") - "c" } val d = Data().apply { } val element = JDOMIMPL.save("aaa", d) Assert.assertEquals(element.name, "aaa") Assert.assertEquals(element.attributes?.size, 3) Assert.assertEquals(element.attributes?.get(0)?.name, "b") Assert.assertEquals(element.attributes?.get(1)?.name, "a") Assert.assertEquals(element.attributes?.get(2)?.name, "c") } @Test fun test_can_sub_write_elements_in_order_inherit() { open class DataBase { var B by JXML[1] / "b" / XText - "b" } open class DataInner : DataBase() class Data : DataInner() { var A by JXML[2] / "a" / XText - "a" var C by JXML[3] / "c" / XText - "c" } val d = Data().apply { } val element = JDOMIMPL.save("aaa", d) println(element.dump()) Assert.assertEquals(element.name, "aaa") Assert.assertEquals(element.children?.size, 3) Assert.assertEquals(element.children?.get(0)?.name, "b") Assert.assertEquals(element.children?.get(1)?.name, "a") Assert.assertEquals(element.children?.get(2)?.name, "c") } @Test fun test_can_write_sub_attribute_from_XML() { class Inner { var X : String? by JXML / "bbb" / XAttribute("a") } class Data { var I by JXML / "zzz"/ XSub(Inner::class.java) } val d = Data().apply { I = Inner().apply{X = "42"}} val element = JDOMIMPL.save("aaa", d) println(element.dump()) Assert.assertEquals(element.name, "aaa") Assert.assertEquals(element.getChild("zzz")?.getChild("bbb")?.getAttributeValue("a"), "42") } @Test fun test_should_not_add_inner_elements_for_null() { class Inner { var X : String? by JXML / "bbb" / "ccc" / "ddd" / XAttribute("a") } val d = Inner() val element = JDOMIMPL.save("aaa", d) println(element.dump()) Assert.assertEquals(element.name, "aaa") Assert.assertNull(element.getChild("bbb")?.getChild("ccc")?.getChild("ddd")?.getAttributeValue("a")) Assert.assertNull(element.getChild("bbb")?.getChild("ccc")?.getChild("ddd")) Assert.assertNull(element.getChild("bbb")?.getChild("ccc")) Assert.assertNull(element.getChild("bbb")) } @Test fun test_can_write_list_elements() { class Data { var X by JXML / "parameters" / XElements("param") / XAttribute("name") } val d = Data().apply { X = listOf("a", "b", "c", "d")} val element = JDOMIMPL.save("aaa", d) println(element.dump()) Assert.assertEquals(element.name, "aaa") Assert.assertNotNull(element.getChild("parameters")) Assert.assertEquals(element.getChild("parameters")?.children?.size, 4) Assert.assertEquals(element.getChild("parameters")?.children?.map{it.getAttributeValue("name")}, listOf("a", "b", "c", "d")) } @Test fun test_write_element_default_value() { class Data { var X by JXML / XAttribute("name") - "42" } val d = Data().apply { } val element = JDOMIMPL.save("aaa", d) println(element.dump()) Assert.assertEquals(element.name, "aaa") Assert.assertNotNull(element.getAttributeValue("name"), "42") } @Test fun test_write_any_element() { class Inner { var N by JXML / XName var Y by JXML / XText } class Data { var X by JXML / "parameters" / XAnyElement / XSub(Inner::class.java) } val d = Data().apply { X = Inner().apply { N = "qqq"; Y = "test" }} val element = JDOMIMPL.save("aaa", d) println(element.dump()) Assert.assertEquals(element.name, "aaa") Assert.assertEquals(element.getChild("parameters")?.getChild("qqq")?.textTrim, "test") } @Test fun test_write_any_element_empty() { class Inner { var N by JXML / XName var Y by JXML / XText } class Data { var X by JXML / "parameters" / XAnyElement / XSub(Inner::class.java) } val d = Data().apply { } val element = JDOMIMPL.save("aaa", d) println(element.dump()) Assert.assertEquals(element.name, "aaa") Assert.assertEquals(element.getChild("parameters"), null) } @Test fun test_write_any_elements() { class Inner { var N by JXML / XName var Y by JXML / XText } class Data { var X by JXML / "parameters" / XAnyElements / XSub(Inner::class.java) } val d = Data().apply { X = listOf( Inner().apply { N = "qqq"; Y = "test" }, Inner().apply { N = "eee"; Y = "zzz" }) } val element = JDOMIMPL.save("aaa", d) println(element.dump()) Assert.assertEquals(element.name, "aaa") Assert.assertEquals(element.getChild("parameters")?.getChild("qqq")?.textTrim, "test") Assert.assertEquals(element.getChild("parameters")?.getChild("eee")?.textTrim, "zzz") } @Test fun test_write_ReadOnly() { class Inner { var N by JXML / XName var Y by JXML / XText } class Data { var X by JXML / "parameters" / XAnyElements / XSub(Inner::class.java) - XReadOnly } val d = Data().apply { X = listOf( Inner().apply { N = "qqq"; Y = "test" }, Inner().apply { N = "eee"; Y = "zzz" }) } val element = JDOMIMPL.save("aaa", d) println(element.dump()) Assert.assertEquals(element.name, "aaa") Assert.assertTrue(element.children?.isEmpty() ?: false) } @Test fun test_write_any_elements_empty() { class Inner { var N by JXML / XName var Y by JXML / XText } class Data { var X by JXML / "parameters" / XAnyElements / XSub(Inner::class.java) } val d = Data().apply { } val element = JDOMIMPL.save("aaa", d) println(element.dump()) Assert.assertEquals(element.name, "aaa") Assert.assertEquals(element.getChild("parameters"), null) } @Test fun test_write_onBeforeSave() { class Data { var X : String? by JXML / XText - XCallback<String>(onBeforeSave = { X -> (X ?: "") + "_OnBeforeSaved"}) } val d = Data().apply { X = "s" } val element = JDOMIMPL.save("aaa", d) println(element.dump()) Assert.assertEquals(element.name, "aaa") Assert.assertEquals(element.text, "s_OnBeforeSaved") } @Test fun test_load_save_1() { class Data { var X : String? by JXML / XCDATA var A : String? by JXML / XAttribute("a") var B : String? by JXML / "b" / XAttribute("a") } val d = Data().apply { X = "xxx"; A = "qqq"; B = "zzz"} saveLoadTest(d) { listOf(X, A, B) } } @Test fun test_load_save_2() { class Data { var X : String? by JXML / XCDATA var A : String? by JXML / XAttribute("a") var B : String? by JXML / "b" / XAttribute("a") } val d = Data().apply { X = "xxx"; A = null; B = "zzz"} saveLoadTest(d) { listOf(X, A, B) } } @Test fun test_load_save_3_sub() { class Inner { var X : String? by JXML / XCDATA var A : String? by JXML / XAttribute("a") var B : String? by JXML / "b" / XAttribute("a") } class Data { var i1 by JXML / "a1" / XSub(Inner::class.java) var i2 by JXML / "a2" / XSub(Inner::class.java) var i3 by JXML / "a3" / XSub(Inner::class.java) } val d = Data().apply { i1 = Inner().apply{X = "xxx"; A = null; B = "zzz"}; i3 = Inner().apply{X = "333"; A = null; B = "z333zz"}; } saveLoadTest(d) { listOf(i1?.X, i1?.A, i1?.B, i2?.X, i2?.A, i2?.B, i3?.X, i3?.A, i3?.B) } } @Test fun test_load_save_4_list() { class Inner { var name by JXML / XAttribute("name") var value by JXML / XAttribute("value") } class Data { var p by JXML / XElements("param") / XSub(Inner::class.java) } val d = Data().apply { p = listOf( Inner().apply { name = "a"; value = "b" }, Inner().apply { name = "c"; value = "d" }, Inner().apply { name = "e"; value = "F" } ) } saveLoadTest(d) { listOf("mock") + (p?.flatMap { listOf(it.name, it.value) } ?: listOf()) } } @Test fun test_load_save_5_unknown() { class Data { var value by JXML / XAnyElement / XUnknown } val d = Data().apply { value = jdom("test") { element("qq"); attribute("a", "b")} } saveLoadTest(d) { listOf(value.dump()) } } @Test fun test_load_save_6_unknown() { class Data { var value by JXML / XAnyElements / XUnknown } val d = Data().apply { value = listOf( jdom("test") { element("qq"); attribute("a", "b")}, jdom("test2") { element("qq"); attribute("a", "b")}, jdom("te") { element("qsq"); attribute("a", "b")} ) } saveLoadTest(d) { listOf("32") + (value?.map{it.dump()} ?: listOf()) } } @Test fun test_load_save_7_multiline_cdata() { class Data { var value by JXML / XCDATA } val d = Data().apply { value = "this\nis\r\na\nmultiline" } saveLoadTest(d) { listOf("32") + listOf(value) } } @Test fun test_load_save_8_multiline_text() { class Data { var value by JXML / XText } val d = Data().apply { value = "this\nis\r\na\nmultiline" } saveLoadTest(d) { listOf("32") + listOf(value) } } private fun <Y : Any> saveLoadTest(d : Y, hash : Y.() -> List<Any?>) { val element = JDOMIMPL.save("aaa", d) val n = JDOM.load(element, d.javaClass) val l1 = d.hash() val l2 = n.hash() println(element.dump()) Assert.assertEquals(l1, l2) } private fun Element?.dump() : String { if (this == null) return "<null>" return XMLOutputter().apply { format = Format.getPrettyFormat() }.outputString(this)!! } }
apache-2.0
57523e2045f6642c2ed42817e2e6ef1d
26.193122
135
0.56949
3.174336
false
true
false
false
qikh/kong-lang
src/main/kotlin/repl/Repl.kt
1
1064
package repl import environment.Environment import evaluator.Eval import jline.console.ConsoleReader import lexer.Lexer import parser.Parser import java.io.PrintWriter import java.io.Writer class Repl { val PROMPT = ">> " fun Start() { val env = Environment() val reader = ConsoleReader() reader.bellEnabled = false reader.prompt = PROMPT val writer = PrintWriter(reader.output) while (true) { val line = reader.readLine() if (line == "quit") { writer.println() break } val lexer = Lexer(line) val p = Parser(lexer) val program = p.parseProgram() if (p.errors.size > 0) { printParseErrors(writer, p.errors) } val evaluated = Eval(program, env) writer.println(evaluated.inspect()) } } private fun printParseErrors(out: Writer, errors: List<String>) { errors.forEach { out.write("\t" + it + "\n") } } }
apache-2.0
395d33603380b59f02d7cd417195104f
21.638298
69
0.552632
4.290323
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/account/MyAccounts.kt
1
22207
package org.andstatus.app.account import android.accounts.Account import org.andstatus.app.backup.MyBackupAgent import org.andstatus.app.backup.MyBackupDataInput import org.andstatus.app.backup.MyBackupDataOutput import org.andstatus.app.backup.MyBackupDescriptor import org.andstatus.app.context.MyContext import org.andstatus.app.context.MyContextHolder import org.andstatus.app.context.MyPreferences import org.andstatus.app.data.SqlIds import org.andstatus.app.data.converter.AccountConverter import org.andstatus.app.net.social.Actor import org.andstatus.app.origin.Origin import org.andstatus.app.util.I18n import org.andstatus.app.util.IsEmpty import org.andstatus.app.util.MyLog import org.andstatus.app.util.StopWatch import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.io.FileNotFoundException import java.io.IOException import java.nio.charset.StandardCharsets import java.util.* import java.util.concurrent.ConcurrentSkipListSet import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.atomic.AtomicLong import java.util.function.Consumer import java.util.stream.Collectors import java.util.stream.Stream class MyAccounts private constructor(private val myContext: MyContext) : IsEmpty { /** Current account is the first in this list */ val recentAccounts: MutableList<MyAccount> = CopyOnWriteArrayList() private val myAccounts: SortedSet<MyAccount> = ConcurrentSkipListSet() private var distinctOriginsCount = 0 fun get(): MutableSet<MyAccount> { return myAccounts } override val isEmpty: Boolean get() = myAccounts.isEmpty() fun size(): Int { return myAccounts.size } fun initialize(): MyAccounts { val stopWatch: StopWatch = StopWatch.createStarted() myAccounts.clear() recentAccounts.clear() for (account in AccountUtils.getCurrentAccounts(myContext.context)) { val ma: MyAccount = MyAccountBuilder.loadFromAndroidAccount(myContext, account).myAccount if (ma.isValid) { myAccounts.add(ma) } else { MyLog.w(this, "The account is invalid: $ma") } } calculateDistinctOriginsCount() recentAccounts.addAll(myAccounts.stream().limit(3).collect(Collectors.toList())) MyLog.i(this, "accountsInitializedMs:" + stopWatch.time + "; " + myAccounts.size + " accounts in " + distinctOriginsCount + " origins") return this } fun getDefaultAccount(): MyAccount { return if (myAccounts.isEmpty()) MyAccount.EMPTY else myAccounts.iterator().next() } fun getDistinctOriginsCount(): Int { return distinctOriginsCount } private fun calculateDistinctOriginsCount() { val origins: MutableSet<Origin?> = HashSet() for (ma in myAccounts) { origins.add(ma.origin) } distinctOriginsCount = origins.size } /** * @return Was the MyAccount (and Account) deleted? */ fun delete(ma: MyAccount): Boolean { val myAccountToDelete = myAccounts.stream().filter { myAccount: MyAccount -> myAccount == ma } .findFirst().orElse(MyAccount.EMPTY) if (myAccountToDelete.nonValid) return false MyAccountBuilder.fromMyAccount(myAccountToDelete).deleteData() myAccounts.remove(myAccountToDelete) MyPreferences.onPreferencesChanged() return true } /** * Find persistent MyAccount by accountName in local cache AND * in Android AccountManager * * @return Invalid account if was not found */ fun fromAccountName(accountNameString: String?): MyAccount { return fromAccountName(AccountName.fromAccountName(myContext, accountNameString)) } /** * Find persistent MyAccount by accountName in local cache AND * in Android AccountManager * * @return Invalid account if was not found */ fun fromAccountName(accountName: AccountName?): MyAccount { if (accountName == null || !accountName.isValid) return MyAccount.EMPTY for (persistentAccount in myAccounts) { if (persistentAccount.getAccountName() == accountName.name) { return persistentAccount } } for (androidAccount in AccountUtils.getCurrentAccounts(myContext.context)) { if (accountName.toString() == androidAccount.name) { val myAccount: MyAccount = MyAccountBuilder.loadFromAndroidAccount(myContext, androidAccount).myAccount if (myAccount.isValid) { myAccounts.add(myAccount) } MyPreferences.onPreferencesChanged() return myAccount } } return MyAccount.EMPTY } /** * Get MyAccount by the ActorId. The MyAccount found may be from another origin * Please note that a valid Actor may not have an Account (in AndStatus) * @return EMPTY account if was not found */ fun fromActorId(actorId: Long): MyAccount { return if (actorId == 0L) MyAccount.EMPTY else fromActor(Actor.load(myContext, actorId), false, false) } fun fromActorOfSameOrigin(actor: Actor): MyAccount { return fromActor(actor, true, false) } /** Doesn't take origin into account */ fun fromActorOfAnyOrigin(actor: Actor): MyAccount { return fromActor(actor, false, false) } private fun fromActor(other: Actor, sameOriginOnly: Boolean, succeededOnly: Boolean): MyAccount { return myAccounts.stream().filter { ma: MyAccount -> ma.isValidAndSucceeded() || !succeededOnly } .filter { ma: MyAccount -> ma.actor.isSame(other, sameOriginOnly) } .findFirst().orElseGet { fromMyActors(other, sameOriginOnly) } } private fun fromMyActors(other: Actor, sameOriginOnly: Boolean): MyAccount { return myAccounts.stream().filter { ma: MyAccount -> ((!sameOriginOnly || ma.origin == other.origin) && myContext.users.myActors.values.stream() .filter { actor: Actor -> actor.user.userId == ma.actor.user.userId } .anyMatch { actor: Actor -> actor.isSame(other, sameOriginOnly) }) } .findFirst().orElse(MyAccount.EMPTY) } /** My account, which can be used to sync the "other" actor's data and to interact with that actor */ fun toSyncThatActor(other: Actor): MyAccount { return if (other.isEmpty) MyAccount.EMPTY else Stream.of(fromActor(other, true, true)) .filter { obj: MyAccount -> obj.isValid }.findFirst() .orElseGet { forRelatedActor(other, true, true) .orElseGet({ if (other.origin.isEmpty) MyAccount.EMPTY else getFirstPreferablySucceededForOrigin(other.origin) }) } } private fun forRelatedActor(relatedActor: Actor, sameOriginOnly: Boolean, succeededOnly: Boolean): Optional<MyAccount> { val forFriend = forFriendOfFollower(relatedActor, sameOriginOnly, succeededOnly, myContext.users.friendsOfMyActors) return if (forFriend.isPresent()) forFriend else forFriendOfFollower(relatedActor, sameOriginOnly, succeededOnly, myContext.users.followersOfMyActors) } private fun forFriendOfFollower(friend: Actor, sameOriginOnly: Boolean, succeededOnly: Boolean, friendsOrFollowers: MutableMap<Long, MutableSet<Long>>): Optional<MyAccount> { return friendsOrFollowers.getOrDefault(friend.actorId, emptySet<Long>()).stream() .map { actorId: Long -> fromActorId(actorId) } .filter { ma: MyAccount -> ma.isValidAndSucceeded() || !succeededOnly } .filter { ma: MyAccount -> !sameOriginOnly || ma.origin == friend.origin } .sorted() .findFirst() } /** Doesn't take origin into account */ fun fromWebFingerId(webFingerId: String?): MyAccount { return if (webFingerId.isNullOrEmpty()) MyAccount.EMPTY else myAccounts.stream() .filter { myAccount: MyAccount -> myAccount.getWebFingerId() == webFingerId } .findFirst() .orElse(MyAccount.EMPTY) } /** * @return current MyAccount (MyAccount selected by the User) or EMPTY if no persistent accounts exist */ val currentAccount: MyAccount get() = recentAccounts.stream() .findFirst().orElse(myAccounts.stream().findFirst().orElse(MyAccount.EMPTY)) /** * @return 0 if no valid persistent accounts exist */ val currentAccountActorId: Long get() = currentAccount.actorId fun getFirstSucceeded(): MyAccount { return getFirstPreferablySucceededForOrigin( Origin.EMPTY) } /** * Return first verified and autoSynced MyAccount of the provided origin. * If not auto synced, at least verified and succeeded, * If there is no verified account, any account of this Origin is been returned. * Otherwise invalid account is returned; * @param origin May be EMPTY to search in any Origin * @return EMPTY account if not found */ fun getFirstPreferablySucceededForOrigin(origin: Origin): MyAccount { return getFirstSucceededForOriginsStrict(mutableListOf(origin)) } /** * Return first verified and autoSynced MyAccount of the provided origins. * If not auto synced, at least verified and succeeded, * If there is no verified account, any account of this Origin is been returned. * Otherwise invalid account is returned; * @param origins May contain Origin.EMPTY to search in any Origin * @return EMPTY account if not found */ private fun getFirstSucceededForOriginsStrict(origins: MutableCollection<Origin>): MyAccount { var ma: MyAccount = MyAccount.EMPTY var maSucceeded: MyAccount = MyAccount.EMPTY var maSynced: MyAccount = MyAccount.EMPTY for (myAccount in myAccounts) { for (origin in origins) { if (!origin.isValid || myAccount.origin == origin) { if (ma.nonValid) { ma = myAccount } if (myAccount.isValidAndSucceeded()) { if (!ma.isValidAndSucceeded()) { maSucceeded = myAccount } if (myAccount.isSyncedAutomatically) { maSynced = myAccount break } } } if (maSynced.isValid) return maSynced } } return if (maSynced.isValid) maSynced else if (maSucceeded.isValid) maSucceeded else ma } /** @return this account if there are no others */ fun firstOtherSucceededForSameOrigin(origin: Origin, thisAccount: MyAccount): MyAccount { return succeededForSameOrigin(origin).stream() .filter { ma: MyAccount -> ma != thisAccount } .sorted().findFirst().orElse(thisAccount) } /** * Return verified and autoSynced MyAccounts for the Origin * @param origin May be empty to search in any Origin * @return Empty Set if not found */ fun succeededForSameOrigin(origin: Origin): MutableSet<MyAccount> { return if (origin.isEmpty) myAccounts.stream() .filter { obj: MyAccount -> obj.isValidAndSucceeded() }.collect(Collectors.toSet()) else myAccounts.stream() .filter { ma: MyAccount -> origin == ma.origin } .filter { obj: MyAccount -> obj.isValidAndSucceeded() } .collect(Collectors.toSet()) } /** @return this account if there are no others */ fun firstOtherSucceededForSameUser(actor: Actor, thisAccount: MyAccount): MyAccount { return succeededForSameUser(actor).stream() .filter { ma: MyAccount -> ma != thisAccount } .sorted().findFirst().orElse(thisAccount) } /** * Return verified and autoSynced MyAccounts for Origin-s, where User of this Actor is known. * @param actor May be empty to search in any Origin * @return Empty Set if not found */ fun succeededForSameUser(actor: Actor): MutableSet<MyAccount> { val origins = actor.user.knownInOrigins(myContext) return if (origins.isEmpty()) myAccounts.stream() .filter { obj: MyAccount -> obj.isValidAndSucceeded() } .collect(Collectors.toSet()) else myAccounts.stream() .filter { ma: MyAccount -> origins.contains(ma.origin) } .filter { obj: MyAccount -> obj.isValidAndSucceeded() } .collect(Collectors.toSet()) } fun hasSyncedAutomatically(): Boolean { for (ma in myAccounts) { if (ma.shouldBeSyncedAutomatically()) return true } return false } /** @return 0 if no syncing is needed */ fun minSyncIntervalMillis(): Long { return myAccounts.stream() .filter { obj: MyAccount -> obj.shouldBeSyncedAutomatically() } .map { obj: MyAccount -> obj.getEffectiveSyncFrequencyMillis() } .min { obj: Long, anotherLong: Long -> obj.compareTo(anotherLong) }.orElse(0L) } /** Should not be called from UI thread * Find MyAccount, which may be linked to a note in this origin. * First try two supplied accounts, then try any other existing account */ fun getAccountForThisNote(origin: Origin, firstAccount: MyAccount, preferredAccount: MyAccount, succeededOnly: Boolean): MyAccount { val method = "getAccountForThisNote" var ma = firstAccount ?: MyAccount.EMPTY if (!accountFits(ma, origin, succeededOnly)) { ma = betterFit(ma, preferredAccount ?: MyAccount.EMPTY, origin, succeededOnly) } if (!accountFits(ma, origin, succeededOnly)) { ma = betterFit(ma, getFirstPreferablySucceededForOrigin(origin), origin, succeededOnly) } if (!accountFits(ma, origin, false)) { ma = MyAccount.EMPTY } if (MyLog.isVerboseEnabled()) { MyLog.v(this, method + "; origin=" + origin.name + "; account1=" + ma + (if (ma == preferredAccount) "" else "; account2=$preferredAccount") + if (succeededOnly) "; succeeded only" else "") } return ma } private fun accountFits(ma: MyAccount, origin: Origin, succeededOnly: Boolean): Boolean { return (if (succeededOnly) ma.isValidAndSucceeded() else ma.isValid) && (!origin.isValid || ma.origin == origin) } private fun betterFit(oldMa: MyAccount, newMa: MyAccount, origin: Origin, succeededOnly: Boolean): MyAccount { if (accountFits(oldMa, origin, succeededOnly) || !accountFits(newMa, origin, false)) { return oldMa } return if (oldMa.nonValid && newMa.isValid) { newMa } else oldMa } /** Set provided MyAccount as the Current one */ fun setCurrentAccount(ma: MyAccount) { val prevAccount = currentAccount if (ma.nonValid || ma == prevAccount) return MyLog.v(this) { ("Changing current account from '" + prevAccount.getAccountName() + "' to '" + ma.getAccountName() + "'") } recentAccounts.remove(ma) recentAccounts.add(0, ma) } fun onDefaultSyncFrequencyChanged() { val syncFrequencySeconds = MyPreferences.getSyncFrequencySeconds() for (ma in myAccounts) { if (ma.syncFrequencySeconds <= 0) AccountUtils.getExistingAndroidAccount(ma.getOAccountName() ).onSuccess { account: Account? -> AccountUtils.setSyncFrequencySeconds(account, syncFrequencySeconds) } } } fun accountsToSync(): MutableList<MyAccount> { val syncedAutomaticallyOnly = hasSyncedAutomatically() return myAccounts.stream().filter { myAccount: MyAccount -> accountToSyncFilter(myAccount, syncedAutomaticallyOnly) } .collect(Collectors.toList()) } private fun accountToSyncFilter(account: MyAccount, syncedAutomaticallyOnly: Boolean): Boolean { if (!account.isValidAndSucceeded()) { MyLog.v(this) { "Account '" + account.getAccountName() + "'" + " skipped as invalid authenticated account" } return false } if (syncedAutomaticallyOnly && !account.isSyncedAutomatically) { MyLog.v(this) { "Account '" + account.getAccountName() + "'" + " skipped as it is not synced automatically" } return false } return true } fun onBackup(data: MyBackupDataOutput, newDescriptor: MyBackupDescriptor): Long { try { val jsa = JSONArray() myAccounts.forEach(Consumer { ma: MyAccount -> jsa.put(ma.toJson()) }) val bytes = jsa.toString(2).toByteArray(StandardCharsets.UTF_8) data.writeEntityHeader(MyBackupAgent.KEY_ACCOUNT, bytes.size, ".json") data.writeEntityData(bytes, bytes.size) } catch (e: JSONException) { throw IOException(e) } newDescriptor.setAccountsCount(myAccounts.size.toLong()) return myAccounts.size.toLong() } /** Returns count of restores objects */ fun onRestore(data: MyBackupDataInput, newDescriptor: MyBackupDescriptor): Long { val restoredCount = AtomicLong() val method = "onRestore" MyLog.i(this, method + "; started, " + I18n.formatBytes(data.getDataSize().toLong())) val bytes = ByteArray(data.getDataSize()) val bytesRead = data.readEntityData(bytes, 0, bytes.size) try { val jsa = JSONArray(String(bytes, 0, bytesRead, StandardCharsets.UTF_8)) for (ind in 0 until jsa.length()) { val order = ind + 1 MyLog.v(this, method + "; restoring " + order + " of " + jsa.length()) AccountConverter.convertJson(data.getMyContext(), jsa[ind] as JSONObject, false) .onSuccess { jso: JSONObject -> val accountData: AccountData = AccountData.fromJson(myContext, jso, false) val builder: MyAccountBuilder = MyAccountBuilder.loadFromAccountData(accountData, "fromJson") val verified = builder.myAccount.credentialsVerified if (verified != CredentialsVerificationStatus.SUCCEEDED) { newDescriptor.getLogger().logProgress("Account " + builder.myAccount.getAccountName() + " was not successfully verified") builder.setCredentialsVerificationStatus(CredentialsVerificationStatus.SUCCEEDED) } builder.saveSilently().onSuccess { r: Boolean? -> MyLog.v(this, "$method; restored $order: $builder") restoredCount.incrementAndGet() if (verified != CredentialsVerificationStatus.SUCCEEDED) { builder.setCredentialsVerificationStatus(verified) builder.saveSilently() } }.onFailure { e: Throwable? -> MyLog.e(this, "$method; failed to restore $order: $builder") } } } if (restoredCount.get() != newDescriptor.getAccountsCount()) { throw FileNotFoundException("Restored only " + restoredCount + " accounts of " + newDescriptor.getAccountsCount()) } newDescriptor.getLogger().logProgress("Restored $restoredCount accounts") } catch (e: JSONException) { throw IOException(method, e) } return restoredCount.get() } override fun toString(): String { return "PersistentAccounts{$myAccounts}" } override fun hashCode(): Int { return myAccounts.hashCode() } override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other == null || other !is MyAccounts) { return false } return myAccounts == other.myAccounts } fun reorderAccounts(reorderedItems: MutableList<MyAccount>) { var count = 0 reorderedItems.mapIndexed { index, myAccount -> if (myAccount.order != index) { count++ val builder: MyAccountBuilder = MyAccountBuilder.fromMyAccount(myAccount) builder.setOrder(index) builder.save() } } MyLog.d(this, "Reordered $count accounts") } fun addIfAbsent(myAccount: MyAccount) { if (!myAccounts.contains(myAccount)) myAccounts.add(myAccount) myContext.users.updateCache(myAccount.actor) } companion object { fun newEmpty(myContext: MyContext): MyAccounts { return MyAccounts(myContext) } fun myAccountIds(): SqlIds { return SqlIds.fromIds( AccountUtils.getCurrentAccounts( MyContextHolder.myContextHolder.getNow().context).stream() .map({ account: Account -> AccountData.fromAndroidAccount( MyContextHolder.myContextHolder.getNow(), account) .getDataLong(MyAccount.KEY_ACTOR_ID, 0) }) .filter { id: Long -> id > 0 } .collect(Collectors.toList()) ) } } }
apache-2.0
2483e046c2490dd24a2595d17d0ac9ed
42.036822
158
0.61377
4.908709
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/ty/Ty.kt
2
9349
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.ty import com.intellij.psi.stubs.StubInputStream import com.intellij.psi.stubs.StubOutputStream import com.intellij.util.Processor import com.intellij.util.containers.ContainerUtil import com.tang.intellij.lua.Constants import com.tang.intellij.lua.project.LuaSettings import com.tang.intellij.lua.search.SearchContext enum class TyKind { Unknown, Primitive, Array, Function, Class, Union, Generic, Nil, Void, Tuple, GenericParam, StringLiteral } enum class TyPrimitiveKind { String, Number, Boolean, Table, Function } class TyFlags { companion object { const val ANONYMOUS = 0x1 const val GLOBAL = 0x2 const val SELF_FUNCTION = 0x4 // xxx.method() const val ANONYMOUS_TABLE = 0x8 // local xx = {}, flag of this table `{}` } } interface ITy : Comparable<ITy> { val kind: TyKind val displayName: String val flags: Int fun union(ty: ITy): ITy fun subTypeOf(other: ITy, context: SearchContext, strict: Boolean): Boolean fun getSuperClass(context: SearchContext): ITy? fun visitSuper(searchContext: SearchContext, processor: Processor<ITyClass>) fun substitute(substitutor: ITySubstitutor): ITy fun each(fn: (ITy) -> Unit) { TyUnion.each(this, fn) } fun eachTopClass(fn: Processor<ITyClass>) fun accept(visitor: ITyVisitor) fun acceptChildren(visitor: ITyVisitor) } fun ITy.hasFlag(flag: Int): Boolean = flags and flag == flag val ITy.isGlobal: Boolean get() = hasFlag(TyFlags.GLOBAL) val ITy.isAnonymous: Boolean get() = hasFlag(TyFlags.ANONYMOUS) private val ITy.worth: Float get() { var value = 10f when(this) { is ITyArray, is ITyGeneric -> value = 80f is ITyPrimitive -> value = 70f is ITyFunction -> value = 60f is ITyClass -> { value = when { this is TyTable -> 9f this.isAnonymous -> 2f this.isGlobal -> 5f else -> 90f } } } return value } abstract class Ty(override val kind: TyKind) : ITy { final override var flags: Int = 0 override val displayName: String get() = TyRenderer.SIMPLE.render(this) fun addFlag(flag: Int) { flags = flags or flag } override fun accept(visitor: ITyVisitor) { visitor.visitTy(this) } override fun acceptChildren(visitor: ITyVisitor) { } override fun union(ty: ITy): ITy { return TyUnion.union(this, ty) } override fun toString(): String { val list = mutableListOf<String>() TyUnion.each(this) { //尽量不使用Global if (!it.isAnonymous && !(it is ITyClass && it.isGlobal)) list.add(it.displayName) } if (list.isEmpty()) { //使用Global TyUnion.each(this) { if (!it.isAnonymous && (it is ITyClass && it.isGlobal)) list.add(it.displayName) } } return list.joinToString("|") } override fun subTypeOf(other: ITy, context: SearchContext, strict: Boolean): Boolean { // Everything is subset of any if (other.kind == TyKind.Unknown) return !strict // Handle unions, subtype if subtype of any of the union components. if (other is TyUnion) return other.getChildTypes().any { type -> subTypeOf(type, context, strict) } // Classes are equal return this == other } override fun getSuperClass(context: SearchContext): ITy? { return null } override fun visitSuper(searchContext: SearchContext, processor: Processor<ITyClass>) { val superType = getSuperClass(searchContext) as? ITyClass ?: return if (processor.process(superType)) superType.visitSuper(searchContext, processor) } override fun compareTo(other: ITy): Int { return other.worth.compareTo(worth) } override fun substitute(substitutor: ITySubstitutor): ITy { return substitutor.substitute(this) } override fun eachTopClass(fn: Processor<ITyClass>) { when (this) { is ITyClass -> fn.process(this) is TyUnion -> { ContainerUtil.process(getChildTypes()) { if (it is ITyClass && !fn.process(it)) return@process false true } } is TyTuple -> { list.firstOrNull()?.eachTopClass(fn) } } } companion object { val UNKNOWN = TyUnknown() val VOID = TyVoid() val BOOLEAN = TyPrimitive(TyPrimitiveKind.Boolean, "boolean") val STRING = TyPrimitiveClass(TyPrimitiveKind.String, "string") val NUMBER = TyPrimitive(TyPrimitiveKind.Number, "number") val TABLE = TyPrimitive(TyPrimitiveKind.Table, "table") val FUNCTION = TyPrimitive(TyPrimitiveKind.Function, "function") val NIL = TyNil() private val serializerMap = mapOf<TyKind, ITySerializer>( TyKind.Array to TyArraySerializer, TyKind.Class to TyClassSerializer, TyKind.Function to TyFunctionSerializer, TyKind.Generic to TyGenericSerializer, TyKind.GenericParam to TyGenericParamSerializer, TyKind.StringLiteral to TyStringLiteralSerializer, TyKind.Tuple to TyTupleSerializer, TyKind.Union to TyUnionSerializer ) private fun getPrimitive(mark: Byte): Ty { return when (mark.toInt()) { TyPrimitiveKind.Boolean.ordinal -> BOOLEAN TyPrimitiveKind.String.ordinal -> STRING TyPrimitiveKind.Number.ordinal -> NUMBER TyPrimitiveKind.Table.ordinal -> TABLE TyPrimitiveKind.Function.ordinal -> FUNCTION else -> UNKNOWN } } private fun getKind(ordinal: Int): TyKind { return TyKind.values().firstOrNull { ordinal == it.ordinal } ?: TyKind.Unknown } fun getBuiltin(name: String): ITy? { return when (name) { Constants.WORD_NIL -> NIL Constants.WORD_VOID -> VOID Constants.WORD_ANY -> UNKNOWN Constants.WORD_BOOLEAN -> BOOLEAN Constants.WORD_STRING -> STRING Constants.WORD_NUMBER -> NUMBER Constants.WORD_TABLE -> TABLE Constants.WORD_FUNCTION -> FUNCTION else -> null } } fun create(name: String): ITy { return getBuiltin(name) ?: TyLazyClass(name) } fun isInvalid(ty: ITy?): Boolean { return ty == null || ty is TyUnknown || ty is TyNil || ty is TyVoid } private fun getSerializer(kind: TyKind): ITySerializer? { return serializerMap[kind] } fun serialize(ty: ITy, stream: StubOutputStream) { stream.writeByte(ty.kind.ordinal) stream.writeInt(ty.flags) when(ty) { is ITyPrimitive -> stream.writeByte(ty.primitiveKind.ordinal) else -> { val serializer = getSerializer(ty.kind) serializer?.serialize(ty, stream) } } } fun deserialize(stream: StubInputStream): ITy { val kind = getKind(stream.readByte().toInt()) val flags = stream.readInt() return when (kind) { TyKind.Primitive -> getPrimitive(stream.readByte()) TyKind.Nil -> NIL TyKind.Void -> VOID else -> { val serializer = getSerializer(kind) serializer?.deserialize(flags, stream) ?: UNKNOWN } } } } } class TyUnknown : Ty(TyKind.Unknown) { override fun equals(other: Any?): Boolean { return other is TyUnknown } override fun hashCode(): Int { return Constants.WORD_ANY.hashCode() } override fun subTypeOf(other: ITy, context: SearchContext, strict: Boolean): Boolean { return !strict } } class TyNil : Ty(TyKind.Nil) { override fun subTypeOf(other: ITy, context: SearchContext, strict: Boolean): Boolean { return super.subTypeOf(other, context, strict) || other is TyNil || !LuaSettings.instance.isNilStrict } } class TyVoid : Ty(TyKind.Void) { override fun subTypeOf(other: ITy, context: SearchContext, strict: Boolean): Boolean { return false } }
apache-2.0
60b5ca570cfde9f81b00e14ca5f5ee29
28.923077
109
0.595179
4.496628
false
false
false
false
handstandsam/ShoppingApp
app/src/main/java/com/handstandsam/shoppingapp/features/login/LoginActivity.kt
1
4293
package com.handstandsam.shoppingapp.features.login import android.content.Context import android.content.Intent import android.os.Bundle import android.view.KeyEvent import android.view.View import android.widget.Toast import androidx.annotation.StringRes import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.AppCompatCheckBox import androidx.appcompat.widget.AppCompatEditText import androidx.lifecycle.lifecycleScope import com.handstandsam.shoppingapp.R import com.handstandsam.shoppingapp.di.AppGraph import com.handstandsam.shoppingapp.features.category.CategoryActivity import com.handstandsam.shoppingapp.features.home.HomeActivity import com.handstandsam.shoppingapp.graph import com.handstandsam.shoppingapp.preferences.UserPreferences import com.handstandsam.shoppingapp.repository.SessionManager import com.handstandsam.shoppingapp.repository.UserRepo class LoginActivity : AppCompatActivity() { private val graph: AppGraph get() = application.graph() private val sessionManager: SessionManager get() = graph.sessionGraph.sessionManager private val userPreferences: UserPreferences get() = graph.sessionGraph.userPreferences private val userRepo: UserRepo get() = graph.networkGraph.userRepo lateinit var rememberMeCheckbox: AppCompatCheckBox lateinit var usernameEditText: AppCompatEditText lateinit var passwordEditText: AppCompatEditText private lateinit var loginView: MyLoginView private lateinit var presenter: LoginPresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) supportActionBar!!.title = "Log in to Shopping App" passwordEditText = findViewById(R.id.password) usernameEditText = findViewById(R.id.username) rememberMeCheckbox = findViewById(R.id.remember_me) findViewById<View>(R.id.submit).setOnClickListener { presenter.loginClicked() } loginView = MyLoginView() presenter = LoginPresenter( view = loginView, sessionManager = sessionManager, userPreferences = userPreferences, userRepo = userRepo, scope = lifecycleScope ) usernameEditText.setOnKeyListener(View.OnKeyListener { v, keyCode, event -> // If the event is a key-down event on the "enter" button if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) { presenter.loginClicked() return@OnKeyListener true } false }) } interface LoginView { fun startHomeActivity() var username: String val isRememberMeChecked: Boolean fun setRememberMe(rememberMe: Boolean) fun kickToHomeScreen() val password: String fun showToast(@StringRes stringResourceId: Int) } inner class MyLoginView : LoginView { override fun startHomeActivity() { val intent = Intent(this@LoginActivity, HomeActivity::class.java) [email protected](intent) } override var username: String get() = usernameEditText.text.toString() set(username) = usernameEditText.setText(username) override val isRememberMeChecked: Boolean get() = rememberMeCheckbox.isChecked override fun setRememberMe(value: Boolean) { rememberMeCheckbox.isChecked = value } override fun kickToHomeScreen() { [email protected](Intent(this@LoginActivity, HomeActivity::class.java)) finish() } override val password: String get() = passwordEditText.text.toString() override fun showToast(@StringRes stringResourceId: Int) { Toast.makeText(applicationContext, stringResourceId, Toast.LENGTH_SHORT).show() } } override fun onResume() { super.onResume() presenter.onResume() } companion object { fun launch(context: Context){ val intent = Intent(context, LoginActivity::class.java) context.startActivity(intent) } } }
apache-2.0
8c389a1f916af7b178bae9b4b444ce7f
30.8
98
0.694386
5.36625
false
false
false
false
Etik-Tak/backend
src/main/kotlin/dk/etiktak/backend/service/product/ProductTagService.kt
1
2982
// Copyright (c) 2017, Daniel Andersen ([email protected]) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. 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. // 3. The name of the author may not 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 dk.etiktak.backend.service.product import dk.etiktak.backend.model.product.ProductTag import dk.etiktak.backend.model.user.Client import dk.etiktak.backend.repository.product.ProductTagRepository import dk.etiktak.backend.service.security.ClientVerified import dk.etiktak.backend.util.CryptoUtil import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service @Transactional open class ProductTagService @Autowired constructor( private val productTagRepository: ProductTagRepository) { private val logger = LoggerFactory.getLogger(ProductLabelService::class.java) /** * Finds a product tag from the given UUID. * * @param uuid UUID * @return Product tag with given UUID */ open fun getProductTagByUuid(uuid: String): ProductTag? { return productTagRepository.findByUuid(uuid) } /** * Creates a product tag. * * @param name Name * @return Product tag */ @ClientVerified open fun createProductTag(client: Client, name: String): ProductTag { val productTag = ProductTag() productTag.uuid = CryptoUtil().uuid() productTag.name = name val modifiedProductTag = productTagRepository.save(productTag) return modifiedProductTag } }
bsd-3-clause
7e7f191ad09834022147aac339cf9967
41.014085
83
0.75218
4.718354
false
false
false
false
jiaminglu/kotlin-native
Interop/Indexer/src/main/kotlin/org/jetbrains/kotlin/native/interop/indexer/NativeIndex.kt
1
8326
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.native.interop.indexer enum class Language(val sourceFileExtension: String) { C("c"), OBJECTIVE_C("m") } interface HeaderInclusionPolicy { /** * Whether unused declarations from given header should be excluded. * * @param headerName header path relative to the appropriate include path element (e.g. `time.h` or `curl/curl.h`), * or `null` for builtin declarations. */ fun excludeUnused(headerName: String?): Boolean /** * Whether all declarations from this header should be excluded. * * Note: the declarations from such headers can be actually present in the internal representation, * but not included into the root collections. */ fun excludeAll(headerId: HeaderId): Boolean // TODO: these methods should probably be combined into the only one, but it would require some refactoring. } data class NativeLibrary(val includes: List<String>, val additionalPreambleLines: List<String>, val compilerArgs: List<String>, val language: Language, val excludeSystemLibs: Boolean, // TODO: drop? val excludeDepdendentModules: Boolean, val headerInclusionPolicy: HeaderInclusionPolicy) /** * Retrieves the definitions from given C header file using given compiler arguments (e.g. defines). */ fun buildNativeIndex(library: NativeLibrary): NativeIndex = buildNativeIndexImpl(library) /** * This class describes the IR of definitions from C header file(s). */ abstract class NativeIndex { abstract val structs: Collection<StructDecl> abstract val enums: Collection<EnumDef> abstract val objCClasses: Collection<ObjCClass> abstract val objCProtocols: Collection<ObjCProtocol> abstract val objCCategories: Collection<ObjCCategory> abstract val typedefs: Collection<TypedefDef> abstract val functions: Collection<FunctionDecl> abstract val macroConstants: Collection<ConstantDef> abstract val includedHeaders: Collection<HeaderId> } /** * The (contents-based) header id. * Its [value] remains valid across different runs of the indexer and the process, * and thus can be used to 'serialize' the id. */ data class HeaderId(val value: String) data class Location(val headerId: HeaderId) interface TypeDeclaration { val location: Location } /** * C struct field. */ class Field(val name: String, val type: Type, val offset: Long, val typeAlign: Long) val Field.isAligned: Boolean get() = offset % (typeAlign * 8) == 0L class BitField(val name: String, val type: Type, val offset: Long, val size: Int) /** * C struct declaration. */ abstract class StructDecl(val spelling: String) : TypeDeclaration { abstract val def: StructDef? } /** * C struct definition. * * @param hasNaturalLayout must be `false` if the struct has unnatural layout, e.g. it is `packed`. * May be `false` even if the struct has natural layout. */ abstract class StructDef(val size: Long, val align: Int, val decl: StructDecl, val hasNaturalLayout: Boolean) { abstract val fields: List<Field> // TODO: merge two lists to preserve declaration order. abstract val bitFields: List<BitField> } /** * C enum value. */ class EnumConstant(val name: String, val value: Long, val isExplicitlyDefined: Boolean) /** * C enum definition. */ abstract class EnumDef(val spelling: String, val baseType: Type) : TypeDeclaration { abstract val constants: List<EnumConstant> } sealed class ObjCContainer { abstract val protocols: List<ObjCProtocol> abstract val methods: List<ObjCMethod> abstract val properties: List<ObjCProperty> } sealed class ObjCClassOrProtocol(val name: String) : ObjCContainer(), TypeDeclaration data class ObjCMethod( val selector: String, val encoding: String, val parameters: List<Parameter>, private val returnType: Type, val isClass: Boolean, val nsConsumesSelf: Boolean, val nsReturnsRetained: Boolean, val isOptional: Boolean, val isInit: Boolean ) { fun returnsInstancetype(): Boolean = returnType is ObjCInstanceType fun getReturnType(container: ObjCClassOrProtocol): Type = if (returnType is ObjCInstanceType) { when (container) { is ObjCClass -> ObjCObjectPointer(container, returnType.nullability, protocols = emptyList()) is ObjCProtocol -> ObjCIdType(returnType.nullability, protocols = listOf(container)) } } else { returnType } } data class ObjCProperty(val name: String, val getter: ObjCMethod, val setter: ObjCMethod?) { fun getType(container: ObjCClassOrProtocol): Type = getter.getReturnType(container) } abstract class ObjCClass(name: String) : ObjCClassOrProtocol(name) { abstract val baseClass: ObjCClass? } abstract class ObjCProtocol(name: String) : ObjCClassOrProtocol(name) abstract class ObjCCategory(val name: String, val clazz: ObjCClass) : ObjCContainer() /** * C function parameter. */ data class Parameter(val name: String?, val type: Type, val nsConsumed: Boolean) /** * C function declaration. */ class FunctionDecl(val name: String, val parameters: List<Parameter>, val returnType: Type, val binaryName: String, val isDefined: Boolean, val isVararg: Boolean) /** * C typedef definition. * * ``` * typedef $aliased $name; * ``` */ class TypedefDef(val aliased: Type, val name: String, override val location: Location) : TypeDeclaration abstract class ConstantDef(val name: String, val type: Type) class IntegerConstantDef(name: String, type: Type, val value: Long) : ConstantDef(name, type) class FloatingConstantDef(name: String, type: Type, val value: Double) : ConstantDef(name, type) /** * C type. */ interface Type interface PrimitiveType : Type object CharType : PrimitiveType object BoolType : PrimitiveType data class IntegerType(val size: Int, val isSigned: Boolean, val spelling: String) : PrimitiveType // TODO: floating type is not actually defined entirely by its size. data class FloatingType(val size: Int, val spelling: String) : PrimitiveType object VoidType : Type data class RecordType(val decl: StructDecl) : Type data class EnumType(val def: EnumDef) : Type data class PointerType(val pointeeType: Type, val pointeeIsConst: Boolean = false) : Type // TODO: refactor type representation and support type modifiers more generally. data class FunctionType(val parameterTypes: List<Type>, val returnType: Type) : Type interface ArrayType : Type { val elemType: Type } data class ConstArrayType(override val elemType: Type, val length: Long) : ArrayType data class IncompleteArrayType(override val elemType: Type) : ArrayType data class Typedef(val def: TypedefDef) : Type sealed class ObjCPointer : Type { enum class Nullability { Nullable, NonNull, Unspecified } abstract val nullability: Nullability } sealed class ObjCQualifiedPointer : ObjCPointer() { abstract val protocols: List<ObjCProtocol> } data class ObjCObjectPointer( val def: ObjCClass, override val nullability: Nullability, override val protocols: List<ObjCProtocol> ) : ObjCQualifiedPointer() data class ObjCClassPointer( override val nullability: Nullability, override val protocols: List<ObjCProtocol> ) : ObjCQualifiedPointer() data class ObjCIdType( override val nullability: Nullability, override val protocols: List<ObjCProtocol> ) : ObjCQualifiedPointer() data class ObjCInstanceType(override val nullability: Nullability) : ObjCPointer() object UnsupportedType : Type
apache-2.0
fa71d7b89de055b2f95b6aa216633ab6
31.150579
119
0.717271
4.493254
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/util/TextViewUtil.kt
2
849
package org.stepic.droid.util import android.text.SpannableString import android.text.TextPaint import android.text.style.URLSpan import android.widget.TextView fun stripUnderlinesFromLinks(tv: TextView) { val spannable = SpannableString(tv.text) val spans = spannable.getSpans(0, spannable.length, URLSpan::class.java) spans.forEach { val start = spannable.getSpanStart(it) val end = spannable.getSpanEnd(it) val flags = spannable.getSpanFlags(it) spannable.removeSpan(it) spannable.setSpan(URLSpanWithoutUnderline(it.url), start, end, flags) } tv.text = spannable } private class URLSpanWithoutUnderline(url: String) : URLSpan(url) { override fun updateDrawState(textPaint: TextPaint) { super.updateDrawState(textPaint) textPaint.isUnderlineText = false } }
apache-2.0
4a07dc539b7a6040497e732037640847
29.321429
77
0.725559
4.223881
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/ShikimoriInterceptor.kt
1
1394
package eu.kanade.tachiyomi.data.track.shikimori import com.google.gson.Gson import okhttp3.Interceptor import okhttp3.Response class ShikimoriInterceptor(val shikimori: Shikimori, val gson: Gson) : Interceptor { /** * OAuth object used for authenticated requests. */ private var oauth: OAuth? = shikimori.restoreToken() override fun intercept(chain: Interceptor.Chain): Response { val originalRequest = chain.request() val currAuth = oauth ?: throw Exception("Not authenticated with Shikimori") val refreshToken = currAuth.refresh_token!! // Refresh access token if expired. if (currAuth.isExpired()) { val response = chain.proceed(ShikimoriApi.refreshTokenRequest(refreshToken)) if (response.isSuccessful) { newAuth(gson.fromJson(response.body()!!.string(), OAuth::class.java)) } else { response.close() } } // Add the authorization header to the original request. val authRequest = originalRequest.newBuilder() .addHeader("Authorization", "Bearer ${oauth!!.access_token}") .header("User-Agent", "Tachiyomi") .build() return chain.proceed(authRequest) } fun newAuth(oauth: OAuth?) { this.oauth = oauth shikimori.saveToken(oauth) } }
apache-2.0
fd2c5fd6b6a97863ba4e9de667f5f614
31.418605
88
0.628407
4.773973
false
false
false
false
Heiner1/AndroidAPS
danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketOptionGetPumpTimeTest.kt
1
1315
package info.nightscout.androidaps.danars.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danars.DanaRSTestBase import org.joda.time.DateTime import org.junit.Assert import org.junit.Test class DanaRsPacketOptionGetPumpTimeTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } if (it is DanaRSPacketOptionGetPumpTime) { it.danaPump = danaPump } } } @Test fun runTest() { val packet = DanaRSPacketOptionGetPumpTime(packetInjector) val array = createArray(8, 0.toByte()) // 6 + 2 putByteToArray(array, 0, 19) // year 2019 putByteToArray(array, 1, 2) // month february putByteToArray(array, 2, 4) // day 4 putByteToArray(array, 3, 20) // hour 20 putByteToArray(array, 4, 11) // min 11 putByteToArray(array, 5, 35) // second 35 packet.handleMessage(array) Assert.assertEquals(DateTime(2019, 2, 4, 20, 11, 35).millis, danaPump.getPumpTime()) Assert.assertEquals("OPTION__GET_PUMP_TIME", packet.friendlyName) } }
agpl-3.0
74e7649af48ea19fc9e82ba02a99f162
33.631579
92
0.64943
4.472789
false
true
false
false
maurocchi/chesslave
backend/src/test/java/io/chesslave/visual/model/SquareImageTest.kt
2
2303
package io.chesslave.visual.model import io.chesslave.model.Board import io.chesslave.visual.Images import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import java.awt.image.BufferedImage // TODO: these tests are too much logic, simplify! @RunWith(Parameterized::class) class SquareImageTest(val board: BufferedImage, val flipped: Boolean) { companion object { @Parameterized.Parameters @JvmStatic fun data(): Collection<Array<Any>> = listOf( arrayOf(Images.read("/images/visual/board.png"), false), arrayOf(Images.read("/images/visual/flipped-board.png"), true)) } val square = Board.g1 val squareImage = SquareImage(board, square, flipped) @Test fun imageTest() { val knight = Images.read("/images/visual/knight-dark-square.png") assertTrue(Images.areEquals(knight, squareImage.image)) } @Test fun sizeTest() { assertEquals((board.width / Board.SIZE).toLong(), squareImage.size.toLong()) } @Test fun leftTest() { assertEquals((squareImage.size * horizontalOffset(square.col)).toLong(), squareImage.left().toLong()) } @Test fun rightTest() { assertEquals((squareImage.size * (horizontalOffset(square.col) + 1)).toLong(), squareImage.right().toLong()) } @Test fun topTest() { assertEquals((squareImage.size * verticalOffset(square.row)).toLong(), squareImage.top().toLong()) } @Test fun bottomTest() { assertEquals((squareImage.size * (verticalOffset(square.row) + 1)).toLong(), squareImage.bottom().toLong()) } @Test fun middleXTest() { assertEquals((squareImage.size / 2 + squareImage.size * horizontalOffset(square.col)).toLong(), squareImage.middleX().toLong()) } @Test fun middleYTest() { assertEquals((squareImage.size / 2 + squareImage.size * verticalOffset(square.row)).toLong(), squareImage.middleY().toLong()) } private fun horizontalOffset(col: Int): Int = if (flipped) Board.SIZE - 1 - col else col private fun verticalOffset(row: Int): Int = if (flipped) row else Board.SIZE - 1 - row }
gpl-2.0
a75440cc2dd5c4bacd74222980c36d73
30.121622
135
0.661746
4.076106
false
true
false
false
sirixdb/sirix
bundles/sirix-kotlin-cli/src/main/kotlin/org/sirix/cli/commands/DumpResourceHistory.kt
1
1597
package org.sirix.cli.commands import org.sirix.access.User import org.sirix.cli.CliOptions import org.sirix.service.json.serialize.StringValue class DumpResourceHistory(options: CliOptions, private val resourceName: String, private val user: User?): CliCommand(options) { override fun execute() { val database = openDatabase(user) database.use { val buffer = StringBuilder() val manager = database.beginResourceSession(resourceName) manager.use { val historyList = manager.history buffer.append("{\"history\":[") historyList.forEachIndexed { index, revisionTuple -> buffer.append("{\"revision\":") buffer.append(revisionTuple.revision) buffer.append(",") buffer.append("\"revisionTimestamp\":\"") buffer.append(revisionTuple.revisionTimestamp) buffer.append("\",") buffer.append("\"author\":\"") buffer.append(StringValue.escape(revisionTuple.user.name)) buffer.append("\",") buffer.append("\"commitMessage\":\"") buffer.append(StringValue.escape(revisionTuple.commitMessage.orElse(""))) buffer.append("\"}") if (index != historyList.size - 1) buffer.append(",") } buffer.append("]}") } cliPrinter.prnLn(buffer.toString()) } } }
bsd-3-clause
b46e5b5099352cf9dd40758ae38e2d68
33
128
0.536005
5.487973
false
false
false
false
PolymerLabs/arcs
java/arcs/core/host/HandleManager.kt
1
1273
package arcs.core.host import arcs.core.data.Capability import arcs.core.data.Schema import arcs.core.entity.Handle import arcs.core.entity.HandleSpec import arcs.core.storage.StorageKey import arcs.core.storage.StorageProxy import arcs.core.util.Scheduler /** * This interface defines the functionality of a component that manages all of the active * handles for one particular scope. * * In most cases, "scope" means an Arc. It is possible to use a [HandleManager] to manage groups * of [Handle]s for other groupings. This is currently not a supported use case for Arcs clients, * but we may use this internally for storage stack testing. */ interface HandleManager { /** Create a new handle owned by this handle manager. */ suspend fun createHandle( spec: HandleSpec, storageKey: StorageKey, ttl: Capability.Ttl = Capability.Ttl.Infinite(), particleId: String = "", immediateSync: Boolean = true, storeSchema: Schema? = null, actor: String? = null, writeOnly: Boolean = false ): Handle /** Return the scheduler used by this [HandleManeger] */ fun scheduler(): Scheduler /** Close all handles created by this handle manager. */ suspend fun close() suspend fun allStorageProxies(): List<StorageProxy<*, *, *>> }
bsd-3-clause
5b2908e698d2bbb672a6785318ac10c7
31.641026
97
0.731343
4.133117
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/ui/mysite/cards/dashboard/bloggingprompts/BloggingPromptCardSourceTest.kt
1
18243
package org.wordpress.android.ui.mysite.cards.dashboard.bloggingprompts import kotlinx.coroutines.InternalCoroutinesApi import kotlinx.coroutines.flow.flowOf import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.kotlin.any import org.mockito.kotlin.eq import org.mockito.kotlin.never import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.wordpress.android.BaseUnitTest import org.wordpress.android.TEST_DISPATCHER import org.wordpress.android.fluxc.model.BloggingRemindersModel import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.bloggingprompts.BloggingPromptModel import org.wordpress.android.fluxc.network.rest.wpcom.bloggingprompts.BloggingPromptsError import org.wordpress.android.fluxc.network.rest.wpcom.bloggingprompts.BloggingPromptsErrorType import org.wordpress.android.fluxc.store.BloggingRemindersStore import org.wordpress.android.fluxc.store.bloggingprompts.BloggingPromptsStore import org.wordpress.android.fluxc.store.bloggingprompts.BloggingPromptsStore.BloggingPromptsResult import org.wordpress.android.test import org.wordpress.android.testScope import org.wordpress.android.ui.mysite.MySiteUiState.PartialState.BloggingPromptUpdate import org.wordpress.android.ui.mysite.SelectedSiteRepository import org.wordpress.android.ui.prefs.AppPrefsWrapper import org.wordpress.android.util.config.BloggingPromptsFeatureConfig import java.util.Date /* SITE */ const val SITE_LOCAL_ID = 1 /* MODEL */ private val PROMPT = BloggingPromptModel( id = 1234, text = "prompt text", title = "", content = "<!-- wp:pullquote -->\n" + "<figure class=\"wp-block-pullquote\"><blockquote><p>You have 15 minutes to address the whole world" + " live (on television or radio — choose your format). What would you say?</p><cite>(courtesy of" + " plinky.com)</cite></blockquote></figure>\n" + "<!-- /wp:pullquote -->", date = Date(), isAnswered = false, attribution = "", respondentsCount = 5, respondentsAvatarUrls = listOf() ) @InternalCoroutinesApi class BloggingPromptCardSourceTest : BaseUnitTest() { @Mock private lateinit var selectedSiteRepository: SelectedSiteRepository @Mock private lateinit var bloggingPromptsStore: BloggingPromptsStore @Mock private lateinit var bloggingPromptsFeatureConfig: BloggingPromptsFeatureConfig @Mock private lateinit var appPrefsWrapper: AppPrefsWrapper @Mock private lateinit var bloggingRemindersStore: BloggingRemindersStore private lateinit var bloggingPromptCardSource: BloggingPromptCardSource private val data = BloggingPromptsResult( model = listOf(PROMPT) ) private val success = BloggingPromptsResult<List<BloggingPromptModel>>() private val apiError = BloggingPromptsResult<List<BloggingPromptModel>>( error = BloggingPromptsError(BloggingPromptsErrorType.API_ERROR) ) private var siteModel = SiteModel().apply { id = SITE_LOCAL_ID setIsPotentialBloggingSite(true) } private val bloggingReminderSettings = BloggingRemindersModel( siteId = SITE_LOCAL_ID, isPromptIncluded = true ) @Before fun setUp() { init() } private fun init(isBloggingPromptFeatureEnabled: Boolean = true) { setUpMocks(isBloggingPromptFeatureEnabled) bloggingPromptCardSource = BloggingPromptCardSource( selectedSiteRepository, bloggingPromptsStore, bloggingPromptsFeatureConfig, appPrefsWrapper, bloggingRemindersStore, TEST_DISPATCHER ) } private fun setUpMocks(isBloggingPromptFeatureEnabled: Boolean) { whenever(bloggingPromptsFeatureConfig.isEnabled()).thenReturn(isBloggingPromptFeatureEnabled) whenever(selectedSiteRepository.getSelectedSite()).thenReturn(siteModel) whenever(appPrefsWrapper.getSkippedPromptDay(any())).thenReturn(null) whenever(bloggingRemindersStore.bloggingRemindersModel(any())).thenReturn(flowOf(bloggingReminderSettings)) } /* GET DATA */ @Test fun `when build is invoked, then start collecting prompts from store (database)`() = test { bloggingPromptCardSource.refresh.observeForever { } bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { } verify(bloggingPromptsStore).getPrompts(eq(siteModel)) } @Test fun `given prompts feature disabled, no get or fetch calls are made`() = test { init(isBloggingPromptFeatureEnabled = false) val result = mutableListOf<BloggingPromptUpdate>() bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { it?.let { result.add(it) } } bloggingPromptCardSource.refresh() verify(bloggingPromptsStore, never()).getPrompts(eq(siteModel)) verify(bloggingPromptsStore, never()).fetchPrompts(any(), any(), any()) } @Test fun `given build is invoked, when prompts are collected, then data is loaded (database)`() = test { val result = mutableListOf<BloggingPromptUpdate>() whenever(bloggingPromptsStore.getPrompts(eq(siteModel))).thenReturn(flowOf(data)) bloggingPromptCardSource.refresh.observeForever { } bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { it?.let { result.add(it) } } assertThat(result.size).isEqualTo(1) assertThat(result.first()).isEqualTo(BloggingPromptUpdate(PROMPT)) } /* REFRESH DATA */ @Test fun `when build is invoked, then prompts are fetched from store (network)`() = test { whenever(bloggingPromptsStore.getPrompts(eq(siteModel))).thenReturn(flowOf(data)) bloggingPromptCardSource.refresh.observeForever { } bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { } verify(bloggingPromptsStore).fetchPrompts(eq(siteModel), eq(20), any()) } @Test fun `given no error, when build is invoked, then data is only loaded from get prompts (database)`() = test { val result = mutableListOf<BloggingPromptUpdate>() whenever(bloggingPromptsStore.getPrompts(eq(siteModel))).thenReturn(flowOf(data)) whenever(bloggingPromptsStore.fetchPrompts(any(), any(), any())).thenReturn(BloggingPromptsResult()) bloggingPromptCardSource.refresh.observeForever { } bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { it?.let { result.add(it) } } assertThat(result.size).isEqualTo(1) assertThat(result.first()).isEqualTo(BloggingPromptUpdate(PROMPT)) } @Test fun `given no error, when refresh is invoked, then data is only loaded from get prompts (database)`() = test { val result = mutableListOf<BloggingPromptUpdate>() whenever(bloggingPromptsStore.getPrompts(eq(siteModel))).thenReturn(flowOf(data)) whenever(bloggingPromptsStore.fetchPrompts(any(), any(), any())).thenReturn(success).thenReturn(success) bloggingPromptCardSource.refresh.observeForever { } bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { it?.let { result.add(it) } } bloggingPromptCardSource.refresh() assertThat(result.size).isEqualTo(1) assertThat(result.first()).isEqualTo(BloggingPromptUpdate(PROMPT)) } /* SKIPPED PROMPT */ @Test fun `given build is invoked, when prompt is skipped, then empty state is loaded`() = test { val result = mutableListOf<BloggingPromptUpdate>() whenever(appPrefsWrapper.getSkippedPromptDay(any())).thenReturn(Date()) bloggingPromptCardSource.refresh.observeForever { } bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { it?.let { result.add(it) } } assertThat(result.size).isEqualTo(1) assertThat(result.first()).isEqualTo(BloggingPromptUpdate(null)) } /* SITE BASED PROMPT AVAILABILITY LOGIC */ @Test fun `on build, if prompt not skipped, prompt reminder opted-in then prompt is loaded`() = test { val result = mutableListOf<BloggingPromptUpdate>() whenever(bloggingPromptsStore.getPrompts(eq(siteModel))).thenReturn(flowOf(data)) whenever(bloggingRemindersStore.bloggingRemindersModel(any())).thenReturn( flowOf( BloggingRemindersModel( siteId = 1, isPromptIncluded = true ) ) ) bloggingPromptCardSource.refresh.observeForever { } bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { it?.let { result.add(it) } } assertThat(result.size).isEqualTo(1) assertThat(result.first()).isEqualTo(BloggingPromptUpdate(PROMPT)) } @Test fun `on build, if prompt not skipped, prompt reminder opted-out and site is blog then prompt is loaded`() = test { val result = mutableListOf<BloggingPromptUpdate>() val bloggingSite = SiteModel().apply { id = SITE_LOCAL_ID setIsPotentialBloggingSite(true) } whenever(selectedSiteRepository.getSelectedSite()).thenReturn(bloggingSite) whenever(bloggingPromptsStore.getPrompts(eq(bloggingSite))).thenReturn(flowOf(data)) whenever(bloggingRemindersStore.bloggingRemindersModel(any())).thenReturn( flowOf( BloggingRemindersModel( siteId = 1, isPromptIncluded = false ) ) ) bloggingPromptCardSource.refresh.observeForever { } bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { it?.let { result.add(it) } } assertThat(result.size).isEqualTo(1) assertThat(result.first()).isEqualTo(BloggingPromptUpdate(PROMPT)) } @Test fun `on build, if prompt not skipped, prompt reminder opted-out and site is not blog then prompt is not loaded`() = test { val result = mutableListOf<BloggingPromptUpdate>() val bloggingSite = SiteModel().apply { id = SITE_LOCAL_ID setIsPotentialBloggingSite(false) } whenever(selectedSiteRepository.getSelectedSite()).thenReturn(bloggingSite) whenever(bloggingRemindersStore.bloggingRemindersModel(any())).thenReturn( flowOf( BloggingRemindersModel( siteId = 1, isPromptIncluded = false ) ) ) bloggingPromptCardSource.refresh.observeForever { } bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { it?.let { result.add(it) } } assertThat(result.size).isEqualTo(1) assertThat(result.first()).isEqualTo(BloggingPromptUpdate(null)) } @Test fun `on build, if prompt not skipped, prompt reminder opted-in and site is not blog then prompt is loaded`() = test { val result = mutableListOf<BloggingPromptUpdate>() val bloggingSite = SiteModel().apply { id = SITE_LOCAL_ID setIsPotentialBloggingSite(false) } whenever(selectedSiteRepository.getSelectedSite()).thenReturn(bloggingSite) whenever(bloggingPromptsStore.getPrompts(eq(bloggingSite))).thenReturn(flowOf(data)) whenever(bloggingRemindersStore.bloggingRemindersModel(any())).thenReturn( flowOf( BloggingRemindersModel( siteId = 1, isPromptIncluded = true ) ) ) bloggingPromptCardSource.refresh.observeForever { } bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { it?.let { result.add(it) } } assertThat(result.size).isEqualTo(1) assertThat(result.first()).isEqualTo(BloggingPromptUpdate(PROMPT)) } /* IS REFRESHING */ @Test fun `when build is invoked, then refresh is set to true`() = test { val result = mutableListOf<Boolean>() bloggingPromptCardSource.refresh.observeForever { result.add(it) } bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { } assertThat(result.size).isEqualTo(2) assertThat(result.first()).isFalse assertThat(result.last()).isTrue } @Test fun `when refresh is invoked, then refresh is set to false`() = test { val result = mutableListOf<Boolean>() whenever(bloggingPromptsStore.getPrompts(eq(siteModel))).thenReturn(flowOf(data)) whenever(bloggingPromptsStore.fetchPrompts(any(), any(), any())).thenReturn(success).thenReturn(success) bloggingPromptCardSource.refresh.observeForever { result.add(it) } bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { } bloggingPromptCardSource.refresh() assertThat(result.size).isEqualTo(5) assertThat(result[0]).isFalse // init assertThat(result[1]).isTrue // build(...) -> refresh() assertThat(result[2]).isFalse // build(...) -> bloggingPromptCardSource.fetchPrompts(...) -> success assertThat(result[3]).isTrue // refresh() assertThat(result[4]).isFalse // refreshData(...) -> bloggingPromptCardSource.fetchPrompts(...) -> success } @Test fun `when refreshTodayPrompt is invoked, single prompt refresh is called`() = test { val regularRefreshResult = mutableListOf<Boolean>() val singlePromptRefreshResult = mutableListOf<Boolean>() whenever(bloggingPromptsStore.getPrompts(eq(siteModel))).thenReturn(flowOf(data)) whenever(bloggingPromptsStore.fetchPrompts(any(), any(), any())).thenReturn(success).thenReturn(success) bloggingPromptCardSource.singleRefresh.observeForever { singlePromptRefreshResult.add(it) } bloggingPromptCardSource.refresh.observeForever { regularRefreshResult.add(it) } bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { } bloggingPromptCardSource.refreshTodayPrompt() assertThat(singlePromptRefreshResult.size).isEqualTo(2) assertThat(singlePromptRefreshResult[0]).isFalse // init assertThat(singlePromptRefreshResult[1]).isTrue // refreshTodayPrompt } @Test fun `when refreshTodayPrompt is invoked, nothing happens if refresh is already in progress`() = test { val regularRefreshResult = mutableListOf<Boolean>() val singlePromptRefreshResult = mutableListOf<Boolean>() whenever(bloggingPromptsStore.getPrompts(eq(siteModel))).thenReturn(flowOf(data)) // we do not return success from bloggingPromptsStore.fetchPrompts() which locks live data in refreshing state bloggingPromptCardSource.singleRefresh.observeForever { singlePromptRefreshResult.add(it) } bloggingPromptCardSource.refresh.observeForever { regularRefreshResult.add(it) } bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { } bloggingPromptCardSource.refreshTodayPrompt() assertThat(singlePromptRefreshResult.size).isEqualTo(1) assertThat(singlePromptRefreshResult[0]).isFalse // init } @Test fun `given no error, when data has been refreshed, then refresh is set to true`() = test { val result = mutableListOf<Boolean>() whenever(bloggingPromptsStore.getPrompts(eq(siteModel))).thenReturn(flowOf(data)) whenever(bloggingPromptsStore.fetchPrompts(any(), any(), any())).thenReturn(success) bloggingPromptCardSource.refresh.observeForever { result.add(it) } bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { } bloggingPromptCardSource.refresh() assertThat(result.size).isEqualTo(5) assertThat(result[0]).isFalse // init assertThat(result[1]).isTrue // build(...) -> refresh() assertThat(result[2]).isFalse // build(...) -> bloggingPromptCardSource.fetchPrompts(...) -> success assertThat(result[3]).isTrue // refresh() assertThat(result[4]).isFalse // refreshData(...) -> bloggingPromptCardSource.fetchPrompts(...) -> success } @Test fun `given error, when data has been refreshed, then refresh is set to false`() = test { val result = mutableListOf<Boolean>() whenever(bloggingPromptsStore.getPrompts(eq(siteModel))).thenReturn(flowOf(data)) whenever(bloggingPromptsStore.fetchPrompts(any(), any(), any())).thenReturn(apiError) bloggingPromptCardSource.refresh.observeForever { result.add(it) } bloggingPromptCardSource.build(testScope(), SITE_LOCAL_ID).observeForever { } bloggingPromptCardSource.refresh() assertThat(result.size).isEqualTo(5) assertThat(result[0]).isFalse // init assertThat(result[1]).isTrue // build(...) -> refresh() assertThat(result[2]).isFalse // build(...) -> bloggingPromptCardSource.fetchPrompts(...) -> error assertThat(result[3]).isTrue // refresh() assertThat(result[4]).isFalse // refreshData(...) -> bloggingPromptCardSource.fetchPrompts(...) -> error } }
gpl-2.0
bac246122c171279248a4e4425e01704
45.296954
120
0.661696
5.03895
false
true
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/deeplearning/transformers/BERTModel.kt
1
6694
/* Copyright 2020-present Simone Cangialosi. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.deeplearning.transformers import com.kotlinnlp.simplednn.core.embeddings.EmbeddingsMap import com.kotlinnlp.simplednn.core.functionalities.activations.GeLU import com.kotlinnlp.simplednn.core.functionalities.activations.Softmax import com.kotlinnlp.simplednn.core.functionalities.initializers.GlorotInitializer import com.kotlinnlp.simplednn.core.functionalities.initializers.Initializer import com.kotlinnlp.simplednn.core.layers.LayerInterface import com.kotlinnlp.simplednn.core.layers.LayerType import com.kotlinnlp.simplednn.core.layers.StackedLayersParameters import com.kotlinnlp.utils.DictionarySet import com.kotlinnlp.utils.Serializer import com.kotlinnlp.utils.removeFrom import java.io.InputStream import java.io.OutputStream import java.io.Serializable /** * The BERT model. * * @property inputSize the size of the input arrays * @property attentionSize the size of the attention arrays * @property attentionOutputSize the size of the attention outputs * @property outputHiddenSize the number of the hidden nodes of the output feed-forward * @property numOfHeads the number of self-attention heads * @property vocabulary the vocabulary with all the well-known forms of the model (forms not present in it are treated * as unknown) * @param wordEmbeddings pre-trained word embeddings or null to generate them randomly using the [vocabulary] * @param numOfLayers the number of stacked layers * @param weightsInitializer the initializer of the weights (zeros if null, default: Glorot) * @param biasesInitializer the initializer of the biases (zeros if null, default: Glorot) */ class BERTModel( val inputSize: Int, val attentionSize: Int, val attentionOutputSize: Int, val outputHiddenSize: Int, val numOfHeads: Int, val vocabulary: DictionarySet<String>, wordEmbeddings: EmbeddingsMap<String>? = null, numOfLayers: Int, weightsInitializer: Initializer? = GlorotInitializer(), biasesInitializer: Initializer? = GlorotInitializer() ) : Serializable { /** * Functional token. */ enum class FuncToken(val form: String) { CLS("[CLS]"), SEP("[SEP]"), PAD("[PAD]"), UNK("[UNK]"), MASK("[MASK]"); companion object { /** * The [FuncToken] associated by form. */ private val tokensByForm: Map<String, FuncToken> = values().associateBy { it.form } /** * @param form a token form * * @return the [FuncToken] with the given form */ fun byForm(form: String) = tokensByForm.getValue(form) } } companion object { /** * Private val used to serialize the class (needed by Serializable). */ @Suppress("unused") private const val serialVersionUID: Long = 1L /** * Read [BERTModel] (serialized) from an input stream and decode it. * * @param inputStream the [InputStream] from which to read the serialized [BERTModel] * * @return the [BERTModel] read from [inputStream] and decoded */ fun load(inputStream: InputStream): BERTModel = Serializer.deserialize(inputStream) } /** * The size of the output arrays (equal to the input). */ val outputSize: Int = this.inputSize /** * The initial parameters of the stacked BERT layers. * They can be reduced with the method [reduceLayersTo]. */ private val initLayers: MutableList<BERTParameters> = MutableList( size = numOfLayers, init = { BERTParameters( inputSize = this.inputSize, attentionSize = this.attentionSize, attentionOutputSize = this.attentionOutputSize, outputHiddenSize = this.outputHiddenSize, numOfHeads = this.numOfHeads, weightsInitializer = weightsInitializer, biasesInitializer = biasesInitializer) } ) /** * The parameters of the stacked BERT layers. */ var layers: List<BERTParameters> = this.initLayers.toList() private set /** * The parameters of the embeddings norm layer. */ val embNorm = StackedLayersParameters( LayerInterface(size = this.inputSize), LayerInterface(size = this.inputSize, connectionType = LayerType.Connection.Norm), weightsInitializer = weightsInitializer, biasesInitializer = biasesInitializer) /** * The word embeddings. * If not trained, they can be set to null before a model serialization and re-set after deserialization, in order to * make the model lighter. */ var wordEmb: EmbeddingsMap<String>? = wordEmbeddings ?: EmbeddingsMap<String>(this.inputSize).apply { vocabulary.getElements().forEach { set(it) } } /** * The functional embeddings associated to the [FuncToken]. */ var funcEmb: EmbeddingsMap<FuncToken> = EmbeddingsMap<FuncToken>(this.inputSize).apply { FuncToken.values().forEach { set(key = it, embedding = wordEmb!!.getOrNull(it.form)) } } /** * The positional embeddings. */ val positionalEmb: EmbeddingsMap<Int> = EmbeddingsMap(this.inputSize) /** * The token type embeddings. */ val tokenTypeEmb: EmbeddingsMap<Int> = EmbeddingsMap<Int>(this.inputSize).apply { set(0) set(1) } /** * The model of the classifier used to train the model. */ var classifier: StackedLayersParameters = StackedLayersParameters( LayerInterface(size = inputSize), LayerInterface(size = inputSize, connectionType = LayerType.Connection.Feedforward, activationFunction = GeLU), LayerInterface(size = inputSize, connectionType = LayerType.Connection.Norm), LayerInterface( size = vocabulary.size, connectionType = LayerType.Connection.Feedforward, activationFunction = Softmax()) ) /** * Serialize this [BERTModel] and write it to an output stream. * * @param outputStream the [OutputStream] in which to write this serialized [BERTModel] */ fun dump(outputStream: OutputStream) = Serializer.serialize(this, outputStream) /** * Reduce the layers of this model to a given size, starting from the last. * * @param size the new number of [BERT] layers */ fun reduceLayersTo(size: Int) { require(size < this.layers.size) { "The reducing size ($size) must be lower than the current layer size (${this.layers.size})" } this.initLayers.removeFrom(size) this.layers = this.initLayers.toList() } }
mpl-2.0
cbeca817ab24bbb8b2039b294fa97c8e
32.638191
119
0.703615
4.327085
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/uploads/AutoSavePostIfNotDraftUseCase.kt
1
7385
package org.wordpress.android.ui.uploads import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode.BACKGROUND import org.greenrobot.eventbus.ThreadMode.MAIN import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.generated.PostActionBuilder import org.wordpress.android.fluxc.model.CauseOfOnPostChanged.RemoteAutoSavePost import org.wordpress.android.fluxc.model.LocalOrRemoteId.RemoteId import org.wordpress.android.fluxc.model.PostModel import org.wordpress.android.fluxc.store.PostStore import org.wordpress.android.fluxc.store.PostStore.OnPostChanged import org.wordpress.android.fluxc.store.PostStore.OnPostStatusFetched import org.wordpress.android.fluxc.store.PostStore.PostError import org.wordpress.android.fluxc.store.PostStore.RemotePostPayload import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.ui.uploads.AutoSavePostIfNotDraftResult.FetchPostStatusFailed import org.wordpress.android.ui.uploads.AutoSavePostIfNotDraftResult.PostAutoSaveFailed import org.wordpress.android.ui.uploads.AutoSavePostIfNotDraftResult.PostAutoSaved import org.wordpress.android.ui.uploads.AutoSavePostIfNotDraftResult.PostIsDraftInRemote import javax.inject.Inject import javax.inject.Named import kotlin.coroutines.Continuation import kotlin.coroutines.resume private const val DRAFT_POST_STATUS = "draft" interface OnAutoSavePostIfNotDraftCallback { fun handleAutoSavePostIfNotDraftResult(result: AutoSavePostIfNotDraftResult) } sealed class AutoSavePostIfNotDraftResult(open val post: PostModel) { // Initial fetch post status request failed data class FetchPostStatusFailed(override val post: PostModel, val error: PostError) : AutoSavePostIfNotDraftResult(post) // Post status is `DRAFT` in remote which means we'll want to update the draft directly data class PostIsDraftInRemote(override val post: PostModel) : AutoSavePostIfNotDraftResult(post) // Post status is not `DRAFT` in remote and the post was auto-saved successfully data class PostAutoSaved(override val post: PostModel) : AutoSavePostIfNotDraftResult(post) // Post status is not `DRAFT` in remote but the post auto-save failed data class PostAutoSaveFailed(override val post: PostModel, val error: PostError) : AutoSavePostIfNotDraftResult(post) } /** * This is a use case that auto-saves a post if it's not a DRAFT in remote and returns various results depending * on the remote post status and whether network requests were successful. * * The reason auto-save is tied to post status is that the `/autosave` REST endpoint will override the changes to * a `DRAFT` directly rather than auto-saving it. While doing so, it'll also disable comments for the post due to * a bug. Both the fact that the endpoint does something we are not expecting and the bug that results from it is * avoided by only calling the `/autosave` endpoint for posts that are not in DRAFT status. We update DRAFTs directly * just as the endpoint would have, but that makes the logic more clear on the client side while avoiding the * comments getting disabled bug. * * See p3hLNG-15Z-p2 for more info. */ class AutoSavePostIfNotDraftUseCase @Inject constructor( private val dispatcher: Dispatcher, private val postStore: PostStore, @Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher ) { private val coroutineScope = CoroutineScope(bgDispatcher) private val postStatusContinuations = HashMap<RemoteId, Continuation<OnPostStatusFetched>>() private val autoSaveContinuations = HashMap<RemoteId, Continuation<OnPostChanged>>() init { dispatcher.register(this) } fun autoSavePostOrUpdateDraft( remotePostPayload: RemotePostPayload, callback: OnAutoSavePostIfNotDraftCallback ) { val remotePostId = RemoteId(remotePostPayload.post.remotePostId) if (remotePostPayload.post.isLocalDraft) { throw IllegalArgumentException("Local drafts should not be auto-saved") } if (postStatusContinuations.containsKey(remotePostId) || autoSaveContinuations.containsKey(remotePostId)) { throw IllegalArgumentException( "This post is already being processed. Make sure not to start an autoSave " + "or update draft action while another one is going on." ) } coroutineScope.launch { val onPostStatusFetched = fetchRemotePostStatus(remotePostPayload) val result = when { onPostStatusFetched.isError -> { FetchPostStatusFailed( post = remotePostPayload.post, error = onPostStatusFetched.error ) } onPostStatusFetched.remotePostStatus == DRAFT_POST_STATUS -> { PostIsDraftInRemote(remotePostPayload.post) } else -> { autoSavePost(remotePostPayload) } } callback.handleAutoSavePostIfNotDraftResult(result) } } private suspend fun fetchRemotePostStatus(remotePostPayload: RemotePostPayload): OnPostStatusFetched { val remotePostId = RemoteId(remotePostPayload.post.remotePostId) return suspendCancellableCoroutine { cont -> postStatusContinuations[remotePostId] = cont dispatcher.dispatch(PostActionBuilder.newFetchPostStatusAction(remotePostPayload)) } } private suspend fun autoSavePost(remotePostPayload: RemotePostPayload): AutoSavePostIfNotDraftResult { val remotePostId = RemoteId(remotePostPayload.post.remotePostId) val onPostChanged: OnPostChanged = suspendCancellableCoroutine { cont -> autoSaveContinuations[remotePostId] = cont dispatcher.dispatch(PostActionBuilder.newRemoteAutoSavePostAction(remotePostPayload)) } return if (onPostChanged.isError) { PostAutoSaveFailed(remotePostPayload.post, onPostChanged.error) } else { val updatedPost = postStore.getPostByRemotePostId( remotePostId.value, remotePostPayload.site ) PostAutoSaved(updatedPost) } } @Subscribe(threadMode = BACKGROUND) @Suppress("unused") fun onPostStatusFetched(event: OnPostStatusFetched) { val remotePostId = RemoteId(event.post.remotePostId) postStatusContinuations[remotePostId]?.let { continuation -> continuation.resume(event) postStatusContinuations.remove(remotePostId) } } @Subscribe(threadMode = MAIN, priority = 9) @Suppress("unused") fun onPostChanged(event: OnPostChanged) { if (event.causeOfChange is RemoteAutoSavePost) { val remotePostId = RemoteId((event.causeOfChange as RemoteAutoSavePost).remotePostId) autoSaveContinuations[remotePostId]?.let { continuation -> continuation.resume(event) autoSaveContinuations.remove(remotePostId) } } } }
gpl-2.0
61d039af99899d2bd7442154a17f53c5
45.446541
117
0.724983
4.829954
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/tests/testData/inspections/dfa/Arrays.kt
9
1678
// WITH_STDLIB fun arrayCast(x: Array<Int>) { @Suppress("UNCHECKED_CAST") val y = x as Array<Any> println(y) } fun arrayRead(x : Array<Int>) { if (x[0] > 10) if (<warning descr="Condition 'x[0] < 0' is always false">x[0] < 0</warning>) { } } fun arrayWrite(x: IntArray) { x[0] += 1 if (x[0] == 1) {} x[0] = 1 if (<warning descr="Condition 'x[0] == 1' is always true">x[0] == 1</warning>) {} } fun indexBounds(x : Array<Int>, y : Int) { if (x[y] > 10) { if (<warning descr="Condition 'y >= 0' is always true">y >= 0</warning>) {} if (<warning descr="Condition 'y == x.size' is always false">y == x.size</warning>) {} if (<warning descr="Condition 'y > x.size' is always false">y > x.size</warning>) {} } } fun indexBoundsNullable(x : Array<Int>, y : Int?) { if (y != null && x[y] > 10) { if (<warning descr="Condition 'y >= x.size' is always false">y >= x.size</warning>) {} if (<warning descr="Condition 'y < 0' is always false">y < 0</warning>) {} } } fun aioobe(x : Array<Int>, y : Int) { if (y >= x.size) { if (x[<warning descr="Index is always out of bounds">y</warning>] > 10) { } } if (y < 0) { if (x[<warning descr="Index is always out of bounds">y</warning>] > 10) {} } } fun aioobeNullable(x : Array<Int>, y : Int?) { if (y != null && y < 0) { if (x[<warning descr="Index is always out of bounds">y</warning>] > 10) { } } } fun arrayOfAny(x : Array<Any>) { val v = x[0] if (v is X) { } } fun nullableArraySize(x : Array<Int>?) { if (x?.size ?: 0 > 0) { } } data class X(val x: Int)
apache-2.0
f0ea6afbc78fcba27686eaf6e2041c5e
27.457627
94
0.523242
2.903114
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveWhenConditionFix.kt
1
1784
// 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.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.psi.EditCommaSeparatedListHelper import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtWhenCondition import org.jetbrains.kotlin.psi.KtWhenEntry import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.utils.addToStdlib.safeAs class RemoveWhenConditionFix(element: KtWhenCondition) : KotlinQuickFixAction<KtWhenCondition>(element) { override fun getFamilyName() = KotlinBundle.message("remove.condition") override fun getText() = familyName override fun invoke(project: Project, editor: Editor?, file: KtFile) { element?.let { EditCommaSeparatedListHelper.removeItem(it) } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): RemoveWhenConditionFix? { if (diagnostic.factory != Errors.SENSELESS_NULL_IN_WHEN) return null val whenCondition = diagnostic.psiElement.getStrictParentOfType<KtWhenCondition>() ?: return null val conditions = whenCondition.parent.safeAs<KtWhenEntry>()?.conditions?.size ?: return null if (conditions < 2) return null return RemoveWhenConditionFix(whenCondition) } } }
apache-2.0
3fbdaae920e4133e7ec2ab43c5b33f47
47.216216
158
0.778027
4.757333
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/mobib/MobibLookup.kt
1
2397
/* * MobibLookup.kt * * Copyright 2018 Google * * 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 au.id.micolous.metrodroid.transit.mobib import au.id.micolous.metrodroid.multi.FormattedString import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.time.MetroTimeZone import au.id.micolous.metrodroid.transit.Station import au.id.micolous.metrodroid.transit.TransitCurrency import au.id.micolous.metrodroid.transit.en1545.En1545LookupSTR import au.id.micolous.metrodroid.util.StationTableReader internal const val MOBIB_STR = "mobib" object MobibLookup : En1545LookupSTR(MOBIB_STR) { override val timeZone: MetroTimeZone get() = MobibTransitData.TZ override fun getRouteName(routeNumber: Int?, routeVariant: Int?, agency: Int?, transport: Int?) = when (agency) { null -> null BUS, TRAM -> routeNumber?.toString()?.let { FormattedString(it) } else -> null } override fun getStation(station: Int, agency: Int?, transport: Int?): Station? { if (station == 0) return null return StationTableReader.getStation(MOBIB_STR, station or ((agency ?: 0) shl 22)) } override fun parseCurrency(price: Int) = TransitCurrency.EUR(price) override fun getAgencyName(agency: Int?, isShort: Boolean) = if (agency == null) null else StationTableReader.getOperatorName(MOBIB_STR, agency, isShort) const val BUS = 0xf const val TRAM = 0x16 override val subscriptionMap = mapOf( 0x2801 to R.string.mobib_jump_1_trip, 0x2803 to R.string.mobib_jump_10_trips, 0x0805 to R.string.mobib_airport_bus, 0x303d to R.string.mobib_jump_24h_bus_airport ) }
gpl-3.0
96682bcc21283c9b133d38bf660d02c3
35.318182
101
0.691281
3.891234
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/application/impl/AppUIExecutorImpl.kt
2
7614
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.application.impl import com.intellij.ide.IdeEventQueue import com.intellij.ide.lightEdit.LightEdit import com.intellij.openapi.Disposable import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.TransactionGuard import com.intellij.openapi.application.constraints.ConstrainedExecution.ContextConstraint import com.intellij.openapi.application.constraints.Expiration import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.impl.PsiDocumentManagerBase import kotlinx.coroutines.Runnable import kotlinx.coroutines.async import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.concurrent.Executor import java.util.function.BooleanSupplier import kotlin.coroutines.ContinuationInterceptor import kotlin.coroutines.CoroutineContext /** * @author eldar */ internal class AppUIExecutorImpl private constructor(private val modality: ModalityState, private val thread: ExecutionThread, constraints: Array<ContextConstraint>, cancellationConditions: Array<BooleanSupplier>, expirableHandles: Set<Expiration>) : AppUIExecutor, BaseExpirableExecutorMixinImpl<AppUIExecutorImpl>(constraints, cancellationConditions, expirableHandles, getExecutorForThread(thread, modality)) { constructor(modality: ModalityState, thread: ExecutionThread) : this(modality, thread, emptyArray(), emptyArray(), emptySet()) companion object { private fun getExecutorForThread(thread: ExecutionThread, modality: ModalityState): Executor { return when (thread) { ExecutionThread.EDT -> MyEdtExecutor(modality) ExecutionThread.WT -> MyWtExecutor(modality) } } } private class MyWtExecutor(private val modality: ModalityState) : Executor { override fun execute(command: Runnable) { if (ApplicationManager.getApplication().isWriteThread && (ApplicationImpl.USE_SEPARATE_WRITE_THREAD || !TransactionGuard.getInstance().isWriteSafeModality(modality) || TransactionGuard.getInstance().isWritingAllowed) && !ModalityState.current().dominates(modality)) { command.run() } else { ApplicationManager.getApplication().invokeLaterOnWriteThread(command, modality) } } } private class MyEdtExecutor(private val modality: ModalityState) : Executor { override fun execute(command: Runnable) { if (ApplicationManager.getApplication().isDispatchThread && (!TransactionGuard.getInstance().isWriteSafeModality(modality) || TransactionGuard.getInstance().isWritingAllowed) && !ModalityState.current().dominates(modality)) { command.run() } else { ApplicationManager.getApplication().invokeLater(command, modality) } } } override fun cloneWith(constraints: Array<ContextConstraint>, cancellationConditions: Array<BooleanSupplier>, expirationSet: Set<Expiration>): AppUIExecutorImpl { return AppUIExecutorImpl(modality, thread, constraints, cancellationConditions, expirationSet) } override fun dispatchLaterUnconstrained(runnable: Runnable) { return when (thread) { ExecutionThread.EDT -> ApplicationManager.getApplication().invokeLater(runnable, modality) ExecutionThread.WT -> ApplicationManager.getApplication().invokeLaterOnWriteThread(runnable, modality) } } override fun later(): AppUIExecutorImpl { val edtEventCount = if (ApplicationManager.getApplication().isDispatchThread) IdeEventQueue.getInstance().eventCount else -1 return withConstraint(object : ContextConstraint { @Volatile var usedOnce: Boolean = false override fun isCorrectContext(): Boolean { return when (thread) { ExecutionThread.EDT -> when (edtEventCount) { -1 -> ApplicationManager.getApplication().isDispatchThread else -> usedOnce || edtEventCount != IdeEventQueue.getInstance().eventCount } ExecutionThread.WT -> usedOnce } } override fun schedule(runnable: Runnable) { dispatchLaterUnconstrained(Runnable { usedOnce = true runnable.run() }) } override fun toString() = "later" }) } override fun withDocumentsCommitted(project: Project): AppUIExecutorImpl { return withConstraint(WithDocumentsCommitted(project, modality), project) } override fun inSmartMode(project: Project): AppUIExecutorImpl { return withConstraint(InSmartMode(project), project) } } fun AppUIExecutor.withConstraint(constraint: ContextConstraint): AppUIExecutor { return (this as AppUIExecutorImpl).withConstraint(constraint) } fun AppUIExecutor.withConstraint(constraint: ContextConstraint, parentDisposable: Disposable): AppUIExecutor { return (this as AppUIExecutorImpl).withConstraint(constraint, parentDisposable) } /** * A [context][CoroutineContext] to be used with the standard [launch], [async], [withContext] coroutine builders. * Contains: [ContinuationInterceptor]. */ @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated( message = "Do not use: coroutine cancellation must not be handled by a dispatcher. " + "Use Dispatchers.Main and ModalityState.asContextElement() if needed", ) fun AppUIExecutor.coroutineDispatchingContext(): ContinuationInterceptor { return (this as AppUIExecutorImpl).asCoroutineDispatcher() } internal class WithDocumentsCommitted(private val project: Project, private val modality: ModalityState) : ContextConstraint { override fun isCorrectContext(): Boolean { val manager = PsiDocumentManager.getInstance(project) as PsiDocumentManagerBase return !manager.isCommitInProgress && !manager.hasEventSystemEnabledUncommittedDocuments() } override fun schedule(runnable: Runnable) { PsiDocumentManager.getInstance(project).performLaterWhenAllCommitted(modality, runnable) } override fun toString(): String { val isCorrectContext = isCorrectContext() val details = if (isCorrectContext) { "" } else { val manager = PsiDocumentManager.getInstance(project) as PsiDocumentManagerBase ", isCommitInProgress()=${manager.isCommitInProgress}" + ", hasEventSystemEnabledUncommittedDocuments()=${manager.hasEventSystemEnabledUncommittedDocuments()}" } return "withDocumentsCommitted {isCorrectContext()=$isCorrectContext$details}" } } internal class InSmartMode(private val project: Project) : ContextConstraint { init { check(!LightEdit.owns(project)) { "InSmartMode can't be used in LightEdit mode, check that LightEdit.owns(project)==false before calling" } } override fun isCorrectContext() = !project.isDisposed && !DumbService.isDumb(project) override fun schedule(runnable: Runnable) { DumbService.getInstance(project).runWhenSmart(runnable) } override fun toString() = "inSmartMode" } internal enum class ExecutionThread { EDT, WT }
apache-2.0
3509808a6379ae8ff2492764fe843ccd
39.285714
128
0.72301
5.438571
false
false
false
false
GunoH/intellij-community
java/java-tests/testSrc/com/intellij/roots/UnloadedModulesConfigurationTest.kt
5
5348
// 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.roots import com.intellij.facet.FacetManager import com.intellij.facet.mock.MockFacetType import com.intellij.facet.mock.registerFacetType import com.intellij.ide.impl.runUnderModalProgressIfIsEdt import com.intellij.idea.TestFor import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.StdModuleTypes import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.testFramework.JavaModuleTestCase import com.intellij.testFramework.PlatformTestUtil import java.io.File import java.nio.file.Paths class UnloadedModulesConfigurationTest : JavaModuleTestCase() { fun `test load project`() { val projectPath = FileUtilRt.toSystemIndependentName(File(PathManagerEx.getTestDataPath(), "moduleRootManager/unloadedModules").absolutePath) val project = PlatformTestUtil.loadAndOpenProject(Paths.get(projectPath), testRootDisposable) val moduleManager = ModuleManager.getInstance(project) assertEquals(3, moduleManager.allModuleDescriptions.size) assertEquals(2, moduleManager.unloadedModuleDescriptions.size) val util = moduleManager.unloadedModuleDescriptions.find { it.name == "util" }!! val projectDirUrl = VfsUtilCore.pathToUrl(projectPath) assertEquals("$projectDirUrl/util", assertOneElement(util.contentRoots).url) assertEmpty(util.dependencyModuleNames) val dep = moduleManager.unloadedModuleDescriptions.find { it.name == "dep" }!! assertEquals("$projectDirUrl/dep", assertOneElement(dep.contentRoots).url) assertEquals("util", assertOneElement(dep.dependencyModuleNames)) } fun `test set unloaded modules`() { val a = createModule("a") val b = createModule("b") val contentRootPath = FileUtil.toSystemIndependentName(createTempDirectory().absolutePath) ModuleRootModificationUtil.addContentRoot(a, contentRootPath) ModuleRootModificationUtil.addDependency(a, b) val moduleManager = ModuleManager.getInstance(project) runUnderModalProgressIfIsEdt { moduleManager.setUnloadedModules(listOf("a")) } assertEquals("a", assertOneElement(moduleManager.unloadedModuleDescriptions).name) assertNull(moduleManager.findModuleByName("a")) assertNotNull(moduleManager.findModuleByName("b")) runUnderModalProgressIfIsEdt { moduleManager.setUnloadedModules(listOf("b")) } assertEquals("b", assertOneElement(moduleManager.unloadedModuleDescriptions).name) val newA = moduleManager.findModuleByName("a") assertNotNull(newA) assertNull(moduleManager.findModuleByName("b")) assertEquals(VfsUtilCore.pathToUrl(contentRootPath), assertOneElement(ModuleRootManager.getInstance(newA!!).contentRootUrls)) } @TestFor(issues = ["IDEA-296840"]) fun `test reload module and check if facet is not disposed`() { registerFacetType(MockFacetType(), project) val a = createModule("a") val b = createModule("b") val contentRootPath = FileUtil.toSystemIndependentName(createTempDirectory().absolutePath) ModuleRootModificationUtil.addContentRoot(a, contentRootPath) ModuleRootModificationUtil.addDependency(a, b) runWriteAction { FacetManager.getInstance(a).addFacet(MockFacetType.getInstance(), "myFacet", null) } val moduleManager = ModuleManager.getInstance(project) runUnderModalProgressIfIsEdt { moduleManager.setUnloadedModules(listOf("a")) } assertEquals("a", assertOneElement(moduleManager.unloadedModuleDescriptions).name) assertNull(moduleManager.findModuleByName("a")) assertNotNull(moduleManager.findModuleByName("b")) runUnderModalProgressIfIsEdt { moduleManager.setUnloadedModules(listOf()) } val moduleA = ModuleManager.getInstance(project).findModuleByName("a")!! val allFacets = FacetManager.getInstance(moduleA).allFacets allFacets.forEach { assertFalse(it.isDisposed) } } fun `test add unloaded module back`() { val a = createModule("a") val aImlPath = a.moduleFilePath val moduleManager = ModuleManager.getInstance(project) runUnderModalProgressIfIsEdt { moduleManager.setUnloadedModules(listOf("a")) } assertEquals("a", assertOneElement(moduleManager.unloadedModuleDescriptions).name) runWriteAction { moduleManager.newModule(aImlPath, StdModuleTypes.JAVA.id) } assertEmpty(moduleManager.unloadedModuleDescriptions) } fun `test rename module to unloaded module`() { createModule("a") val b = createModule("b") val moduleManager = ModuleManager.getInstance(project) runUnderModalProgressIfIsEdt { moduleManager.setUnloadedModules(listOf("a")) } assertEquals("a", assertOneElement(moduleManager.unloadedModuleDescriptions).name) runWriteAction { val model = moduleManager.getModifiableModel() model.renameModule(b, "a") model.commit() } assertEmpty(moduleManager.unloadedModuleDescriptions) } }
apache-2.0
a069256375f5921f46a15cadf47a46ce
40.465116
145
0.774121
5.093333
false
true
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/conversation/colors/ui/ChatColorSelectionState.kt
2
1295
package org.thoughtcrime.securesms.conversation.colors.ui import org.thoughtcrime.securesms.conversation.colors.ChatColors import org.thoughtcrime.securesms.conversation.colors.ChatColorsPalette import org.thoughtcrime.securesms.util.adapter.mapping.MappingModelList import org.thoughtcrime.securesms.wallpaper.ChatWallpaper data class ChatColorSelectionState( val wallpaper: ChatWallpaper? = null, val chatColors: ChatColors? = null, private val chatColorOptions: List<ChatColors> = listOf() ) { val chatColorModels: MappingModelList init { val models: List<ChatColorMappingModel> = chatColorOptions.map { chatColors -> ChatColorMappingModel( chatColors, chatColors == this.chatColors, false ) }.toList() val defaultModel: ChatColorMappingModel = if (wallpaper != null) { ChatColorMappingModel( wallpaper.autoChatColors, chatColors?.id == ChatColors.Id.Auto, true ) } else { ChatColorMappingModel( ChatColorsPalette.Bubbles.default.withId(ChatColors.Id.Auto), chatColors?.id == ChatColors.Id.Auto, true ) } chatColorModels = MappingModelList().apply { add(defaultModel) addAll(models) add(CustomColorMappingModel()) } } }
gpl-3.0
990e11e44ccf3ee482ae2f12715f55f6
27.777778
82
0.708108
4.465517
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-tests/jvmAndNix/test/io/ktor/tests/server/plugins/DataConversionTest.kt
1
1512
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.server.plugins import io.ktor.server.application.* import io.ktor.server.plugins.dataconversion.* import io.ktor.server.testing.* import io.ktor.util.reflect.* import kotlin.test.* @Suppress("DEPRECATION") class DataConversionTest { @Test fun testDefaultConversion() = withTestApplication { val id = application.conversionService.fromValues(listOf("1"), typeInfo<Int>()) assertEquals(1, id) } private val expectedList = listOf(1, 2) @Test fun testDefaultConversionList() = withTestApplication { val type = typeInfo<List<Int>>() val id = application.conversionService.fromValues(listOf("1", "2"), type) assertEquals(expectedList, id) } data class EntityID(val typeId: Int, val entityId: Int) @Test fun testInstalledConversion() = withTestApplication { application.install(DataConversion) { convert<EntityID> { decode { values -> val (typeId, entityId) = values.single().split('-').map { it.toInt() } EntityID(typeId, entityId) } encode { value -> listOf("${value.typeId}-${value.entityId}") } } } val id = application.conversionService.fromValues(listOf("42-999"), typeInfo<EntityID>()) assertEquals(EntityID(42, 999), id) } }
apache-2.0
67bbbb323b16691da3c4f5d2a6247d3a
30.5
119
0.634921
4.369942
false
true
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/util/annotation-utils.kt
1
2764
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.util import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiAnnotationMemberValue import com.intellij.psi.PsiArrayInitializerMemberValue import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassObjectAccessExpression import com.intellij.psi.PsiClassType import com.intellij.psi.PsiElement import com.intellij.psi.PsiModifierListOwner import org.jetbrains.annotations.Contract @Contract(pure = true) fun PsiModifierListOwner.findAnnotation(qualifiedName: String): PsiAnnotation? { return modifierList?.findAnnotation(qualifiedName) } @Contract(pure = true) fun PsiAnnotationMemberValue.findAnnotations(): List<PsiAnnotation> { return parseArray { it as? PsiAnnotation } } @Contract(pure = true) fun PsiAnnotationMemberValue.computeStringArray(): List<String> { return parseArray { it.constantStringValue } } @Contract(pure = true) fun PsiAnnotationMemberValue.resolveClassArray(): List<PsiClass> { return parseArray { it.resolveClass() } } @Contract(pure = true) fun PsiAnnotationMemberValue.resolveClass(): PsiClass? { if (this !is PsiClassObjectAccessExpression) { return null } return (operand.type as PsiClassType).resolve() } /** * Returns `true` if the annotation value is present (not `null`) and * initialized either to a single value or an array with at least one * element. * * @return `true` if the annotation member is not empty */ fun PsiAnnotationMemberValue?.isNotEmpty(): Boolean { return this != null && (this !is PsiArrayInitializerMemberValue || initializers.isNotEmpty()) } @Contract(pure = true) private inline fun <T : Any> PsiAnnotationMemberValue.parseArray(func: (PsiAnnotationMemberValue) -> T?): List<T> { return if (this is PsiArrayInitializerMemberValue) { initializers.mapNotNull(func) } else { return listOfNotNull(func(this)) } } // PsiNameValuePair -> PsiAnnotationParameterList -> PsiAnnotation @get:Contract(pure = true) val PsiElement.annotationFromNameValuePair get() = parent?.parent as? PsiAnnotation // value -> PsiNameValuePair -> see above @get:Contract(pure = true) val PsiElement.annotationFromValue get() = parent?.annotationFromNameValuePair // value -> PsiArrayInitializerMemberValue -> PsiNameValuePair -> see above @get:Contract(pure = true) val PsiElement.annotationFromArrayValue: PsiAnnotation? get() { val parent = parent ?: return null return if (parent is PsiArrayInitializerMemberValue) { parent.parent?.annotationFromNameValuePair } else { parent.annotationFromNameValuePair } }
mit
6f0264b6e691a3c4534a6adab090777a
29.043478
115
0.744573
4.622074
false
false
false
false
drakelord/wire
wire-compiler/src/main/java/com/squareup/wire/schema/Root.kt
1
5086
/* * Copyright 2018 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.schema import com.google.common.io.Closer import com.squareup.wire.schema.internal.parser.ProtoParser import okio.buffer import okio.source import java.io.IOException import java.nio.file.FileSystem import java.nio.file.FileSystems import java.nio.file.FileVisitResult import java.nio.file.Files import java.nio.file.Path import java.nio.file.ProviderNotFoundException import java.nio.file.SimpleFileVisitor import java.nio.file.attribute.BasicFileAttributes internal sealed class Root { /** Returns all proto files within this root. */ abstract fun allProtoFiles(): Set<ProtoFilePath> /** Returns the proto file if it's in this root, or null if it isn't. */ abstract fun resolve(import: String): ProtoFilePath? } /** * Returns this location's roots. * * @param baseToRoots cached roots to avoid opening the same .zip multiple times. */ // TODO(jwilson): rework this API to combine baseToRoots and Closer. internal fun Location.roots( fs: FileSystem, closer: Closer, baseToRoots: MutableMap<String, List<Root>> = mutableMapOf() ): List<Root> { if (base.isNotEmpty()) { val roots = baseToRoots.computeIfAbsent(base) { Location.get(it).roots(fs, closer) } for (root in roots) { val resolved = root.resolve(path) ?: continue return listOf(resolved) } throw IllegalArgumentException("unable to resolve $this") } else { val path = fs.getPath(path) return path.roots(closer, this) } } /** Returns this path's roots. */ private fun Path.roots(closer: Closer, location: Location): List<Root> { return when { Files.isDirectory(this) -> { check(location.base.isEmpty()) listOf(DirectoryRoot(location.path, this)) } endsWithDotProto() -> listOf(ProtoFilePath(location, this)) // Handle a .zip or .jar file by adding all .proto files within. else -> { check(location.base.isEmpty()) try { val sourceFs = FileSystems.newFileSystem(this, javaClass.classLoader) closer.register(sourceFs) sourceFs.rootDirectories.map { DirectoryRoot(location.path, it) } } catch (e: ProviderNotFoundException) { throw IllegalArgumentException( "expected a directory, archive (.zip / .jar / etc.), or .proto: $this") } } } } /** * A logical location (the base location and path to the file), plus the physical path to load. * These will be different if the file is loaded from a .zip archive. */ internal class ProtoFilePath(val location: Location, val path: Path) : Root() { init { check(path.endsWithDotProto()) { "expected a .proto suffix for $location" } } override fun allProtoFiles() = setOf(this) override fun resolve(import: String): ProtoFilePath? { if (import == location.path) return this return null } /** * Returns the parsed proto file and the path that should be used to import it. * * This is a path like `squareup/dinosaurs/Dinosaur.proto` for a file based on its package name * (like `squareup.dinosaurs`) and its file name (like `Dinosaur.proto`). */ fun parse(): ProtoFile { try { path.source().buffer().use { source -> val data = source.readUtf8() val element = ProtoParser.parse(location, data) return ProtoFile.get(element) } } catch (e: IOException) { throw IOException("Failed to load $path", e) } } } internal class DirectoryRoot( /** The location of either a directory or .zip file. */ val base: String, /** The root to search. If this is a .zip file this is within its internal file system. */ val rootDirectory: Path ) : Root() { override fun allProtoFiles(): Set<ProtoFilePath> { val result = mutableSetOf<ProtoFilePath>() Files.walkFileTree(rootDirectory, object : SimpleFileVisitor<Path>() { override fun visitFile(descendant: Path, attrs: BasicFileAttributes): FileVisitResult { if (descendant.endsWithDotProto()) { val location = Location.get(base, "${rootDirectory.relativize(descendant)}") result.add(ProtoFilePath(location, descendant)) } return FileVisitResult.CONTINUE } }) return result } override fun resolve(import: String): ProtoFilePath? { val resolved = rootDirectory.resolve(import) if (!Files.exists(resolved)) return null return ProtoFilePath(Location.get(base, import), resolved) } } private fun Path.endsWithDotProto() = fileName.toString().endsWith(".proto")
apache-2.0
affff7204b60338563def0b0d8036953
32.032468
97
0.696028
4.020553
false
false
false
false
dhis2/dhis2-android-sdk
core/src/test/java/org/hisp/dhis/android/core/settings/internal/SynchronizationSettingsHandlerShould.kt
1
4062
/* * 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.settings.internal import com.nhaarman.mockitokotlin2.* import org.hisp.dhis.android.core.arch.db.stores.internal.ObjectWithoutUidStore import org.hisp.dhis.android.core.arch.handlers.internal.HandleAction import org.hisp.dhis.android.core.arch.handlers.internal.Handler import org.hisp.dhis.android.core.settings.DataSetSetting import org.hisp.dhis.android.core.settings.ProgramSetting import org.hisp.dhis.android.core.settings.SynchronizationSettings import org.junit.Before import org.junit.Test class SynchronizationSettingsHandlerShould { private val synchronizationSettingStore: ObjectWithoutUidStore<SynchronizationSettings> = mock() private val dataSetSettingHandler: Handler<DataSetSetting> = mock() private val programSettingHandler: Handler<ProgramSetting> = mock() private val synchronizationSettings: SynchronizationSettings = SynchronizationSettings.builder().build() private lateinit var synchronizationSettingsHandler: Handler<SynchronizationSettings> private lateinit var synchronizationSettingsList: List<SynchronizationSettings> @Before @Throws(Exception::class) fun setUp() { synchronizationSettingsList = listOf(synchronizationSettings) whenever(synchronizationSettingStore.updateOrInsertWhere(any())) doReturn HandleAction.Insert synchronizationSettingsHandler = SynchronizationSettingHandler( synchronizationSettingStore, dataSetSettingHandler, programSettingHandler ) } @Test fun clean_database_before_insert_collection() { synchronizationSettingsHandler.handleMany(synchronizationSettingsList) verify(synchronizationSettingStore).delete() verify(synchronizationSettingStore).updateOrInsertWhere(synchronizationSettings) } @Test fun call_dataSet_and_program_handlers_after_insert_item() { synchronizationSettingsHandler.handleMany(synchronizationSettingsList) // Two times: first one to remove existing values, second one to store new ones verify(dataSetSettingHandler, times(2)).handleMany(any()) verify(programSettingHandler, times(2)).handleMany(any()) } @Test fun clean_database_if_empty_collection() { synchronizationSettingsHandler.handleMany(emptyList()) verify(synchronizationSettingStore).delete() verify(synchronizationSettingStore, never()).updateOrInsertWhere(synchronizationSettings) } }
bsd-3-clause
6046c2e67fc11f0aa78b360dd633ad1f
46.788235
108
0.775234
4.917676
false
false
false
false
mdanielwork/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/WebServerFileHandler.kt
5
1770
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.builtInWebServer import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import io.netty.channel.Channel import io.netty.handler.codec.http.FullHttpRequest import io.netty.handler.codec.http.HttpHeaders abstract class WebServerFileHandler { companion object { internal val EP_NAME = ExtensionPointName.create<WebServerFileHandler>("org.jetbrains.webServerFileHandler") } open val pageFileExtensions: Array<String> get() = emptyArray() /** * canonicalRequestPath contains index file name (if not specified in the request) */ abstract fun process(pathInfo: PathInfo, canonicalPath: CharSequence, project: Project, request: FullHttpRequest, channel: Channel, projectNameIfNotCustomHost: String?, extraHeaders: HttpHeaders): Boolean } fun getRequestPath(canonicalPath: CharSequence, projectNameIfNotCustomHost: String?): String = if (projectNameIfNotCustomHost == null) "/$canonicalPath" else "/$projectNameIfNotCustomHost/$canonicalPath"
apache-2.0
f831e57a3b42d640810aa320b79f9ab0
39.25
203
0.721469
4.796748
false
false
false
false
dahlstrom-g/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/settings/MarkdownExtensionsSettings.kt
9
1521
// 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.intellij.plugins.markdown.settings import com.intellij.openapi.components.* import com.intellij.util.messages.Topic import com.intellij.util.xmlb.annotations.XMap import org.jetbrains.annotations.ApiStatus @ApiStatus.Experimental @Service(Service.Level.APP) @State(name = "MarkdownExtensionsSettings", storages = [Storage("markdown.xml")], category = SettingsCategory.TOOLS) class MarkdownExtensionsSettings: SimplePersistentStateComponent<MarkdownExtensionsSettings.State>(State()) { class State: BaseState() { @get:XMap var enabledExtensions by map<String, Boolean>() } var extensionsEnabledState get() = state.enabledExtensions set(value) { state.enabledExtensions = value } fun isExtensionEnabled(extensionsId: String): Boolean { return state.enabledExtensions[extensionsId] == true } @ApiStatus.Experimental fun interface ChangeListener { /** * @param fromSettingsDialog true if extensions state was changed from IDE settings dialog. */ fun extensionsSettingsChanged(fromSettingsDialog: Boolean) companion object { @Topic.AppLevel @JvmField val TOPIC = Topic.create("MarkdownExtensionsSettingsChanged", ChangeListener::class.java) } } companion object { @JvmStatic fun getInstance(): MarkdownExtensionsSettings { return service() } } }
apache-2.0
6861795869ce997e431f3f4fb051e2ca
32.065217
158
0.750822
4.68
false
false
false
false
phylame/jem
imabw/src/main/kotlin/jem/imabw/ui/VariantPane.kt
1
17553
/* * Copyright 2015-2017 Peng Wan <[email protected]> * * This file is part of Jem. * * 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 jem.imabw.ui import javafx.beans.binding.Bindings import javafx.beans.binding.StringBinding import javafx.beans.property.SimpleObjectProperty import javafx.beans.property.SimpleStringProperty import javafx.collections.FXCollections import javafx.geometry.Orientation import javafx.scene.Node import javafx.scene.control.* import javafx.scene.input.KeyCode import javafx.scene.layout.BorderPane import javafx.scene.layout.GridPane import javafx.scene.layout.Region import jclp.* import jclp.io.Flob import jclp.io.flobOf import jclp.text.* import jem.Attributes import jem.imabw.* import mala.App import mala.App.tr import mala.ixin.graphicFor import mala.ixin.initAsForm import mala.ixin.selectNextOrFirst import mala.ixin.selectPreviousOrLast import org.controlsfx.control.ListSelectionView import java.time.LocalDate import java.util.* import java.util.concurrent.Callable internal class VariantItem(key: String, data: Any) { val keyProperty: SimpleStringProperty = SimpleStringProperty(key) val dataProperty: SimpleObjectProperty<Any> = SimpleObjectProperty(data) val typeProperty: StringBinding = Bindings.createStringBinding(Callable { TypeManager.getType(dataProperty.value) ?: "" }, dataProperty) val key: String inline get() = keyProperty.value val type: String inline get() = typeProperty.value var data: Any inline get() = dataProperty.value inline set(value) { dataProperty.value = value } } open class VariantPane(private val values: ValueMap, private val tagId: String, showName: Boolean = true) : BorderPane() { private val valueRef = LinkedList<Any>() private val variants = FXCollections.observableArrayList<VariantItem>() private val currentKeys inline get() = variants.map { it.key } private val table = TableView<VariantItem>(variants) private val toolbar = ToolBar() var isModified = false private set init { center = table right = toolbar styleClass += "variant-pane" initTable(showName) initToolBar() initData() } fun syncVariants() { variants.forEach { it.data.retain() } for (name in values.names.toList() - ignoredKeys()) { values.remove(name) } for (item in variants) { item.key.ifNotEmpty { values[it] = item.data } } variants.forEach { it.data.release() } valueRef.forEach { it.release() } } fun storeState() { UISettings.storeState(table, tagId) } protected open fun getItemTitle(key: String): String = key protected open fun getTypeTitle(type: String): String = TypeManager.getTitle(type) or type protected open fun formatItemData(value: Any): String = TypeManager.printable(value) or { value.toString() } protected open fun getItemType(key: String): String? = null protected open fun getDefaultValue(key: String): Any = "" protected open fun isMultiValues(key: String): Boolean = false protected open fun getAvailableValues(key: String): List<String> = emptyList() protected open fun availableKeys(): Collection<String> = emptyList() protected open fun ignoredKeys(): Collection<String> = emptyList() protected open fun dialogNewTitle() = tr("d.newVariant.title") private fun initTable(showTitle: Boolean) { with(table) { isEditable = true selectionModel.selectionMode = SelectionMode.MULTIPLE columnResizePolicy = TableView.CONSTRAINED_RESIZE_POLICY setOnKeyPressed { event -> if (event.code == KeyCode.INSERT) { newItem() event.consume() } else if (event.code == KeyCode.DELETE) { removeItem(table.selectionModel.selectedItems, true) event.consume() } } columns += TableColumn<VariantItem, String>(tr("com.variant.id")).apply { setCellValueFactory { it.value.keyProperty } } if (showTitle) { columns += TableColumn<VariantItem, String>(tr("com.variant.name")).apply { setCellValueFactory { Bindings.createStringBinding(Callable { getItemTitle(it.value.key) }, it.value.keyProperty) } } } columns += TableColumn<VariantItem, String>(tr("com.variant.type")).apply { setCellValueFactory { Bindings.createStringBinding(Callable { getTypeTitle(it.value.type) }, it.value.typeProperty) } } columns += TableColumn<VariantItem, Any>(tr("com.variant.value")).apply { setOnEditCommit { event -> if (event.newValue != event.oldValue) { event.rowValue.data = event.newValue isModified = true } } setCellFactory { EditableDataCell() } setCellValueFactory { it.value.dataProperty } } UISettings.restoreState(this, tagId) } } private fun initToolBar() { val selection = table.selectionModel.selectedItems with(toolbar) { orientation = Orientation.VERTICAL items += newButton("create").apply { setOnAction { newItem() } } items += newButton("remove").apply { setOnAction { removeItem(selection) } disableProperty().bind(Bindings.isEmpty(selection)) } items += newButton("export").apply { setOnAction { exportItem(table.selectionModel.selectedItem) } val exportableTypes = arrayOf(TypeManager.FLOB, TypeManager.TEXT) disableProperty().bind(Bindings.createBooleanBinding(Callable { selection.size != 1 || selection.first().type !in exportableTypes }, selection)) } } } private fun newButton(id: String): Button { val button = Button("", App.assets.graphicFor("misc/$id")) button.tooltip = Tooltip(tr("com.variant.$id.toast")) return button } private fun initData() { values.filter { it.key !in ignoredKeys() }.mapTo(variants) { VariantItem(it.key, it.value) } table.selectionModel.select(0) } private fun newItem() { val items = arrayListOf<KeyAndName>() for (key in availableKeys() - ignoredKeys() - currentKeys) { items += KeyAndName(key, getItemTitle(key)) } if (items.isNotEmpty()) { newPredefinedItem(items) } else { newCustomizedItem() } } private fun newPredefinedItem(items: Collection<KeyAndName>) { with(Dialog<ButtonType>()) { init(dialogNewTitle(), scene.window, "newVariant1") val selectionView = ListSelectionView<KeyAndName>().apply { sourceItems.addAll(items) dialogPane.content = this } val customize = ButtonType(tr("d.newVariant.customize"), ButtonBar.ButtonData.LEFT) dialogPane.buttonTypes.setAll(ButtonType.OK, ButtonType.CANCEL, customize) dialogPane.lookupButton(ButtonType.OK).disableProperty().bind(Bindings.isEmpty(selectionView.targetItems)) val buttonType = showAndWait().get() if (buttonType == ButtonType.OK) { val model = table.selectionModel.apply { clearSelection() } for (item in selectionView.targetItems) { variants += VariantItem(item.key, getDefaultValue(item.key).also { valueRef += it }) model.selectLast() isModified = true } table.scrollTo(table.items.size - 1) } else if (buttonType == customize) { newCustomizedItem() } } } private fun newCustomizedItem() { val invalidKeys = currentKeys + ignoredKeys() with(Dialog<ButtonType>()) { init(dialogNewTitle(), scene.window, "newVariant2") dialogPane.buttonTypes.setAll(ButtonType.OK, ButtonType.CANCEL) val okButton = dialogPane.lookupButton(ButtonType.OK) val typeCombo = ComboBox<KeyAndName>().apply { maxWidth = Double.MAX_VALUE var defaultIndex = 0 items.addAll(TypeManager.allTypes.mapIndexed { index, type -> if (type == TypeManager.STRING) defaultIndex = index KeyAndName(type, getTypeTitle(type)) }) selectionModel.select(defaultIndex) } val nameField = TextField().apply { setOnKeyPressed { event -> @Suppress("NON_EXHAUSTIVE_WHEN") when (event.code) { KeyCode.UP -> { typeCombo.selectPreviousOrLast() event.consume() } KeyCode.DOWN -> { typeCombo.selectNextOrFirst() event.consume() } } } textProperty().addListener { _, _, text -> okButton.isDisable = text.isEmpty() || text in invalidKeys } } dialogPane.content = GridPane().apply { initAsForm( listOf( Label(tr("d.newVariant.name")), Label(tr("d.newVariant.type")) ), listOf( nameField, typeCombo ) ) } nameField.requestFocus() okButton.isDisable = true if (showAndWait().get() == ButtonType.OK) { val value = TypeManager.getDefault(typeCombo.selectionModel.selectedItem.key) variants += VariantItem(nameField.text.trim(), value?.also { valueRef += it } ?: "") table.selectionModel.apply { clearSelection() }.selectLast() table.scrollTo(table.items.size - 1) isModified = true } } } private fun removeItem(items: Collection<VariantItem>, showWarn: Boolean = false) { if (items.isEmpty()) return if (showWarn) { val hint = if (items.size == 1) { tr("d.removeVariant.oneHint", getItemTitle(items.first().key)) } else { tr("d.removeVariant.moreHint", items.size) } if (!confirm(tr("d.removeVariant.title"), hint)) { return } } for (item in items.toList()) { variants.remove(item) isModified = true } } private fun exportItem(item: VariantItem) { val value = item.data if (value is Flob) { val title = tr("d.exportItem.flob.title", item.key) selectSaveFile(title, value.name, scene.window)?.let { saveFlob(title, value, it, scene.window) } } else if (value is Text) { val title = tr("d.exportItem.text.title", item.key) selectSaveFile(title, "${item.key}.txt", scene.window)?.let { saveText(title, value, it, scene.window) } } } private inner class EditableDataCell : TableCell<VariantItem, Any>() { private var editor: Node? = null override fun updateItem(item: Any?, empty: Boolean) { super.updateItem(item, empty) when { empty -> { text = null graphic = null } isEditing -> { text = null graphic = editor?.apply { updateEditor(item!!) } } else -> { text = formatItemData(item!!) graphic = null } } } override fun startEdit() { if (isEmpty) return super.startEdit() createEditor(item) editor?.let { text = null graphic = it (it as? Region)?.maxWidth = Double.MAX_VALUE it.requestFocus() } } override fun cancelEdit() { super.cancelEdit() text = formatItemData(item) graphic = null } private fun createEditor(data: Any) { editor = null val key = variants[index].key when (data) { is CharSequence -> { if (isMultiValues(key)) { val str = data.toString().replace(Attributes.VALUE_SEPARATOR, "\n") text(tr("d.editVariant.title", getItemTitle(key)), initial = str, mustDiff = true, owner = scene.window)?.let { commitEdit(it.split("\n").filter { it.isNotEmpty() }.joinToString(Attributes.VALUE_SEPARATOR)) } cancelEdit() return } editor = getAvailableValues(key).ifNotEmpty { values -> ComboBox<String>().apply { isEditable = true items.setAll(values) editor.text = data.toString() setOnAction { commitEdit(selectionModel.selectedItem) } } } ?: TextField(data.toString()).apply { setOnAction { commitEdit(text) } focusedProperty().addListener { _, _, focused -> if (!focused) commitEdit(text) } } } is LocalDate -> { editor = DatePicker(data).apply { isShowWeekNumbers = true setOnAction { commitEdit(value) } editor.focusedProperty().addListener { _, _, focused -> if (!focused) commitEdit(converter.fromString(editor.text)) } } } is Locale -> { editor = LocalePicker(data).apply { setOnAction { commitEdit(value) } } } is Text -> { text(tr("d.editVariant.title", getItemTitle(key)), data.toString(), owner = scene.window)?.let { commitEdit(textOf(it)) } cancelEdit() } is Flob -> { selectOpenFile(tr("d.selectFile.title"), scene.window)?.let { commitEdit(flobOf(it)) } cancelEdit() } is Boolean -> { commitEdit(!data) } else -> { val type = data.javaClass if (type in ConverterManager) { editor = TextField(ConverterManager.render(data)).apply { setOnAction { try { commitEdit(ConverterManager.parse(text, type)) } catch (e: RuntimeException) { App.error("invalid value", e) } } focusedProperty().addListener { _, _, focused -> if (!focused) { try { commitEdit(ConverterManager.parse(text, type)) } catch (e: RuntimeException) { App.error("invalid value", e) } } } } } } } } private fun updateEditor(data: Any) { println("update editor for $data") val comp = editor when (comp) { is TextArea -> { comp.text = data.toString() } is DatePicker -> { comp.value = data as LocalDate } } } } }
apache-2.0
8305ecbebfdbe8dc24387f9374e63d21
36.829741
135
0.516835
5.199348
false
false
false
false
DreierF/MyTargets
shared/src/main/java/de/dreier/mytargets/shared/analysis/aggregation/cluster/ClusterStrategy.kt
1
4598
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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. */ package de.dreier.mytargets.shared.analysis.aggregation.cluster import de.dreier.mytargets.shared.analysis.aggregation.IAggregationResultRenderer import de.dreier.mytargets.shared.models.db.Shot import java.util.* class ClusterStrategy : AggregationStrategyBase() { private val clusters = ArrayList<Cluster>() override fun reset() { super.reset() clusters.clear() } /** * DBSCAN */ override fun compute(shots: List<Shot>): IAggregationResultRenderer { clusters.clear() val visited = HashMap<Shot, PointStatus>() for (point in shots) { if (isCancelled) { break } if (visited[point] != null) { continue } val neighbors = getNeighbors(point, shots) if (neighbors.size + 1 >= MINIMUM_POINTS_FOR_CLUSTER) { // DBSCAN does not care about center points val cluster = Cluster(shots.size) clusters.add(expandCluster(cluster, point, neighbors, shots, visited)) } else { visited[point] = PointStatus.NOISE } } val clusterResultRenderer = ClusterResultRenderer(clusters) clusterResultRenderer.onPrepareDraw() return clusterResultRenderer } /** * Expands the cluster to include density-reachable items. * * @param cluster Cluster to expand * @param point Point to add to cluster * @param neighbors List of neighbors * @param points the data set * @param visited the set of already visited points * @return the expanded cluster */ private fun expandCluster(cluster: Cluster, point: Shot, neighbors: List<Shot>, points: Collection<Shot>, visited: MutableMap<Shot, PointStatus>): Cluster { cluster.add(point) visited[point] = PointStatus.PART_OF_CLUSTER var seeds: MutableList<Shot> = ArrayList(neighbors) var index = 0 while (index < seeds.size) { val current = seeds[index] val pStatus = visited[current] // only check non-visited points if (pStatus == null) { val currentNeighbors = getNeighbors(current, points) if (currentNeighbors.size >= MINIMUM_POINTS_FOR_CLUSTER) { seeds = merge(seeds, currentNeighbors) } } if (pStatus != PointStatus.PART_OF_CLUSTER) { visited[current] = PointStatus.PART_OF_CLUSTER cluster.add(current) } index++ } return cluster } /** * Returns a list of density-reachable neighbors of a `point`. * * @param point the point to look for * @param points possible neighbors * @return the List of neighbors */ private fun getNeighbors(point: Shot, points: Collection<Shot>): List<Shot> { return points.filter { point != it && distanceFrom(it, point) <= EPS } } /** * Merges two lists together. * * @param one first list * @param two second list * @return merged lists */ private fun merge(one: MutableList<Shot>, two: List<Shot>): MutableList<Shot> { val oneSet = HashSet(one) two.filterNotTo(one) { oneSet.contains(it) } return one } private fun distanceFrom(p1: Shot, p2: Shot): Double { val diffX = (p1.x - p2.x).toDouble() val diffY = (p1.y - p2.y).toDouble() return Math.sqrt(diffX * diffX + diffY * diffY) } private enum class PointStatus { /** * The point has is considered to be noise. */ NOISE, /** * The point is already part of a cluster. */ PART_OF_CLUSTER } companion object { private const val EPS = 0.4 private const val MINIMUM_POINTS_FOR_CLUSTER = 2 } }
gpl-2.0
1f93a54901efef2bb17335d990359c0f
30.930556
86
0.58308
4.507843
false
false
false
false
SpectraLogic/ds3_java_browser
dsb-gui/src/main/java/com/spectralogic/dsbrowser/gui/services/jobService/PutJob.kt
1
5217
/* * **************************************************************************** * Copyright 2014-2018 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ package com.spectralogic.dsbrowser.gui.services.jobService import com.google.common.collect.ImmutableMap import com.spectralogic.ds3client.Ds3Client import com.spectralogic.ds3client.helpers.Ds3ClientHelpers import com.spectralogic.ds3client.metadata.MetadataAccessImpl import com.spectralogic.dsbrowser.api.services.logging.LogType import com.spectralogic.dsbrowser.gui.services.jobService.data.JobData import com.spectralogic.dsbrowser.gui.services.jobService.util.ChunkManagment import com.spectralogic.dsbrowser.gui.services.jobService.util.Stats import com.spectralogic.dsbrowser.gui.util.toByteRepresentation import io.reactivex.Completable import io.reactivex.Observable import org.slf4j.LoggerFactory import java.util.UUID import java.util.concurrent.TimeUnit class PutJob(private val putJobData: JobData) : JobService() { override fun getDs3Client(): Ds3Client = putJobData.client() private val chunkManagement: ChunkManagment = ChunkManagment() private val stats: Stats = Stats(message, putJobData.loggingService(), putJobData.dateTimeUtils()) private var wasCancelled = false private companion object { private val LOG = LoggerFactory.getLogger(GetJob::class.java) } override fun jobUUID(): UUID = putJobData.jobId override fun finishedCompletable(): Completable { return Completable.fromAction { val resources = prepare() transfer(resources) if (!wasCancelled) { tearDown() } } } private fun prepare(): Ds3ClientHelpers.Job { title.set(putJobData.internationalize("preparingJob")) val job: Ds3ClientHelpers.Job = putJobData.job LOG.info("Job ID is {}", job.jobId) totalJob.set(putJobData.jobSize()) val totalJobMessage: String = putJobData.jobSize().toByteRepresentation() if (putJobData.shouldRestoreFileAttributes()) { job.withMetadata(MetadataAccessImpl(ImmutableMap.copyOf(putJobData.prefixMap))) } job.attachFailureEventListener { event -> putJobData.loggingService().logMessage(event.toString(), LogType.ERROR) } job.attachDataTransferredListener { sent.set(it + sent.get()) stats.updateStatistics(putJobData.getStartTime(), sent, totalJob, totalJobMessage, putJobData.targetPath(), putJobData.bucket, false) } job.attachWaitingForChunksListener { chunkManagement.waitForChunks(it, putJobData.loggingService(), LOG) } job.attachObjectCompletedListener { stats.updateStatistics(putJobData.getStartTime(), sent, totalJob, totalJobMessage, putJobData.targetPath(), putJobData.bucket, true, it) } putJobData.saveJob(totalJob.get()) return job } private fun transfer(job: Ds3ClientHelpers.Job) { putJobData.setStartTime() title.set(putJobData.runningTitle()) putJobData.loggingService().logMessage(putJobData.internationalize("starting") + " PUT " + job.jobId, LogType.SUCCESS) job.transfer { transferName: String -> putJobData.getObjectChannelBuilder(transferName).buildChannel(transferName.removePrefix(putJobData.targetPath())) } } private fun tearDown() { if (totalJob.get() < 1) { totalJob.set(1L) sent.set(1L) } LOG.info("Job {} is in cache, waiting to complete", putJobData.job.jobId) message.set("In Cache, Waiting to complete") sent.set(totalJob.value) visible.bind(putJobData.showCachedJobProperty()) Observable.interval(60, TimeUnit.SECONDS) .takeUntil({ _ -> wasCancelled || putJobData.isCompleted() }) .retry { throwable -> putJobData.loggingService().logMessage("Error checking status of job " + jobUUID() + " will retry", LogType.ERROR) LOG.error("Unable to check status of job " + jobUUID(), throwable) when (throwable) { is IllegalStateException -> false else -> true } } .ignoreElements() .blockingAwait() sent.set(totalJob.value) putJobData.removeJob() } override fun cancel() { wasCancelled = true if (totalJob.get() < putJobData.jobSize()) { putJobData.job.cancel() } } }
apache-2.0
0bdbe837f889b928871edf9fcdd176cd
42.483333
148
0.652291
4.572305
false
false
false
false
seratch/jslack
slack-api-model-kotlin-extension/src/main/kotlin/com/slack/api/model/kotlin_extension/block/HeaderBlockBuilder.kt
1
652
package com.slack.api.model.kotlin_extension.block import com.slack.api.model.block.HeaderBlock import com.slack.api.model.block.composition.PlainTextObject @BlockLayoutBuilder class HeaderBlockBuilder : Builder<HeaderBlock> { private var blockId: String? = null private var _text: PlainTextObject? = null fun blockId(id: String) { blockId = id } fun text(text: String, emoji: Boolean? = null) { _text = PlainTextObject(text, emoji) } override fun build(): HeaderBlock { return HeaderBlock.builder() .blockId(blockId) .text(_text) .build() } }
mit
25bc837aa2a772c579684a120adaed50
25.12
60
0.642638
4
false
false
false
false
ssseasonnn/RxDownload
rxdownload4-manager/src/main/java/zlc/season/rxdownload4/manager/RxDownloadManager.kt
1
3811
package zlc.season.rxdownload4.manager import zlc.season.ironbranch.assertMainThreadWithResult import zlc.season.ironbranch.ensureMainThread import zlc.season.rxdownload4.DEFAULT_MAX_CONCURRENCY import zlc.season.rxdownload4.DEFAULT_RANGE_SIZE import zlc.season.rxdownload4.RANGE_CHECK_HEADER import zlc.season.rxdownload4.downloader.DefaultDispatcher import zlc.season.rxdownload4.downloader.Dispatcher import zlc.season.rxdownload4.request.Request import zlc.season.rxdownload4.request.RequestImpl import zlc.season.rxdownload4.storage.SimpleStorage import zlc.season.rxdownload4.storage.Storage import zlc.season.rxdownload4.task.Task import zlc.season.rxdownload4.validator.SimpleValidator import zlc.season.rxdownload4.validator.Validator import zlc.season.rxdownload4.watcher.Watcher import zlc.season.rxdownload4.watcher.WatcherImpl import java.io.File @JvmOverloads fun String.manager( header: Map<String, String> = RANGE_CHECK_HEADER, maxConCurrency: Int = DEFAULT_MAX_CONCURRENCY, rangeSize: Long = DEFAULT_RANGE_SIZE, dispatcher: Dispatcher = DefaultDispatcher, validator: Validator = SimpleValidator, storage: Storage = SimpleStorage, request: Request = RequestImpl, watcher: Watcher = WatcherImpl, notificationCreator: NotificationCreator = EmptyNotification, recorder: TaskRecorder = EmptyRecorder, taskLimitation: TaskLimitation = BasicTaskLimitation.of() ): TaskManager { return Task(this).manager( header = header, maxConCurrency = maxConCurrency, rangeSize = rangeSize, dispatcher = dispatcher, validator = validator, storage = storage, request = request, watcher = watcher, notificationCreator = notificationCreator, recorder = recorder, taskLimitation = taskLimitation ) } @JvmOverloads fun Task.manager( header: Map<String, String> = RANGE_CHECK_HEADER, maxConCurrency: Int = DEFAULT_MAX_CONCURRENCY, rangeSize: Long = DEFAULT_RANGE_SIZE, dispatcher: Dispatcher = DefaultDispatcher, validator: Validator = SimpleValidator, storage: Storage = SimpleStorage, request: Request = RequestImpl, watcher: Watcher = WatcherImpl, notificationCreator: NotificationCreator = EmptyNotification, recorder: TaskRecorder = EmptyRecorder, taskLimitation: TaskLimitation = BasicTaskLimitation.of() ): TaskManager { return TaskManagerPool.obtain( task = this, header = header, maxConCurrency = maxConCurrency, rangeSize = rangeSize, dispatcher = dispatcher, validator = validator, storage = storage, request = request, watcher = watcher, notificationCreator = notificationCreator, recorder = recorder, taskLimitation = taskLimitation ) } fun TaskManager.subscribe(function: (Status) -> Unit): Any { return assertMainThreadWithResult { val tag = Any() addCallback(tag, true, function) return@assertMainThreadWithResult tag } } fun TaskManager.dispose(tag: Any) { ensureMainThread { removeCallback(tag) } } fun TaskManager.currentStatus(): Status { return assertMainThreadWithResult { return@assertMainThreadWithResult currentStatus() } } fun TaskManager.start() { ensureMainThread { taskLimitation.start(this) } } fun TaskManager.stop() { ensureMainThread { taskLimitation.stop(this) } } fun TaskManager.delete() { ensureMainThread { taskLimitation.delete(this) } } fun TaskManager.file(): File { return getFile() }
apache-2.0
8141de19cc76e7854b85ef675bce5ba4
30.766667
69
0.68932
4.591566
false
false
false
false
paplorinc/intellij-community
platform/platform-impl/src/com/intellij/internal/statistic/utils/StatisticsUtil.kt
1
10379
// 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.internal.statistic.utils import com.intellij.ide.plugins.* import com.intellij.internal.statistic.beans.UsageDescriptor import com.intellij.internal.statistic.eventLog.EventLogConfiguration import com.intellij.internal.statistic.eventLog.newData import com.intellij.internal.statistic.service.fus.collectors.FUSUsageContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.project.Project import com.intellij.openapi.project.getProjectCacheFileName import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.Getter import com.intellij.openapi.util.ModificationTracker import com.intellij.psi.util.CachedValue import com.intellij.openapi.util.TimeoutCachedValue import com.intellij.util.containers.ObjectIntHashMap import gnu.trove.THashSet import java.io.IOException import java.util.* import java.util.concurrent.TimeUnit fun getProjectId(project: Project): String { return EventLogConfiguration.anonymize(project.getProjectCacheFileName()) } fun createData(project: Project?, context: FUSUsageContext?): Map<String, Any> { return newData(project, context) } fun isDevelopedByJetBrains(pluginId: PluginId?): Boolean { val plugin = PluginManager.getPlugin(pluginId) return plugin == null || PluginManagerMain.isDevelopedByJetBrains(plugin.vendor) } /** * Constructs a proper UsageDescriptor for a boolean value, * by adding "enabled" or "disabled" suffix to the given key, depending on the value. */ fun getBooleanUsage(key: String, value: Boolean): UsageDescriptor { return UsageDescriptor(key + if (value) ".enabled" else ".disabled", 1) } fun getEnumUsage(key: String, value: Enum<*>?): UsageDescriptor { return UsageDescriptor(key + "." + value?.name?.toLowerCase(Locale.ENGLISH), 1) } /** * Constructs a proper UsageDescriptor for a counting value. * If one needs to know a number of some items in the project, there is no direct way to report usages per-project. * Therefore this workaround: create several keys representing interesting ranges, and report that key which correspond to the range * which the given value belongs to. * * For example, to report a number of commits in Git repository, you can call this method like that: * ``` * val usageDescriptor = getCountingUsage("git.commit.count", listOf(0, 1, 100, 10000, 100000), realCommitCount) * ``` * and if there are e.g. 50000 commits in the repository, one usage of the following key will be reported: `git.commit.count.10K+`. * * NB: * (1) the list of steps must be sorted ascendingly; If it is not, the result is undefined. * (2) the value should lay somewhere inside steps ranges. If it is below the first step, the following usage will be reported: * `git.commit.count.<1`. * * @key The key prefix which will be appended with "." and range code. * @steps Limits of the ranges. Each value represents the start of the next range. The list must be sorted ascendingly. * @value Value to be checked among the given ranges. */ fun getCountingUsage(key: String, value: Int, steps: List<Int>) : UsageDescriptor { if (steps.isEmpty()) return UsageDescriptor("$key.$value", 1) if (value < steps[0]) return UsageDescriptor("$key.<${steps[0]}", 1) var stepIndex = 0 while (stepIndex < steps.size - 1) { if (value < steps[stepIndex + 1]) break stepIndex++ } val step = steps[stepIndex] val addPlus = stepIndex == steps.size - 1 || steps[stepIndex + 1] != step + 1 val stepName = humanize(step) + if (addPlus) "+" else "" return UsageDescriptor("$key.$stepName", 1) } /** * [getCountingUsage] with steps (0, 1, 2, 3, 5, 10, 15, 30, 50, 100, 500, 1000, 5000, 10000, ...) */ fun getCountingUsage(key: String, value: Int): UsageDescriptor { if (value > Int.MAX_VALUE / 10) return UsageDescriptor("$key.MANY", 1) if (value < 0) return UsageDescriptor("$key.<0", 1) if (value < 3) return UsageDescriptor("$key.$value", 1) val fixedSteps = listOf(3, 5, 10, 15, 30, 50) var step = fixedSteps.last { it <= value } while (true) { if (value < step * 2) break step *= 2 if (value < step * 5) break step *= 5 } val stepName = humanize(step) return UsageDescriptor("$key.$stepName+", 1) } private const val kilo = 1000 private val mega = kilo * kilo private fun humanize(number: Int): String { if (number == 0) return "0" val m = number / mega val k = (number % mega) / kilo val r = (number % kilo) val ms = if (m > 0) "${m}M" else "" val ks = if (k > 0) "${k}K" else "" val rs = if (r > 0) "${r}" else "" return ms + ks + rs } fun <T> addIfDiffers(set: MutableSet<in UsageDescriptor>, settingsBean: T, defaultSettingsBean: T, valueFunction: (T) -> Any, featureIdPrefix: String) { addIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction, { "$featureIdPrefix.$it" }) } fun <T, V> addIfDiffers(set: MutableSet<in UsageDescriptor>, settingsBean: T, defaultSettingsBean: T, valueFunction: (T) -> V, featureIdFunction: (V) -> String) { val value = valueFunction(settingsBean) val defaultValue = valueFunction(defaultSettingsBean) if (!Comparing.equal(value, defaultValue)) { set.add(UsageDescriptor(featureIdFunction(value), 1)) } } fun toUsageDescriptors(result: ObjectIntHashMap<String>): Set<UsageDescriptor> { if (result.isEmpty) { return emptySet() } else { val descriptors = THashSet<UsageDescriptor>(result.size()) result.forEachEntry { key, value -> descriptors.add(UsageDescriptor(key, value)) true } return descriptors } } fun merge(first: Set<UsageDescriptor>, second: Set<UsageDescriptor>): Set<UsageDescriptor> { if (first.isEmpty()) { return second } if (second.isEmpty()) { return first } val merged = ObjectIntHashMap<String>() addAll(merged, first) addAll(merged, second) return toUsageDescriptors(merged) } private fun addAll(result: ObjectIntHashMap<String>, usages: Set<UsageDescriptor>) { for (usage in usages) { val key = usage.key result.put(key, result.get(key, 0) + usage.value) } } private val safeToReportPluginIds: Getter<Set<String>> = TimeoutCachedValue(1, TimeUnit.HOURS) { val plugins = collectSafePluginDescriptors() val ids = mutableSetOf<String>() plugins.mapNotNullTo(ids) { descriptor: PluginDescriptor -> descriptor.pluginId?.idString } ids }; /** * We are safe to report only plugins which are developed by JetBrains or in our official plugin repository due to GDPR */ private fun collectSafePluginDescriptors(): List<IdeaPluginDescriptor> { // before loading default repository plugins lets check it's not changed, and is really official JetBrains repository if (ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) { try { val cached = RepositoryHelper.loadCachedPlugins() if (cached != null) { val plugins = ArrayList<IdeaPluginDescriptor>() plugins.addAll(cached) plugins.addAll(getBundledJetBrainsPluginDescriptors()) return plugins } else { // schedule plugins loading, will take them the next time ApplicationManager.getApplication().executeOnPooledThread { try { RepositoryHelper.loadPlugins(null) } catch (ignored: IOException) { } } return emptyList() //report nothing until repo plugins loaded } } catch (ignored: IOException) { } } return getBundledJetBrainsPluginDescriptors() } /** * Note that there may be private custom IDE build with bundled custom plugins; * so isBundled check is not enough */ private fun getBundledJetBrainsPluginDescriptors(): List<IdeaPluginDescriptor> { return PluginManager.getPlugins().filter { it.isBundled && PluginManagerMain.isDevelopedByJetBrains(it) }.toList() } /** * Checks this plugin is created by JetBrains or from official repository, so API from it may be reported */ fun isSafeToReportFrom(descriptor: IdeaPluginDescriptor?): Boolean { if (descriptor == null) { return false } if (isDevelopedByJetBrains(descriptor.pluginId)) { return true } // only plugins installed from some repository (not bundled and not provided via classpath in development IDE instance - // they are also considered bundled) would be reported return !descriptor.isBundled && isSafeToReport(descriptor.pluginId?.idString) } /** * Checks plugin with same id is created by JetBrains or from official repository, so pluginId may be reported. * * On the very first invocation may need to load cached plugins later; in that case no plugins are considered safe */ fun isSafeToReport(pluginId: String?): Boolean { return pluginId != null && safeToReportPluginIds.get().contains(pluginId) } /** * Returns if this code is coming from IntelliJ platform, a plugin created by JetBrains (bundled or not) or from official repository, * so API from it may be reported */ fun getPluginType(clazz: Class<*>): PluginType { val pluginId = PluginManagerCore.getPluginByClassName(clazz.name) ?: return PluginType.PLATFORM val plugin = PluginManager.getPlugin(pluginId) ?: return PluginType.UNKNOWN if (PluginManagerMain.isDevelopedByJetBrains(plugin)) { return if (plugin.isBundled) PluginType.JB_BUNDLED else PluginType.JB_NOT_BUNDLED } // only plugins installed from some repository (not bundled and not provided via classpath in development IDE instance - // they are also considered bundled) would be reported val listed = !plugin.isBundled && isSafeToReport(pluginId.idString) return if (listed) PluginType.LISTED else PluginType.NOT_LISTED } private class DelayModificationTracker internal constructor(delay: Long, unit: TimeUnit) : ModificationTracker { private val myStamp = System.currentTimeMillis() private val myDelay: Long = TimeUnit.MILLISECONDS.convert(delay, unit) override fun getModificationCount(): Long { val diff = System.currentTimeMillis() - (myStamp + myDelay) return if (diff > 0) diff else 0 } }
apache-2.0
33c848a5212b1f9704e7a73d9ae3aaed
36.741818
140
0.724058
4.181708
false
false
false
false
esafirm/android-playground
app/src/main/java/com/esafirm/androidplayground/ui/CommonRecyclerViews.kt
1
3798
package com.esafirm.androidplayground.ui.nestedrecyclerview import android.graphics.Color import android.view.View import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearSnapHelper import androidx.recyclerview.widget.RecyclerView import com.esafirm.androidplayground.utils.dp interface AdapterItem { fun bind(viewHolder: RecyclerView.ViewHolder) fun create(viewParent: ViewGroup?): RecyclerView.ViewHolder } class AbstractSingleItem( private val text: String, private val extraBind: (SingleViewHolder) -> Unit = {}, private val extraCreate: (SingleViewHolder) -> Unit = {} ) : AdapterItem { override fun bind(viewHolder: RecyclerView.ViewHolder) { viewHolder as SingleViewHolder viewHolder.textView.text = text extraBind.invoke(viewHolder) } override fun create(viewParent: ViewGroup?): RecyclerView.ViewHolder { val context = viewParent?.context val viewHolder = SingleViewHolder(TextView(context).apply { layoutParams = ViewGroup.MarginLayoutParams(MATCH_PARENT, WRAP_CONTENT).apply { setMargins(20.dp.toInt(), 16.dp.toInt(), 20.dp.toInt(), 16.dp.toInt()) } setTextColor(Color.BLACK) }) extraCreate.invoke(viewHolder) return viewHolder } } class SingleItem(private val text: String) : AdapterItem { override fun bind(viewHolder: RecyclerView.ViewHolder) { viewHolder as SingleViewHolder viewHolder.textView.text = text } override fun create(viewParent: ViewGroup?): RecyclerView.ViewHolder { val context = viewParent?.context return SingleViewHolder(TextView(context).apply { layoutParams = ViewGroup.MarginLayoutParams(MATCH_PARENT, WRAP_CONTENT).apply { setMargins(20.dp.toInt(), 16.dp.toInt(), 20.dp.toInt(), 16.dp.toInt()) } setTextColor(Color.BLACK) }) } } class SingleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val textView by lazy { itemView as TextView } } class HeadlineNewsItem(private val newsList: List<String>) : AdapterItem { override fun bind(viewHolder: RecyclerView.ViewHolder) { viewHolder as HeadlineNEwsViewHolder viewHolder.recyclerView.adapter = HorizontalRecyclerAdapter(newsList) } override fun create(viewParent: ViewGroup?): RecyclerView.ViewHolder { val context = viewParent?.context return HeadlineNEwsViewHolder(RecyclerView(context!!).apply { layoutParams = RecyclerView.LayoutParams(MATCH_PARENT, WRAP_CONTENT) layoutManager = LinearLayoutManager(context).apply { orientation = LinearLayoutManager.HORIZONTAL } LinearSnapHelper().attachToRecyclerView(this) }) } class HeadlineNEwsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val recyclerView by lazy { itemView as RecyclerView } } } class CommonAdapter( private val items: List<AdapterItem> ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return items.firstOrNull { it.javaClass.hashCode() == viewType }.let { it!!.create(parent) } } override fun getItemCount(): Int = items.size override fun getItemViewType(position: Int): Int { return items[position].javaClass.hashCode() } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { items[position].bind(holder) } }
mit
8d429831f7fae537bfc9fb24a540ed14
34.166667
111
0.707478
4.838217
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/insight/ListenerLineMarkerProvider.kt
1
5179
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.insight import com.demonwav.mcdev.MinecraftSettings import com.demonwav.mcdev.asset.GeneralAssets import com.demonwav.mcdev.util.gotoTargetElement import com.intellij.codeInsight.TargetElementUtil import com.intellij.codeInsight.daemon.GutterIconNavigationHandler import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProviderDescriptor import com.intellij.codeInsight.daemon.MergeableLineMarkerInfo import com.intellij.featureStatistics.FeatureUsageTracker import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiExpression import com.intellij.psi.PsiFunctionalExpression import com.intellij.psi.PsiMethod import com.intellij.psi.util.PsiExpressionTrimRenderer import com.intellij.psi.util.PsiUtilCore import com.intellij.util.Function import javax.swing.Icon /** * A [LineMarkerProviderDescriptor] that will provide a line marker info icon * in the gutter for annotated event listeners. This is intended to be written to be * platform independent of which Minecraft Platform API is being used. */ class ListenerLineMarkerProvider : LineMarkerProviderDescriptor() { override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? { if (!MinecraftSettings.instance.isShowEventListenerGutterIcons) { return null } val listener = element.eventListener ?: return null // By this point, we can guarantee that the action of "go to declaration" will work // since the PsiClass can be resolved, meaning the event listener is listening to // a valid event. return EventLineMarkerInfo( element, element.textRange, icon, createHandler(listener.second) ) } // This is a navigation handler that just simply goes and opens up the event's declaration, // even if the event target is a nested class. private fun createHandler(method: PsiMethod): GutterIconNavigationHandler<PsiElement> { return GutterIconNavigationHandler handler@{ _, element1 -> // We need to re-evaluate the targeted method, because if the method signature slightly changes before // IntelliJ decides to re-evaluate the method, but the class is no longer valid. // In this circumstance, we can find the class anyways because it's still a valid listener. val containingFile = element1.containingFile val parameter = method.eventParameterPair ?: return@handler val resolve = parameter.second val virtualFile = PsiUtilCore.getVirtualFile(resolve) if (virtualFile != null && containingFile != null) { val project = method.project val editor = FileEditorManager.getInstance(project).selectedTextEditor if (editor != null) { FeatureUsageTracker.getInstance().triggerFeatureUsed("navigation.goto.declaration") var navElement: PsiElement? = resolve.navigationElement navElement = TargetElementUtil.getInstance().getGotoDeclarationTarget(resolve, navElement) if (navElement != null) { gotoTargetElement(navElement, editor, containingFile) } } } } } override fun collectSlowLineMarkers(elements: List<PsiElement>, result: Collection<LineMarkerInfo<*>>) {} override fun getName() = "Event Listener line marker" override fun getIcon() = GeneralAssets.LISTENER private class EventLineMarkerInfo constructor( element: PsiElement, range: TextRange, icon: Icon, handler: GutterIconNavigationHandler<PsiElement> ) : MergeableLineMarkerInfo<PsiElement>( element, range, icon, Function { "Go to Event declaration" }, handler, GutterIconRenderer.Alignment.RIGHT ) { override fun canMergeWith(info: MergeableLineMarkerInfo<*>): Boolean { if (info !is EventLineMarkerInfo) { return false } val otherElement = info.getElement() val myElement = element return otherElement != null && myElement != null } override fun getCommonIcon(infos: List<MergeableLineMarkerInfo<*>>) = myIcon!! override fun getCommonTooltip(infos: List<MergeableLineMarkerInfo<*>>): Function<in PsiElement, String> = Function { "Multiple method overrides" } override fun getElementPresentation(element: PsiElement): String { val parent = element.parent if (parent is PsiFunctionalExpression) { return PsiExpressionTrimRenderer.render(parent as PsiExpression) } return super.getElementPresentation(element) } } }
mit
095ce8d5b63a441e95ca80d345dcddcb
39.460938
114
0.68855
5.434418
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/course_news/ui/adapter/delegate/CourseNewsAdapterDelegate.kt
1
11384
package org.stepik.android.view.course_news.ui.adapter.delegate import android.text.SpannableStringBuilder import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.core.text.bold import androidx.core.text.buildSpannedString import androidx.core.view.isVisible import androidx.recyclerview.widget.LinearLayoutManager import by.kirich1409.viewbindingdelegate.viewBinding import org.stepic.droid.R import org.stepic.droid.databinding.ItemAnnouncementBadgeBinding import org.stepic.droid.databinding.ItemCourseNewsBinding import org.stepic.droid.ui.util.setCompoundDrawables import org.stepic.droid.util.DateTimeHelper import org.stepik.android.domain.announcement.model.Announcement import org.stepik.android.domain.course_news.model.CourseNewsListItem import org.stepik.android.view.course_news.model.AnnouncementBadge import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder import ru.nobird.android.ui.adapterdelegates.dsl.adapterDelegate import ru.nobird.android.ui.adapters.DefaultDelegateAdapter import java.util.Date import java.util.TimeZone class CourseNewsAdapterDelegate( val isTeacher: Boolean ) : AdapterDelegate<CourseNewsListItem, DelegateViewHolder<CourseNewsListItem>>() { override fun isForViewType(position: Int, data: CourseNewsListItem): Boolean = data is CourseNewsListItem.Data override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CourseNewsListItem> = ViewHolder(createView(parent, R.layout.item_course_news)) private inner class ViewHolder(root: View) : DelegateViewHolder<CourseNewsListItem>(root) { private val viewBinding: ItemCourseNewsBinding by viewBinding { ItemCourseNewsBinding.bind(root) } private val badgesAdapter = DefaultDelegateAdapter<AnnouncementBadge>() init { badgesAdapter += adapterDelegate( layoutResId = R.layout.item_announcement_badge ) { val badgesBinding: ItemAnnouncementBadgeBinding = ItemAnnouncementBadgeBinding.bind(this.itemView) onBind { val textColor = ContextCompat.getColor(context, it.textColorRes) badgesBinding.root.setText(it.textRes) badgesBinding.root.setTextColor(textColor) badgesBinding.root.setBackgroundResource(it.backgroundRes) badgesBinding.root.setCompoundDrawables(start = it.compoundDrawableRes) } } } override fun onBind(data: CourseNewsListItem) { data as CourseNewsListItem.Data val isOneTimeEvent = !data.announcement.isInfinite && !data.announcement.onEnroll val isActiveEvent = data.announcement.onEnroll || (data.announcement.isInfinite && (data.announcement.startDate == null || data.announcement.startDate.time < DateTimeHelper.nowUtc())) with(viewBinding.newsBadges) { itemAnimator = null isNestedScrollingEnabled = false layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) adapter = badgesAdapter } viewBinding.newsBadges.isVisible = isTeacher badgesAdapter.items = buildBadgesList(data.announcement, isOneTimeEvent, isActiveEvent) viewBinding.newsDate.text = formatAnnouncementDate(data.announcement, isActiveEvent) viewBinding.newsSubject.text = data.announcement.subject viewBinding.newsText.setText(data.announcement.text) val mustShowStatistics = isTeacher && (data.announcement.status == Announcement.AnnouncementStatus.SCHEDULED || data.announcement.status == Announcement.AnnouncementStatus.SENT) val teacherInformation = if (mustShowStatistics) { buildSpannedString { data.announcement.publishCount?.let { appendCount(this, R.string.course_news_publish_count, it) } data.announcement.queueCount?.let { appendCount(this, R.string.course_news_queued_count, it) } data.announcement.sentCount?.let { appendCount(this, R.string.course_news_sent_count, it) } data.announcement.openCount?.let { appendCount(this, R.string.course_news_open_count, it) } data.announcement.clickCount?.let { appendCount(this, R.string.course_news_click_count, it, newline = false) } } } else { "" } viewBinding.newsStatistics.text = teacherInformation viewBinding.newsStatistics.isVisible = teacherInformation.isNotEmpty() } private fun appendCount(spannableStringBuilder: SpannableStringBuilder, stringRes: Int, count: Int, newline: Boolean = true) { with(spannableStringBuilder) { append(context.getString(stringRes)) bold { append(count.toString()) } if (newline) append("\n") } } private fun buildBadgesList(announcement: Announcement, isOneTimeEvent: Boolean, isActiveEvent: Boolean): List<AnnouncementBadge> { val statusBadge = when (announcement.status) { Announcement.AnnouncementStatus.COMPOSING -> AnnouncementBadge.COMPOSING Announcement.AnnouncementStatus.SCHEDULED -> if (isActiveEvent) { AnnouncementBadge.SENDING } else { AnnouncementBadge.SCHEDULED } Announcement.AnnouncementStatus.QUEUEING, Announcement.AnnouncementStatus.QUEUED, Announcement.AnnouncementStatus.SENDING -> AnnouncementBadge.SENDING Announcement.AnnouncementStatus.SENT, Announcement.AnnouncementStatus.ABORTED -> AnnouncementBadge.SENT } val eventBadge = if (isOneTimeEvent) { AnnouncementBadge.ONE_TIME } else { AnnouncementBadge.ON_EVENT } return listOf(statusBadge, eventBadge) } private fun formatAnnouncementDate(announcement: Announcement, isActiveEvent: Boolean): String { val defaultDate = (announcement.sentDate ?: announcement.createDate) ?: Date() val formattedDate = if (!isTeacher) { if (isActiveEvent && announcement.noticeDates.lastOrNull() != null) { formatDateTimePattern(announcement.noticeDates.last()) } else { null } } else { when (announcement.status) { Announcement.AnnouncementStatus.COMPOSING -> { announcement.displayedStartDate?.let { displayedStartDate -> val formattedStartDate = formatDateTimePattern(displayedStartDate) if (isActiveEvent) { context.getString( R.string.course_news_on_event_composing, formattedStartDate ) } else { formattedStartDate } } } Announcement.AnnouncementStatus.SCHEDULED -> { announcement.displayedStartDate?.let { displayedStartDate -> val formattedStartDate = formatDateTimePattern(displayedStartDate) if (isActiveEvent) { context.getString( R.string.course_news_on_event_sending, formattedStartDate ) } else { context.getString( R.string.course_news_one_time_scheduled, formattedStartDate ) } } } Announcement.AnnouncementStatus.QUEUEING, Announcement.AnnouncementStatus.QUEUED, Announcement.AnnouncementStatus.SENDING -> { announcement.displayedStartDate?.let { displayedStartDate -> val formattedStartDate = formatDateTimePattern(displayedStartDate) if (isActiveEvent) { context.getString( R.string.course_news_on_event_sending, formattedStartDate ) } else { context.getString( R.string.course_news_one_time_sending, formattedStartDate ) } } } Announcement.AnnouncementStatus.SENT, Announcement.AnnouncementStatus.ABORTED -> { announcement.displayedStartDate?.let { displayedStartDate -> val formattedStartDate = formatDateTimePattern(displayedStartDate) if (isActiveEvent) { announcement.displayedFinishDate?.let { displayedFinishDate -> context.getString( R.string.course_news_on_event_sent, formattedStartDate, formatDateTimePattern(displayedFinishDate) ) } } else { formattedStartDate } } } } } return formattedDate ?: formatDateTimePattern(defaultDate) } private fun formatDateTimePattern(date: Date): String = DateTimeHelper.getPrintableDate(date, DateTimeHelper.DISPLAY_DATETIME_COMMA_PATTERN, TimeZone.getDefault()) } }
apache-2.0
4111b2bafe064f9b2b4376b886b43300
47.862661
149
0.532765
6.388328
false
false
false
false
allotria/intellij-community
plugins/ide-features-trainer/src/training/dsl/impl/LessonExecutorUtil.kt
2
7866
// 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 training.dsl.impl import com.intellij.openapi.application.invokeLater import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.ui.UIBundle import com.intellij.ui.awt.RelativePoint import com.intellij.util.Alarm import icons.FeaturesTrainerIcons import training.dsl.LearningBalloonConfig import training.dsl.TaskContext import training.dsl.TaskRuntimeContext import training.learn.ActionsRecorder import training.learn.LearnBundle import training.learn.lesson.LessonManager import training.ui.LearningUiHighlightingManager import training.ui.LessonMessagePane import training.ui.MessageFactory import training.ui.UISettings import java.awt.Component import java.awt.Dimension import java.awt.Point import java.awt.event.ActionEvent import java.util.concurrent.CompletableFuture import java.util.concurrent.Future import javax.swing.* import javax.swing.border.EmptyBorder internal data class TaskProperties(var hasDetection: Boolean = false, var messagesNumber: Int = 0) internal object LessonExecutorUtil { /** This task is a real task with some event required and corresponding text. Used for progress indication. */ fun taskProperties(taskContent: TaskContext.() -> Unit, project: Project): TaskProperties { val fakeTaskContext = ExtractTaskPropertiesContext(project) taskContent(fakeTaskContext) return TaskProperties(fakeTaskContext.hasDetection, fakeTaskContext.textCount) } fun textMessages(taskContent: TaskContext.() -> Unit, project: Project): List<String> { val fakeTaskContext = ExtractTextTaskContext(project) taskContent(fakeTaskContext) return fakeTaskContext.messages } fun showBalloonMessage(text: String, ui: JComponent, balloonConfig: LearningBalloonConfig, actionsRecorder: ActionsRecorder, project: Project) { val messages = MessageFactory.convert(text) val messagesPane = LessonMessagePane(false) messagesPane.setBounds(0, 0, balloonConfig.width.takeIf { it != 0 } ?: 500, 1000) messagesPane.isOpaque = false messagesPane.addMessage(messages) val preferredSize = messagesPane.preferredSize messagesPane.toolTipText = LearnBundle.message("learn.stop.hint") val balloonPanel = JPanel() balloonPanel.border = EmptyBorder(8, 8, 8, 8) balloonPanel.isOpaque = false balloonPanel.layout = BoxLayout(balloonPanel, BoxLayout.Y_AXIS) var height = preferredSize.height + 16 val width = (if (balloonConfig.width != 0) balloonConfig.width else (preferredSize.width + 6)) + 16 balloonPanel.add(messagesPane) val gotItCallBack = balloonConfig.gotItCallBack val gotItButton = if (gotItCallBack != null) JButton().also { balloonPanel.add(it) it.action = object : AbstractAction(UIBundle.message("got.it")) { override fun actionPerformed(e: ActionEvent?) { gotItCallBack() } } it.isSelected = true it.isFocusable = true height += it.preferredSize.height } else null gotItButton?.isSelected = true balloonPanel.preferredSize = Dimension(width, height) val balloon = JBPopupFactory.getInstance().createBalloonBuilder(balloonPanel) .setCloseButtonEnabled(false) .setAnimationCycle(0) .setHideOnAction(false) .setHideOnClickOutside(false) .setBlockClicksThroughBalloon(true) .setFillColor(UISettings.instance.backgroundColor) .setBorderColor(UISettings.instance.activeTaskBorder) .setHideOnCloseClick(false) .setDisposable(actionsRecorder) .setCloseButtonEnabled(true) .createBalloon() balloon.addListener(object : JBPopupListener { override fun onClosed(event: LightweightWindowEvent) { val checkStopLesson = { invokeLater { if (actionsRecorder.disposed) return@invokeLater val yesNo = Messages.showYesNoDialog(project, LearnBundle.message("learn.stop.lesson.question"), LearnBundle.message("learn.stop.lesson"), FeaturesTrainerIcons.Img.PluginIcon) if (yesNo == Messages.YES) { invokeLater { LessonManager.instance.stopLesson() } } else { if (actionsRecorder.disposed) return@invokeLater showBalloonMessage(text, ui, balloonConfig, actionsRecorder, project) } } } Alarm().addRequest(checkStopLesson, 500) // it is a hacky a little bit } }) balloon.show(getPosition(ui, balloonConfig.side), balloonConfig.side) gotItButton?.requestFocus() } private fun getPosition(component: JComponent, side: Balloon.Position): RelativePoint { val visibleRect = LearningUiHighlightingManager.getRectangle(component) ?: component.visibleRect val xShift = when (side) { Balloon.Position.atLeft -> 0 Balloon.Position.atRight -> visibleRect.width Balloon.Position.above, Balloon.Position.below -> visibleRect.width / 2 else -> error("Unexpected balloon position") } val yShift = when (side) { Balloon.Position.above -> 0 Balloon.Position.below -> visibleRect.height Balloon.Position.atLeft, Balloon.Position.atRight -> visibleRect.height / 2 else -> error("Unexpected balloon position") } val point = Point(visibleRect.x + xShift, visibleRect.y + yShift) return RelativePoint(component, point) } } private class ExtractTaskPropertiesContext(override val project: Project) : TaskContext() { var textCount = 0 var hasDetection = false override fun text(text: String, useBalloon: LearningBalloonConfig?) { if (useBalloon?.duplicateMessage == false) return textCount++ } override fun trigger(actionId: String) { hasDetection = true } override fun trigger(checkId: (String) -> Boolean) { hasDetection = true } override fun <T> trigger(actionId: String, calculateState: TaskRuntimeContext.() -> T, checkState: TaskRuntimeContext.(T, T) -> Boolean) { hasDetection = true } override fun triggerStart(actionId: String, checkState: TaskRuntimeContext.() -> Boolean) { hasDetection = true } override fun triggers(vararg actionIds: String) { hasDetection = true } override fun stateCheck(checkState: TaskRuntimeContext.() -> Boolean): CompletableFuture<Boolean> { hasDetection = true return CompletableFuture<Boolean>() } override fun <T : Any> stateRequired(requiredState: TaskRuntimeContext.() -> T?): Future<T> { hasDetection = true return CompletableFuture() } override fun addFutureStep(p: DoneStepContext.() -> Unit) { hasDetection = true } override fun addStep(step: CompletableFuture<Boolean>) { hasDetection = true } @Suppress("OverridingDeprecatedMember") override fun triggerByUiComponentAndHighlight(findAndHighlight: TaskRuntimeContext.() -> () -> Component) { hasDetection = true } override fun action(actionId: String): String = "" //Doesn't matter what to return override fun code(sourceSample: String): String = "" //Doesn't matter what to return override fun strong(text: String): String = "" //Doesn't matter what to return override fun icon(icon: Icon): String = "" //Doesn't matter what to return } private class ExtractTextTaskContext(override val project: Project) : TaskContext() { val messages = ArrayList<String>() override fun text(text: String, useBalloon: LearningBalloonConfig?) { if (useBalloon?.duplicateMessage == false) return messages.add(text) } }
apache-2.0
7879ab2a740ed77a3e7ba8a9aa343bc3
36.279621
187
0.729596
4.557358
false
true
false
false
allotria/intellij-community
plugins/github/src/org/jetbrains/plugins/github/ui/component/GHAccountSelectorComponentFactory.kt
2
7406
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.ui.component import com.intellij.ide.ui.laf.darcula.DarculaUIUtil import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.ui.popup.list.ComboBoxPopup import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.util.ui.cloneDialog.AccountMenuItem import com.intellij.util.ui.cloneDialog.AccountMenuItemRenderer import com.intellij.util.ui.cloneDialog.VcsCloneDialogUiSpec import com.intellij.util.ui.codereview.avatar.CachingAvatarIconsProvider import org.jetbrains.plugins.github.GithubIcons import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.accounts.GithubAccountInformationProvider import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.ui.util.GHUIUtil import org.jetbrains.plugins.github.ui.util.getName import org.jetbrains.plugins.github.util.CachingGHUserAvatarLoader import org.jetbrains.plugins.github.util.submitIOTask import java.awt.* import java.awt.event.KeyEvent import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.util.concurrent.CompletableFuture import javax.swing.* import javax.swing.border.Border import javax.swing.event.ListDataEvent import javax.swing.event.ListDataListener class GHAccountSelectorComponentFactory { fun create(model: ComboBoxWithActionsModel<GithubAccount>): JComponent { val label = JLabel().apply { isOpaque = false cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) isFocusable = true border = FocusBorder() } Controller(model, label) return label } class FocusBorder : Border { override fun paintBorder(c: Component?, g: Graphics?, x: Int, y: Int, width: Int, height: Int) { if (c?.hasFocus() == true && g is Graphics2D) { DarculaUIUtil.paintFocusBorder(g, width, height, 0f, true) } } override fun getBorderInsets(c: Component): Insets { val g2d = c.graphics as? Graphics2D ?: return JBUI.emptyInsets() val bw = if (UIUtil.isUnderDefaultMacTheme()) JBUIScale.scale(3).toFloat() else DarculaUIUtil.BW.float val f = if (UIUtil.isRetina(g2d)) 0.5f else 1.0f val lw = if (UIUtil.isUnderDefaultMacTheme()) JBUIScale.scale(f) else DarculaUIUtil.LW.float val insets = (bw + lw).toInt() return Insets(insets, insets, insets, insets) } override fun isBorderOpaque() = false } class Controller(private val accountsModel: ComboBoxWithActionsModel<GithubAccount>, private val label: JLabel) : ComboBoxPopup.Context<ComboBoxWithActionsModel.Item<GithubAccount>> { private val avatarsProvider = AccountAvatarIconsProvider() private var popup: ComboBoxPopup<*>? = null init { accountsModel.addListDataListener(object : ListDataListener { override fun contentsChanged(e: ListDataEvent) = updateLabel() override fun intervalAdded(e: ListDataEvent?) = updateLabel() override fun intervalRemoved(e: ListDataEvent?) = updateLabel() }) label.addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent?) = showPopup() }) label.registerPopupOnKeyboardShortcut(KeyEvent.VK_ENTER) label.registerPopupOnKeyboardShortcut(KeyEvent.VK_SPACE) updateLabel() } private fun updateLabel() { val selectedAccount = accountsModel.selectedItem?.wrappee with(label) { isVisible = accountsModel.items.isNotEmpty() icon = avatarsProvider.getIcon(selectedAccount, GHUIUtil.AVATAR_SIZE) toolTipText = selectedAccount?.name ?: GithubBundle.message("account.choose.link") } } private fun showPopup() { popup = object : ComboBoxPopup<ComboBoxWithActionsModel.Item<GithubAccount>>(this, accountsModel.selectedItem, { accountsModel.setSelectedItem(it) }) { //otherwise component borders are overridden override fun getListElementRenderer() = renderer }.apply { //TODO: remove speedsearch addListener(object : JBPopupListener { override fun onClosed(event: LightweightWindowEvent) { popup = null } }) showUnderneathOf(label) } } private fun JComponent.registerPopupOnKeyboardShortcut(keyCode: Int) { registerKeyboardAction({ showPopup() }, KeyStroke.getKeyStroke(keyCode, 0), JComponent.WHEN_FOCUSED) } override fun getProject(): Project? = null override fun getModel(): ListModel<ComboBoxWithActionsModel.Item<GithubAccount>> = accountsModel override fun getRenderer(): ListCellRenderer<ComboBoxWithActionsModel.Item<GithubAccount>> = PopupItemRenderer(avatarsProvider) } private class PopupItemRenderer(private val avatarsProvider: AccountAvatarIconsProvider) : ListCellRenderer<ComboBoxWithActionsModel.Item<GithubAccount>> { private val delegateRenderer = AccountMenuItemRenderer() override fun getListCellRendererComponent(list: JList<out ComboBoxWithActionsModel.Item<GithubAccount>>?, value: ComboBoxWithActionsModel.Item<GithubAccount>, index: Int, selected: Boolean, focused: Boolean): Component { val item = when (value) { is ComboBoxWithActionsModel.Item.Wrapper<GithubAccount> -> value.wrappee.let { account -> val icon = avatarsProvider.getIcon(account, VcsCloneDialogUiSpec.Components.popupMenuAvatarSize) val serverAddress = account.server.toString() AccountMenuItem.Account(account.name, serverAddress, icon) } is ComboBoxWithActionsModel.Item.Action<GithubAccount> -> value.action.let { AccountMenuItem.Action(it.getName(), {}, showSeparatorAbove = value.needSeparatorAbove) } } return delegateRenderer.getListCellRendererComponent(null, item, index, selected, focused) } } private class AccountAvatarIconsProvider : CachingAvatarIconsProvider<GithubAccount>( GithubIcons.DefaultAvatar) { private val requestExecutorManager = GithubApiRequestExecutorManager.getInstance() private val accountInformationProvider = GithubAccountInformationProvider.getInstance() private val avatarLoader = CachingGHUserAvatarLoader.getInstance() override fun loadImage(key: GithubAccount): Image? { val executor = requestExecutorManager.getExecutor(key) return ProgressManager.getInstance().submitIOTask(EmptyProgressIndicator()) { accountInformationProvider.getInformation(executor, it, key) }.thenCompose { val url = it.avatarUrl ?: return@thenCompose CompletableFuture.completedFuture(null) avatarLoader.requestAvatar(executor, url) }.get() } } }
apache-2.0
5bbd11a6c77584f86243e42bdd8b27ec
42.315789
140
0.729004
4.987205
false
false
false
false
allotria/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/grammar/GrammarChecker.kt
2
8318
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.grazie.grammar import com.intellij.grazie.grammar.ide.GraziePsiElementProcessor import com.intellij.grazie.grammar.ide.GraziePsiElementProcessor.ElementShift import com.intellij.grazie.grammar.ide.GraziePsiElementProcessor.TokenInfo import com.intellij.grazie.grammar.strategy.GrammarCheckingStrategy import com.intellij.grazie.grammar.strategy.StrategyUtils import com.intellij.grazie.utils.length import com.intellij.grazie.utils.toPointer import com.intellij.psi.PsiElement import com.intellij.refactoring.suggested.startOffset import java.util.* import kotlin.collections.ArrayList object GrammarChecker { private data class ShiftInText(val start: Int, val length: Int, val totalDeleted: Int) private fun GrammarCheckingStrategy.determineStealthyRanges(textsWithRoots: List<GraziePsiElementProcessor.Companion.RootWithText>): Pair<StringBuilder, List<IntRange>> { val resultText = StringBuilder() val ranges = ArrayList<IntRange>() var offset = 0 for ((root, text) in textsWithRoots) { ranges.addAll(getStealthyRanges(root, text).map { IntRange(it.start + offset, it.endInclusive + offset) }) resultText.append(text) offset += text.length } return resultText to ranges.sortedWith(Comparator.comparingInt { it.start }) } private fun determineTextShifts(textsWithRoots: List<GraziePsiElementProcessor.Companion.RootWithText>, strategy: GrammarCheckingStrategy, shifts: List<ElementShift>): Pair<StringBuilder, ArrayList<ShiftInText>> { fun ArrayList<ShiftInText>.addShift(position: Int, length: Int, totalDeleted: Int) { if (isNotEmpty() && last().start == position) { val last = removeAt(size - 1) // combine shifts from same position add(ShiftInText(position, last.length + length, last.totalDeleted + length)) } else { add(ShiftInText(position, length, totalDeleted)) } } val result = ArrayList<ShiftInText>() var stealthed = 0 // count of newly removed characters from text after getResultedShifts() var total = 0 // total deleted chars from text val iterator = shifts.listIterator() // Iterate over ignored ranges determined by PsiElement behaviour and // ranges determined by strategy.getStealthyRanges, which working with text // while combining intersecting ranges val (text, ranges) = strategy.determineStealthyRanges(textsWithRoots) for (range in ranges) { var deleted = 0 for ((position, length) in iterator) { if (position < range.start) { // shift before range (remains the same, just add) result.addShift(position - stealthed, length, total + length) } else if (position in range) { // shift inside range (combine in one) deleted += length } else { // shift after range - need a step back iterator.previous() break } total += length } // delete text from stealthy ranges (we need stealthed to track offset in text) text.delete(range.start - stealthed, range.endInclusive + 1 - stealthed) total += range.length result.addShift(range.start - stealthed, deleted + range.length, total) stealthed += range.length } // after processing all ranges there still can be shifts after them for ((position, length) in iterator) { total += length result.addShift(position, length, total) } return text to result } fun check(roots: List<PsiElement>, strategy: GrammarCheckingStrategy): Set<Typo> { val (parent, tokens, shifts, texts) = GraziePsiElementProcessor.processElements(roots, strategy) if (tokens.isEmpty()) return emptySet() val (text, textShifts) = determineTextShifts(texts, strategy, shifts) val offset = StrategyUtils.trimLeadingQuotesAndSpaces(text) return check(parent, roots, text, textShifts, offset, tokens, strategy) } private fun findPositionInsideParent(position: Int, shifts: List<ShiftInText>): Int { val index = shifts.binarySearch { it.start.compareTo(position) } return when { index >= 0 -> shifts[index].totalDeleted -(index + 1) > 0 -> shifts[-(index + 1) - 1].totalDeleted else -> 0 } + position } private fun findTextRangesToDelete(rangeInRoot: IntRange, rangeInText: IntRange, shifts: List<ShiftInText>) = ArrayList<IntRange>().apply { var start = rangeInRoot.start // take all shifts inside typo and invert them shifts.filter { it.start > rangeInText.start && it.start <= rangeInText.endInclusive }.forEach { shift -> add(IntRange(start, shift.start + shift.totalDeleted - shift.length - 1)) start = shift.start + shift.totalDeleted } add(IntRange(start, rangeInRoot.endInclusive + 1)) } private fun findTokensInTypoPatternRange(tokens: Collection<TokenInfo>, patternRangeInRoot: IntRange): List<TokenInfo> { return tokens.filter { it.range.endInclusive >= patternRangeInRoot.start && it.range.start <= patternRangeInRoot.endInclusive }.also { check(it.isNotEmpty()) { "No tokens for range in typo: $patternRangeInRoot in ${tokens.map { token -> token.range }}" } } } private fun findRootInParentContainingRange(parent: PsiElement, roots: List<PsiElement>, rangeInParent: IntRange): PsiElement? { return roots.map { val start = it.startOffset - parent.startOffset it to IntRange(start, start + it.textLength) }.find { it.second.start < rangeInParent.start && it.second.endInclusive <= rangeInParent.endInclusive }?.first } private fun check(parent: PsiElement, roots: List<PsiElement>, text: StringBuilder, shifts: List<ShiftInText>, offset: Int, tokens: Collection<TokenInfo>, strategy: GrammarCheckingStrategy) = GrammarEngine.getTypos(text.toString(), offset = offset).mapNotNull { typo -> val rangeInText = typo.location.errorRange val rangeInParent = rangeInText.convertToRangeInParent(shifts) val textRangesToDelete = findTextRangesToDelete(rangeInParent, rangeInText, shifts) val patternRangeInParent = typo.location.patternRange.convertToRangeInParent(shifts) val tokensInTypoPatternRange = findTokensInTypoPatternRange(tokens, patternRangeInParent) val root = findRootInParentContainingRange(parent, roots, rangeInParent) val isTypoAccepted = if (root == null) { strategy.isTypoAccepted(parent, roots, rangeInParent, patternRangeInParent) } else { strategy.isTypoAccepted( root, rangeInParent.convertToRangeInRoot(root, parent), patternRangeInParent.convertToRangeInRoot(root, parent) ) && strategy.isTypoAccepted(parent, roots, rangeInParent, patternRangeInParent) } val category = typo.category when { !isTypoAccepted -> null // typo not accepted by strategy tokensInTypoPatternRange.any { token -> token.behavior == GrammarCheckingStrategy.ElementBehavior.ABSORB || // typo pattern in absorb element category in token.ignoredCategories || // typo rule in ignored category typo.info.rule.id in token.ignoredGroup.rules // typo rule in ignored group } -> null else -> typo.copy( location = typo.location.copy(errorRange = rangeInParent, patternRange = patternRangeInParent, textRanges = textRangesToDelete, pointer = parent.toPointer()) ) } }.toSet() private fun IntRange.convertToRangeInParent(shifts: List<ShiftInText>): IntRange { return IntRange(findPositionInsideParent(start, shifts), findPositionInsideParent(endInclusive, shifts)) } private fun IntRange.convertToRangeInRoot(root: PsiElement, parent: PsiElement): IntRange { val offset = (root.startOffset - parent.startOffset) return IntRange(start - offset, endInclusive - offset) } }
apache-2.0
e78bb87cc5132f45208723f36c5e0f83
45.211111
140
0.688146
4.488937
false
false
false
false
jiro-aqua/vertical-text-viewer
vtextview/src/main/java/jp/gr/aqua/vjap/VChar.kt
1
3715
package jp.gr.aqua.vjap data class VChar(val str : String? = null , val char : Char = '\u0000' , val idx : Int = -1) { val length : Int get() = (str?.length?:1) val asString: String get() = str?:char.toString() val firstChar : Char get() = str?.get(0)?:char fun isLineBreak() : Boolean = char == '\n' fun isLatin() : Boolean = '\u0000' < char && char < '\u0080' fun isLatinString() : Boolean { val ch = if ( str != null ){ str[0] } else{ char } return '\u0000' < ch && ch < '\u0080' } fun isGyoumatuKinsoku() : Boolean = KINSOKU_GYOUMATU.contains(char) fun isGyoutouKinsoku() : Boolean = KINSOKU_GYOUTOU.contains(char) fun isBurasageKinsoku() : Boolean = KINSOKU_BURASAGE.contains(char) fun isRubyMarkup(ruby:Ruby) : Boolean = str?.let{ruby.isRubyMarkup(str)}?:false fun isExclamation() : Boolean = char == '!' || char == '!' fun isQuestion() : Boolean = char == '?' || char == '?' fun isEmpty() : Boolean = str?.isEmpty() ?: char=='\u0000' fun isNotEmpty() : Boolean = !isEmpty() fun isKanji() : Boolean = isNotEmpty() && ( Character.UnicodeBlock.of(firstChar) === java.lang.Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || this.equals("々") || this.equals("〆") || this.equals("仝") || this.equals("〇") || this.equals("ヶ") ) override fun equals(other: Any?) : Boolean{ return if ( other is VChar ) { if (this.str != null && other.str != null) { this.str == other.str } else if (this.str != null && other.str == null) { if (this.str.length == 1) { this.firstChar == other.char } else { false } } else if (this.str == null && other.str != null) { if (other.str.length == 1) { this.char == other.firstChar } else { false } } else { this.char == other.char } }else if ( other is String ){ if (this.str != null ) { this.str == other } else { if (other.length == 1) { other[0] == this.char }else{ false } } }else{ false } } fun kind() : Int { val ch = firstChar if (ch in '0'..'9') return 1 if (ch in 'A'..'Z') return 2 if (ch in 'a'..'z') return 2 return 0 } fun isHalfAlNum() : Boolean = kind() != 0 override fun hashCode(): Int { return super.hashCode() } operator fun plus(next : VChar) : VChar{ return VChar(this.asString + next.asString) } operator fun plus(next : String) : VChar{ return VChar(this.asString + next) } companion object{ private const val KINSOKU_BURASAGE = ",、。.  " private const val KINSOKU_GYOUTOU = ",)]}、〕〉》」』】〙〗〟’”⦆»)" + "ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇳㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻"+ "‐゠–〜~"+ "?!?!‼⁇⁈⁉"+ "・:;。.  " private const val KINSOKU_GYOUMATU = "([{〔〈《「『【〘〖〝‘“⦅«" //private val KANJI_INKCLUDE = "々仝〆〇ヶ" // 青空文庫では漢字じゃないけどルビ判定で漢字とみなす文字 } override fun toString(): String { return this.asString } }
apache-2.0
0dea7997a56b84434705635590973ffe
31.271028
121
0.484217
3.122061
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/src/flow/operators/Zip.kt
1
11618
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:JvmMultifileClass @file:JvmName("FlowKt") @file:Suppress("UNCHECKED_CAST", "NON_APPLICABLE_CALL_FOR_BUILDER_INFERENCE") // KT-32203 package kotlinx.coroutines.flow import kotlinx.coroutines.flow.internal.* import kotlin.jvm.* import kotlinx.coroutines.flow.flow as safeFlow import kotlinx.coroutines.flow.internal.unsafeFlow as flow /** * Returns a [Flow] whose values are generated with [transform] function by combining * the most recently emitted values by each flow. * * It can be demonstrated with the following example: * ``` * val flow = flowOf(1, 2).onEach { delay(10) } * val flow2 = flowOf("a", "b", "c").onEach { delay(15) } * flow.combine(flow2) { i, s -> i.toString() + s }.collect { * println(it) // Will print "1a 2a 2b 2c" * } * ``` * * This function is a shorthand for `flow.combineTransform(flow2) { a, b -> emit(transform(a, b)) } */ @JvmName("flowCombine") public fun <T1, T2, R> Flow<T1>.combine(flow: Flow<T2>, transform: suspend (a: T1, b: T2) -> R): Flow<R> = flow { combineInternal(arrayOf(this@combine, flow), nullArrayFactory(), { emit(transform(it[0] as T1, it[1] as T2)) }) } /** * Returns a [Flow] whose values are generated with [transform] function by combining * the most recently emitted values by each flow. * * It can be demonstrated with the following example: * ``` * val flow = flowOf(1, 2).onEach { delay(10) } * val flow2 = flowOf("a", "b", "c").onEach { delay(15) } * combine(flow, flow2) { i, s -> i.toString() + s }.collect { * println(it) // Will print "1a 2a 2b 2c" * } * ``` * * This function is a shorthand for `combineTransform(flow, flow2) { a, b -> emit(transform(a, b)) } */ public fun <T1, T2, R> combine(flow: Flow<T1>, flow2: Flow<T2>, transform: suspend (a: T1, b: T2) -> R): Flow<R> = flow.combine(flow2, transform) /** * Returns a [Flow] whose values are generated by [transform] function that process the most recently emitted values by each flow. * * The receiver of the [transform] is [FlowCollector] and thus `transform` is a * generic function that may transform emitted element, skip it or emit it multiple times. * * Its usage can be demonstrated with the following example: * ``` * val flow = requestFlow() * val flow2 = searchEngineFlow() * flow.combineTransform(flow2) { request, searchEngine -> * emit("Downloading in progress") * val result = download(request, searchEngine) * emit(result) * } * ``` */ @JvmName("flowCombineTransform") public fun <T1, T2, R> Flow<T1>.combineTransform( flow: Flow<T2>, @BuilderInference transform: suspend FlowCollector<R>.(a: T1, b: T2) -> Unit ): Flow<R> = combineTransformUnsafe(this, flow) { args: Array<*> -> transform( args[0] as T1, args[1] as T2 ) } /** * Returns a [Flow] whose values are generated by [transform] function that process the most recently emitted values by each flow. * * The receiver of the [transform] is [FlowCollector] and thus `transform` is a * generic function that may transform emitted element, skip it or emit it multiple times. * * Its usage can be demonstrated with the following example: * ``` * val flow = requestFlow() * val flow2 = searchEngineFlow() * combineTransform(flow, flow2) { request, searchEngine -> * emit("Downloading in progress") * val result = download(request, searchEngine) * emit(result) * } * ``` */ public fun <T1, T2, R> combineTransform( flow: Flow<T1>, flow2: Flow<T2>, @BuilderInference transform: suspend FlowCollector<R>.(a: T1, b: T2) -> Unit ): Flow<R> = combineTransformUnsafe(flow, flow2) { args: Array<*> -> transform( args[0] as T1, args[1] as T2 ) } /** * Returns a [Flow] whose values are generated with [transform] function by combining * the most recently emitted values by each flow. */ public fun <T1, T2, T3, R> combine( flow: Flow<T1>, flow2: Flow<T2>, flow3: Flow<T3>, @BuilderInference transform: suspend (T1, T2, T3) -> R ): Flow<R> = combineUnsafe(flow, flow2, flow3) { args: Array<*> -> transform( args[0] as T1, args[1] as T2, args[2] as T3 ) } /** * Returns a [Flow] whose values are generated by [transform] function that process the most recently emitted values by each flow. * * The receiver of the [transform] is [FlowCollector] and thus `transform` is a * generic function that may transform emitted element, skip it or emit it multiple times. */ public fun <T1, T2, T3, R> combineTransform( flow: Flow<T1>, flow2: Flow<T2>, flow3: Flow<T3>, @BuilderInference transform: suspend FlowCollector<R>.(T1, T2, T3) -> Unit ): Flow<R> = combineTransformUnsafe(flow, flow2, flow3) { args: Array<*> -> transform( args[0] as T1, args[1] as T2, args[2] as T3 ) } /** * Returns a [Flow] whose values are generated with [transform] function by combining * the most recently emitted values by each flow. */ public fun <T1, T2, T3, T4, R> combine( flow: Flow<T1>, flow2: Flow<T2>, flow3: Flow<T3>, flow4: Flow<T4>, transform: suspend (T1, T2, T3, T4) -> R ): Flow<R> = combineUnsafe(flow, flow2, flow3, flow4) { args: Array<*> -> transform( args[0] as T1, args[1] as T2, args[2] as T3, args[3] as T4 ) } /** * Returns a [Flow] whose values are generated by [transform] function that process the most recently emitted values by each flow. * * The receiver of the [transform] is [FlowCollector] and thus `transform` is a * generic function that may transform emitted element, skip it or emit it multiple times. */ public fun <T1, T2, T3, T4, R> combineTransform( flow: Flow<T1>, flow2: Flow<T2>, flow3: Flow<T3>, flow4: Flow<T4>, @BuilderInference transform: suspend FlowCollector<R>.(T1, T2, T3, T4) -> Unit ): Flow<R> = combineTransformUnsafe(flow, flow2, flow3, flow4) { args: Array<*> -> transform( args[0] as T1, args[1] as T2, args[2] as T3, args[3] as T4 ) } /** * Returns a [Flow] whose values are generated with [transform] function by combining * the most recently emitted values by each flow. */ public fun <T1, T2, T3, T4, T5, R> combine( flow: Flow<T1>, flow2: Flow<T2>, flow3: Flow<T3>, flow4: Flow<T4>, flow5: Flow<T5>, transform: suspend (T1, T2, T3, T4, T5) -> R ): Flow<R> = combineUnsafe(flow, flow2, flow3, flow4, flow5) { args: Array<*> -> transform( args[0] as T1, args[1] as T2, args[2] as T3, args[3] as T4, args[4] as T5 ) } /** * Returns a [Flow] whose values are generated by [transform] function that process the most recently emitted values by each flow. * * The receiver of the [transform] is [FlowCollector] and thus `transform` is a * generic function that may transform emitted element, skip it or emit it multiple times. */ public fun <T1, T2, T3, T4, T5, R> combineTransform( flow: Flow<T1>, flow2: Flow<T2>, flow3: Flow<T3>, flow4: Flow<T4>, flow5: Flow<T5>, @BuilderInference transform: suspend FlowCollector<R>.(T1, T2, T3, T4, T5) -> Unit ): Flow<R> = combineTransformUnsafe(flow, flow2, flow3, flow4, flow5) { args: Array<*> -> transform( args[0] as T1, args[1] as T2, args[2] as T3, args[3] as T4, args[4] as T5 ) } /** * Returns a [Flow] whose values are generated with [transform] function by combining * the most recently emitted values by each flow. */ public inline fun <reified T, R> combine( vararg flows: Flow<T>, crossinline transform: suspend (Array<T>) -> R ): Flow<R> = flow { combineInternal(flows, { arrayOfNulls(flows.size) }, { emit(transform(it)) }) } /** * Returns a [Flow] whose values are generated by [transform] function that process the most recently emitted values by each flow. * * The receiver of the [transform] is [FlowCollector] and thus `transform` is a * generic function that may transform emitted element, skip it or emit it multiple times. */ public inline fun <reified T, R> combineTransform( vararg flows: Flow<T>, @BuilderInference crossinline transform: suspend FlowCollector<R>.(Array<T>) -> Unit ): Flow<R> = safeFlow { combineInternal(flows, { arrayOfNulls(flows.size) }, { transform(it) }) } /* * Same as combine, but does not copy array each time, deconstructing existing * array each time. Used in overloads that accept FunctionN instead of Function<Array<R>> */ private inline fun <reified T, R> combineUnsafe( vararg flows: Flow<T>, crossinline transform: suspend (Array<T>) -> R ): Flow<R> = flow { combineInternal(flows, nullArrayFactory(), { emit(transform(it)) }) } /* * Same as combineTransform, but does not copy array each time, deconstructing existing * array each time. Used in overloads that accept FunctionN instead of Function<Array<R>> */ private inline fun <reified T, R> combineTransformUnsafe( vararg flows: Flow<T>, @BuilderInference crossinline transform: suspend FlowCollector<R>.(Array<T>) -> Unit ): Flow<R> = safeFlow { combineInternal(flows, nullArrayFactory(), { transform(it) }) } // Saves bunch of anonymous classes private fun <T> nullArrayFactory(): () -> Array<T>? = { null } /** * Returns a [Flow] whose values are generated with [transform] function by combining * the most recently emitted values by each flow. */ public inline fun <reified T, R> combine( flows: Iterable<Flow<T>>, crossinline transform: suspend (Array<T>) -> R ): Flow<R> { val flowArray = flows.toList().toTypedArray() return flow { combineInternal( flowArray, arrayFactory = { arrayOfNulls(flowArray.size) }, transform = { emit(transform(it)) }) } } /** * Returns a [Flow] whose values are generated by [transform] function that process the most recently emitted values by each flow. * * The receiver of the [transform] is [FlowCollector] and thus `transform` is a * generic function that may transform emitted element, skip it or emit it multiple times. */ public inline fun <reified T, R> combineTransform( flows: Iterable<Flow<T>>, @BuilderInference crossinline transform: suspend FlowCollector<R>.(Array<T>) -> Unit ): Flow<R> { val flowArray = flows.toList().toTypedArray() return safeFlow { combineInternal(flowArray, { arrayOfNulls(flowArray.size) }, { transform(it) }) } } /** * Zips values from the current flow (`this`) with [other] flow using provided [transform] function applied to each pair of values. * The resulting flow completes as soon as one of the flows completes and cancel is called on the remaining flow. * * It can be demonstrated with the following example: * ``` * val flow = flowOf(1, 2, 3).onEach { delay(10) } * val flow2 = flowOf("a", "b", "c", "d").onEach { delay(15) } * flow.zip(flow2) { i, s -> i.toString() + s }.collect { * println(it) // Will print "1a 2b 3c" * } * ``` * * ### Buffering * * The upstream flow is collected sequentially in the same coroutine without any buffering, while the * [other] flow is collected concurrently as if `buffer(0)` is used. See documentation in the [buffer] operator * for explanation. You can use additional calls to the [buffer] operator as needed for more concurrency. */ public fun <T1, T2, R> Flow<T1>.zip(other: Flow<T2>, transform: suspend (T1, T2) -> R): Flow<R> = zipImpl(this, other, transform)
apache-2.0
e102a230d5a6291ef21d45f73a3d0e7a
34.099698
131
0.660096
3.403046
false
false
false
false
leafclick/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/checkin/CodeAnalysisBeforeCheckinShowOnlyNew.kt
1
4936
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.checkin import com.intellij.codeInsight.CodeSmellInfo import com.intellij.diff.tools.util.text.LineOffsetsUtil import com.intellij.diff.util.Range import com.intellij.openapi.application.ReadAction import com.intellij.openapi.application.WriteAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.Document import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.CodeSmellDetector import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.changes.ChangesUtil import com.intellij.openapi.vcs.changes.VcsPreservingExecutor import com.intellij.openapi.vcs.ex.compareLines import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.impl.PsiDocumentManagerImpl import com.intellij.util.containers.MultiMap import gnu.trove.THashMap internal object CodeAnalysisBeforeCheckinShowOnlyNew { val LOG = logger<CodeAnalysisBeforeCheckinShowOnlyNew>() @JvmStatic fun runAnalysis(project: Project, selectedFiles: List<VirtualFile>, progressIndicator: ProgressIndicator) : List<CodeSmellInfo> { progressIndicator.isIndeterminate = false val codeSmellDetector = CodeSmellDetector.getInstance(project) val newCodeSmells = codeSmellDetector.findCodeSmells(selectedFiles) val location2CodeSmell = MultiMap<Pair<VirtualFile, Int>, CodeSmellInfo>() val fileToChanges: MutableMap<VirtualFile, List<Range>> = THashMap() val changeListManager = ChangeListManager.getInstance(project) val files4Update = ChangesUtil.getFilesFromChanges(changeListManager.allChanges) val fileDocumentManager = FileDocumentManager.getInstance() newCodeSmells.forEach { codeSmellInfo -> val virtualFile = fileDocumentManager.getFile(codeSmellInfo.document) ?: return@forEach val unchanged = fileToChanges.getOrPut(virtualFile) { try { val contentFromVcs = changeListManager.getChange(virtualFile)?.beforeRevision?.content ?: return@getOrPut emptyList() val documentContent = codeSmellInfo.document.immutableCharSequence compareLines(documentContent, contentFromVcs, LineOffsetsUtil.create(documentContent), LineOffsetsUtil.create(contentFromVcs)).iterateUnchanged().toList() } catch (e: VcsException) { LOG.warn("Couldn't load content", e) emptyList() } } val startLine = codeSmellInfo.startLine val range = unchanged.firstOrNull { it.start1 <= startLine && startLine < it.end1 } ?: return@forEach location2CodeSmell.putValue(Pair(virtualFile, range.start2 + startLine - range.start1), codeSmellInfo) } val commonCodeSmells = HashSet<CodeSmellInfo>() runAnalysisAfterShelvingSync(project, selectedFiles, progressIndicator) { VfsUtil.markDirtyAndRefresh(false, false, false, *files4Update) WriteAction.runAndWait<Exception> { PsiDocumentManagerImpl.getInstance(project).commitAllDocuments() } codeSmellDetector.findCodeSmells(selectedFiles.filter { it.exists() }).forEach { oldCodeSmell -> val file = fileDocumentManager.getFile(oldCodeSmell.document) ?: return@forEach location2CodeSmell[Pair(file, oldCodeSmell.startLine)].forEach inner@{ newCodeSmell -> if (oldCodeSmell.description == newCodeSmell.description) { commonCodeSmells.add(newCodeSmell) return@inner } } } } return newCodeSmells.filter { !commonCodeSmells.contains(it) }.map { val file = fileDocumentManager.getFile(it.document) ?: return@map it if (file.isValid) { return@map it } val newFile = VirtualFileManager.getInstance().findFileByUrl(file.url) ?: return@map it val document = ReadAction.compute<Document?, Exception> { fileDocumentManager.getDocument(newFile) } ?: return@map it CodeSmellInfo(document, it.description, it.textRange, it.severity) } } private fun runAnalysisAfterShelvingSync(project: Project, files: List<VirtualFile>, progressIndicator: ProgressIndicator, afterShelve: () -> Unit) { val versionedRoots = files.mapNotNull { ProjectLevelVcsManager.getInstance(project).getVcsRootFor(it) }.toSet() val message = VcsBundle.message("searching.for.code.smells.freezing.process") VcsPreservingExecutor.executeOperation(project, versionedRoots, message, progressIndicator) { afterShelve() } } }
apache-2.0
3002f840723a33502613d942c7a2fd25
52.663043
152
0.764587
4.737044
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/ranges/contains/inOptimizableLongRange.kt
2
946
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS // WITH_RUNTIME fun check(x: Long, left: Long, right: Long): Boolean { val result = x in left..right val manual = x >= left && x <= right val range = left..right assert(result == manual) { "Failed: optimized === manual for $range" } assert(result == checkUnoptimized(x, range)) { "Failed: optimized === unoptimized for $range" } return result } fun checkUnoptimized(x: Long, range: ClosedRange<Long>): Boolean { return x in range } fun box(): String { assert(check(1L, 0L, 2L)) assert(!check(1L, -1L, 0L)) assert(!check(239L, 239L, 238L)) assert(check(239L, 238L, 239L)) assert(check(Long.MIN_VALUE, Long.MIN_VALUE, Long.MIN_VALUE)) assert(check(Long.MAX_VALUE, Long.MIN_VALUE, Long.MAX_VALUE)) var value = 0L assert(++value in 1L..1L) assert(++value !in 1L..1L) return "OK" }
apache-2.0
f1627dc670d3e54d10d49d7a61769877
28.5625
99
0.641649
3.185185
false
false
false
false
aconsuegra/algorithms-playground
src/main/kotlin/me/consuegra/algorithms/KMultiplyIntArray.kt
1
1096
package me.consuegra.algorithms /** * Given an array of integers, return an array in which each position is the result of multiplying all other entries * in the array * <p> * Examples: * [1,2,3,4] -> [24,12,8,6] * [6,-4,0,5] -> [0,0,-120,0] */ class KMultiplyIntArray { fun multiplyIntArrayOption1(input: IntArray) : IntArray { val result = IntArray(input.size) for (i in 0 until input.size) { var product = 1 (0 until input.size) .filter { i != it } .forEach { product *= input[it] } result[i] = product } return result } fun multiplyIntArrayOption2(input: IntArray) : IntArray { val result = IntArray(input.size) var leftProduct = 1 for (i in 0 until input.size) { result[i] = leftProduct leftProduct *= input[i] } var rightProduct = 1 for (i in input.size - 1 downTo 0) { result[i] *= rightProduct rightProduct *= input[i] } return result } }
mit
8b1f89b84493740cbae8d130af940ba5
24.488372
116
0.538321
3.845614
false
false
false
false
byoutline/kickmaterial
app/src/androidTest/java/com/byoutline/kickmaterial/espressohelpers/DaggerRules.kt
1
3644
package com.byoutline.kickmaterial.espressohelpers import android.app.Activity import android.app.Application import android.os.Handler import android.os.Looper import android.support.test.InstrumentationRegistry import android.support.test.espresso.Espresso import android.support.test.espresso.IdlingRegistry import android.support.test.espresso.base.DefaultFailureHandler import android.support.test.rule.ActivityTestRule import com.byoutline.cachedfield.CachedFieldWithArg import com.byoutline.cachedfield.utils.CachedFieldIdlingResource import com.byoutline.kickmaterial.KickMaterialApp import com.byoutline.kickmaterial.dagger.AppComponent import com.byoutline.kickmaterial.features.projectlist.MainActivity import com.squareup.spoon.Spoon import org.junit.rules.ExternalResource import org.junit.runner.Description import org.junit.runners.model.Statement import kotlin.reflect.KClass /** * Methods returning custom [ActivityTestRule]s that set test [AppComponent]. * @author Sebastian Kacprzak <sebastian.kacprzak at byoutline.com> */ object DaggerRules { fun userFirstLaunchRule(): ActivityTestRule<MainActivity> = getActivityRule({ TestComponents.getFirstRunComponent(it) }, MainActivity::class) fun userNextLaunchRule(): ActivityTestRule<MainActivity> = getActivityRule({ TestComponents.getNextRunComponent(it) }, MainActivity::class) fun idlingResourceDiscoverField() = CachedFieldIdlingResourceRule(KickMaterialApp.component.discoverField) private fun <ACTIVITY : Activity> getActivityRule( mainComponentProv: (KickMaterialApp) -> AppComponent, clazz: KClass<ACTIVITY> ): ActivityTestRule<ACTIVITY> { val mainHandler = Handler(Looper.getMainLooper()) return DaggerActivityTestRule(clazz.java, beforeActivityLaunchedAction = { application -> val app = application as KickMaterialApp val globalComponent = mainComponentProv(app) mainHandler.post { app.setComponents(globalComponent) } }) } } class DaggerActivityTestRule<T : Activity>( activityClass: Class<T>, initialTouchMode: Boolean = false, launchActivity: Boolean = true, private val beforeActivityLaunchedAction: (Application) -> Unit = {} ) : ActivityTestRule<T>(activityClass, initialTouchMode, launchActivity) { override fun beforeActivityLaunched() { super.beforeActivityLaunched() beforeActivityLaunchedAction(InstrumentationRegistry.getInstrumentation() .targetContext.applicationContext as Application) } override fun apply(base: Statement, description: Description): Statement { // On Ci take screenshot if test fails if (System.getenv("CIRCLECI") != null) { Espresso.setFailureHandler { error, viewMatcher -> Spoon.screenshot(activity, error.javaClass.simpleName, description.className, description.methodName) DefaultFailureHandler(activity).handle(error, viewMatcher) } } return super.apply(base, description) } } class CachedFieldIdlingResourceRule(private val cachedFieldWithArg: CachedFieldWithArg<*, *>) : ExternalResource() { private lateinit var cachedFieldIdlingResource: CachedFieldIdlingResource @Throws(Throwable::class) override fun before() { cachedFieldIdlingResource = CachedFieldIdlingResource.from(cachedFieldWithArg) IdlingRegistry.getInstance().register(cachedFieldIdlingResource) } override fun after() { IdlingRegistry.getInstance().unregister(cachedFieldIdlingResource) } }
apache-2.0
01f41b5b76b94ddc65b11743bc9e4684
39.488889
117
0.751647
5.026207
false
true
false
false
aconsuegra/algorithms-playground
src/main/kotlin/me/consuegra/algorithms/KMaximumSubarray.kt
1
641
package me.consuegra.algorithms /** * Find the contiguous subarray within an array (containing at least one number) which has the largest sum. * <p> * For example, given the array [-2,1,-3,4,-1,2,1,-5,4], * the contiguous subarray [4,-1,2,1] has the largest sum = 6. */ class KMaximumSubarray { fun maxSubarray(input: IntArray) : Int { var maxSum = Integer.MIN_VALUE var acc = 0 input.forEach { num -> acc += num if (maxSum < acc) { maxSum = acc } if (acc < 0) { acc = 0 } } return maxSum } }
mit
83e178a2e9304b8f1bd5f3cb58315a29
23.653846
107
0.519501
3.642045
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/CommonSdkLookupBuilder.kt
12
3771
// 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.roots.ui.configuration import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.SdkType import com.intellij.openapi.projectRoots.impl.UnknownSdkFixAction import com.intellij.openapi.util.NlsContexts.ProgressTitle internal data class CommonSdkLookupBuilder( override val project: Project? = null, @ProgressTitle override val progressMessageTitle: String? = null, override val progressIndicator: ProgressIndicator? = null, override val sdkName: String? = null, override val sdkType: SdkType? = null, override val onDownloadingSdkDetected : (Sdk) -> SdkLookupDownloadDecision = { SdkLookupDownloadDecision.WAIT }, override val onBeforeSdkSuggestionStarted: () -> SdkLookupDecision = { SdkLookupDecision.CONTINUE }, override val onLocalSdkSuggested: (UnknownSdkLocalSdkFix) -> SdkLookupDecision = { SdkLookupDecision.CONTINUE }, override val onDownloadableSdkSuggested: (UnknownSdkDownloadableSdkFix) -> SdkLookupDecision = { SdkLookupDecision.CONTINUE }, override val onSdkFixResolved : (UnknownSdkFixAction) -> SdkLookupDecision = { SdkLookupDecision.CONTINUE }, override val sdkHomeFilter: ((String) -> Boolean)? = null, override val versionFilter: ((String) -> Boolean)? = null, override val testSdkSequence: Sequence<Sdk?> = emptySequence(), override val onSdkNameResolved: (Sdk?) -> Unit = { }, override val onSdkResolved: (Sdk?) -> Unit = { }, private val lookup: (CommonSdkLookupBuilder) -> Unit ) : SdkLookupBuilder, SdkLookupParameters { override fun withProject(project: Project?) = copy(project = project) override fun withProgressMessageTitle(@ProgressTitle message: String) = copy(progressMessageTitle = message) override fun withSdkName(name: String) = copy(sdkName = name) override fun withSdkType(sdkType: SdkType) = copy(sdkType = sdkType) override fun withVersionFilter(filter: (String) -> Boolean) = copy(versionFilter = filter) override fun withSdkHomeFilter(filter: (String) -> Boolean) = copy(sdkHomeFilter = filter) override fun onDownloadingSdkDetected(handler: (Sdk) -> SdkLookupDownloadDecision) = copy(onDownloadingSdkDetected = handler) override fun withProgressIndicator(indicator: ProgressIndicator) = copy(progressIndicator = indicator) override fun testSuggestedSdksFirst(sdks: Sequence<Sdk?>) = copy(testSdkSequence = testSdkSequence + sdks) override fun testSuggestedSdkFirst(sdk: () -> Sdk?) = copy(testSdkSequence = testSdkSequence + generateSequence(sdk) { null }) override fun onBeforeSdkSuggestionStarted(handler: () -> SdkLookupDecision) = copy(onBeforeSdkSuggestionStarted = handler) override fun onLocalSdkSuggested(handler: (UnknownSdkLocalSdkFix) -> SdkLookupDecision) = copy(onLocalSdkSuggested = handler) override fun onSdkFixResolved(handler: (UnknownSdkFixAction) -> SdkLookupDecision) = copy(onSdkFixResolved = handler) override fun onDownloadableSdkSuggested(handler: (UnknownSdkDownloadableSdkFix) -> SdkLookupDecision) = copy(onDownloadableSdkSuggested = handler) override fun onSdkResolved(handler: (Sdk?) -> Unit) = copy(onSdkResolved = this.onSdkResolved + handler) override fun onSdkNameResolved(handler: (Sdk?) -> Unit) = copy(onSdkNameResolved = this.onSdkNameResolved + handler) override fun executeLookup() = lookup(this) @JvmName("plusTUnit") private operator fun <T> ( (T) -> Unit).plus(v : (T) -> Unit) : (T) -> Unit = { this(it) v(it) } }
apache-2.0
30663f8de846089f7c9381bfe5f9be15
39.548387
140
0.757359
4.478622
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/hierarchy/calls/callers/kotlinPackageFunction/main0.kt
13
386
fun <caret>packageFun(s: String): String = s val packageVal = packageFun("") class KClient { init { packageFun("") } companion object { val a = packageFun("") } val bar: String get() = packageFun("") fun bar() { fun localFun() = packageFun("") packageFun("") } } object KClientObj { val a = packageFun("") }
apache-2.0
2c5049531e6a4dcf9b63acfb8e0c864a
13.884615
44
0.523316
3.86
false
false
false
false
siosio/intellij-community
plugins/kotlin/frontend-api/src/org/jetbrains/kotlin/idea/frontend/api/ReadActionConfinementValidityToken.kt
2
2768
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.frontend.api import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import org.jetbrains.kotlin.trackers.createProjectWideOutOfBlockModificationTracker class ReadActionConfinementValidityToken(project: Project) : ValidityToken() { private val modificationTracker = project.createProjectWideOutOfBlockModificationTracker() private val onCreatedTimeStamp = modificationTracker.modificationCount override fun isValid(): Boolean { return onCreatedTimeStamp == modificationTracker.modificationCount } @OptIn(HackToForceAllowRunningAnalyzeOnEDT::class) override fun getInvalidationReason(): String { if (onCreatedTimeStamp != modificationTracker.modificationCount) return "PSI has changed since creation" error("Getting invalidation reason for valid validity token") } @OptIn(HackToForceAllowRunningAnalyzeOnEDT::class) override fun isAccessible(): Boolean { val application = ApplicationManager.getApplication() if (application.isDispatchThread && !allowOnEdt.get()) return false if (!application.isReadAccessAllowed) return false return true } @OptIn(HackToForceAllowRunningAnalyzeOnEDT::class) override fun getInaccessibilityReason(): String { val application = ApplicationManager.getApplication() if (application.isDispatchThread && !allowOnEdt.get()) return "Called in EDT thread" if (!application.isReadAccessAllowed) return "Called outside read action" error("Getting inaccessibility reason for validity token when it is accessible") } companion object { @HackToForceAllowRunningAnalyzeOnEDT val allowOnEdt: ThreadLocal<Boolean> = ThreadLocal.withInitial { false } } } @RequiresOptIn("All frontend related work should not be allowed to be ran from EDT thread. Only use it as a temporary solution") annotation class HackToForceAllowRunningAnalyzeOnEDT /** * All frontend related work should not be allowed to be ran from EDT thread. Only use it as a temporary solution. * * @see KtAnalysisSession * @see ReadActionConfinementValidityToken */ @HackToForceAllowRunningAnalyzeOnEDT inline fun <T> hackyAllowRunningOnEdt(action: () -> T): T { if (ReadActionConfinementValidityToken.allowOnEdt.get()) return action() ReadActionConfinementValidityToken.allowOnEdt.set(true) try { return action() } finally { ReadActionConfinementValidityToken.allowOnEdt.set(false) } }
apache-2.0
d85003c378d61fc28d1307bbdb5490f3
40.954545
128
0.760477
5.005425
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/ExtractionEngine.kt
1
5107
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageType import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.ui.awt.RelativePoint import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively import org.jetbrains.kotlin.idea.refactoring.introduce.showErrorHint import org.jetbrains.kotlin.idea.util.ProgressIndicatorUtils import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.nonBlocking import org.jetbrains.kotlin.utils.addToStdlib.cast import org.jetbrains.kotlin.utils.addToStdlib.safeAs import javax.swing.event.HyperlinkEvent abstract class ExtractionEngineHelper(val operationName: String) { open fun adjustExtractionData(data: ExtractionData): ExtractionData = data fun doRefactor(config: ExtractionGeneratorConfiguration, onFinish: (ExtractionResult) -> Unit = {}) { val project = config.descriptor.extractionData.project onFinish(project.executeWriteCommand<ExtractionResult>(operationName) { config.generateDeclaration() }) } open fun validate(descriptor: ExtractableCodeDescriptor): ExtractableCodeDescriptorWithConflicts = descriptor.validate() abstract fun configureAndRun( project: Project, editor: Editor, descriptorWithConflicts: ExtractableCodeDescriptorWithConflicts, onFinish: (ExtractionResult) -> Unit = {} ) } class ExtractionEngine( val helper: ExtractionEngineHelper ) { fun run( editor: Editor, extractionData: ExtractionData, onFinish: (ExtractionResult) -> Unit = {} ) { val project = extractionData.project val adjustExtractionData = helper.adjustExtractionData(extractionData) val analysisResult = ProgressIndicatorUtils.underModalProgress(project, KotlinBundle.message("progress.title.analyze.extraction.data") ) { adjustExtractionData.performAnalysis() } if (ApplicationManager.getApplication()!!.isUnitTestMode && analysisResult.status != AnalysisResult.Status.SUCCESS) { throw BaseRefactoringProcessor.ConflictsInTestsException(analysisResult.messages.map { it.renderMessage() }) } fun validateAndRefactor() { nonBlocking(project, { try { helper.validate(analysisResult.descriptor!!) } catch (e: RuntimeException) { ExtractableCodeDescriptorWithException(e) } }) { result -> result.safeAs<ExtractableCodeDescriptorWithException>()?.let { throw it.exception } val validationResult = result.cast<ExtractableCodeDescriptorWithConflicts>() project.checkConflictsInteractively(validationResult.conflicts) { helper.configureAndRun(project, editor, validationResult) { try { onFinish(it) } finally { it.dispose() extractionData.dispose() } } } } } val message = analysisResult.messages.joinToString("\n") { it.renderMessage() } when (analysisResult.status) { AnalysisResult.Status.CRITICAL_ERROR -> { showErrorHint(project, editor, message, helper.operationName) } AnalysisResult.Status.NON_CRITICAL_ERROR -> { val anchorPoint = RelativePoint( editor.contentComponent, editor.visualPositionToXY(editor.selectionModel.selectionStartPosition!!) ) JBPopupFactory.getInstance()!! .createHtmlTextBalloonBuilder( "$message<br/><br/><a href=\"EXTRACT\">${KotlinBundle.message("text.proceed.with.extraction")}</a>", MessageType.WARNING ) { event -> if (event?.eventType == HyperlinkEvent.EventType.ACTIVATED) { validateAndRefactor() } } .setHideOnClickOutside(true) .setHideOnFrameResize(false) .setHideOnLinkClick(true) .createBalloon() .show(anchorPoint, Balloon.Position.below) } AnalysisResult.Status.SUCCESS -> validateAndRefactor() } } }
apache-2.0
918c921bfb639524e9f23a9269feda8c
43.408696
158
0.63736
5.706145
false
true
false
false
JetBrains/kotlin-native
runtime/src/main/kotlin/kotlin/coroutines/intrinsics/IntrinsicsNative.kt
2
11044
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package kotlin.coroutines.intrinsics import kotlin.coroutines.* import kotlin.coroutines.native.internal.* import kotlin.native.internal.* /** * Starts an unintercepted coroutine without a receiver and with result type [T] and executes it until its first suspension. * Returns the result of the coroutine or throws its exception if it does not suspend or [COROUTINE_SUSPENDED] if it suspends. * In the latter case, the [completion] continuation is invoked when the coroutine completes with a result or an exception. * * The coroutine is started directly in the invoker's thread without going through the [ContinuationInterceptor] that might * be present in the completion's [CoroutineContext]. It is the invoker's responsibility to ensure that a proper invocation * context is established. * * This function is designed to be used from inside of [suspendCoroutineUninterceptedOrReturn] to resume the execution of the suspended * coroutine using a reference to the suspending function. */ @Suppress("UNCHECKED_CAST") @kotlin.internal.InlineOnly public actual inline fun <T> (suspend () -> T).startCoroutineUninterceptedOrReturn( completion: Continuation<T> ): Any? = (this as Function1<Continuation<T>, Any?>).invoke(completion) /** * Starts an unintercepted coroutine with receiver type [R] and result type [T] and executes it until its first suspension. * Returns the result of the coroutine or throws its exception if it does not suspend or [COROUTINE_SUSPENDED] if it suspends. * In the latter case, the [completion] continuation is invoked when the coroutine completes with a result or an exception. * * The coroutine is started directly in the invoker's thread without going through the [ContinuationInterceptor] that might * be present in the completion's [CoroutineContext]. It is the invoker's responsibility to ensure that a proper invocation * context is established. * * This function is designed to be used from inside of [suspendCoroutineUninterceptedOrReturn] to resume the execution of the suspended * coroutine using a reference to the suspending function. */ @Suppress("UNCHECKED_CAST") @kotlin.internal.InlineOnly public actual inline fun <R, T> (suspend R.() -> T).startCoroutineUninterceptedOrReturn( receiver: R, completion: Continuation<T> ): Any? = (this as Function2<R, Continuation<T>, Any?>).invoke(receiver, completion) @Suppress("UNCHECKED_CAST") @kotlin.internal.InlineOnly internal actual inline fun <R, P, T> (suspend R.(P) -> T).startCoroutineUninterceptedOrReturn( receiver: R, param: P, completion: Continuation<T> ): Any? = (this as Function3<R, P, Continuation<T>, Any?>).invoke(receiver, param, completion) private object CoroutineSuspendedMarker /** * Creates unintercepted coroutine without receiver and with result type [T]. * This function creates a new, fresh instance of suspendable computation every time it is invoked. * * To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance. * The [completion] continuation is invoked when coroutine completes with result or exception. * * This function returns unintercepted continuation. * Invocation of `resume(Unit)` starts coroutine immediately in the invoker's call stack without going through the * [ContinuationInterceptor] that might be present in the completion's [CoroutineContext]. * It is the invoker's responsibility to ensure that a proper invocation context is established. * Note that [completion] of this function may get invoked in an arbitrary context. * * [Continuation.intercepted] can be used to acquire the intercepted continuation. * Invocation of `resume(Unit)` on intercepted continuation guarantees that execution of * both the coroutine and [completion] happens in the invocation context established by * [ContinuationInterceptor]. * * Repeated invocation of any resume function on the resulting continuation corrupts the * state machine of the coroutine and may result in arbitrary behaviour or exception. */ @SinceKotlin("1.3") @Suppress("UNCHECKED_CAST") public actual fun <T> (suspend () -> T).createCoroutineUnintercepted( completion: Continuation<T> ): Continuation<Unit> { val probeCompletion = probeCoroutineCreated(completion) return if (this is BaseContinuationImpl) create(probeCompletion) else createCoroutineFromSuspendFunction(probeCompletion) { (this as Function1<Continuation<T>, Any?>).invoke(it) } } /** * Creates unintercepted coroutine with receiver type [R] and result type [T]. * This function creates a new, fresh instance of suspendable computation every time it is invoked. * * To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance. * The [completion] continuation is invoked when coroutine completes with result or exception. * * This function returns unintercepted continuation. * Invocation of `resume(Unit)` starts coroutine immediately in the invoker's call stack without going through the * [ContinuationInterceptor] that might be present in the completion's [CoroutineContext]. * It is the invoker's responsibility to ensure that a proper invocation context is established. * Note that [completion] of this function may get invoked in an arbitrary context. * * [Continuation.intercepted] can be used to acquire the intercepted continuation. * Invocation of `resume(Unit)` on intercepted continuation guarantees that execution of * both the coroutine and [completion] happens in the invocation context established by * [ContinuationInterceptor]. * * Repeated invocation of any resume function on the resulting continuation corrupts the * state machine of the coroutine and may result in arbitrary behaviour or exception. */ @SinceKotlin("1.3") @Suppress("UNCHECKED_CAST") public actual fun <R, T> (suspend R.() -> T).createCoroutineUnintercepted( receiver: R, completion: Continuation<T> ): Continuation<Unit> { val probeCompletion = probeCoroutineCreated(completion) return if (this is BaseContinuationImpl) create(receiver, probeCompletion) else { createCoroutineFromSuspendFunction(probeCompletion) { (this as Function2<R, Continuation<T>, Any?>).invoke(receiver, it) } } } /** * Intercepts this continuation with [ContinuationInterceptor]. * * This function shall be used on the immediate result of [createCoroutineUnintercepted] or [suspendCoroutineUninterceptedOrReturn], * in which case it checks for [ContinuationInterceptor] in the continuation's [context][Continuation.context], * invokes [ContinuationInterceptor.interceptContinuation], caches and returns the result. * * If this function is invoked on other [Continuation] instances it returns `this` continuation unchanged. */ @SinceKotlin("1.3") public actual fun <T> Continuation<T>.intercepted(): Continuation<T> = (this as? ContinuationImpl)?.intercepted() ?: this // INTERNAL DEFINITIONS /** * This function is used when [createCoroutineUnintercepted] encounters suspending lambda that does not extend BaseContinuationImpl. * * It happens in two cases: * 1. Callable reference to suspending function, * 2. Suspending function reference implemented by Java code. * * We must wrap it into an instance that extends [BaseContinuationImpl], because that is an expectation of all coroutines machinery. * As an optimization we use lighter-weight [RestrictedContinuationImpl] base class (it has less fields) if the context is * [EmptyCoroutineContext], and a full-blown [ContinuationImpl] class otherwise. * * The instance of [BaseContinuationImpl] is passed to the [block] so that it can be passed to the corresponding invocation. */ @SinceKotlin("1.3") @Suppress("UNCHECKED_CAST") private inline fun <T> createCoroutineFromSuspendFunction( completion: Continuation<T>, crossinline block: (Continuation<T>) -> Any? ): Continuation<Unit> { val context = completion.context // label == 0 when coroutine is not started yet (initially) or label == 1 when it was return if (context === EmptyCoroutineContext) object : RestrictedContinuationImpl(completion as Continuation<Any?>) { private var label = 0 override fun invokeSuspend(result: Result<Any?>): Any? = when (label) { 0 -> { label = 1 result.getOrThrow() // Rethrow exception if trying to start with exception (will be caught by BaseContinuationImpl.resumeWith block(this) // run the block, may return or suspend } 1 -> { label = 2 result.getOrThrow() // this is the result if the block had suspended } else -> error("This coroutine had already completed") } } else object : ContinuationImpl(completion as Continuation<Any?>, context) { private var label = 0 override fun invokeSuspend(result: Result<Any?>): Any? = when (label) { 0 -> { label = 1 result.getOrThrow() // Rethrow exception if trying to start with exception (will be caught by BaseContinuationImpl.resumeWith block(this) // run the block, may return or suspend } 1 -> { label = 2 result.getOrThrow() // this is the result if the block had suspended } else -> error("This coroutine had already completed") } } } /** * This function creates continuation suitable for passing as implicit argument to suspend functions. * The continuation calls [callback] and then delegates to [completion]. * * The result is [ContinuationImpl] because that is an expectation of all coroutines machinery. * * It can be thought as a state machine of * ``` * suspend fun foo() { * val result = runCatching { <suspended here> } * callback(result) * } * ``` */ @Suppress("UNCHECKED_CAST") internal inline fun createContinuationArgumentFromCallback( completion: Continuation<Unit>, crossinline callback: (Result<Any?>) -> Unit ): Continuation<Any?> = object : ContinuationImpl(completion as Continuation<Any?>) { private var invoked = false override fun invokeSuspend(result: Result<Any?>): Any? { if (invoked) error("This coroutine had already completed") invoked = true callback(result) return Unit // Not suspended. } }
apache-2.0
b8757ad4c35de47b75dd2b4904f51000
46
153
0.70364
4.923763
false
false
false
false
jwren/intellij-community
platform/wsl-impl/src/com/intellij/execution/wsl/sync/LinuxFileStorage.kt
6
7025
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.execution.wsl.sync import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.wsl.* import com.intellij.openapi.diagnostic.Logger import com.intellij.util.TimeoutUtil import com.intellij.util.io.delete import java.io.InputStream import java.nio.ByteBuffer import java.nio.ByteOrder import java.util.concurrent.TimeUnit import kotlin.io.path.writeText private val LOGGER = Logger.getInstance(LinuxFileStorage::class.java) class LinuxFileStorage(dir: LinuxFilePath, distro: AbstractWslDistribution, onlyExtensions: Array<String>) : FileStorage<LinuxFilePath, WindowsFilePath>(dir.trimEnd('/') + '/', distro, onlyExtensions) { // Linux side only works with UTF of 7-bit ASCII which is also supported by UTF and WSL doesn't support other charsets private val CHARSET = Charsets.UTF_8 private val FILE_SEPARATOR = CHARSET.encode(":").get() private val LINK_SEPARATOR = CHARSET.encode(";").get() override fun createSymLinks(links: Map<FilePathRelativeToDir, FilePathRelativeToDir>) { val script = createTmpWinFile(distro) script.first.writeText(links .map { it.key.escapedWithDir to it.value.escapedWithDir } .joinToString("\n") // No need to create link if parent dir doesn't exist { "[ -e $(dirname ${it.first}) ] && ln -s ${it.second} ${it.first}" }) distro.runCommand("sh", script.second, ignoreExitCode = true) script.first.delete() } override fun getHashesAndLinks(skipHashCalculation: Boolean): Pair<List<WslHashRecord>, Map<FilePathRelativeToDir, FilePathRelativeToDir>> { val hashes = ArrayList<WslHashRecord>(AVG_NUM_FILES) val links = HashMap<FilePathRelativeToDir, FilePathRelativeToDir>(AVG_NUM_FILES) val time = TimeoutUtil.measureExecutionTime<Throwable> { val tool = distro.getTool("wslhash", dir, if (skipHashCalculation) "no_hash" else "hash", *onlyExtensions) val process = tool.createProcess() process.inputStream.use { val hashesAndLinks = getHashesInternal(it) hashes += hashesAndLinks.first links += hashesAndLinks.second } waitProcess(process, tool.commandLineString) } LOGGER.info("Linux files calculated in $time") return Pair(hashes, links) } override fun createTempFile(): String = distro.runCommand("mktemp", "-u") override fun removeLinks(vararg linksToRemove: FilePathRelativeToDir) { this.removeFiles(linksToRemove.asList()) } override fun isEmpty(): Boolean { val options = WSLCommandLineOptions().apply { addInitCommand("[ -e ${escapePath(dir)} ]") } val process = distro.patchCommandLine(GeneralCommandLine("ls", "-A", dir), null, options).createProcess() if (!process.waitFor(5, TimeUnit.SECONDS)) throw Exception("Process didn't finish: WSL frozen?") if (process.exitValue() == 0) { // Folder exists, lets check if empty return process.inputStream.read() == -1 } else { // Folder doesn't exist val error = process.errorStream.readAllBytes().decodeToString() if (error.isEmpty()) return true // Doesn't exist, but still empty throw Exception("Error checking folder: $error") } } override fun removeFiles(filesToRemove: Collection<FilePathRelativeToDir>) { LOGGER.info("Removing files") runCommands(*filesToRemove.map { arrayOf("rm", it.escapedWithDir) }.toTypedArray()) } override fun removeTempFile(file: LinuxFilePath) { distro.runCommand("rm", file) } override fun tarAndCopyTo(files: Collection<FilePathRelativeToDir>, destTar: WindowsFilePath) { val linuxTarFile = createTempFile() val listFile = createTmpWinFile(distro) listFile.first.writeText(files.joinToString("\n")) LOGGER.info("Creating tar") // See tar(1) distro.runCommand("tar", "cf", linuxTarFile, "-m", "-h", "-O", "-C", dir, "-T", listFile.second) listFile.first.delete() LOGGER.info("Copying tar") distro.runCommand("cp", linuxTarFile, distro.getWslPath(destTar)) distro.runCommand("rm", linuxTarFile) } override fun unTar(tarFile: LinuxFilePath) { LOGGER.info("Unpacking") distro.runCommand("mkdir", "-p", dir) distro.runCommand("tar", "xf", tarFile, "-C", dir) } /** * Read `wslhash` stdout and return map of [file->hash] */ private fun getHashesInternal(toolStdout: InputStream): Pair<List<WslHashRecord>, Map<FilePathRelativeToDir, FilePathRelativeToDir>> { val hashes = ArrayList<WslHashRecord>(AVG_NUM_FILES) val links = HashMap<FilePathRelativeToDir, FilePathRelativeToDir>(AVG_NUM_FILES) val fileOutput = ByteBuffer.wrap(toolStdout.readAllBytes()).order(ByteOrder.LITTLE_ENDIAN) // See wslhash.c: format is the following: [file_path]:[hash]. // Hash is little-endian 8 byte (64 bit) integer // or [file_path];[link_len][link] where link_len is 4 byte signed int var fileStarted = 0 val outputLimit = fileOutput.limit() while (fileOutput.position() < outputLimit) { when (fileOutput.get()) { FILE_SEPARATOR -> { val hash = fileOutput.long val prevPos = fileOutput.position() // 9 = 8 bytes long + separator val name = CHARSET.decode(fileOutput.limit(prevPos - 9).position(fileStarted)).toString() fileOutput.limit(outputLimit).position(prevPos) hashes += WslHashRecord(FilePathRelativeToDir(name), hash) fileStarted = prevPos } LINK_SEPARATOR -> { val length = fileOutput.int val prevPos = fileOutput.position() // 5 = 4 bytes int + separator val file = CHARSET.decode(fileOutput.limit(prevPos - 5).position(fileStarted)).toString() val link = CHARSET.decode(fileOutput.limit(prevPos + length).position(prevPos)).toString() fileOutput.limit(outputLimit).position(prevPos + length) if (link.startsWith(dir)) { links[FilePathRelativeToDir((file))] = FilePathRelativeToDir(link.substring(dir.length)) } fileStarted = prevPos + length } } } return Pair(hashes, links) } private val FilePathRelativeToDir.escapedWithDir: String get() = escapePath(dir + asUnixPath) private fun escapePath(path: LinuxFilePath) = GeneralCommandLine(path).commandLineString // it is cheaper to run 1-2 commands directly, but long list of command should run as script private fun runCommands(vararg commands: Array<String>) { if (commands.count() < 3) { for (command in commands) { distro.runCommand(*command) } } else { val script = createTmpWinFile(distro) script.first.writeText(commands.joinToString("\n") { it.joinToString(" ") }) distro.runCommand("sh", script.second) script.first.delete() } } }
apache-2.0
3f5947aed3023ad33d5d47adf9c65a6c
40.081871
142
0.684555
4.320418
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/exporter/SignalSmsExportService.kt
1
7505
package org.thoughtcrime.securesms.exporter import android.content.Context import android.content.Intent import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import app.cash.exhaustive.Exhaustive import org.signal.core.util.PendingIntentFlags import org.signal.smsexporter.ExportableMessage import org.signal.smsexporter.SmsExportService import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.attachments.AttachmentId import org.thoughtcrime.securesms.database.SignalDatabase import org.thoughtcrime.securesms.database.model.MessageId import org.thoughtcrime.securesms.database.model.databaseprotos.MessageExportState import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.exporter.flow.SmsExportActivity import org.thoughtcrime.securesms.notifications.NotificationChannels import org.thoughtcrime.securesms.notifications.NotificationIds import org.thoughtcrime.securesms.notifications.v2.NotificationPendingIntentHelper import org.thoughtcrime.securesms.util.JsonUtils import java.io.IOException import java.io.InputStream /** * Service which integrates the SMS exporter functionality. */ class SignalSmsExportService : SmsExportService() { companion object { /** * Launches the export service and immediately begins exporting messages. */ fun start(context: Context, clearPreviousExportState: Boolean) { val intent = Intent(context, SignalSmsExportService::class.java) .apply { putExtra(CLEAR_PREVIOUS_EXPORT_STATE_EXTRA, clearPreviousExportState) } ContextCompat.startForegroundService(context, intent) } } private var reader: SignalSmsExportReader? = null override fun getNotification(progress: Int, total: Int): ExportNotification { val pendingIntent = NotificationPendingIntentHelper.getActivity( this, 0, SmsExportActivity.createIntent(this), PendingIntentFlags.mutable() ) return ExportNotification( NotificationIds.SMS_EXPORT_SERVICE, NotificationCompat.Builder(this, NotificationChannels.BACKUPS) .setSmallIcon(R.drawable.ic_signal_backup) .setContentTitle(getString(R.string.SignalSmsExportService__exporting_messages)) .setContentIntent(pendingIntent) .setProgress(total, progress, false) .build() ) } override fun getExportCompleteNotification(): ExportNotification? { if (ApplicationDependencies.getAppForegroundObserver().isForegrounded) { return null } val pendingIntent = NotificationPendingIntentHelper.getActivity( this, 0, SmsExportActivity.createIntent(this), PendingIntentFlags.mutable() ) return ExportNotification( NotificationIds.SMS_EXPORT_COMPLETE, NotificationCompat.Builder(this, NotificationChannels.APP_ALERTS) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(getString(R.string.SignalSmsExportService__signal_sms_export_complete)) .setContentText(getString(R.string.SignalSmsExportService__tap_to_return_to_signal)) .setContentIntent(pendingIntent) .build() ) } override fun clearPreviousExportState() { SignalDatabase.sms.clearExportState() SignalDatabase.mms.clearExportState() } override fun prepareForExport() { SignalDatabase.sms.clearInsecureMessageExportedErrorStatus() SignalDatabase.mms.clearInsecureMessageExportedErrorStatus() } override fun getUnexportedMessageCount(): Int { ensureReader() return reader!!.getCount() } override fun getUnexportedMessages(): Iterable<ExportableMessage> { ensureReader() return reader!! } override fun onMessageExportStarted(exportableMessage: ExportableMessage) { SignalDatabase.mmsSms.updateMessageExportState(exportableMessage.getMessageId()) { it.toBuilder().setProgress(MessageExportState.Progress.STARTED).build() } } override fun onMessageExportSucceeded(exportableMessage: ExportableMessage) { SignalDatabase.mmsSms.updateMessageExportState(exportableMessage.getMessageId()) { it.toBuilder().setProgress(MessageExportState.Progress.COMPLETED).build() } SignalDatabase.mmsSms.markMessageExported(exportableMessage.getMessageId()) } override fun onMessageExportFailed(exportableMessage: ExportableMessage) { SignalDatabase.mmsSms.updateMessageExportState(exportableMessage.getMessageId()) { it.toBuilder().setProgress(MessageExportState.Progress.INIT).build() } SignalDatabase.mmsSms.markMessageExportFailed(exportableMessage.getMessageId()) } override fun onMessageIdCreated(exportableMessage: ExportableMessage, messageId: Long) { SignalDatabase.mmsSms.updateMessageExportState(exportableMessage.getMessageId()) { it.toBuilder().setMessageId(messageId).build() } } override fun onAttachmentPartExportStarted(exportableMessage: ExportableMessage, part: ExportableMessage.Mms.Part) { SignalDatabase.mmsSms.updateMessageExportState(exportableMessage.getMessageId()) { it.toBuilder().addStartedAttachments(part.contentId).build() } } override fun onAttachmentPartExportSucceeded(exportableMessage: ExportableMessage, part: ExportableMessage.Mms.Part) { SignalDatabase.mmsSms.updateMessageExportState(exportableMessage.getMessageId()) { it.toBuilder().addCompletedAttachments(part.contentId).build() } } override fun onAttachmentPartExportFailed(exportableMessage: ExportableMessage, part: ExportableMessage.Mms.Part) { SignalDatabase.mmsSms.updateMessageExportState(exportableMessage.getMessageId()) { val startedAttachments = it.startedAttachmentsList - part.contentId it.toBuilder().clearStartedAttachments().addAllStartedAttachments(startedAttachments).build() } } override fun onRecipientExportStarted(exportableMessage: ExportableMessage, recipient: String) { SignalDatabase.mmsSms.updateMessageExportState(exportableMessage.getMessageId()) { it.toBuilder().addStartedRecipients(recipient).build() } } override fun onRecipientExportSucceeded(exportableMessage: ExportableMessage, recipient: String) { SignalDatabase.mmsSms.updateMessageExportState(exportableMessage.getMessageId()) { it.toBuilder().addCompletedRecipients(recipient).build() } } override fun onRecipientExportFailed(exportableMessage: ExportableMessage, recipient: String) { SignalDatabase.mmsSms.updateMessageExportState(exportableMessage.getMessageId()) { val startedAttachments = it.startedRecipientsList - recipient it.toBuilder().clearStartedRecipients().addAllStartedRecipients(startedAttachments).build() } } @Throws(IOException::class) override fun getInputStream(part: ExportableMessage.Mms.Part): InputStream { return SignalDatabase.attachments.getAttachmentStream(JsonUtils.fromJson(part.contentId, AttachmentId::class.java), 0) } override fun onExportPassCompleted() { reader?.close() } private fun ExportableMessage.getMessageId(): MessageId { @Exhaustive val messageId: Any = when (this) { is ExportableMessage.Mms<*> -> id is ExportableMessage.Sms<*> -> id } if (messageId is MessageId) { return messageId } else { throw AssertionError("Exportable message id must be type MessageId. Type: ${messageId.javaClass}") } } private fun ensureReader() { if (reader == null) { reader = SignalSmsExportReader() } } }
gpl-3.0
8d639a7f9f2b6e59230f125185a62730
36.713568
122
0.772418
4.780255
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/androidAndroidTest/kotlin/androidx/compose/ui/text/matchers/BitmapSubject.kt
3
2089
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.matchers import android.graphics.Bitmap import com.google.common.truth.FailureMetadata import com.google.common.truth.Subject import com.google.common.truth.Subject.Factory /** * Truth extension for Bitmap. */ internal class BitmapSubject private constructor( failureMetadata: FailureMetadata?, private val subject: Bitmap? ) : Subject(failureMetadata, subject) { companion object { internal val SUBJECT_FACTORY: Factory<BitmapSubject?, Bitmap?> = Factory { failureMetadata, subject -> BitmapSubject(failureMetadata, subject) } } /** * Checks the equality of two [Bitmap]s. * * @param bitmap the [Bitmap] to be matched. */ fun isEqualToBitmap(bitmap: Bitmap) { if (subject == bitmap) return check("isNotNull()").that(subject).isNotNull() check("sameAs()").that(subject!!.sameAs(bitmap)).isTrue() } /** * Checks the inequality of two [Bitmap]s. * * @param bitmap the [Bitmap] to be matched. */ fun isNotEqualToBitmap(bitmap: Bitmap) { if (subject == null) return check("sameAs()").that(subject.sameAs(bitmap)).isFalse() } override fun actualCustomStringRepresentation(): String { return if (subject != null) { "($subject ${subject.width}x${subject.height} ${subject.config.name})" } else { super.actualCustomStringRepresentation() } } }
apache-2.0
e3e2436b9976ed5c993af02c786f4ada
31.153846
91
0.675443
4.307216
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/utils.kt
1
4807
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.safeDelete import com.intellij.ide.IdeBundle import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.ThrowableComputable import com.intellij.psi.* import com.intellij.psi.search.searches.OverridingMethodsSearch import com.intellij.refactoring.util.RefactoringDescriptionLocation import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parameterIndex import java.util.* fun PsiElement.canDeleteElement(): Boolean { if (this is KtObjectDeclaration && isObjectLiteral()) return false if (this is KtParameter) { val parameterList = parent as? KtParameterList ?: return false val declaration = parameterList.parent as? KtDeclaration ?: return false return declaration !is KtPropertyAccessor } return this is KtClassOrObject || this is KtSecondaryConstructor || this is KtNamedFunction || this is PsiMethod || this is PsiClass || this is KtProperty || this is KtTypeParameter || this is KtTypeAlias } fun PsiElement.removeOverrideModifier() { when (this) { is KtNamedFunction, is KtProperty -> { (this as KtModifierListOwner).modifierList?.getModifier(KtTokens.OVERRIDE_KEYWORD)?.delete() } is PsiMethod -> { modifierList.annotations.firstOrNull { annotation -> annotation.qualifiedName == "java.lang.Override" }?.delete() } } } fun PsiMethod.cleanUpOverrides() { val superMethods = findSuperMethods(true) for (overridingMethod in OverridingMethodsSearch.search(this, true).findAll()) { val currentSuperMethods = overridingMethod.findSuperMethods(true).asSequence() + superMethods.asSequence() if (currentSuperMethods.all { superMethod -> superMethod.unwrapped == unwrapped }) { overridingMethod.unwrapped?.removeOverrideModifier() } } } fun checkParametersInMethodHierarchy(parameter: PsiParameter): Collection<PsiElement>? { val method = parameter.declarationScope as PsiMethod val parametersToDelete = ProgressManager.getInstance() .runProcessWithProgressSynchronously(ThrowableComputable<Collection<PsiElement>?, RuntimeException> { runReadAction { collectParametersHierarchy(method, parameter) } }, KotlinBundle.message("progress.title.collect.hierarchy", parameter.name), true, parameter.project) if (parametersToDelete == null || parametersToDelete.size <= 1 || isUnitTestMode()) return parametersToDelete val message = KotlinBundle.message("override.declaration.delete.multiple.parameters", ElementDescriptionUtil.getElementDescription(method, RefactoringDescriptionLocation.WITHOUT_PARENT)) val exitCode = Messages.showOkCancelDialog(parameter.project, message, IdeBundle.message("title.warning"), Messages.getQuestionIcon()) return if (exitCode == Messages.OK) parametersToDelete else null } // TODO: generalize breadth-first search private fun collectParametersHierarchy(method: PsiMethod, parameter: PsiParameter): Set<PsiElement> { val queue = ArrayDeque<PsiMethod>() val visited = HashSet<PsiMethod>() val parametersToDelete = HashSet<PsiElement>() queue.add(method) while (!queue.isEmpty()) { val currentMethod = queue.poll() visited += currentMethod addParameter(currentMethod, parametersToDelete, parameter) currentMethod.findSuperMethods(true) .filter { it !in visited } .forEach { queue.offer(it) } OverridingMethodsSearch.search(currentMethod) .filter { it !in visited } .forEach { queue.offer(it) } } return parametersToDelete } private fun addParameter(method: PsiMethod, result: MutableSet<PsiElement>, parameter: PsiParameter) { val parameterIndex = parameter.unwrapped!!.parameterIndex() if (method is KtLightMethod) { val declaration = method.kotlinOrigin if (declaration is KtFunction) { result.add(declaration.valueParameters[parameterIndex]) } } else { result.add(method.parameterList.parameters[parameterIndex]) } }
apache-2.0
1354bc6a406401f47a1f2331e45b2e64
41.548673
158
0.720616
5.174381
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/Panel.kt
1
6560
// 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.ui.dsl.builder import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.util.NlsContexts import com.intellij.ui.components.JBLabel import com.intellij.ui.dsl.gridLayout.Gaps import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.dsl.gridLayout.VerticalAlign import com.intellij.ui.layout.* import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import java.awt.Color import javax.swing.JLabel /** * Empty label parameter for [Panel.row] method in case label is omitted. */ @Deprecated("Use \"\" instead of this constant") val EMPTY_LABEL = "" @ApiStatus.NonExtendable @JvmDefaultWithCompatibility interface Panel : CellBase<Panel> { override fun visible(isVisible: Boolean): Panel override fun visibleIf(predicate: ComponentPredicate): Panel override fun enabled(isEnabled: Boolean): Panel override fun enabledIf(predicate: ComponentPredicate): Panel @Deprecated("Use align method instead") override fun horizontalAlign(horizontalAlign: HorizontalAlign): Panel @Deprecated("Use align method instead") override fun verticalAlign(verticalAlign: VerticalAlign): Panel override fun align(align: Align): Panel override fun resizableColumn(): Panel override fun gap(rightGap: RightGap): Panel override fun customize(customGaps: Gaps): Panel /** * Adds standard left indent and groups rows into [RowsRange] that allows to use some groups operations on the rows * * @see [rowsRange] */ fun indent(init: Panel.() -> Unit): RowsRange /** * Adds row with [RowLayout.LABEL_ALIGNED] layout and [label]. The label can contain mnemonic and is assigned * to the first component in the row via [JLabel.labelFor] property. * Use row("") if label is empty */ fun row(@Nls label: String, init: Row.() -> Unit): Row /** * Adds row with [RowLayout.LABEL_ALIGNED] layout and [label]. The label is assigned * to the first component in the row via [JLabel.labelFor] property. * If label is null then [RowLayout.INDEPENDENT] layout is used */ fun row(label: JLabel? = null, init: Row.() -> Unit): Row /** * Adds specified columns in a row */ fun twoColumnsRow(column1: (Row.() -> Unit)?, column2: (Row.() -> Unit)? = null): Row /** * Adds specified columns in a row */ fun threeColumnsRow(column1: (Row.() -> Unit)?, column2: (Row.() -> Unit)? = null, column3: (Row.() -> Unit)? = null): Row @Deprecated(message = "Use overloaded method or group/groupRowsRange instead", level = DeprecationLevel.HIDDEN) fun separator(@NlsContexts.Separator title: String? = null, background: Color? = null): Row /** * Adds horizontal line separator. Use [group] or [groupRowsRange] if you need a separator with title */ fun separator(background: Color? = null): Row /** * Creates sub-panel that occupies the whole width and uses its own grid inside */ fun panel(init: Panel.() -> Unit): Panel /** * Groups rows into [RowsRange] that allows to use some groups operations on the rows * * @see [indent] */ fun rowsRange(init: Panel.() -> Unit): RowsRange /** * Adds panel with independent grid, title and some vertical space above (except the group in the parents first row) * and below (except the group in the parents last row) the group. * Grouped radio buttons and checkboxes should use [Panel.buttonsGroup] method, which uses different title gaps. * To change gaps around the group use [Row.topGap] and [Row.bottomGap] for the method result * * @param indent true if left indent is needed */ fun group(@NlsContexts.BorderTitle title: String? = null, indent: Boolean = true, init: Panel.() -> Unit): Row /** * See overloaded method */ fun group(title: JBLabel, indent: Boolean = true, init: Panel.() -> Unit): Row @Deprecated("Use overloaded group(...) instead") @ApiStatus.ScheduledForRemoval fun group(@NlsContexts.BorderTitle title: String? = null, indent: Boolean = true, topGroupGap: Boolean? = null, bottomGroupGap: Boolean? = null, init: Panel.() -> Unit): Panel /** * Similar to [Panel.group] but uses the same grid as the parent. * * @see [RowsRange] */ fun groupRowsRange(@NlsContexts.BorderTitle title: String? = null, indent: Boolean = true, topGroupGap: Boolean? = null, bottomGroupGap: Boolean? = null, init: Panel.() -> Unit): RowsRange /** * Adds collapsible panel with independent grid, title and some vertical space above (except the group in the parents first row) * and below (except the group in the parents last row) the group. * To change gaps around the group use [Row.topGap] and [Row.bottomGap] for the method result * * @param indent true if left indent is needed */ fun collapsibleGroup(@NlsContexts.BorderTitle title: String, indent: Boolean = true, init: Panel.() -> Unit): CollapsibleRow @Deprecated("Use buttonsGroup(...) instead") @ApiStatus.ScheduledForRemoval fun <T> buttonGroup(binding: PropertyBinding<T>, type: Class<T>, @NlsContexts.BorderTitle title: String? = null, indent: Boolean = title != null, init: Panel.() -> Unit) /** * Unions [Row.radioButton] in one group. Must be also used for [Row.checkBox] if they are grouped with some title. * Note that [Panel.group] provides different gaps around the title * @param indent true if left indent is needed. By default, true if title exists and false otherwise */ fun buttonsGroup(@NlsContexts.BorderTitle title: String? = null, indent: Boolean = title != null, init: Panel.() -> Unit): ButtonsGroup /** * Registers [callback] that will be called from [DialogPanel.apply] method */ fun onApply(callback: () -> Unit): Panel /** * Registers [callback] that will be called from [DialogPanel.reset] method */ fun onReset(callback: () -> Unit): Panel /** * Registers [callback] that will be called from [DialogPanel.isModified] method */ fun onIsModified(callback: () -> Boolean): Panel /** * Overrides default spacing configuration. Should be used for very specific cases */ fun customizeSpacingConfiguration(spacingConfiguration: SpacingConfiguration, init: Panel.() -> Unit) }
apache-2.0
a365a58d9ec21f7ca0ea52a564421df5
35.853933
137
0.685671
4.304462
false
false
false
false