repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
syrop/Wiktor-Navigator
navigator/src/main/kotlin/pl/org/seva/navigator/main/data/fb/FbReader.kt
1
4320
/* * Copyright (C) 2017 Wiktor Nizio * * 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/>. * * If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp */ package pl.org.seva.navigator.main.data.fb import com.google.android.gms.maps.model.LatLng import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseReference import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.ReplaySubject import pl.org.seva.navigator.contact.Contact import pl.org.seva.navigator.debug.debug import pl.org.seva.navigator.main.init.instance import pl.org.seva.navigator.main.ui.colorFactory val fbReader by instance<FbReader>() class FbReader : Fb() { fun peerLocationListener(email: String): Observable<LatLng> { return email.toReference().child(LAT_LNG).listen() .filter { it.value != null } .map { checkNotNull(it.value) } .map { it as String } .map { it.toLatLng() } } fun debugListener(email: String): Observable<String> { return email.toReference().child(DEBUG).listen() .filter { it.value != null } .map { checkNotNull(it.value) } .map { it as String } .filter { !debug.isIgnoredForPeer(email, it) } } fun friendshipRequestedListener(): Observable<Contact> = FRIENDSHIP_REQUESTED.contactListener() fun friendshipAcceptedListener(): Observable<Contact> = FRIENDSHIP_ACCEPTED.contactListener() fun friendshipDeletedListener(): Observable<Contact> = FRIENDSHIP_DELETED.contactListener() fun readFriends(): Observable<Contact> { val reference = currentUserReference().child(FRIENDS) return reference.read() .concatMapIterable { it.children } .filter { it.exists() } .map { it.toContact() } } fun findContact(email: String): Observable<Contact> = email.toReference().readContact() private fun DatabaseReference.readContact(): Observable<Contact> = read().map { it.toContact() } private fun String.contactListener(): Observable<Contact> { val reference = currentUserReference().child(this) return reference.read() .concatMapIterable<DataSnapshot> { it.children } .concatWith(reference.childListener()) .doOnNext { reference.child(checkNotNull(it.key)).removeValue() } .map { it.toContact() } } private fun DatabaseReference.childListener(): Observable<DataSnapshot> { val result = ReplaySubject.create<DataSnapshot>() addChildEventListener(RxChildEventListener(result)) return result.hide() } private fun DatabaseReference.read(): Observable<DataSnapshot> { val resultSubject = PublishSubject.create<DataSnapshot>() return resultSubject .doOnSubscribe { addListenerForSingleValueEvent(RxValueEventListener(resultSubject)) } .take(READ_ONCE) } private fun DatabaseReference.listen(): Observable<DataSnapshot> { val resultSubject = PublishSubject.create<DataSnapshot>() val value = RxValueEventListener(resultSubject) return resultSubject .doOnSubscribe { addValueEventListener(value) } .doOnDispose { removeEventListener(value) } } private fun DataSnapshot.toContact() = if (exists()) { Contact(checkNotNull(key).from64(), child(DISPLAY_NAME).value as String, colorFactory.nextColor()) } else Contact() companion object { const val READ_ONCE = 1L } }
gpl-3.0
9bdbf9e17168f6b781e8b0f407fc96cb
38.272727
114
0.677546
4.537815
false
false
false
false
hazuki0x0/YuzuBrowser
module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/ui/original/AdBlockImportViewModel.kt
1
1230
/* * Copyright (C) 2017-2021 Hazuki * * 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 jp.hazuki.yuzubrowser.adblock.ui.original import androidx.lifecycle.ViewModel import jp.hazuki.yuzubrowser.core.lifecycle.KotlinLiveData import jp.hazuki.yuzubrowser.core.lifecycle.LiveEvent class AdBlockImportViewModel : ViewModel() { val isExclude = KotlinLiveData(true) val isButtonEnable = KotlinLiveData(true) val text = KotlinLiveData("") val event = LiveEvent<Int>() fun onOkClick() { event.notify(EVENT_OK) } fun onCancelClick() { event.notify(EVENT_CANCEL) } companion object { const val EVENT_OK = 1 const val EVENT_CANCEL = 2 } }
apache-2.0
60f13a6c835782184d0f056d2895fa6f
26.333333
75
0.711382
4.169492
false
false
false
false
kangsLee/sh8email-kotlin
app/src/main/kotlin/org/triplepy/sh8email/sh8/api/ReceivedCookiesInterceptor.kt
1
1211
package org.triplepy.sh8email.sh8.api import okhttp3.Interceptor import org.triplepy.sh8email.sh8.Constants import org.triplepy.sh8email.sh8.app.App import java.util.* /** * The sh8email-android Project. * ============================== * org.triplepy.sh8email.sh8.api * ============================== * Created by igangsan on 2016. 8. 28.. * * AddCookiesInterceptor와 마찬가지로 Interceptor를 Implements 하여 구현합니다. * 다른점은 request를 수행시키고 받아온 response값을 조작한다는 점 입니다. * 만약 response Header에 Set-Cookie란 값이 있다면 cookies값을 Preferences에 저장시킵니다. * 그리고는 header가 추가 된 response값을 반환시킵니다. * * @author 이강산 (river-mountain) * */ class ReceivedCookiesInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): okhttp3.Response { val response = chain.proceed(chain.request()) if (!response.headers("Set-Cookie").isEmpty()) { val cookies = HashSet<String>() cookies.addAll(response.headers("Set-Cookie")) App.pref.put(Constants.PREF_COOKIE, cookies) } return response } }
apache-2.0
19bb5429a185e2a440de33af6d5e0b9c
27.702703
72
0.658812
3.274691
false
false
false
false
AdamMc331/CashCaretaker
app/src/test/java/com/androidessence/cashcaretaker/ui/transactionlist/TransactionListViewModelTest.kt
1
1652
package com.androidessence.cashcaretaker.ui.transactionlist import com.androidessence.cashcaretaker.CoroutinesTestRule import com.androidessence.cashcaretaker.core.models.Transaction import org.junit.Before import org.junit.Rule import org.junit.Test class TransactionListViewModelTest { private lateinit var testRobot: TransactionListViewModelRobot @JvmField @Rule val coroutineTestRule = CoroutinesTestRule() @Before fun setUp() { testRobot = TransactionListViewModelRobot() } @Test fun fetchValidTransactions() { val accountName = "Checking" val testTransactions = listOf( Transaction( description = "Test Transaction" ) ) val expectedViewState = TransactionListViewState( showLoading = false, accountName = accountName, transactions = testTransactions, ) testRobot .mockTransactionsForAccount( accountName, testTransactions ) .buildViewModel(accountName) .assertViewState(expectedViewState) } @Test fun fetchEmptyTransactionList() { val accountName = "Checking" val expectedViewState = TransactionListViewState( showLoading = false, accountName = accountName, transactions = emptyList(), ) testRobot .mockTransactionsForAccount( accountName, emptyList() ) .buildViewModel(accountName) .assertViewState(expectedViewState) } }
mit
609c392d1cf411e3ab5228a832d22447
24.8125
65
0.619249
5.837456
false
true
false
false
tingtingths/jukebot
app/src/main/java/com/jukebot/jukebot/ConsoleActivity.kt
1
7603
package com.jukebot.jukebot import android.app.ActivityManager import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.AsyncTask import android.os.Bundle import android.support.design.widget.NavigationView import android.support.v4.view.GravityCompat import android.support.v4.widget.DrawerLayout import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.text.method.MovementMethod import android.text.method.ScrollingMovementMethod import android.view.Menu import android.view.MenuItem import android.widget.ImageView import android.widget.TextView import com.google.gson.Gson import com.jukebot.jukebot.logging.Logger import com.jukebot.jukebot.manager.MessageManager import com.jukebot.jukebot.storage.PersistentStorage import com.jukebot.jukebot.telegram.Bot import com.pengrad.telegrambot.model.PhotoSize import com.pengrad.telegrambot.request.GetFile import com.pengrad.telegrambot.request.GetMe import com.pengrad.telegrambot.request.GetUserProfilePhotos import com.pengrad.telegrambot.response.BaseResponse import com.pengrad.telegrambot.response.GetFileResponse import com.pengrad.telegrambot.response.GetMeResponse import com.pengrad.telegrambot.response.GetUserProfilePhotosResponse import java.io.InputStream import java.net.URL class ConsoleActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_console) // jukebot val tv: TextView = findViewById(R.id.debugTextView) as TextView tv.movementMethod = ScrollingMovementMethod() as MovementMethod? Logger.debugConsole = tv // --------------------- val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) val drawer = findViewById(R.id.drawer_layout) as DrawerLayout //val toggle = ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) val toggle = ActionBarDrawerToggle(this, drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawer.setDrawerListener(toggle) toggle.syncState() val navigationView = findViewById(R.id.nav_view) as NavigationView navigationView.setNavigationItemSelectedListener(this) Logger.log(this.javaClass.simpleName, "token=${PersistentStorage.get(Constant.KEY_BOT_TOKEN)}") FetchBotInfoTask().execute() } private fun getAvatar(userId: Int) = MessageManager.enqueue(Pair(GetUserProfilePhotos(userId), { resp: BaseResponse? -> if (resp != null && resp.isOk && resp is GetUserProfilePhotosResponse) { resp.photos().photos()[0].forEach { photoSize -> if (photoSize is PhotoSize // for smart cast && photoSize.height() <= 160) { Logger.log(this.javaClass.simpleName, "selected photo=$photoSize") MessageManager.enqueue(Pair(GetFile(photoSize.fileId()), { resp: BaseResponse? -> if (resp != null && resp.isOk && resp is GetFileResponse && resp.file().filePath() != null) { // grab file FetchImageTask(findViewById(R.id.drawerBotAvatar) as ImageView) .execute("https://api.telegram.org/file/bot${PersistentStorage.get(Constant.KEY_BOT_TOKEN) as String}/${resp.file().filePath()}") } })) return@forEach } } } })) override fun onPrepareOptionsMenu(menu: Menu?): Boolean = false private fun isServiceRunning(clazz: Class<*>): Boolean { val manager: ActivityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager for (service in manager.getRunningServices(Int.MAX_VALUE)) { if (clazz.name == service.service.className && service.started && service.foreground) { Logger.log(this.javaClass.simpleName, "service=${Gson().toJson(service)}") return true } } return false } override fun onBackPressed() { val drawer = findViewById(R.id.drawer_layout) as DrawerLayout if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.console, menu) return true } override fun onNavigationItemSelected(item: MenuItem): Boolean { // Handle navigation view item clicks here. val id = item.itemId if (id == R.id.nav_settings) { fragmentManager .beginTransaction() .replace(R.id.contentPanel, SettingsFragment()) .addToBackStack(null) .commit() } if (id == R.id.nav_exit) { closeApp() } val drawer = findViewById(R.id.drawer_layout) as DrawerLayout drawer.closeDrawer(GravityCompat.START) return true } inner class FetchBotInfoTask : AsyncTask<Unit, Unit, Unit>() { override fun doInBackground(vararg params: Unit?) { // get bot info while (!isServiceRunning(Bot::class.java)) { Logger.log(this.javaClass.simpleName, "await service") Thread.sleep(500) } Logger.log(this.javaClass.simpleName, "service started") MessageManager.enqueue(Pair(GetMe(), { resp: BaseResponse? -> try { if (resp != null && resp.isOk && resp is GetMeResponse) { (findViewById(R.id.drawerBotName) as TextView).text = "@${resp.user().username()}" getAvatar(resp.user().id()) } } catch (e: Exception) { e.printStackTrace() } })) } } inner class FetchImageTask(val imgView: ImageView) : AsyncTask<String, Unit, Bitmap?>() { override fun doInBackground(vararg urls: String?): Bitmap? { var bitmap: Bitmap? = null if (urls[0] != null) { try { val inputStream: InputStream = URL(urls[0]).openStream() bitmap = BitmapFactory.decodeStream(inputStream) inputStream.close() } catch (e: Exception) { e.printStackTrace() } } return bitmap } override fun onPostExecute(bitmap: Bitmap?) { super.onPostExecute(bitmap) if (bitmap != null) imgView.setImageBitmap(bitmap) } } fun closeApp() { stopService(Intent(this, Bot::class.java)) System.exit(0) } }
mit
0715c52d5b2fa8708ddb5e38e090ece0
38.190722
173
0.60555
5.045123
false
false
false
false
daemontus/Distributed-CTL-Model-Checker
src/main/kotlin/com/github/sybila/checker/operator/FirstOrderOperator.kt
3
2986
package com.github.sybila.checker.operator import com.github.sybila.checker.Channel import com.github.sybila.checker.Operator import com.github.sybila.checker.map.mutable.HashStateMap class ForAllOperator<out Params : Any>( full: Operator<Params>, inner: MutableList<Operator<Params>?>, bound: Operator<Params>, channel: Channel<Params> ) : LazyOperator<Params>(channel, { //forall x in B: A <=> forall x: ((at x: B) => A) <=> forall x: (!(at x: B) || A) val b = HashStateMap(ff, bound.compute().entries().asSequence().toMap()) val boundTransmission = (0 until partitionCount).map { b } mapReduce(boundTransmission.prepareTransmission(partitionId))?.forEach { b[it.first] = it.second } //now everyone has a full bound val result = newLocalMutableMap(partitionId) full.compute().entries().forEach { result[it.first] = it.second } for (state in 0 until stateCount) { if (state in b) { val i = inner[state]!!.compute() result.states().forEach { result[it] = result[it] and (i[it] or b[state].not()) } } inner[state] = null } result }) class ExistsOperator<out Params : Any>( inner: MutableList<Operator<Params>?>, bound: Operator<Params>, channel: Channel<Params> ) : LazyOperator<Params>(channel, { //exists x in B: A <=> exists x: ((at x: B) && A) val result = newLocalMutableMap(partitionId) val b = HashStateMap(ff, bound.compute().entries().asSequence().toMap()) val boundTransmission = (0 until partitionCount).map { b } mapReduce(boundTransmission.prepareTransmission(partitionId))?.forEach { b[it.first] = it.second } //now everyone has a full bound for (state in 0 until stateCount) { if (state in b) { val i = inner[state]!!.compute() i.entries().forEach { result[it.first] = result[it.first] or (it.second and b[state]) } } inner[state] = null } result }) class BindOperator<out Params : Any>( inner: MutableList<Operator<Params>?>, channel: Channel<Params> ) : LazyOperator<Params>(channel, { val result = newLocalMutableMap(partitionId) for (state in 0 until stateCount) { val i = inner[state]!!.compute() if (state in this) { result[state] = i[state] } inner[state] = null } result }) class AtOperator<out Params : Any>( state: Int, inner: Operator<Params>, channel: Channel<Params> ) : LazyOperator<Params>(channel, { val i = inner.compute() val transmission: Array<List<Pair<Int, Params>>?> = if (state in this) { (0 until partitionCount).map { listOf(state to i[state]) }.toTypedArray() } else kotlin.arrayOfNulls<List<Pair<Int, Params>>>(partitionCount) val result = mapReduce(transmission)?.first() ?: (state to i[state]) (0 until stateCount).asStateMap(result.second) })
gpl-3.0
d2910e02fe82848b5cf011771f494e7e
31.11828
96
0.625251
3.965471
false
false
false
false
androidx/constraintlayout
projects/ComposeConstraintLayout/macrobenchmark-app/src/main/java/com/example/macrobenchmark/ui/sampledata/Strings.kt
2
3831
/* * Copyright (C) 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.macrobenchmark.ui.sampledata /** * From [androidx.compose.ui.tooling.preview.datasource.LoremIpsum] */ private val LOREM_IPSUM = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer sodales laoreet commodo. Phasellus a purus eu risus elementum consequat. Aenean eu elit ut nunc convallis laoreet non ut libero. Suspendisse interdum placerat risus vel ornare. Donec vehicula, turpis sed consectetur ullamcorper, ante nunc egestas quam, ultricies adipiscing velit enim at nunc. Aenean id diam neque. Praesent ut lacus sed justo viverra fermentum et ut sem. Fusce convallis gravida lacinia. Integer semper dolor ut elit sagittis lacinia. Praesent sodales scelerisque eros at rhoncus. Duis posuere sapien vel ipsum ornare interdum at eu quam. Vestibulum vel massa erat. Aenean quis sagittis purus. Phasellus arcu purus, rutrum id consectetur non, bibendum at nibh. Duis nec erat dolor. Nulla vitae consectetur ligula. Quisque nec mi est. Ut quam ante, rutrum at pellentesque gravida, pretium in dui. Cras eget sapien velit. Suspendisse ut sem nec tellus vehicula eleifend sit amet quis velit. Phasellus quis suscipit nisi. Nam elementum malesuada tincidunt. Curabitur iaculis pretium eros, malesuada faucibus leo eleifend a. Curabitur congue orci in neque euismod a blandit libero vehicula.""".trim() private val LOREM_IPSUM_WORDS = LOREM_IPSUM.split(" ") private val names = listOf( "Jacob", "Sophia", "Noah", "Emma", "Mason", "Isabella", "William", "Olivia", "Ethan", "Ava", "Liam", "Emily", "Michael", "Abigail", "Alexander", "Mia", "Jayden", "Madison", "Daniel", "Elizabeth", "Aiden", "Chloe", "James", "Ella", "Elijah", "Avery", "Matthew", "Charlotte", "Benjamin", "Sofia" ) private val surnames = arrayOf( "Smith", "Johnson", "Williams", "Brown", "Jones", "Garcia", "Miller", "Davis", "Rodriguez", "Martinez" ) private val cities = arrayOf( "Shanghai", "Karachi", "Beijing", "Delhi", "Lagos", "Tianjin", "Istanbul", "Tokyo", "Guangzhou", "Mumbai", "Moscow", "São Paulo", "Shenzhen", "Jakarta", "Lahore", "Seoul", "Wuhan", "Kinshasa", "Cairo", "Mexico City", "Lima", "London", "New York City" ) internal fun randomFirstName(): String = names.random() internal fun randomLastName(): String = surnames.random() internal fun randomFullName(): String = randomFirstName() + " " + randomLastName() internal fun randomCity(): String = cities.random() internal object LoremIpsum { fun string(wordCount: Int, withLineBreaks: Boolean = false): String = words(wordCount, withLineBreaks).joinToString(separator = " ") fun words(wordCount: Int, withLineBreaks: Boolean = false): List<String> = if (withLineBreaks) { // Source includes line breaks LOREM_IPSUM_WORDS.take(wordCount.coerceIn(1, LOREM_IPSUM_WORDS.size)) } else { LOREM_IPSUM.filter { it != '\n' }.split(' ') .take(wordCount.coerceIn(1, LOREM_IPSUM_WORDS.size)) } }
apache-2.0
cb721723e02d995b2d7ed2b9042c94bd
27.377778
82
0.673368
3.237532
false
false
false
false
signed/intellij-community
plugins/stats-collector/src/com/intellij/stats/completion/Utils.kt
1
3121
package com.intellij.stats.completion import com.intellij.openapi.application.PathManager import java.io.File import java.io.FileFilter import java.nio.file.Files abstract class UrlProvider { abstract val statsServerPostUrl: String abstract val experimentDataUrl: String } abstract class FilePathProvider { abstract fun getUniqueFile(): File abstract fun getDataFiles(): List<File> abstract fun getStatsDataDirectory(): File abstract fun cleanupOldFiles() } class InternalUrlProvider: UrlProvider() { private val internalHost = "http://unit-617.labs.intellij.net" private val host: String get() = internalHost override val statsServerPostUrl = "http://test.jetstat-resty.aws.intellij.net/uploadstats" override val experimentDataUrl = "$host:8090/experiment/info" } class PluginDirectoryFilePathProvider : UniqueFilesProvider("chunk", PathManager.getSystemPath()) open class UniqueFilesProvider(private val baseName: String, private val rootDirectoryPath: String) : FilePathProvider() { private val MAX_ALLOWED_SEND_SIZE = 2 * 1024 * 1024 override fun cleanupOldFiles() { val files = getDataFiles() val sizeToSend = files.fold(0L, { totalSize, file -> totalSize + file.length() }) if (sizeToSend > MAX_ALLOWED_SEND_SIZE) { var currentSize = sizeToSend val iterator = files.iterator() while (iterator.hasNext() && currentSize > MAX_ALLOWED_SEND_SIZE) { val file = iterator.next() val fileSize = file.length() Files.delete(file.toPath()) currentSize -= fileSize } } } override fun getUniqueFile(): File { val dir = getStatsDataDirectory() val currentMaxIndex = dir .listFiles(FileFilter { it.isFile }) .filter { it.name.startsWith(baseName) } .map { it.name.substringAfter('_') } .filter { it.isIntConvertable() } .map(String::toInt) .max() val newIndex = if (currentMaxIndex != null) currentMaxIndex + 1 else 0 val file = File(dir, "${baseName}_$newIndex") return file } override fun getDataFiles(): List<File> { val dir = getStatsDataDirectory() return dir.listFiles(FileFilter { it.isFile }) .filter { it.name.startsWith(baseName) } .filter { it.name.substringAfter('_').isIntConvertable() } .sortedBy { it.getChunkNumber() } } override fun getStatsDataDirectory(): File { val dir = File(rootDirectoryPath, "completion-stats-data") if (!dir.exists()) { dir.mkdir() } return dir } private fun File.getChunkNumber() = this.name.substringAfter('_').toInt() private fun String.isIntConvertable(): Boolean { try { this.toInt() return true } catch (e: NumberFormatException) { return false } } }
apache-2.0
1c9c2ef23e6efbef47d354f4bd189b1e
31.185567
97
0.608459
4.876563
false
false
false
false
peterholak/mogul
jvm/src/main/kotlin/mogul/platform/jvm/Window.kt
1
3151
package mogul.platform.jvm import mogul.microdom.Color import mogul.microdom.Position import mogul.microdom.setSourceRgb import mogul.platform.Antialias import mogul.platform.AutoClose import sdl2cairo.* import sdl2cairo.SDL2.* import sdl2cairo.pango.* import mogul.platform.Window as WindowInterface import mogul.platform.Cairo as CairoInterface val SDL_EventType.l; get() = (javaClass.getMethod("swigValue").invoke(this) as Int).toLong() class Window( title: String, val userEvents: UserEvents, val width: Int, val height: Int, val background: Color = Color.black, val autoClose: AutoClose = AutoClose.Close ) : WindowInterface { val window = SDL_CreateWindow( title, SDL_WINDOWPOS_UNDEFINED.toInt(), SDL_WINDOWPOS_UNDEFINED.toInt(), width, height, SDL_WindowFlags.SDL_WINDOW_SHOWN.swigValue().toLong() ) ?: throw Exception("Failed to create window") internal val id: Long = SDL_GetWindowID(window) val renderer = SDL_CreateRenderer( window, -1, SDL_RendererFlags.SDL_RENDERER_ACCELERATED.swigValue().toLong() or SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC.swigValue().toLong() ) ?: throw Exception("Failed to initialize renderer") val texture = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_ARGB8888.toLong(), SDL_TextureAccess.SDL_TEXTUREACCESS_STREAMING.swigValue(), width, height ) ?: throw Exception("Failed to create texture") private var invalidated = true override fun wasInvalidated() = invalidated override fun draw(code: (cairo: CairoInterface) -> Unit) { val pixels = new_voidpp() val pitch = new_intp() SDL_LockTexture(texture, null, pixels, pitch) val surface = cairo_image_surface_create_for_data( voidp_to_ucharp(voidpp_value(pixels)), cairo_format_t.CAIRO_FORMAT_ARGB32, width, height, intp_value(pitch) ) val cairoT = cairo_create(surface) ?: throw Exception("Failed to initialize cairo") val cairo = Cairo(cairoT) cairo.setSourceRgb(background) cairo.setAntialias(Antialias.None) cairo_paint(cairoT) code(cairo) cairo_destroy(cairoT) cairo_surface_destroy(surface) SDL_UnlockTexture(texture) invalidate() delete_voidpp(pixels) delete_intp(pitch) } override fun invalidate() { invalidated = true SDL_PushEvent(userEvents.newInvalidated(this)) } override fun render() { SDL2.SDL_RenderClear(renderer) SDL2.SDL_RenderCopy(renderer, texture, null, null) SDL2.SDL_RenderPresent(renderer) invalidated = false } override fun getPosition(): Position { val xPtr = new_intp() val yPtr = new_intp() SDL_GetWindowPosition(window, xPtr, yPtr) return Position(intp_value(xPtr), intp_value(yPtr)).also { delete_intp(xPtr) delete_intp(yPtr) } } }
mit
aa546c1ac431fc31a217161c5aa8cc35
30.828283
143
0.63345
4.135171
false
false
false
false
jkcclemens/FFXIVRaffler
FFXIVRaffler/src/main/kotlin/me/kyleclemens/ffxivraffler/FFXIVRaffler.kt
1
3770
/* * 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 me.kyleclemens.ffxivraffler import me.kyleclemens.ffxivraffler.gui.GUIUtils import me.kyleclemens.ffxivraffler.gui.Raffle import me.kyleclemens.ffxivraffler.util.OS import me.kyleclemens.osx.HelperApplication import me.kyleclemens.osx.HelperQuitResponse import me.kyleclemens.osx.HelperQuitStrategy import me.kyleclemens.osx.events.HelperAppReOpenedEvent import me.kyleclemens.osx.events.HelperQuitEvent import me.kyleclemens.osx.handlers.HelperQuitHandler import me.kyleclemens.osx.listeners.HelperAppReOpenedListener import java.awt.Dimension import java.awt.event.WindowAdapter import java.awt.event.WindowEvent import javax.swing.UIManager import javax.swing.UnsupportedLookAndFeelException import javax.swing.WindowConstants class FFXIVRaffler { companion object { fun cleanUp() { if (FFXIVRaffler.getOS() != OS.OS_X) { System.exit(0) } } fun getOS(): OS { return with(System.getProperty("os.name").toLowerCase()) { when { this.contains("mac") -> OS.OS_X this.contains("linux") -> OS.LINUX this.contains("windows") -> OS.WINDOWS else -> OS.OTHER } } } } } fun main(args: Array<String>) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) } catch (e: ClassNotFoundException) { e.printStackTrace() } catch (e: InstantiationException) { e.printStackTrace() } catch (e: UnsupportedLookAndFeelException) { e.printStackTrace() } catch (e: IllegalAccessException) { e.printStackTrace() } val os = FFXIVRaffler.getOS() if (os == OS.OS_X) { val osxApplication = HelperApplication() System.setProperty("apple.laf.useScreenMenuBar", "true") osxApplication.addAppEventListener(object : HelperAppReOpenedListener { override fun appReOpened(event: HelperAppReOpenedEvent) { val frame = GUIUtils.openedFrames["FFXIV Raffler"] ?: return frame.pack() frame.isVisible = true } }) osxApplication.setQuitStrategy(HelperQuitStrategy.CLOSE_ALL_WINDOWS) osxApplication.setQuitHandler(object : HelperQuitHandler { override fun handleQuitRequestWith(event: HelperQuitEvent, response: HelperQuitResponse) { FFXIVRaffler.cleanUp() System.exit(0) } }) } val raffle = Raffle() GUIUtils.openWindow( raffle, "FFXIV Raffler", { frame -> val menuBar = GUIUtils.createMenuBar(frame, raffle) frame.jMenuBar = menuBar if (os == OS.OS_X) { val osxApplication = HelperApplication() osxApplication.setDefaultMenuBar(menuBar) } frame.addWindowListener(object : WindowAdapter() { override fun windowOpened(e: WindowEvent) { raffle.targetField.requestFocus() } override fun windowClosed(e: WindowEvent) { FFXIVRaffler.cleanUp() } override fun windowDeactivated(e: WindowEvent) { if (os == OS.OS_X) { this.windowClosed(e) } } }) }, WindowConstants.HIDE_ON_CLOSE, { it.minimumSize = Dimension(it.width, it.height) } ) }
mpl-2.0
52b911d90a2bd040c869512862fb50f8
33.587156
102
0.607162
4.586375
false
false
false
false
SimonMarquis/FCM-toolbox
app/src/main/java/fr/smarquis/fcm/data/model/Message.kt
1
891
package fr.smarquis.fcm.data.model import androidx.annotation.Keep import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity @Keep data class Message( @PrimaryKey @ColumnInfo(name = "messageId") val messageId: String, @ColumnInfo(name = "from") val from: String?, @ColumnInfo(name = "to") val to: String?, @ColumnInfo(name = "data") val data: Map<String, String>, @ColumnInfo(name = "collapseKey") val collapseKey: String?, @ColumnInfo(name = "messageType") val messageType: String?, @ColumnInfo(name = "sentTime") val sentTime: Long, @ColumnInfo(name = "ttl") val ttl: Int, @ColumnInfo(name = "priority") val priority: Int, @ColumnInfo(name = "originalPriority") val originalPriority: Int, @ColumnInfo(name = "payload") val payload: Payload? = null)
apache-2.0
43208fd92aed3e42673f7285622637ee
39.5
73
0.667789
4.031674
false
false
false
false
samuelclay/NewsBlur
clients/android/NewsBlur/src/com/newsblur/subscription/SubscriptionManager.kt
1
12742
package com.newsblur.subscription import android.app.Activity import android.content.Context import com.android.billingclient.api.AcknowledgePurchaseParams import com.android.billingclient.api.AcknowledgePurchaseResponseListener import com.android.billingclient.api.BillingClient import com.android.billingclient.api.BillingClientStateListener import com.android.billingclient.api.BillingFlowParams import com.android.billingclient.api.BillingResult import com.android.billingclient.api.Purchase import com.android.billingclient.api.PurchasesUpdatedListener import com.android.billingclient.api.SkuDetails import com.android.billingclient.api.SkuDetailsParams import com.newsblur.R import com.newsblur.network.APIManager import com.newsblur.service.NBSyncService import com.newsblur.util.AppConstants import com.newsblur.util.FeedUtils import com.newsblur.util.Log import com.newsblur.util.NBScope import com.newsblur.util.PrefsUtils import com.newsblur.util.executeAsyncTask import dagger.hilt.EntryPoint import dagger.hilt.InstallIn import dagger.hilt.android.EntryPointAccessors import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.text.DateFormat import java.text.SimpleDateFormat import java.util.* interface SubscriptionManager { /** * Open connection to Play Store to retrieve * purchases and subscriptions. */ fun startBillingConnection(listener: SubscriptionsListener? = null) /** * Generated subscription state by retrieve all available subscriptions * and checking whether the user has an active subscription. * * Subscriptions are configured via the Play Store console. */ fun syncSubscriptionState() /** * Launch the billing flow overlay for a specific subscription. * @param activity Activity on which the billing overlay will be displayed. * @param skuDetails Subscription details for the intended purchases. */ fun purchaseSubscription(activity: Activity, skuDetails: SkuDetails) /** * Sync subscription state between NewsBlur and Play Store. */ suspend fun syncActiveSubscription(): Job /** * Notify backend of active Play Store subscription. */ fun saveReceipt(purchase: Purchase) suspend fun hasActiveSubscription(): Boolean } interface SubscriptionsListener { fun onActiveSubscription(renewalMessage: String?) {} fun onAvailableSubscription(skuDetails: SkuDetails) {} fun onBillingConnectionReady() {} fun onBillingConnectionError(message: String? = null) {} } @EntryPoint @InstallIn(SingletonComponent::class) interface SubscriptionManagerEntryPoint { fun apiManager(): APIManager } class SubscriptionManagerImpl( private val context: Context, private val scope: CoroutineScope = NBScope, ) : SubscriptionManager { private var listener: SubscriptionsListener? = null private val acknowledgePurchaseListener = AcknowledgePurchaseResponseListener { billingResult: BillingResult -> when (billingResult.responseCode) { BillingClient.BillingResponseCode.OK -> { Log.d(this, "acknowledgePurchaseResponseListener OK") scope.launch(Dispatchers.Default) { syncActiveSubscription() } } BillingClient.BillingResponseCode.BILLING_UNAVAILABLE -> { // Billing API version is not supported for the type requested. Log.d(this, "acknowledgePurchaseResponseListener BILLING_UNAVAILABLE") } BillingClient.BillingResponseCode.SERVICE_UNAVAILABLE -> { // Network connection is down. Log.d(this, "acknowledgePurchaseResponseListener SERVICE_UNAVAILABLE") } else -> { // Handle any other error codes. Log.d(this, "acknowledgePurchaseResponseListener ERROR - message: " + billingResult.debugMessage) } } } /** * Billing client listener triggered after every user purchase intent. */ private val purchaseUpdateListener = PurchasesUpdatedListener { billingResult: BillingResult, purchases: List<Purchase>? -> if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) { Log.d(this, "purchaseUpdateListener OK") for (purchase in purchases) { handlePurchase(purchase) } } else if (billingResult.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) { // Handle an error caused by a user cancelling the purchase flow. Log.d(this, "purchaseUpdateListener USER_CANCELLED") } else if (billingResult.responseCode == BillingClient.BillingResponseCode.BILLING_UNAVAILABLE) { // Billing API version is not supported for the type requested. Log.d(this, "purchaseUpdateListener BILLING_UNAVAILABLE") } else if (billingResult.responseCode == BillingClient.BillingResponseCode.SERVICE_UNAVAILABLE) { // Network connection is down. Log.d(this, "purchaseUpdateListener SERVICE_UNAVAILABLE") } else { // Handle any other error codes. Log.d(this, "purchaseUpdateListener ERROR - message: " + billingResult.debugMessage) } } private val billingClientStateListener: BillingClientStateListener = object : BillingClientStateListener { override fun onBillingSetupFinished(billingResult: BillingResult) { if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) { Log.d(this, "onBillingSetupFinished OK") listener?.onBillingConnectionReady() } else { listener?.onBillingConnectionError("Error connecting to Play Store.") } } override fun onBillingServiceDisconnected() { Log.d(this, "onBillingServiceDisconnected") // Try to restart the connection on the next request to // Google Play by calling the startConnection() method. listener?.onBillingConnectionError("Error connecting to Play Store.") } } private val billingClient: BillingClient = BillingClient.newBuilder(context) .setListener(purchaseUpdateListener) .enablePendingPurchases() .build() override fun startBillingConnection(listener: SubscriptionsListener?) { this.listener = listener billingClient.startConnection(billingClientStateListener) } override fun syncSubscriptionState() { scope.launch(Dispatchers.Default) { if (hasActiveSubscription()) syncActiveSubscription() else syncAvailableSubscription() } } override fun purchaseSubscription(activity: Activity, skuDetails: SkuDetails) { Log.d(this, "launchBillingFlow for sku: ${skuDetails.sku}") val billingFlowParams = BillingFlowParams.newBuilder() .setSkuDetails(skuDetails) .build() billingClient.launchBillingFlow(activity, billingFlowParams) } override suspend fun syncActiveSubscription() = scope.launch(Dispatchers.Default) { val hasNewsBlurSubscription = PrefsUtils.getIsPremium(context) val activePlayStoreSubscription = getActiveSubscriptionAsync().await() if (hasNewsBlurSubscription || activePlayStoreSubscription != null) { listener?.let { val renewalString: String? = getRenewalMessage(activePlayStoreSubscription) withContext(Dispatchers.Main) { it.onActiveSubscription(renewalString) } } } if (!hasNewsBlurSubscription && activePlayStoreSubscription != null) { saveReceipt(activePlayStoreSubscription) } } override suspend fun hasActiveSubscription(): Boolean = PrefsUtils.getIsPremium(context) || getActiveSubscriptionAsync().await() != null override fun saveReceipt(purchase: Purchase) { Log.d(this, "saveReceipt: ${purchase.orderId}") val hiltEntryPoint = EntryPointAccessors .fromApplication(context.applicationContext, SubscriptionManagerEntryPoint::class.java) scope.executeAsyncTask( doInBackground = { hiltEntryPoint.apiManager().saveReceipt(purchase.orderId, purchase.skus.first()) }, onPostExecute = { if (!it.isError) { NBSyncService.forceFeedsFolders() FeedUtils.triggerSync(context) } } ) } private suspend fun syncAvailableSubscription() = scope.launch(Dispatchers.Default) { val skuDetails = getAvailableSubscriptionAsync().await() withContext(Dispatchers.Main) { skuDetails?.let { Log.d(this, it.toString()) listener?.onAvailableSubscription(it) } ?: listener?.onBillingConnectionError() } } private fun getAvailableSubscriptionAsync(): Deferred<SkuDetails?> { val deferred = CompletableDeferred<SkuDetails?>() val params = SkuDetailsParams.newBuilder().apply { // add subscription SKUs from Play Store setSkusList(listOf(AppConstants.PREMIUM_SKU)) setType(BillingClient.SkuType.SUBS) }.build() billingClient.querySkuDetailsAsync(params) { _: BillingResult?, skuDetailsList: List<SkuDetails>? -> Log.d(this, "SkuDetailsResponse ${skuDetailsList.toString()}") skuDetailsList?.let { // Currently interested only in the premium yearly News Blur subscription. val skuDetails = it.find { skuDetails -> skuDetails.sku == AppConstants.PREMIUM_SKU } Log.d(this, skuDetails.toString()) deferred.complete(skuDetails) } ?: deferred.complete(null) } return deferred } private fun getActiveSubscriptionAsync(): Deferred<Purchase?> { val deferred = CompletableDeferred<Purchase?>() billingClient.queryPurchasesAsync(BillingClient.SkuType.SUBS) { _, purchases -> val purchase = purchases.find { purchase -> purchase.skus.contains(AppConstants.PREMIUM_SKU) } deferred.complete(purchase) } return deferred } private fun handlePurchase(purchase: Purchase) { Log.d(this, "handlePurchase: ${purchase.orderId}") if (purchase.purchaseState == Purchase.PurchaseState.PURCHASED && purchase.isAcknowledged) { scope.launch(Dispatchers.Default) { syncActiveSubscription() } } else if (purchase.purchaseState == Purchase.PurchaseState.PURCHASED && !purchase.isAcknowledged) { // need to acknowledge first time sub otherwise it will void Log.d(this, "acknowledge purchase: ${purchase.orderId}") AcknowledgePurchaseParams.newBuilder() .setPurchaseToken(purchase.purchaseToken) .build() .also { billingClient.acknowledgePurchase(it, acknowledgePurchaseListener) } } } /** * Generate subscription renewal message. */ private fun getRenewalMessage(purchase: Purchase?): String? { val expirationTimeMs = PrefsUtils.getPremiumExpire(context) return when { // lifetime subscription expirationTimeMs == 0L -> { context.getString(R.string.premium_subscription_no_expiration) } expirationTimeMs > 0 -> { // date constructor expects ms val expirationDate = Date(expirationTimeMs * 1000) val dateFormat: DateFormat = SimpleDateFormat("EEE, MMMM d, yyyy", Locale.getDefault()) dateFormat.timeZone = TimeZone.getDefault() if (purchase != null && !purchase.isAutoRenewing) { context.getString(R.string.premium_subscription_expiration, dateFormat.format(expirationDate)) } else { context.getString(R.string.premium_subscription_renewal, dateFormat.format(expirationDate)) } } else -> null } } }
mit
2110a40ea81acdaa438233872c7785be
39.582803
127
0.663554
5.55207
false
false
false
false
EyeSeeTea/QAApp
app/src/main/java/org/eyeseetea/malariacare/data/repositories/UserD2ApiRepository.kt
1
2067
package org.eyeseetea.malariacare.data.repositories import okhttp3.OkHttpClient import org.eyeseetea.malariacare.data.d2api.BasicAuthInterceptor import org.eyeseetea.malariacare.data.d2api.UserD2Api import org.eyeseetea.malariacare.data.database.utils.PreferencesState import org.eyeseetea.malariacare.domain.boundary.repositories.UserFailure import org.eyeseetea.malariacare.domain.boundary.repositories.UserRepository import org.eyeseetea.malariacare.domain.common.Either import org.eyeseetea.malariacare.domain.entity.User import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class UserD2ApiRepository : UserRepository { private lateinit var userD2Api: UserD2Api private var lastServerURL: String? = null init { initializeApi() } override fun getCurrent(): Either<UserFailure, User> { return try { initializeApi() val userResponse = userD2Api.getMe().execute() if (userResponse!!.isSuccessful && userResponse.body() != null) { val user = userResponse.body() Either.Right(user!!) } else { Either.Left(UserFailure.UnexpectedError) } } catch (e: Exception) { Either.Left(UserFailure.NetworkFailure) } } private fun initializeApi() { val credentials = PreferencesState.getInstance().creedentials if (credentials != null && credentials.serverURL != lastServerURL) { val authInterceptor = BasicAuthInterceptor(credentials.username, credentials.password) val retrofit = Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .client( OkHttpClient.Builder() .addInterceptor(authInterceptor).build() ) .baseUrl(credentials.serverURL) .build() userD2Api = retrofit.create(UserD2Api::class.java) lastServerURL = credentials.serverURL } } }
gpl-3.0
5c6c13ca57fba1e2c03ec0620070c5cc
32.885246
98
0.663764
4.898104
false
false
false
false
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/search/suggestion/SuggestionCardView.kt
1
5287
package jp.toastkid.yobidashi.search.suggestion import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import androidx.cardview.widget.CardView import androidx.core.view.isVisible import androidx.databinding.DataBindingUtil import com.google.android.flexbox.AlignItems import com.google.android.flexbox.FlexDirection import com.google.android.flexbox.FlexWrap import com.google.android.flexbox.FlexboxLayoutManager import com.google.android.flexbox.JustifyContent import jp.toastkid.api.suggestion.SuggestionApi import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.databinding.ViewCardSearchSuggestionBinding import jp.toastkid.yobidashi.libs.Toaster import jp.toastkid.yobidashi.libs.network.NetworkChecker import jp.toastkid.yobidashi.search.SearchFragmentViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * Facade of search suggestion module. * Initialize with binding object. * * @author toastkidjp */ class SuggestionCardView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : CardView(context, attrs, defStyleAttr) { /** * Suggest ModuleAdapter. */ private var adapter: Adapter? = null /** * Suggestion API. */ private val suggestionApi = SuggestionApi() /** * Cache. */ private val cache = HashMap<String, List<String>>(SUGGESTION_CACHE_CAPACITY) private var binding: ViewCardSearchSuggestionBinding? = null /** * Last subscription's lastSubscription. */ private var lastSubscription: Job? = null init { val from = LayoutInflater.from(context) binding = DataBindingUtil.inflate( from, R.layout.view_card_search_suggestion, this, true ) adapter = Adapter(from) val layoutManager = FlexboxLayoutManager(context) layoutManager.flexDirection = FlexDirection.ROW layoutManager.flexWrap = FlexWrap.WRAP layoutManager.justifyContent = JustifyContent.FLEX_START layoutManager.alignItems = AlignItems.STRETCH initializeSearchSuggestionList(layoutManager) } private fun initializeSearchSuggestionList(layoutManager: FlexboxLayoutManager) { binding?.searchSuggestions?.layoutManager = layoutManager binding?.searchSuggestions?.adapter = adapter } /** * Clear suggestion items. */ fun clear() { adapter?.clear() adapter?.notifyDataSetChanged() } /** * Request web API. * * @param key */ fun request(key: String) { lastSubscription?.cancel() if (cache.containsKey(key)) { val cachedList = cache[key] ?: return lastSubscription = replace(cachedList) return } val context = context if (NetworkChecker.isNotAvailable(context)) { return } if (PreferenceApplier(context).wifiOnly && NetworkChecker.isUnavailableWiFi(context)) { Toaster.tShort(context, R.string.message_wifi_not_connecting) return } suggestionApi.fetchAsync(key) { suggestions -> if (suggestions.isEmpty()) { CoroutineScope(Dispatchers.Main).launch { hide() } return@fetchAsync } cache[key] = suggestions lastSubscription = replace(suggestions) } } /** * Use for voice search. * * @param words Recognizer result words. */ internal fun addAll(words: List<String>) { CoroutineScope(Dispatchers.Main).launch { withContext(Dispatchers.Default) { words.forEach { adapter?.add(it) } } adapter?.notifyDataSetChanged() } } /** * Replace suggestions with specified items. * * @param suggestions * @return [Job] */ private fun replace(suggestions: Iterable<String>): Job { return CoroutineScope(Dispatchers.Main).launch { withContext(Dispatchers.Default) { adapter?.clear() suggestions.forEach { adapter?.add(it) } } show() adapter?.notifyDataSetChanged() } } /** * Show this module. */ fun show() { if (!isVisible && isEnabled) { runOnMainThread { isVisible = true } } } /** * Hide this module. */ fun hide() { if (isVisible) { runOnMainThread { isVisible = false } } } private fun runOnMainThread(action: () -> Unit) = post { action() } fun setViewModel(viewModel: SearchFragmentViewModel) { adapter?.setViewModel(viewModel) } /** * Dispose last subscription. */ fun dispose() { lastSubscription?.cancel() binding = null } companion object { /** * Suggest cache capacity. */ private const val SUGGESTION_CACHE_CAPACITY = 30 } }
epl-1.0
524771d7a4ab9a35fe4ebd15cc7c0eba
25.303483
95
0.634197
5.020893
false
false
false
false
android/trackr
app/src/main/java/com/example/android/trackr/ui/DataBindingDelegates.kt
1
1820
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.trackr.ui import android.view.View import androidx.databinding.ViewDataBinding import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver /** * Retrieves a data binding handle in a Fragment. The property should not be accessed before * [Fragment.onViewCreated]. * * ``` * private val binding by dataBindings(HomeFragmentBinding::bind) * * override fun onViewCreated(view: View, savedInstanceState: Bundle?) { * // Use the binding. * } * ``` */ inline fun <reified BindingT : ViewDataBinding> Fragment.dataBindings( crossinline bind: (View) -> BindingT ) = object : Lazy<BindingT> { private var cached: BindingT? = null private val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_DESTROY) { cached = null } } override val value: BindingT get() = cached ?: bind(requireView()).also { it.lifecycleOwner = viewLifecycleOwner viewLifecycleOwner.lifecycle.addObserver(observer) cached = it } override fun isInitialized() = cached != null }
apache-2.0
4a951a387d77f5154b78d490acbc45fb
30.929825
92
0.697253
4.449878
false
false
false
false
SUPERCILEX/Robot-Scouter
library/core-data/src/main/java/com/supercilex/robotscouter/core/data/Args.kt
1
1890
package com.supercilex.robotscouter.core.data import android.content.Intent import android.os.Bundle import androidx.core.os.bundleOf import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.supercilex.robotscouter.core.model.Team const val TEAM_KEY = "com.supercilex.robotscouter.data.util.Team" const val TEAMS_KEY = "com.supercilex.robotscouter.data.util.Teams" const val REF_KEY = "com.supercilex.robotscouter.REF" const val TAB_KEY = "tab_key" const val SCOUT_ARGS_KEY = "scout_args" const val TEMPLATE_ARGS_KEY = "template_args" const val KEY_ADD_SCOUT = "add_scout" const val KEY_OVERRIDE_TEMPLATE_KEY = "override_template_key" fun <T : CharSequence> T?.nullOrFull() = takeUnless { isNullOrBlank() } fun Bundle.putRef(ref: DocumentReference) = putString(REF_KEY, ref.path) fun Bundle.getRef() = Firebase.firestore.document(checkNotNull(getString(REF_KEY))) fun Team.toBundle() = bundleOf(TEAM_KEY to this@toBundle) fun Intent.putExtra(teams: List<Team>): Intent = putExtra(TEAMS_KEY, ArrayList(teams)) fun Bundle.getTeam(): Team = checkNotNull(getParcelable(TEAM_KEY)) fun Intent.getTeamListExtra(): List<Team> = getParcelableArrayListExtra<Team>(TEAMS_KEY).orEmpty() fun getTabIdBundle(key: String?) = bundleOf(TAB_KEY to key) fun getTabId(bundle: Bundle?): String? = bundle?.getString(TAB_KEY) fun getScoutBundle( team: Team, addScout: Boolean = false, overrideTemplateId: String? = null, scoutId: String? = null ): Bundle { require(addScout || overrideTemplateId == null) { "Can't use an override id without adding a scout." } return team.toBundle().apply { putBoolean(KEY_ADD_SCOUT, addScout) putString(KEY_OVERRIDE_TEMPLATE_KEY, overrideTemplateId) putAll(getTabIdBundle(scoutId)) } }
gpl-3.0
dc17569f78eb58a37d8ecb040ce852b1
34.660377
98
0.742328
3.62069
false
false
false
false
Ekito/koin
koin-projects/examples/androidx-samples/src/main/java/org/koin/sample/androidx/scope/ScopedActivityA.kt
1
1677
package org.koin.sample.androidx.scope import android.os.Bundle import kotlinx.android.synthetic.main.scoped_activity_a.* import org.junit.Assert.* import org.koin.androidx.scope.ScopeActivity import org.koin.core.qualifier.named import org.koin.sample.android.R import org.koin.sample.androidx.components.* import org.koin.sample.androidx.components.scope.Session import org.koin.sample.androidx.components.scope.SessionActivity import org.koin.sample.androidx.utils.navigateTo class ScopedActivityA : ScopeActivity(contentLayoutId = R.layout.scoped_activity_a) { // Inject from current scope val currentSession by inject<Session>() val currentActivitySession by inject<SessionActivity>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) assertEquals(currentSession, get<Session>()) // Conpare different scope instances val scopeSession1 = getKoin().createScope(SESSION_1, named(SCOPE_ID)) val scopeSession2 = getKoin().createScope(SESSION_2, named(SCOPE_ID)) assertNotEquals(scopeSession1.get<Session>(named(SCOPE_SESSION)), currentSession) assertNotEquals(scopeSession1.get<Session>(named(SCOPE_SESSION)), scopeSession2.get<Session>(named(SCOPE_SESSION))) // set data in scope SCOPE_ID val session = getKoin().createScope(SCOPE_ID, named(SCOPE_ID)).get<Session>(named(SCOPE_SESSION)) session.id = ID title = "Scope Activity A" scoped_a_button.setOnClickListener { navigateTo<ScopedActivityB>(isRoot = true) } assertTrue(this == currentActivitySession.activity) } }
apache-2.0
32f3b876f76d404f11028c7044f7c8b1
36.288889
105
0.729278
4.3
false
false
false
false
MyDogTom/detekt
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/ThrowingNewInstanceOfSameExceptionSpek.kt
1
1448
package io.gitlab.arturbosch.detekt.rules.exceptions import io.gitlab.arturbosch.detekt.test.lint import org.assertj.core.api.Assertions import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.subject.SubjectSpek class ThrowingNewInstanceOfSameExceptionSpek : SubjectSpek<ThrowingNewInstanceOfSameException>({ subject { ThrowingNewInstanceOfSameException() } given("a catch block which rethrows a new instance of the caught exception") { val code = """ fun x() { try { } catch (e: IllegalStateException) { throw IllegalStateException(e) } } """ it("should report") { val findings = subject.lint(code) Assertions.assertThat(findings).hasSize(1) } } given("a catch block which rethrows a new instance of another exception") { val code = """ fun x() { try { } catch (e: IllegalStateException) { throw IllegalArgumentException(e) } } """ it("should not report") { val findings = subject.lint(code) Assertions.assertThat(findings).hasSize(0) } } given("a catch block which throws a new instance of the same exception type without wrapping the caught exception") { val code = """ fun x() { try { } catch (e: IllegalStateException) { throw IllegalStateException() } } """ it("should not report") { val findings = subject.lint(code) Assertions.assertThat(findings).hasSize(0) } } })
apache-2.0
6d8b54e157ae5eb3e81475f8f71950c4
23.542373
118
0.69268
3.638191
false
false
false
false
geckour/Egret
app/src/main/java/com/geckour/egret/model/AccessToken.kt
1
506
package com.geckour.egret.model import com.github.gfx.android.orma.annotation.* import java.util.* @Table data class AccessToken( @Setter("id") @PrimaryKey(autoincrement = true) val id: Long = -1L, @Setter("access_token") @Column val token: String = "", @Setter("instance_id") @Column val instanceId: Long = -1L, @Setter("account_id") @Column(indexed = true) val accountId: Long = -1L, @Setter("is_current") @Column(indexed = true) var isCurrent: Boolean = false )
gpl-3.0
d923a78b13a382c39a0c02183f7b15a7
38
84
0.662055
3.56338
false
false
false
false
http4k/http4k
http4k-testing/hamkrest/src/main/kotlin/org/http4k/hamkrest/cookie.kt
1
1549
package org.http4k.hamkrest import com.natpryce.hamkrest.Matcher import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.has import com.natpryce.hamkrest.present import org.http4k.core.cookie.Cookie import org.http4k.core.cookie.SameSite import java.time.Instant fun hasCookieName(expected: CharSequence): Matcher<Cookie> = has(Cookie::name, equalTo(expected)) @JvmName("hasCookieValueNullableString") fun hasCookieValue(matcher: Matcher<String?>): Matcher<Cookie> = has(Cookie::value, matcher) fun hasCookieValue(matcher: Matcher<String>): Matcher<Cookie> = has(Cookie::value, present(matcher)) fun hasCookieValue(expected: CharSequence): Matcher<Cookie> = has(Cookie::value, equalTo(expected)) fun hasCookieDomain(expected: CharSequence): Matcher<Cookie> = has("domain", { c: Cookie -> c.domain }, equalTo(expected)) fun hasCookiePath(expected: CharSequence): Matcher<Cookie> = has("path", { c: Cookie -> c.path }, equalTo(expected)) fun isSecureCookie(expected: Boolean = true): Matcher<Cookie> = has("secure", { c: Cookie -> c.secure }, equalTo(expected)) fun isHttpOnlyCookie(expected: Boolean = true): Matcher<Cookie> = has("httpOnly", { c: Cookie -> c.httpOnly }, equalTo(expected)) fun hasCookieExpiry(expected: Instant): Matcher<Cookie> = hasCookieExpiry(equalTo(expected)) fun hasCookieExpiry(matcher: Matcher<Instant>): Matcher<Cookie> = has("expiry", { c: Cookie -> c.expires!! }, matcher) fun hasCookieSameSite(expected: SameSite): Matcher<Cookie> = has("sameSite", { c: Cookie -> c.sameSite }, equalTo(expected))
apache-2.0
9c15a3bcfcd28bbb5d7ddd710f88fdf8
47.40625
129
0.758554
3.796569
false
false
false
false
openhab/openhab.android
mobile/src/main/java/org/openhab/habdroid/ui/preference/WifiSsidInputPreference.kt
1
4785
/* * Copyright (c) 2010-2022 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.habdroid.ui.preference import android.content.Context import android.os.Build import android.text.InputType import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.ArrayAdapter import androidx.core.content.edit import androidx.core.os.bundleOf import androidx.fragment.app.DialogFragment import androidx.preference.DialogPreference import androidx.preference.PreferenceDialogFragmentCompat import com.google.android.material.switchmaterial.SwitchMaterial import com.google.android.material.textfield.MaterialAutoCompleteTextView import com.google.android.material.textfield.TextInputLayout import org.openhab.habdroid.R import org.openhab.habdroid.core.OpenHabApplication import org.openhab.habdroid.model.toWifiSsids import org.openhab.habdroid.ui.CustomDialogPreference import org.openhab.habdroid.util.getCurrentWifiSsid class WifiSsidInputPreference constructor(context: Context, attrs: AttributeSet) : DialogPreference(context, attrs), CustomDialogPreference { private var value: Pair<String, Boolean>? = null init { dialogTitle = null setPositiveButtonText(android.R.string.ok) setNegativeButtonText(android.R.string.cancel) } override fun getDialogLayoutResource(): Int { return R.layout.pref_dialog_wifi_ssid } private fun updateSummary() { val ssids = value?.first?.toWifiSsids() summary = if (ssids.isNullOrEmpty()) { context.getString(R.string.info_not_set) } else { ssids.joinToString(", ") } } fun setValue(value: Pair<String, Boolean>? = this.value) { if (callChangeListener(value)) { this.value = value updateSummary() } } override fun createDialog(): DialogFragment { return PrefFragment.newInstance(key, title) } class PrefFragment : PreferenceDialogFragmentCompat() { private lateinit var editorWrapper: TextInputLayout private lateinit var editor: MaterialAutoCompleteTextView private lateinit var restrictButton: SwitchMaterial override fun onCreateDialogView(context: Context): View { val inflater = LayoutInflater.from(activity) val v = inflater.inflate(R.layout.pref_dialog_wifi_ssid, null) editorWrapper = v.findViewById(R.id.input_wrapper) editor = v.findViewById(android.R.id.edit) restrictButton = v.findViewById(R.id.restrict_switch) editor.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE arguments?.getCharSequence(KEY_TITLE)?.let { title -> editorWrapper.hint = title } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { editor.importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_NO } val currentValue = (preference as WifiSsidInputPreference).value val currentSsid = preference.context.getCurrentWifiSsid(OpenHabApplication.DATA_ACCESS_TAG_SELECT_SERVER_WIFI) val currentSsidAsArray = currentSsid?.let { arrayOf(it) } ?: emptyArray() val adapter = ArrayAdapter(editor.context, android.R.layout.simple_dropdown_item_1line, currentSsidAsArray) editor.setAdapter(adapter) editor.setText(currentValue?.first.orEmpty()) editor.setSelection(editor.text.length) restrictButton.isChecked = currentValue?.second ?: false return v } override fun onDialogClosed(positiveResult: Boolean) { if (positiveResult) { val prefs = preference.sharedPreferences!! prefs.edit { val pref = preference as WifiSsidInputPreference pref.setValue(Pair(editor.text.toString(), restrictButton.isChecked)) } } } companion object { private const val KEY_TITLE = "title" fun newInstance( key: String, title: CharSequence? ): PrefFragment { val f = PrefFragment() f.arguments = bundleOf( ARG_KEY to key, KEY_TITLE to title ) return f } } } }
epl-1.0
1cc2b35896cbc45824135f93149f8e93
34.708955
119
0.66186
4.809045
false
false
false
false
MFlisar/Lumberjack
library-notification/src/main/java/com/michaelflisar/lumberjack/ExtensionNotification.kt
1
2891
package com.michaelflisar.lumberjack import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.core.app.NotificationCompat import com.michaelflisar.feedbackmanager.Feedback import com.michaelflisar.feedbackmanager.FeedbackFile import com.michaelflisar.lumberjack.core.CoreUtil import java.io.File /* * convenient extension to simply show a notification for exceptions/infos/whatever that the user should report if possible * * - app version will be appended to the subject automatically * - file should be local and accessible files - they will be exposed via a ContentProvider so that the email client can access the file */ fun L.showCrashNotification( context: Context, logFile: File?, receiver: String, appIcon: Int, notificationChannelId: String, notificationId: Int, notificationTitle: String = "Rare exception found", notificationText: String = "Please report this error by clicking this notification, thanks", subject: String = "Exception found in ${context.packageName}", titleForChooser: String = "Send report with", filesToAppend: List<File> = emptyList() ) { val allFiles = filesToAppend.toMutableList() logFile?.let { allFiles.add(0, it) } val feedback = Feedback( listOf(receiver), CoreUtil.getRealSubject(context, subject), attachments = allFiles.map { FeedbackFile.DefaultName(it) } ) feedback .startNotification( context, titleForChooser, notificationTitle, notificationText, appIcon, notificationChannelId, notificationId ) } /* * convenient extension to simply show a notification to the user or for debugging infos */ fun L.showInfoNotification( context: Context, notificationChannelId: String, notificationId: Int, notificationTitle: String, notificationText: String, notificationIcon: Int, clickIntent: Intent? = null, apply: ((builder: NotificationCompat.Builder) -> Unit)? = null ) { val pendingIntent = clickIntent?.let { val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PendingIntent.FLAG_IMMUTABLE } else 0 PendingIntent.getActivity(context, 0, it, flag) } val builder: NotificationCompat.Builder = NotificationCompat.Builder(context, notificationChannelId) .setSmallIcon(notificationIcon) .setContentTitle(notificationTitle) .setContentText(notificationText) pendingIntent?.let { builder.setContentIntent(it) } apply?.let { it(builder) } val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(notificationId, builder.build()) }
apache-2.0
1ded1ea6d1ae4715123bc43403b0a82c
33.843373
136
0.717399
4.810316
false
false
false
false
timbotetsu/kotlin-koans
src/v_builders/_36_ExtensionFunctionLiterals.kt
1
561
package v_builders import util.TODO import util.doc36 fun todoTask36(): Nothing = TODO( """ Task 36. Read about extension function literals. You can declare `isEven` and `isOdd` as values, that can be called as extension functions. Complete the declarations below. """, documentation = doc36() ) fun task36(): List<Boolean> { val isEven: Int.() -> Boolean = { this % 2 == 0 } val isOdd: Int.() -> Boolean = { this % 2 == 1 } return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven()) }
mit
23a5c29500852965bd7ed2fb01bfccbd
22.375
98
0.59893
4.007143
false
false
false
false
tfcbandgeek/SmartReminders-android
app/src/main/java/jgappsandgames/smartreminderslite/utility/ShortcutUtility.kt
1
6087
package jgappsandgames.smartreminderslite.utility // Java import java.util.Arrays // Android OS import android.app.Activity import android.content.pm.ShortcutInfo import android.content.pm.ShortcutManager import android.graphics.drawable.Icon // App import jgappsandgames.smartreminderslite.R // Save import jgappsandgames.smartreminderssave.tasks.TaskManager import jgappsandgames.smartreminderssave.utility.hasShortcuts import org.jetbrains.anko.shortcutManager /** * ShortcutUtility * Created by joshua on 1/5/2018. */ // Create Shortcuts ------------------------------------------------------------------------ fun createTagShortcut(activity: Activity) { if (hasShortcuts()) activity.shortcutManager.addDynamicShortcuts( Arrays.asList(ShortcutInfo.Builder(activity, "tag") .setShortLabel("Tags") .setLongLabel("Tags") .setIcon(Icon.createWithResource(activity, R.drawable.label)) .setIntent(buildHomeIntent(activity, IntentOptions(shortcut = true))) .build())) } fun createPriorityShortcut(activity: Activity) { if (hasShortcuts()) activity.shortcutManager.addDynamicShortcuts( Arrays.asList(ShortcutInfo.Builder(activity, "priority") .setShortLabel("Priority") .setLongLabel("Priority") .setIcon(Icon.createWithResource(activity, android.R.drawable.btn_star)) .setIntent(buildPriorityIntent(activity, IntentOptions(shortcut = true))) .build())) } fun createStatusShortcut(activity: Activity) { if (hasShortcuts()) activity.shortcutManager.addDynamicShortcuts( Arrays.asList(ShortcutInfo.Builder(activity, "status") .setShortLabel("Status") .setLongLabel("Status") .setIcon(Icon.createWithResource(activity, R.drawable.status)) .setIntent(buildStatusIntent(activity, IntentOptions(shortcut = true))) .build())) } fun createTodayShortcut(activity: Activity) { if (hasShortcuts()) activity.shortcutManager.addDynamicShortcuts( Arrays.asList(ShortcutInfo.Builder(activity, "today") .setShortLabel("Today") .setLongLabel("Today") .setIcon(Icon.createWithResource(activity, R.drawable.today)) .setIntent(buildDayIntent(activity, IntentOptions(shortcut = true))) .build())) } fun createWeekShortcut(activity: Activity) { if (hasShortcuts()) activity.shortcutManager.addDynamicShortcuts( Arrays.asList(ShortcutInfo.Builder(activity, "week") .setShortLabel("Week") .setLongLabel("Week") .setIcon(Icon.createWithResource(activity, R.drawable.week)) .setIntent(buildWeekIntent(activity, IntentOptions(shortcut = true))) .build())) } fun createMonthShortcut(activity: Activity) { if (hasShortcuts()) activity.shortcutManager.addDynamicShortcuts( Arrays.asList(ShortcutInfo.Builder(activity, "month") .setShortLabel("Month") .setLongLabel("Month") .setIntent(buildMonthIntent(activity, IntentOptions(shortcut = true))) .build())) } fun createTaskShortcut(activity: Activity, task: String) { if (hasShortcuts()) { val taskObject = TaskManager.taskPool.getPoolObject().load(task) val sT: String = if (taskObject.getTitle().length > 8) taskObject.getTitle().substring(0, 8) else taskObject.getTitle() activity.shortcutManager.addDynamicShortcuts(Arrays.asList(ShortcutInfo.Builder(activity, task) .setShortLabel(sT) .setLongLabel(taskObject.getTitle()) .setIcon(Icon.createWithResource(activity, android.R.drawable.ic_menu_agenda)) .setIntent(buildTaskIntent(activity, IntentOptions(shortcut = true), TaskOptions(task = taskObject))) .build())) } } // Remove Shortcuts ------------------------------------------------------------------------ fun removeTagShortcut(activity: Activity) { if (hasShortcuts()) { val manager = activity.getSystemService(ShortcutManager::class.java) val s = ArrayList<String>() s.add("tag") manager!!.removeDynamicShortcuts(s) } } fun removePriorityShortcut(activity: Activity) { if (hasShortcuts()) { val manager = activity.getSystemService(ShortcutManager::class.java) val s = ArrayList<String>() s.add("priority") manager!!.removeDynamicShortcuts(s) } } fun removeStatusShortcut(activity: Activity) { if (hasShortcuts()) { val manager = activity.getSystemService(ShortcutManager::class.java) val s = ArrayList<String>() s.add("status") manager!!.removeDynamicShortcuts(s) } } fun removeTodayShortcut(activity: Activity) { if (hasShortcuts()) { val manager = activity.getSystemService(ShortcutManager::class.java) val s = ArrayList<String>() s.add("today") manager!!.removeDynamicShortcuts(s) } } fun removeWeekShortcut(activity: Activity) { if (hasShortcuts()) { val manager = activity.getSystemService(ShortcutManager::class.java) val s = ArrayList<String>() s.add("week") manager!!.removeDynamicShortcuts(s) } } fun removeMonthShortcut(activity: Activity) { if (hasShortcuts()) { val manager = activity.getSystemService(ShortcutManager::class.java) val s = ArrayList<String>() s.add("month") manager!!.removeDynamicShortcuts(s) } } fun removeTaskShortcut(activity: Activity, task: String) { if (hasShortcuts()) { val manager = activity.getSystemService(ShortcutManager::class.java) val s = ArrayList<String>() s.add(task) manager!!.removeDynamicShortcuts(s) } }
apache-2.0
9b5e15b470bc3d1ce895f7928cc9fe9b
35.238095
117
0.628553
5.026424
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/drinking_water/AddDrinkingWater.kt
1
1542
package de.westnordost.streetcomplete.quests.drinking_water import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.OUTDOORS class AddDrinkingWater : OsmFilterQuestType<DrinkingWater>() { override val elementFilter = """ nodes with ( man_made = water_tap or man_made = water_well or natural = spring ) and access !~ private|no and indoor != yes and !drinking_water and !drinking_water:legal and amenity != drinking_water """ override val commitMessage = "Add whether water is drinkable" override val wikiLink = "Key:drinking_water" override val icon = R.drawable.ic_quest_drinking_water override val isDeleteElementEnabled = true override val questTypeAchievements = listOf(OUTDOORS) override fun getTitle(tags: Map<String, String>) = R.string.quest_drinking_water_title override fun getTitleArgs(tags: Map<String, String>, featureName: Lazy<String?>) = arrayOf(featureName.value.toString()) override fun createForm() = AddDrinkingWaterForm() override fun applyAnswerTo(answer: DrinkingWater, changes: StringMapChangesBuilder) { changes.addOrModify("drinking_water", answer.osmValue) answer.osmLegalValue?.let { changes.addOrModify("drinking_water:legal", it) } } }
gpl-3.0
931df0aa9a67e9a5ddc52498ec893282
39.578947
90
0.732166
4.589286
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
example/src/main/java/org/wordpress/android/fluxc/example/ui/products/WooProductsFragment.kt
1
36384
package org.wordpress.android.fluxc.example.ui.products import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.fragment_woo_products.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.action.WCProductAction.ADDED_PRODUCT_CATEGORY import org.wordpress.android.fluxc.action.WCProductAction.ADDED_PRODUCT_TAGS import org.wordpress.android.fluxc.action.WCProductAction.DELETED_PRODUCT import org.wordpress.android.fluxc.action.WCProductAction.FETCH_PRODUCTS import org.wordpress.android.fluxc.action.WCProductAction.FETCH_PRODUCT_CATEGORIES import org.wordpress.android.fluxc.action.WCProductAction.FETCH_PRODUCT_TAGS import org.wordpress.android.fluxc.action.WCProductAction.FETCH_SINGLE_PRODUCT_SHIPPING_CLASS import org.wordpress.android.fluxc.example.R.layout import org.wordpress.android.fluxc.example.prependToLog import org.wordpress.android.fluxc.example.replaceFragment import org.wordpress.android.fluxc.example.ui.StoreSelectingFragment import org.wordpress.android.fluxc.example.utils.showSingleLineDialog import org.wordpress.android.fluxc.generated.WCProductActionBuilder import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.WCProductCategoryModel import org.wordpress.android.fluxc.model.WCProductImageModel import org.wordpress.android.fluxc.store.MediaStore import org.wordpress.android.fluxc.store.WCAddonsStore import org.wordpress.android.fluxc.store.WCProductStore import org.wordpress.android.fluxc.store.WCProductStore.AddProductCategoryPayload import org.wordpress.android.fluxc.store.WCProductStore.AddProductTagsPayload import org.wordpress.android.fluxc.store.WCProductStore.DeleteProductPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchProductCategoriesPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchProductReviewsPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchProductShippingClassListPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchProductSkuAvailabilityPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchProductTagsPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchProductVariationsPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchProductsPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchSingleProductPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchSingleProductReviewPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchSingleProductShippingClassPayload import org.wordpress.android.fluxc.store.WCProductStore.OnProductCategoryChanged import org.wordpress.android.fluxc.store.WCProductStore.OnProductChanged import org.wordpress.android.fluxc.store.WCProductStore.OnProductImagesChanged import org.wordpress.android.fluxc.store.WCProductStore.OnProductShippingClassesChanged import org.wordpress.android.fluxc.store.WCProductStore.OnProductSkuAvailabilityChanged import org.wordpress.android.fluxc.store.WCProductStore.OnProductTagChanged import org.wordpress.android.fluxc.store.WCProductStore.OnProductsSearched import org.wordpress.android.fluxc.store.WCProductStore.SearchProductsPayload import org.wordpress.android.fluxc.store.WCProductStore.UpdateProductImagesPayload import org.wordpress.android.fluxc.store.WooCommerceStore import javax.inject.Inject @Suppress("LargeClass") class WooProductsFragment : StoreSelectingFragment() { @Inject internal lateinit var dispatcher: Dispatcher @Inject internal lateinit var wcProductStore: WCProductStore @Inject lateinit var addonsStore: WCAddonsStore @Inject internal lateinit var wooCommerceStore: WooCommerceStore @Inject internal lateinit var mediaStore: MediaStore private var pendingFetchSingleProductShippingClassRemoteId: Long? = null private var pendingFetchProductVariationsProductRemoteId: Long? = null private var pendingFetchSingleProductVariationOffset: Int = 0 private var pendingFetchProductShippingClassListOffset: Int = 0 private var pendingFetchProductCategoriesOffset: Int = 0 private var pendingFetchProductTagsOffset: Int = 0 private var enteredCategoryName: String? = null private val enteredTagNames: MutableList<String> = mutableListOf() private val coroutineScope = CoroutineScope(Dispatchers.Main) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(layout.fragment_woo_products, container, false) @Suppress("LongMethod", "ComplexMethod") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) fetch_single_product.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog(activity, "Enter the remoteProductId of product to fetch:") { editText -> editText.text.toString().toLongOrNull()?.let { remoteProductId -> prependToLog("Submitting request to fetch product by remoteProductID $remoteProductId") coroutineScope.launch { val result = wcProductStore.fetchSingleProduct( FetchSingleProductPayload( site, remoteProductId ) ) val product = wcProductStore.getProductByRemoteId(site, result.remoteProductId) product?.let { val numVariations = it.getVariationIdList().size if (numVariations > 0) { prependToLog("Single product with $numVariations variations fetched! ${it.name}") } else { prependToLog("Single product fetched! ${it.name}") } } ?: prependToLog("WARNING: Fetched product not found in the local database!") } } ?: prependToLog("No valid remoteOrderId defined...doing nothing") } } } fetch_single_variation.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter the remoteProductId of variation to fetch:" ) { productIdText -> val productRemoteId = productIdText.text.toString().toLongOrNull() productRemoteId?.let { productId -> showSingleLineDialog( activity, "Enter the remoteVariationId of variation to fetch:" ) { variationIdText -> variationIdText.text.toString().toLongOrNull()?.let { variationId -> coroutineScope.launch { prependToLog( "Submitting request to fetch product by " + "remoteProductId $productRemoteId, " + "remoteVariationProductID $variationId" ) val result = wcProductStore.fetchSingleVariation(site, productId, variationId) prependToLog("Fetching single variation " + "${result.error?.let { "failed" } ?: "was successful"}" ) val variation = wcProductStore.getVariationByRemoteId( site, result.remoteProductId, result.remoteVariationId ) variation?.let { prependToLog("Variation with id! ${it.remoteVariationId} found in local db") } ?: prependToLog("WARNING: Fetched product not found in the local database!") } } ?: prependToLog("No valid remoteVariationId defined...doing nothing") } } ?: prependToLog("No valid remoteProductId defined...doing nothing") } } } fetch_product_sku_availability.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter a product SKU:" ) { editText -> val payload = FetchProductSkuAvailabilityPayload(site, editText.text.toString()) dispatcher.dispatch(WCProductActionBuilder.newFetchProductSkuAvailabilityAction(payload)) } } } fetch_products.setOnClickListener { selectedSite?.let { site -> val payload = FetchProductsPayload(site) dispatcher.dispatch(WCProductActionBuilder.newFetchProductsAction(payload)) } } fetch_products_with_filters.setOnClickListener { replaceFragment(WooProductFiltersFragment.newInstance(selectedPos)) } fetch_specific_products.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog(activity, "Enter remote product IDs, separated by comma:") { editText -> val ids = editText.text.toString().replace(" ", "").split(",").mapNotNull { val id = it.toLongOrNull() if (id == null) { prependToLog("$it is not a valid remote product ID, ignoring...") } id } if (ids.isNotEmpty()) { coroutineScope.launch { val result = wcProductStore.fetchProducts( site, includedProductIds = ids ) if (result.isError) { prependToLog("Fetching products failed: ${result.error.message}") } else { val products = wcProductStore.getProductsByRemoteIds(site, ids) prependToLog("${products.size} were fetched") prependToLog("$products") } } } else { prependToLog("No valid product IDs...doing nothing") } } } } search_products.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter a search query:" ) { editText -> val payload = SearchProductsPayload( site = site, searchQuery = editText.text.toString() ) dispatcher.dispatch(WCProductActionBuilder.newSearchProductsAction(payload)) } } } search_products_sku.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter a SKU to search for:" ) { editText -> val payload = SearchProductsPayload( site = site, searchQuery = editText.text.toString(), isSkuSearch = true ) dispatcher.dispatch(WCProductActionBuilder.newSearchProductsAction(payload)) } } } fetch_product_variations.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter the remoteProductId of product to fetch variations:" ) { editText -> editText.text.toString().toLongOrNull()?.let { id -> coroutineScope.launch { pendingFetchProductVariationsProductRemoteId = id prependToLog("Submitting request to fetch product variations by remoteProductID $id") val result = wcProductStore.fetchProductVariations(FetchProductVariationsPayload(site, id)) prependToLog( "Fetched ${result.rowsAffected} product variants. " + "More variants available ${result.canLoadMore}" ) if (result.canLoadMore) { pendingFetchSingleProductVariationOffset += result.rowsAffected load_more_product_variations.visibility = View.VISIBLE load_more_product_variations.isEnabled = true } else { pendingFetchSingleProductVariationOffset = 0 load_more_product_variations.isEnabled = false } } } ?: prependToLog("No valid remoteProductId defined...doing nothing") } } } load_more_product_variations.setOnClickListener { selectedSite?.let { site -> pendingFetchProductVariationsProductRemoteId?.let { id -> coroutineScope.launch { prependToLog("Submitting offset request to fetch product variations by remoteProductID $id") val payload = FetchProductVariationsPayload( site, id, offset = pendingFetchSingleProductVariationOffset ) val result = wcProductStore.fetchProductVariations(payload) prependToLog( "Fetched ${result.rowsAffected} product variants. " + "More variants available ${result.canLoadMore}" ) if (result.canLoadMore) { pendingFetchSingleProductVariationOffset += result.rowsAffected load_more_product_variations.visibility = View.VISIBLE load_more_product_variations.isEnabled = true } else { pendingFetchSingleProductVariationOffset = 0 load_more_product_variations.isEnabled = false } } } ?: prependToLog("No valid remoteProductId defined...doing nothing") } } fetch_reviews_for_product.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter the remoteProductId of product to fetch reviews:" ) { editText -> val remoteProductId = editText.text.toString().toLongOrNull() remoteProductId?.let { id -> coroutineScope.launch { prependToLog("Submitting request to fetch product reviews for remoteProductID $id") val result = wcProductStore.fetchProductReviews( FetchProductReviewsPayload( site, productIds = listOf(remoteProductId) ) ) prependToLog("Fetched ${result.rowsAffected} product reviews") } } ?: prependToLog("No valid remoteProductId defined...doing nothing") } } } fetch_all_reviews.setOnClickListener { selectedSite?.let { site -> coroutineScope.launch { prependToLog("Submitting request to fetch product reviews for site ${site.id}") val payload = FetchProductReviewsPayload(site) val result = wcProductStore.fetchProductReviews(payload) prependToLog("Fetched ${result.rowsAffected} product reviews") } } } fetch_review_by_id.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter the remoteReviewId of the review to fetch:" ) { editText -> val reviewId = editText.text.toString().toLongOrNull() reviewId?.let { id -> coroutineScope.launch { prependToLog("Submitting request to fetch product review for ID $id") val payload = FetchSingleProductReviewPayload(site, id) val result = wcProductStore.fetchSingleProductReview(payload) if (!result.isError) { prependToLog("Fetched ${result.rowsAffected} single product review") } else { prependToLog("Fetching single product review FAILED") } } } ?: prependToLog("No valid remoteReviewId defined...doing nothing") } } } update_review_status.setOnClickListener { selectedSite?.let { site -> coroutineScope.launch { val id = showSingleLineDialog( activity = requireActivity(), message = "Enter the remoteReviewId of the review", isNumeric = true )?.toLongOrNull() if (id == null) { prependToLog("Please enter a valid id") return@launch } val newStatus = showSingleLineDialog( activity = requireActivity(), message = "Enter the new status: (approved|hold|spam|trash)" ) if (newStatus == null) { prependToLog("Please enter a valid status") return@launch } val result = wcProductStore.updateProductReviewStatus( site = site, reviewId = id, newStatus = newStatus ) if (!result.isError) { prependToLog("Product Review status updated successfully") } else { prependToLog( "Product Review status update failed, " + "${result.error.type} ${result.error.message}" ) } } } } fetch_product_shipping_class.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter the remoteShippingClassId of the site to fetch:" ) { editText -> pendingFetchSingleProductShippingClassRemoteId = editText.text.toString().toLongOrNull() pendingFetchSingleProductShippingClassRemoteId?.let { id -> prependToLog("Submitting request to fetch product shipping class for ID $id") val payload = FetchSingleProductShippingClassPayload(site, id) dispatcher.dispatch(WCProductActionBuilder.newFetchSingleProductShippingClassAction(payload)) } ?: prependToLog("No valid remoteShippingClassId defined...doing nothing") } } } fetch_product_shipping_classes.setOnClickListener { selectedSite?.let { site -> prependToLog("Submitting request to fetch product shipping classes for site ${site.id}") val payload = FetchProductShippingClassListPayload(site) dispatcher.dispatch(WCProductActionBuilder.newFetchProductShippingClassListAction(payload)) } } load_more_product_shipping_classes.setOnClickListener { selectedSite?.let { site -> prependToLog("Submitting offset request to fetch product shipping classes for site ${site.id}") val payload = FetchProductShippingClassListPayload( site, offset = pendingFetchProductShippingClassListOffset ) dispatcher.dispatch(WCProductActionBuilder.newFetchProductShippingClassListAction(payload)) } } fetch_product_categories.setOnClickListener { selectedSite?.let { site -> prependToLog("Submitting request to fetch product categories for site ${site.id}") val payload = FetchProductCategoriesPayload(site) dispatcher.dispatch(WCProductActionBuilder.newFetchProductCategoriesAction(payload)) } } observe_product_categories.setOnClickListener { selectedSite?.let { site -> coroutineScope.launch { val categories = wcProductStore.observeCategories(site).first() prependToLog("Categories: $categories") } } } load_more_product_categories.setOnClickListener { selectedSite?.let { site -> prependToLog("Submitting offset request to fetch product categories for site ${site.id}") val payload = FetchProductCategoriesPayload( site, offset = pendingFetchProductCategoriesOffset ) dispatcher.dispatch(WCProductActionBuilder.newFetchProductCategoriesAction(payload)) } } add_product_category.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter a category name:" ) { editText -> enteredCategoryName = editText.text.toString() if (enteredCategoryName != null && enteredCategoryName?.isNotEmpty() == true) { prependToLog("Submitting request to add product category") val wcProductCategoryModel = WCProductCategoryModel().apply { name = enteredCategoryName!! } val payload = AddProductCategoryPayload(site, wcProductCategoryModel) dispatcher.dispatch(WCProductActionBuilder.newAddProductCategoryAction(payload)) } else { prependToLog("No category name entered...doing nothing") } } } } fetch_product_tags.setOnClickListener { showSingleLineDialog( activity, "Enter a search query, leave blank for none:" ) { editText -> val searchQuery = editText.text.toString() selectedSite?.let { site -> prependToLog("Submitting request to fetch product tags for site ${site.id}") val payload = FetchProductTagsPayload(site, searchQuery = searchQuery) dispatcher.dispatch(WCProductActionBuilder.newFetchProductTagsAction(payload)) } } } load_more_product_tags.setOnClickListener { selectedSite?.let { site -> prependToLog("Submitting offset request to fetch product tags for site ${site.id}") val payload = FetchProductTagsPayload(site, offset = pendingFetchProductTagsOffset) dispatcher.dispatch(WCProductActionBuilder.newFetchProductTagsAction(payload)) } } add_product_tags.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter tag name:" ) { editTextTagName1 -> showSingleLineDialog( activity, "Enter another tag name:" ) { editTextTagName2 -> val tagName1 = editTextTagName1.text.toString() val tagName2 = editTextTagName2.text.toString() if (tagName1.isNotEmpty() && tagName2.isNotEmpty()) { enteredTagNames.add(tagName1) enteredTagNames.add(tagName2) prependToLog("Submitting request to add product tags for site ${site.id}") val payload = AddProductTagsPayload(site, enteredTagNames) dispatcher.dispatch(WCProductActionBuilder.newAddProductTagsAction(payload)) } else { prependToLog("Tag name is empty. Doing nothing..") } } } } } test_add_ons.setOnClickListener { selectedSite?.let { site -> WooAddonsTestFragment.show(childFragmentManager, site.siteId) } } update_product_images.setOnClickListener { showSingleLineDialog( activity, "Enter the remoteProductId of the product to update images:" ) { editTextProduct -> editTextProduct.text.toString().toLongOrNull()?.let { productId -> showSingleLineDialog( activity, "Enter the mediaId of the image to assign to the product:" ) { editTextMedia -> editTextMedia.text.toString().toLongOrNull()?.let { mediaId -> updateProductImages(productId, mediaId) } } } } } update_product.setOnClickListener { replaceFragment(WooUpdateProductFragment.newInstance(selectedPos)) } update_variation.setOnClickListener { replaceFragment(WooUpdateVariationFragment.newInstance(selectedPos)) } add_new_product.setOnClickListener { replaceFragment(WooUpdateProductFragment.newInstance(selectedPos, isAddNewProduct = true)) } delete_product.setOnClickListener { showSingleLineDialog( activity, "Enter the remoteProductId of the product to delete:" ) { editTextProduct -> editTextProduct.text.toString().toLongOrNull()?.let { productId -> selectedSite?.let { site -> val payload = DeleteProductPayload(site, productId) dispatcher.dispatch(WCProductActionBuilder.newDeleteProductAction(payload)) } } } } batch_update_variations.setOnClickListener { replaceFragment(WooBatchUpdateVariationsFragment.newInstance(selectedPos)) } } /** * Note that this will replace all this product's images with a single image, as defined by mediaId. Also note * that the media must already be cached for this to work (ie: you may need to go to the first screen in the * example app, tap Media, then ensure the media is fetched) */ private fun updateProductImages(productId: Long, mediaId: Long) { selectedSite?.let { site -> mediaStore.getSiteMediaWithId(site, mediaId)?.let { media -> prependToLog("Submitting request to update product images") val imageList = ArrayList<WCProductImageModel>().also { it.add(WCProductImageModel.fromMediaModel(media)) } val payload = UpdateProductImagesPayload(site, productId, imageList) dispatcher.dispatch(WCProductActionBuilder.newUpdateProductImagesAction(payload)) } ?: prependToLog(("Not a valid media id")) } ?: prependToLog(("No site selected")) } override fun onStart() { super.onStart() dispatcher.register(this) } override fun onStop() { super.onStop() dispatcher.unregister(this) } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onProductChanged(event: OnProductChanged) { if (event.isError) { prependToLog("Error from " + event.causeOfChange + " - error: " + event.error.type) return } selectedSite?.let { site -> when (event.causeOfChange) { FETCH_PRODUCTS -> { prependToLog("Fetched ${event.rowsAffected} products") } DELETED_PRODUCT -> { prependToLog("${event.rowsAffected} product deleted") } else -> prependToLog("Product store was updated from a " + event.causeOfChange) } } } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onProductsSearched(event: OnProductsSearched) { if (event.isError) { prependToLog("Error searching products - error: " + event.error.type) } else { prependToLog("Found ${event.searchResults.size} products matching ${event.searchQuery}") } } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onProductSkuAvailabilityChanged(event: OnProductSkuAvailabilityChanged) { if (event.isError) { prependToLog("Error searching product sku availability - error: " + event.error.type) } else { prependToLog("Sku ${event.sku} available for site ${selectedSite?.name}: ${event.available}") } } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onProductImagesChanged(event: OnProductImagesChanged) { if (event.isError) { prependToLog("Error updating product images - error: " + event.error.type) } else { prependToLog("Product images updated") } } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onProductCategoriesChanged(event: OnProductCategoryChanged) { if (event.isError) { prependToLog("Error from " + event.causeOfChange + " - error: " + event.error.type) return } selectedSite?.let { site -> when (event.causeOfChange) { FETCH_PRODUCT_CATEGORIES -> { prependToLog("Fetched ${event.rowsAffected} product categories. " + "More categories available ${event.canLoadMore}") if (event.canLoadMore) { pendingFetchProductCategoriesOffset += event.rowsAffected load_more_product_categories.visibility = View.VISIBLE load_more_product_categories.isEnabled = true } else { pendingFetchProductCategoriesOffset = 0 load_more_product_categories.isEnabled = false } } ADDED_PRODUCT_CATEGORY -> { val category = enteredCategoryName?.let { wcProductStore.getProductCategoryByNameAndParentId(site, it) } prependToLog("${event.rowsAffected} product category added with name: ${category?.name}") } else -> { } } } } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onProductShippingClassesChanged(event: OnProductShippingClassesChanged) { if (event.isError) { prependToLog("Error from " + event.causeOfChange + " - error: " + event.error.type) return } selectedSite?.let { site -> when (event.causeOfChange) { FETCH_SINGLE_PRODUCT_SHIPPING_CLASS -> logFetchSingleProductShippingClass(site) else -> checkProductShippingClassesAndLoadMore(event) } } } private fun logFetchSingleProductShippingClass(site: SiteModel) { pendingFetchSingleProductShippingClassRemoteId?.let { remoteId -> pendingFetchSingleProductShippingClassRemoteId = null val productShippingClass = wcProductStore.getShippingClassByRemoteId(site, remoteId) productShippingClass?.let { prependToLog("Single product shipping class fetched! ${it.name}") } ?: prependToLog("WARNING: Fetched shipping class not found in the local database!") } } private fun checkProductShippingClassesAndLoadMore(event: OnProductShippingClassesChanged) { prependToLog( "Fetched ${event.rowsAffected} product shipping classes. " + "More shipping classes available ${event.canLoadMore}" ) if (event.canLoadMore) { pendingFetchProductShippingClassListOffset += event.rowsAffected load_more_product_shipping_classes.visibility = View.VISIBLE load_more_product_shipping_classes.isEnabled = true } else { pendingFetchProductShippingClassListOffset = 0 load_more_product_shipping_classes.isEnabled = false } } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onProductTagChanged(event: OnProductTagChanged) { if (event.isError) { prependToLog("Error from " + event.causeOfChange + " - error: " + event.error.type) return } selectedSite?.let { site -> when (event.causeOfChange) { FETCH_PRODUCT_TAGS -> { prependToLog("Fetched ${event.rowsAffected} product tags. More tags available ${event.canLoadMore}") if (event.canLoadMore) { pendingFetchProductTagsOffset += event.rowsAffected load_more_product_tags.visibility = View.VISIBLE load_more_product_tags.isEnabled = true } else { pendingFetchProductTagsOffset = 0 load_more_product_tags.isEnabled = false } } ADDED_PRODUCT_TAGS -> { val tags = wcProductStore.getProductTagsByNames(site, enteredTagNames) val tagNames = tags.map { it.name }.joinToString(",") prependToLog("${event.rowsAffected} product tags added for $tagNames") if (enteredTagNames.size > event.rowsAffected) { prependToLog("Error occurred when trying to add some product tags") } } else -> { } } } } }
gpl-2.0
90898ae6b3ce1c571c112a3234cc104b
46.685452
120
0.558542
6.534483
false
false
false
false
adityaDave2017/my-vocab
app/src/main/java/com/android/vocab/provider/VocabProvider.kt
1
10854
package com.android.vocab.provider import android.content.ContentProvider import android.content.ContentUris import android.content.ContentValues import android.content.UriMatcher import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.net.Uri import android.util.Log @Suppress("unused") class VocabProvider : ContentProvider() { private val LOG_TAG: String = VocabProvider::class.java.simpleName lateinit var vocabHelper: VocabHelper companion object { val queryWordsAndType:String = """ SELECT * FROM ${VocabContract.WordEntry.TABLE_NAME} INNER JOIN ${VocabContract.WordTypeEntry.TABLE_NAME} ON ${VocabContract.WordEntry.TABLE_NAME}.${VocabContract.WordEntry.COLUMN_TYPE_ID} = ${VocabContract.WordTypeEntry.TABLE_NAME}.${VocabContract.WordTypeEntry._ID} """ val queryWordsAndTypeForId:String = "$queryWordsAndType WHERE ${VocabContract.WordEntry._ID} = ?" val queryForSynonymsWord: String = """ SELECT * FROM ${VocabContract.SynonymEntry.TABLE_NAME} INNER JOIN ${VocabContract.WordEntry.TABLE_NAME} ON ${VocabContract.SynonymEntry.TABLE_NAME}.${VocabContract.SynonymEntry.COLUMN_SYNONYM_WORD_ID} = ${VocabContract.WordEntry.TABLE_NAME}.${VocabContract.WordEntry._ID} WHERE ${VocabContract.SynonymEntry.TABLE_NAME}.${VocabContract.SynonymEntry.COLUMN_MAIN_WORD_ID} = ? """ val queryForAntonymsWord: String = """ SELECT * FROM ${VocabContract.AntonymEntry.TABLE_NAME} INNER JOIN ${VocabContract.WordEntry.TABLE_NAME} ON ${VocabContract.AntonymEntry.TABLE_NAME}.${VocabContract.AntonymEntry.COLUMN_ANTONYM_WORD_ID} = ${VocabContract.WordEntry.TABLE_NAME}.${VocabContract.WordEntry._ID} WHERE ${VocabContract.AntonymEntry.TABLE_NAME}.${VocabContract.AntonymEntry.COLUMN_MAIN_WORD_ID} = ? """ val URI_MATCHER: UriMatcher = UriMatcher(UriMatcher.NO_MATCH) val WORD_TYPE_LIST: Int = 100 val WORD_TYPE_ITEM: Int = 101 val WORD_LIST: Int = 200 val WORD_ITEM: Int = 201 val SENTENCE_LIST: Int = 300 val SENTENCE_ITEM: Int = 301 val SYNONYM_LIST: Int = 400 val SYNONYM_ITEM: Int = 401 val ANTONYM_LIST: Int = 500 val ANTONYM_ITEM: Int = 501 val WORD_AND_TYPE_LIST:Int = 600 val WORD_AND_TYPE_ITEM: Int = 601 val SYNONYM_FOR_WORD_LIST: Int = 700 val ANTONYM_FOR_WORD_LIST: Int = 701 init { URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, VocabContract.PATH_WORD_TYPE, WORD_TYPE_LIST) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, "${VocabContract.PATH_WORD_TYPE}/#", WORD_TYPE_ITEM) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, VocabContract.PATH_WORD, WORD_LIST) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, "${VocabContract.PATH_WORD}/#", WORD_ITEM) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, VocabContract.PATH_SENTENCE, SENTENCE_LIST) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, "${VocabContract.PATH_SENTENCE}/#", SENTENCE_ITEM) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, VocabContract.PATH_SYNONYM, SYNONYM_LIST) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, "${VocabContract.PATH_SYNONYM}/#", SYNONYM_ITEM) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, VocabContract.PATH_ANTONYM, ANTONYM_LIST) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, "${VocabContract.PATH_ANTONYM}/#", ANTONYM_ITEM) /* Custom Query Registration */ URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, VocabContract.PATH_WORD_AND_TYPE, WORD_AND_TYPE_LIST) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, "${VocabContract.PATH_WORD_AND_TYPE}/#", WORD_AND_TYPE_ITEM) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, "${VocabContract.PATH_SYNONYM_FOR_WORD}/#", SYNONYM_FOR_WORD_LIST) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, "${VocabContract.PATH_ANTONYM_FOR_WORD}/#", ANTONYM_FOR_WORD_LIST) } } override fun insert(uri: Uri?, contentValues: ContentValues?): Uri { val sqliteDatabase: SQLiteDatabase = vocabHelper.writableDatabase val id: Long = when (URI_MATCHER.match(uri)) { WORD_TYPE_LIST -> sqliteDatabase.insert(VocabContract.WordTypeEntry.TABLE_NAME, null, contentValues) WORD_LIST -> sqliteDatabase.insert(VocabContract.WordEntry.TABLE_NAME, null, contentValues) SENTENCE_LIST -> sqliteDatabase.insert(VocabContract.SentenceEntry.TABLE_NAME, null, contentValues) SYNONYM_LIST -> sqliteDatabase.insert(VocabContract.SynonymEntry.TABLE_NAME, null, contentValues) ANTONYM_LIST -> sqliteDatabase.insert(VocabContract.AntonymEntry.TABLE_NAME, null, contentValues) else -> throw IllegalArgumentException("Uri not supported: $uri") } return ContentUris.withAppendedId(uri, id) } override fun query(uri: Uri?, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor { val sqliteDatabase: SQLiteDatabase = vocabHelper.readableDatabase val cursor: Cursor = when (URI_MATCHER.match(uri)) { WORD_TYPE_LIST -> sqliteDatabase.query(VocabContract.WordTypeEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder) WORD_TYPE_ITEM -> sqliteDatabase.query(VocabContract.WordTypeEntry.TABLE_NAME, projection, "${VocabContract.WordTypeEntry.COLUMN_TYPE_NAME}=?", arrayOf(ContentUris.parseId(uri).toString()), null, null, sortOrder) WORD_LIST -> sqliteDatabase.query(VocabContract.WordEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder) WORD_ITEM -> sqliteDatabase.query(VocabContract.WordEntry.TABLE_NAME, projection, "${VocabContract.WordEntry._ID}=?", arrayOf(ContentUris.parseId(uri).toString()), null, null, sortOrder) SENTENCE_LIST -> sqliteDatabase.query(VocabContract.SentenceEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder) SENTENCE_ITEM -> sqliteDatabase.query(VocabContract.SentenceEntry.TABLE_NAME, projection, "${VocabContract.SentenceEntry._ID}=?", arrayOf(ContentUris.parseId(uri).toString()), null, null, sortOrder) SYNONYM_ITEM -> sqliteDatabase.query(VocabContract.SynonymEntry.TABLE_NAME, projection, "${VocabContract.SynonymEntry.COLUMN_MAIN_WORD_ID}=?", arrayOf(ContentUris.parseId(uri).toString()), null, null, sortOrder) ANTONYM_ITEM -> sqliteDatabase.query(VocabContract.AntonymEntry.TABLE_NAME, projection, "${VocabContract.AntonymEntry.COLUMN_MAIN_WORD_ID}=?", arrayOf(ContentUris.parseId(uri).toString()), null, null, sortOrder) WORD_AND_TYPE_LIST -> sqliteDatabase.rawQuery(queryWordsAndType, null) WORD_AND_TYPE_ITEM -> sqliteDatabase.rawQuery(queryWordsAndTypeForId, arrayOf(ContentUris.parseId(uri).toString())) SYNONYM_FOR_WORD_LIST -> sqliteDatabase.rawQuery(queryForSynonymsWord, arrayOf(ContentUris.parseId(uri).toString())) ANTONYM_FOR_WORD_LIST -> sqliteDatabase.rawQuery(queryForAntonymsWord, arrayOf(ContentUris.parseId(uri).toString())) else -> throw IllegalArgumentException("Cannot query unknown uri: $uri") } cursor.setNotificationUri(context?.contentResolver, uri) return cursor } override fun onCreate(): Boolean { vocabHelper = VocabHelper(context) return true } override fun update(uri: Uri?, contentValues: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int { val sqliteDatabase: SQLiteDatabase = vocabHelper.writableDatabase val rows: Int = when (URI_MATCHER.match(uri)) { // WORD_TYPE_ITEM -> sqliteDatabase.update(VocabContract.WordTypeEntry.TABLE_NAME, contentValues, VocabContract.WordTypeEntry._, selectionArgs) WORD_ITEM -> sqliteDatabase.update(VocabContract.WordEntry.TABLE_NAME, contentValues , "${VocabContract.WordEntry._ID}=?", arrayOf(ContentUris.parseId(uri).toString())) // SENTENCE_ITEM -> SYNONYM_ITEM -> sqliteDatabase.update(VocabContract.SynonymEntry.TABLE_NAME, contentValues, "${VocabContract.SynonymEntry._ID}=?", arrayOf(ContentUris.parseId(uri).toString())) ANTONYM_ITEM -> sqliteDatabase.update(VocabContract.AntonymEntry.TABLE_NAME, contentValues, "${VocabContract.AntonymEntry._ID}=?", arrayOf(ContentUris.parseId(uri).toString())) else -> throw IllegalArgumentException("Uri not supported: $uri") } if (rows != 0) { context?.contentResolver?.notifyChange(uri, null) } return rows } override fun delete(uri: Uri?, selection: String?, selectionArgs: Array<out String>?): Int { val sqliteDatabase: SQLiteDatabase = vocabHelper.writableDatabase val rows: Int = when (URI_MATCHER.match(uri)) { // WORD_TYPE_ITEM -> sqliteDatabase.delete(VocabContract.WordTypeEntry.TABLE_NAME, selection, selectionArgs) WORD_ITEM -> sqliteDatabase.delete(VocabContract.WordEntry.TABLE_NAME, "${VocabContract.WordEntry._ID}=?", arrayOf(ContentUris.parseId(uri).toString())) SYNONYM_ITEM -> sqliteDatabase.delete(VocabContract.SynonymEntry.TABLE_NAME, "${VocabContract.SynonymEntry._ID}=?", arrayOf(ContentUris.parseId(uri).toString())) ANTONYM_ITEM -> sqliteDatabase.delete(VocabContract.AntonymEntry.TABLE_NAME, "${VocabContract.AntonymEntry._ID}=?", arrayOf(ContentUris.parseId(uri).toString())) else -> throw IllegalArgumentException("Uri not supported: $uri") } if (rows != 0) { context?.contentResolver?.notifyChange(uri, null) } return rows } override fun getType(uri: Uri?): String { return when (URI_MATCHER.match(uri)) { WORD_TYPE_LIST -> VocabContract.WordTypeEntry.CONTENT_LIST_TYPE WORD_TYPE_ITEM -> VocabContract.WordTypeEntry.CONTENT_ITEM_TYPE WORD_LIST -> VocabContract.WordEntry.CONTENT_LIST_TYPE WORD_ITEM -> VocabContract.WordEntry.CONTENT_ITEM_TYPE SENTENCE_LIST -> VocabContract.SentenceEntry.CONTENT_LIST_TYPE SENTENCE_ITEM -> VocabContract.SentenceEntry.CONTENT_ITEM_TYPE SYNONYM_ITEM -> VocabContract.SynonymEntry.CONTENT_LIST_TYPE ANTONYM_ITEM -> VocabContract.AntonymEntry.CONTENT_LIST_TYPE // Todo: Custom items left else -> throw IllegalArgumentException("No type for uri: $uri") } } }
mit
3a163107330d589c2373b4152dfd6c64
54.953608
224
0.694306
4.729412
false
false
false
false
sabi0/intellij-community
platform/projectModel-api/src/com/intellij/openapi/diagnostic/logger.kt
2
1599
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.diagnostic import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.progress.ProcessCanceledException import kotlin.reflect.KProperty import kotlin.reflect.jvm.javaGetter inline fun <reified T : Any> logger(): Logger = Logger.getInstance(T::class.java) fun logger(category: String): Logger = Logger.getInstance(category) /** * Get logger instance to be used in Kotlin package methods. Usage: * ``` * private val LOG: Logger get() = logger(::LOG) // define at top level of the file containing the function * ``` * In Kotlin 1.1 even simpler declaration will be possible: * ``` * private val LOG: Logger = logger(::LOG) * ``` * Notice explicit type declaration which can't be skipped in this case. */ fun logger(field: KProperty<Logger>): Logger = Logger.getInstance(field.javaGetter!!.declaringClass) inline fun Logger.debug(e: Exception? = null, lazyMessage: () -> String) { if (isDebugEnabled) { debug(lazyMessage(), e) } } inline fun Logger.debugOrInfoIfTestMode(e: Exception? = null, lazyMessage: () -> String) { if (ApplicationManager.getApplication()?.isUnitTestMode == true) { info(lazyMessage()) } else { debug(e, lazyMessage) } } inline fun <T> Logger.runAndLogException(runnable: () -> T): T? { try { return runnable() } catch (e: ProcessCanceledException) { return null } catch (e: Throwable) { error(e) return null } }
apache-2.0
8c3f93f09b5eee81dc41b404efbec5cf
29.769231
140
0.711069
3.977612
false
false
false
false
mercadopago/px-android
example/src/main/java/com/mercadopago/android/px/di/Dependencies.kt
1
733
package com.mercadopago.android.px.di import android.content.Context import com.mercadopago.android.px.di.module.LocalRepositoryModule import com.mercadopago.android.px.di.module.ViewModelModule internal class Dependencies { var viewModelModule: ViewModelModule? = null private set var localPreferences: LocalRepositoryModule? = null private set fun initialize(context: Context) { localPreferences = LocalRepositoryModule(context.applicationContext) viewModelModule = ViewModelModule() } fun clean() { viewModelModule = null localPreferences = null } companion object { @JvmStatic val instance: Dependencies by lazy { Dependencies() } } }
mit
02d4554c95c9df0578909731bcfccee9
26.185185
76
0.717599
5.090278
false
false
false
false
smuzani/Umbrella
app/src/main/java/com/syedmuzani/umbrella/activities/MainActivity.kt
1
2065
package com.syedmuzani.umbrella.activities import android.app.Activity import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import com.syedmuzani.umbrella.R import com.syedmuzani.umbrella.adapters.MainPageListAdapter import com.syedmuzani.umbrella.models.MainMenuLink import java.util.* /** * Central point to visit all other libraries */ class MainActivity : AppCompatActivity() { internal var activity: Activity = this internal var links: MutableList<MainMenuLink> = ArrayList() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.listview) val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) val rv: RecyclerView = findViewById(R.id.rv) initRecyclerView() rv.layoutManager = LinearLayoutManager(this) val orientation = (rv.layoutManager as LinearLayoutManager).orientation val dividerItemDecoration = DividerItemDecoration(this, orientation) rv.addItemDecoration(dividerItemDecoration) rv.adapter = MainPageListAdapter(links) } private fun initRecyclerView() { links.add(MainMenuLink("Facebook Login", FacebookLoginActivity::class.java)) links.add(MainMenuLink("To Do List (File based)", ToDoFileBasedActivity::class.java)) links.add(MainMenuLink("To Do List (DB based)", ToDoDatabasedActivity::class.java)) links.add(MainMenuLink("Anko DSL Layouts", DslActivity::class.java)) links.add(MainMenuLink("VideoView", VideoActivity::class.java)) links.add(MainMenuLink("Fingerprint", FingerprintActivity::class.java)) links.add(MainMenuLink("Firebase With Countdown", FirebaseActivity::class.java)) links.add(MainMenuLink("Date/TimePicker", DateTimePickerActivity::class.java)) } }
artistic-2.0
507980caf57eb098118b203a177edb91
42.93617
93
0.751574
4.640449
false
false
false
false
Mauin/detekt
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/SafeCastSpec.kt
1
1227
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.test.assertThat import io.gitlab.arturbosch.detekt.test.lint import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.subject.SubjectSpek class SafeCastSpec : SubjectSpek<SafeCast>({ subject { SafeCast() } given("some cast expressions") { it("reports negated expression") { val code = """ fun test() { if (element !is KtElement) { null } else { element } }""" assertThat(subject.lint(code)).hasSize(1) } it("reports expression") { val code = """ fun test() { if (element is KtElement) { element } else { null } }""" assertThat(subject.lint(code)).hasSize(1) } it("does not report wrong condition") { val code = """ fun test() { if (element == other) { element } else { null } }""" assertThat(subject.lint(code)).hasSize(0) } it("does not report wrong else clause") { val code = """ fun test() { if (element is KtElement) { element } else { KtElement() } }""" assertThat(subject.lint(code)).hasSize(0) } } })
apache-2.0
6145912a232231ad4f1d49ab2ffac25b
18.790323
50
0.596577
3.298387
false
true
false
false
Mauin/detekt
detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/OffsetsToLineColumn.kt
1
1839
package io.gitlab.arturbosch.detekt.formatting import java.util.ArrayList /** * Extracted and adapted from KtLint. * * @author Artur Bosch */ internal fun calculateLineColByOffset(text: String): (offset: Int) -> Pair<Int, Int> { var i = -1 val e = text.length val arr = ArrayList<Int>() do { arr.add(i + 1) i = text.indexOf('\n', i + 1) } while (i != -1) arr.add(e + if (arr.last() == e) 1 else 0) val segmentTree = SegmentTree(arr.toTypedArray()) return { offset -> val line = segmentTree.indexOf(offset) if (line != -1) { val col = offset - segmentTree.get(line).left line + 1 to col + 1 } else { 1 to 1 } } } internal fun calculateLineBreakOffset(fileContent: String): (offset: Int) -> Int { val arr = ArrayList<Int>() var i = 0 do { arr.add(i) i = fileContent.indexOf("\r\n", i + 1) } while (i != -1) arr.add(fileContent.length) return if (arr.size != 2) { SegmentTree(arr.toTypedArray()).let { return { offset -> it.indexOf(offset) } } } else { _ -> 0 } } internal class SegmentTree(sortedArray: Array<Int>) { private val segments: List<Segment> fun get(i: Int): Segment = segments[i] fun indexOf(v: Int): Int = binarySearch(v, 0, this.segments.size - 1) private fun binarySearch(v: Int, l: Int, r: Int): Int = when { l > r -> -1 else -> { val i = l + (r - l) / 2 val s = segments[i] if (v < s.left) binarySearch(v, l, i - 1) else (if (s.right < v) binarySearch(v, i + 1, r) else i) } } init { require(sortedArray.size > 1) { "At least two data points are required" } sortedArray.reduce { r, v -> require(r <= v) { "Data points are not sorted (ASC)" }; v } segments = sortedArray.take(sortedArray.size - 1) .mapIndexed { i: Int, v: Int -> Segment(v, sortedArray[i + 1] - 1) } } } internal data class Segment(val left: Int, val right: Int)
apache-2.0
13f1896ce70d3151a33de4acdacc56a6
24.541667
90
0.621533
2.799087
false
false
false
false
timusus/Shuttle
app/src/main/java/com/simplecity/amp_library/ui/dialog/WeekSelectorDialog.kt
1
1747
package com.simplecity.amp_library.ui.dialog import android.annotation.SuppressLint import android.app.Dialog import android.content.Context import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v4.app.FragmentManager import android.view.LayoutInflater import android.widget.NumberPicker import com.afollestad.materialdialogs.MaterialDialog import com.simplecity.amp_library.R import com.simplecity.amp_library.model.Playlist import com.simplecity.amp_library.utils.SettingsManager import dagger.android.support.AndroidSupportInjection import javax.inject.Inject class WeekSelectorDialog : DialogFragment() { @Inject lateinit var settingsManager: SettingsManager override fun onAttach(context: Context?) { AndroidSupportInjection.inject(this) super.onAttach(context) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { @SuppressLint("InflateParams") val view = LayoutInflater.from(context).inflate(R.layout.weekpicker, null) val numberPicker: NumberPicker numberPicker = view.findViewById(R.id.weeks) numberPicker.maxValue = 12 numberPicker.minValue = 1 numberPicker.value = settingsManager.numWeeks return MaterialDialog.Builder(context!!) .title(R.string.week_selector) .customView(view, false) .negativeText(R.string.cancel) .positiveText(R.string.button_ok) .onPositive { _, _ -> settingsManager.numWeeks = numberPicker.value } .build() } fun show(fragmentManager: FragmentManager) { show(fragmentManager, TAG) } companion object { const val TAG = "WeekSelectorDialog" } }
gpl-3.0
068bdbf5ade0b32c1d025d06317e9f4e
30.781818
82
0.725816
4.747283
false
false
false
false
GeoffreyMetais/vlc-android
application/tools/src/main/java/org/videolan/tools/BitmapCache.kt
1
3475
/* * ************************************************************************ * BitmapCache.kt * ************************************************************************* * Copyright © 2020 VLC authors and VideoLAN * Author: Nicolas POMEPUY * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * ************************************************************************** * * */ /***************************************************************************** * BitmapCache.java * * Copyright © 2012 VLC authors and VideoLAN * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. */ package org.videolan.tools import android.graphics.Bitmap import android.util.Log import androidx.collection.LruCache import videolan.org.commontools.BuildConfig object BitmapCache { private val mMemCache: LruCache<String, Bitmap> private val TAG = "VLC/BitmapCache" init { // Use 20% of the available memory for this memory cache. val cacheSize = Runtime.getRuntime().maxMemory() / 5 if (BuildConfig.DEBUG) Log.i(TAG, "LRUCache size set to " + cacheSize.readableSize()) mMemCache = object : LruCache<String, Bitmap>(cacheSize.toInt()) { override fun sizeOf(key: String, value: Bitmap): Int { return value.rowBytes * value.height } } } @Synchronized fun getBitmapFromMemCache(key: String?): Bitmap? { if (key == null) return null val b = mMemCache.get(key) if (b == null) { mMemCache.remove(key) return null } return b } @Synchronized fun addBitmapToMemCache(key: String?, bitmap: Bitmap?) { if (key != null && bitmap != null && getBitmapFromMemCache(key) == null) { mMemCache.put(key, bitmap) } } private fun getBitmapFromMemCache(resId: Int): Bitmap? { return getBitmapFromMemCache("res:$resId") } private fun addBitmapToMemCache(resId: Int, bitmap: Bitmap?) { addBitmapToMemCache("res:$resId", bitmap) } @Synchronized fun clear() { mMemCache.evictAll() } }
gpl-2.0
1c9f25401e58c57b6bbc41d70294f97c
33.04902
82
0.618198
4.72517
false
false
false
false
bailuk/AAT
aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/view/search/PoiList.kt
1
2600
package ch.bailu.aat_gtk.view.search import ch.bailu.aat_gtk.app.GtkAppContext import ch.bailu.aat_lib.lib.filter_list.FilterList import ch.bailu.aat_lib.lib.filter_list.FilterListUtil import ch.bailu.aat_lib.preferences.SolidPoiDatabase import ch.bailu.aat_lib.search.poi.PoiListItem import ch.bailu.foc.Foc import ch.bailu.gtk.GTK import ch.bailu.gtk.bridge.ListIndex import ch.bailu.gtk.gtk.ListItem import ch.bailu.gtk.gtk.ListView import ch.bailu.gtk.gtk.ScrolledWindow import ch.bailu.gtk.gtk.SignalListItemFactory import org.mapsforge.poi.storage.PoiCategory class PoiList( private val sdatabase: SolidPoiDatabase, private val selected: Foc, private val onSelected: (model: PoiListItem) -> Unit ) { private val listIndex = ListIndex() private val filterList = FilterList() private val items = HashMap<ListItem, PoiListItemView>() private val list = ListView(listIndex.inSelectionModel(), SignalListItemFactory().apply { onSetup { items[it] = PoiListItemView(it) } onBind { val view = items[it] if (view is PoiListItemView) { val model = filterList.getFromVisible(it.position) if (model is PoiListItem) { view.set(model) } } } onTeardown { val view = items.remove(it) if (view is PoiListItemView) { view.onTeardown() } } }).apply { onActivate { val model = filterList.getFromVisible(it) if (model is PoiListItem) { onSelected(model) } } } val scrolled = ScrolledWindow().apply { child = list hexpand = GTK.TRUE vexpand = GTK.TRUE } init { readList() } private fun readList() { FilterListUtil.readList(filterList, GtkAppContext, sdatabase.valueAsString, selected) listIndex.size = filterList.sizeVisible() } fun updateList() { filterList.filterAll() listIndex.size = filterList.sizeVisible() } fun updateList(text: String) { filterList.filter(text) listIndex.size = filterList.sizeVisible() } fun getSelectedCategories(): ArrayList<PoiCategory> { val export = ArrayList<PoiCategory>(10) for (i in 0 until filterList.sizeVisible()) { val e = filterList.getFromVisible(i) as PoiListItem if (e.isSelected) { export.add(e.category) } } return export } }
gpl-3.0
381a2d4d4f38b2f501eb0af303f12779
26.956989
93
0.614615
4.227642
false
false
false
false
nextcloud/android
app/src/main/java/com/owncloud/android/ui/fragment/GalleryFragmentBottomSheetDialog.kt
1
4531
/* * Nextcloud Android client application * * @author TSI-mc * Copyright (C) 2022 TSI-mc * Copyright (C) 2022 Nextcloud GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.owncloud.android.ui.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.nextcloud.client.di.Injectable import com.owncloud.android.databinding.FragmentGalleryBottomSheetBinding import com.owncloud.android.utils.theme.ViewThemeUtils import javax.inject.Inject class GalleryFragmentBottomSheetDialog( private val actions: GalleryFragmentBottomSheetActions ) : BottomSheetDialogFragment(), Injectable { @Inject lateinit var viewThemeUtils: ViewThemeUtils private lateinit var binding: FragmentGalleryBottomSheetBinding private lateinit var mBottomBehavior: BottomSheetBehavior<*> private var currentMediaState: MediaState = MediaState.MEDIA_STATE_DEFAULT override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentGalleryBottomSheetBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupLayout() setupClickListener() mBottomBehavior = BottomSheetBehavior.from(binding.root.parent as View) } public override fun onStart() { super.onStart() mBottomBehavior.state = BottomSheetBehavior.STATE_EXPANDED } fun setupLayout() { listOf( binding.tickMarkShowImages, binding.tickMarkShowVideo, binding.hideImagesImageview, binding.hideVideoImageView, binding.selectMediaFolderImageView ).forEach { viewThemeUtils.platform.colorImageView(it) } when (currentMediaState) { MediaState.MEDIA_STATE_PHOTOS_ONLY -> { binding.tickMarkShowImages.visibility = View.VISIBLE binding.tickMarkShowVideo.visibility = View.GONE } MediaState.MEDIA_STATE_VIDEOS_ONLY -> { binding.tickMarkShowImages.visibility = View.GONE binding.tickMarkShowVideo.visibility = View.VISIBLE } else -> { binding.tickMarkShowImages.visibility = View.VISIBLE binding.tickMarkShowVideo.visibility = View.VISIBLE } } } private fun setupClickListener() { binding.hideImages.setOnClickListener { v: View? -> currentMediaState = if (currentMediaState == MediaState.MEDIA_STATE_VIDEOS_ONLY) { MediaState.MEDIA_STATE_DEFAULT } else { MediaState.MEDIA_STATE_VIDEOS_ONLY } notifyStateChange() dismiss() } binding.hideVideo.setOnClickListener { v: View? -> currentMediaState = if (currentMediaState == MediaState.MEDIA_STATE_PHOTOS_ONLY) { MediaState.MEDIA_STATE_DEFAULT } else { MediaState.MEDIA_STATE_PHOTOS_ONLY } notifyStateChange() dismiss() } binding.selectMediaFolder.setOnClickListener { v: View? -> actions.selectMediaFolder() dismiss() } } private fun notifyStateChange() { setupLayout() actions.updateMediaContent(currentMediaState) } val currMediaState: MediaState get() = currentMediaState enum class MediaState { MEDIA_STATE_DEFAULT, MEDIA_STATE_PHOTOS_ONLY, MEDIA_STATE_VIDEOS_ONLY } }
gpl-2.0
445ba642363822b76285932ae4be8117
34.960317
116
0.677113
5.096738
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mixin/insight/MixinEntryPoint.kt
1
2016
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.insight import com.demonwav.mcdev.platform.mixin.util.MixinConstants import com.intellij.codeInspection.reference.RefElement import com.intellij.codeInspection.visibility.EntryPointWithVisibilityLevel import com.intellij.psi.PsiElement import com.intellij.psi.PsiMember import com.intellij.psi.PsiMethod import com.intellij.psi.util.PsiUtil import com.intellij.util.xmlb.XmlSerializer import org.jdom.Element class MixinEntryPoint : EntryPointWithVisibilityLevel() { @JvmField var MIXIN_ENTRY_POINT = true override fun getId() = "mixin" override fun getDisplayName() = "Mixin injectors" override fun getTitle() = "Suggest private visibility level for Mixin injectors" override fun getIgnoreAnnotations() = MixinConstants.Annotations.ENTRY_POINTS override fun isEntryPoint(element: PsiElement): Boolean { val modifierList = (element as? PsiMethod)?.modifierList ?: return false return MixinConstants.Annotations.ENTRY_POINTS.any { modifierList.findAnnotation(it) != null } } override fun isEntryPoint(refElement: RefElement, psiElement: PsiElement) = isEntryPoint(psiElement) override fun getMinVisibilityLevel(member: PsiMember): Int { if (member !is PsiMethod) return -1 val modifierList = member.modifierList return if (MixinConstants.Annotations.METHOD_INJECTORS.any { modifierList.findAnnotation(it) != null }) { PsiUtil.ACCESS_LEVEL_PRIVATE } else { -1 } } override fun isSelected() = MIXIN_ENTRY_POINT override fun setSelected(selected: Boolean) { MIXIN_ENTRY_POINT = selected } override fun readExternal(element: Element) = XmlSerializer.serializeInto(this, element) override fun writeExternal(element: Element) = XmlSerializer.serializeInto(this, element) }
mit
498f3f1071cb3f6ba7e635948bc9b4ab
32.6
113
0.731647
4.623853
false
false
false
false
soywiz/korge
korge-dragonbones/src/commonMain/kotlin/com/dragonbones/animation/TimelineState.kt
1
37636
/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.dragonbones.animation import com.dragonbones.armature.* import com.dragonbones.core.* import com.dragonbones.event.* import com.dragonbones.model.* import com.soywiz.kmem.* import kotlin.math.* /** * @internal */ class ActionTimelineState(pool: SingleObjectPool<ActionTimelineState>) : TimelineState(pool) { override fun toString(): String { return "[class dragonBones.ActionTimelineState]" } private fun _onCrossFrame(frameIndex: Int) { val eventDispatcher = this._armature!!.eventDispatcher if (this._animationState!!.actionEnabled) { val frameOffset = this._animationData!!.frameOffset + this._timelineArray!![(this._timelineData!!).offset + BinaryOffset.TimelineFrameOffset + frameIndex].toInt() val actionCount = this._frameArray!![frameOffset + 1].toInt() val actions = this._animationData!!.parent!!.actions // May be the animaton data not belong to this armature data. //for (var i = 0; i < actionCount; ++i) { for (i in 0 until actionCount) { val actionIndex = this._frameArray!![frameOffset + 2 + i].toInt() val action = actions[actionIndex] if (action.type == ActionType.Play) { val eventObject = pool.eventObject.borrow() // eventObject.time = this._frameArray[frameOffset] * this._frameRateR; // Precision problem eventObject.time = this._frameArray!![frameOffset].toDouble() / this._frameRate eventObject.animationState = this._animationState!! EventObject.actionDataToInstance(action, eventObject, this._armature!!) this._armature!!._bufferAction(eventObject, true) } else { val eventType = if (action.type == ActionType.Frame) EventObject.FRAME_EVENT else EventObject.SOUND_EVENT if (action.type == ActionType.Sound || eventDispatcher.hasDBEventListener(eventType)) { val eventObject = pool.eventObject.borrow() // eventObject.time = this._frameArray[frameOffset] * this._frameRateR; // Precision problem eventObject.time = this._frameArray!![frameOffset].toDouble() / this._frameRate eventObject.animationState = this._animationState!! EventObject.actionDataToInstance(action, eventObject, this._armature!!) this._armature?.eventDispatcher?.queueEvent(eventObject) } } } } } override fun _onArriveAtFrame() {} override fun _onUpdateFrame() {} override fun update(passedTime: Double) { val prevState = this.playState var prevPlayTimes = this.currentPlayTimes val prevTime = this._currentTime if (this._setCurrentTime(passedTime)) { val eventActive = this._animationState?._parent == null && this._animationState!!.actionEnabled val eventDispatcher = this._armature?.eventDispatcher if (prevState < 0) { if (this.playState != prevState) { if (this._animationState!!.displayControl && this._animationState!!.resetToPose) { // Reset zorder to pose. this._armature?._sortZOrder(null, 0) } prevPlayTimes = this.currentPlayTimes if (eventActive && eventDispatcher!!.hasDBEventListener(EventObject.START)) { val eventObject = pool.eventObject.borrow() eventObject.type = EventObject.START eventObject.armature = this._armature!! eventObject.animationState = this._animationState!! this._armature?.eventDispatcher?.queueEvent(eventObject) } } else { return } } val isReverse = this._animationState!!.timeScale < 0.0 var loopCompleteEvent: EventObject? = null var completeEvent: EventObject? = null if (eventActive && this.currentPlayTimes != prevPlayTimes) { if (eventDispatcher!!.hasDBEventListener(EventObject.LOOP_COMPLETE)) { loopCompleteEvent = pool.eventObject.borrow() loopCompleteEvent.type = EventObject.LOOP_COMPLETE loopCompleteEvent.armature = this._armature!! loopCompleteEvent.animationState = this._animationState!! } if (this.playState > 0) { if (eventDispatcher.hasDBEventListener(EventObject.COMPLETE)) { completeEvent = pool.eventObject.borrow() completeEvent.type = EventObject.COMPLETE completeEvent.armature = this._armature!! completeEvent.animationState = this._animationState!! } } } if (this._frameCount > 1) { val timelineData = this._timelineData as TimelineData val timelineFrameIndex = floor(this._currentTime * this._frameRate).toInt() // uint val frameIndex = this._frameIndices!![timelineData.frameIndicesOffset + timelineFrameIndex] if (this._frameIndex != frameIndex) { // Arrive at frame. var crossedFrameIndex = this._frameIndex this._frameIndex = frameIndex if (this._timelineArray != null) { this._frameOffset = this._animationData!!.frameOffset + this._timelineArray!![timelineData.offset + BinaryOffset.TimelineFrameOffset + this._frameIndex].toInt() if (isReverse) { if (crossedFrameIndex < 0) { val prevFrameIndex = floor(prevTime * this._frameRate).toInt() crossedFrameIndex = this._frameIndices!![timelineData.frameIndicesOffset + prevFrameIndex] if (this.currentPlayTimes == prevPlayTimes) { // Start. if (crossedFrameIndex == frameIndex) { // Uncrossed. crossedFrameIndex = -1 } } } while (crossedFrameIndex >= 0) { val frameOffset = this._animationData!!.frameOffset + this._timelineArray!![timelineData.offset + BinaryOffset.TimelineFrameOffset + crossedFrameIndex].toInt() // val framePosition = this._frameArray[frameOffset] * this._frameRateR; // Precision problem val framePosition = this._frameArray!![frameOffset] / this._frameRate if ( this._position <= framePosition && framePosition <= this._position + this._duration ) { // Support interval play. this._onCrossFrame(crossedFrameIndex) } if (loopCompleteEvent != null && crossedFrameIndex == 0) { // Add loop complete event after first frame. this._armature?.eventDispatcher?.queueEvent(loopCompleteEvent) loopCompleteEvent = null } if (crossedFrameIndex > 0) { crossedFrameIndex-- } else { crossedFrameIndex = this._frameCount - 1 } if (crossedFrameIndex == frameIndex) { break } } } else { if (crossedFrameIndex < 0) { val prevFrameIndex = floor(prevTime * this._frameRate).toInt() crossedFrameIndex = this._frameIndices!![timelineData.frameIndicesOffset + prevFrameIndex] val frameOffset = this._animationData!!.frameOffset + this._timelineArray!![timelineData.offset + BinaryOffset.TimelineFrameOffset + crossedFrameIndex].toInt() // val framePosition = this._frameArray[frameOffset] * this._frameRateR; // Precision problem val framePosition = this._frameArray!![frameOffset].toDouble() / this._frameRate if (this.currentPlayTimes == prevPlayTimes) { // Start. if (prevTime <= framePosition) { // Crossed. if (crossedFrameIndex > 0) { crossedFrameIndex-- } else { crossedFrameIndex = this._frameCount - 1 } } else if (crossedFrameIndex == frameIndex) { // Uncrossed. crossedFrameIndex = -1 } } } while (crossedFrameIndex >= 0) { if (crossedFrameIndex < this._frameCount - 1) { crossedFrameIndex++ } else { crossedFrameIndex = 0 } val frameOffset = this._animationData!!.frameOffset + this._timelineArray!![timelineData.offset + BinaryOffset.TimelineFrameOffset + crossedFrameIndex].toInt() // val framePosition = this._frameArray[frameOffset] * this._frameRateR; // Precision problem val framePosition = this._frameArray!![frameOffset].toDouble() / this._frameRate if ( this._position <= framePosition && framePosition <= this._position + this._duration // ) { // Support interval play. this._onCrossFrame(crossedFrameIndex) } if (loopCompleteEvent != null && crossedFrameIndex == 0) { // Add loop complete event before first frame. this._armature?.eventDispatcher?.queueEvent(loopCompleteEvent) loopCompleteEvent = null } if (crossedFrameIndex == frameIndex) { break } } } } } } else if (this._frameIndex < 0) { this._frameIndex = 0 if (this._timelineData != null) { this._frameOffset = this._animationData!!.frameOffset + this._timelineArray!![this._timelineData!!.offset + BinaryOffset.TimelineFrameOffset].toInt() // Arrive at frame. val framePosition = this._frameArray!![this._frameOffset].toDouble() / this._frameRate if (this.currentPlayTimes == prevPlayTimes) { // Start. if (prevTime <= framePosition) { this._onCrossFrame(this._frameIndex) } } else if (this._position <= framePosition) { // Loop complete. if (!isReverse && loopCompleteEvent != null) { // Add loop complete event before first frame. this._armature?.eventDispatcher?.queueEvent(loopCompleteEvent) loopCompleteEvent = null } this._onCrossFrame(this._frameIndex) } } } if (loopCompleteEvent != null) { this._armature?.eventDispatcher?.queueEvent(loopCompleteEvent) } if (completeEvent != null) { this._armature?.eventDispatcher?.queueEvent(completeEvent) } } } fun setCurrentTime(value: Double) { this._setCurrentTime(value) this._frameIndex = -1 } } /** * @internal */ class ZOrderTimelineState(pool: SingleObjectPool<ZOrderTimelineState>) : TimelineState(pool) { override fun toString(): String { return "[class dragonBones.ZOrderTimelineState]" } override fun _onArriveAtFrame() { if (this.playState >= 0) { val count = this._frameArray!![this._frameOffset + 1].toInt() if (count > 0) { this._armature?._sortZOrder(this._frameArray!!, this._frameOffset + 2) } else { this._armature?._sortZOrder(null, 0) } } } override fun _onUpdateFrame() {} } /** * @internal */ class BoneAllTimelineState(pool: SingleObjectPool<BoneAllTimelineState>) : MutilpleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.BoneAllTimelineState]" } override fun _onArriveAtFrame() { super._onArriveAtFrame() if (this._isTween && this._frameIndex == this._frameCount - 1) { this._rd[2] = TransformDb.normalizeRadian(this._rd[2]) this._rd[3] = TransformDb.normalizeRadian(this._rd[3]) } if (this._timelineData == null) { // Pose. this._rd[4] = 1.0 this._rd[5] = 1.0 } } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameFloatOffset this._valueCount = 6 this._valueArray = this._animationData?.parent?.parent?.frameFloatArray!! } override fun fadeOut() { this.dirty = false this._rd[2] = TransformDb.normalizeRadian(this._rd[2]) this._rd[3] = TransformDb.normalizeRadian(this._rd[3]) } override fun blend(_isDirty: Boolean) { val valueScale = this._armature!!.armatureData.scale val rd = this._rd // val blendState = this.targetBlendState!! val bone = blendState.targetBone!! val blendWeight = blendState.blendWeight val result = bone.animationPose if (blendState.dirty > 1) { result.xf += (rd[0] * blendWeight * valueScale).toFloat() result.yf += (rd[1] * blendWeight * valueScale).toFloat() result.rotation += (rd[2] * blendWeight).toFloat() result.skew += (rd[3] * blendWeight).toFloat() result.scaleX += ((rd[4] - 1.0) * blendWeight).toFloat() result.scaleY += ((rd[5] - 1.0) * blendWeight).toFloat() } else { result.xf = (rd[0] * blendWeight * valueScale).toFloat() result.yf = (rd[1] * blendWeight * valueScale).toFloat() result.rotation = (rd[2] * blendWeight).toFloat() result.skew = (rd[3] * blendWeight).toFloat() result.scaleX = ((rd[4] - 1.0) * blendWeight + 1.0).toFloat() // result.scaleY = ((rd[5] - 1.0) * blendWeight + 1.0).toFloat() // } if (_isDirty || this.dirty) { this.dirty = false bone._transformDirty = true } } } /** * @internal */ class BoneTranslateTimelineState(pool: SingleObjectPool<BoneTranslateTimelineState>) : DoubleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.BoneTranslateTimelineState]" } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameFloatOffset this._valueScale = this._armature!!.armatureData.scale this._valueArray = this._animationData!!.parent!!.parent!!.frameFloatArray!! } override fun blend(_isDirty: Boolean) { val blendState = this.targetBlendState!! val bone = blendState.targetBone!! val blendWeight = blendState.blendWeight val result = bone.animationPose when { blendState.dirty > 1 -> { result.xf += (this._resultA * blendWeight).toFloat() result.yf += (this._resultB * blendWeight).toFloat() } blendWeight != 1.0 -> { result.xf = (this._resultA * blendWeight).toFloat() result.yf = (this._resultB * blendWeight).toFloat() } else -> { result.xf = this._resultA.toFloat() result.yf = this._resultB.toFloat() } } if (_isDirty || this.dirty) { this.dirty = false bone._transformDirty = true } } } /** * @internal */ class BoneRotateTimelineState(pool: SingleObjectPool<BoneRotateTimelineState>) : DoubleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.BoneRotateTimelineState]" } override fun _onArriveAtFrame() { super._onArriveAtFrame() if (this._isTween && this._frameIndex == this._frameCount - 1) { this._differenceA = TransformDb.normalizeRadian(this._differenceA) this._differenceB = TransformDb.normalizeRadian(this._differenceB) } } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameFloatOffset this._valueArray = this._animationData!!.parent!!.parent!!.frameFloatArray!! } override fun fadeOut() { this.dirty = false this._resultA = TransformDb.normalizeRadian(this._resultA) this._resultB = TransformDb.normalizeRadian(this._resultB) } override fun blend(_isDirty: Boolean) { val blendState = this.targetBlendState!! val bone = blendState.targetBone!! val blendWeight = blendState.blendWeight val result = bone.animationPose when { blendState.dirty > 1 -> { result.rotation += (this._resultA * blendWeight).toFloat() result.skew += (this._resultB * blendWeight).toFloat() } blendWeight != 1.0 -> { result.rotation = (this._resultA * blendWeight).toFloat() result.skew = (this._resultB * blendWeight).toFloat() } else -> { result.rotation = this._resultA.toFloat() result.skew = this._resultB.toFloat() } } if (_isDirty || this.dirty) { this.dirty = false bone._transformDirty = true } } } /** * @internal */ class BoneScaleTimelineState(pool: SingleObjectPool<BoneScaleTimelineState>) : DoubleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.BoneScaleTimelineState]" } override fun _onArriveAtFrame() { super._onArriveAtFrame() if (this._timelineData == null) { // Pose. this._resultA = 1.0 this._resultB = 1.0 } } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameFloatOffset this._valueArray = this._animationData!!.parent!!.parent!!.frameFloatArray!! } override fun blend(_isDirty: Boolean) { val blendState = this.targetBlendState!! val bone = blendState.targetBone!! val blendWeight = blendState.blendWeight val result = bone.animationPose when { blendState.dirty > 1 -> { result.scaleX += ((this._resultA - 1.0) * blendWeight).toFloat() result.scaleY += ((this._resultB - 1.0) * blendWeight).toFloat() } blendWeight != 1.0 -> { result.scaleX = ((this._resultA - 1.0) * blendWeight + 1.0).toFloat() result.scaleY = ((this._resultB - 1.0) * blendWeight + 1.0).toFloat() } else -> { result.scaleX = this._resultA.toFloat() result.scaleY = this._resultB.toFloat() } } if (_isDirty || this.dirty) { this.dirty = false bone._transformDirty = true } } } /** * @internal */ class SurfaceTimelineState(pool: SingleObjectPool<SurfaceTimelineState>) : MutilpleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.SurfaceTimelineState]" } private var _deformCount: Int = 0 private var _deformOffset: Int = 0 private var _sameValueOffset: Int = 0 override fun _onClear() { super._onClear() this._deformCount = 0 this._deformOffset = 0 this._sameValueOffset = 0 } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) if (this._timelineData != null) { val dragonBonesData = this._animationData!!.parent!!.parent val frameIntArray = dragonBonesData!!.frameIntArray!! val frameIntOffset = this._animationData!!.frameIntOffset + this._timelineArray!![this._timelineData!!.offset + BinaryOffset.TimelineFrameValueCount].toInt() this._valueOffset = this._animationData!!.frameFloatOffset this._valueCount = frameIntArray[frameIntOffset + BinaryOffset.DeformValueCount].toInt() this._deformCount = frameIntArray[frameIntOffset + BinaryOffset.DeformCount].toInt() this._deformOffset = frameIntArray[frameIntOffset + BinaryOffset.DeformValueOffset].toInt() this._sameValueOffset = frameIntArray[frameIntOffset + BinaryOffset.DeformFloatOffset].toInt() + this._animationData!!.frameFloatOffset this._valueScale = this._armature!!.armatureData.scale this._valueArray = dragonBonesData.frameFloatArray!! this._rd = DoubleArray(this._valueCount * 2) } else { this._deformCount = ((this.targetBlendState)!!.targetSurface)!!._deformVertices.size } } override fun blend(_isDirty: Boolean) { val blendState = this.targetBlendState!! val surface = blendState.targetSurface ?: error("blendState.targetSurface=null: target=${blendState.targetCommon}") val blendWeight = blendState.blendWeight val result = surface._deformVertices val valueArray = this._valueArray if (valueArray != null) { val valueCount = this._valueCount val deformOffset = this._deformOffset val sameValueOffset = this._sameValueOffset val rd = this._rd for (i in 0 until this._deformCount) { var value: Double value = if (i < deformOffset) { valueArray[sameValueOffset + i].toDouble() } else if (i < deformOffset + valueCount) { rd[i - deformOffset] } else { valueArray[sameValueOffset + i - valueCount].toDouble() } if (blendState.dirty > 1) { result[i] += (value * blendWeight).toFloat() } else { result[i] = (value * blendWeight).toFloat() } } } else if (blendState.dirty == 1) { for (i in 0 until this._deformCount) { result[i] = 0f } } if (_isDirty || this.dirty) { this.dirty = false surface._transformDirty = true } } } /** * @internal */ class AlphaTimelineState(pool: SingleObjectPool<AlphaTimelineState>) : SingleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.AlphaTimelineState]" } override fun _onArriveAtFrame() { super._onArriveAtFrame() if (this._timelineData == null) { // Pose. this._result = 1.0 } } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameIntOffset this._valueScale = 0.01 this._valueArray = this._animationData!!.parent!!.parent!!.frameIntArray!! } override fun blend(_isDirty: Boolean) { val blendState = this.targetBlendState!! val alphaTarget = blendState.targetTransformObject!! val blendWeight = blendState.blendWeight if (blendState.dirty > 1) { alphaTarget._alpha += this._result * blendWeight if (alphaTarget._alpha > 1.0) { alphaTarget._alpha = 1.0 } } else { alphaTarget._alpha = this._result * blendWeight } if (_isDirty || this.dirty) { this.dirty = false this._armature?._alphaDirty = true } } } /** * @internal */ class SlotDisplayTimelineState(pool: SingleObjectPool<SlotDisplayTimelineState>) : TimelineState(pool) { override fun toString(): String { return "[class dragonBones.SlotDisplayTimelineState]" } override fun _onArriveAtFrame() { if (this.playState >= 0) { val slot = this.targetSlot!! val displayIndex: Int = if (this._timelineData != null) this._frameArray!![this._frameOffset + 1].toInt() else slot._slotData!!.displayIndex if (slot.displayIndex != displayIndex) { slot._setDisplayIndex(displayIndex, true) } } } override fun _onUpdateFrame() { } } /** * @internal */ class SlotColorTimelineState(pool: SingleObjectPool<SlotColorTimelineState>) : TweenTimelineState(pool) { override fun toString(): String { return "[class dragonBones.SlotColorTimelineState]" } private val _current: IntArray = intArrayOf(0, 0, 0, 0, 0, 0, 0, 0) private val _difference: IntArray = intArrayOf(0, 0, 0, 0, 0, 0, 0, 0) private val _result: DoubleArray = doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) @Suppress("UNUSED_CHANGED_VALUE") override fun _onArriveAtFrame() { super._onArriveAtFrame() if (this._timelineData != null) { val dragonBonesData = this._animationData!!.parent!!.parent val colorArray = dragonBonesData!!.colorArray!! val frameIntArray = dragonBonesData.frameIntArray!! val valueOffset = this._animationData!!.frameIntOffset + this._frameValueOffset + this._frameIndex var colorOffset = frameIntArray[valueOffset].toInt() if (colorOffset < 0) { colorOffset += 65536 // Fixed out of bounds bug. } if (this._isTween) { this._current[0] = colorArray[colorOffset++].toInt() this._current[1] = colorArray[colorOffset++].toInt() this._current[2] = colorArray[colorOffset++].toInt() this._current[3] = colorArray[colorOffset++].toInt() this._current[4] = colorArray[colorOffset++].toInt() this._current[5] = colorArray[colorOffset++].toInt() this._current[6] = colorArray[colorOffset++].toInt() this._current[7] = colorArray[colorOffset++].toInt() colorOffset = if (this._frameIndex == this._frameCount - 1) { frameIntArray[this._animationData!!.frameIntOffset + this._frameValueOffset].toInt() } else { frameIntArray[valueOffset + 1].toInt() } if (colorOffset < 0) { colorOffset += 65536 // Fixed out of bounds bug. } this._difference[0] = colorArray[colorOffset++] - this._current[0] this._difference[1] = colorArray[colorOffset++] - this._current[1] this._difference[2] = colorArray[colorOffset++] - this._current[2] this._difference[3] = colorArray[colorOffset++] - this._current[3] this._difference[4] = colorArray[colorOffset++] - this._current[4] this._difference[5] = colorArray[colorOffset++] - this._current[5] this._difference[6] = colorArray[colorOffset++] - this._current[6] this._difference[7] = colorArray[colorOffset++] - this._current[7] } else { this._result[0] = colorArray[colorOffset++] * 0.01 this._result[1] = colorArray[colorOffset++] * 0.01 this._result[2] = colorArray[colorOffset++] * 0.01 this._result[3] = colorArray[colorOffset++] * 0.01 this._result[4] = colorArray[colorOffset++].toDouble() this._result[5] = colorArray[colorOffset++].toDouble() this._result[6] = colorArray[colorOffset++].toDouble() this._result[7] = colorArray[colorOffset++].toDouble() } } else { // Pose. val slot = this.targetSlot!! val color = slot.slotData.color!! this._result[0] = color.alphaMultiplier this._result[1] = color.redMultiplier this._result[2] = color.greenMultiplier this._result[3] = color.blueMultiplier this._result[4] = color.alphaOffset.toDouble() this._result[5] = color.redOffset.toDouble() this._result[6] = color.greenOffset.toDouble() this._result[7] = color.blueOffset.toDouble() } } override fun _onUpdateFrame() { super._onUpdateFrame() if (this._isTween) { this._result[0] = (this._current[0] + this._difference[0] * this._tweenProgress) * 0.01 this._result[1] = (this._current[1] + this._difference[1] * this._tweenProgress) * 0.01 this._result[2] = (this._current[2] + this._difference[2] * this._tweenProgress) * 0.01 this._result[3] = (this._current[3] + this._difference[3] * this._tweenProgress) * 0.01 this._result[4] = this._current[4] + this._difference[4] * this._tweenProgress this._result[5] = this._current[5] + this._difference[5] * this._tweenProgress this._result[6] = this._current[6] + this._difference[6] * this._tweenProgress this._result[7] = this._current[7] + this._difference[7] * this._tweenProgress } } override fun fadeOut() { this._isTween = false } override fun update(passedTime: Double) { super.update(passedTime) // Fade animation. if (this._isTween || this.dirty) { val slot = this.targetSlot!! val result = slot._colorTransform if (this._animationState!!._fadeState != 0 || this._animationState!!._subFadeState != 0) { if ( result.alphaMultiplier != this._result[0] || result.redMultiplier != this._result[1] || result.greenMultiplier != this._result[2] || result.blueMultiplier != this._result[3] || result.alphaOffset != this._result[4].toInt() || result.redOffset != this._result[5].toInt() || result.greenOffset != this._result[6].toInt() || result.blueOffset != this._result[7].toInt() ) { val fadeProgress = this._animationState!!._fadeProgress.pow(4.0) result.alphaMultiplier += (this._result[0] - result.alphaMultiplier) * fadeProgress result.redMultiplier += (this._result[1] - result.redMultiplier) * fadeProgress result.greenMultiplier += (this._result[2] - result.greenMultiplier) * fadeProgress result.blueMultiplier += (this._result[3] - result.blueMultiplier) * fadeProgress result.alphaOffset += ((this._result[4] - result.alphaOffset) * fadeProgress).toInt() result.redOffset += ((this._result[5] - result.redOffset) * fadeProgress).toInt() result.greenOffset += ((this._result[6] - result.greenOffset) * fadeProgress).toInt() result.blueOffset += ((this._result[7] - result.blueOffset) * fadeProgress).toInt() slot._colorDirty = true } } else if (this.dirty) { this.dirty = false if ( result.alphaMultiplier != this._result[0] || result.redMultiplier != this._result[1] || result.greenMultiplier != this._result[2] || result.blueMultiplier != this._result[3] || result.alphaOffset != this._result[4].toInt() || result.redOffset != this._result[5].toInt() || result.greenOffset != this._result[6].toInt() || result.blueOffset != this._result[7].toInt() ) { result.alphaMultiplier = this._result[0] result.redMultiplier = this._result[1] result.greenMultiplier = this._result[2] result.blueMultiplier = this._result[3] result.alphaOffset = this._result[4].toInt() result.redOffset = this._result[5].toInt() result.greenOffset = this._result[6].toInt() result.blueOffset = this._result[7].toInt() slot._colorDirty = true } } } } } /** * @internal */ class SlotZIndexTimelineState(pool: SingleObjectPool<SlotZIndexTimelineState>) : SingleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.SlotZIndexTimelineState]" } override fun _onArriveAtFrame() { super._onArriveAtFrame() if (this._timelineData == null) { // Pose. val blendState = this.targetBlendState!! val slot = blendState.targetSlot!! this._result = slot.slotData.zIndex.toDouble() } } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameIntOffset this._valueArray = this._animationData!!.parent!!.parent!!.frameIntArray!! } override fun blend(_isDirty: Boolean) { val blendState = this.targetBlendState!! val slot = blendState.targetSlot!! val blendWeight = blendState.blendWeight if (blendState.dirty > 1) { // @TODO: Kotlin conversion original (no toInt): slot._zIndex += this._result * blendWeight slot._zIndex += (this._result * blendWeight).toInt() } else { // @TODO: Kotlin conversion original (no toInt): slot._zIndex = this._result * blendWeight slot._zIndex = (this._result * blendWeight).toInt() } if (_isDirty || this.dirty) { this.dirty = false this._armature?._zIndexDirty = true } } } /** * @internal */ class DeformTimelineState(pool: SingleObjectPool<DeformTimelineState>) : MutilpleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.DeformTimelineState]" } var geometryOffset: Int = 0 var displayFrame: DisplayFrame? = null private var _deformCount: Int = 0 private var _deformOffset: Int = 0 private var _sameValueOffset: Int = 0 override fun _onClear() { super._onClear() this.geometryOffset = 0 this.displayFrame = null this._deformCount = 0 this._deformOffset = 0 this._sameValueOffset = 0 } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) if (this._timelineData != null) { val frameIntOffset = this._animationData!!.frameIntOffset + this._timelineArray!![this._timelineData!!.offset + BinaryOffset.TimelineFrameValueCount] val dragonBonesData = this._animationData?.parent?.parent val frameIntArray = dragonBonesData!!.frameIntArray val slot = (this.targetBlendState)!!.targetSlot!! this.geometryOffset = frameIntArray!![frameIntOffset + BinaryOffset.DeformVertexOffset].toInt() if (this.geometryOffset < 0) { this.geometryOffset += 65536 // Fixed out of bounds bug. } for (i in 0 until slot.displayFrameCount) { val displayFrame = slot.getDisplayFrameAt(i) val geometryData = displayFrame.getGeometryData() ?: continue if (geometryData.offset == this.geometryOffset) { this.displayFrame = displayFrame this.displayFrame?.updateDeformVertices() break } } if (this.displayFrame == null) { this.returnToPool() // return } this._valueOffset = this._animationData!!.frameFloatOffset this._valueCount = frameIntArray[frameIntOffset + BinaryOffset.DeformValueCount].toInt() this._deformCount = frameIntArray[frameIntOffset + BinaryOffset.DeformCount].toInt() this._deformOffset = frameIntArray[frameIntOffset + BinaryOffset.DeformValueOffset].toInt() this._sameValueOffset = frameIntArray[frameIntOffset + BinaryOffset.DeformFloatOffset].toInt() + this._animationData!!.frameFloatOffset this._valueScale = this._armature!!.armatureData.scale this._valueArray = dragonBonesData.frameFloatArray!! this._rd = DoubleArray(this._valueCount * 2) } else { this._deformCount = this.displayFrame!!.deformVertices.size } } override fun blend(_isDirty: Boolean) { val blendState = this.targetBlendState!! val slot = blendState.targetSlot!! val blendWeight = blendState.blendWeight val result = this.displayFrame!!.deformVertices val valueArray = this._valueArray if (valueArray != null) { val valueCount = this._valueCount val deformOffset = this._deformOffset val sameValueOffset = this._sameValueOffset val rd = this._rd for (i in 0 until this._deformCount) { val value = when { i < deformOffset -> valueArray[sameValueOffset + i].toDouble() i < deformOffset + valueCount -> rd[i - deformOffset] else -> valueArray[sameValueOffset + i - valueCount].toDouble() } if (blendState.dirty > 1) { result[i] += value * blendWeight } else { result[i] = value * blendWeight } } } else if (blendState.dirty == 1) { //for (var i = 0; i < this._deformCount; ++i) { for (i in 0 until this._deformCount) { result[i] = 0.0 } } if (_isDirty || this.dirty) { this.dirty = false if (slot._geometryData == this.displayFrame!!.getGeometryData()) { slot._verticesDirty = true } } } } /** * @internal */ class IKConstraintTimelineState(pool: SingleObjectPool<IKConstraintTimelineState>) : DoubleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.IKConstraintTimelineState]" } override fun _onUpdateFrame() { super._onUpdateFrame() val ikConstraint = this.targetIKConstraint!! if (this._timelineData != null) { ikConstraint._bendPositive = this._currentA > 0.0 ikConstraint._weight = this._currentB } else { val ikConstraintData = ikConstraint._constraintData as IKConstraintData ikConstraint._bendPositive = ikConstraintData.bendPositive ikConstraint._weight = ikConstraintData.weight } ikConstraint.invalidUpdate() this.dirty = false } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameIntOffset this._valueScale = 0.01 this._valueArray = this._animationData!!.parent!!.parent!!.frameIntArray!! } } /** * @internal */ class AnimationProgressTimelineState(pool: SingleObjectPool<AnimationProgressTimelineState>) : SingleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.AnimationProgressTimelineState]" } override fun _onUpdateFrame() { super._onUpdateFrame() val animationState = this.targetAnimationState!! if (animationState._parent != null) { animationState.currentTime = this._result * animationState.totalTime } this.dirty = false } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameIntOffset this._valueScale = 0.0001 this._valueArray = this._animationData!!.parent!!.parent!!.frameIntArray!! } } /** * @internal */ class AnimationWeightTimelineState(pool: SingleObjectPool<AnimationWeightTimelineState>) : SingleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.AnimationWeightTimelineState]" } override fun _onUpdateFrame() { super._onUpdateFrame() val animationState = this.targetAnimationState!! if (animationState._parent != null) { animationState.weight = this._result } this.dirty = false } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameIntOffset this._valueScale = 0.0001 this._valueArray = this._animationData!!.parent!!.parent!!.frameIntArray!! } } /** * @internal */ class AnimationParametersTimelineState(pool: SingleObjectPool<AnimationParametersTimelineState>) : DoubleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.AnimationParametersTimelineState]" } override fun _onUpdateFrame() { super._onUpdateFrame() val animationState = this.targetAnimationState!! if (animationState._parent != null) { animationState.parameterX = this._resultA animationState.parameterY = this._resultB } this.dirty = false } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameIntOffset this._valueScale = 0.0001 this._valueArray = this._animationData!!.parent!!.parent!!.frameIntArray!! } }
apache-2.0
c4717d713540c0dd65f058572ff9fc13
32.967509
150
0.689207
4.029119
false
false
false
false
edvin/tornadofx
src/test/kotlin/tornadofx/testapps/TableViewDirtyTest.kt
1
3629
package tornadofx.testapps import javafx.beans.property.SimpleObjectProperty import javafx.beans.property.SimpleStringProperty import javafx.collections.FXCollections import javafx.scene.control.SelectionMode import javafx.scene.control.TableView import javafx.scene.control.TableView.CONSTRAINED_RESIZE_POLICY import javafx.scene.text.FontWeight import tornadofx.* import java.util.* class TableViewDirtyTestApp : WorkspaceApp(TableViewDirtyTest::class) class TableViewDirtyTest : View("Dirty Tables") { val customers = FXCollections.observableArrayList(Customer("Thomas", "Nield"), Customer("Matthew", "Turnblom"), Customer("Edvin", "Syse")) var table: TableView<Customer> by singleAssign() override val root = borderpane { center { tableview(customers) { table = this prefHeight = 200.0 column("First Name", Customer::firstNameProperty) { makeEditable() cellDecorator { style { fontWeight = FontWeight.BOLD } } } column("Last Name", Customer::lastNameProperty).makeEditable() enableCellEditing() regainFocusAfterEdit() enableDirtyTracking() selectOnDrag() contextmenu { item(stringBinding(selectionModel.selectedCells) { "Rollback ${selectedColumn?.text}" }) { disableWhen { editModel.selectedItemDirty.not() } action { editModel.rollback(selectedItem, selectedColumn) } } item(stringBinding(selectionModel.selectedCells) { "Commit ${selectedColumn?.text}" }) { disableWhen { editModel.selectedItemDirty.not() } action { editModel.commit(selectedItem, selectedColumn) } } } selectionModel.selectionMode = SelectionMode.MULTIPLE columnResizePolicy = CONSTRAINED_RESIZE_POLICY } } bottom { hbox(10) { paddingAll = 4 button("Commit row") { disableWhen { table.editModel.selectedItemDirty.not() } action { table.editModel.commitSelected() } } button("Rollback row") { disableWhen { table.editModel.selectedItemDirty.not() } action { table.editModel.rollbackSelected() } } } } } override fun onSave() { table.editModel.commit() } override fun onRefresh() { table.editModel.rollback() } init { icon = FX.icon } class Customer(firstName: String, lastName: String) { val idProperty = SimpleObjectProperty<UUID>(UUID.randomUUID()) var id by idProperty val firstNameProperty = SimpleStringProperty(firstName) var firstName by firstNameProperty val lastNameProperty = SimpleStringProperty(lastName) val lastName by lastNameProperty override fun toString() = "$firstName $lastName" override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as Customer if (id != other.id) return false return true } override fun hashCode(): Int { return id.hashCode() } } }
apache-2.0
2ae9419099b8130daa0be6ffd059b275
33.235849
142
0.567374
5.54893
false
false
false
false
cashapp/sqldelight
drivers/driver-test/src/commonMain/kotlin/com/squareup/sqldelight/driver/test/TransacterTest.kt
1
5036
package com.squareup.sqldelight.driver.test import app.cash.sqldelight.TransacterImpl import app.cash.sqldelight.db.QueryResult import app.cash.sqldelight.db.SqlDriver import app.cash.sqldelight.db.SqlSchema import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertTrue abstract class TransacterTest { protected lateinit var transacter: TransacterImpl private lateinit var driver: SqlDriver abstract fun setupDatabase(schema: SqlSchema): SqlDriver @BeforeTest fun setup() { val driver = setupDatabase( object : SqlSchema { override val version = 1 override fun create(driver: SqlDriver): QueryResult<Unit> = QueryResult.Unit override fun migrate( driver: SqlDriver, oldVersion: Int, newVersion: Int, ): QueryResult<Unit> = QueryResult.Unit }, ) transacter = object : TransacterImpl(driver) {} this.driver = driver } @AfterTest fun teardown() { driver.close() } @Test fun afterCommitRunsAfterTransactionCommits() { var counter = 0 transacter.transaction { afterCommit { counter++ } assertEquals(0, counter) } assertEquals(1, counter) } @Test fun afterCommitDoesNotRunAfterTransactionRollbacks() { var counter = 0 transacter.transaction { afterCommit { counter++ } assertEquals(0, counter) rollback() } assertEquals(0, counter) } @Test fun afterCommitRunsAfterEnclosingTransactionCommits() { var counter = 0 transacter.transaction { afterCommit { counter++ } assertEquals(0, counter) transaction { afterCommit { counter++ } assertEquals(0, counter) } assertEquals(0, counter) } assertEquals(2, counter) } @Test fun afterCommitDoesNotRunInNestedTransactionWhenEnclosingRollsBack() { var counter = 0 transacter.transaction { afterCommit { counter++ } assertEquals(0, counter) transaction { afterCommit { counter++ } } rollback() } assertEquals(0, counter) } @Test fun afterCommitDoesNotRunInNestedTransactionWhenNestedRollsBack() { var counter = 0 transacter.transaction { afterCommit { counter++ } assertEquals(0, counter) transaction { afterCommit { counter++ } rollback() } throw AssertionError() } assertEquals(0, counter) } @Test fun afterRollbackNoOpsIfTheTransactionNeverRollsBack() { var counter = 0 transacter.transaction { afterRollback { counter++ } } assertEquals(0, counter) } @Test fun afterRollbackRunsAfterARollbackOccurs() { var counter = 0 transacter.transaction { afterRollback { counter++ } rollback() } assertEquals(1, counter) } @Test fun afterRollbackRunsAfterAnInnerTransactionRollsBack() { var counter = 0 transacter.transaction { afterRollback { counter++ } transaction { rollback() } throw AssertionError() } assertEquals(1, counter) } @Test fun afterRollbackRunsInAnInnerTransactionWhenTheOuterTransactionRollsBack() { var counter = 0 transacter.transaction { transaction { afterRollback { counter++ } } rollback() } assertEquals(1, counter) } @Test fun transactionsCloseThemselvesOutProperly() { var counter = 0 transacter.transaction { afterCommit { counter++ } } transacter.transaction { afterCommit { counter++ } } assertEquals(2, counter) } @Test fun settingNoEnclosingFailsIfThereIsACurrentlyRunningTransaction() { transacter.transaction(noEnclosing = true) { assertFailsWith<IllegalStateException> { transacter.transaction(noEnclosing = true) { throw AssertionError() } } } } @Test fun anExceptionThrownInPostRollbackFunctionIsCombinedWithTheExceptionInTheMainBody() { class ExceptionA : RuntimeException() class ExceptionB : RuntimeException() val t = assertFailsWith<Throwable>() { transacter.transaction { afterRollback { throw ExceptionA() } throw ExceptionB() } } assertTrue("Exception thrown in body not in message($t)") { t.toString().contains("ExceptionA") } assertTrue("Exception thrown in rollback not in message($t)") { t.toString().contains("ExceptionB") } } @Test fun weCanReturnAValueFromATransaction() { val result: String = transacter.transactionWithResult { return@transactionWithResult "sup" } assertEquals(result, "sup") } @Test fun weCanRollbackWithValueFromATransaction() { val result: String = transacter.transactionWithResult { rollback("rollback") @Suppress("UNREACHABLE_CODE") return@transactionWithResult "sup" } assertEquals(result, "rollback") } }
apache-2.0
543d4e5f9c55cef03da9a3ec57659136
21.382222
105
0.663622
4.759924
false
true
false
false
chilangolabs/MDBancomer
app/src/main/java/com/chilangolabs/mdb/utils/Logger.kt
1
1008
package com.chilangolabs.mdb.utils import android.util.Log /** * @author Gorro. */ object Logger { var isDebug = true } fun Any.loge(msg: Any, thr: Throwable? = null) { if (Logger.isDebug) { Log.e(this::class.java.simpleName, "----> $msg", thr) } } fun Any.logi(msg: Any, thr: Throwable? = null) { if (Logger.isDebug) { Log.i(this::class.java.simpleName, "----> $msg", thr) } } fun Any.logd(msg: Any, thr: Throwable? = null) { if (Logger.isDebug) { Log.d(this::class.java.simpleName, "----> $msg", thr) } } fun Any.logw(msg: Any, thr: Throwable? = null) { if (Logger.isDebug) { Log.w(this::class.java.simpleName, "----> $msg", thr) } } fun Any.logv(msg: Any, thr: Throwable? = null) { if (Logger.isDebug) { Log.v(this::class.java.simpleName, "----> $msg", thr) } } fun Any.loga(msg: Any, thr: Throwable? = null) { if (Logger.isDebug) { Log.wtf(this::class.java.simpleName, "----> $msg", thr) } }
mit
100427e44d9e156f4429b5bfb33231e1
19.591837
63
0.564484
2.947368
false
false
false
false
cicakhq/potato
contrib/rqjava/src/com/dhsdevelopments/rqjava/ChannelSubscription.kt
1
1877
package com.dhsdevelopments.rqjava import com.google.gson.Gson import com.rabbitmq.client.AMQP import com.rabbitmq.client.Channel import com.rabbitmq.client.DefaultConsumer import com.rabbitmq.client.Envelope import java.io.ByteArrayInputStream import java.io.InputStreamReader import java.nio.charset.Charset import java.util.logging.Level import java.util.logging.Logger class ChannelSubscription(val conn: PotatoConnection, val cid: String, val callback: (Message) -> Unit) { private val rqChannel: Channel companion object { private val logger = Logger.getLogger(ChannelSubscription::class.qualifiedName) private val UTF8 = Charset.forName("UTF-8") } init { rqChannel = conn.amqpConn.createChannel() try { val q = rqChannel.queueDeclare("", true, false, true, null) // routing key format: DOMAIN.CHANNEL.SENDER rqChannel.queueBind(q.queue, "message-send-ex", "*.$cid.*") val consumer = object : DefaultConsumer(rqChannel) { override fun handleDelivery(consumerTag: String, envelope: Envelope, properties: AMQP.BasicProperties, body: ByteArray) { val gson = Gson() val message = InputStreamReader(ByteArrayInputStream(body), UTF8).use { gson.fromJson(it, Message::class.java) } callback(message) } } rqChannel.basicConsume(q.queue, true, consumer) } catch(e: Exception) { try { rqChannel.close() } catch(e2: Exception) { logger.log(Level.SEVERE, "Error closing channel when handling exception in subscribeChannel", e2) } throw e } } fun disconnect() { rqChannel.close() } }
apache-2.0
6550a12b17da410fb9c0245c27ac0df6
31.947368
137
0.615876
4.578049
false
false
false
false
chadrick-kwag/datalabeling_app
app/src/main/java/com/example/chadrick/datalabeling/Fragments/UserMainFragment.kt
1
5085
package com.example.chadrick.datalabeling.Fragments import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v7.widget.LinearLayoutManager import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import com.android.volley.Request import com.android.volley.toolbox.JsonArrayRequest import com.example.chadrick.datalabeling.Models.* import com.example.chadrick.datalabeling.R import com.example.chadrick.datalabeling.Adapters.RAAdapter import kotlinx.android.synthetic.main.usermainfragment_layout.* import org.json.JSONArray import org.json.JSONObject import java.io.File /** * Created by chadrick on 17. 12. 2. */ class UserMainFragment : Fragment() { private val serverFectchedDSlist: ArrayList<DataSet> = ArrayList<DataSet>() lateinit var allDSrecyclerviewAdapter: RAAdapter lateinit var RArvAdapter: RAAdapter private val RAlist: ArrayList<DataSet> = ArrayList<DataSet>() lateinit var recentactivitylogmanager: RecentActivityLogManager companion object { val TAG = "UserMainFragment" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(TAG,"bitcoin: Usermainfragment created") for( frag in fragmentManager.fragments){ Log.d("bitcoin","print frags in settingsfragment frag = "+frag.toString()) } } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val root: View? = inflater?.inflate(R.layout.usermainfragment_layout, container, false) // setup adapter for RA allDSrecyclerviewAdapter = RAAdapter.newInstance(context, serverFectchedDSlist, ::getfragmentmanager) recentactivitylogmanager = RecentActivityLogManager.getInstance(App.applicationContext()) RArvAdapter = RAAdapter.newInstance(context, RAlist, ::getfragmentmanager) for(frag in fragmentManager.fragments){ Log.d("bitcoin","in Usermainfragment oncreateview frag = "+frag.toString()) } return root } fun getfragmentmanager():FragmentManager{ return fragmentManager } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) AllDSrecyclerview.adapter = allDSrecyclerviewAdapter AllDSrecyclerview.layoutManager = LinearLayoutManager(context.applicationContext, LinearLayoutManager.HORIZONTAL, false) RArecyclerview.adapter = RArvAdapter RArecyclerview.layoutManager = LinearLayoutManager(context.applicationContext, LinearLayoutManager.HORIZONTAL, false) } override fun onResume() { Log.d(TAG, "fuck: inside onresume") super.onResume() updateElements() } private fun populateDSrv() { serverFectchedDSlist.clear() // prepare jsonarray request val reqobj: JSONArray = JSONArray() reqobj.put(JSONObject("{'ds_request_id':'anything'}")) val jsonarrayreq: JsonArrayRequest = JsonArrayRequest(Request.Method.POST, ServerInfo.instance.serveraddress + "/dslist", reqobj, { response: JSONArray -> for (i in 0..(response.length() - 1)) { val item = response.getJSONObject(i) var direxist: Boolean = false val filename = item.get("id").toString() val file: File = File(App.applicationContext().filesDir, filename) if (file.exists()) { direxist = true } val ds: DataSet = DataSet(item.getInt("id"), item.getString("title"), direxist, App.applicationContext().filesDir.toString()) serverFectchedDSlist.add(ds) allDSrecyclerviewAdapter.notifyDataSetChanged() } }, { error -> Toast.makeText(context.applicationContext, "failed to fetch dslist", Toast.LENGTH_SHORT).show() } ) // val queue = Volley.newRequestQueue(context.applicationContext) val queue = requestqueueSingleton.getQueue() queue.add(jsonarrayreq) } fun populateRAlist() { Log.d(TAG, "inside populateRAlist") RAlist.clear() val newlist = recentactivitylogmanager.getsortedlist() for (item in newlist) { RAlist.add(item) } if (RAlist.size == 0) { RArecyclerview.visibility = View.INVISIBLE nonefound_tv.visibility = View.VISIBLE } else { RArecyclerview.visibility = View.VISIBLE nonefound_tv.visibility = View.INVISIBLE } RArvAdapter.notifyDataSetChanged() } fun updateElements(){ populateDSrv() populateRAlist() } }
mit
8f1868b7d493b1976c586d27d9187918
28.917647
149
0.657227
4.788136
false
false
false
false
wendigo/chrome-reactive-kotlin
src/main/kotlin/pl/wendigo/chrome/Browser.kt
1
9189
package pl.wendigo.chrome import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import okhttp3.OkHttpClient import okhttp3.Request import org.slf4j.Logger import org.slf4j.LoggerFactory import org.testcontainers.utility.DockerImageName import pl.wendigo.chrome.api.ProtocolDomains import pl.wendigo.chrome.api.target.TargetInfo import pl.wendigo.chrome.protocol.ProtocolConnection import pl.wendigo.chrome.targets.Manager import pl.wendigo.chrome.targets.Target import java.io.Closeable import kotlin.math.max /** * Creates new browser that allows querying remote Chrome instance for debugging sessions * * @sample pl.wendigo.chrome.samples.Containerized.main */ open class Browser internal constructor( private val browserInfo: BrowserInfo, private val options: Options, connection: ProtocolConnection, private val manager: Manager ) : ProtocolDomains(connection), Closeable, AutoCloseable { /** * Creates new target and opens new debugging session via debugging protocol. * * If incognito is true then new browser context is created (similar to incognito mode but you can have many of those). */ @JvmOverloads fun target(url: String = options.blankPage, incognito: Boolean = options.incognito, width: Int = options.viewportWidth, height: Int = options.viewportHeight): Target { return manager.create( url = url, incognito = incognito, width = width, height = height ) } /** * Lists all targets that can be attached to. */ fun targets(): List<TargetInfo> = manager.list() /** * Returns information on browser. */ fun browserInfo(): BrowserInfo = browserInfo /** * Attaches to existing target creating new session if multiplexed connections is used. */ fun attach(target: TargetInfo): Target = manager.attach(target) /** * Closes target releasing all resources on the browser side and connections. */ fun close(target: Target) { manager.close(target) } /** * Closes session manager and established connection to the debugger. */ override fun close() { try { manager.close() connection.close() } catch (e: Exception) { logger.info("Caught exception while closing Browser", e) } } override fun toString(): String { return "Browser($browserInfo, $options, $manager)" } companion object { private val logger: Logger = LoggerFactory.getLogger(Browser::class.java) private val decoder = Json { ignoreUnknownKeys = true; isLenient = true } /** * Returns library build info. */ @JvmStatic fun buildInfo(): BuildInfo { return Browser.javaClass.getResource("/version.json")!!.readText().run { decoder.decodeFromString(BuildInfo.serializer(), this) } } /** * Creates new Browser instance by connecting to remote chrome debugger. */ private fun connect(chromeAddress: String = "localhost:9222", options: Options): Browser { val info = fetchInfo(chromeAddress) val connection = ProtocolConnection.open(info.webSocketDebuggerUrl, options.eventsBufferSize) val protocol = ProtocolDomains(connection) return Browser( info, options, connection, Manager( info.webSocketDebuggerUrl, options.multiplexConnections, options.eventsBufferSize, protocol ) ) } /** * Fetches browser info. */ internal fun fetchInfo(chromeAddress: String): BrowserInfo { val client = OkHttpClient.Builder().build() val info = client.newCall(Request.Builder().url("http://$chromeAddress/json/version").build()).execute() return when (info.isSuccessful) { true -> decoder.decodeFromString(info.body?.string()!!) false -> throw BrowserInfoDiscoveryFailedException("Could not query browser info - response code was ${info.code}") } } @JvmStatic fun builder() = Builder() } /** * [Builder] is responsible for setting options and defaults while creating new instance of [Browser]. */ class Builder { private var address: String = "localhost:9222" private var blankPage: String = "about:blank" private var eventsBufferSize: Int = 128 private var viewportWidth: Int = 1024 private var viewportHeight: Int = 768 private var multiplexConnections: Boolean = true // see https://crbug.com/991325 private var incognito: Boolean = true private var dockerImage: String = "eu.gcr.io/zenika-hub/alpine-chrome:89" private var runDockerImage: Boolean = false /** * Sets browser debugger address (default: localhost:9222) */ fun withAddress(address: String): Builder = this.apply { this.address = address } /** * Sets default blank page location (default: about:blank) */ fun withBlankPage(address: String): Builder = this.apply { this.blankPage = address } /** * Sets frames buffer size for underlying [pl.wendigo.chrome.protocol.WebSocketFramesStream]'s reactive replaying subject (default: 128) * * High buffer size allows to observe N frames prior to subscribing. */ fun withEventsBufferSize(size: Int): Builder = this.apply { this.eventsBufferSize = max(size, 1) } /** * Sets default viewport height while creating sessions (default; 768, min: 100) */ fun withViewportHeight(height: Int): Builder = this.apply { this.viewportHeight = max(100, height) } /** * Sets default viewport width while creating sessions (default: 1024, min: 100) */ fun withViewportWidth(width: Int): Builder = this.apply { this.viewportWidth = max(100, width) } /** * Enables [Manager] to share single, underlying WebSocket connection to debugger with multiple sessions (default: true) * * @see [https://bugs.chromium.org/p/chromium/issues/detail?id=991325](https://bugs.chromium.org/p/chromium/issues/detail?id=991325) */ fun multiplexConnections(enabled: Boolean): Builder = this.apply { this.multiplexConnections = enabled } /** * Enables incognito mode while creating new targets (default: true) * * Incognito mode uses [pl.wendigo.chrome.api.browser.BrowserContextID] to separate different targets from each other (separating cookies, caches, storages...) */ fun incognito(enabled: Boolean): Builder = this.apply { this.incognito = enabled } /** * Sets docker image name that will be used to create headless Chrome instance (default: eu.gcr.io/zenika-hub/alpine-chrome:89) */ fun withDockerImage(dockerImage: String): Builder = this.apply { this.dockerImage = dockerImage } /** * Enabled creating headless Chrome instance when [Browser] is created (default: false) */ fun runInDocker(enabled: Boolean): Builder = this.apply { this.runDockerImage = enabled } private fun toOptions(): Options = Options( eventsBufferSize = eventsBufferSize, viewportHeight = viewportHeight, viewportWidth = viewportWidth, incognito = incognito, blankPage = blankPage, multiplexConnections = multiplexConnections ) /** * Creates new instance of [Browser] with configuration passed to builder */ fun build(): Browser = when (runDockerImage) { true -> ContainerizedBrowser.connect(DockerImageName.parse(dockerImage), toOptions()) false -> connect(address, toOptions()) } } @Serializable data class BrowserInfo( @SerialName("Browser") val browser: String, @SerialName("Protocol-Version") val protocolVersion: String, @SerialName("User-Agent") val userAgent: String, @SerialName("V8-Version") val v8Version: String? = null, @SerialName("WebKit-Version") val webKitVersion: String, @SerialName("webSocketDebuggerUrl") val webSocketDebuggerUrl: String ) internal data class Options( val eventsBufferSize: Int, val viewportWidth: Int, val viewportHeight: Int, val multiplexConnections: Boolean, val incognito: Boolean, val blankPage: String ) }
apache-2.0
af8afc964eec1796857f7417140a8799
33.033333
171
0.619219
4.985893
false
false
false
false
AndroidX/androidx
compose/runtime/runtime-rxjava2/src/main/java/androidx/compose/runtime/rxjava2/RxJava2Adapter.kt
3
5873
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.runtime.rxjava2 import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.Maybe import io.reactivex.Observable import io.reactivex.Single import io.reactivex.disposables.Disposable import io.reactivex.plugins.RxJavaPlugins /** * Subscribes to this [Observable] and represents its values via [State]. Every time there would * be new value posted into the [Observable] the returned [State] will be updated causing * recomposition of every [State.value] usage. * * The internal observer will be automatically disposed when this composable disposes. * * Note that errors are not handled and the default [RxJavaPlugins.onError] logic will be * used. To handle the error in a more meaningful way you can use operators like * [Observable.onErrorReturn] or [Observable.onErrorResumeNext]. * * @sample androidx.compose.runtime.rxjava2.samples.ObservableSample * * @param initial The initial value for the returned [State] which will be asynchronously updated * with the real one once we receive it from the stream */ @Composable fun <R, T : R> Observable<T>.subscribeAsState(initial: R): State<R> = asState(initial) { subscribe(it) } /** * Subscribes to this [Flowable] and represents its values via [State]. Every time there would * be new value posted into the [Flowable] the returned [State] will be updated causing * recomposition of every [State.value] usage. * * The internal observer will be automatically disposed when this composable disposes. * * Note that errors are not handled and the default [RxJavaPlugins.onError] logic will be * used. To handle the error in a more meaningful way you can use operators like * [Flowable.onErrorReturn] or [Flowable.onErrorResumeNext]. * * @sample androidx.compose.runtime.rxjava2.samples.FlowableSample * * @param initial The initial value for the returned [State] which will be asynchronously updated * with the real one once we receive it from the stream */ @Composable fun <R, T : R> Flowable<T>.subscribeAsState(initial: R): State<R> = asState(initial) { subscribe(it) } /** * Subscribes to this [Single] and represents its value via [State]. Once the value would be * posted into the [Single] the returned [State] will be updated causing recomposition of * every [State.value] usage. * * The internal observer will be automatically disposed when this composable disposes. * * Note that errors are not handled and the default [RxJavaPlugins.onError] logic will be * used. To handle the error in a more meaningful way you can use operators like * [Single.onErrorReturn] or [Single.onErrorResumeNext]. * * @sample androidx.compose.runtime.rxjava2.samples.SingleSample * * @param initial The initial value for the returned [State] which will be asynchronously updated * with the real one once we receive it from the stream */ @Composable fun <R, T : R> Single<T>.subscribeAsState(initial: R): State<R> = asState(initial) { subscribe(it) } /** * Subscribes to this [Maybe] and represents its value via [State]. Once the value would be * posted into the [Maybe] the returned [State] will be updated causing recomposition of * every [State.value] usage. * * The internal observer will be automatically disposed when this composable disposes. * * Note that errors are not handled and the default [RxJavaPlugins.onError] logic will be * used. To handle the error in a more meaningful way you can use operators like * [Maybe.onErrorComplete], [Maybe.onErrorReturn] or [Maybe.onErrorResumeNext]. * * @sample androidx.compose.runtime.rxjava2.samples.MaybeSample * * @param initial The initial value for the returned [State] which will be asynchronously updated * with the real one once we receive it from the stream */ @Composable fun <R, T : R> Maybe<T>.subscribeAsState(initial: R): State<R> = asState(initial) { subscribe(it) } /** * Subscribes to this [Completable] and represents its completed state via [State]. Once the * [Completable] will be completed the returned [State] will be updated with `true` value * causing recomposition of every [State.value] usage. * * The internal observer will be automatically disposed when this composable disposes. * * Note that errors are not handled and the default [RxJavaPlugins.onError] logic will be * used. To handle the error in a more meaningful way you can use operators like * [Completable.onErrorComplete] or [Completable.onErrorResumeNext]. * * @sample androidx.compose.runtime.rxjava2.samples.CompletableSample */ @Composable fun Completable.subscribeAsState(): State<Boolean> = asState(false) { callback -> subscribe { callback(true) } } @Composable private inline fun <T, S> S.asState( initial: T, crossinline subscribe: S.((T) -> Unit) -> Disposable ): State<T> { val state = remember { mutableStateOf(initial) } DisposableEffect(this) { val disposable = subscribe { state.value = it } onDispose { disposable.dispose() } } return state }
apache-2.0
54ee57398440050e4a32af40a1bb717d
40.359155
97
0.750894
4.246565
false
false
false
false
Nunnery/MythicDrops
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/api/socketing/SocketCommand.kt
1
3070
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2019 Richard Harrah * * Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.tealcube.minecraft.bukkit.mythicdrops.api.socketing open class SocketCommand(string: String) { var runner: SocketCommandRunner var command: String var permissions: List<String> = emptyList() init { val indexOfFirstColon = string.indexOf(":") if (indexOfFirstColon == -1) { runner = SocketCommandRunner.DEFAULT command = string.trim { it <= ' ' } } else { var run: SocketCommandRunner? = SocketCommandRunner.fromName(string.substring(0, indexOfFirstColon)) if (run == null) { run = SocketCommandRunner.DEFAULT } runner = run var commandS: String commandS = if (string.substring(0, runner.name.length).equals(runner.name, ignoreCase = true)) { string.substring(runner.name.length, string.length).trim { it <= ' ' } } else { string.trim { it <= ' ' } } if (commandS.substring(0, 1).equals(":", ignoreCase = true)) { commandS = commandS.substring(1, commandS.length).trim { it <= ' ' } } command = commandS.trim { it <= ' ' } } } override fun toString(): String { return "SocketCommand(runner=$runner, command='$command', permissions=$permissions)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SocketCommand) return false if (runner != other.runner) return false if (command != other.command) return false if (permissions != other.permissions) return false return true } override fun hashCode(): Int { var result = runner.hashCode() result = 31 * result + command.hashCode() result = 31 * result + permissions.hashCode() return result } }
mit
9ad5437ef2922df3c8c538cac533b2df
40.486486
112
0.647557
4.679878
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/CurrencyViews.kt
1
2724
package com.habitrpg.android.habitica.ui.views import android.content.Context import android.util.AttributeSet import android.util.TypedValue import android.widget.LinearLayout import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.extensions.isUsingNightModeResources class CurrencyViews : LinearLayout { var lightBackground: Boolean = false set(value) { field = value hourglassTextView.lightBackground = value gemTextView.lightBackground = value goldTextView.lightBackground = value } private val hourglassTextView: CurrencyView = CurrencyView(context, "hourglasses", lightBackground) private val goldTextView: CurrencyView = CurrencyView(context, "gold", lightBackground) private val gemTextView: CurrencyView = CurrencyView(context, "gems", lightBackground) var gold: Double get() = goldTextView.value set(value) { goldTextView.value = value } var gems: Double get() = gemTextView.value set(value) { gemTextView.value = value } var hourglasses: Double get() = hourglassTextView.value set(value) { hourglassTextView.value = value } var hourglassVisibility get() = hourglassTextView.visibility set(value) { hourglassTextView.visibility = value hourglassTextView.hideWhenEmpty = false } var goldVisibility: Int get() = goldTextView.visibility set(value) { goldTextView.visibility = value } var gemVisibility get() = gemTextView.visibility set(value) { gemTextView.visibility = value } constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) { val attributes = context?.theme?.obtainStyledAttributes( attrs, R.styleable.CurrencyViews, 0, 0 ) setupViews() val fallBackLight = context?.isUsingNightModeResources() != true lightBackground = attributes?.getBoolean(R.styleable.CurrencyViews_hasLightBackground, fallBackLight) ?: fallBackLight } constructor(context: Context?) : super(context) { setupViews() } private fun setupViews() { val margin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12f, context.resources.displayMetrics).toInt() setupView(hourglassTextView, margin) setupView(goldTextView, margin) setupView(gemTextView, margin) } private fun setupView(view: CurrencyView, margin: Int) { this.addView(view) view.textSize = 12f val params = view.layoutParams as? LayoutParams params?.marginStart = margin view.layoutParams = params } }
gpl-3.0
0382b1dbeef2cae498df8b855bf079f8
35.810811
126
0.678781
5.101124
false
false
false
false
jorjoluiso/QuijoteLui
src/main/kotlin/com/quijotelui/repository/RetencionDaoImpl.kt
1
3038
package com.quijotelui.repository import com.quijotelui.model.Informacion import com.quijotelui.model.Parametro import com.quijotelui.model.Retencion import com.quijotelui.model.RetencionDetalle import org.springframework.stereotype.Repository import org.springframework.transaction.annotation.Transactional import javax.persistence.EntityManager import javax.persistence.PersistenceContext @Transactional @Repository class RetencionDaoImpl : IRetencionDao { @PersistenceContext lateinit var entityMAnager : EntityManager override fun findAll(): MutableList<Retencion> { return entityMAnager.createQuery("from Retencion").resultList as MutableList<Retencion> } override fun findByComprobante(codigo: String, numero: String): MutableList<Retencion> { return entityMAnager.createQuery("from Retencion " + "where codigo = :codigo " + "and numero = :numero") .setParameter("codigo", codigo) .setParameter("numero", numero).resultList as MutableList<Retencion> } override fun findContribuyenteByComprobante(codigo: String, numero: String): MutableList<Any> { val result = entityMAnager.createQuery("from Contribuyente c, " + "Retencion r " + "WHERE c.id = r.idContribuyente " + "and r.codigo = :codigo " + "and r.numero = :numero") .setParameter("codigo", codigo) .setParameter("numero", numero) .resultList return result as MutableList<Any> } override fun findRetencionDetalleByComprobante(codigo : String, numero : String) : MutableList<RetencionDetalle> { return entityMAnager.createQuery("from RetencionDetalle " + "where codigo = :codigo " + "and numero = :numero") .setParameter("codigo", codigo) .setParameter("numero", numero).resultList as MutableList<RetencionDetalle> } override fun findParametroByNombre(nombre : String) : MutableList<Parametro> { return entityMAnager.createQuery("from Parametro " + "where nombre = :nombre " + "and estado = 'Activo'") .setParameter("nombre", nombre).resultList as MutableList<Parametro> } override fun findInformacionByDocumento(documento: String): MutableList<Informacion> { return entityMAnager.createQuery("from Informacion " + "where documento = :documento") .setParameter("documento", documento) .resultList as MutableList<Informacion> } override fun findEstadoByComprobante(codigo: String, numero: String): MutableList<Any> { return entityMAnager.createQuery("select estado from ReporteRetencion " + "where codigo = :codigo " + "and numero = :numero") .setParameter("codigo", codigo) .setParameter("numero", numero).resultList as MutableList<Any> } }
gpl-3.0
9894ff90c92ea2d87c732a4c075ec319
40.630137
118
0.654049
5.193162
false
false
false
false
jtalks-org/pochta
src/main/kotlin/org/jtalks/pochta/util/SendEmail.kt
1
6215
package org.jtalks.pochta.util import javax.mail.MessagingException import javax.mail.Session import javax.mail.PasswordAuthentication import javax.mail.internet.MimeMessage import javax.mail.internet.InternetAddress import javax.mail.Message import javax.mail.Transport import java.io.StringReader import java.io.ByteArrayInputStream /** * Simple testing utility to send mails */ public fun main(args: Array<String>) { Transport.send(multipartMail()) System.out.println("Sent message successfully....") } fun plainMail(): MimeMessage { val to = "[email protected]" val from = "[email protected]" val properties = System.getProperties() properties?.put("mail.smtp.host", "localhost") properties?.put("mail.smtp.port", "9025") properties?.put("mail.smtp.auth", "true") val session = Session.getDefaultInstance(properties, object : javax.mail.Authenticator() { override fun getPasswordAuthentication(): PasswordAuthentication { return PasswordAuthentication("user", "secret") } }) val message = MimeMessage(session) message.setFrom(InternetAddress(from)) message.addRecipient(Message.RecipientType.TO, InternetAddress(to)) message.setSubject("This is the long long long long long long long longSubject Line!") message.setText("This is actual message") return message } fun b64Mail(): MimeMessage { val message = plainMail() message.setHeader("Content-Transfer-Encoding", "base64"); return message } fun multipartMail(): MimeMessage { val properties = System.getProperties() properties?.put("mail.smtp.host", "localhost") properties?.put("mail.smtp.port", "9025") properties?.put("mail.smtp.auth", "true") val session = Session.getDefaultInstance(properties, object : javax.mail.Authenticator() { override fun getPasswordAuthentication(): PasswordAuthentication { return PasswordAuthentication("user", "secret") } }) val stream = ByteArrayInputStream(("From: [email protected] \n" + "To: [email protected] \n" + "Message-ID: <1799061474.01422213640062.JavaMail.i_autotests@jtalks-infra-1> \n" + "Subject: =?UTF-8?B?0JDQutGC0LjQstCw0YbQuNGPINCw0LrQutCw0YPQvdGC0LAgSlRhbGtz?= \n" + "MIME-Version: 1.0 \n" + "Content-Type: multipart/mixed; \n" + "boundary=\"----=_Part_0_980719463.1422213640036\" \n" + "Date: Sun, 25 Jan 2015 20:20:40 +0100 (CET) \n" + "\n" + "------=_Part_0_980719463.1422213640036 \n" + "Content-Type: multipart/related; \n" + "boundary=\"----=_Part_1_2012376838.1422213640046\" \n" + "\n" + "------=_Part_1_2012376838.1422213640046 \n" + "Content-Type: multipart/alternative; \n" + "boundary=\"----=_Part_2_1297559663.1422213640047\" \n" + "\n" + "------=_Part_2_1297559663.1422213640047 \n" + "Content-Type: text/plain; charset=UTF-8 \n" + "Content-Transfer-Encoding: base64 \n" + "\n" + "CtCf0YDQuNCy0LXRgiwganRYaEVPeE44bzJhVllEeE5tM1lJeURPTyEKCtCt0YLQviDQv9C40YHR\n" + "jNC80L4g0LTQu9GPINC/0L7QtNGC0LLQtdGA0LbQtNC10L3QuNGPINGA0LXQs9C40YHRgtGA0LDR\n" + "htC40Lgg0L3QsCBKVGFsa3Mg0YTQvtGA0YPQvNC1LgrQn9C+0LbQsNC70YPQudGB0YLQsCwg0L/R\n" + "gNC+0YHQu9C10LTRg9C50YLQtSDQv9C+INGB0YHRi9C70LrQtSDQvdC40LbQtSDQtNC70Y8g0LDQ\n" + "utGC0LjQstCw0YbQuNC4INCS0LDRiNC10LPQviDQsNC60LrQsNGD0L3RgtCwLiDQrdGC0LAg0YHR\n" + "gdGL0LvQutCwINC00LXQudGB0YLQstC40YLQtdC70YzQvdCwIDI0INGH0LDRgdCwLgrQktC90LjQ\n" + "vNCw0L3QuNC1LCDQsNC60LrQsNGD0L3RgiDQsdGD0LTQtdGCINCw0LLRgtC+0LzQsNGC0LjRh9C1\n" + "0YHQutC4INGD0LTQsNC70LXQvSDRh9C10YDQtdC3IDI0INGH0LDRgdCwLCDQtdGB0LvQuCDQvdC1\n" + "INCx0YPQtNC10YIg0LDQutGC0LjQstC40YDQvtCy0LDQvS4K0JDQutGC0LjQstCw0YbQuNC+0L3Q\n" + "vdCw0Y8g0YHRgdGL0LvQutCwOiBodHRwOi8vYXV0b3Rlc3RzLmp0YWxrcy5vcmc6ODAvamNvbW11\n" + "bmUvdXNlci9hY3RpdmF0ZS83ODQxNmRmYi1lM2FjLTRkOGEtYWIzMy03OWM4MGQwZjFjMGUKCtCh\n" + "INC90LDQuNC70YPRh9GI0LjQvNC4INC/0L7QttC10LvQsNC90LjRj9C80LgsCtCk0L7RgNGD0Lwg\n" + "SlRhbGtzLg== \n" + "------=_Part_2_1297559663.1422213640047 \n" + "Content-Type: text/html;charset=UTF-8 \n" + "Content-Transfer-Encoding: base64 \n" + "\n" + "CjxwPtCf0YDQuNCy0LXRgiwganRYaEVPeE44bzJhVllEeE5tM1lJeURPTyE8L3A+Cjxici8+Cjxw \n" + "PtCt0YLQviDQv9C40YHRjNC80L4g0LTQu9GPINC/0L7QtNGC0LLQtdGA0LbQtNC10L3QuNGPINGA\n" + "0LXQs9C40YHRgtGA0LDRhtC40Lgg0L3QsCBKVGFsa3Mg0YTQvtGA0YPQvNC1LjwvcD4KPHA+0J/Q\n" + "vtC20LDQu9GD0LnRgdGC0LAsINC/0YDQvtGB0LvQtdC00YPQudGC0LUg0L/QviDRgdGB0YvQu9C6\n" + "0LUg0L3QuNC20LUg0LTQu9GPINCw0LrRgtC40LLQsNGG0LjQuCDQktCw0YjQtdCz0L4g0LDQutC6\n" + "0LDRg9C90YLQsC4g0K3RgtCwINGB0YHRi9C70LrQsCDQtNC10LnRgdGC0LLQuNGC0LXQu9GM0L3Q\n" + "sCAyNCDRh9Cw0YHQsC48L3A+CjxwPtCS0L3QuNC80LDQvdC40LUsINCw0LrQutCw0YPQvdGCINCx\n" + "0YPQtNC10YIg0LDQstGC0L7QvNCw0YLQuNGH0LXRgdC60Lgg0YPQtNCw0LvQtdC9INGH0LXRgNC1\n" + "0LcgMjQg0YfQsNGB0LAsINC10YHQu9C4INC90LUg0LHRg9C00LXRgiDQsNC60YLQuNCy0LjRgNC+\n" + "0LLQsNC9LjwvcD4KPHA+0JDQutGC0LjQstCw0YbQuNC+0L3QvdCw0Y8g0YHRgdGL0LvQutCwOiA8\n" + "YSBocmVmPSJodHRwOi8vYXV0b3Rlc3RzLmp0YWxrcy5vcmc6ODAvamNvbW11bmUvdXNlci9hY3Rp\n" + "dmF0ZS83ODQxNmRmYi1lM2FjLTRkOGEtYWIzMy03OWM4MGQwZjFjMGUiPmh0dHA6Ly9hdXRvdGVz\n" + "dHMuanRhbGtzLm9yZy9qY29tbXVuZS91c2VyL2FjdGl2YXRlLzc4NDE2ZGZiLWUzYWMtNGQ4YS1h\n" + "YjMzLTc5YzgwZDBmMWMwZTwvYT48L3A+CjxiciAvPgo8cD7QoSDQvdCw0LjQu9GD0YfRiNC40LzQ\n" + "uCDQv9C+0LbQtdC70LDQvdC40Y/QvNC4LDwvcD4KPHA+0KTQvtGA0YPQvCBKVGFsa3MuPC9wPg==\n" + "------=_Part_2_1297559663.1422213640047-- \n" + "\n" + "------=_Part_1_2012376838.1422213640046-- \n" + "\n" + "------=_Part_0_980719463.1422213640036-- \n" + "").getBytes("UTF-8")) return MimeMessage(session, stream) }
agpl-3.0
2631956eb2cab08b60888aa5d3d79935
52.128205
96
0.695575
2.609152
false
false
false
false
nrizzio/Signal-Android
app/src/spinner/java/org/thoughtcrime/securesms/database/MessageBitmaskColumnTransformer.kt
1
9658
package org.thoughtcrime.securesms.database import android.database.Cursor import org.signal.core.util.requireLong import org.signal.spinner.ColumnTransformer import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BAD_DECRYPT_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_DRAFT_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_INBOX_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_OUTBOX_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_PENDING_INSECURE_SMS_FALLBACK import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_PENDING_SECURE_SMS_FALLBACK import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_SENDING_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_SENT_FAILED_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_SENT_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_TYPE_MASK import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BOOST_REQUEST_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.CHANGE_NUMBER_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.ENCRYPTION_REMOTE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.ENCRYPTION_REMOTE_DUPLICATE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.ENCRYPTION_REMOTE_FAILED_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.ENCRYPTION_REMOTE_LEGACY_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.ENCRYPTION_REMOTE_NO_SESSION_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.END_SESSION_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.EXPIRATION_TIMER_UPDATE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.GROUP_CALL_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.GROUP_LEAVE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.GROUP_UPDATE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.GROUP_V2_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.GROUP_V2_LEAVE_BITS import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.GV1_MIGRATION_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.INCOMING_AUDIO_CALL_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.INCOMING_VIDEO_CALL_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.INVALID_MESSAGE_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.JOINED_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.KEY_EXCHANGE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.KEY_EXCHANGE_BUNDLE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.KEY_EXCHANGE_CONTENT_FORMAT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.KEY_EXCHANGE_CORRUPTED_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.KEY_EXCHANGE_IDENTITY_DEFAULT_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.KEY_EXCHANGE_IDENTITY_UPDATE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.KEY_EXCHANGE_IDENTITY_VERIFIED_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.KEY_EXCHANGE_INVALID_VERSION_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.MESSAGE_FORCE_SMS_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.MESSAGE_RATE_LIMITED_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.MISSED_AUDIO_CALL_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.MISSED_VIDEO_CALL_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.OUTGOING_AUDIO_CALL_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.OUTGOING_MESSAGE_TYPES import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.OUTGOING_VIDEO_CALL_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.PROFILE_CHANGE_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.PUSH_MESSAGE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.SECURE_MESSAGE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.SMS_EXPORT_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.SPECIAL_TYPES_MASK import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.SPECIAL_TYPE_GIFT_BADGE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.SPECIAL_TYPE_PAYMENTS_ACTIVATED import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.SPECIAL_TYPE_PAYMENTS_ACTIVATE_REQUEST import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.SPECIAL_TYPE_PAYMENTS_NOTIFICATION import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.SPECIAL_TYPE_STORY_REACTION import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.THREAD_MERGE_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.UNSUPPORTED_MESSAGE_TYPE object MessageBitmaskColumnTransformer : ColumnTransformer { override fun matches(tableName: String?, columnName: String): Boolean { return columnName == "type" || columnName == "msg_box" } override fun transform(tableName: String?, columnName: String, cursor: Cursor): String { val type = cursor.requireLong(columnName) val describe = """ isOutgoingMessageType:${isOutgoingMessageType(type)} isForcedSms:${type and MESSAGE_FORCE_SMS_BIT != 0L} isDraftMessageType:${type and BASE_TYPE_MASK == BASE_DRAFT_TYPE} isFailedMessageType:${type and BASE_TYPE_MASK == BASE_SENT_FAILED_TYPE} isPendingMessageType:${type and BASE_TYPE_MASK == BASE_OUTBOX_TYPE || type and BASE_TYPE_MASK == BASE_SENDING_TYPE } isSentType:${type and BASE_TYPE_MASK == BASE_SENT_TYPE} isPendingSmsFallbackType:${type and BASE_TYPE_MASK == BASE_PENDING_INSECURE_SMS_FALLBACK || type and BASE_TYPE_MASK == BASE_PENDING_SECURE_SMS_FALLBACK} isPendingSecureSmsFallbackType:${type and BASE_TYPE_MASK == BASE_PENDING_SECURE_SMS_FALLBACK} isPendingInsecureSmsFallbackType:${type and BASE_TYPE_MASK == BASE_PENDING_INSECURE_SMS_FALLBACK} isInboxType:${type and BASE_TYPE_MASK == BASE_INBOX_TYPE} isJoinedType:${type and BASE_TYPE_MASK == JOINED_TYPE} isUnsupportedMessageType:${type and BASE_TYPE_MASK == UNSUPPORTED_MESSAGE_TYPE} isInvalidMessageType:${type and BASE_TYPE_MASK == INVALID_MESSAGE_TYPE} isBadDecryptType:${type and BASE_TYPE_MASK == BAD_DECRYPT_TYPE} isSecureType:${type and SECURE_MESSAGE_BIT != 0L} isPushType:${type and PUSH_MESSAGE_BIT != 0L} isEndSessionType:${type and END_SESSION_BIT != 0L} isKeyExchangeType:${type and KEY_EXCHANGE_BIT != 0L} isIdentityVerified:${type and KEY_EXCHANGE_IDENTITY_VERIFIED_BIT != 0L} isIdentityDefault:${type and KEY_EXCHANGE_IDENTITY_DEFAULT_BIT != 0L} isCorruptedKeyExchange:${type and KEY_EXCHANGE_CORRUPTED_BIT != 0L} isInvalidVersionKeyExchange:${type and KEY_EXCHANGE_INVALID_VERSION_BIT != 0L} isBundleKeyExchange:${type and KEY_EXCHANGE_BUNDLE_BIT != 0L} isContentBundleKeyExchange:${type and KEY_EXCHANGE_CONTENT_FORMAT != 0L} isIdentityUpdate:${type and KEY_EXCHANGE_IDENTITY_UPDATE_BIT != 0L} isRateLimited:${type and MESSAGE_RATE_LIMITED_BIT != 0L} isExpirationTimerUpdate:${type and EXPIRATION_TIMER_UPDATE_BIT != 0L} isIncomingAudioCall:${type == INCOMING_AUDIO_CALL_TYPE} isIncomingVideoCall:${type == INCOMING_VIDEO_CALL_TYPE} isOutgoingAudioCall:${type == OUTGOING_AUDIO_CALL_TYPE} isOutgoingVideoCall:${type == OUTGOING_VIDEO_CALL_TYPE} isMissedAudioCall:${type == MISSED_AUDIO_CALL_TYPE} isMissedVideoCall:${type == MISSED_VIDEO_CALL_TYPE} isGroupCall:${type == GROUP_CALL_TYPE} isGroupUpdate:${type and GROUP_UPDATE_BIT != 0L} isGroupV2:${type and GROUP_V2_BIT != 0L} isGroupQuit:${type and GROUP_LEAVE_BIT != 0L && type and GROUP_V2_BIT == 0L} isChatSessionRefresh:${type and ENCRYPTION_REMOTE_FAILED_BIT != 0L} isDuplicateMessageType:${type and ENCRYPTION_REMOTE_DUPLICATE_BIT != 0L} isDecryptInProgressType:${type and 0x40000000 != 0L} isNoRemoteSessionType:${type and ENCRYPTION_REMOTE_NO_SESSION_BIT != 0L} isLegacyType:${type and ENCRYPTION_REMOTE_LEGACY_BIT != 0L || type and ENCRYPTION_REMOTE_BIT != 0L} isProfileChange:${type == PROFILE_CHANGE_TYPE} isGroupV1MigrationEvent:${type == GV1_MIGRATION_TYPE} isChangeNumber:${type == CHANGE_NUMBER_TYPE} isBoostRequest:${type == BOOST_REQUEST_TYPE} isThreadMerge:${type == THREAD_MERGE_TYPE} isSmsExport:${type == SMS_EXPORT_TYPE} isGroupV2LeaveOnly:${type and GROUP_V2_LEAVE_BITS == GROUP_V2_LEAVE_BITS} isSpecialType:${type and SPECIAL_TYPES_MASK != 0L} isStoryReaction:${type and SPECIAL_TYPES_MASK == SPECIAL_TYPE_STORY_REACTION} isGiftBadge:${type and SPECIAL_TYPES_MASK == SPECIAL_TYPE_GIFT_BADGE} isPaymentsNotificaiton:${type and SPECIAL_TYPES_MASK == SPECIAL_TYPE_PAYMENTS_NOTIFICATION} isRequestToActivatePayments:${type and SPECIAL_TYPES_MASK == SPECIAL_TYPE_PAYMENTS_ACTIVATE_REQUEST} isPaymentsActivated:${type and SPECIAL_TYPES_MASK == SPECIAL_TYPE_PAYMENTS_ACTIVATED} """.trimIndent() return "$type<br><br>" + describe.replace(Regex("is[A-Z][A-Za-z0-9]*:false\n?"), "").replace("\n", "<br>") } private fun isOutgoingMessageType(type: Long): Boolean { for (outgoingType in OUTGOING_MESSAGE_TYPES) { if (type and BASE_TYPE_MASK == outgoingType) return true } return false } }
gpl-3.0
29ad653c9d82c1bd1679e44abcd7ac3b
68.482014
158
0.793643
4.025844
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/data/checker/CheckUsers.kt
1
8218
/* * Copyright (c) 2018 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.data.checker import android.provider.BaseColumns import org.andstatus.app.data.ActorSql import org.andstatus.app.data.DbUtils import org.andstatus.app.data.MyProvider import org.andstatus.app.database.table.ActorTable import org.andstatus.app.net.social.Actor import org.andstatus.app.user.User import org.andstatus.app.util.MyLog import org.andstatus.app.util.StringUtil import org.andstatus.app.util.TriState import java.util.* import java.util.stream.IntStream /** * @author [email protected] */ internal class CheckUsers : DataChecker() { private class CheckResults { var actorsToMergeUsers: MutableMap<String, MutableSet<Actor>> = HashMap() var usersToSave: MutableSet<User> = HashSet() var actorsWithoutUsers: MutableSet<Actor> = HashSet() var actorsToFixWebFingerId: MutableSet<Actor> = HashSet() var actorsWithoutOrigin: MutableSet<Actor> = HashSet() var problems: MutableList<String> = ArrayList() } override fun fixInternal(): Long { val results = getResults() logResults(results) if (countOnly) return results.problems.size.toLong() var changedCount: Long = 0 for (user in results.usersToSave) { user.save(myContext) changedCount++ } changedCount += results.actorsToMergeUsers.values.stream().mapToLong { actors: MutableSet<Actor> -> mergeUsers(actors) }.sum() for (actor in results.actorsWithoutOrigin) { val parent = actor.getParent() if (parent.nonEmpty) { // The error affects development database only val groupUsername: String = actor.groupType.name + ".of." + parent.getUsername() + "." + parent.actorId val groupTempOid = StringUtil.toTempOid(groupUsername) val sql = "UPDATE " + ActorTable.TABLE_NAME + " SET " + ActorTable.ORIGIN_ID + "=" + parent.origin.id + ", " + ActorTable.USERNAME + "='" + groupUsername + "', " + ActorTable.ACTOR_OID + "='" + groupTempOid + "'" + " WHERE " + BaseColumns._ID + "=" + actor.actorId myContext.database?.execSQL(sql) changedCount++ } else { MyLog.w(this, "Couldn't fix origin for $actor") } } for (actor in results.actorsToFixWebFingerId) { val sql = ("UPDATE " + ActorTable.TABLE_NAME + " SET " + ActorTable.WEBFINGER_ID + "='" + actor.getWebFingerId() + "' WHERE " + BaseColumns._ID + "=" + actor.actorId) myContext.database?.execSQL(sql) changedCount++ } for (actor1 in results.actorsWithoutUsers) { val actor = actor1.lookupUser() actor.saveUser() val sql = ("UPDATE " + ActorTable.TABLE_NAME + " SET " + ActorTable.USER_ID + "=" + actor.user.userId + " WHERE " + BaseColumns._ID + "=" + actor.actorId) myContext.database?.execSQL(sql) changedCount++ } return changedCount } private fun logResults(results: CheckResults) { if (results.problems.isEmpty()) { MyLog.d(this, "No problems found") return } MyLog.i(this, "Problems found: " + results.problems.size) IntStream.range(0, results.problems.size) .mapToObj { i: Int -> (i + 1).toString() + ". " + results.problems[i] } .forEachOrdered { s: String? -> MyLog.i(this, s) } } private fun getResults(): CheckResults { val results = CheckResults() val sql = ("SELECT " + ActorSql.selectFullProjection() + " FROM " + ActorSql.tables(isFullProjection = true, userOnly = false, userIsOptional = true) + " ORDER BY " + ActorTable.WEBFINGER_ID + " COLLATE NOCASE") var rowsCount: Long = 0 MyLog.v(this) { sql } myContext.database?.rawQuery(sql, null).use { c -> var key = "" var actors: MutableSet<Actor> = HashSet() while (c?.moveToNext() == true) { rowsCount++ val actor: Actor = Actor.fromCursor(myContext, c, false) val webFingerId = DbUtils.getString(c, ActorTable.WEBFINGER_ID) if (actor.isWebFingerIdValid() && actor.getWebFingerId() != webFingerId) { results.actorsToFixWebFingerId.add(actor) results.problems.add("Fix webfingerId: '$webFingerId' $actor") } if (myContext.accounts.fromWebFingerId(actor.getWebFingerId()).isValid && actor.user.isMyUser.untrue ) { actor.user.isMyUser = TriState.TRUE results.usersToSave.add(actor.user) results.problems.add("Fix user isMy: $actor") } else if (actor.user.userId == 0L) { results.actorsWithoutUsers.add(actor) results.problems.add("Fix userId==0: $actor") } if (actor.origin.isEmpty) { results.actorsWithoutOrigin.add(actor) results.problems.add("Fix no Origin: $actor") } if (key.isEmpty() || actor.getWebFingerId() != key) { if (shouldMerge(actors)) { results.actorsToMergeUsers[key] = actors results.problems.add("Fix merge users 1 \"$key\": $actors") } key = actor.getWebFingerId() actors = HashSet() } actors.add(actor) } if (shouldMerge(actors)) { results.actorsToMergeUsers[key] = actors results.problems.add("Fix merge users 2 \"$key\": $actors") } } logger.logProgress("Check completed, " + rowsCount + " actors checked." + " Users of actors to be merged: " + results.actorsToMergeUsers.size + ", to fix WebfingerId: " + results.actorsToFixWebFingerId.size + ", to add users: " + results.actorsWithoutUsers.size + ", to save users: " + results.usersToSave.size ) return results } private fun shouldMerge(actors: MutableSet<Actor>): Boolean { return actors.size > 1 && (actors.stream().anyMatch { a: Actor -> a.user.userId == 0L } || actors.stream().mapToLong { a: Actor -> a.user.userId }.distinct().count() > 1) } private fun mergeUsers(actors: MutableSet<Actor>): Long { val userWith = actors.stream().map { a: Actor -> a.user }.reduce { a: User, b: User -> if (a.userId < b.userId) a else b } .orElse(User.EMPTY) return if (userWith.userId == 0L) 0 else actors.stream().map { actor: Actor -> val logMsg = "Linking $actor with $userWith" if (logger.loggedMoreSecondsAgoThan(5)) logger.logProgress(logMsg) MyProvider.update(myContext, ActorTable.TABLE_NAME, ActorTable.USER_ID + "=" + userWith.userId, BaseColumns._ID + "=" + actor.actorId ) if (actor.user.userId != 0L && actor.user.userId != userWith.userId && userWith.isMyUser.isTrue) { actor.user.isMyUser = TriState.FALSE actor.user.save(myContext) } 1 }.count() } }
apache-2.0
c5a452d919d7bec6e355b96d53a0b50d
45.429379
134
0.573254
4.483361
false
false
false
false
esofthead/mycollab
mycollab-reporting/src/main/java/com/mycollab/reporting/ReportTemplateExecutor.kt
3
5212
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.reporting import com.mycollab.core.MyCollabException import com.mycollab.core.utils.DateTimeUtils import net.sf.dynamicreports.report.builder.DynamicReports.cmp import net.sf.dynamicreports.report.builder.DynamicReports.hyperLink import net.sf.dynamicreports.report.builder.component.ComponentBuilder import net.sf.dynamicreports.report.constant.HorizontalTextAlignment import net.sf.dynamicreports.report.exception.DRException import org.slf4j.LoggerFactory import java.io.* import java.time.LocalDateTime import java.time.ZoneId import java.util.* import java.util.concurrent.CountDownLatch /** * @author MyCollab Ltd * @since 5.1.4 */ abstract class ReportTemplateExecutor(protected var timeZone: ZoneId, protected var locale: Locale, protected var reportTitle: String, protected var outputForm: ReportExportType) { lateinit var parameters: MutableMap<String, Any> protected var reportStyles: ReportStyles = ReportStyles.instance() val defaultExportFileName: String get() = outputForm.defaultFileName @Throws(Exception::class) abstract fun initReport() @Throws(DRException::class) abstract fun fillReport() @Throws(IOException::class, DRException::class) abstract fun outputReport(outputStream: OutputStream) protected fun defaultTitleComponent(): ComponentBuilder<*, *> { val link = hyperLink("https://www.mycollab.com") val dynamicReportsComponent = cmp.horizontalList( cmp.image(ReportTemplateExecutor::class.java.classLoader.getResourceAsStream("images/logo.png")) .setFixedDimension(150, 28), cmp.horizontalGap(20), cmp.verticalList( cmp.text("https://www.mycollab.com").setStyle(reportStyles.italicStyle).setHyperLink(link) .setHorizontalTextAlignment(HorizontalTextAlignment.RIGHT), cmp.text("Generated at: ${DateTimeUtils.formatDate(LocalDateTime.now(), "yyyy-MM-dd'T'HH:mm:ss", Locale.US, timeZone)}") .setHorizontalTextAlignment(HorizontalTextAlignment.RIGHT)) ) return cmp.horizontalList().add(dynamicReportsComponent).newRow().add(reportStyles.line()).newRow().add(cmp.verticalGap(10)) } fun exportStream(): InputStream { val latch = CountDownLatch(1) val inStream = PipedInputStream() val `in` = object : InputStream() { @Throws(IOException::class) override fun read(b: ByteArray): Int { return inStream.read(b) } @Throws(IOException::class) override fun read(): Int { return inStream.read() } @Throws(IOException::class) override fun close() { super.close() latch.countDown() } } val outputStream = PipedOutputStream() Thread(Runnable { val out = object : OutputStream() { @Throws(IOException::class) override fun write(b: Int) { outputStream.write(b) } @Throws(IOException::class) override fun close() { while (latch.count != 0L) { try { latch.await() } catch (e: InterruptedException) { e.printStackTrace() break } } super.close() } } try { parameters = parameters initReport() fillReport() outputReport(out) } catch (e: Exception) { LOG.error("Error report", e) } finally { try { outputStream.close() out.close() } catch (e: IOException) { LOG.error("Try to close reporting stream error", e) } } }).start() try { outputStream.connect(inStream) } catch (e: IOException) { throw MyCollabException(e) } return `in` } companion object { private val LOG = LoggerFactory.getLogger(ReportTemplateExecutor::class.java) } }
agpl-3.0
14bd0384f089d0263fe45a027e484032
34.691781
188
0.591249
5.015399
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/codeInsight/inspection/SimplifyLocalAssignment.kt
2
2482
/* * 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.codeInsight.inspection import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import com.intellij.psi.util.PsiTreeUtil import com.tang.intellij.lua.Constants import com.tang.intellij.lua.psi.LuaLiteralExpr import com.tang.intellij.lua.psi.LuaLocalDef import com.tang.intellij.lua.psi.LuaVisitor import org.jetbrains.annotations.Nls /** * * Created by tangzx on 2016/12/16. */ class SimplifyLocalAssignment : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return object : LuaVisitor() { override fun visitLocalDef(o: LuaLocalDef) { val exprList = o.exprList if (exprList != null) { val list = exprList.exprList if (list.size == 1) { val expr = list[0] if (expr is LuaLiteralExpr && Constants.WORD_NIL == expr.getText()) { holder.registerProblem(expr, "Local assignment can be simplified", ProblemHighlightType.LIKE_UNUSED_SYMBOL, Fix()) } } } } } } inner class Fix : LocalQuickFix { @Nls override fun getFamilyName(): String { return "Simplify local assignment" } override fun applyFix(project: Project, problemDescriptor: ProblemDescriptor) { val localDef = PsiTreeUtil.getParentOfType(problemDescriptor.endElement, LuaLocalDef::class.java) val assign = localDef?.assign val exprList = localDef?.exprList if (localDef != null && assign != null && exprList != null) localDef.deleteChildRange(assign, exprList) } } }
apache-2.0
03d9674ce4afe9c3bc27c758e5f2158f
36.606061
142
0.649476
4.630597
false
false
false
false
SiimKinks/sqlitemagic
gradle-plugin/src/main/kotlin/com/siimkinks/sqlitemagic/task/InvokeTransformation.kt
1
2351
package com.siimkinks.sqlitemagic.task import com.siimkinks.sqlitemagic.annotation.internal.Invokes import javassist.CtClass import javassist.CtMethod import javassist.bytecode.annotation.Annotation import org.gradle.api.file.FileCollection import org.gradle.api.logging.Logging import java.io.File class InvokeTransformation( destinationDir: File, sources: FileCollection, classpath: FileCollection, debug: Boolean = false ) : BaseTransformation(destinationDir, sources, classpath, debug) { private val METHOD_ANNOTATIONS = setOf<String>(Invokes::class.java.canonicalName) override val LOG = Logging.getLogger(InvokeTransformation::class.java) override fun shouldTransform(candidateClass: CtClass): Boolean { return candidateClass.methods.any { it.hasAnyAnnotationFrom(METHOD_ANNOTATIONS) } } override fun applyTransform(clazz: CtClass) { logInfo("Transforming ${clazz.name}") clazz.methods.forEach { val invokes = it.findAnnotation(Invokes::class.java) if (invokes != null) { handleInvocation(clazz, it, invokes) } } } private fun handleInvocation(clazz: CtClass, method: CtMethod, invokesAnnotation: Annotation) { val value = invokesAnnotation.getAnnotationElementValue(ANNOTATION_VALUE_NAME) ?: return val pos = value.indexOf("#") val targetMethod = value.substring(pos + 1) val targetClass = value.substring(0, pos) logInfo("Invoker ${method.name} invokes targetMethod $targetMethod of class $targetClass") try { val body = StringBuilder() val returnType = method.returnType if (!returnType.name.equals("void", ignoreCase = true)) { body.append("return ") } body.append(targetClass) body.append('.') body.append(targetMethod) body.append('(') if (invokesAnnotation.getAnnotationElementValue("useThisAsOnlyParam")?.toBoolean() == true) { body.append("this") } else { body.append("$$") } body.append(");") method.setBody(body.toString()) } catch (e: Throwable) { val errMsg = e.message if (errMsg != null && errMsg.contains("class is frozen")) { logInfo("Not transforming frozen class ${clazz.name}; errMsg=$errMsg") } else { logError("Transformation failed for class ${clazz.name}", e) } } } }
apache-2.0
4e3f688a31fb85056e52d6fde51d4eab
34.104478
99
0.692897
4.386194
false
false
false
false
naosim/RPGSample
rpglib/src/main/kotlin/com/naosim/rpglib/model/value/field/Field.kt
1
1012
package com.naosim.rpglib.model.value.field import com.naosim.rpglib.model.viewmodel.sound.bgm.HasBGM class Field( val fieldName: FieldName, val hasBGM: HasBGM? = null, private val backFieldDataAndFieldCollisionData: FieldDataAndFieldCollisionData, private val frontFieldDataAndFieldCollisionData: FieldDataAndFieldCollisionData? = null ) { constructor(fieldName: FieldName, backFieldDataAndFieldCollisionData: FieldDataAndFieldCollisionData, frontFieldDataAndFieldCollisionData: FieldDataAndFieldCollisionData? = null) : this(fieldName, null, backFieldDataAndFieldCollisionData, frontFieldDataAndFieldCollisionData) val backFieldLayer = FieldLayer(fieldName, FieldLayerNameType.back, backFieldDataAndFieldCollisionData) val frontFieldLayer: FieldLayer? = if(frontFieldDataAndFieldCollisionData != null) { FieldLayer(fieldName, FieldLayerNameType.front, frontFieldDataAndFieldCollisionData) } else { null } }
mit
f2ea5cf3917126a8cd0b34def9a24609
47.238095
189
0.773715
5.685393
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/model/DaoUtil.kt
1
1244
package com.intfocus.template.model import android.content.Context import android.database.sqlite.SQLiteDatabase import com.intfocus.template.model.gen.* /** * @author liuruilin * @data 2017/11/5 * @describe */ object DaoUtil { private var daoSession: DaoSession? = null private var database: SQLiteDatabase? = null /** * 初始化数据库 * 建议放在Application中执行 */ fun initDataBase(context: Context) { //通过DaoMaster的内部类DevOpenHelper,可得到一个SQLiteOpenHelper对象。 val devOpenHelper = DaoMaster.DevOpenHelper(context, "shengyiplus.db", null) //数据库名称 database = devOpenHelper.writableDatabase val daoMaster = DaoMaster(database) daoSession = daoMaster.newSession() } fun getDaoSession(): DaoSession? = daoSession fun getDatabase(): SQLiteDatabase? = database fun getSourceDao(): SourceDao = daoSession!!.sourceDao fun getCollectionDao(): CollectionDao = daoSession!!.collectionDao fun getReportDao(): ReportDao = daoSession!!.reportDao fun getPushMsgDao(): PushMsgBeanDao = daoSession!!.pushMsgBeanDao fun getAttentionItemDao(): AttentionItemDao = daoSession!!.attentionItemDao }
gpl-3.0
ba6438e923fcfcfdbb93bcc97caeb642
27.047619
92
0.718166
4.51341
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/model/response/mine_page/UserInfo.kt
1
586
package com.intfocus.template.model.response.mine_page /** * Created by liuruilin on 2017/8/11. */ class UserInfo { var user_num: String? = null var user_name: String? = null var gravatar: String? = null var group_name: String? = null var role_name: String? = null var login_duration: String? = null var browse_report_count: String? = null var surpass_percentage: Double = 0.toDouble() var login_count: String? = null var browse_count: String? = null var coordinate_location: String? = null var browse_distinct_count: String? = null }
gpl-3.0
aa2ea4362bbb7700de92bec9574db134
29.842105
54
0.670648
3.595092
false
false
false
false
WillowChat/Hopper
src/main/kotlin/chat/willow/hopper/auth/Pbdfk2HmacSha512PasswordStorage.kt
1
4031
package chat.willow.hopper.auth import java.security.NoSuchAlgorithmException import java.security.spec.InvalidKeySpecException import java.util.* import javax.crypto.SecretKeyFactory import javax.crypto.spec.PBEKeySpec typealias EncodedEntry = String interface IPbdfk2HmacSha512PasswordStorage { fun deriveKey(plaintext: String, salt: String, iterations: Int = Pbdfk2HmacSha512PasswordStorage.DEFAULT_ITERATIONS, keyLengthBits: Int = Pbdfk2HmacSha512PasswordStorage.DEFAULT_KEY_LENGTH_BITS): ByteArray? fun encode(salt: String, computedHash: ByteArray, iterations: Int = Pbdfk2HmacSha512PasswordStorage.DEFAULT_ITERATIONS): EncodedEntry? fun decode(encodedEntry: EncodedEntry): Pbdfk2HmacSha512PasswordStorage.DecodedEntry? } object Pbdfk2HmacSha512PasswordStorage: IPbdfk2HmacSha512PasswordStorage { val DEFAULT_ITERATIONS = 64000 val DEFAULT_KEY_LENGTH_BITS = 256 private val BITS_IN_A_BYTE = 8 private val MIN_ITERATIONS = 10000 private val MAX_ITERATIONS = 1000000 private val MIN_SALT_LENGTH = 8 private val MAX_SALT_LENGTH = 256 private val MIN_PLAINTEXT_LENGTH = 8 private val MAX_PLAINTEXT_LENGTH = 256 private val MIN_ENCODED_HASH_SANITY = 8 override fun deriveKey(plaintext: String, salt: String, iterations: Int, keyLengthBits: Int): ByteArray? { if (plaintext.length < MIN_PLAINTEXT_LENGTH || plaintext.length > MAX_PLAINTEXT_LENGTH) { return null } if (salt.length < MIN_SALT_LENGTH || salt.length > MAX_SALT_LENGTH) { return null } if (iterations < MIN_ITERATIONS || iterations > MAX_ITERATIONS) { return null } try { // TODO: Extract and make testable by wrapping SKF stuff val skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512") val spec = PBEKeySpec(plaintext.toCharArray(), salt.toByteArray(charset = Charsets.UTF_8), iterations, keyLengthBits) val key = skf.generateSecret(spec) if (key.encoded.isEmpty()) { return null } return key.encoded } catch (e: NoSuchAlgorithmException) { return null } catch (e: InvalidKeySpecException) { return null } } // algorithm:iterations:hashSize:salt:hash // 1:64000:hashsizebits:salt:hash override fun encode(salt: String, computedHash: ByteArray, iterations: Int): String? { if (computedHash.isEmpty()) { return null } if (salt.contains(':')) { return null } val encodedHash = Base64.getEncoder().encodeToString(computedHash) return "1:$iterations:${computedHash.size * BITS_IN_A_BYTE}:$salt:$encodedHash" } override fun decode(encodedEntry: String): DecodedEntry? { val parts = encodedEntry.split(':', limit = 5) if (parts.any { it.contains(":") } || parts.size != 5) { return null } val iterations = parts.getOrNull(1)?.toIntOrNull() ?: return null val hashSize = parts.getOrNull(2)?.toIntOrNull() ?: return null val salt = parts.getOrNull(3) ?: return null val encodedHash = parts.getOrNull(4) ?: return null if (salt.length < MIN_SALT_LENGTH || salt.length > MAX_SALT_LENGTH) { return null } if (iterations < MIN_ITERATIONS || iterations > MAX_ITERATIONS) { return null } if (encodedHash.length < MIN_ENCODED_HASH_SANITY) { return null } return DecodedEntry(encodedHash, iterations, hashSize, salt) } private fun extractFrom(parts: List<String>, index: Int): Int? { val part: String = parts.getOrNull(index) ?: return null return part.toIntOrNull() } data class DecodedEntry(val derivedKeyHash: String, val iterations: Int, val hashSize: Int, val salt: String) }
isc
a84ff1738a850932d2048700225873c6
31.516129
129
0.640536
4.498884
false
false
false
false
rhdunn/xquery-intellij-plugin
src/plugin-existdb/main/uk/co/reecedunn/intellij/plugin/existdb/query/rest/EXistDBQueryError.kt
1
2881
/* * Copyright (C) 2018-2020 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.existdb.query.rest import com.intellij.openapi.vfs.VirtualFile import org.jsoup.Jsoup import uk.co.reecedunn.intellij.plugin.core.xml.dom.XmlDocument import uk.co.reecedunn.intellij.plugin.processor.debug.frame.VirtualFileStackFrame import uk.co.reecedunn.intellij.plugin.processor.query.QueryError import uk.co.reecedunn.intellij.plugin.xpm.module.path.XpmModuleUri @Suppress("RegExpAnonymousGroup") private val RE_EXISTDB_MESSAGE = "^(exerr:ERROR )?(org.exist.xquery.XPathException: )?([^ ]+) (.*)\n?$".toRegex() @Suppress("RegExpAnonymousGroup") private val RE_EXISTDB_LOCATION = "^line ([0-9]+), column ([0-9]+).*$".toRegex() fun String.toEXistDBQueryError(queryFile: VirtualFile): QueryError = when { this.startsWith("<html>") -> parseMessageHtml() else -> this.parseMessageXml(queryFile) } private fun String.parseMessageHtml(): QueryError { val html = Jsoup.parse(this) return QueryError( standardCode = "FOER0000", vendorCode = null, description = html.select("title").text(), value = listOf(), frames = listOf() ) } private fun String.parseMessageXml(queryFile: VirtualFile): QueryError { val xml = XmlDocument.parse(this, mapOf()) val messageText = xml.root.children("message").first().text()!!.split("\n")[0] val parts = RE_EXISTDB_MESSAGE.matchEntire(messageText)?.groupValues ?: throw RuntimeException("Cannot parse eXist-db error message: $messageText") val locationParts = RE_EXISTDB_LOCATION.matchEntire(parts[4].substringAfter(" [at "))?.groupValues val path = xml.root.children("path").first().text() val line = locationParts?.get(1)?.toIntOrNull() ?: 1 val col = locationParts?.get(2)?.toIntOrNull() ?: 1 val frame = when (path) { null, "/db" -> VirtualFileStackFrame(queryFile, line - 1, col - 1) else -> VirtualFileStackFrame(XpmModuleUri(queryFile, path), line - 1, col - 1) } return QueryError( standardCode = (parts[3].let { if (it == "Type:") null else it } ?: "FOER0000").replace("^err:".toRegex(), ""), vendorCode = null, description = parts[4].substringBefore(" [at "), value = listOf(), frames = listOf(frame) ) }
apache-2.0
17c9a9253b481a5f6a8ca34dc8b36cf8
39.013889
119
0.688997
3.930423
false
false
false
false
K0zka/wikistat
src/main/kotlin/org/dictat/wikistat/model/Nova.kt
1
465
package org.dictat.wikistat.model import java.util.Date import com.fasterxml.jackson.annotation.JsonProperty /** * A nova is an exceptional (over-average) behavior of a page. */ public data class Nova { JsonProperty("s") var start: Date? = null JsonProperty("e") var end: Date? = null JsonProperty("n") var novaType: NovaType? = null JsonProperty("l") var lang: String? = null JsonProperty("p") var page: String? = null }
apache-2.0
bf0266ae66adec7a99ba7996feb2b7b1
22.3
62
0.668817
3.632813
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/exh/metadata/sql/queries/SearchTagQueries.kt
1
1780
package exh.metadata.sql.queries import com.pushtorefresh.storio.sqlite.queries.DeleteQuery import com.pushtorefresh.storio.sqlite.queries.Query import eu.kanade.tachiyomi.data.database.DbProvider import eu.kanade.tachiyomi.data.database.inTransaction import exh.metadata.sql.models.SearchTag import exh.metadata.sql.tables.SearchTagTable interface SearchTagQueries : DbProvider { fun getSearchTagsForManga(mangaId: Long) = db.get() .listOfObjects(SearchTag::class.java) .withQuery(Query.builder() .table(SearchTagTable.TABLE) .where("${SearchTagTable.COL_MANGA_ID} = ?") .whereArgs(mangaId) .build()) .prepare() fun deleteSearchTagsForManga(mangaId: Long) = db.delete() .byQuery(DeleteQuery.builder() .table(SearchTagTable.TABLE) .where("${SearchTagTable.COL_MANGA_ID} = ?") .whereArgs(mangaId) .build()) .prepare() fun insertSearchTag(searchTag: SearchTag) = db.put().`object`(searchTag).prepare() fun insertSearchTags(searchTags: List<SearchTag>) = db.put().objects(searchTags).prepare() fun deleteSearchTag(searchTag: SearchTag) = db.delete().`object`(searchTag).prepare() fun deleteAllSearchTags() = db.delete().byQuery(DeleteQuery.builder() .table(SearchTagTable.TABLE) .build()) .prepare() fun setSearchTagsForManga(mangaId: Long, tags: List<SearchTag>) { db.inTransaction { deleteSearchTagsForManga(mangaId).executeAsBlocking() tags.chunked(100) { chunk -> insertSearchTags(chunk).executeAsBlocking() } } } }
apache-2.0
721087f5337e2576d01208072a79b93b
36.893617
94
0.627528
4.69657
false
false
false
false
agrawalsuneet/DotsLoader
dotsloader/src/main/java/com/agrawalsuneet/dotsloader/loaders/SlidingLoader.kt
1
5941
package com.agrawalsuneet.dotsloader.loaders import android.content.Context import android.os.Handler import android.util.AttributeSet import android.view.ViewTreeObserver import android.view.animation.* import android.widget.LinearLayout import com.agrawalsuneet.dotsloader.R import com.agrawalsuneet.dotsloader.basicviews.CircleView import com.agrawalsuneet.dotsloader.basicviews.ThreeDotsBaseView /** * Created by suneet on 12/13/17. */ class SlidingLoader : ThreeDotsBaseView { override var animDuration: Int = 500 set(value) { field = value firstDelayDuration = value / 10 secondDelayDuration = value / 5 } override var interpolator: Interpolator = AnticipateOvershootInterpolator() set(value) { field = AnticipateOvershootInterpolator() } var distanceToMove: Int = 12 set(value) { field = value invalidate() } private var firstDelayDuration: Int = 0 private var secondDelayDuration: Int = 0 constructor(context: Context, dotsRadius: Int, dotsDist: Int, firstDotColor: Int, secondDotColor: Int, thirdDotColor: Int) : super(context, dotsRadius, dotsDist, firstDotColor, secondDotColor, thirdDotColor) { initView() } constructor(context: Context?) : super(context) { initView() } constructor(context: Context?, attrs: AttributeSet) : super(context, attrs) { initAttributes(attrs) initView() } constructor(context: Context?, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { initAttributes(attrs) initView() } override fun initAttributes(attrs: AttributeSet) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SlidingLoader, 0, 0) this.dotsRadius = typedArray.getDimensionPixelSize(R.styleable.SlidingLoader_slidingloader_dotsRadius, 30) this.dotsDist = typedArray.getDimensionPixelSize(R.styleable.SlidingLoader_slidingloader_dotsDist, 15) this.firstDotColor = typedArray.getColor(R.styleable.SlidingLoader_slidingloader_firstDotColor, resources.getColor(R.color.loader_selected)) this.secondDotColor = typedArray.getColor(R.styleable.SlidingLoader_slidingloader_secondDotColor, resources.getColor(R.color.loader_selected)) this.thirdDotColor = typedArray.getColor(R.styleable.SlidingLoader_slidingloader_thirdDotColor, resources.getColor(R.color.loader_selected)) this.animDuration = typedArray.getInt(R.styleable.SlidingLoader_slidingloader_animDur, 500) this.distanceToMove = typedArray.getInteger(R.styleable.SlidingLoader_slidingloader_distanceToMove, 12) typedArray.recycle() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val calWidth = (10 * dotsRadius) + (distanceToMove * dotsRadius) + (2 * dotsDist) val calHeight = 2 * dotsRadius setMeasuredDimension(calWidth, calHeight) } override fun initView() { removeAllViews() removeAllViewsInLayout() firstCircle = CircleView(context, dotsRadius, firstDotColor) secondCircle = CircleView(context, dotsRadius, secondDotColor) thirdCircle = CircleView(context, dotsRadius, thirdDotColor) val paramsFirstCircle = LinearLayout.LayoutParams((2 * dotsRadius), 2 * dotsRadius) paramsFirstCircle.leftMargin = (2 * dotsRadius) val paramsSecondCircle = LinearLayout.LayoutParams((2 * dotsRadius), 2 * dotsRadius) paramsSecondCircle.leftMargin = dotsDist val paramsThirdCircle = LinearLayout.LayoutParams((2 * dotsRadius), 2 * dotsRadius) paramsThirdCircle.leftMargin = dotsDist paramsThirdCircle.rightMargin = (2 * dotsRadius) addView(firstCircle, paramsFirstCircle) addView(secondCircle, paramsSecondCircle) addView(thirdCircle, paramsThirdCircle) val loaderView = this viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { startLoading(true) val vto = loaderView.viewTreeObserver vto.removeOnGlobalLayoutListener(this) } }) } private fun startLoading(isForwardDir: Boolean) { val trans1Anim = getTranslateAnim(isForwardDir) if (isForwardDir) thirdCircle.startAnimation(trans1Anim) else firstCircle.startAnimation(trans1Anim) val trans2Anim = getTranslateAnim(isForwardDir) Handler().postDelayed({ secondCircle.startAnimation(trans2Anim) }, firstDelayDuration.toLong()) val trans3Anim = getTranslateAnim(isForwardDir) Handler().postDelayed({ if (isForwardDir) firstCircle.startAnimation(trans3Anim) else thirdCircle.startAnimation(trans3Anim) }, secondDelayDuration.toLong()) trans3Anim.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationRepeat(animation: Animation?) { } override fun onAnimationEnd(animation: Animation?) { startLoading(!isForwardDir) } override fun onAnimationStart(animation: Animation) { } }) } private fun getTranslateAnim(isForwardDir: Boolean): TranslateAnimation { val transAnim = TranslateAnimation(if (isForwardDir) 0f else (distanceToMove * dotsRadius).toFloat(), if (isForwardDir) (distanceToMove * dotsRadius).toFloat() else 0f, 0f, 0f) transAnim.duration = animDuration.toLong() transAnim.fillAfter = true transAnim.interpolator = interpolator return transAnim } }
apache-2.0
03e1f0c33b3d321c5aa6c864585cc088
34.580838
114
0.686585
5.229754
false
false
false
false
andrewoma/kwery
mapper/src/test/kotlin/com/github/andrewoma/kwery/mappertest/example/test/FilmDaoTest.kt
1
7855
/* * Copyright (c) 2015 Andrew O'Malley * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.andrewoma.kwery.mappertest.example.test import com.github.andrewoma.kwery.fetcher.GraphFetcher import com.github.andrewoma.kwery.fetcher.Node import com.github.andrewoma.kwery.fetcher.node import com.github.andrewoma.kwery.mappertest.example.* import org.junit.Test import java.time.Duration import java.time.LocalDateTime import kotlin.comparisons.compareBy import kotlin.properties.Delegates import kotlin.test.* class FilmDaoTest : AbstractFilmDaoTest<Film, Int, FilmDao>() { var graphFetcher: GraphFetcher by Delegates.notNull() var filmActorDao: FilmActorDao by Delegates.notNull() override var dao: FilmDao by Delegates.notNull() override fun afterSessionSetup() { dao = FilmDao(session) filmActorDao = FilmActorDao(session) graphFetcher = createFilmFetcher(session) super.afterSessionSetup() } override val data by lazy { listOf( Film(-1, "Underworld", 2003, sd.languageEnglish, null, Duration.ofMinutes(121), FilmRating.NC_17, LocalDateTime.now(), listOf("Commentaries", "Behind the Scenes")), Film(-1, "Underworld: Evolution", 2006, sd.languageEnglish, null, Duration.ofMinutes(106), FilmRating.R, LocalDateTime.now(), listOf("Behind the Scenes")), Film(-1, "Underworld: Rise of the Lycans", 2006, sd.languageEnglish, sd.languageSpanish, Duration.ofMinutes(92), FilmRating.R, LocalDateTime.now(), listOf()) ) } override fun mutateContents(t: Film) = t.copy( title = "Resident Evil", language = sd.languageSpanish, originalLanguage = sd.languageEnglish, duration = Duration.ofMinutes(10), rating = FilmRating.G ) override fun contentsEqual(t1: Film, t2: Film) = t1.title == t2.title && t1.language.id == t2.language.id && t1.originalLanguage?.id == t2.originalLanguage?.id && t1.duration == t2.duration && t1.rating == t2.rating @Test fun `findWithActors should fetch actors via a join`() { val film = insertAll().first() val actors = listOf(sd.actorKate, sd.actorBrad) for (actor in actors) { filmActorDao.insert(FilmActor(FilmActor.Id(film.id, actor.id), LocalDateTime.now())) } val found = dao.findWithActors(film.title, film.releaseYear)!! assertEquals(actors.toSet(), found.actors) } @Test fun `findWithLanguages should fetch actors via a join`() { val films = insertAll() dao.findWithLanguages(films[0].title, films[0].releaseYear)!!.let { film -> assertEquals(film.language, sd.languageEnglish) assertNull(film.originalLanguage) } dao.findWithLanguages(films[2].title, films[2].releaseYear)!!.let { film -> assertEquals(film.language, sd.languageEnglish) assertEquals(film.originalLanguage, sd.languageSpanish) } } @Test fun `findAllTitlesAndReleaseYears should return partial data`() { insertAll() val films = dao.findAllTitlesAndReleaseYears() assertTrue(films.map { it.title }.toSet().contains("Underworld")) assertTrue(films.map { it.releaseYear }.toSet().contains(2006)) assertFalse(films.map { it.rating }.toSet().contains(FilmRating.R)) } fun <T> Collection<T>.fetch(node: Node) = graphFetcher.fetch(this, node) @Test fun `find by graph fetcher`() { val films = insertAll() val ids = films.map { it.id } val actors = listOf(sd.actorKate, sd.actorBrad) for (film in films) { for (actor in actors) { filmActorDao.insert(FilmActor(FilmActor.Id(film.id, actor.id), LocalDateTime.now())) } } // Check to see actors and language are populated var fetched = dao.findByIds(ids).values.fetch(Node(Node.all)) assertEquals(films.size, fetched.size) for (film in fetched) { assertEquals(2, film.actors.size) assertEquals(sd.languageEnglish.name, film.language.name) if (film.title == "Underworld: Rise of the Lycans") { assertEquals(sd.languageSpanish, film.originalLanguage) } else { assertNull(film.originalLanguage) } } // Check to see only the language is populate fetched = dao.findByIds(ids).values.fetch(Node(Film::language.node())) assertEquals(films.size, fetched.size) for (film in fetched) { assertEquals(0, film.actors.size) assertEquals(sd.languageEnglish.name, film.language.name) } } @Test fun `findByCriteria should filter films`() { val inserted = insertAll() for ((index, film) in inserted.withIndex()) { val actorId = if (index % 2 == 0) sd.actorBrad.id else sd.actorKate.id filmActorDao.insert(FilmActor(FilmActor.Id(film.id, actorId), LocalDateTime.now())) } val data = dao.findAll().sortedWith(compareBy(Film::title, Film::releaseYear)).fetch(Node(Node.all)) fun assert(criteria: FilmCriteria, expected: List<Film>) { if (criteria != FilmCriteria()) { assertNotEquals(data.size, expected.size, "Invalid filter - no values filtered") } assertNotEquals(0, expected.size, "Invalid filter - all values filtered") assertEquals(expected.map(Film::id), dao.findByCriteria(criteria).map(Film::id)) } fun assert(criteria: FilmCriteria, filter: (FilmCriteria, Film) -> Boolean) = assert(criteria, data.filter { filter(criteria, it) }) assert(FilmCriteria()) { _, _ -> true } // Default criteria should select everything // Individual criteria assert(FilmCriteria(releaseYear = 2003)) { c, f -> f.releaseYear == c.releaseYear } assert(FilmCriteria(title = "lycans")) { c, f -> f.title.toLowerCase().contains(c.title!!.toLowerCase()) } assert(FilmCriteria(maxDuration = Duration.ofHours(2))) { c, f -> f.duration == null || f.duration <= c.maxDuration } assert(FilmCriteria(limit = 2, offset = 1), data.drop(1).take(2)) assert(FilmCriteria(actor = sd.actorKate)) { c, f -> c.actor in f.actors} assert(FilmCriteria(ratings = setOf(FilmRating.R, FilmRating.G))) { c, f -> f.rating in c.ratings} // Combinations assert(FilmCriteria(ratings = setOf(FilmRating.R), maxDuration = Duration.ofHours(1).plusMinutes(32))) { c, f -> f.rating in c.ratings && f.duration != null && f.duration <= c.maxDuration } } }
mit
a9dae174555f4f7e2bddddaf991755fb
43.129213
142
0.650414
4.342178
false
true
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/presentation/more/settings/PreferenceScreen.kt
1
3569
package eu.kanade.presentation.more.settings import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.util.fastForEachIndexed import eu.kanade.presentation.components.ScrollbarLazyColumn import eu.kanade.presentation.more.settings.screen.SearchableSettings import eu.kanade.presentation.more.settings.widget.PreferenceGroupHeader import kotlinx.coroutines.delay import kotlin.time.Duration.Companion.seconds /** * Preference Screen composable which contains a list of [Preference] items * @param items [Preference] items which should be displayed on the preference screen. An item can be a single [PreferenceItem] or a group ([Preference.PreferenceGroup]) * @param modifier [Modifier] to be applied to the preferenceScreen layout */ @Composable fun PreferenceScreen( items: List<Preference>, modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues(0.dp), ) { val state = rememberLazyListState() val highlightKey = SearchableSettings.highlightKey if (highlightKey != null) { LaunchedEffect(Unit) { val i = items.findHighlightedIndex(highlightKey) if (i >= 0) { delay(0.5.seconds) state.animateScrollToItem(i) } SearchableSettings.highlightKey = null } } ScrollbarLazyColumn( modifier = modifier, state = state, contentPadding = contentPadding, ) { items.fastForEachIndexed { i, preference -> when (preference) { // Create Preference Group is Preference.PreferenceGroup -> { if (!preference.enabled) return@fastForEachIndexed item { Column { PreferenceGroupHeader(title = preference.title) } } items(preference.preferenceItems) { item -> PreferenceItem( item = item, highlightKey = highlightKey, ) } item { if (i < items.lastIndex) { Spacer(modifier = Modifier.height(12.dp)) } } } // Create Preference Item is Preference.PreferenceItem<*> -> item { PreferenceItem( item = preference, highlightKey = highlightKey, ) } } } } } private fun List<Preference>.findHighlightedIndex(highlightKey: String): Int { return flatMap { if (it is Preference.PreferenceGroup) { mutableListOf<String?>() .apply { add(null) // Header addAll(it.preferenceItems.map { groupItem -> groupItem.title }) add(null) // Spacer } } else { listOf(it.title) } }.indexOfFirst { it == highlightKey } }
apache-2.0
7169c12eb0696304e7f6980ece0679d4
35.418367
169
0.586719
5.490769
false
false
false
false
hotpodata/common
src/main/java/com/hotpodata/common/view/CircleImageView.kt
1
3947
package com.hotpodata.common.view import android.annotation.TargetApi import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Path import android.os.Build import android.util.AttributeSet import android.view.View import android.widget.ImageView import com.hotpodata.common.R /** * Created by jdrotos on 7/30/14. */ class CircleImageView : ImageView { private var mCircleBgColor = Color.TRANSPARENT private var mCircleBorderColor = Color.TRANSPARENT private var mCircleBorderWidth = 2 private val mBgPaint = Paint() private val mBorderPaint = Paint() constructor(context: Context) : super(context) { init(context, null) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(context, attrs) } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { init(context, attrs) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { init(context, attrs) } private fun init(context: Context, attrs: AttributeSet?) { if (attrs != null) { val a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView) if (a != null) { if (a.hasValue(R.styleable.CircleImageView_circleBackgroundColor)) { mCircleBgColor = a.getColor(R.styleable.CircleImageView_circleBackgroundColor, mCircleBgColor) } if (a.hasValue(R.styleable.CircleImageView_circleBorderColor)) { mCircleBorderColor = a.getColor(R.styleable.CircleImageView_circleBorderColor, mCircleBorderColor) } if (a.hasValue(R.styleable.CircleImageView_circleBorderWidth)) { mCircleBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_circleBorderWidth, mCircleBorderWidth) } a.recycle() } } updatePaints() //clipPath does not work if we are working in the hardware layer if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { setLayerType(View.LAYER_TYPE_NONE, null) } else { setLayerType(View.LAYER_TYPE_SOFTWARE, null) } } private fun updatePaints() { //the circle background mBgPaint.isAntiAlias = true mBgPaint.color = mCircleBgColor mBgPaint.style = Paint.Style.FILL //circle border mBorderPaint.isAntiAlias = true mBorderPaint.color = mCircleBorderColor mBorderPaint.strokeWidth = mCircleBorderWidth.toFloat() mBorderPaint.style = Paint.Style.STROKE } fun setCircleBgColor(color: Int) { mCircleBgColor = color updatePaints() } fun setCircleBorderColor(color: Int) { mCircleBorderColor = color updatePaints() } fun setCircleBorderWidth(width: Int) { mCircleBorderWidth = width updatePaints() } override fun onDraw(canvas: Canvas) { val w = width val h = height val circle = Path() circle.addCircle(w / 2f, h / 2f, Math.min(w, h) / 2f, Path.Direction.CW) if (mCircleBgColor != Color.TRANSPARENT) { canvas.drawPath(circle, mBgPaint) } if (mCircleBorderColor != Color.TRANSPARENT && mCircleBorderWidth > 0) { val borderCirclePath = Path() val hsw = mCircleBorderWidth / 2f borderCirclePath.addCircle(w / 2f, h / 2f, (Math.min(w, h) / 2f) - hsw, Path.Direction.CW) canvas.drawPath(borderCirclePath, mBorderPaint) } canvas.clipPath(circle) super.onDraw(canvas) } }
apache-2.0
0b870d56538b3597727d531b64d5c2a1
31.619835
144
0.64226
4.67654
false
false
false
false
exponentjs/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/medialibrary/GetAlbums.kt
2
2494
package abi43_0_0.expo.modules.medialibrary import android.content.Context import android.database.Cursor.FIELD_TYPE_NULL import android.os.AsyncTask import android.os.Bundle import android.provider.MediaStore import android.provider.MediaStore.Images.Media import abi43_0_0.expo.modules.core.Promise internal open class GetAlbums(private val mContext: Context, private val mPromise: Promise) : AsyncTask<Void?, Void?, Void?>() { override fun doInBackground(vararg params: Void?): Void? { val projection = arrayOf(Media.BUCKET_ID, Media.BUCKET_DISPLAY_NAME) val selection = "${MediaStore.Files.FileColumns.MEDIA_TYPE} != ${MediaStore.Files.FileColumns.MEDIA_TYPE_NONE}" val albums = HashMap<String, Album>() try { mContext.contentResolver .query( MediaLibraryConstants.EXTERNAL_CONTENT, projection, selection, null, Media.BUCKET_DISPLAY_NAME ) .use { asset -> if (asset == null) { mPromise.reject( MediaLibraryConstants.ERROR_UNABLE_TO_LOAD, "Could not get albums. Query returns null." ) return@use } val bucketIdIndex = asset.getColumnIndex(Media.BUCKET_ID) val bucketDisplayNameIndex = asset.getColumnIndex(Media.BUCKET_DISPLAY_NAME) while (asset.moveToNext()) { val id = asset.getString(bucketIdIndex) if (asset.getType(bucketDisplayNameIndex) == FIELD_TYPE_NULL) { continue } val album = albums[id] ?: Album( id = id, title = asset.getString(bucketDisplayNameIndex) ).also { albums[id] = it } album.count++ } mPromise.resolve(albums.values.map { it.toBundle() }) } } catch (e: SecurityException) { mPromise.reject( MediaLibraryConstants.ERROR_UNABLE_TO_LOAD_PERMISSION, "Could not get albums: need READ_EXTERNAL_STORAGE permission.", e ) } catch (e: RuntimeException) { mPromise.reject(MediaLibraryConstants.ERROR_UNABLE_TO_LOAD, "Could not get albums.", e) } return null } private class Album(private val id: String, private val title: String, var count: Int = 0) { fun toBundle() = Bundle().apply { putString("id", id) putString("title", title) putParcelable("type", null) putInt("assetCount", count) } } }
bsd-3-clause
d7f79f6ef9fa095c513ba8fcad33c2e8
30.974359
115
0.620289
4.352531
false
false
false
false
esqr/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/buttons/vote/base/BaseVoteButton.kt
1
1755
package io.github.feelfreelinux.wykopmobilny.ui.widgets.buttons.vote.base import android.content.Context import android.util.AttributeSet import android.util.TypedValue import android.widget.TextView import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.WykopApp import io.github.feelfreelinux.wykopmobilny.ui.dialogs.showExceptionDialog import io.github.feelfreelinux.wykopmobilny.utils.getActivityContext import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi import javax.inject.Inject @Suppress("LeakingThis") abstract class BaseVoteButton : TextView { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs, R.attr.MirkoButtonStyle) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) @Inject lateinit var userManager : UserManagerApi abstract fun vote() abstract fun unvote() init { WykopApp.uiInjector.inject(this) val typedValue = TypedValue() getActivityContext()!!.theme?.resolveAttribute(R.attr.voteButtonStatelist, typedValue, true) setBackgroundResource(typedValue.resourceId) setOnClickListener { userManager.runIfLoggedIn(context) { if (isSelected) unvote() else vote() } } } var voteCount : Int get() = text.toString().toInt() set(value) { text = context.getString(R.string.votes_count, value) } var isButtonSelected: Boolean get() = isSelected set(value) { isSelected = value } fun showErrorDialog(e : Throwable) = context.showExceptionDialog(e) }
mit
5fe6253051436335adf7ff85963fbe21
33.431373
111
0.719658
4.743243
false
false
false
false
PolymerLabs/arcs
java/arcs/core/storage/keys/VolatileStorageKey.kt
1
2033
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.storage.keys import arcs.core.common.ArcId import arcs.core.common.toArcId import arcs.core.data.Capabilities import arcs.core.data.Capability import arcs.core.storage.StorageKey import arcs.core.storage.StorageKeyFactory import arcs.core.storage.StorageKeyProtocol import arcs.core.storage.StorageKeySpec /** Protocol to be used with the volatile driver. */ /** Storage key for a piece of data kept in the volatile driver. */ data class VolatileStorageKey( /** Id of the arc where this key was created. */ val arcId: ArcId, /** Unique identifier for this particular key. */ val unique: String ) : StorageKey(protocol) { override fun toKeyString(): String = "$arcId/$unique" override fun newKeyWithComponent(component: String): StorageKey { return VolatileStorageKey(arcId, component) } override fun toString(): String = super.toString() class VolatileStorageKeyFactory : StorageKeyFactory( protocol, Capabilities( listOf( Capability.Persistence.IN_MEMORY, Capability.Shareable(false) ) ) ) { override fun create(options: StorageKeyOptions): StorageKey { return VolatileStorageKey(options.arcId, options.unique) } } companion object : StorageKeySpec<VolatileStorageKey> { private val VOLATILE_STORAGE_KEY_PATTERN = "^([^/]+)/(.*)\$".toRegex() override val protocol = StorageKeyProtocol.Volatile override fun parse(rawKeyString: String): VolatileStorageKey { val match = requireNotNull(VOLATILE_STORAGE_KEY_PATTERN.matchEntire(rawKeyString)) { "Not a valid VolatileStorageKey" } return VolatileStorageKey(match.groupValues[1].toArcId(), match.groupValues[2]) } } }
bsd-3-clause
f43cae5f46f44b440903229051d3f149
30.276923
96
0.722577
4.409978
false
false
false
false
ThoseGrapefruits/intellij-rust
src/test/kotlin/org/rust/lang/core/lexer/RustLexingTestCase.kt
1
1858
package org.rust.lang.core.lexer import com.intellij.lexer.Lexer import com.intellij.openapi.application.PathManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.testFramework.LexerTestCase import java.io.File import java.io.IOException import java.nio.file.Paths public class RustLexingTestCase : LexerTestCase() { override fun getDirPath(): String { val home = Paths.get(PathManager.getHomePath()).toAbsolutePath() val testData = Paths.get("src", "test", "resources", "org", "rust", "lang", "core", "lexer", "fixtures").toAbsolutePath() // XXX: unfortunately doFileTest will look for the file relative to the home directory of // the test instance of IDEA, so let's cook a dirPath starting with several ../../ return home.relativize(testData).toString() } override fun createLexer(): Lexer? = RustLexer() // NOTE(matkad): this is basically a copy-paste of doFileTest. // The only difference is that encoding is set to utf-8 fun doTest() { val fileName = PathManager.getHomePath() + "/" + dirPath + "/" + getTestName(true) + ".rs" var text = "" try { val fileText = FileUtil.loadFile(File(fileName), CharsetToolkit.UTF8); text = StringUtil.convertLineSeparators(if (shouldTrim()) fileText.trim() else fileText); } catch (e: IOException) { fail("can't load file " + fileName + ": " + e.message); } doTest(text); } fun testComments() = doTest() fun testShebang() = doTest() fun testFloat() = doTest() fun testIdentifiers() = doTest() fun testCharLiterals() = doTest() fun testStringLiterals() = doTest() fun testByteLiterals() = doTest() }
mit
119ec00c6773c35c9e1aaeb3677e842f
37.708333
101
0.665231
4.331002
false
true
false
false
elsiff/MoreFish
src/main/kotlin/me/elsiff/morefish/fishing/catchhandler/CatchFireworkSpawner.kt
1
868
package me.elsiff.morefish.fishing.catchhandler import me.elsiff.morefish.fishing.Fish import org.bukkit.Color import org.bukkit.FireworkEffect import org.bukkit.entity.Firework import org.bukkit.entity.Player /** * Created by elsiff on 2019-01-15. */ class CatchFireworkSpawner : CatchHandler { private val effect = FireworkEffect.builder() .with(FireworkEffect.Type.BALL_LARGE) .withColor(Color.AQUA) .withFade(Color.BLUE) .withTrail() .withFlicker() .build() override fun handle(catcher: Player, fish: Fish) { if (fish.type.hasCatchFirework) { val firework = catcher.world.spawn(catcher.location, Firework::class.java) val meta = firework.fireworkMeta meta.addEffect(effect) meta.power = 1 firework.fireworkMeta = meta } } }
mit
0c16884462f044442a656ed649cfd8a6
27.966667
86
0.66129
3.823789
false
false
false
false
Hexworks/zircon
zircon.jvm.examples/src/main/kotlin/org/hexworks/zircon/examples/fragments/TableWithSelectionExample.kt
1
6164
package org.hexworks.zircon.examples.fragments import org.hexworks.cobalt.databinding.api.binding.bindTransform import org.hexworks.cobalt.databinding.api.collection.ListProperty import org.hexworks.cobalt.databinding.api.extension.toProperty import org.hexworks.cobalt.databinding.api.value.ObservableValue import org.hexworks.zircon.api.ComponentDecorations.box import org.hexworks.zircon.api.component.HBox import org.hexworks.zircon.api.component.VBox import org.hexworks.zircon.api.component.renderer.ComponentRenderer import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.data.Tile import org.hexworks.zircon.api.dsl.component.* import org.hexworks.zircon.api.dsl.fragment.buildTable import org.hexworks.zircon.api.fragment.Table import org.hexworks.zircon.examples.base.OneColumnComponentExampleKotlin import org.hexworks.zircon.examples.fragments.table.* import org.hexworks.zircon.examples.fragments.table.randomWage class TableWithSelectionExample : OneColumnComponentExampleKotlin() { companion object { @JvmStatic fun main(args: Array<String>) { TableWithSelectionExample().show("Table with selection") } } override fun build(box: VBox) { val persons = 15.randomPersons().toProperty() val tableWidth = box.width / 3 * 2 val panelWidth = box.width / 3 val tableFragment = buildTable<Person> { // TODO: Use an observable list and add UI elements to add/remove elements data = persons height = box.height selectedRowRenderer = ComponentRenderer { tileGraphics, context -> val style = context.currentStyle tileGraphics.fill(Tile.defaultTile()) tileGraphics.applyStyle(style.withBackgroundColor(context.theme.accentColor)) } textColumn { name = "First name" width = 14 valueProvider = Person::firstName } textColumn { name = "Last name" width = 14 valueProvider = Person::lastName } numberColumn { name = "Age" width = 3 valueProvider = Person::age } iconColumn { name = "Height" valueProvider = Person::heightIcon } observableTextColumn { name = "Wage" width = 8 valueProvider = Person::formattedWage } } val selectionPanel = buildSelectionPanel(persons, tableFragment, panelWidth) box.addComponent(buildHbox { preferredSize = box.contentSize withChildren(buildPanel { preferredSize = Size.create(tableWidth, box.height) withChildren(tableFragment.root) }, selectionPanel) }) } /** * Builds the right panel displaying the currently selected person. */ private fun buildSelectionPanel( persons: ListProperty<Person>, tableFragment: Table<Person>, width: Int ) = buildVbox { preferredSize = Size.create(width, tableFragment.size.height) spacing = 1 decoration = box() val panelContentSize = contentSize val personValue = tableFragment .selectedRowsValue .bindTransform { it.firstOrNull() ?: Person( "None", "Selected", 0, Height.SHORT, 50000.toProperty() ) } header { text = "Selected person:" } withChildren( personValue.asLabel(contentSize.width, Person::firstName), personValue.asLabel(contentSize.width, Person::lastName), heightPanel(contentSize.width, personValue), ) label { preferredSize = Size.create(contentSize.width, 1) textProperty.updateFrom(personValue.value.formattedWage) } button { +"shuffle" onActivated { val newWage = randomWage() personValue.value.wage.updateValue(newWage) } } horizontalNumberInput { preferredSize = Size.create(contentSize.width, 1) maxValue = Person.MAX_WAGE minValue = Person.MIN_WAGE }.apply { currentValue = personValue.value.wage.value currentValueProperty.bindTransform { personValue.value.wage.updateValue(it) } } button { preferredSize = contentSize.withHeight(1) textProperty.updateFrom(personValue.bindTransform { "Delete ${it.firstName} ${it.lastName}" }) onActivated { persons.remove(personValue.value) } } hbox { spacing = 1 preferredSize = panelContentSize.withHeight(1) button { +"+" onActivated { persons.add(randomPerson()) } } label { +"random Person" } button { +"-" onActivated { if (persons.isNotEmpty()) { persons.removeAt(persons.lastIndex) } } } } } private fun heightPanel(width: Int, person: ObservableValue<Person>): HBox = buildHbox { spacing = 1 preferredSize = Size.create(width, 1) icon { iconProperty.updateFrom(person.bindTransform { it.heightIcon }) } label { preferredSize = Size.create(width - 2, 1) textProperty.updateFrom(person.bindTransform { it.height.name }) } } private fun <T : Any> ObservableValue<T>.asLabel(width: Int, labelText: T.() -> String) = buildLabel { preferredSize = Size.create(width, 1) textProperty.updateFrom(bindTransform(labelText), true) } }
apache-2.0
f99fe363575af9570f06c3baf21a4712
29.974874
106
0.571869
5.201688
false
false
false
false
hpost/kommon
app/src/main/java/cc/femto/kommon/ui/recyclerview/MarginDecoration.kt
1
1000
package cc.femto.kommon.ui.recyclerview import android.graphics.Rect import android.support.v7.widget.RecyclerView import android.view.View open class MarginDecoration : RecyclerView.ItemDecoration { private var margin = -1 private var marginLeft: Int = 0 private var marginTop: Int = 0 private var marginRight: Int = 0 private var marginBottom: Int = 0 constructor(margin: Int) { this.margin = margin } constructor(marginLeft: Int, marginTop: Int, marginRight: Int, marginBottom: Int) { this.marginLeft = marginLeft this.marginTop = marginTop this.marginRight = marginRight this.marginBottom = marginBottom } override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) { if (margin != -1) { outRect.set(margin, margin, margin, margin) } else { outRect.set(marginLeft, marginTop, marginRight, marginBottom) } } }
apache-2.0
fef68bd25445cec962724035c59969d8
26.027027
110
0.67
4.524887
false
false
false
false
JoeSteven/HuaBan
app/src/main/java/com/joe/zatuji/module/login/LoginActivity.kt
1
1423
package com.joe.zatuji.module.login import android.os.Bundle import com.joe.zatuji.R import com.joe.zatuji.base.BaseFragmentActivity import com.joe.zatuji.event.LoginSuccessEvent import com.joe.zatuji.module.login.login.LoginFragment import com.joe.zatuji.module.login.register.RegisterFragment import com.joey.cheetah.core.async.RxJavaManager /** * Description: * author:Joey * date:2018/11/20 */ class LoginActivity: BaseFragmentActivity() { private val tagLogin = "login" private val tagRegister = "register" private lateinit var loginFragment:LoginFragment private lateinit var registerFragment:RegisterFragment override fun createFragment() { loginFragment = LoginFragment() registerFragment = RegisterFragment() } override fun restoreFragment(p0: Bundle?) { loginFragment = fragmentManager.findFragmentByTag(tagLogin) as LoginFragment? ?: LoginFragment() registerFragment = fragmentManager.findFragmentByTag(tagRegister) as RegisterFragment? ?: RegisterFragment() } override fun attachFragment() { addFragment(loginFragment, R.id.fl_container_login,tagLogin) } fun toRegister() { addFragmentToStack(registerFragment, R.id.fl_container_login, tagRegister) } override fun initLayout(): Int { return R.layout.activity_login } override fun initView() {} override fun initPresenter() {} }
apache-2.0
2ca3e5b8dd002f1165ebabf30a565840
28.666667
116
0.736472
4.488959
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stories/StoriesMediaPickerResultHandler.kt
1
4723
package org.wordpress.android.ui.stories import android.app.Activity import android.content.Intent import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.ui.ActivityLauncher import org.wordpress.android.ui.PagePostCreationSourcesDetail import org.wordpress.android.ui.media.MediaBrowserActivity import org.wordpress.android.ui.media.MediaBrowserType import org.wordpress.android.ui.mysite.SiteNavigationAction import org.wordpress.android.ui.mysite.SiteNavigationAction.AddNewStory import org.wordpress.android.ui.mysite.SiteNavigationAction.AddNewStoryWithMediaIds import org.wordpress.android.ui.mysite.SiteNavigationAction.AddNewStoryWithMediaUris import org.wordpress.android.ui.photopicker.MediaPickerConstants import org.wordpress.android.util.AppLog import org.wordpress.android.util.AppLog.T.UTILS import org.wordpress.android.viewmodel.Event import javax.inject.Inject class StoriesMediaPickerResultHandler @Inject constructor() { private val _onNavigation = MutableLiveData<Event<SiteNavigationAction>>() val onNavigation = _onNavigation as LiveData<Event<SiteNavigationAction>> @Deprecated("Use rather the other handle method and the live data navigation.") fun handleMediaPickerResultForStories( data: Intent, activity: Activity?, selectedSite: SiteModel?, source: PagePostCreationSourcesDetail ): Boolean { if (selectedSite == null) { return false } when (val navigationAction = buildNavigationAction(data, selectedSite, source)) { is AddNewStory -> ActivityLauncher.addNewStoryForResult( activity, navigationAction.site, navigationAction.source ) is AddNewStoryWithMediaIds -> ActivityLauncher.addNewStoryWithMediaIdsForResult( activity, navigationAction.site, navigationAction.source, navigationAction.mediaIds.toLongArray() ) is AddNewStoryWithMediaUris -> ActivityLauncher.addNewStoryWithMediaUrisForResult( activity, navigationAction.site, navigationAction.source, navigationAction.mediaUris.toTypedArray() ) else -> { return false } } return true } fun handleMediaPickerResultForStories( data: Intent, selectedSite: SiteModel, source: PagePostCreationSourcesDetail ): Boolean { val navigationAction = buildNavigationAction(data, selectedSite, source) return if (navigationAction != null) { _onNavigation.postValue(Event(navigationAction)) true } else { false } } private fun buildNavigationAction( data: Intent, selectedSite: SiteModel, source: PagePostCreationSourcesDetail ): SiteNavigationAction? { if (data.getBooleanExtra(MediaPickerConstants.EXTRA_LAUNCH_WPSTORIES_CAMERA_REQUESTED, false)) { return AddNewStory(selectedSite, source) } else if (isWPStoriesMediaBrowserTypeResult(data)) { if (data.hasExtra(MediaBrowserActivity.RESULT_IDS)) { val mediaIds = data.getLongArrayExtra(MediaBrowserActivity.RESULT_IDS)?.asList() ?: listOf() return AddNewStoryWithMediaIds(selectedSite, source, mediaIds) } else { val mediaUriStringsArray = data.getStringArrayExtra( MediaPickerConstants.EXTRA_MEDIA_URIS ) if (mediaUriStringsArray.isNullOrEmpty()) { AppLog.e( UTILS, "Can't resolve picked or captured image" ) return null } val mediaUris = mediaUriStringsArray.asList() return AddNewStoryWithMediaUris( selectedSite, source, mediaUris = mediaUris ) } } return null } private fun isWPStoriesMediaBrowserTypeResult(data: Intent): Boolean { if (data.hasExtra(MediaBrowserActivity.ARG_BROWSER_TYPE)) { val browserType = data.getSerializableExtra(MediaBrowserActivity.ARG_BROWSER_TYPE) return (browserType as MediaBrowserType).isWPStoriesPicker } return false } }
gpl-2.0
8203a7084bb6ad9922fc50af9da0f318
39.367521
108
0.634766
5.752741
false
false
false
false
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/widgets/UpdateWidgets.kt
1
2050
package com.kelsos.mbrc.widgets import android.appwidget.AppWidgetManager import android.content.Context import android.content.Intent import com.kelsos.mbrc.annotations.PlayerState.State import com.kelsos.mbrc.domain.TrackInfo object UpdateWidgets { const val COVER = "com.kelsos.mbrc.widgets.COVER" const val COVER_PATH = "com.kelsos.mbrc.widgets.COVER_PATH" const val STATE = "com.kelsos.mbrc.widgets.STATE" const val INFO = "com.kelsos.mbrc.widgets.INFO" const val TRACK_INFO = "com.kelsos.mbrc.widgets.TRACKINFO" const val PLAYER_STATE = "com.kelsos.mbrc.widgets.PLAYER_STATE" fun updateCover(context: Context, path: String = "") { val normalIntent = getIntent(WidgetNormal::class.java, context) .putExtra(COVER, true) .putExtra(COVER_PATH, path) val smallIntent = getIntent(WidgetSmall::class.java, context) .putExtra(COVER, true) .putExtra(COVER_PATH, path) context.sendBroadcast(smallIntent) context.sendBroadcast(normalIntent) } fun updatePlaystate(context: Context, @State state: String) { val normalIntent = getIntent(WidgetNormal::class.java, context) .putExtra(STATE, true) .putExtra(PLAYER_STATE, state) val smallIntent = getIntent(WidgetSmall::class.java, context) .putExtra(STATE, true) .putExtra(PLAYER_STATE, state) context.sendBroadcast(smallIntent) context.sendBroadcast(normalIntent) } fun updateTrackInfo(context: Context, info: TrackInfo) { val normalIntent = getIntent(WidgetNormal::class.java, context) .putExtra(INFO, true) .putExtra(TRACK_INFO, info) val smallIntent = getIntent(WidgetSmall::class.java, context) .putExtra(INFO, true) .putExtra(TRACK_INFO, info) context.sendBroadcast(smallIntent) context.sendBroadcast(normalIntent) } private fun getIntent(clazz: Class<*>, context: Context): Intent { val widgetUpdateIntent = Intent(context, clazz) widgetUpdateIntent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE return widgetUpdateIntent } }
gpl-3.0
743abaa5557b80a4552e17bec579506e
32.064516
72
0.732683
3.949904
false
false
false
false
hzsweers/CatchUp
libraries/base-ui/src/main/kotlin/io/sweers/catchup/base/ui/widget/BaselineGridTextView.kt
1
6372
/* * Copyright (C) 2019. Zac Sweers * * 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.sweers.catchup.base.ui.widget import android.annotation.SuppressLint import android.content.Context import android.content.res.TypedArray import android.util.AttributeSet import android.util.TypedValue import androidx.annotation.FontRes import androidx.appcompat.widget.AppCompatTextView import androidx.core.content.res.use import catchup.ui.core.R import kotlin.math.abs import kotlin.math.ceil import kotlin.math.floor /** * An extension to [AppCompatTextView] which aligns text to a 4dp baseline grid. * * To achieve this we expose a `lineHeightHint` allowing you to specify the desired line * height (alternatively a `lineHeightMultiplierHint` to use a multiplier of the text size). * This line height will be adjusted to be a multiple of 4dp to ensure that baselines sit on * the grid. * * We also adjust spacing above and below the text to ensure that the first line's baseline sits on * the grid (relative to the view's top) & that this view's height is a multiple of 4dp so that * subsequent views start on the grid. */ @SuppressLint("Recycle") // False positive class BaselineGridTextView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = android.R.attr.textViewStyle ) : AppCompatTextView( context, attrs, defStyleAttr ) { private val fourDip: Float var lineHeightMultiplierHint = 1f set(value) { field = value computeLineHeight() } var lineHeightHint = 0f set(value) { field = value computeLineHeight() } var maxLinesByHeight = false set(value) { field = value requestLayout() } private var extraTopPadding = 0 private var extraBottomPadding = 0 @FontRes var fontResId = 0 private set init { context.obtainStyledAttributes( attrs, R.styleable.BaselineGridTextView, defStyleAttr, 0 ).use { // first check TextAppearance for line height & font attributes if (it.hasValue(R.styleable.BaselineGridTextView_android_textAppearance)) { val textAppearanceId = it.getResourceId( R.styleable.BaselineGridTextView_android_textAppearance, android.R.style.TextAppearance ) context.obtainStyledAttributes( textAppearanceId, R.styleable.BaselineGridTextView ).use { parseTextAttrs(it) } } // then check view attrs parseTextAttrs(it) maxLinesByHeight = it.getBoolean(R.styleable.BaselineGridTextView_maxLinesByHeight, false) } fourDip = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 4f, resources.displayMetrics ) computeLineHeight() } override fun getCompoundPaddingTop(): Int { // include extra padding to place the first line's baseline on the grid return super.getCompoundPaddingTop() + extraTopPadding } override fun getCompoundPaddingBottom(): Int { // include extra padding to make the height a multiple of 4dp return super.getCompoundPaddingBottom() + extraBottomPadding } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { extraTopPadding = 0 extraBottomPadding = 0 super.onMeasure(widthMeasureSpec, heightMeasureSpec) var height = measuredHeight height += ensureBaselineOnGrid() height += ensureHeightGridAligned(height) setMeasuredDimension(measuredWidth, height) checkMaxLines(height, MeasureSpec.getMode(heightMeasureSpec)) } private fun parseTextAttrs(a: TypedArray) { if (a.hasValue(R.styleable.BaselineGridTextView_lineHeightMultiplierHint)) { lineHeightMultiplierHint = a.getFloat( R.styleable.BaselineGridTextView_lineHeightMultiplierHint, 1f ) } if (a.hasValue(R.styleable.BaselineGridTextView_lineHeightHint)) { lineHeightHint = a.getDimensionPixelSize( R.styleable.BaselineGridTextView_lineHeightHint, 0 ).toFloat() } if (a.hasValue(R.styleable.BaselineGridTextView_android_fontFamily)) { fontResId = a.getResourceId(R.styleable.BaselineGridTextView_android_fontFamily, 0) } } /** * Ensures line height is a multiple of 4dp. */ private fun computeLineHeight() { val fm = paint.fontMetrics val fontHeight = abs(fm.ascent - fm.descent) + fm.leading val desiredLineHeight = if (lineHeightHint > 0) lineHeightHint else lineHeightMultiplierHint * fontHeight val baselineAlignedLineHeight = (fourDip * ceil((desiredLineHeight / fourDip).toDouble()).toFloat() + 0.5f).toInt() setLineSpacing(baselineAlignedLineHeight - fontHeight, 1f) } /** * Ensure that the first line of text sits on the 4dp grid. */ private fun ensureBaselineOnGrid(): Int { val baseline = baseline.toFloat() val gridAlign = baseline % fourDip if (gridAlign != 0f) { extraTopPadding = (fourDip - ceil(gridAlign.toDouble())).toInt() } return extraTopPadding } /** * Ensure that height is a multiple of 4dp. */ private fun ensureHeightGridAligned(height: Int): Int { val gridOverhang = height % fourDip if (gridOverhang != 0f) { extraBottomPadding = (fourDip - ceil(gridOverhang.toDouble())).toInt() } return extraBottomPadding } /** * When measured with an exact height, text can be vertically clipped mid-line. Prevent * this by setting the `maxLines` property based on the available space. */ private fun checkMaxLines(height: Int, heightMode: Int) { if (!maxLinesByHeight || heightMode != MeasureSpec.EXACTLY) return val textHeight = height - compoundPaddingTop - compoundPaddingBottom val completeLines = floor((textHeight / lineHeight).toDouble()).toInt() maxLines = completeLines } }
apache-2.0
af932be61b81fa9ffec34d45cead1c94
30.86
119
0.711551
4.567742
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinValueArgumentListFixer.kt
4
1740
// 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.editor.fixers import com.intellij.lang.SmartEnterProcessorWithFixers import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiUtilCore import org.jetbrains.kotlin.idea.editor.KotlinSmartEnterHandler import org.jetbrains.kotlin.psi.KtValueArgumentList import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespace class KotlinValueArgumentListFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() { override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, element: PsiElement) { if (element !is KtValueArgumentList || element.rightParenthesis != null) return val lPar = element.leftParenthesis ?: return val lastArgument = element.arguments.lastOrNull() if (lastArgument != null && PsiUtilCore.hasErrorElementChild(lastArgument)) { val prev = lastArgument.getPrevSiblingIgnoringWhitespace() ?: lPar val offset = prev.endOffset if (prev == lPar) { editor.document.insertString(offset, ")") editor.caretModel.moveToOffset(offset) } else { editor.document.insertString(offset, " )") editor.caretModel.moveToOffset(offset + 1) } } else { val offset = lastArgument?.endOffset ?: element.endOffset editor.document.insertString(offset, ")") editor.caretModel.moveToOffset(offset + 1) } } }
apache-2.0
bbdfdf073de2a03d16704f537025015b
44.815789
158
0.70977
5.072886
false
false
false
false
jk1/intellij-community
platform/diff-impl/tests/com/intellij/diff/merge/MergeTestBase.kt
2
14456
// 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.diff.merge import com.intellij.diff.DiffContentFactoryImpl import com.intellij.diff.HeavyDiffTestCase import com.intellij.diff.contents.DocumentContent import com.intellij.diff.merge.MergeTestBase.SidesState.* import com.intellij.diff.merge.TextMergeViewer.MyThreesideViewer import com.intellij.diff.util.* import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider import com.intellij.openapi.project.Project import com.intellij.openapi.util.Couple import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.text.StringUtil import com.intellij.util.ui.UIUtil abstract class MergeTestBase : HeavyDiffTestCase() { fun test1(left: String, base: String, right: String, f: TestBuilder.() -> Unit) { test(left, base, right, 1, f) } fun test2(left: String, base: String, right: String, f: TestBuilder.() -> Unit) { test(left, base, right, 2, f) } fun testN(left: String, base: String, right: String, f: TestBuilder.() -> Unit) { test(left, base, right, -1, f) } fun test(left: String, base: String, right: String, changesCount: Int, f: TestBuilder.() -> Unit) { val contentFactory = DiffContentFactoryImpl() val leftContent: DocumentContent = contentFactory.create(parseSource(left)) val baseContent: DocumentContent = contentFactory.create(parseSource(base)) val rightContent: DocumentContent = contentFactory.create(parseSource(right)) val outputContent: DocumentContent = contentFactory.create(parseSource("")) outputContent.document.setReadOnly(false) val context = MockMergeContext(project) val request = MockMergeRequest(leftContent, baseContent, rightContent, outputContent) val viewer = TextMergeTool.INSTANCE.createComponent(context, request) as TextMergeViewer try { val toolbar = viewer.init() UIUtil.dispatchAllInvocationEvents() val builder = TestBuilder(viewer, toolbar.toolbarActions ?: emptyList()) builder.assertChangesCount(changesCount) builder.f() } finally { Disposer.dispose(viewer) } } inner class TestBuilder(val mergeViewer: TextMergeViewer, private val actions: List<AnAction>) { val viewer: MyThreesideViewer = mergeViewer.viewer val changes: List<TextMergeChange> = viewer.allChanges val editor: EditorEx = viewer.editor val document: Document = editor.document private val textEditor = TextEditorProvider.getInstance().getTextEditor(editor) private val undoManager = UndoManager.getInstance(project!!) fun change(num: Int): TextMergeChange { if (changes.size < num) throw Exception("changes: ${changes.size}, index: $num") return changes[num] } fun activeChanges(): List<TextMergeChange> = viewer.changes // // Actions // fun runApplyNonConflictsAction(side: ThreeSide) { runActionById(side.select("Left", "All", "Right")!!) } private fun runActionById(text: String): Boolean { val action = actions.filter { text == it.templatePresentation.text }.single() return runAction(action) } private fun runAction(action: AnAction): Boolean { val actionEvent = AnActionEvent.createFromAnAction(action, null, ActionPlaces.MAIN_MENU, editor.dataContext) action.update(actionEvent) val success = actionEvent.presentation.isEnabledAndVisible if (success) action.actionPerformed(actionEvent) return success } // // Modification // fun command(affected: TextMergeChange, f: () -> Unit): Unit { command(listOf(affected), f) } fun command(affected: List<TextMergeChange>? = null, f: () -> Unit): Unit { viewer.executeMergeCommand(null, affected, f) UIUtil.dispatchAllInvocationEvents() } fun write(f: () -> Unit): Unit { ApplicationManager.getApplication().runWriteAction({ CommandProcessor.getInstance().executeCommand(project, f, null, null) }) } fun Int.ignore(side: Side, modifier: Boolean = false) { val change = change(this) command(change) { viewer.ignoreChange(change, side, modifier) } } fun Int.apply(side: Side, modifier: Boolean = false) { val change = change(this) command(change) { viewer.replaceChange(change, side, modifier) } } fun Int.resolve() { val change = change(this) command(change) { assertTrue(change.isConflict && viewer.canResolveChangeAutomatically(change, ThreeSide.BASE)) viewer.resolveChangeAutomatically(change, ThreeSide.BASE) } } fun Int.canResolveConflict(): Boolean { val change = change(this) return viewer.canResolveChangeAutomatically(change, ThreeSide.BASE) } // // Text modification // fun insertText(offset: Int, newContent: CharSequence) { replaceText(offset, offset, newContent) } fun deleteText(startOffset: Int, endOffset: Int) { replaceText(startOffset, endOffset, "") } fun replaceText(startOffset: Int, endOffset: Int, newContent: CharSequence) { write { document.replaceString(startOffset, endOffset, parseSource(newContent)) } } fun insertText(offset: LineCol, newContent: CharSequence) { replaceText(offset.toOffset(), offset.toOffset(), newContent) } fun deleteText(startOffset: LineCol, endOffset: LineCol) { replaceText(startOffset.toOffset(), endOffset.toOffset(), "") } fun replaceText(startOffset: LineCol, endOffset: LineCol, newContent: CharSequence) { write { replaceText(startOffset.toOffset(), endOffset.toOffset(), newContent) } } fun replaceText(oldContent: CharSequence, newContent: CharSequence) { write { val range = findRange(parseSource(oldContent)) replaceText(range.first, range.second, newContent) } } fun deleteText(oldContent: CharSequence) { write { val range = findRange(parseSource(oldContent)) replaceText(range.first, range.second, "") } } fun insertTextBefore(oldContent: CharSequence, newContent: CharSequence) { write { insertText(findRange(parseSource(oldContent)).first, newContent) } } fun insertTextAfter(oldContent: CharSequence, newContent: CharSequence) { write { insertText(findRange(parseSource(oldContent)).second, newContent) } } private fun findRange(oldContent: CharSequence): Couple<Int> { val text = document.charsSequence val index1 = StringUtil.indexOf(text, oldContent) assertTrue(index1 >= 0, "content - '\n$oldContent\n'\ntext - '\n$text'") val index2 = StringUtil.indexOf(text, oldContent, index1 + 1) assertTrue(index2 == -1, "content - '\n$oldContent\n'\ntext - '\n$text'") return Couple(index1, index1 + oldContent.length) } // // Undo // fun undo(count: Int = 1) { if (count == -1) { while (undoManager.isUndoAvailable(textEditor)) { undoManager.undo(textEditor) } } else { for (i in 1..count) { assertTrue(undoManager.isUndoAvailable(textEditor)) undoManager.undo(textEditor) } } } fun redo(count: Int = 1) { if (count == -1) { while (undoManager.isRedoAvailable(textEditor)) { undoManager.redo(textEditor) } } else { for (i in 1..count) { assertTrue(undoManager.isRedoAvailable(textEditor)) undoManager.redo(textEditor) } } } fun checkUndo(count: Int = -1, f: TestBuilder.() -> Unit) { val initialState = ViewerState.recordState(viewer) f() UIUtil.dispatchAllInvocationEvents() val afterState = ViewerState.recordState(viewer) undo(count) UIUtil.dispatchAllInvocationEvents() val undoState = ViewerState.recordState(viewer) redo(count) UIUtil.dispatchAllInvocationEvents() val redoState = ViewerState.recordState(viewer) assertEquals(initialState, undoState) assertEquals(afterState, redoState) } // // Checks // fun assertChangesCount(expected: Int) { if (expected == -1) return val actual = activeChanges().size assertEquals(expected, actual) } fun Int.assertType(type: TextDiffType, changeType: SidesState) { assertType(type) assertType(changeType) } fun Int.assertType(type: TextDiffType) { val change = change(this) assertEquals(change.diffType, type) } fun Int.assertType(changeType: SidesState) { assertTrue(changeType != NONE) val change = change(this) val actual = change.type val isLeftChange = changeType != RIGHT val isRightChange = changeType != LEFT assertEquals(Pair(isLeftChange, isRightChange), Pair(actual.isChange(Side.LEFT), actual.isChange(Side.RIGHT))) } fun Int.assertResolved(type: SidesState) { val change = change(this) val isLeftResolved = type == LEFT || type == BOTH val isRightResolved = type == RIGHT || type == BOTH assertEquals(Pair(isLeftResolved, isRightResolved), Pair(change.isResolved(Side.LEFT), change.isResolved(Side.RIGHT))) } fun Int.assertRange(start: Int, end: Int) { val change = change(this) assertEquals(Pair(start, end), Pair(change.startLine, change.endLine)) } fun Int.assertRange(start1: Int, end1: Int, start2: Int, end2: Int, start3: Int, end3: Int) { val change = change(this) assertEquals(MergeRange(start1, end1, start2, end2, start3, end3), MergeRange(change.getStartLine(ThreeSide.LEFT), change.getEndLine(ThreeSide.LEFT), change.getStartLine(ThreeSide.BASE), change.getEndLine(ThreeSide.BASE), change.getStartLine(ThreeSide.RIGHT), change.getEndLine(ThreeSide.RIGHT))) } fun Int.assertContent(expected: String, start: Int, end: Int) { assertContent(expected) assertRange(start, end) } fun Int.assertContent(expected: String) { val change = change(this) val document = editor.document val actual = DiffUtil.getLinesContent(document, change.startLine, change.endLine) assertEquals(parseSource(expected), actual) } fun assertContent(expected: String) { val actual = viewer.editor.document.charsSequence assertEquals(parseSource(expected), actual) } // // Helpers // operator fun Int.not(): LineColHelper = LineColHelper(this) operator fun LineColHelper.minus(col: Int): LineCol = LineCol(this.line, col) inner class LineColHelper(val line: Int) { } inner class LineCol(val line: Int, val col: Int) { fun toOffset(): Int = editor.document.getLineStartOffset(line) + col } } private class MockMergeContext(private val myProject: Project?) : MergeContext() { override fun getProject(): Project? = myProject override fun isFocusedInWindow(): Boolean = false override fun requestFocusInWindow() { } override fun finishMerge(result: MergeResult) { } } private class MockMergeRequest(val left: DocumentContent, val base: DocumentContent, val right: DocumentContent, val output: DocumentContent) : TextMergeRequest() { override fun getTitle(): String? = null override fun applyResult(result: MergeResult) { } override fun getContents(): List<DocumentContent> = listOf(left, base, right) override fun getOutputContent(): DocumentContent = output override fun getContentTitles(): List<String?> = listOf(null, null, null) } enum class SidesState { LEFT, RIGHT, BOTH, NONE } private data class ViewerState constructor(private val content: CharSequence, private val changes: List<ViewerState.ChangeState>) { companion object { fun recordState(viewer: MyThreesideViewer): ViewerState { val content = viewer.editor.document.immutableCharSequence val changes = viewer.allChanges.map { recordChangeState(viewer, it) } return ViewerState(content, changes) } private fun recordChangeState(viewer: MyThreesideViewer, change: TextMergeChange): ChangeState { val document = viewer.editor.document; val content = DiffUtil.getLinesContent(document, change.startLine, change.endLine) val resolved = if (change.isResolved) BOTH else if (change.isResolved(Side.LEFT)) LEFT else if (change.isResolved(Side.RIGHT)) RIGHT else NONE val starts = Trio.from { change.getStartLine(it) } val ends = Trio.from { change.getStartLine(it) } return ChangeState(content, starts, ends, resolved) } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ViewerState) return false if (!StringUtil.equals(content, other.content)) return false if (changes != other.changes) return false return true } override fun hashCode(): Int = StringUtil.hashCode(content) private data class ChangeState(private val content: CharSequence, private val starts: Trio<Int>, private val ends: Trio<Int>, private val resolved: SidesState) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ChangeState) return false if (!StringUtil.equals(content, other.content)) return false if (starts != other.starts) return false if (ends != other.ends) return false if (resolved != other.resolved) return false return true } override fun hashCode(): Int = StringUtil.hashCode(content) } } }
apache-2.0
f8f49fe6d7e83fad37914c526df21db8
33.583732
140
0.671693
4.655717
false
false
false
false
yongce/AndroidLib
baseLib/src/test/java/me/ycdev/android/lib/common/packets/RawPacketsWorkerTest.kt
1
904
package me.ycdev.android.lib.common.packets import com.google.common.truth.Truth.assertThat import org.junit.Test class RawPacketsWorkerTest : PacketsWorkerTestBase() { @Test fun packetAndParse() { val packetsWorker = RawPacketsWorker(parserCallback) for (length in 1..1024) { val data = generateData(length) val packets = packetsWorker.packetData(data) assertThat(packets.size).isEqualTo(1) packetsWorker.parsePackets(packets[0]) assertThat(parserCallback.getData()).isEqualTo(data) } } @Test fun parseEmptyData() { val packetsWorker = RawPacketsWorker(parserCallback) val packets = packetsWorker.packetData(byteArrayOf()) assertThat(packets.size).isEqualTo(1) packetsWorker.parsePackets(packets[0]) assertThat(parserCallback.getData()).isNull() } }
apache-2.0
b831876a923a892ebcda4ceccafce5b2
30.172414
64
0.67146
4.475248
false
true
false
false
AoDevBlue/AnimeUltimeTv
app/src/main/java/blue/aodev/animeultimetv/data/local/LocalSourceSet.kt
1
1547
package blue.aodev.animeultimetv.data.local import blue.aodev.animeultimetv.data.IRealmService import blue.aodev.animeultimetv.domain.model.Timing import blue.aodev.animeultimetv.utils.extensions.loadOrCreate import io.reactivex.Completable import io.reactivex.Single import io.realm.Realm class LocalSourceSet(val realm: IRealmService) : ILocalSourceSet { override fun saveTiming(timing: Timing): Completable { return Completable.fromAction { with(realm.getInstance()) { use { executeTransaction { val timingRealm = timing.toRealmObject(this) copyToRealmOrUpdate(timingRealm) } } } } } override fun getTimings(): Single<List<Timing>> { return Single.fromCallable { with(realm.getInstance()) { use { val timings = where(TimingRealm::class.java).findAll() copyFromRealm(timings).map { it.toModel() } } } } } fun Timing.toRealmObject(realm: Realm): TimingRealm { val primaryKey = TimingRealm.toPrimaryKey(animeId, episodeIndex) val timingRealm = realm.loadOrCreate<TimingRealm>(primaryKey, "primaryKey") timingRealm.time = time return timingRealm } fun TimingRealm.toModel(): Timing { val ids = TimingRealm.fromPrimaryKey(this.primaryKey) return Timing(ids.first, ids.second, this.time) } }
mit
cdd6662fd19e5d357c78345556f69395
31.25
83
0.613445
4.880126
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/openal/src/templates/kotlin/openal/ALBinding.kt
4
5471
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package openal import org.lwjgl.generator.* import java.io.* private const val CAPABILITIES_CLASS = "ALCapabilities" private val ALBinding = Generator.register(object : APIBinding( Module.OPENAL, CAPABILITIES_CLASS, APICapabilities.JAVA_CAPABILITIES ) { private val classes by lazy { super.getClasses("AL") } private val functions by lazy { classes.getFunctionPointers() } private val functionOrdinals by lazy { LinkedHashMap<String, Int>().also { functionOrdinals -> classes.asSequence() .filter { it.hasNativeFunctions } .forEach { it.functions.asSequence() .forEach { cmd -> if (!cmd.has<Macro>() && !functionOrdinals.contains(cmd.name)) { functionOrdinals[cmd.name] = functionOrdinals.size } } } } } override fun shouldCheckFunctionAddress(function: Func): Boolean = function.nativeClass.templateName != "AL10" override fun generateFunctionAddress(writer: PrintWriter, function: Func) { writer.println("$t${t}long $FUNCTION_ADDRESS = AL.getICD().${function.name};") } private fun PrintWriter.printCheckFunctions( nativeClass: NativeClass, filter: (Func) -> Boolean ) { print("checkFunctions(provider, caps, new int[] {") nativeClass.printPointers(this, { func -> functionOrdinals[func.name].toString() }, filter) print("},") nativeClass.printPointers(this, { "\"${it.name}\"" }, filter) print(")") } private fun PrintWriter.checkExtensionFunctions(nativeClass: NativeClass) { val capName = nativeClass.capName("AL") print(""" private static boolean check_${nativeClass.templateName}(FunctionProvider provider, PointerBuffer caps, Set<String> ext) { if (!ext.contains("$capName")) { return false; }""") print("\n\n$t${t}return ") printCheckFunctions(nativeClass) { !it.has(IgnoreMissing) } println(" || reportMissing(\"AL\", \"$capName\");") println("$t}") } init { javaImport( "org.lwjgl.*", "java.util.function.IntFunction", "static org.lwjgl.system.APIUtil.*", "static org.lwjgl.system.Checks.*" ) documentation = "Defines the capabilities of an OpenAL context." } override fun PrintWriter.generateJava() { generateJavaPreamble() println("""public final class $CAPABILITIES_CLASS {""") val functionSet = LinkedHashSet<String>() classes.asSequence() .filter { it.hasNativeFunctions } .forEach { val functions = it.functions.asSequence() .filter { cmd -> if (!cmd.has<Macro>()) { if (functionSet.add(cmd.name)) { return@filter true } } false } .joinToString(",\n$t$t") { cmd -> cmd.name } if (functions.isNotEmpty()) { println("\n$t// ${it.templateName}") println("${t}public final long") println("$t$t$functions;") } } println() classes.forEach { println(it.getCapabilityJavadoc()) println("${t}public final boolean ${it.capName("AL")};") } print(""" /** Off-heap array of the above function addresses. */ final PointerBuffer addresses; $CAPABILITIES_CLASS(FunctionProvider provider, Set<String> ext, IntFunction<PointerBuffer> bufferFactory) { PointerBuffer caps = bufferFactory.apply(${functions.size}); """) for (extension in classes) { val capName = extension.capName("AL") print( if (extension.hasNativeFunctions) "\n$t$t$capName = check_${extension.templateName}(provider, caps, ext);" else "\n$t$t$capName = ext.contains(\"$capName\");" ) } println() functionOrdinals.forEach { (it, index) -> print("\n$t$t$it = caps.get($index);") } print(""" addresses = ThreadLocalUtil.setupAddressBuffer(caps); } /** Returns the buffer of OpenAL function pointers. */ public PointerBuffer getAddressBuffer() { return addresses; } """) for (extension in classes) { if (extension.hasNativeFunctions) { checkExtensionFunctions(extension) } } println("\n}") } }) // DSL Extensions fun String.nativeClassAL(templateName: String, prefixTemplate: String = "AL", postfix: String = "", init: (NativeClass.() -> Unit)? = null) = nativeClass(Module.OPENAL, templateName, prefix = "AL", prefixTemplate = prefixTemplate, postfix = postfix, binding = ALBinding, init = init) val NativeClass.specLinkOpenALSoft: String get() = url("https://openal-soft.org/openal-extensions/$templateName.txt", templateName) val NativeClass.extensionName: String get() = "{@code ${prefixTemplate}_$templateName}"
bsd-3-clause
1a90e181f01883751c55ccaa39d1a54f
32.365854
145
0.560227
4.928829
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/nanovg/src/templates/kotlin/nanovg/NVGTypesBGFX.kt
4
688
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package nanovg import org.lwjgl.generator.* val int32_tb = PrimitiveType("int32_t", PrimitiveMapping.BOOLEAN4) val ViewId = typedef(uint16_t, "bgfx_view_id_t") val TextureHandle = typedef(uint16_t, "bgfx_texture_handle_t") val AllocatorI = "bgfx_allocator_interface_t".opaque.p val NVGLUframebufferBGFX = struct(Module.NANOVG, "NVGLUFramebufferBGFX", nativeName = "NVGLUframebuffer", mutable = false) { documentation = "A framebuffer object." NVGcontext.p("ctx", "") typedef(uint16_t, "bgfx_frame_buffer_handle_t")("handle", "") int("image", "") ViewId("viewId", "") }
bsd-3-clause
f885dbfa31615d970519ddbf86c3b7db
31.809524
124
0.706395
3.422886
false
false
false
false
Tickaroo/tikxml
annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/textcontent/Day.kt
1
601
package com.tickaroo.tikxml.annotationprocessing.textcontent import com.tickaroo.tikxml.annotation.TextContent import com.tickaroo.tikxml.annotation.Xml /** * @author Hannes Dorfmann */ @Xml class Day { @TextContent var name: String? = null override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Day) return false val day = other as Day? return if (name != null) name == day!!.name else day!!.name == null } override fun hashCode(): Int { return if (name != null) name!!.hashCode() else 0 } }
apache-2.0
a87f9231441b6793585d15489eb337f7
21.259259
75
0.637271
4.060811
false
false
false
false
saffih/ElmDroid
app/src/main/java/elmdroid/elmdroid/example4/TabbedElmApp.kt
1
7531
package elmdroid.elmdroid.example4 import android.content.Intent import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.TextView import elmdroid.elmdroid.R import kotlinx.android.synthetic.main.activity_tabbed.* import saffih.elmdroid.ElmBase /** * Copyright Joseph Hartal (Saffi) * Created by saffi on 29/04/17. */ /** * class wrapping the id provided by ui, * providing strong typed data type */ enum class ItemOption(val id: Int) { settings(R.id.action_settings); companion object { val map by lazy { values().associate { it.id to it } } fun byId(id: Int) = map.get(id) } } /** * Nested hierarchy of handled messages */ sealed class Msg { class Init : Msg() sealed class Fab : Msg() { class Clicked(val view: View) : Fab() } sealed class Options : Msg() { class ItemSelected(val item: MenuItem) : Options() } sealed class Action : Msg() { class GotOrig : Action() } } /** * Immutable Model */ data class Model(val activity: MActivity = MActivity()) data class MActivity( val pager: MViewPager = MViewPager(), val fab: MFab = MFab(), val toolbar: MToolbar = MToolbar(), val options: MOptions = MOptions()) data class MOptions(val itemOption: MItemOption = MItemOption(false)) data class MViewPager(val i: Int = 0) data class MToolbar(val i: Int = 0) data class MFab(val snackbar: MSnackbar = MSnackbar()) data class MSnackbar(val i: Int = 0) data class MItemOption(val handled: Boolean = true, val item: ItemOption? = null) /** * State machine for the app and derived view */ class TabbedElmApp(override val me: TabbedActivity) : ElmBase<Model, Msg>(me) { override fun init(): Model { dispatch(Msg.Init()) return Model() } override fun update(msg: Msg, model: Model): Model { return when (msg) { is Msg.Init -> { model } else -> { val m = update(msg, model.activity) model.copy(activity = m) } } } fun update(msg: Msg, model: MActivity): MActivity { return when (msg) { is Msg.Init -> model is Msg.Fab.Clicked -> { Snackbar.make(msg.view, "Goto original studio generated activity", Snackbar.LENGTH_LONG) .setAction("Goto", { me.startActivity( Intent(me, TabbedActivityOrig::class.java)) }).show() model } is Msg.Options -> { val m = update(msg, model.options) model.copy(options = m) } is Msg.Action.GotOrig -> model } } private fun update(msg: Msg.Options, model: MOptions): MOptions { return when (msg) { is Msg.Options.ItemSelected -> { val m = update(msg, model.itemOption) model.copy(itemOption = m) } } } fun update(msg: Msg.Options.ItemSelected, model: MItemOption): MItemOption { val selected = ItemOption.byId(msg.item.itemId) if (selected == null) { return MItemOption(handled = false) } else { return MItemOption(item = selected) } } override fun view(model: Model, pre: Model?) { val setup = { } checkView(setup, model, pre) { view(model.activity, pre?.activity) } } private fun view(model: MActivity, pre: MActivity?) { val setup = { me.setContentView(R.layout.activity_main_example4) } checkView(setup, model, pre) { view(model.fab, pre?.fab) view(model.toolbar, pre?.toolbar) view(model.pager, pre?.pager) } } private fun view(model: MViewPager, pre: MViewPager?) { val setup = { // Create the adapter that will return a fragment for each of the three // primary sections of the activity. val mSectionsPagerAdapter = SectionsPagerAdapter(me.supportFragmentManager) // Set up the ViewPager with the sections adapter. val mViewPager = me.container mViewPager.adapter = mSectionsPagerAdapter } checkView(setup, model, pre) { // view(myModel.activity, pre?.activity ) } } private fun view(model: MToolbar, pre: MToolbar?) { val setup = { val toolbar = me.toolbar me.setSupportActionBar(toolbar) } checkView(setup, model, pre) { // view(myModel.activity, pre?.activity ) } } private fun view(model: MFab, pre: MFab?) { val setup = { val fab = me.fab fab.setOnClickListener { view -> dispatch(Msg.Fab.Clicked(view)) } } checkView(setup, model, pre) { view(model.snackbar, pre?.snackbar) } } private fun view(model: MSnackbar, pre: MSnackbar?) { val setup = { } checkView(setup, model, pre) { // view(myModel.activity, pre?.activity ) } } } /** * A placeholder fragment containing a simple view. */ class PlaceholderFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater!!.inflate(R.layout.fragment_tabbed_activity_example4, container, false) val textView = rootView.findViewById(R.id.section_label) as TextView textView.text = getString(R.string.section_format, arguments.getInt(ARG_SECTION_NUMBER)) return rootView } companion object { /** * The fragment argument representing the section number for this * fragment. */ private val ARG_SECTION_NUMBER = "section_number" /** * Returns a new instance of this fragment for the given section * number. */ fun newInstance(sectionNumber: Int): PlaceholderFragment { val fragment = PlaceholderFragment() val args = Bundle() args.putInt(ARG_SECTION_NUMBER, sectionNumber) fragment.arguments = args return fragment } } } /** * A [FragmentPagerAdapter] that returns a fragment corresponding to * one of the sections/tabs/pages. */ class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) { override fun getItem(position: Int): Fragment { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). return PlaceholderFragment.newInstance(position + 1) } override fun getCount(): Int { // Show 3 total pages. return 3 } override fun getPageTitle(position: Int): CharSequence? { when (position) { 0 -> return "SECTION 1" 1 -> return "SECTION 2" 2 -> return "SECTION 3" } return null } }
apache-2.0
210836222cf0dafcb333ce9f59164bb8
26.789668
104
0.584252
4.514988
false
false
false
false
pkleimann/livingdoc2
livingdoc-engine/src/main/kotlin/org/livingdoc/engine/execution/examples/Util.kt
1
639
package org.livingdoc.engine.execution.examples fun executeWithBeforeAndAfter(before: () -> Unit, body: () -> Unit, after: () -> Unit) { var exception: Throwable? = null try { before.invoke() body.invoke() } catch (e: Throwable) { exception = e } finally { try { after.invoke() } catch (e: Throwable) { if (exception != null) { exception.addSuppressed(e) } else { exception = e } } finally { if (exception != null) { throw exception } } } }
apache-2.0
16fb21408de4642f12ea68674868c48e
23.576923
88
0.463224
4.597122
false
false
false
false
dahlstrom-g/intellij-community
plugins/gradle/java/src/config/GradleUseScopeEnlarger.kt
15
3303
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.config import com.intellij.openapi.application.ReadAction import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil.* import com.intellij.openapi.module.Module import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.PsiMember import com.intellij.psi.PsiReference import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.psi.search.UseScopeEnlarger import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.PsiUtilCore import com.intellij.util.Processor import org.jetbrains.plugins.gradle.service.GradleBuildClasspathManager import org.jetbrains.plugins.gradle.util.GradleConstants /** * @author Vladislav.Soroka */ class GradleUseScopeEnlarger : UseScopeEnlarger() { override fun getAdditionalUseScope(element: PsiElement): SearchScope? { return try { getScope(element) } catch (e: IndexNotReadyException) { null } } companion object { private fun getScope(element: PsiElement): SearchScope? { val virtualFile = PsiUtilCore.getVirtualFile(element.containingFile) ?: return null val fileIndex = ProjectRootManager.getInstance(element.project).fileIndex val module = fileIndex.getModuleForFile(virtualFile) ?: return null if (!isExternalSystemAwareModule(GradleConstants.SYSTEM_ID, module)) return null val rootProjectPath = getExternalRootProjectPath(module) ?: return null return if (!isApplicable(element, module, rootProjectPath, virtualFile, fileIndex)) null else object : GlobalSearchScope(element.project) { override fun contains(file: VirtualFile): Boolean { return GradleConstants.EXTENSION == file.extension || file.name.endsWith(GradleConstants.KOTLIN_DSL_SCRIPT_EXTENSION) } override fun isSearchInModuleContent(aModule: Module) = rootProjectPath == getExternalRootProjectPath(module) override fun isSearchInLibraries() = false } } private fun isApplicable(element: PsiElement, module: Module, rootProjectPath: String, virtualFile: VirtualFile, fileIndex: ProjectFileIndex): Boolean { val projectPath = getExternalProjectPath(module) ?: return false if (projectPath.endsWith("/buildSrc")) return true val sourceRoot = fileIndex.getSourceRootForFile(virtualFile) return sourceRoot in GradleBuildClasspathManager.getInstance(element.project).getModuleClasspathEntries(rootProjectPath) } fun search(element: PsiMember, consumer: Processor<PsiReference>) { val scope: SearchScope = ReadAction.compute<SearchScope, RuntimeException> { getScope(element) } ?: return val newParams = ReferencesSearch.SearchParameters(element, scope, true) ReferencesSearch.search(newParams).forEach(consumer) } } }
apache-2.0
b0a2ed38122c01a924692ce18c05c8e1
44.246575
140
0.750833
5.019757
false
false
false
false
AlexZhukovich/MedicationReminder
app/src/androidTest/java/com/alexzh/medicationreminder/data/PillDaoTest.kt
1
4896
package com.alexzh.medicationreminder.data import android.arch.core.executor.testing.InstantTaskExecutorRule import android.arch.persistence.room.EmptyResultSetException import android.arch.persistence.room.Room import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import com.alexzh.medicationreminder.TestData import com.alexzh.medicationreminder.data.local.MedicationReminderDatabase import com.alexzh.medicationreminder.data.local.PillDao import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class PillDaoTest { private lateinit var mPillDao: PillDao @Rule @JvmField val instantTaskExecutorRule = InstantTaskExecutorRule() @Before fun setUp() { val context = InstrumentationRegistry.getContext() val database = Room.inMemoryDatabaseBuilder(context, MedicationReminderDatabase::class.java) .allowMainThreadQueries() .build() mPillDao = database.pillDao() } @Test fun should_getEmptyListOfPills_fromEmptyTable() { mPillDao.getPills() .test() .assertValue(TestData.EMPTY_LIST_OF_PILLS) } @Test fun should_getPillById_afterInserting() { mPillDao.insert(TestData.getFirstPill()) mPillDao.getPillById(TestData.getFirstPill().id) .test() .assertValue(TestData.getFirstPill()) } @Test fun should_getError_afterLoadingPillByIdFromNonExistingPill() { mPillDao.getPillById(TestData.getFirstPill().id) .test() .assertError(EmptyResultSetException::class.java) } @Test fun should_insert_newPill() { val pillId = mPillDao.insert(TestData.getFirstPill()) assertEquals(TestData.FIRST_PILL_ID, pillId) mPillDao.getPills() .test() .assertValue(listOf(TestData.getFirstPill())) } @Test fun should_notInsert_theSamePillTwice() { mPillDao.insert(TestData.getFirstPill()) mPillDao.insert(TestData.getFirstPill()) mPillDao.getPills() .test() .assertValue(listOf(TestData.getFirstPill())) } @Test fun should_notInsert_emptyListOfPills() { val ids = mPillDao.insert(TestData.EMPTY_LIST_OF_PILLS) assertEquals(TestData.EMPTY_LIST_OF_IDS, ids) mPillDao.getPills() .test() .assertValue(TestData.EMPTY_LIST_OF_PILLS) } @Test fun should_insert_listOfPills() { val expectedIds = listOf(TestData.FIRST_PILL_ID, TestData.SECOND_PILL_ID) val ids = mPillDao.insert(TestData.getPills()) assertEquals(expectedIds, ids) mPillDao.getPills() .test() .assertValue(TestData.getPills()) } @Test fun should_notInsert_listOfPillsTwice() { mPillDao.insert(TestData.getPills()) mPillDao.insert(TestData.getPills()) mPillDao.getPills() .test() .assertValue(TestData.getPills()) } @Test fun should_update_existingPill() { mPillDao.insert(TestData.getSecondPill()) val count = mPillDao.update(TestData.getSecondUpdatedPill()) assertEquals(1, count) mPillDao.getPills() .test() .assertValue(listOf(TestData.getSecondUpdatedPill())) } @Test fun should_notUpdate_nonExistingPill() { val count = mPillDao.update(TestData.getFirstPill()) assertEquals(0, count) mPillDao.getPills() .test() .assertValue(TestData.EMPTY_LIST_OF_PILLS) } @Test fun should_delete_existingPill() { mPillDao.insert(TestData.getFirstPill()) mPillDao.insert(TestData.getSecondPill()) val count = mPillDao.delete(TestData.getFirstPill()) assertEquals(1, count) mPillDao.getPills() .test() .assertValue(listOf(TestData.getSecondPill())) } @Test fun should_notDelete_NonExistingPill () { val count = mPillDao.delete(TestData.getFirstPill()) assertEquals(0, count) mPillDao.getPills() .test() .assertValue(TestData.EMPTY_LIST_OF_PILLS) } @Test fun should_delete_allPills() { mPillDao.insert(TestData.getPills()) mPillDao.deleteAllPills() mPillDao.getPills() .test() .assertValue(TestData.EMPTY_LIST_OF_PILLS) } @Test fun should_notDelete_allPillsFromEmptyTable() { mPillDao.deleteAllPills() mPillDao.getPills() .test() .assertValue(TestData.EMPTY_LIST_OF_PILLS) } }
mit
c393bd5f6e7eaa2f5cfaf26e424e9110
27.47093
100
0.630923
4.662857
false
true
false
false
paplorinc/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ProjectExcludesIgnoredFileProvider.kt
2
2012
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.roots.impl.DirectoryIndexExcludePolicy import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.changes.ui.ChangesComparator import com.intellij.openapi.vfs.VirtualFileManager class ProjectExcludesIgnoredFileProvider : IgnoredFileProvider { override fun isIgnoredFile(project: Project, filePath: FilePath) = ChangeListManagerImpl.getInstanceImpl(project).ignoredFilesComponent.isIgnoredFile(filePath) override fun getIgnoredFiles(project: Project) = getProjectExcludePathsRelativeTo(project) override fun getIgnoredGroupDescription() = "Project exclude paths" private fun getProjectExcludePathsRelativeTo(project: Project): Set<IgnoredFileDescriptor> { val excludes = sortedSetOf(ChangesComparator.getVirtualFileComparator(false)) val fileIndex = ProjectFileIndex.SERVICE.getInstance(project) for (policy in DirectoryIndexExcludePolicy.EP_NAME.getExtensions(project)) { for (url in policy.excludeUrlsForProject) { val file = VirtualFileManager.getInstance().findFileByUrl(url) if (file != null) { excludes.add(file) } } } for (module in ModuleManager.getInstance(project).modules) { if (module.isDisposed) continue for (excludeRoot in ModuleRootManager.getInstance(module).excludeRoots) { if (!fileIndex.isExcluded(excludeRoot)) { //root is included into some inner module so it shouldn't be ignored continue } excludes.add(excludeRoot) } } return excludes.map { file -> IgnoredBeanFactory.ignoreFile(file, project) }.toSet() } }
apache-2.0
056f91cd318b12a6f55f1a553ca059ad
39.26
140
0.762922
4.756501
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/ide/customize/transferSettings/ui/TransferSettingsLeftPanelItemRenderer.kt
1
2967
// 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.ide.customize.transferSettings.ui import com.intellij.icons.AllIcons import com.intellij.ide.customize.transferSettings.models.BaseIdeVersion import com.intellij.ide.customize.transferSettings.models.FailedIdeVersion import com.intellij.ui.dsl.builder.BottomGap import com.intellij.ui.dsl.builder.RightGap import com.intellij.ui.dsl.builder.TopGap import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.gridLayout.Gaps import com.intellij.ui.dsl.gridLayout.VerticalAlign import com.intellij.util.IconUtil import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.Component import javax.swing.JList import javax.swing.ListCellRenderer class TransferSettingsLeftPanelItemRenderer : ListCellRenderer<BaseIdeVersion> { override fun getListCellRendererComponent( list: JList<out BaseIdeVersion>?, item: BaseIdeVersion, index: Int, isSelected: Boolean, cellHasFocus: Boolean ): Component { val fg = UIUtil.getListForeground(isSelected, cellHasFocus) val bg = UIUtil.getListBackground(isSelected, cellHasFocus) return panel { // todo: there's a bug with this label. i tried to fix it but nothing helped. anyway, it's not a supported scenario now in rider /*if (item is FailedIdeVersion && (index == 0 || (list?.model?.getElementAt(index-1) !is FailedIdeVersion))) { row { val ts = TitledSeparator(RiderIdeaInteropBundle.message("IdeVersionListItemRenderer.separator.failed.to.open")) ts.apply { background = UIUtil.getListBackground(false, false) isOpaque = true } cell(ts) .horizontalAlign(HorizontalAlign.FILL) .customize(Gaps(bottom = 4)) } }*/ row { icon(IconUtil.scale(item.icon, null, 35 / item.icon.iconWidth.toFloat())) .verticalAlign(VerticalAlign.CENTER) .customize(Gaps(right = 10, left = 10)) // TODO: create a customizer and pass inset here panel { row { if (item is FailedIdeVersion) { icon(AllIcons.General.Warning).gap(RightGap.SMALL).customize(Gaps(right = 3)) } label(item.name).bold().verticalAlign(VerticalAlign.TOP).applyToComponent { font = font.deriveFont(13f) foreground = fg }.customize(Gaps()) } item.subName?.let { row { label(it).applyToComponent { font = font.deriveFont(12f) foreground = fg }.customize(Gaps()) }.bottomGap(BottomGap.NONE) } } }.topGap(TopGap.SMALL).bottomGap(BottomGap.SMALL) }.apply { background = bg border = JBUI.Borders.empty() } } }
apache-2.0
e883566c989d171c616aeca8aac833c7
37.545455
134
0.653859
4.502276
false
false
false
false
RuneSuite/client
plugins-dev/src/main/java/org/runestar/client/plugins/dev/FriendsListDebug.kt
1
1629
package org.runestar.client.plugins.dev import org.runestar.client.api.plugins.DisposablePlugin import org.runestar.client.api.Fonts import org.runestar.client.api.game.live.Game import org.runestar.client.api.game.live.Canvas import org.runestar.client.api.plugins.PluginSettings import java.awt.Color class FriendsListDebug : DisposablePlugin<FriendsListDebug.Settings>() { override val defaultSettings = Settings() override fun onStart() { add(Canvas.repaints.subscribe { g -> g.color = Color.WHITE g.font = Fonts.PLAIN_11 val x = 20 var y = 40 val lines = ArrayList<String>() when (settings.mode) { Mode.CLAN -> { val cc = Game.clanChat ?: return@subscribe lines.add("owner=${cc.owner}") lines.add("name=${cc.name}") lines.add("") cc.mapTo(lines) { it.toString() } } Mode.FRIEND -> { val fs = Game.friendsSystem.friendsList fs.mapTo(lines) { it.toString() } } Mode.IGNORE -> { val gs = Game.friendsSystem.ignoreList gs.mapTo(lines) { it.toString() } } } for (line in lines) { g.drawString(line, x, y) y += g.font.size + 4 } }) } enum class Mode { CLAN, FRIEND, IGNORE } class Settings( val mode: Mode = Mode.FRIEND ) : PluginSettings() }
mit
40ac3f765bda246a926a298b035311cc
29.185185
72
0.513812
4.438692
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/Method2.kt
1
1084
package org.runestar.client.updater.mapper import org.objectweb.asm.Type import org.objectweb.asm.tree.MethodNode class Method2(val jar: Jar2, val klass: Class2, val node: MethodNode) { companion object { const val CONSTRUCTOR_NAME = "<init>" const val CLASS_INITIALIZER_NAME = "<clinit>" } val name: String get() = node.name val desc: String get() = node.desc val type: Type = Type.getMethodType(node.desc) val arguments = type.argumentTypes.asList() val returnType: Type = type.returnType val access get() = node.access val signature = name to arguments val mark = name to type val id = Triple(klass.type, name, type) val instructions get() = node.instructions.iterator().asSequence() .map { Instruction2(jar, klass, this, it) } val isClassInitializer: Boolean get() { return name == CLASS_INITIALIZER_NAME } val isConstructor: Boolean get() { return name == CONSTRUCTOR_NAME } override fun toString(): String { return "$klass.$name$desc" } }
mit
dfae8dca810ea7872d981eb673fe0ea4
23.111111
71
0.652214
4.121673
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/SwitchToWhenConversion.kt
1
5945
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.nj2k.conversions import com.intellij.psi.PsiElement import com.intellij.psi.controlFlow.ControlFlowFactory import com.intellij.psi.controlFlow.ControlFlowUtil import com.intellij.psi.controlFlow.LocalsOrMyInstanceFieldsControlFlowPolicy import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.RecursiveApplicableConversionBase import org.jetbrains.kotlin.nj2k.blockStatement import org.jetbrains.kotlin.nj2k.runExpression import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.util.takeWhileInclusive class SwitchToWhenConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKJavaSwitchBlock) return recurse(element) element.invalidate() element.cases.forEach { case -> case.statements.forEach { it.detach(case) } if (case is JKJavaLabelSwitchCase) { case::labels.detached() } } val cases = switchCasesToWhenCases(element.cases).moveElseCaseToTheEnd() val whenBlock = when (element) { is JKJavaSwitchExpression -> JKKtWhenExpression(element.expression, cases, element.calculateType(typeFactory)) is JKJavaSwitchStatement -> JKKtWhenStatement(element.expression, cases) else -> error("Unexpected class ${element::class.simpleName}") } return recurse(whenBlock) } private fun List<JKKtWhenCase>.moveElseCaseToTheEnd(): List<JKKtWhenCase> = sortedBy { case -> case.labels.any { it is JKKtElseWhenLabel } } private fun switchCasesToWhenCases(cases: List<JKJavaSwitchCase>): List<JKKtWhenCase> { if (cases.isEmpty()) return emptyList() val statements = if (cases.first() is JKJavaArrowSwitchLabelCase) cases.first().statements else { cases .takeWhileInclusive { it.statements.fallsThrough() } .flatMap { it.statements } .takeWhileInclusive { statement -> statement.singleListOrBlockStatements().none { isSwitchBreakOrYield(it) } } .mapNotNull { statement -> when (statement) { is JKBlockStatement -> blockStatement( statement.block.statements .takeWhileInclusive { !isSwitchBreakOrYield(it) } .mapNotNull { handleBreakOrYield(it) } ).withFormattingFrom(statement) else -> handleBreakOrYield(statement) } } } val javaLabels = cases .takeWhileInclusive { it.statements.isEmpty() } val statementLabels = javaLabels .filterIsInstance<JKJavaLabelSwitchCase>() .flatMap { it.labels } .map { JKKtValueWhenLabel(it) } val elseLabel = javaLabels .find { it is JKJavaDefaultSwitchCase } ?.let { JKKtElseWhenLabel() } val elseWhenCase = elseLabel?.let { label -> JKKtWhenCase(listOf(label), statements.map { it.copyTreeAndDetach() }.singleBlockOrWrapToRun()) } val mainWhenCase = if (statementLabels.isNotEmpty()) { JKKtWhenCase(statementLabels, statements.singleBlockOrWrapToRun()) } else null return listOfNotNull(mainWhenCase) + listOfNotNull(elseWhenCase) + switchCasesToWhenCases(cases.drop(javaLabels.size)) } private fun handleBreakOrYield(statement: JKStatement) = when { isSwitchBreak(statement) -> null else -> statement.copyTreeAndDetach() } private fun List<JKStatement>.singleBlockOrWrapToRun(): JKStatement = singleOrNull() ?: blockStatement(map { statement -> when (statement) { is JKBlockStatement -> JKExpressionStatement(runExpression(statement, symbolProvider)) else -> statement } }) private fun JKStatement.singleListOrBlockStatements(): List<JKStatement> = when (this) { is JKBlockStatement -> block.statements else -> listOf(this) } private fun isSwitchBreak(statement: JKStatement) = statement is JKBreakStatement && statement.label is JKLabelEmpty private fun isSwitchBreakOrYield(statement: JKStatement) = isSwitchBreak(statement) || statement is JKJavaYieldStatement private fun List<JKStatement>.fallsThrough(): Boolean = all { it.fallsThrough() } private fun JKStatement.fallsThrough(): Boolean = when { this.isThrowStatement() || this is JKBreakStatement || this is JKReturnStatement || this is JKContinueStatement -> false this is JKBlockStatement -> block.statements.fallsThrough() this is JKIfElseStatement || this is JKJavaSwitchBlock || this is JKKtWhenBlock -> psi?.canCompleteNormally() == true else -> true } private fun JKStatement.isThrowStatement(): Boolean = (this as? JKExpressionStatement)?.expression is JKThrowExpression private fun PsiElement.canCompleteNormally(): Boolean { val controlFlow = ControlFlowFactory.getInstance(project).getControlFlow(this, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance()) val startOffset = controlFlow.getStartOffset(this) val endOffset = controlFlow.getEndOffset(this) return startOffset == -1 || endOffset == -1 || ControlFlowUtil.canCompleteNormally(controlFlow, startOffset, endOffset) } }
apache-2.0
a4f19dd21683d62b757d56387132b45d
41.776978
129
0.648444
5.394737
false
false
false
false
JetBrains/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/intention/impl/preview/IntentionPreviewComputable.kt
1
12452
// 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.codeInsight.intention.impl.preview import com.intellij.application.options.CodeStyle import com.intellij.codeInsight.daemon.impl.ShowIntentionsPass import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.IntentionActionDelegate import com.intellij.codeInsight.intention.impl.CachedIntentions import com.intellij.codeInsight.intention.impl.IntentionActionWithTextCaching import com.intellij.codeInsight.intention.impl.ShowIntentionActionsHandler import com.intellij.codeInsight.intention.impl.config.IntentionsMetadataService import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo import com.intellij.codeInsight.intention.preview.IntentionPreviewUtils import com.intellij.codeInspection.ex.QuickFixWrapper import com.intellij.diff.comparison.ComparisonManager import com.intellij.diff.comparison.ComparisonPolicy import com.intellij.diff.fragments.LineFragment import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.cl.PluginAwareClassLoader import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.model.SideEffectGuard import com.intellij.model.SideEffectGuard.SideEffectNotAllowedException import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.progress.DumbProgressIndicator import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.* import com.intellij.psi.impl.source.PostprocessReformattingAspect import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtilBase import java.io.IOException import java.lang.ref.Reference import java.util.concurrent.Callable internal class IntentionPreviewComputable(private val project: Project, private val action: IntentionAction, private val originalFile: PsiFile, private val originalEditor: Editor) : Callable<IntentionPreviewInfo> { override fun call(): IntentionPreviewInfo { val diffContent = tryCreateDiffContent() if (diffContent != null) { return diffContent } return tryCreateFallbackDescriptionContent() } private fun tryCreateFallbackDescriptionContent(): IntentionPreviewInfo { val originalAction = IntentionActionDelegate.unwrap(action) val actionMetaData = IntentionsMetadataService.getInstance().getMetaData().singleOrNull { md -> IntentionActionDelegate.unwrap(md.action).javaClass === originalAction.javaClass } ?: return IntentionPreviewInfo.EMPTY return try { IntentionPreviewInfo.Html(actionMetaData.description.text.replace(HTML_COMMENT_REGEX, "")) } catch(ex: IOException) { IntentionPreviewInfo.EMPTY } } private fun tryCreateDiffContent(): IntentionPreviewInfo? { try { return generatePreview() } catch (e: ProcessCanceledException) { throw e } catch (e: SideEffectNotAllowedException) { val wrapper = RuntimeException(e.message) wrapper.stackTrace = e.stackTrace logger<IntentionPreviewComputable>().error("Side effect occurred on invoking the intention '${action.text}' on a copy of the file", wrapper) return null } catch (e: Exception) { logger<IntentionPreviewComputable>().error("Exceptions occurred on invoking the intention '${action.text}' on a copy of the file.", e) return null } } fun generatePreview(): IntentionPreviewInfo? { if (project.isDisposed) return null val origPair = ShowIntentionActionsHandler.chooseFileForAction(originalFile, originalEditor, action) ?: return null ProgressManager.checkCanceled() val writable = originalEditor.document.isWritable try { return invokePreview(origPair.first, origPair.second) } finally { originalEditor.document.setReadOnly(!writable) } } private fun invokePreview(origFile: PsiFile, origEditor: Editor): IntentionPreviewInfo? { var info: IntentionPreviewInfo = IntentionPreviewInfo.EMPTY var fileToCopy = action.getElementToMakeWritable(origFile) ?. containingFile ?: origFile val psiFileCopy: PsiFile val editorCopy: IntentionPreviewEditor val anotherFile = fileToCopy != origFile if (!anotherFile) { val fileFactory = PsiFileFactory.getInstance(project) if (origFile != originalFile) { // injection val manager = InjectedLanguageManager.getInstance(project) fileToCopy = fileFactory.createFileFromText(origFile.name, origFile.fileType, manager.getUnescapedText(origFile)) } psiFileCopy = IntentionPreviewUtils.obtainCopyForPreview(fileToCopy) editorCopy = IntentionPreviewEditor(psiFileCopy, originalEditor.settings) setupEditor(editorCopy, origFile, origEditor) } else { psiFileCopy = IntentionPreviewUtils.obtainCopyForPreview(fileToCopy) editorCopy = IntentionPreviewEditor(psiFileCopy, originalEditor.settings) } originalEditor.document.setReadOnly(true) ProgressManager.checkCanceled() // force settings initialization, as it may spawn EDT action which is not allowed inside generatePreview() val settings = CodeStyle.getSettings(editorCopy) IntentionPreviewUtils.previewSession(editorCopy) { PostprocessReformattingAspect.getInstance(project).postponeFormattingInside { info = SideEffectGuard.computeWithoutSideEffects<IntentionPreviewInfo?, Exception> { action.generatePreview(project, editorCopy, psiFileCopy) } } } if (info == IntentionPreviewInfo.FALLBACK_DIFF && fileToCopy == origFile) { info = SideEffectGuard.computeWithoutSideEffects<IntentionPreviewInfo?, Exception> { generateFallbackDiff(editorCopy, psiFileCopy) } } Reference.reachabilityFence(settings) val manager = PsiDocumentManager.getInstance(project) manager.commitDocument(editorCopy.document) manager.doPostponedOperationsAndUnblockDocument(editorCopy.document) val comparisonManager = ComparisonManager.getInstance() return when (val result = info) { IntentionPreviewInfo.DIFF, IntentionPreviewInfo.DIFF_NO_TRIM -> { val document = psiFileCopy.viewProvider.document val policy = if (info == IntentionPreviewInfo.DIFF) ComparisonPolicy.TRIM_WHITESPACES else ComparisonPolicy.DEFAULT IntentionPreviewDiffResult( psiFile = psiFileCopy, origFile = fileToCopy, policy = policy, fileName = if (anotherFile) psiFileCopy.name else null, normalDiff = !anotherFile, lineFragments = comparisonManager.compareLines(fileToCopy.text, document.text, policy, DumbProgressIndicator.INSTANCE)) } IntentionPreviewInfo.EMPTY, IntentionPreviewInfo.FALLBACK_DIFF -> null is IntentionPreviewInfo.CustomDiff -> { val fileFactory = PsiFileFactory.getInstance(project) IntentionPreviewDiffResult( fileFactory.createFileFromText("__dummy__", result.fileType(), result.modifiedText()), fileFactory.createFileFromText("__dummy__", result.fileType(), result.originalText()), comparisonManager.compareLines(result.originalText(), result.modifiedText(), ComparisonPolicy.TRIM_WHITESPACES, DumbProgressIndicator.INSTANCE), fileName = result.fileName(), normalDiff = false, policy = ComparisonPolicy.TRIM_WHITESPACES) } else -> result } } private fun generateFallbackDiff(editorCopy: IntentionPreviewEditor, psiFileCopy: PsiFile): IntentionPreviewInfo { // Fallback algorithm for intention actions that don't support preview normally // works only for registered intentions (not for compilation or inspection quick-fixes) if (!action.startInWriteAction()) return IntentionPreviewInfo.EMPTY if (action.getElementToMakeWritable(originalFile)?.containingFile !== originalFile) return IntentionPreviewInfo.EMPTY val action = findCopyIntention(project, editorCopy, psiFileCopy, action) ?: return IntentionPreviewInfo.EMPTY val unwrapped = IntentionActionDelegate.unwrap(action) val cls = (if (unwrapped is QuickFixWrapper) unwrapped.fix else unwrapped)::class.java val loader = cls.classLoader val thirdParty = loader is PluginAwareClassLoader && PluginManagerCore.isDevelopedByJetBrains(loader.pluginDescriptor) if (!thirdParty) { logger<IntentionPreviewComputable>().error("Intention preview fallback is used for action ${cls.name}|${action.familyName}") } ProgressManager.checkCanceled() IntentionPreviewUtils.previewSession(editorCopy) { PostprocessReformattingAspect.getInstance(project) .postponeFormattingInside { action.invoke(project, editorCopy, psiFileCopy) } } return IntentionPreviewInfo.DIFF } private fun setupEditor(editorCopy: IntentionPreviewEditor, origFile: PsiFile, origEditor: Editor) { ProgressManager.checkCanceled() val selection: TextRange val caretOffset: Int if (origFile != originalFile) { // injection val selectionModel = origEditor.selectionModel val start = mapInjectedOffsetToUnescaped(origFile, selectionModel.selectionStart) val end = if (selectionModel.selectionEnd == selectionModel.selectionStart) start else mapInjectedOffsetToUnescaped(origFile, selectionModel.selectionEnd) selection = TextRange(start, end) val caretModel = origEditor.caretModel caretOffset = when (caretModel.offset) { selectionModel.selectionStart -> start selectionModel.selectionEnd -> end else -> mapInjectedOffsetToUnescaped(origFile, caretModel.offset) } } else { selection = TextRange(originalEditor.selectionModel.selectionStart, originalEditor.selectionModel.selectionEnd) caretOffset = originalEditor.caretModel.offset } editorCopy.caretModel.moveToOffset(caretOffset) editorCopy.selectionModel.setSelection(selection.startOffset, selection.endOffset) } private fun mapInjectedOffsetToUnescaped(injectedFile: PsiFile, injectedOffset: Int): Int { var unescapedOffset = 0 var escapedOffset = 0 injectedFile.accept(object : PsiRecursiveElementWalkingVisitor() { override fun visitElement(element: PsiElement) { val leafText = InjectedLanguageUtilBase.getUnescapedLeafText(element, false) if (leafText != null) { unescapedOffset += leafText.length escapedOffset += element.textLength if (escapedOffset >= injectedOffset) { unescapedOffset -= escapedOffset - injectedOffset stopWalking() } } super.visitElement(element) } }) return unescapedOffset } } private val HTML_COMMENT_REGEX = Regex("<!--.+-->") private fun getFixes(cachedIntentions: CachedIntentions): Sequence<IntentionActionWithTextCaching> { return sequenceOf<IntentionActionWithTextCaching>() .plus(cachedIntentions.intentions) .plus(cachedIntentions.inspectionFixes) .plus(cachedIntentions.errorFixes) } private fun findCopyIntention(project: Project, editorCopy: Editor, psiFileCopy: PsiFile, originalAction: IntentionAction): IntentionAction? { val actionsToShow = ShowIntentionsPass.getActionsToShow(editorCopy, psiFileCopy, false) val cachedIntentions = CachedIntentions.createAndUpdateActions(project, psiFileCopy, editorCopy, actionsToShow) return getFixes(cachedIntentions).find { it.text == originalAction.text }?.action } internal data class IntentionPreviewDiffResult(val psiFile: PsiFile, val origFile: PsiFile, val lineFragments: List<LineFragment>, val normalDiff: Boolean = true, val fileName: String? = null, val policy: ComparisonPolicy): IntentionPreviewInfo
apache-2.0
3d4a409a67c429199d3af7e29b3b3c11
48.217391
140
0.732412
5.67031
false
false
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/navigation/impl/PsiFileNavigationTarget.kt
2
1599
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.navigation.impl import com.intellij.codeInsight.navigation.fileLocation import com.intellij.codeInsight.navigation.fileStatusAttributes import com.intellij.navigation.NavigationTarget import com.intellij.navigation.TargetPresentation import com.intellij.openapi.vfs.newvfs.VfsPresentationUtil import com.intellij.pom.Navigatable import com.intellij.psi.PsiFile internal class PsiFileNavigationTarget( private val psiFile: PsiFile ) : NavigationTarget { override fun isValid(): Boolean = psiFile.isValid override fun getNavigatable(): Navigatable = psiFile override fun getTargetPresentation(): TargetPresentation { val project = psiFile.project var builder = TargetPresentation .builder(psiFile.name) .icon(psiFile.getIcon(0)) .containerText(psiFile.parent?.virtualFile?.presentableUrl) val file = psiFile.virtualFile ?: return builder.presentation() builder = builder .backgroundColor(VfsPresentationUtil.getFileBackgroundColor(project, file)) .presentableTextAttributes(fileStatusAttributes(project, file)) // apply file error and file status highlighting to file name val locationAndIcon = fileLocation(project, file) ?: return builder.presentation() @Suppress("HardCodedStringLiteral") builder = builder.locationText(locationAndIcon.first, locationAndIcon.second) return builder.presentation() } }
apache-2.0
b6b6a30d62cd77a9d4f28648cdce6dfd
37.071429
140
0.768605
5.028302
false
false
false
false
allotria/intellij-community
plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesTreeModel.kt
1
8424
// 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 git4idea.ui.branch.dashboard import com.intellij.dvcs.DvcsUtil import com.intellij.dvcs.branch.GroupingKey import com.intellij.dvcs.branch.GroupingKey.GROUPING_BY_DIRECTORY import com.intellij.dvcs.branch.GroupingKey.GROUPING_BY_REPOSITORY import com.intellij.openapi.actionSystem.DataKey import com.intellij.openapi.components.service import com.intellij.util.ThreeState import git4idea.branch.GitBranchType import git4idea.i18n.GitBundle.message import git4idea.repo.GitRepository import git4idea.ui.branch.GitBranchManager import org.jetbrains.annotations.Nls import java.util.* import javax.swing.tree.DefaultMutableTreeNode internal val GIT_BRANCHES = DataKey.create<List<BranchInfo>>("GitBranchKey") internal val GIT_BRANCH_FILTERS = DataKey.create<List<String>>("GitBranchFilterKey") internal data class RemoteInfo(val remoteName: String, val repository: GitRepository?) internal data class BranchInfo(val branchName: String, val isLocal: Boolean, val isCurrent: Boolean, var isFavorite: Boolean, val repositories: List<GitRepository>) { var isMy: ThreeState = ThreeState.UNSURE override fun toString() = branchName } internal data class BranchNodeDescriptor(val type: NodeType, val branchInfo: BranchInfo? = null, val repository: GitRepository? = null, val displayName: String? = resolveDisplayName(branchInfo, repository), val parent: BranchNodeDescriptor? = null) { override fun toString(): String { val suffix = branchInfo?.branchName ?: displayName return if (suffix != null) "$type:$suffix" else "$type" } fun getDisplayText() = displayName ?: branchInfo?.branchName } private fun resolveDisplayName(branchInfo: BranchInfo?, repository: GitRepository?) = when { branchInfo != null -> branchInfo.branchName repository != null -> DvcsUtil.getShortRepositoryName(repository) else -> null } internal enum class NodeType { ROOT, LOCAL_ROOT, REMOTE_ROOT, BRANCH, GROUP_NODE, GROUP_REPOSITORY_NODE, HEAD_NODE } internal class BranchTreeNode(nodeDescriptor: BranchNodeDescriptor) : DefaultMutableTreeNode(nodeDescriptor) { fun getTextRepresentation(): @Nls String { val nodeDescriptor = userObject as? BranchNodeDescriptor ?: return super.toString() return when (nodeDescriptor.type) { NodeType.LOCAL_ROOT -> message("group.Git.Local.Branch.title") NodeType.REMOTE_ROOT -> message("group.Git.Remote.Branch.title") NodeType.HEAD_NODE -> message("group.Git.HEAD.Branch.Filter.title") NodeType.GROUP_REPOSITORY_NODE -> " ${nodeDescriptor.getDisplayText()}" else -> nodeDescriptor.getDisplayText() ?: super.toString() } } fun getNodeDescriptor() = userObject as BranchNodeDescriptor override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false if (other !is BranchTreeNode) return false return Objects.equals(this.userObject, other.userObject) } override fun hashCode() = Objects.hash(userObject) } internal class NodeDescriptorsModel(private val localRootNodeDescriptor: BranchNodeDescriptor, private val remoteRootNodeDescriptor: BranchNodeDescriptor) { /** * Parent node descriptor to direct children map */ private val branchNodeDescriptors = hashMapOf<BranchNodeDescriptor, MutableSet<BranchNodeDescriptor>>() fun clear() = branchNodeDescriptors.clear() fun getChildrenForParent(parent: BranchNodeDescriptor): Set<BranchNodeDescriptor> = branchNodeDescriptors.getOrDefault(parent, emptySet()) fun populateFrom(branches: Sequence<BranchInfo>, groupingConfig: Map<GroupingKey, Boolean>) { branches.forEach { branch -> populateFrom(branch, groupingConfig) } } private fun populateFrom(br: BranchInfo, groupingConfig: Map<GroupingKey, Boolean>) { val curParent: BranchNodeDescriptor = if (br.isLocal) localRootNodeDescriptor else remoteRootNodeDescriptor val groupByDirectory = groupingConfig[GROUPING_BY_DIRECTORY]!! val groupByRepository = groupingConfig[GROUPING_BY_REPOSITORY]!! when { groupByRepository && groupByDirectory -> { applyGroupingByRepository(curParent, br) { branch, parent -> applyGroupingByDirectory(parent, branch) } } groupByRepository -> applyGroupingByRepository(curParent, br) groupByDirectory -> applyGroupingByDirectory(curParent, br.copy()) else -> addChild(curParent, BranchNodeDescriptor(NodeType.BRANCH, br.copy(), parent = curParent)) } } private fun applyGroupingByRepository(curParent: BranchNodeDescriptor, br: BranchInfo, additionalGrouping: ((BranchInfo, BranchNodeDescriptor) -> Unit)? = null) { val repositoryNodeDescriptors = hashMapOf<GitRepository, BranchNodeDescriptor>() br.repositories.forEach { repository -> val branch = br.copy(isCurrent = repository.isCurrentBranch(br.branchName), isFavorite = repository.isFavorite(br)) val repositoryNodeDescriptor = repositoryNodeDescriptors.computeIfAbsent(repository) { val repositoryNodeDescriptor = BranchNodeDescriptor(NodeType.GROUP_REPOSITORY_NODE, repository = repository, parent = curParent) addChild(curParent, repositoryNodeDescriptor) repositoryNodeDescriptor } if (additionalGrouping != null) { additionalGrouping.invoke(branch, repositoryNodeDescriptor) } else { val branchNodeDescriptor = BranchNodeDescriptor(NodeType.BRANCH, branch, parent = repositoryNodeDescriptor) addChild(repositoryNodeDescriptor, branchNodeDescriptor) } } } private fun applyGroupingByDirectory(parent: BranchNodeDescriptor, branch: BranchInfo) { val iter = branch.branchName.split("/").iterator() var curParent = parent while (iter.hasNext()) { val branchNamePart = iter.next() val groupNode = iter.hasNext() val nodeType = if (groupNode) NodeType.GROUP_NODE else NodeType.BRANCH val branchInfo = if (nodeType == NodeType.BRANCH) branch else null val branchNodeDescriptor = BranchNodeDescriptor(nodeType, branchInfo, displayName = branchNamePart, parent = curParent) addChild(curParent, branchNodeDescriptor) curParent = branchNodeDescriptor } } private fun addChild(parent: BranchNodeDescriptor, child: BranchNodeDescriptor) { val directChildren = branchNodeDescriptors.computeIfAbsent(parent) { sortedSetOf(BRANCH_TREE_NODE_COMPARATOR) } directChildren.add(child) branchNodeDescriptors[parent] = directChildren } private fun GitRepository.isCurrentBranch(branchName: String) = currentBranch?.name == branchName private fun GitRepository.isFavorite(branch: BranchInfo) = project.service<GitBranchManager>().isFavorite(if (branch.isLocal) GitBranchType.LOCAL else GitBranchType.REMOTE, this, branch.branchName) } internal val BRANCH_TREE_NODE_COMPARATOR = Comparator<BranchNodeDescriptor> { d1, d2 -> val b1 = d1.branchInfo val b2 = d2.branchInfo val displayText1 = d1.getDisplayText() val displayText2 = d2.getDisplayText() val b1GroupNode = d1.type == NodeType.GROUP_NODE val b2GroupNode = d2.type == NodeType.GROUP_NODE val b1Current = b1 != null && b1.isCurrent val b2Current = b2 != null && b2.isCurrent val b1Favorite = b1 != null && b1.isFavorite val b2Favorite = b2 != null && b2.isFavorite fun compareByDisplayTextOrType() = if (displayText1 != null && displayText2 != null) displayText1.compareTo(displayText2) else d1.type.compareTo(d2.type) when { b1Current && b2Current -> compareByDisplayTextOrType() b1Current -> -1 b2Current -> 1 b1Favorite && b2Favorite -> compareByDisplayTextOrType() b1Favorite -> -1 b2Favorite -> 1 b1GroupNode && b2GroupNode -> compareByDisplayTextOrType() b1GroupNode -> -1 b2GroupNode -> 1 else -> compareByDisplayTextOrType() } }
apache-2.0
7e8d720a930ec540ab11c852547e49d3
42.875
140
0.711657
5.038278
false
false
false
false
scenerygraphics/scenery
src/test/kotlin/graphics/scenery/tests/examples/basic/CurveDifferentBaseShapes.kt
1
4749
package graphics.scenery.tests.examples.basic import org.joml.* import graphics.scenery.* import graphics.scenery.backends.Renderer import graphics.scenery.geometry.Curve import graphics.scenery.geometry.UniformBSpline import graphics.scenery.numerics.Random import graphics.scenery.attribute.material.Material /** * Example of a curve with different baseShapes. * * @author Justin Buerger <[email protected]> */ class CurveDifferentBaseShapes: SceneryBase("CurveDifferentBaseShapes", windowWidth = 1280, windowHeight = 720) { override fun init() { renderer = hub.add(Renderer.createRenderer(hub, applicationName, scene, windowWidth, windowHeight)) val rowSize = 10f val points = ArrayList<Vector3f>() points.add(Vector3f(-8f, -9f, -9f)) points.add(Vector3f(-7f, -5f, -7f)) points.add(Vector3f(-5f, -5f, -5f)) points.add(Vector3f(-4f, -2f, -3f)) points.add(Vector3f(-2f, -3f, -4f)) points.add(Vector3f(-1f, -1f, -1f)) points.add(Vector3f(0f, 0f, 0f)) points.add(Vector3f(2f, 1f, 0f)) fun shapeGenerator(splineVerticesCount: Int): ArrayList<ArrayList<Vector3f>> { val shapeList = ArrayList<ArrayList<Vector3f>>(splineVerticesCount) val splineVerticesCountThird = splineVerticesCount/3 val splineVerticesCountTwoThirds = splineVerticesCount*2/3 for (i in 0 until splineVerticesCountThird) { val list = ArrayList<Vector3f>() list.add(Vector3f(0.3f, 0.3f, 0f)) list.add(Vector3f(0.3f, -0.3f, 0f)) list.add(Vector3f(-0.3f, -0.3f, 0f)) shapeList.add(list) } for(i in splineVerticesCountThird until splineVerticesCountTwoThirds) { val list = ArrayList<Vector3f>() list.add(Vector3f(0.3f, 0.3f, 0f)) list.add(Vector3f(0.3f, -0.3f, 0f)) list.add(Vector3f(-0.3f, -0.3f, 0f)) list.add(Vector3f(-0.3f, 0.3f, 0f)) shapeList.add(list) } for(i in splineVerticesCountTwoThirds until splineVerticesCount) { val list = ArrayList<Vector3f>() list.add(Vector3f(0.3f, 0.3f, 0f)) list.add(Vector3f(0.3f, -0.3f, 0f)) list.add(Vector3f(0f, -0.5f, 0f)) list.add(Vector3f(-0.3f, -0.3f, 0f)) list.add(Vector3f(-0.3f, 0.3f, 0f)) list.add(Vector3f(0f, 0.5f, 0f)) shapeList.add(list) } return shapeList } val bSpline = UniformBSpline(points) val splineSize = bSpline.splinePoints().size val geo = Curve(bSpline, false) { shapeGenerator(splineSize) } scene.addChild(geo) val lightbox = Box(Vector3f(25.0f, 25.0f, 25.0f), insideNormals = true) lightbox.name = "Lightbox" lightbox.material { diffuse = Vector3f(0.1f, 0.1f, 0.1f) roughness = 1.0f metallic = 0.0f cullingMode = Material.CullingMode.None } scene.addChild(lightbox) val lights = (0 until 8).map { val l = PointLight(radius = 20.0f) l.spatial { position = Vector3f( Random.randomFromRange(-rowSize / 2.0f, rowSize / 2.0f), Random.randomFromRange(-rowSize / 2.0f, rowSize / 2.0f), Random.randomFromRange(1.0f, 5.0f) ) } l.emissionColor = Random.random3DVectorFromRange( 0.2f, 0.8f) l.intensity = Random.randomFromRange(0.2f, 0.8f) lightbox.addChild(l) l } lights.forEach { scene.addChild(it) } val stageLight = PointLight(radius = 10.0f) stageLight.name = "StageLight" stageLight.intensity = 0.5f stageLight.spatial { position = Vector3f(0.0f, 0.0f, 5.0f) } scene.addChild(stageLight) val cameraLight = PointLight(radius = 5.0f) cameraLight.name = "CameraLight" cameraLight.emissionColor = Vector3f(1.0f, 1.0f, 0.0f) cameraLight.intensity = 0.8f val cam: Camera = DetachedHeadCamera() cam.spatial { position = Vector3f(0.0f, 0.0f, 10.0f) } cam.perspectiveCamera(50.0f, windowWidth, windowHeight) scene.addChild(cam) cam.addChild(cameraLight) } override fun inputSetup() { super.inputSetup() setupCameraModeSwitching() } companion object { @JvmStatic fun main(args: Array<String>) { CurveDifferentBaseShapes().main() } } }
lgpl-3.0
5c9b7ba8d6915de4aef4d3b246e49721
34.706767
113
0.577385
3.567994
false
false
false
false
allotria/intellij-community
plugins/dependency-updater/src/com/intellij/externalSystem/DependencyModifierService.kt
1
2424
package com.intellij.externalSystem import com.intellij.buildsystem.model.DeclaredDependency import com.intellij.buildsystem.model.unified.UnifiedDependency import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import org.jetbrains.annotations.ApiStatus @ApiStatus.Experimental class DependencyModifierService(private val myProject: Project) { fun addRepository(module: Module, repository: UnifiedDependencyRepository) = modify(module) { it.addRepository(module, repository) } fun deleteRepository(module: Module, repository: UnifiedDependencyRepository) = modify(module) { it.deleteRepository(module, repository) } fun declaredDependencies(module: Module): List<DeclaredDependency> = read(module) { it.declaredDependencies(module); } fun declaredRepositories(module: Module): List<UnifiedDependencyRepository> = read(module) { it.declaredRepositories(module); } fun supports(module: Module): Boolean { return ExternalDependencyModificator.EP_NAME.getExtensionList(myProject).any { it.supports(module) } } fun addDependency(module: Module, descriptor: UnifiedDependency) = modify(module) { it.addDependency(module, descriptor) } fun updateDependency(module: Module, oldDescriptor: UnifiedDependency, newDescriptor: UnifiedDependency) = modify(module) { it.updateDependency(module, oldDescriptor, newDescriptor) } fun removeDependency(module: Module, descriptor: UnifiedDependency) = modify(module) { it.removeDependency(module, descriptor) } private fun modify(module: Module, modifier: (ExternalDependencyModificator) -> Unit) { return ExternalDependencyModificator.EP_NAME.getExtensionList(myProject).firstOrNull { it.supports(module) }?.let(modifier) ?: throw IllegalArgumentException(DependencyUpdaterBundle.message("cannot.modify.module", module.name)) } private fun <T> read(module: Module, reader: (ExternalDependencyModificator) -> List<T>): List<T> { return ExternalDependencyModificator.EP_NAME.getExtensionList(myProject) .filter{ it.supports(module)} .flatMap { reader(it) } } companion object { @JvmStatic fun getInstance(project: Project): DependencyModifierService { return project.getService(DependencyModifierService::class.java) } } }
apache-2.0
b6d566b2028f30c8af758f202bcf9991
36.307692
127
0.765677
4.74364
false
false
false
false
android/wear-os-samples
WearOAuth/oauth-device-grant/src/main/java/com/example/android/wearable/oauth/devicegrant/AuthDeviceGrantViewModel.kt
1
7578
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.wearable.oauth.devicegrant import android.app.Application import android.content.Intent import android.net.Uri import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import androidx.wear.remote.interactions.RemoteActivityHelper import com.example.android.wearable.oauth.util.doGetRequest import com.example.android.wearable.oauth.util.doPostRequest import kotlinx.coroutines.CancellationException import kotlinx.coroutines.delay import kotlinx.coroutines.launch private const val TAG = "AuthDeviceGrantViewModel" // TODO Add your client id & secret here (for dev purposes only). private const val CLIENT_ID = "" private const val CLIENT_SECRET = "" /** * The viewModel that implements the OAuth flow. The method [startAuthFlow] implements the * different steps of the flow. It first retrieves the URL that should be opened on the paired * device, then polls for the access token, and uses it to retrieve the user's name. */ class AuthDeviceGrantViewModel(application: Application) : AndroidViewModel(application) { // Status to show on the Wear OS display val status: MutableLiveData<Int> by lazy { MutableLiveData<Int>() } // Dynamic content to show on the Wear OS display val result: MutableLiveData<String> by lazy { MutableLiveData<String>() } private fun showStatus(statusString: Int, resultString: String = "") { status.postValue(statusString) result.postValue(resultString) } fun startAuthFlow() { viewModelScope.launch { // Step 1: Retrieve the verification URI showStatus(R.string.status_switch_to_phone) val verificationInfo = retrieveVerificationInfo().getOrElse { showStatus(R.string.status_failed) return@launch } // Step 2: Show the pairing code & open the verification URI on the paired device showStatus(R.string.status_code, verificationInfo.userCode) fireRemoteIntent(verificationInfo.verificationUri) // Step 3: Poll the Auth server for the token val token = retrieveToken(verificationInfo.deviceCode, verificationInfo.interval) // Step 4: Use the token to make an authorized request val userName = retrieveUserProfile(token).getOrElse { showStatus(R.string.status_failed) return@launch } showStatus(R.string.status_retrieved, userName) } } // The response data when retrieving the verification data class VerificationInfo( val verificationUri: String, val userCode: String, val deviceCode: String, val interval: Int ) /** * Retrieve the information needed to verify the user. When performing this request, the server * generates a user & device code pair. The user code is shown to the user and opened on the * paired device. The device code is passed while polling the OAuth server. */ private suspend fun retrieveVerificationInfo(): Result<VerificationInfo> { return try { Log.d(TAG, "Retrieving verification info...") val responseJson = doPostRequest( url = "https://oauth2.googleapis.com/device/code", params = mapOf( "client_id" to CLIENT_ID, "scope" to "https://www.googleapis.com/auth/userinfo.profile" ) ) Result.success( VerificationInfo( verificationUri = responseJson.getString("verification_url"), userCode = responseJson.getString("user_code"), deviceCode = responseJson.getString("device_code"), interval = responseJson.getInt("interval") ) ) } catch (e: CancellationException) { throw e } catch (e: Exception) { e.printStackTrace() Result.failure(e) } } /** * Opens the verification URL on the paired device. * * When the user has the corresponding app installed on their paired Android device, the Data * Layer can be used instead, see https://developer.android.com/training/wearables/data-layer. * * When the user has the corresponding app installed on their paired iOS device, it should * use [Universal Links](https://developer.apple.com/ios/universal-links/) to intercept the * intent. */ private fun fireRemoteIntent(verificationUri: String) { RemoteActivityHelper(getApplication()).startRemoteActivity( Intent(Intent.ACTION_VIEW).apply { addCategory(Intent.CATEGORY_BROWSABLE) data = Uri.parse(verificationUri) }, null ) } /** * Poll the Auth server for the token. This will only return when the user has finished their * authorization flow on the paired device. * * For this sample the various exceptions aren't handled. */ private tailrec suspend fun retrieveToken(deviceCode: String, interval: Int): String { Log.d(TAG, "Polling for token...") return fetchToken(deviceCode).getOrElse { Log.d(TAG, "No token yet. Waiting...") delay(interval * 1000L) return retrieveToken(deviceCode, interval) } } private suspend fun fetchToken(deviceCode: String): Result<String> { return try { val responseJson = doPostRequest( url = "https://oauth2.googleapis.com/token", params = mapOf( "client_id" to CLIENT_ID, "client_secret" to CLIENT_SECRET, "device_code" to deviceCode, "grant_type" to "urn:ietf:params:oauth:grant-type:device_code" ) ) Result.success(responseJson.getString("access_token")) } catch (e: CancellationException) { throw e } catch (e: Exception) { e.printStackTrace() Result.failure(e) } } /** * Using the access token, make an authorized request to the Auth server to retrieve the user's * profile. */ private suspend fun retrieveUserProfile(token: String): Result<String> { return try { val responseJson = doGetRequest( url = "https://www.googleapis.com/oauth2/v2/userinfo", requestHeaders = mapOf( "Authorization" to "Bearer $token" ) ) Result.success(responseJson.getString("name")) } catch (e: CancellationException) { throw e } catch (e: Exception) { e.printStackTrace() Result.failure(e) } } }
apache-2.0
65ba340168b0d3161fc9da994250b39c
37.663265
99
0.634732
4.851472
false
false
false
false
faceofcat/Tesla-Core-Lib
src/main/kotlin/net/ndrei/teslacorelib/annotations/handlers.kt
1
2539
package net.ndrei.teslacorelib.annotations import net.minecraft.item.crafting.IRecipe import net.minecraft.util.ResourceLocation import net.minecraftforge.fml.common.Loader import net.minecraftforge.fml.common.registry.GameRegistry import net.minecraftforge.fml.relauncher.Side import net.minecraftforge.fml.relauncher.SideOnly import net.minecraftforge.registries.IForgeRegistry import net.ndrei.teslacorelib.TeslaCoreLib import net.ndrei.teslacorelib.blocks.RegisteredBlock import net.ndrei.teslacorelib.items.RegisteredItem import net.ndrei.teslacorelib.render.ISelfRegisteringRenderer /** * Created by CF on 2017-06-22. */ @Deprecated("One should really use JSON resources for recipes.", ReplaceWith("A JSON File!"), DeprecationLevel.WARNING) object AutoRegisterRecipesHandler: BaseAnnotationHandler<Any>({ it, _, _ -> val registry = GameRegistry.findRegistry(IRecipe::class.java) when (it) { is RegisteredItem -> it.registerRecipe { AutoRegisterRecipesHandler.registerRecipe(registry, it) } is RegisteredBlock -> it.registerRecipe { AutoRegisterRecipesHandler.registerRecipe(registry, it) } // else -> TeslaCoreLib.logger.error("Annotated class '${it.javaClass.canonicalName}' does not provide a recipe.") } }, AutoRegisterItem::class, AutoRegisterBlock::class) { @Deprecated("One should really use JSON resources for recipes.", ReplaceWith("A JSON File!"), DeprecationLevel.WARNING) fun registerRecipe(registry: IForgeRegistry<IRecipe>, recipe: IRecipe): ResourceLocation { if (recipe.registryName == null) { val output = recipe.recipeOutput val activeContainer = Loader.instance().activeModContainer() val baseLoc = ResourceLocation(activeContainer?.modId, output.item.registryName?.path) var recipeLoc = baseLoc var index = 0 while (registry.containsKey(recipeLoc)) { recipeLoc = ResourceLocation(activeContainer?.modId, "${baseLoc.path}_${++index}") } recipe.registryName = recipeLoc } registry.register(recipe) return recipe.registryName!! } } @SideOnly(Side.CLIENT) object AutoRegisterRendererHandler: BaseAnnotationHandler<Any>({ it, _, _ -> when (it) { is ISelfRegisteringRenderer -> it.registerRenderer() else -> TeslaCoreLib.logger.warn("Annotated class '${it.javaClass.canonicalName}' does not provide a renderer.") } }, AutoRegisterItem::class, AutoRegisterBlock::class/*, AutoRegisterFluid::class*/)
mit
c43f1a07d868fd3fef11091ad8c2020d
48.784314
123
0.732572
4.728119
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/defaultArguments/constructor/annotationWithEmptyArray.kt
5
196
annotation class Anno(val x: Array<String> = emptyArray()) @Anno fun test1() = 1 @Anno(arrayOf("K")) fun test2() = 2 fun box(): String { return if (test1() + test2() == 3) "OK" else "Fail" }
apache-2.0
bc31a7589170dad9fe3565891dd2ad32
23.625
58
0.607143
2.882353
false
true
false
false