repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
anuraaga/armeria | examples/context-propagation/kotlin/src/main/kotlin/example/armeria/contextpropagation/kotlin/Main.kt | 1 | 1628 | /*
* Copyright 2020 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* 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 example.armeria.contextpropagation.kotlin
import com.linecorp.armeria.client.WebClient
import com.linecorp.armeria.common.HttpResponse
import com.linecorp.armeria.common.HttpStatus
import com.linecorp.armeria.server.Server
fun main(args: Array<String>) {
val backend = Server.builder()
.service("/square/{num}") { ctx, _ ->
val num = ctx.pathParam("num")?.toLong()
if (num != null) {
HttpResponse.of((num * num).toString())
} else {
HttpResponse.of(HttpStatus.BAD_REQUEST)
}
}
.http(8081)
.build()
val backendClient = WebClient.of("http://localhost:8081")
val frontend = Server.builder()
.http(8080)
.serviceUnder("/", MainService(backendClient))
.build()
Runtime.getRuntime().addShutdownHook(Thread {
backend.stop().join()
frontend.stop().join()
})
backend.start().join()
frontend.start().join()
}
| apache-2.0 | 5e58b3d78a84cc275bbe360b1640104d | 30.921569 | 78 | 0.659091 | 4.272966 | false | false | false | false |
spark/photon-tinker-android | meshui/src/main/java/io/particle/mesh/ui/controlpanel/ControlPanelLandingFragment.kt | 1 | 7740 | package io.particle.mesh.ui.controlpanel
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import io.particle.android.sdk.cloud.BroadcastContract
import io.particle.android.sdk.cloud.ParticleCloud
import io.particle.android.sdk.cloud.ParticleCloudSDK
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.ARGON
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.A_SOM
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.B5_SOM
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.BLUZ
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.BORON
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.B_SOM
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.CORE
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.DIGISTUMP_OAK
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.ELECTRON
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.ESP32
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.OTHER
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.P1
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.PHOTON
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.RASPBERRY_PI
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.RED_BEAR_DUO
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.XENON
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType.X_SOM
import io.particle.commonui.DeviceNotesDelegate
import io.particle.commonui.RenameHelper
import io.particle.mesh.common.android.livedata.BroadcastReceiverLD
import io.particle.mesh.setup.flow.FlowRunnerUiListener
import io.particle.mesh.setup.flow.Scopes
import io.particle.mesh.ui.R
import io.particle.mesh.ui.TitleBarOptions
import io.particle.mesh.ui.inflateFragment
import kotlinx.android.synthetic.main.fragment_control_panel_landing.*
import mu.KotlinLogging
class ControlPanelLandingFragment : BaseControlPanelFragment() {
override val titleBarOptions = TitleBarOptions(R.string.p_controlpanel_control_panel)
private lateinit var cloud: ParticleCloud
private lateinit var devicesUpdatedBroadcast: BroadcastReceiverLD<Int>
private val flowManagementScope = Scopes()
private val log = KotlinLogging.logger {}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
cloud = ParticleCloudSDK.getCloud()
var initialValue = 0
devicesUpdatedBroadcast = BroadcastReceiverLD(
requireActivity(),
BroadcastContract.BROADCAST_DEVICES_UPDATED,
{ ++initialValue },
true
)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return container?.inflateFragment(R.layout.fragment_control_panel_landing)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
devicesUpdatedBroadcast.observe(viewLifecycleOwner, Observer { updateDetails() })
}
override fun onFragmentReady(activity: FragmentActivity, flowUiListener: FlowRunnerUiListener) {
super.onFragmentReady(activity, flowUiListener)
val deviceType = device.deviceType!!
p_controlpanel_landing_name_frame.setOnClickListener {
RenameHelper.renameDevice(activity, device)
}
p_controlpanel_landing_notes_frame.setOnClickListener { editNotes() }
network_info_header.isVisible = deviceType in gen3Devices
p_controlpanel_landing_wifi_item_frame.isVisible = deviceType in listOf(ARGON, A_SOM)
p_controlpanel_landing_wifi_item.setOnClickListener {
flowScopes.onMain {
startFlowWithBarcode(flowRunner::startControlPanelInspectCurrentWifiNetworkFlow)
}
}
p_controlpanel_landing_cellular_item_frame.isVisible = deviceType in listOf(BORON, B_SOM, B5_SOM)
p_controlpanel_landing_cellular_item.setOnClickListener {
flowRunner.startShowControlPanelCellularOptionsFlow(device)
}
p_controlpanel_landing_ethernet_item_frame.isVisible = deviceType in gen3Devices
p_controlpanel_landing_ethernet_item_frame.setOnClickListener {
flowScopes.onMain {
startFlowWithBarcode(flowRunner::startShowControlPanelEthernetOptionsFlow)
}
}
p_controlpanel_landing_mesh_item.isVisible = deviceType in gen3Devices
p_controlpanel_landing_mesh_item.setOnClickListener {
val uri: Uri = Uri.parse(
"https://docs.particle.io/reference/developer-tools/cli/#particle-mesh"
)
val intent = Intent(Intent.ACTION_VIEW, uri)
if (intent.resolveActivity(requireContext().packageManager) != null) {
startActivity(intent)
}
}
p_controlpanel_landing_docs_item.setOnClickListener {
showDocumentation(activity, device.deviceType!!)
}
p_controlpanel_landing_unclaim_item.setOnClickListener {
navigateToUnclaim()
}
}
override fun onResume() {
super.onResume()
updateDetails()
}
override fun onStop() {
super.onStop()
log.info { "onStop()" }
}
private fun updateDetails() {
p_controlpanel_landing_name_value.text = device.name
p_controlpanel_landing_notes_value.text = device.notes
}
private fun navigateToUnclaim() {
flowSystemInterface.showGlobalProgressSpinner(true)
findNavController().navigate(
R.id.action_global_controlPanelUnclaimDeviceFragment,
ControlPanelUnclaimDeviceFragmentArgs(device.name).toBundle()
)
flowSystemInterface.showGlobalProgressSpinner(false)
}
private fun editNotes() {
val editLD = MutableLiveData<String>()
DeviceNotesDelegate.editDeviceNotes(
requireActivity(),
device,
flowManagementScope,
editLD
)
editLD.observe(this, Observer {
p_controlpanel_landing_notes_value.text = it
})
}
}
private val gen3Devices = setOf(
ParticleDeviceType.ARGON,
ParticleDeviceType.A_SOM,
ParticleDeviceType.BORON,
ParticleDeviceType.B_SOM,
ParticleDeviceType.B5_SOM,
ParticleDeviceType.XENON,
ParticleDeviceType.X_SOM
)
private fun showDocumentation(context: Context, deviceType: ParticleDeviceType) {
val finalPathSegment = when (deviceType) {
CORE -> "core"
PHOTON -> "photon"
P1 -> "datasheets/wi-fi/p1-datasheet"
ELECTRON -> "electron"
ARGON, A_SOM -> "argon"
BORON, B_SOM, B5_SOM -> "boron"
XENON, X_SOM -> "xenon"
RASPBERRY_PI,
RED_BEAR_DUO,
BLUZ,
DIGISTUMP_OAK,
ESP32,
OTHER -> null
}
finalPathSegment?.let {
val uri = Uri.parse("https://docs.particle.io/$finalPathSegment")
context.startActivity(Intent(Intent.ACTION_VIEW, uri))
}
}
| apache-2.0 | ba3faa095280c52855477d010e9a9433 | 36.391304 | 105 | 0.723902 | 4.612634 | false | false | false | false |
toastkidjp/Jitte | image/src/main/java/jp/toastkid/image/preview/detail/ImageDetailFragment.kt | 1 | 1791 | /*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.image.preview.detail
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.exifinterface.media.ExifInterface
import androidx.fragment.app.DialogFragment
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import java.io.File
import java.io.FileInputStream
class ImageDetailFragment : BottomSheetDialogFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreateView(inflater, container, savedInstanceState)
val context = context ?: return null
val textView = TextView(context)
val imageUri = arguments?.getParcelable<Uri>(KEY_EXTRA_IMAGE_URI) ?: return null
val inputStream = FileInputStream(File(imageUri.toString()))
val exifInterface = ExifInterface(inputStream)
textView.text = ExifInformationExtractorUseCase().invoke(exifInterface)
inputStream.close()
return textView
}
companion object {
private const val KEY_EXTRA_IMAGE_URI = "image_uri"
fun withImageUri(imageUri: Uri): DialogFragment =
ImageDetailFragment().also {
it.arguments = bundleOf(KEY_EXTRA_IMAGE_URI to imageUri)
}
}
} | epl-1.0 | 9b67ec4fa537d51f8a9714df444ca739 | 31.581818 | 88 | 0.717476 | 4.827493 | false | false | false | false |
inorichi/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/backup/full/FullBackupManager.kt | 1 | 14137 | package eu.kanade.tachiyomi.data.backup.full
import android.content.Context
import android.net.Uri
import com.hippo.unifile.UniFile
import eu.kanade.tachiyomi.data.backup.AbstractBackupManager
import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_CATEGORY
import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_CATEGORY_MASK
import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_CHAPTER
import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_CHAPTER_MASK
import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_HISTORY
import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_HISTORY_MASK
import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_TRACK
import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_TRACK_MASK
import eu.kanade.tachiyomi.data.backup.full.models.Backup
import eu.kanade.tachiyomi.data.backup.full.models.BackupCategory
import eu.kanade.tachiyomi.data.backup.full.models.BackupChapter
import eu.kanade.tachiyomi.data.backup.full.models.BackupFull
import eu.kanade.tachiyomi.data.backup.full.models.BackupHistory
import eu.kanade.tachiyomi.data.backup.full.models.BackupManga
import eu.kanade.tachiyomi.data.backup.full.models.BackupSerializer
import eu.kanade.tachiyomi.data.backup.full.models.BackupSource
import eu.kanade.tachiyomi.data.backup.full.models.BackupTracking
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.History
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.models.MangaCategory
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.util.system.logcat
import kotlinx.serialization.protobuf.ProtoBuf
import logcat.LogPriority
import okio.buffer
import okio.gzip
import okio.sink
import kotlin.math.max
class FullBackupManager(context: Context) : AbstractBackupManager(context) {
val parser = ProtoBuf
/**
* Create backup Json file from database
*
* @param uri path of Uri
* @param isJob backup called from job
*/
override fun createBackup(uri: Uri, flags: Int, isJob: Boolean): String? {
// Create root object
var backup: Backup? = null
databaseHelper.inTransaction {
val databaseManga = getFavoriteManga()
backup = Backup(
backupManga(databaseManga, flags),
backupCategories(),
emptyList(),
backupExtensionInfo(databaseManga)
)
}
try {
val file: UniFile = (
if (isJob) {
// Get dir of file and create
var dir = UniFile.fromUri(context, uri)
dir = dir.createDirectory("automatic")
// Delete older backups
val numberOfBackups = numberOfBackups()
val backupRegex = Regex("""tachiyomi_\d+-\d+-\d+_\d+-\d+.proto.gz""")
dir.listFiles { _, filename -> backupRegex.matches(filename) }
.orEmpty()
.sortedByDescending { it.name }
.drop(numberOfBackups - 1)
.forEach { it.delete() }
// Create new file to place backup
dir.createFile(BackupFull.getDefaultFilename())
} else {
UniFile.fromUri(context, uri)
}
)
?: throw Exception("Couldn't create backup file")
val byteArray = parser.encodeToByteArray(BackupSerializer, backup!!)
file.openOutputStream().sink().gzip().buffer().use { it.write(byteArray) }
val fileUri = file.uri
// Validate it to make sure it works
FullBackupRestoreValidator().validate(context, fileUri)
return fileUri.toString()
} catch (e: Exception) {
logcat(LogPriority.ERROR, e)
throw e
}
}
private fun backupManga(mangas: List<Manga>, flags: Int): List<BackupManga> {
return mangas.map {
backupMangaObject(it, flags)
}
}
private fun backupExtensionInfo(mangas: List<Manga>): List<BackupSource> {
return mangas
.asSequence()
.map { it.source }
.distinct()
.map { sourceManager.getOrStub(it) }
.map { BackupSource.copyFrom(it) }
.toList()
}
/**
* Backup the categories of library
*
* @return list of [BackupCategory] to be backed up
*/
private fun backupCategories(): List<BackupCategory> {
return databaseHelper.getCategories()
.executeAsBlocking()
.map { BackupCategory.copyFrom(it) }
}
/**
* Convert a manga to Json
*
* @param manga manga that gets converted
* @param options options for the backup
* @return [BackupManga] containing manga in a serializable form
*/
private fun backupMangaObject(manga: Manga, options: Int): BackupManga {
// Entry for this manga
val mangaObject = BackupManga.copyFrom(manga)
// Check if user wants chapter information in backup
if (options and BACKUP_CHAPTER_MASK == BACKUP_CHAPTER) {
// Backup all the chapters
val chapters = databaseHelper.getChapters(manga).executeAsBlocking()
if (chapters.isNotEmpty()) {
mangaObject.chapters = chapters.map { BackupChapter.copyFrom(it) }
}
}
// Check if user wants category information in backup
if (options and BACKUP_CATEGORY_MASK == BACKUP_CATEGORY) {
// Backup categories for this manga
val categoriesForManga = databaseHelper.getCategoriesForManga(manga).executeAsBlocking()
if (categoriesForManga.isNotEmpty()) {
mangaObject.categories = categoriesForManga.mapNotNull { it.order }
}
}
// Check if user wants track information in backup
if (options and BACKUP_TRACK_MASK == BACKUP_TRACK) {
val tracks = databaseHelper.getTracks(manga).executeAsBlocking()
if (tracks.isNotEmpty()) {
mangaObject.tracking = tracks.map { BackupTracking.copyFrom(it) }
}
}
// Check if user wants history information in backup
if (options and BACKUP_HISTORY_MASK == BACKUP_HISTORY) {
val historyForManga = databaseHelper.getHistoryByMangaId(manga.id!!).executeAsBlocking()
if (historyForManga.isNotEmpty()) {
val history = historyForManga.mapNotNull { history ->
val url = databaseHelper.getChapter(history.chapter_id).executeAsBlocking()?.url
url?.let { BackupHistory(url, history.last_read) }
}
if (history.isNotEmpty()) {
mangaObject.history = history
}
}
}
return mangaObject
}
fun restoreMangaNoFetch(manga: Manga, dbManga: Manga) {
manga.id = dbManga.id
manga.copyFrom(dbManga)
insertManga(manga)
}
/**
* Fetches manga information
*
* @param manga manga that needs updating
* @return Updated manga info.
*/
fun restoreManga(manga: Manga): Manga {
return manga.also {
it.initialized = it.description != null
it.id = insertManga(it)
}
}
/**
* Restore the categories from Json
*
* @param backupCategories list containing categories
*/
internal fun restoreCategories(backupCategories: List<BackupCategory>) {
// Get categories from file and from db
val dbCategories = databaseHelper.getCategories().executeAsBlocking()
// Iterate over them
backupCategories.map { it.getCategoryImpl() }.forEach { category ->
// Used to know if the category is already in the db
var found = false
for (dbCategory in dbCategories) {
// If the category is already in the db, assign the id to the file's category
// and do nothing
if (category.name == dbCategory.name) {
category.id = dbCategory.id
found = true
break
}
}
// If the category isn't in the db, remove the id and insert a new category
// Store the inserted id in the category
if (!found) {
// Let the db assign the id
category.id = null
val result = databaseHelper.insertCategory(category).executeAsBlocking()
category.id = result.insertedId()?.toInt()
}
}
}
/**
* Restores the categories a manga is in.
*
* @param manga the manga whose categories have to be restored.
* @param categories the categories to restore.
*/
internal fun restoreCategoriesForManga(manga: Manga, categories: List<Int>, backupCategories: List<BackupCategory>) {
val dbCategories = databaseHelper.getCategories().executeAsBlocking()
val mangaCategoriesToUpdate = ArrayList<MangaCategory>(categories.size)
categories.forEach { backupCategoryOrder ->
backupCategories.firstOrNull {
it.order == backupCategoryOrder
}?.let { backupCategory ->
dbCategories.firstOrNull { dbCategory ->
dbCategory.name == backupCategory.name
}?.let { dbCategory ->
mangaCategoriesToUpdate += MangaCategory.create(manga, dbCategory)
}
}
}
// Update database
if (mangaCategoriesToUpdate.isNotEmpty()) {
databaseHelper.deleteOldMangasCategories(listOf(manga)).executeAsBlocking()
databaseHelper.insertMangasCategories(mangaCategoriesToUpdate).executeAsBlocking()
}
}
/**
* Restore history from Json
*
* @param history list containing history to be restored
*/
internal fun restoreHistoryForManga(history: List<BackupHistory>) {
// List containing history to be updated
val historyToBeUpdated = ArrayList<History>(history.size)
for ((url, lastRead) in history) {
val dbHistory = databaseHelper.getHistoryByChapterUrl(url).executeAsBlocking()
// Check if history already in database and update
if (dbHistory != null) {
dbHistory.apply {
last_read = max(lastRead, dbHistory.last_read)
}
historyToBeUpdated.add(dbHistory)
} else {
// If not in database create
databaseHelper.getChapter(url).executeAsBlocking()?.let {
val historyToAdd = History.create(it).apply {
last_read = lastRead
}
historyToBeUpdated.add(historyToAdd)
}
}
}
databaseHelper.updateHistoryLastRead(historyToBeUpdated).executeAsBlocking()
}
/**
* Restores the sync of a manga.
*
* @param manga the manga whose sync have to be restored.
* @param tracks the track list to restore.
*/
internal fun restoreTrackForManga(manga: Manga, tracks: List<Track>) {
// Fix foreign keys with the current manga id
tracks.map { it.manga_id = manga.id!! }
// Get tracks from database
val dbTracks = databaseHelper.getTracks(manga).executeAsBlocking()
val trackToUpdate = mutableListOf<Track>()
tracks.forEach { track ->
var isInDatabase = false
for (dbTrack in dbTracks) {
if (track.sync_id == dbTrack.sync_id) {
// The sync is already in the db, only update its fields
if (track.media_id != dbTrack.media_id) {
dbTrack.media_id = track.media_id
}
if (track.library_id != dbTrack.library_id) {
dbTrack.library_id = track.library_id
}
dbTrack.last_chapter_read = max(dbTrack.last_chapter_read, track.last_chapter_read)
isInDatabase = true
trackToUpdate.add(dbTrack)
break
}
}
if (!isInDatabase) {
// Insert new sync. Let the db assign the id
track.id = null
trackToUpdate.add(track)
}
}
// Update database
if (trackToUpdate.isNotEmpty()) {
databaseHelper.insertTracks(trackToUpdate).executeAsBlocking()
}
}
internal fun restoreChaptersForManga(manga: Manga, chapters: List<Chapter>) {
val dbChapters = databaseHelper.getChapters(manga).executeAsBlocking()
chapters.forEach { chapter ->
val dbChapter = dbChapters.find { it.url == chapter.url }
if (dbChapter != null) {
chapter.id = dbChapter.id
chapter.copyFrom(dbChapter)
if (dbChapter.read && !chapter.read) {
chapter.read = dbChapter.read
chapter.last_page_read = dbChapter.last_page_read
} else if (chapter.last_page_read == 0 && dbChapter.last_page_read != 0) {
chapter.last_page_read = dbChapter.last_page_read
}
if (!chapter.bookmark && dbChapter.bookmark) {
chapter.bookmark = dbChapter.bookmark
}
}
chapter.manga_id = manga.id
}
val newChapters = chapters.groupBy { it.id != null }
newChapters[true]?.let { updateKnownChapters(it) }
newChapters[false]?.let { insertChapters(it) }
}
}
| apache-2.0 | 9b8d06775dd180c5e985bc32a22f75a4 | 38.37883 | 121 | 0.599278 | 5.025595 | false | false | false | false |
y2k/RssReader | app/src/main/kotlin/y2k/rssreader/components/SubscriptionComponent.kt | 1 | 1573 | package y2k.rssreader.components
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ListView
import android.widget.TextView
import y2k.rssreader.Provider.selectSubscription
import y2k.rssreader.RssSubscription
import y2k.rssreader.getSubscriptions
import y2k.rssreader.toLiveCycleObservable
/**
* Created by y2k on 21/08/16.
*/
class SubscriptionComponent(context: Context, attrs: AttributeSet?) : ListView(context, attrs) {
init {
getSubscriptions()
.toLiveCycleObservable(context)
.subscribe { subs ->
adapter = object : BaseAdapter() {
override fun getView(index: Int, view: View?, parent: ViewGroup?): View {
val v = view ?: View.inflate(context, android.R.layout.simple_list_item_2, null)
val i = subs[index]
(v.findViewById(android.R.id.text1) as TextView).text = i.title
(v.findViewById(android.R.id.text2) as TextView).text = i.url
return v
}
override fun getCount() = subs.size
override fun getItemId(index: Int) = index.toLong()
override fun getItem(index: Int) = TODO()
}
}
setOnItemClickListener { adapterView, view, index, id ->
selectSubscription(adapter.getItem(index) as RssSubscription)
}
}
} | mit | 5f083a994ecc1519d4d220398819100a | 34.772727 | 104 | 0.615385 | 4.546243 | false | false | false | false |
Kotlin/dokka | plugins/base/src/test/kotlin/transformers/ModuleAndPackageDocumentationTransformerUnitTest.kt | 1 | 10256 | package transformers
import org.jetbrains.dokka.base.transformers.documentables.ModuleAndPackageDocumentationReader
import org.jetbrains.dokka.base.transformers.documentables.ModuleAndPackageDocumentationTransformer
import org.jetbrains.dokka.links.DRI
import org.jetbrains.dokka.model.DModule
import org.jetbrains.dokka.model.DPackage
import org.jetbrains.dokka.model.SourceSetDependent
import org.jetbrains.dokka.model.doc.DocumentationNode
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import testApi.testRunner.dPackage
import testApi.testRunner.documentationNode
import testApi.testRunner.sourceSet
class ModuleAndPackageDocumentationTransformerUnitTest {
@Test
fun `empty list of modules`() {
val transformer = ModuleAndPackageDocumentationTransformer(
object : ModuleAndPackageDocumentationReader {
override fun get(module: DModule): SourceSetDependent<DocumentationNode> = throw NotImplementedError()
override fun get(pkg: DPackage): SourceSetDependent<DocumentationNode> = throw NotImplementedError()
}
)
assertEquals(
emptyList<DModule>(), transformer(emptyList()),
)
}
@Test
fun `single module documentation`() {
val transformer = ModuleAndPackageDocumentationTransformer(
object : ModuleAndPackageDocumentationReader {
override fun get(pkg: DPackage): SourceSetDependent<DocumentationNode> = throw NotImplementedError()
override fun get(module: DModule): SourceSetDependent<DocumentationNode> {
return module.sourceSets.associateWith { sourceSet ->
documentationNode("doc" + sourceSet.displayName)
}
}
}
)
val result = transformer(
listOf(
DModule(
"ModuleName",
documentation = emptyMap(),
packages = emptyList(),
sourceSets = setOf(
sourceSet("A"),
sourceSet("B")
)
)
)
)
assertEquals(
DModule(
"ModuleName",
documentation = mapOf(
sourceSet("A") to documentationNode("docA"),
sourceSet("B") to documentationNode("docB")
),
sourceSets = setOf(sourceSet("A"), sourceSet("B")),
packages = emptyList()
),
result.single()
)
}
@Test
fun `merges with already existing module documentation`() {
val transformer = ModuleAndPackageDocumentationTransformer(
object : ModuleAndPackageDocumentationReader {
override fun get(pkg: DPackage): SourceSetDependent<DocumentationNode> = throw NotImplementedError()
override fun get(module: DModule): SourceSetDependent<DocumentationNode> {
/* Only add documentation for first source set */
return module.sourceSets.take(1).associateWith { sourceSet ->
documentationNode("doc" + sourceSet.displayName)
}
}
}
)
val result = transformer(
listOf(
DModule(
"MyModule",
documentation = mapOf(
sourceSet("A") to documentationNode("pre-existing:A"),
sourceSet("B") to documentationNode("pre-existing:B")
),
sourceSets = setOf(sourceSet("A"), sourceSet("B")),
packages = emptyList()
)
)
)
assertEquals(
DModule(
"MyModule",
documentation = mapOf(
/* Expect previous documentation and newly attached one */
sourceSet("A") to documentationNode("pre-existing:A", "docA"),
/* Only first source set will get documentation attached */
sourceSet("B") to documentationNode("pre-existing:B")
),
sourceSets = setOf(sourceSet("A"), sourceSet("B")),
packages = emptyList()
),
result.single()
)
}
@Test
fun `package documentation`() {
val transformer = ModuleAndPackageDocumentationTransformer(
object : ModuleAndPackageDocumentationReader {
override fun get(module: DModule): SourceSetDependent<DocumentationNode> = emptyMap()
override fun get(pkg: DPackage): SourceSetDependent<DocumentationNode> {
/* Only attach documentation to packages with 'attach' */
if ("attach" !in pkg.dri.packageName.orEmpty()) return emptyMap()
/* Only attach documentation to two source sets */
return pkg.sourceSets.take(2).associateWith { sourceSet ->
documentationNode("doc:${sourceSet.displayName}:${pkg.dri.packageName}")
}
}
}
)
val result = transformer(
listOf(
DModule(
"MyModule",
documentation = emptyMap(),
sourceSets = emptySet(),
packages = listOf(
dPackage(
dri = DRI("com.sample"),
documentation = mapOf(
sourceSet("A") to documentationNode("pre-existing:A:com.sample")
),
sourceSets = setOf(sourceSet("A"), sourceSet("B"), sourceSet("C")),
),
dPackage(
dri = DRI("com.attach"),
documentation = mapOf(
sourceSet("A") to documentationNode("pre-existing:A:com.attach")
),
sourceSets = setOf(sourceSet("A"), sourceSet("B"), sourceSet("C"))
),
dPackage(
dri = DRI("com.attach.sub"),
documentation = mapOf(
sourceSet("A") to documentationNode("pre-existing:A:com.attach.sub"),
sourceSet("B") to documentationNode("pre-existing:B:com.attach.sub"),
sourceSet("C") to documentationNode("pre-existing:C:com.attach.sub")
),
sourceSets = setOf(sourceSet("A"), sourceSet("B"), sourceSet("C")),
)
)
)
)
)
result.single().packages.forEach { pkg ->
assertEquals(
setOf(sourceSet("A"), sourceSet("B"), sourceSet("C")), pkg.sourceSets,
"Expected source sets A, B, C for package ${pkg.dri.packageName}"
)
}
val comSample = result.single().packages.single { it.dri.packageName == "com.sample" }
assertEquals(
mapOf(sourceSet("A") to documentationNode("pre-existing:A:com.sample")),
comSample.documentation,
"Expected no documentation added to package 'com.sample' because of wrong package"
)
val comAttach = result.single().packages.single { it.dri.packageName == "com.attach" }
assertEquals(
mapOf(
sourceSet("A") to documentationNode("pre-existing:A:com.attach", "doc:A:com.attach"),
sourceSet("B") to documentationNode("doc:B:com.attach")
),
comAttach.documentation,
"Expected documentation added to source sets A and B"
)
assertEquals(
DModule(
"MyModule",
documentation = emptyMap(),
sourceSets = emptySet(),
packages = listOf(
dPackage(
dri = DRI("com.sample"),
documentation = mapOf(
/* No documentation added, since in wrong package */
sourceSet("A") to documentationNode("pre-existing:A:com.sample")
),
sourceSets = setOf(sourceSet("A"), sourceSet("B"), sourceSet("C")),
),
dPackage(
dri = DRI("com.attach"),
documentation = mapOf(
/* Documentation added */
sourceSet("A") to documentationNode("pre-existing:A:com.attach", "doc:A:com.attach"),
sourceSet("B") to documentationNode("doc:B:com.attach")
),
sourceSets = setOf(sourceSet("A"), sourceSet("B"), sourceSet("C")),
),
dPackage(
dri = DRI("com.attach.sub"),
documentation = mapOf(
/* Documentation added */
sourceSet("A") to documentationNode(
"pre-existing:A:com.attach.sub",
"doc:A:com.attach.sub"
),
/* Documentation added */
sourceSet("B") to documentationNode(
"pre-existing:B:com.attach.sub",
"doc:B:com.attach.sub"
),
/* No documentation added, since in wrong source set */
sourceSet("C") to documentationNode("pre-existing:C:com.attach.sub")
),
sourceSets = setOf(sourceSet("A"), sourceSet("B"), sourceSet("C")),
)
)
), result.single()
)
}
}
| apache-2.0 | b4f14a7443dfeec24136c8f41d5f94c1 | 41.380165 | 118 | 0.4922 | 6.200726 | false | false | false | false |
Commit451/LabCoat | app/src/main/java/com/commit451/gitlab/model/api/ProjectNamespace.kt | 2 | 868 | package com.commit451.gitlab.model.api
import android.os.Parcelable
import com.squareup.moshi.Json
import kotlinx.android.parcel.Parcelize
import java.util.Date
@Parcelize
data class ProjectNamespace(
@Json(name = "id")
var id: Long = 0,
@Json(name = "name")
var name: String? = null,
@Json(name = "path")
var path: String? = null,
@Json(name = "owner_id")
var ownerId: Long = 0,
@Json(name = "created_at")
var createdAt: Date? = null,
@Json(name = "updated_at")
var updatedAt: Date? = null,
@Json(name = "description")
var description: String? = null,
@Json(name = "avatar")
var avatar: Avatar? = null,
@Json(name = "public")
var isPublic: Boolean = false
) : Parcelable {
@Parcelize
data class Avatar(
@Json(name = "url")
var url: String? = null
) : Parcelable
}
| apache-2.0 | 89f232fbbcf15917473ac17cee1e4648 | 23.8 | 39 | 0.618664 | 3.403922 | false | false | false | false |
fnberta/PopularMovies | app/src/main/java/ch/berta/fabio/popularmovies/features/grid/component/Navigation.kt | 1 | 2142 | /*
* Copyright (c) 2017 Fabio Berta
*
* 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 ch.berta.fabio.popularmovies.features.grid.component
import ch.berta.fabio.popularmovies.NavigationTarget
import ch.berta.fabio.popularmovies.R
import ch.berta.fabio.popularmovies.features.details.view.DetailsActivity
import ch.berta.fabio.popularmovies.features.details.view.DetailsArgs
import ch.berta.fabio.popularmovies.features.grid.SortOption
import io.reactivex.Observable
import io.reactivex.functions.BiFunction
const val RQ_DETAILS = 1
fun navigationTargets(actions: Observable<GridAction>): Observable<NavigationTarget> {
val sortSelections = actions
.ofType(GridAction.SortSelection::class.java)
val movieClicks = actions
.ofType(GridAction.MovieClick::class.java)
.withLatestFrom(sortSelections,
BiFunction<GridAction.MovieClick, GridAction.SortSelection, NavigationTarget>
{ (selectedMovie), (sort) ->
val args = DetailsArgs(selectedMovie.id, selectedMovie.title, selectedMovie.releaseDate,
selectedMovie.overview, selectedMovie.voteAverage, selectedMovie.poster,
selectedMovie.backdrop, sort.option == SortOption.SORT_FAVORITE)
NavigationTarget.Activity(DetailsActivity::class.java, args, RQ_DETAILS,
selectedMovie.posterView, R.string.shared_transition_details_poster)
})
val navigationTargets = listOf(movieClicks)
return Observable.merge(navigationTargets)
}
| apache-2.0 | cd353ca084918ff919cebe15f405fc79 | 44.574468 | 112 | 0.711485 | 4.666667 | false | false | false | false |
team401/2017-Robot-Code | src/main/java/org/team401/lib/MotionProfileParser.kt | 1 | 1117 | package org.team401.lib
import java.io.File
import java.util.ArrayList
object MotionProfileParser {
/**
* Parses a motion profile from a .csv file. Returns an empty profile if any error occurs.
*/
fun parse(name: String, path: String): MotionProfile {
val empty = MotionProfile(name, DoubleArray(0), DoubleArray(0), IntArray(0))
val file = File(path)
val lines = try {
file.readLines()
} catch (e: Exception) {
println("Could not find motion profile $path")
CrashTracker.logThrowableCrash(e)
return empty
}
val positions = ArrayList<Double>()
val speeds = ArrayList<Double>()
val durations = ArrayList<Int>()
try {
lines.forEach {
val entries = it.substring(1, it.length - 3).split(",")
positions.add(entries[0].toDouble())
speeds.add(entries[1].toDouble())
durations.add((entries[2].toDouble() + .5).toInt())
}
} catch (e: Exception) {
print("Could not parse motion profile $path")
CrashTracker.logThrowableCrash(e)
return empty
}
return MotionProfile(name, positions.toDoubleArray(), speeds.toDoubleArray(), durations.toIntArray())
}
} | gpl-3.0 | 2b5f128a43a414bc37921812cf7157eb | 26.268293 | 103 | 0.689346 | 3.468944 | false | false | false | false |
HerbLuo/shop-api | src/main/java/cn/cloudself/model/CarEntity.kt | 1 | 745 | package cn.cloudself.model
import javax.persistence.*
/**
* @author HerbLuo
* @version 1.0.0.d
*/
@Entity
@Table(name = "car", schema = "shop")
data class CarEntity(
@get:Id
@get:Column(name = "id", nullable = false)
@get:GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Int = 0,
@get:Basic
@get:Column(name = "user_id", nullable = false)
var userId: Int = 0,
@Suppress("MemberVisibilityCanPrivate")
@get:ManyToOne
@get:JoinColumn(name = "item_id", referencedColumnName = "id", nullable = false)
var item: ItemEntity? = null
) {
constructor(id: Int, item: ItemEntity?) : this() {
this.id = id
this.item = item
}
}
| mit | 1fcec32befe0d80d5136df35f3712fe6 | 22.28125 | 88 | 0.585235 | 3.599034 | false | false | false | false |
paronos/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupRestoreService.kt | 2 | 17318 | package eu.kanade.tachiyomi.data.backup
import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.IBinder
import android.os.PowerManager
import com.github.salomonbrys.kotson.fromJson
import com.google.gson.JsonArray
import com.google.gson.JsonParser
import com.google.gson.stream.JsonReader
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.backup.models.Backup.CATEGORIES
import eu.kanade.tachiyomi.data.backup.models.Backup.CHAPTERS
import eu.kanade.tachiyomi.data.backup.models.Backup.HISTORY
import eu.kanade.tachiyomi.data.backup.models.Backup.MANGA
import eu.kanade.tachiyomi.data.backup.models.Backup.MANGAS
import eu.kanade.tachiyomi.data.backup.models.Backup.TRACK
import eu.kanade.tachiyomi.data.backup.models.Backup.VERSION
import eu.kanade.tachiyomi.data.backup.models.DHistory
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.*
import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.util.chop
import eu.kanade.tachiyomi.util.isServiceRunning
import eu.kanade.tachiyomi.util.sendLocalBroadcast
import rx.Observable
import rx.Subscription
import rx.schedulers.Schedulers
import timber.log.Timber
import uy.kohesive.injekt.injectLazy
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
/**
* Restores backup from json file
*/
class BackupRestoreService : Service() {
companion object {
/**
* Returns the status of the service.
*
* @param context the application context.
* @return true if the service is running, false otherwise.
*/
private fun isRunning(context: Context): Boolean =
context.isServiceRunning(BackupRestoreService::class.java)
/**
* Starts a service to restore a backup from Json
*
* @param context context of application
* @param uri path of Uri
*/
fun start(context: Context, uri: Uri) {
if (!isRunning(context)) {
val intent = Intent(context, BackupRestoreService::class.java).apply {
putExtra(BackupConst.EXTRA_URI, uri)
}
context.startService(intent)
}
}
/**
* Stops the service.
*
* @param context the application context.
*/
fun stop(context: Context) {
context.stopService(Intent(context, BackupRestoreService::class.java))
}
}
/**
* Wake lock that will be held until the service is destroyed.
*/
private lateinit var wakeLock: PowerManager.WakeLock
/**
* Subscription where the update is done.
*/
private var subscription: Subscription? = null
/**
* The progress of a backup restore
*/
private var restoreProgress = 0
/**
* Amount of manga in Json file (needed for restore)
*/
private var restoreAmount = 0
/**
* List containing errors
*/
private val errors = mutableListOf<Pair<Date, String>>()
/**
* Backup manager
*/
private lateinit var backupManager: BackupManager
/**
* Database
*/
private val db: DatabaseHelper by injectLazy()
/**
* Tracking manager
*/
internal val trackManager: TrackManager by injectLazy()
private lateinit var executor: ExecutorService
/**
* Method called when the service is created. It injects dependencies and acquire the wake lock.
*/
override fun onCreate() {
super.onCreate()
wakeLock = (getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "BackupRestoreService:WakeLock")
wakeLock.acquire()
executor = Executors.newSingleThreadExecutor()
}
/**
* Method called when the service is destroyed. It destroys the running subscription and
* releases the wake lock.
*/
override fun onDestroy() {
subscription?.unsubscribe()
executor.shutdown() // must be called after unsubscribe
if (wakeLock.isHeld) {
wakeLock.release()
}
super.onDestroy()
}
/**
* This method needs to be implemented, but it's not used/needed.
*/
override fun onBind(intent: Intent): IBinder? = null
/**
* Method called when the service receives an intent.
*
* @param intent the start intent from.
* @param flags the flags of the command.
* @param startId the start id of this command.
* @return the start value of the command.
*/
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent == null) return Service.START_NOT_STICKY
val uri = intent.getParcelableExtra<Uri>(BackupConst.EXTRA_URI)
// Unsubscribe from any previous subscription if needed.
subscription?.unsubscribe()
subscription = Observable.using(
{ db.lowLevel().beginTransaction() },
{ getRestoreObservable(uri).doOnNext { db.lowLevel().setTransactionSuccessful() } },
{ executor.execute { db.lowLevel().endTransaction() } })
.doAfterTerminate { stopSelf(startId) }
.subscribeOn(Schedulers.from(executor))
.subscribe()
return Service.START_NOT_STICKY
}
/**
* Returns an [Observable] containing restore process.
*
* @param uri restore file
* @return [Observable<Manga>]
*/
private fun getRestoreObservable(uri: Uri): Observable<List<Manga>> {
val startTime = System.currentTimeMillis()
return Observable.just(Unit)
.map {
val reader = JsonReader(contentResolver.openInputStream(uri).bufferedReader())
val json = JsonParser().parse(reader).asJsonObject
// Get parser version
val version = json.get(VERSION)?.asInt ?: 1
// Initialize manager
backupManager = BackupManager(this, version)
val mangasJson = json.get(MANGAS).asJsonArray
restoreAmount = mangasJson.size() + 1 // +1 for categories
restoreProgress = 0
errors.clear()
// Restore categories
json.get(CATEGORIES)?.let {
backupManager.restoreCategories(it.asJsonArray)
restoreProgress += 1
showRestoreProgress(restoreProgress, restoreAmount, "Categories added", errors.size)
}
mangasJson
}
.flatMap { Observable.from(it) }
.concatMap {
val obj = it.asJsonObject
val manga = backupManager.parser.fromJson<MangaImpl>(obj.get(MANGA))
val chapters = backupManager.parser.fromJson<List<ChapterImpl>>(obj.get(CHAPTERS) ?: JsonArray())
val categories = backupManager.parser.fromJson<List<String>>(obj.get(CATEGORIES) ?: JsonArray())
val history = backupManager.parser.fromJson<List<DHistory>>(obj.get(HISTORY) ?: JsonArray())
val tracks = backupManager.parser.fromJson<List<TrackImpl>>(obj.get(TRACK) ?: JsonArray())
val observable = getMangaRestoreObservable(manga, chapters, categories, history, tracks)
if (observable != null) {
observable
} else {
errors.add(Date() to "${manga.title} - ${getString(R.string.source_not_found)}")
restoreProgress += 1
val content = getString(R.string.dialog_restoring_source_not_found, manga.title.chop(15))
showRestoreProgress(restoreProgress, restoreAmount, manga.title, errors.size, content)
Observable.just(manga)
}
}
.toList()
.doOnNext {
val endTime = System.currentTimeMillis()
val time = endTime - startTime
val logFile = writeErrorLog()
val completeIntent = Intent(BackupConst.INTENT_FILTER).apply {
putExtra(BackupConst.EXTRA_TIME, time)
putExtra(BackupConst.EXTRA_ERRORS, errors.size)
putExtra(BackupConst.EXTRA_ERROR_FILE_PATH, logFile.parent)
putExtra(BackupConst.EXTRA_ERROR_FILE, logFile.name)
putExtra(BackupConst.ACTION, BackupConst.ACTION_RESTORE_COMPLETED_DIALOG)
}
sendLocalBroadcast(completeIntent)
}
.doOnError { error ->
Timber.e(error)
writeErrorLog()
val errorIntent = Intent(BackupConst.INTENT_FILTER).apply {
putExtra(BackupConst.ACTION, BackupConst.ACTION_ERROR_RESTORE_DIALOG)
putExtra(BackupConst.EXTRA_ERROR_MESSAGE, error.message)
}
sendLocalBroadcast(errorIntent)
}
.onErrorReturn { emptyList() }
}
/**
* Write errors to error log
*/
private fun writeErrorLog(): File {
try {
if (errors.isNotEmpty()) {
val destFile = File(externalCacheDir, "tachiyomi_restore.log")
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault())
destFile.bufferedWriter().use { out ->
errors.forEach { (date, message) ->
out.write("[${sdf.format(date)}] $message\n")
}
}
return destFile
}
} catch (e: Exception) {
// Empty
}
return File("")
}
/**
* Returns a manga restore observable
*
* @param manga manga data from json
* @param chapters chapters data from json
* @param categories categories data from json
* @param history history data from json
* @param tracks tracking data from json
* @return [Observable] containing manga restore information
*/
private fun getMangaRestoreObservable(manga: Manga, chapters: List<Chapter>,
categories: List<String>, history: List<DHistory>,
tracks: List<Track>): Observable<Manga>? {
// Get source
val source = backupManager.sourceManager.get(manga.source) ?: return null
val dbManga = backupManager.getMangaFromDatabase(manga)
return if (dbManga == null) {
// Manga not in database
mangaFetchObservable(source, manga, chapters, categories, history, tracks)
} else { // Manga in database
// Copy information from manga already in database
backupManager.restoreMangaNoFetch(manga, dbManga)
// Fetch rest of manga information
mangaNoFetchObservable(source, manga, chapters, categories, history, tracks)
}
}
/**
* [Observable] that fetches manga information
*
* @param manga manga that needs updating
* @param chapters chapters of manga that needs updating
* @param categories categories that need updating
*/
private fun mangaFetchObservable(source: Source, manga: Manga, chapters: List<Chapter>,
categories: List<String>, history: List<DHistory>,
tracks: List<Track>): Observable<Manga> {
return backupManager.restoreMangaFetchObservable(source, manga)
.onErrorReturn {
errors.add(Date() to "${manga.title} - ${it.message}")
manga
}
.filter { it.id != null }
.flatMap {
chapterFetchObservable(source, it, chapters)
// Convert to the manga that contains new chapters.
.map { manga }
}
.doOnNext {
restoreExtraForManga(it, categories, history, tracks)
}
.flatMap {
trackingFetchObservable(it, tracks)
// Convert to the manga that contains new chapters.
.map { manga }
}
.doOnCompleted {
restoreProgress += 1
showRestoreProgress(restoreProgress, restoreAmount, manga.title, errors.size)
}
}
private fun mangaNoFetchObservable(source: Source, backupManga: Manga, chapters: List<Chapter>,
categories: List<String>, history: List<DHistory>,
tracks: List<Track>): Observable<Manga> {
return Observable.just(backupManga)
.flatMap { manga ->
if (!backupManager.restoreChaptersForManga(manga, chapters)) {
chapterFetchObservable(source, manga, chapters)
.map { manga }
} else {
Observable.just(manga)
}
}
.doOnNext {
restoreExtraForManga(it, categories, history, tracks)
}
.flatMap { manga ->
trackingFetchObservable(manga, tracks)
// Convert to the manga that contains new chapters.
.map { manga }
}
.doOnCompleted {
restoreProgress += 1
showRestoreProgress(restoreProgress, restoreAmount, backupManga.title, errors.size)
}
}
private fun restoreExtraForManga(manga: Manga, categories: List<String>, history: List<DHistory>, tracks: List<Track>) {
// Restore categories
backupManager.restoreCategoriesForManga(manga, categories)
// Restore history
backupManager.restoreHistoryForManga(history)
// Restore tracking
backupManager.restoreTrackForManga(manga, tracks)
}
/**
* [Observable] that fetches chapter information
*
* @param source source of manga
* @param manga manga that needs updating
* @return [Observable] that contains manga
*/
private fun chapterFetchObservable(source: Source, manga: Manga, chapters: List<Chapter>): Observable<Pair<List<Chapter>, List<Chapter>>> {
return backupManager.restoreChapterFetchObservable(source, manga, chapters)
// If there's any error, return empty update and continue.
.onErrorReturn {
errors.add(Date() to "${manga.title} - ${it.message}")
Pair(emptyList(), emptyList())
}
}
/**
* [Observable] that refreshes tracking information
* @param manga manga that needs updating.
* @param tracks list containing tracks from restore file.
* @return [Observable] that contains updated track item
*/
private fun trackingFetchObservable(manga: Manga, tracks: List<Track>): Observable<Track> {
return Observable.from(tracks)
.concatMap { track ->
val service = trackManager.getService(track.sync_id)
if (service != null && service.isLogged) {
service.refresh(track)
.doOnNext { db.insertTrack(it).executeAsBlocking() }
.onErrorReturn {
errors.add(Date() to "${manga.title} - ${it.message}")
track
}
} else {
errors.add(Date() to "${manga.title} - ${service?.name} not logged in")
Observable.empty()
}
}
}
/**
* Called to update dialog in [BackupConst]
*
* @param progress restore progress
* @param amount total restoreAmount of manga
* @param title title of restored manga
*/
private fun showRestoreProgress(progress: Int, amount: Int, title: String, errors: Int,
content: String = getString(R.string.dialog_restoring_backup, title.chop(15))) {
val intent = Intent(BackupConst.INTENT_FILTER).apply {
putExtra(BackupConst.EXTRA_PROGRESS, progress)
putExtra(BackupConst.EXTRA_AMOUNT, amount)
putExtra(BackupConst.EXTRA_CONTENT, content)
putExtra(BackupConst.EXTRA_ERRORS, errors)
putExtra(BackupConst.ACTION, BackupConst.ACTION_SET_PROGRESS_DIALOG)
}
sendLocalBroadcast(intent)
}
} | apache-2.0 | 892bc6580a52174793053e93c0f6a9f6 | 38.006757 | 143 | 0.573912 | 5.350015 | false | false | false | false |
Devexperts/lin-check | lincheck/src/main/java/com/devexperts/dxlab/lincheck/verifier/linearizability/LinearizabilityVerifier.kt | 1 | 3843 | package com.devexperts.dxlab.lincheck.verifier.linearizability
/*
* #%L
* Lincheck
* %%
* Copyright (C) 2015 - 2018 Devexperts, LLC
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
import com.devexperts.dxlab.lincheck.execution.ExecutionResult
import com.devexperts.dxlab.lincheck.execution.ExecutionScenario
import com.devexperts.dxlab.lincheck.verifier.*
/**
* This verifier checks that the specified results could be happen in linearizable execution,
* for what it tries to find a possible linear execution which transitions does not violate both
* regular LTS (see [LTS] and [RegularLTS]) transitions and the happens-before order. Essentially,
* it just tries to execute the next actor in each thread and goes deeper until all actors are executed.
*
* This verifier is based on [AbstractLTSVerifier] and caches the already processed results
* for performance improvement (see [CachedVerifier]).
*/
class LinearizabilityVerifier(scenario: ExecutionScenario, testClass : Class<*>) : AbstractLTSVerifier<RegularLTS.State>(scenario, testClass) {
override fun createInitialContext(results: ExecutionResult): LTSContext<RegularLTS.State>
= LinearizabilityContext(scenario, RegularLTS(testClass).initialState, results)
}
/**
* Next possible states are determined lazily by trying to execute next actor in order for every thread
*
* Current state of scenario execution is represented with the number of actors executed in every thread
*/
private class LinearizabilityContext(scenario: ExecutionScenario,
state: RegularLTS.State,
executed: IntArray,
val results: ExecutionResult
) : LTSContext<RegularLTS.State>(scenario, state, executed) {
constructor(scenario: ExecutionScenario, state: RegularLTS.State, results: ExecutionResult)
: this(scenario, state, IntArray(scenario.threads + 2), results)
override fun nextContexts(threadId: Int): List<LinearizabilityContext> {
// Check if there are unprocessed actors in the specified thread
if (isCompleted(threadId)) return emptyList()
// Check whether an actor from the specified thread can be executed
// in accordance with the rule that all actors from init part should be
// executed at first, after that all actors from parallel part, and
// all actors from post part should be executed at last.
val legal = when (threadId) {
0 -> true // INIT: we already checked that there is an unprocessed actor
in 1 .. scenario.threads -> initCompleted // PARALLEL
else -> initCompleted && parallelCompleted // POST
}
if (!legal) return emptyList()
// Check whether the transition is possible in LTS
val i = executed[threadId]
val nextState = state.next(scenario[threadId][i], results[threadId][i]) ?: return emptyList()
// The transition is possible, create a new context
val nextExecuted = executed.copyOf()
nextExecuted[threadId]++
return listOf(LinearizabilityContext(scenario, nextState, nextExecuted, results))
}
}
| lgpl-3.0 | acbf5f0475bbc4b843c1cce8db0632ed | 48.269231 | 143 | 0.711423 | 4.791771 | false | false | false | false |
abreslav/androidVNC | androidVNC/src/com/example/adsl/Properties.kt | 1 | 39404 | package com.example.adsl
import android.view.ContextMenu
import android.view.ViewGroup
import android.content.Context
import android.widget.*
import android.app.AlertDialog
import android.widget.LinearLayout.LayoutParams
import android.view.View
var android.app.MediaRouteButton.routeTypes: Int
get() = getRouteTypes()
set(value) = setRouteTypes(value)
val _AppWidgetHostView.appWidgetId: Int
get() = viewGroup.getAppWidgetId()
val _AppWidgetHostView.appWidgetInfo: android.appwidget.AppWidgetProviderInfo?
get() = viewGroup.getAppWidgetInfo()
val _GestureOverlayView.currentStroke: java.util.ArrayList<android.gesture.GesturePoint>
get() = viewGroup.getCurrentStroke()
var _GestureOverlayView.eventsInterceptionEnabled: Boolean
get() = viewGroup.isEventsInterceptionEnabled()
set(value) = viewGroup.setEventsInterceptionEnabled(value)
var _GestureOverlayView.fadeEnabled: Boolean
get() = viewGroup.isFadeEnabled()
set(value) = viewGroup.setFadeEnabled(value)
var _GestureOverlayView.fadeOffset: Long
get() = viewGroup.getFadeOffset()
set(value) = viewGroup.setFadeOffset(value)
var _GestureOverlayView.gesture: android.gesture.Gesture?
get() = viewGroup.getGesture()
set(value) = viewGroup.setGesture(value!!)
var _GestureOverlayView.gestureColor: Int
get() = viewGroup.getGestureColor()
set(value) = viewGroup.setGestureColor(value)
val _GestureOverlayView.gesturePath: android.graphics.Path?
get() = viewGroup.getGesturePath()
var _GestureOverlayView.gestureStrokeAngleThreshold: Float
get() = viewGroup.getGestureStrokeAngleThreshold()
set(value) = viewGroup.setGestureStrokeAngleThreshold(value)
var _GestureOverlayView.gestureStrokeLengthThreshold: Float
get() = viewGroup.getGestureStrokeLengthThreshold()
set(value) = viewGroup.setGestureStrokeLengthThreshold(value)
var _GestureOverlayView.gestureStrokeSquarenessTreshold: Float
get() = viewGroup.getGestureStrokeSquarenessTreshold()
set(value) = viewGroup.setGestureStrokeSquarenessTreshold(value)
var _GestureOverlayView.gestureStrokeType: Int
get() = viewGroup.getGestureStrokeType()
set(value) = viewGroup.setGestureStrokeType(value)
var _GestureOverlayView.gestureStrokeWidth: Float
get() = viewGroup.getGestureStrokeWidth()
set(value) = viewGroup.setGestureStrokeWidth(value)
var _GestureOverlayView.gestureVisible: Boolean
get() = viewGroup.isGestureVisible()
set(value) = viewGroup.setGestureVisible(value)
val _GestureOverlayView.gesturing: Boolean
get() = viewGroup.isGesturing()
var _GestureOverlayView.orientation: Int
get() = viewGroup.getOrientation()
set(value) = viewGroup.setOrientation(value)
var _GestureOverlayView.uncertainGestureColor: Int
get() = viewGroup.getUncertainGestureColor()
set(value) = viewGroup.setUncertainGestureColor(value)
val android.inputmethodservice.ExtractEditText.focused: Boolean
get() = isFocused()
val android.inputmethodservice.ExtractEditText.inputMethodTarget: Boolean
get() = isInputMethodTarget()
var android.inputmethodservice.KeyboardView.keyboard: android.inputmethodservice.Keyboard?
get() = getKeyboard()
set(value) = setKeyboard(value!!)
var android.inputmethodservice.KeyboardView.previewEnabled: Boolean
get() = isPreviewEnabled()
set(value) = setPreviewEnabled(value)
var android.inputmethodservice.KeyboardView.proximityCorrectionEnabled: Boolean
get() = isProximityCorrectionEnabled()
set(value) = setProximityCorrectionEnabled(value)
var android.opengl.GLSurfaceView.debugFlags: Int
get() = getDebugFlags()
set(value) = setDebugFlags(value)
var android.opengl.GLSurfaceView.preserveEGLContextOnPause: Boolean
get() = getPreserveEGLContextOnPause()
set(value) = setPreserveEGLContextOnPause(value)
var android.opengl.GLSurfaceView.renderMode: Int
get() = getRenderMode()
set(value) = setRenderMode(value)
var android.renderscript.RSSurfaceView.renderScriptGL: android.renderscript.RenderScriptGL?
get() = getRenderScriptGL()
set(value) = setRenderScriptGL(value!!)
var android.renderscript.RSTextureView.renderScriptGL: android.renderscript.RenderScriptGL?
get() = getRenderScriptGL()
set(value) = setRenderScriptGL(value!!)
val android.view.SurfaceView.holder: android.view.SurfaceHolder?
get() = getHolder()
val android.view.TextureView.available: Boolean
get() = isAvailable()
val android.view.TextureView.bitmap: android.graphics.Bitmap?
get() = getBitmap()
val android.view.TextureView.layerType: Int
get() = getLayerType()
var android.view.TextureView.opaque: Boolean
get() = isOpaque()
set(value) = setOpaque(value)
var android.view.TextureView.surfaceTexture: android.graphics.SurfaceTexture?
get() = getSurfaceTexture()
set(value) = setSurfaceTexture(value!!)
var android.view.TextureView.surfaceTextureListener: android.view.TextureView.SurfaceTextureListener?
get() = getSurfaceTextureListener()
set(value) = setSurfaceTextureListener(value!!)
var android.view.ViewGroup.alwaysDrawnWithCacheEnabled: Boolean
get() = isAlwaysDrawnWithCacheEnabled()
set(value) = setAlwaysDrawnWithCacheEnabled(value)
var android.view.ViewGroup.animationCacheEnabled: Boolean
get() = isAnimationCacheEnabled()
set(value) = setAnimationCacheEnabled(value)
val android.view.ViewGroup.childCount: Int
get() = getChildCount()
var android.view.ViewGroup.descendantFocusability: Int
get() = getDescendantFocusability()
set(value) = setDescendantFocusability(value)
val android.view.ViewGroup.focusedChild: android.view.View?
get() = getFocusedChild()
var android.view.ViewGroup.layoutAnimation: android.view.animation.LayoutAnimationController?
get() = getLayoutAnimation()
set(value) = setLayoutAnimation(value!!)
var android.view.ViewGroup.layoutAnimationListener: android.view.animation.Animation.AnimationListener?
get() = getLayoutAnimationListener()
set(value) = setLayoutAnimationListener(value!!)
var android.view.ViewGroup.layoutTransition: android.animation.LayoutTransition?
get() = getLayoutTransition()
set(value) = setLayoutTransition(value!!)
var android.view.ViewGroup.motionEventSplittingEnabled: Boolean
get() = isMotionEventSplittingEnabled()
set(value) = setMotionEventSplittingEnabled(value)
var android.view.ViewGroup.persistentDrawingCache: Int
get() = getPersistentDrawingCache()
set(value) = setPersistentDrawingCache(value)
var android.view.ViewStub.inflatedId: Int
get() = getInflatedId()
set(value) = setInflatedId(value)
var android.view.ViewStub.layoutInflater: android.view.LayoutInflater?
get() = getLayoutInflater()
set(value) = setLayoutInflater(value!!)
var android.view.ViewStub.layoutResource: Int
get() = getLayoutResource()
set(value) = setLayoutResource(value)
var _WebView.certificate: android.net.http.SslCertificate?
get() = viewGroup.getCertificate()
set(value) = viewGroup.setCertificate(value!!)
val _WebView.contentHeight: Int
get() = viewGroup.getContentHeight()
val _WebView.favicon: android.graphics.Bitmap?
get() = viewGroup.getFavicon()
val _WebView.hitTestResult: android.webkit.WebView.HitTestResult?
get() = viewGroup.getHitTestResult()
val _WebView.originalUrl: String?
get() = viewGroup.getOriginalUrl()
val _WebView.privateBrowsingEnabled: Boolean
get() = viewGroup.isPrivateBrowsingEnabled()
val _WebView.progress: Int
get() = viewGroup.getProgress()
val _WebView.scale: Float
get() = viewGroup.getScale()
val _WebView.settings: android.webkit.WebSettings?
get() = viewGroup.getSettings()
val _WebView.title: String?
get() = viewGroup.getTitle()
val _WebView.url: String?
get() = viewGroup.getUrl()
var android.widget.AbsSeekBar.keyProgressIncrement: Int
get() = getKeyProgressIncrement()
set(value) = setKeyProgressIncrement(value)
var android.widget.AbsSeekBar.thumb: android.graphics.drawable.Drawable?
get() = getThumb()
set(value) = setThumb(value!!)
var android.widget.AbsSeekBar.thumbOffset: Int
get() = getThumbOffset()
set(value) = setThumbOffset(value)
var _AdapterViewFlipper.autoStart: Boolean
get() = viewGroup.isAutoStart()
set(value) = viewGroup.setAutoStart(value)
var _AdapterViewFlipper.flipInterval: Int
get() = viewGroup.getFlipInterval()
set(value) = viewGroup.setFlipInterval(value)
val _AdapterViewFlipper.flipping: Boolean
get() = viewGroup.isFlipping()
var android.widget.AutoCompleteTextView.completionHint: CharSequence?
get() = getCompletionHint()
set(value) = setCompletionHint(value!!)
var android.widget.AutoCompleteTextView.dropDownAnchor: Int
get() = getDropDownAnchor()
set(value) = setDropDownAnchor(value)
val android.widget.AutoCompleteTextView.dropDownBackground: android.graphics.drawable.Drawable?
get() = getDropDownBackground()
var android.widget.AutoCompleteTextView.dropDownHeight: Int
get() = getDropDownHeight()
set(value) = setDropDownHeight(value)
var android.widget.AutoCompleteTextView.dropDownHorizontalOffset: Int
get() = getDropDownHorizontalOffset()
set(value) = setDropDownHorizontalOffset(value)
var android.widget.AutoCompleteTextView.dropDownVerticalOffset: Int
get() = getDropDownVerticalOffset()
set(value) = setDropDownVerticalOffset(value)
var android.widget.AutoCompleteTextView.dropDownWidth: Int
get() = getDropDownWidth()
set(value) = setDropDownWidth(value)
val android.widget.AutoCompleteTextView.itemClickListener: android.widget.AdapterView.OnItemClickListener?
get() = getItemClickListener()
val android.widget.AutoCompleteTextView.itemSelectedListener: android.widget.AdapterView.OnItemSelectedListener?
get() = getItemSelectedListener()
var android.widget.AutoCompleteTextView.listSelection: Int
get() = getListSelection()
set(value) = setListSelection(value)
var android.widget.AutoCompleteTextView.onItemClickListener: android.widget.AdapterView.OnItemClickListener?
get() = getOnItemClickListener()
set(value) = setOnItemClickListener(value!!)
var android.widget.AutoCompleteTextView.onItemSelectedListener: android.widget.AdapterView.OnItemSelectedListener?
get() = getOnItemSelectedListener()
set(value) = setOnItemSelectedListener(value!!)
val android.widget.AutoCompleteTextView.performingCompletion: Boolean
get() = isPerformingCompletion()
val android.widget.AutoCompleteTextView.popupShowing: Boolean
get() = isPopupShowing()
var android.widget.AutoCompleteTextView.threshold: Int
get() = getThreshold()
set(value) = setThreshold(value)
var android.widget.AutoCompleteTextView.validator: android.widget.AutoCompleteTextView.Validator?
get() = getValidator()
set(value) = setValidator(value!!)
var _CalendarView.date: Long
get() = viewGroup.getDate()
set(value) = viewGroup.setDate(value)
var _CalendarView.dateTextAppearance: Int
get() = viewGroup.getDateTextAppearance()
set(value) = viewGroup.setDateTextAppearance(value)
var _CalendarView.enabled: Boolean
get() = viewGroup.isEnabled()
set(value) = viewGroup.setEnabled(value)
var _CalendarView.firstDayOfWeek: Int
get() = viewGroup.getFirstDayOfWeek()
set(value) = viewGroup.setFirstDayOfWeek(value)
var _CalendarView.focusedMonthDateColor: Int
get() = viewGroup.getFocusedMonthDateColor()
set(value) = viewGroup.setFocusedMonthDateColor(value)
var _CalendarView.maxDate: Long
get() = viewGroup.getMaxDate()
set(value) = viewGroup.setMaxDate(value)
var _CalendarView.minDate: Long
get() = viewGroup.getMinDate()
set(value) = viewGroup.setMinDate(value)
var _CalendarView.selectedDateVerticalBar: android.graphics.drawable.Drawable?
get() = viewGroup.getSelectedDateVerticalBar()
set(value) = viewGroup.setSelectedDateVerticalBar(value!!)
var _CalendarView.selectedWeekBackgroundColor: Int
get() = viewGroup.getSelectedWeekBackgroundColor()
set(value) = viewGroup.setSelectedWeekBackgroundColor(value)
var _CalendarView.showWeekNumber: Boolean
get() = viewGroup.getShowWeekNumber()
set(value) = viewGroup.setShowWeekNumber(value)
var _CalendarView.shownWeekCount: Int
get() = viewGroup.getShownWeekCount()
set(value) = viewGroup.setShownWeekCount(value)
var _CalendarView.unfocusedMonthDateColor: Int
get() = viewGroup.getUnfocusedMonthDateColor()
set(value) = viewGroup.setUnfocusedMonthDateColor(value)
var _CalendarView.weekDayTextAppearance: Int
get() = viewGroup.getWeekDayTextAppearance()
set(value) = viewGroup.setWeekDayTextAppearance(value)
var _CalendarView.weekNumberColor: Int
get() = viewGroup.getWeekNumberColor()
set(value) = viewGroup.setWeekNumberColor(value)
var _CalendarView.weekSeparatorLineColor: Int
get() = viewGroup.getWeekSeparatorLineColor()
set(value) = viewGroup.setWeekSeparatorLineColor(value)
var android.widget.CheckedTextView.checkMarkDrawable: android.graphics.drawable.Drawable?
get() = getCheckMarkDrawable()
set(value) = setCheckMarkDrawable(value!!)
var android.widget.CheckedTextView.checked: Boolean
get() = isChecked()
set(value) = setChecked(value)
var android.widget.Chronometer.base: Long
get() = getBase()
set(value) = setBase(value)
var android.widget.Chronometer.format: String?
get() = getFormat()
set(value) = setFormat(value!!)
var android.widget.Chronometer.onChronometerTickListener: android.widget.Chronometer.OnChronometerTickListener?
get() = getOnChronometerTickListener()
set(value) = setOnChronometerTickListener(value!!)
var android.widget.CompoundButton.checked: Boolean
get() = isChecked()
set(value) = setChecked(value)
val _DatePicker.calendarView: android.widget.CalendarView?
get() = viewGroup.getCalendarView()
var _DatePicker.calendarViewShown: Boolean
get() = viewGroup.getCalendarViewShown()
set(value) = viewGroup.setCalendarViewShown(value)
val _DatePicker.dayOfMonth: Int
get() = viewGroup.getDayOfMonth()
var _DatePicker.enabled: Boolean
get() = viewGroup.isEnabled()
set(value) = viewGroup.setEnabled(value)
var _DatePicker.maxDate: Long
get() = viewGroup.getMaxDate()
set(value) = viewGroup.setMaxDate(value)
var _DatePicker.minDate: Long
get() = viewGroup.getMinDate()
set(value) = viewGroup.setMinDate(value)
val _DatePicker.month: Int
get() = viewGroup.getMonth()
var _DatePicker.spinnersShown: Boolean
get() = viewGroup.getSpinnersShown()
set(value) = viewGroup.setSpinnersShown(value)
val _DatePicker.year: Int
get() = viewGroup.getYear()
val _DialerFilter.digits: CharSequence?
get() = viewGroup.getDigits()
val _DialerFilter.filterText: CharSequence?
get() = viewGroup.getFilterText()
val _DialerFilter.letters: CharSequence?
get() = viewGroup.getLetters()
var _DialerFilter.mode: Int
get() = viewGroup.getMode()
set(value) = viewGroup.setMode(value)
val _DialerFilter.qwertyKeyboard: Boolean
get() = viewGroup.isQwertyKeyboard()
val android.widget.EditText.text: android.text.Editable?
get() = getText()
var _ExpandableListView.adapter: android.widget.ListAdapter?
get() = viewGroup.getAdapter()
set(value) = viewGroup.setAdapter(value!!)
val _ExpandableListView.expandableListAdapter: android.widget.ExpandableListAdapter?
get() = viewGroup.getExpandableListAdapter()
val _ExpandableListView.selectedId: Long
get() = viewGroup.getSelectedId()
val _ExpandableListView.selectedPosition: Long
get() = viewGroup.getSelectedPosition()
val _FrameLayout.considerGoneChildrenWhenMeasuring: Boolean
get() = viewGroup.getConsiderGoneChildrenWhenMeasuring()
var _FrameLayout.foreground: android.graphics.drawable.Drawable?
get() = viewGroup.getForeground()
set(value) = viewGroup.setForeground(value!!)
var _FrameLayout.foregroundGravity: Int
get() = viewGroup.getForegroundGravity()
set(value) = viewGroup.setForegroundGravity(value)
var _FrameLayout.measureAllChildren: Boolean
get() = viewGroup.getMeasureAllChildren()
set(value) = viewGroup.setMeasureAllChildren(value)
var _GridLayout.alignmentMode: Int
get() = viewGroup.getAlignmentMode()
set(value) = viewGroup.setAlignmentMode(value)
var _GridLayout.columnCount: Int
get() = viewGroup.getColumnCount()
set(value) = viewGroup.setColumnCount(value)
var _GridLayout.columnOrderPreserved: Boolean
get() = viewGroup.isColumnOrderPreserved()
set(value) = viewGroup.setColumnOrderPreserved(value)
var _GridLayout.orientation: Int
get() = viewGroup.getOrientation()
set(value) = viewGroup.setOrientation(value)
var _GridLayout.rowCount: Int
get() = viewGroup.getRowCount()
set(value) = viewGroup.setRowCount(value)
var _GridLayout.rowOrderPreserved: Boolean
get() = viewGroup.isRowOrderPreserved()
set(value) = viewGroup.setRowOrderPreserved(value)
var _GridLayout.useDefaultMargins: Boolean
get() = viewGroup.getUseDefaultMargins()
set(value) = viewGroup.setUseDefaultMargins(value)
var _GridView.adapter: android.widget.ListAdapter?
get() = viewGroup.getAdapter()
set(value) = viewGroup.setAdapter(value!!)
var _GridView.columnWidth: Int
get() = viewGroup.getColumnWidth()
set(value) = viewGroup.setColumnWidth(value)
var _GridView.gravity: Int
get() = viewGroup.getGravity()
set(value) = viewGroup.setGravity(value)
var _GridView.horizontalSpacing: Int
get() = viewGroup.getHorizontalSpacing()
set(value) = viewGroup.setHorizontalSpacing(value)
var _GridView.numColumns: Int
get() = viewGroup.getNumColumns()
set(value) = viewGroup.setNumColumns(value)
val _GridView.requestedColumnWidth: Int
get() = viewGroup.getRequestedColumnWidth()
val _GridView.requestedHorizontalSpacing: Int
get() = viewGroup.getRequestedHorizontalSpacing()
var _GridView.stretchMode: Int
get() = viewGroup.getStretchMode()
set(value) = viewGroup.setStretchMode(value)
var _GridView.verticalSpacing: Int
get() = viewGroup.getVerticalSpacing()
set(value) = viewGroup.setVerticalSpacing(value)
var _HorizontalScrollView.fillViewport: Boolean
get() = viewGroup.isFillViewport()
set(value) = viewGroup.setFillViewport(value)
val _HorizontalScrollView.maxScrollAmount: Int
get() = viewGroup.getMaxScrollAmount()
var _HorizontalScrollView.smoothScrollingEnabled: Boolean
get() = viewGroup.isSmoothScrollingEnabled()
set(value) = viewGroup.setSmoothScrollingEnabled(value)
var android.widget.ImageView.adjustViewBounds: Boolean
get() = getAdjustViewBounds()
set(value) = setAdjustViewBounds(value)
var android.widget.ImageView.baseline: Int
get() = getBaseline()
set(value) = setBaseline(value)
var android.widget.ImageView.baselineAlignBottom: Boolean
get() = getBaselineAlignBottom()
set(value) = setBaselineAlignBottom(value)
var android.widget.ImageView.colorFilter: android.graphics.ColorFilter?
get() = getColorFilter()
set(value) = setColorFilter(value!!)
var android.widget.ImageView.cropToPadding: Boolean
get() = getCropToPadding()
set(value) = setCropToPadding(value)
val android.widget.ImageView.drawable: android.graphics.drawable.Drawable?
get() = getDrawable()
var android.widget.ImageView.imageAlpha: Int
get() = getImageAlpha()
set(value) = setImageAlpha(value)
var android.widget.ImageView.imageMatrix: android.graphics.Matrix?
get() = getImageMatrix()
set(value) = setImageMatrix(value!!)
var android.widget.ImageView.maxHeight: Int
get() = getMaxHeight()
set(value) = setMaxHeight(value)
var android.widget.ImageView.maxWidth: Int
get() = getMaxWidth()
set(value) = setMaxWidth(value)
var android.widget.ImageView.scaleType: android.widget.ImageView.ScaleType?
get() = getScaleType()
set(value) = setScaleType(value!!)
val _LinearLayout.baseline: Int
get() = viewGroup.getBaseline()
var _LinearLayout.baselineAligned: Boolean
get() = viewGroup.isBaselineAligned()
set(value) = viewGroup.setBaselineAligned(value)
var _LinearLayout.baselineAlignedChildIndex: Int
get() = viewGroup.getBaselineAlignedChildIndex()
set(value) = viewGroup.setBaselineAlignedChildIndex(value)
var _LinearLayout.dividerDrawable: android.graphics.drawable.Drawable?
get() = viewGroup.getDividerDrawable()
set(value) = viewGroup.setDividerDrawable(value!!)
var _LinearLayout.dividerPadding: Int
get() = viewGroup.getDividerPadding()
set(value) = viewGroup.setDividerPadding(value)
var _LinearLayout.measureWithLargestChildEnabled: Boolean
get() = viewGroup.isMeasureWithLargestChildEnabled()
set(value) = viewGroup.setMeasureWithLargestChildEnabled(value)
var _LinearLayout.orientation: Int
get() = viewGroup.getOrientation()
set(value) = viewGroup.setOrientation(value)
var _LinearLayout.showDividers: Int
get() = viewGroup.getShowDividers()
set(value) = viewGroup.setShowDividers(value)
var _LinearLayout.weightSum: Float
get() = viewGroup.getWeightSum()
set(value) = viewGroup.setWeightSum(value)
var _ListView.adapter: android.widget.ListAdapter?
get() = viewGroup.getAdapter()
set(value) = viewGroup.setAdapter(value!!)
val _ListView.checkItemIds: LongArray?
get() = viewGroup.getCheckItemIds()
var _ListView.divider: android.graphics.drawable.Drawable?
get() = viewGroup.getDivider()
set(value) = viewGroup.setDivider(value!!)
var _ListView.dividerHeight: Int
get() = viewGroup.getDividerHeight()
set(value) = viewGroup.setDividerHeight(value)
val _ListView.footerViewsCount: Int
get() = viewGroup.getFooterViewsCount()
val _ListView.headerViewsCount: Int
get() = viewGroup.getHeaderViewsCount()
var _ListView.itemsCanFocus: Boolean
get() = viewGroup.getItemsCanFocus()
set(value) = viewGroup.setItemsCanFocus(value)
val _ListView.maxScrollAmount: Int
get() = viewGroup.getMaxScrollAmount()
val _ListView.opaque: Boolean
get() = viewGroup.isOpaque()
var _ListView.overscrollFooter: android.graphics.drawable.Drawable?
get() = viewGroup.getOverscrollFooter()
set(value) = viewGroup.setOverscrollFooter(value!!)
var _ListView.overscrollHeader: android.graphics.drawable.Drawable?
get() = viewGroup.getOverscrollHeader()
set(value) = viewGroup.setOverscrollHeader(value!!)
val _MediaController.showing: Boolean
get() = viewGroup.isShowing()
val _NumberPicker.accessibilityNodeProvider: android.view.accessibility.AccessibilityNodeProvider?
get() = viewGroup.getAccessibilityNodeProvider()
var _NumberPicker.displayedValues: Array<String>?
get() = viewGroup.getDisplayedValues()
set(value) = viewGroup.setDisplayedValues(value!!)
var _NumberPicker.maxValue: Int
get() = viewGroup.getMaxValue()
set(value) = viewGroup.setMaxValue(value)
var _NumberPicker.minValue: Int
get() = viewGroup.getMinValue()
set(value) = viewGroup.setMinValue(value)
val _NumberPicker.solidColor: Int
get() = viewGroup.getSolidColor()
var _NumberPicker.value: Int
get() = viewGroup.getValue()
set(value) = viewGroup.setValue(value)
var _NumberPicker.wrapSelectorWheel: Boolean
get() = viewGroup.getWrapSelectorWheel()
set(value) = viewGroup.setWrapSelectorWheel(value)
var android.widget.ProgressBar.indeterminate: Boolean
get() = isIndeterminate()
set(value) = setIndeterminate(value)
var android.widget.ProgressBar.indeterminateDrawable: android.graphics.drawable.Drawable?
get() = getIndeterminateDrawable()
set(value) = setIndeterminateDrawable(value!!)
var android.widget.ProgressBar.interpolator: android.view.animation.Interpolator?
get() = getInterpolator()
set(value) = setInterpolator(value!!)
var android.widget.ProgressBar.max: Int
get() = getMax()
set(value) = setMax(value)
var android.widget.ProgressBar.progress: Int
get() = getProgress()
set(value) = setProgress(value)
var android.widget.ProgressBar.progressDrawable: android.graphics.drawable.Drawable?
get() = getProgressDrawable()
set(value) = setProgressDrawable(value!!)
var android.widget.ProgressBar.secondaryProgress: Int
get() = getSecondaryProgress()
set(value) = setSecondaryProgress(value)
val _RadioGroup.checkedRadioButtonId: Int
get() = viewGroup.getCheckedRadioButtonId()
val android.widget.RatingBar.indicator: Boolean
get() = isIndicator()
var android.widget.RatingBar.numStars: Int
get() = getNumStars()
set(value) = setNumStars(value)
var android.widget.RatingBar.onRatingBarChangeListener: android.widget.RatingBar.OnRatingBarChangeListener?
get() = getOnRatingBarChangeListener()
set(value) = setOnRatingBarChangeListener(value!!)
var android.widget.RatingBar.rating: Float
get() = getRating()
set(value) = setRating(value)
var android.widget.RatingBar.stepSize: Float
get() = getStepSize()
set(value) = setStepSize(value)
val _RelativeLayout.baseline: Int
get() = viewGroup.getBaseline()
var _RelativeLayout.gravity: Int
get() = viewGroup.getGravity()
set(value) = viewGroup.setGravity(value)
var _ScrollView.fillViewport: Boolean
get() = viewGroup.isFillViewport()
set(value) = viewGroup.setFillViewport(value)
val _ScrollView.maxScrollAmount: Int
get() = viewGroup.getMaxScrollAmount()
var _ScrollView.smoothScrollingEnabled: Boolean
get() = viewGroup.isSmoothScrollingEnabled()
set(value) = viewGroup.setSmoothScrollingEnabled(value)
val _SearchView.iconfiedByDefault: Boolean
get() = viewGroup.isIconfiedByDefault()
var _SearchView.iconified: Boolean
get() = viewGroup.isIconified()
set(value) = viewGroup.setIconified(value)
var _SearchView.imeOptions: Int
get() = viewGroup.getImeOptions()
set(value) = viewGroup.setImeOptions(value)
var _SearchView.inputType: Int
get() = viewGroup.getInputType()
set(value) = viewGroup.setInputType(value)
var _SearchView.maxWidth: Int
get() = viewGroup.getMaxWidth()
set(value) = viewGroup.setMaxWidth(value)
val _SearchView.query: CharSequence?
get() = viewGroup.getQuery()
var _SearchView.queryHint: CharSequence?
get() = viewGroup.getQueryHint()
set(value) = viewGroup.setQueryHint(value!!)
var _SearchView.queryRefinementEnabled: Boolean
get() = viewGroup.isQueryRefinementEnabled()
set(value) = viewGroup.setQueryRefinementEnabled(value)
var _SearchView.submitButtonEnabled: Boolean
get() = viewGroup.isSubmitButtonEnabled()
set(value) = viewGroup.setSubmitButtonEnabled(value)
var _SearchView.suggestionsAdapter: android.widget.CursorAdapter?
get() = viewGroup.getSuggestionsAdapter()
set(value) = viewGroup.setSuggestionsAdapter(value!!)
val _SlidingDrawer.content: android.view.View?
get() = viewGroup.getContent()
val _SlidingDrawer.handle: android.view.View?
get() = viewGroup.getHandle()
val _SlidingDrawer.moving: Boolean
get() = viewGroup.isMoving()
val _SlidingDrawer.opened: Boolean
get() = viewGroup.isOpened()
val _Spinner.baseline: Int
get() = viewGroup.getBaseline()
var _Spinner.dropDownHorizontalOffset: Int
get() = viewGroup.getDropDownHorizontalOffset()
set(value) = viewGroup.setDropDownHorizontalOffset(value)
var _Spinner.dropDownVerticalOffset: Int
get() = viewGroup.getDropDownVerticalOffset()
set(value) = viewGroup.setDropDownVerticalOffset(value)
var _Spinner.dropDownWidth: Int
get() = viewGroup.getDropDownWidth()
set(value) = viewGroup.setDropDownWidth(value)
var _Spinner.gravity: Int
get() = viewGroup.getGravity()
set(value) = viewGroup.setGravity(value)
val _Spinner.popupBackground: android.graphics.drawable.Drawable?
get() = viewGroup.getPopupBackground()
var _Spinner.prompt: CharSequence?
get() = viewGroup.getPrompt()
set(value) = viewGroup.setPrompt(value!!)
val android.widget.Switch.compoundPaddingRight: Int
get() = getCompoundPaddingRight()
var android.widget.Switch.switchMinWidth: Int
get() = getSwitchMinWidth()
set(value) = setSwitchMinWidth(value)
var android.widget.Switch.switchPadding: Int
get() = getSwitchPadding()
set(value) = setSwitchPadding(value)
var android.widget.Switch.textOff: CharSequence?
get() = getTextOff()
set(value) = setTextOff(value!!)
var android.widget.Switch.textOn: CharSequence?
get() = getTextOn()
set(value) = setTextOn(value!!)
var android.widget.Switch.thumbDrawable: android.graphics.drawable.Drawable?
get() = getThumbDrawable()
set(value) = setThumbDrawable(value!!)
var android.widget.Switch.thumbTextPadding: Int
get() = getThumbTextPadding()
set(value) = setThumbTextPadding(value)
var android.widget.Switch.trackDrawable: android.graphics.drawable.Drawable?
get() = getTrackDrawable()
set(value) = setTrackDrawable(value!!)
var _TabHost.currentTab: Int
get() = viewGroup.getCurrentTab()
set(value) = viewGroup.setCurrentTab(value)
val _TabHost.currentTabTag: String?
get() = viewGroup.getCurrentTabTag()
val _TabHost.currentTabView: android.view.View?
get() = viewGroup.getCurrentTabView()
val _TabHost.currentView: android.view.View?
get() = viewGroup.getCurrentView()
val _TabHost.tabContentView: android.widget.FrameLayout?
get() = viewGroup.getTabContentView()
val _TabHost.tabWidget: android.widget.TabWidget?
get() = viewGroup.getTabWidget()
var _TabWidget.stripEnabled: Boolean
get() = viewGroup.isStripEnabled()
set(value) = viewGroup.setStripEnabled(value)
val _TabWidget.tabCount: Int
get() = viewGroup.getTabCount()
var _TableLayout.shrinkAllColumns: Boolean
get() = viewGroup.isShrinkAllColumns()
set(value) = viewGroup.setShrinkAllColumns(value)
var _TableLayout.stretchAllColumns: Boolean
get() = viewGroup.isStretchAllColumns()
set(value) = viewGroup.setStretchAllColumns(value)
val _TableRow.virtualChildCount: Int
get() = viewGroup.getVirtualChildCount()
var android.widget.TextView.autoLinkMask: Int
get() = getAutoLinkMask()
set(value) = setAutoLinkMask(value)
val android.widget.TextView.baseline: Int
get() = getBaseline()
var android.widget.TextView.compoundDrawablePadding: Int
get() = getCompoundDrawablePadding()
set(value) = setCompoundDrawablePadding(value)
val android.widget.TextView.compoundDrawables: Array<android.graphics.drawable.Drawable>?
get() = getCompoundDrawables()
val android.widget.TextView.compoundPaddingBottom: Int
get() = getCompoundPaddingBottom()
val android.widget.TextView.compoundPaddingLeft: Int
get() = getCompoundPaddingLeft()
val android.widget.TextView.compoundPaddingRight: Int
get() = getCompoundPaddingRight()
val android.widget.TextView.compoundPaddingTop: Int
get() = getCompoundPaddingTop()
val android.widget.TextView.currentHintTextColor: Int
get() = getCurrentHintTextColor()
val android.widget.TextView.currentTextColor: Int
get() = getCurrentTextColor()
var android.widget.TextView.cursorVisible: Boolean
get() = isCursorVisible()
set(value) = setCursorVisible(value)
var android.widget.TextView.customSelectionActionModeCallback: android.view.ActionMode.Callback?
get() = getCustomSelectionActionModeCallback()
set(value) = setCustomSelectionActionModeCallback(value!!)
val android.widget.TextView.editableText: android.text.Editable?
get() = getEditableText()
var android.widget.TextView.ellipsize: android.text.TextUtils.TruncateAt?
get() = getEllipsize()
set(value) = setEllipsize(value!!)
var android.widget.TextView.error: CharSequence?
get() = getError()
set(value) = setError(value!!)
val android.widget.TextView.extendedPaddingBottom: Int
get() = getExtendedPaddingBottom()
val android.widget.TextView.extendedPaddingTop: Int
get() = getExtendedPaddingTop()
var android.widget.TextView.filters: Array<android.text.InputFilter>?
get() = getFilters()
set(value) = setFilters(value!!)
var android.widget.TextView.freezesText: Boolean
get() = getFreezesText()
set(value) = setFreezesText(value)
var android.widget.TextView.gravity: Int
get() = getGravity()
set(value) = setGravity(value)
var android.widget.TextView.highlightColor: Int
get() = getHighlightColor()
set(value) = setHighlightColor(value)
var android.widget.TextView.hint: CharSequence?
get() = getHint()
set(value) = setHint(value!!)
val android.widget.TextView.hintTextColors: android.content.res.ColorStateList?
get() = getHintTextColors()
val android.widget.TextView.imeActionId: Int
get() = getImeActionId()
val android.widget.TextView.imeActionLabel: CharSequence?
get() = getImeActionLabel()
var android.widget.TextView.imeOptions: Int
get() = getImeOptions()
set(value) = setImeOptions(value)
var android.widget.TextView.includeFontPadding: Boolean
get() = getIncludeFontPadding()
set(value) = setIncludeFontPadding(value)
val android.widget.TextView.inputMethodTarget: Boolean
get() = isInputMethodTarget()
var android.widget.TextView.inputType: Int
get() = getInputType()
set(value) = setInputType(value)
var android.widget.TextView.keyListener: android.text.method.KeyListener?
get() = getKeyListener()
set(value) = setKeyListener(value!!)
val android.widget.TextView.layout: android.text.Layout?
get() = getLayout()
val android.widget.TextView.lineCount: Int
get() = getLineCount()
val android.widget.TextView.lineHeight: Int
get() = getLineHeight()
val android.widget.TextView.lineSpacingExtra: Float
get() = getLineSpacingExtra()
val android.widget.TextView.lineSpacingMultiplier: Float
get() = getLineSpacingMultiplier()
val android.widget.TextView.linkTextColors: android.content.res.ColorStateList?
get() = getLinkTextColors()
var android.widget.TextView.linksClickable: Boolean
get() = getLinksClickable()
set(value) = setLinksClickable(value)
var android.widget.TextView.marqueeRepeatLimit: Int
get() = getMarqueeRepeatLimit()
set(value) = setMarqueeRepeatLimit(value)
var android.widget.TextView.maxEms: Int
get() = getMaxEms()
set(value) = setMaxEms(value)
var android.widget.TextView.maxHeight: Int
get() = getMaxHeight()
set(value) = setMaxHeight(value)
var android.widget.TextView.maxLines: Int
get() = getMaxLines()
set(value) = setMaxLines(value)
var android.widget.TextView.maxWidth: Int
get() = getMaxWidth()
set(value) = setMaxWidth(value)
var android.widget.TextView.minEms: Int
get() = getMinEms()
set(value) = setMinEms(value)
var android.widget.TextView.minHeight: Int
get() = getMinHeight()
set(value) = setMinHeight(value)
var android.widget.TextView.minLines: Int
get() = getMinLines()
set(value) = setMinLines(value)
var android.widget.TextView.minWidth: Int
get() = getMinWidth()
set(value) = setMinWidth(value)
var android.widget.TextView.movementMethod: android.text.method.MovementMethod?
get() = getMovementMethod()
set(value) = setMovementMethod(value!!)
val android.widget.TextView.paint: android.text.TextPaint?
get() = getPaint()
var android.widget.TextView.paintFlags: Int
get() = getPaintFlags()
set(value) = setPaintFlags(value)
var android.widget.TextView.privateImeOptions: String?
get() = getPrivateImeOptions()
set(value) = setPrivateImeOptions(value!!)
val android.widget.TextView.selectionEnd: Int
get() = getSelectionEnd()
val android.widget.TextView.selectionStart: Int
get() = getSelectionStart()
val android.widget.TextView.shadowColor: Int
get() = getShadowColor()
val android.widget.TextView.shadowDx: Float
get() = getShadowDx()
val android.widget.TextView.shadowDy: Float
get() = getShadowDy()
val android.widget.TextView.shadowRadius: Float
get() = getShadowRadius()
val android.widget.TextView.suggestionsEnabled: Boolean
get() = isSuggestionsEnabled()
var android.widget.TextView.text: CharSequence?
get() = getText()
set(value) = setText(value!!)
val android.widget.TextView.textColors: android.content.res.ColorStateList?
get() = getTextColors()
var android.widget.TextView.textScaleX: Float
get() = getTextScaleX()
set(value) = setTextScaleX(value)
val android.widget.TextView.textSelectable: Boolean
get() = isTextSelectable()
var android.widget.TextView.textSize: Float
get() = getTextSize()
set(value) = setTextSize(value)
val android.widget.TextView.totalPaddingBottom: Int
get() = getTotalPaddingBottom()
val android.widget.TextView.totalPaddingLeft: Int
get() = getTotalPaddingLeft()
val android.widget.TextView.totalPaddingRight: Int
get() = getTotalPaddingRight()
val android.widget.TextView.totalPaddingTop: Int
get() = getTotalPaddingTop()
var android.widget.TextView.transformationMethod: android.text.method.TransformationMethod?
get() = getTransformationMethod()
set(value) = setTransformationMethod(value!!)
var android.widget.TextView.typeface: android.graphics.Typeface?
get() = getTypeface()
set(value) = setTypeface(value!!)
val android.widget.TextView.urls: Array<android.text.style.URLSpan>?
get() = getUrls()
val _TimePicker._24HourView: Boolean
get() = viewGroup.is24HourView()
val _TimePicker.baseline: Int
get() = viewGroup.getBaseline()
var _TimePicker.currentHour: Int?
get() = viewGroup.getCurrentHour()
set(value) = viewGroup.setCurrentHour(value!!)
var _TimePicker.currentMinute: Int?
get() = viewGroup.getCurrentMinute()
set(value) = viewGroup.setCurrentMinute(value!!)
var _TimePicker.enabled: Boolean
get() = viewGroup.isEnabled()
set(value) = viewGroup.setEnabled(value)
var android.widget.ToggleButton.textOff: CharSequence?
get() = getTextOff()
set(value) = setTextOff(value!!)
var android.widget.ToggleButton.textOn: CharSequence?
get() = getTextOn()
set(value) = setTextOn(value!!)
val _TwoLineListItem.text1: android.widget.TextView?
get() = viewGroup.getText1()
val _TwoLineListItem.text2: android.widget.TextView?
get() = viewGroup.getText2()
val android.widget.VideoView.bufferPercentage: Int
get() = getBufferPercentage()
val android.widget.VideoView.currentPosition: Int
get() = getCurrentPosition()
val android.widget.VideoView.duration: Int
get() = getDuration()
val android.widget.VideoView.playing: Boolean
get() = isPlaying()
val _ViewAnimator.baseline: Int
get() = viewGroup.getBaseline()
val _ViewAnimator.currentView: android.view.View?
get() = viewGroup.getCurrentView()
var _ViewAnimator.displayedChild: Int
get() = viewGroup.getDisplayedChild()
set(value) = viewGroup.setDisplayedChild(value)
var _ViewAnimator.inAnimation: android.view.animation.Animation?
get() = viewGroup.getInAnimation()
set(value) = viewGroup.setInAnimation(value!!)
var _ViewAnimator.outAnimation: android.view.animation.Animation?
get() = viewGroup.getOutAnimation()
set(value) = viewGroup.setOutAnimation(value!!)
var _ViewFlipper.autoStart: Boolean
get() = viewGroup.isAutoStart()
set(value) = viewGroup.setAutoStart(value)
val _ViewFlipper.flipping: Boolean
get() = viewGroup.isFlipping()
val _ViewSwitcher.nextView: android.view.View?
get() = viewGroup.getNextView()
| gpl-2.0 | f7a427e91d1e149126b4ed27ba9b74f1 | 31.377979 | 114 | 0.752995 | 4.111865 | false | false | false | false |
xiaopansky/Sketch | sample/src/main/java/me/panpf/sketch/sample/util/ImageOrientationCorrectTestFileGenerator.kt | 1 | 7142 | package me.panpf.sketch.sample.util
import android.content.Context
import android.content.res.AssetManager
import android.graphics.*
import android.preference.PreferenceManager
import me.panpf.sketch.sample.AssetImage
import me.panpf.sketch.uri.AssetUriModel
import me.panpf.sketch.util.ExifInterface
import me.panpf.sketch.util.SketchUtils
import java.io.*
class ImageOrientationCorrectTestFileGenerator {
private var files: Array<Config>? = null
private var assetManager: AssetManager? = null
private fun init(context: Context) {
if (files != null) {
return
}
if (assetManager == null) {
assetManager = context.assets
}
val changed = isChanged(context)
if (changed) {
updateVersion(context)
}
var externalFilesDir = context.getExternalFilesDir(null)
if (externalFilesDir == null) {
externalFilesDir = context.filesDir
}
val dirPath = externalFilesDir!!.path + File.separator + "TEST_ORIENTATION"
val filesList = arrayListOf<Config>()
for (w in configs.indices) {
val elements = configs[w].split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val filePath = String.format("%s%s%s", dirPath, File.separator, elements[0])
filesList += Config(filePath, Integer.parseInt(elements[1]), Integer.parseInt(elements[2]), Integer.parseInt(elements[3]))
}
files = filesList.toTypedArray()
if (changed) {
val dir = File(dirPath)
if (dir.exists()) {
SketchUtils.cleanDir(dir)
}
}
}
private fun isChanged(context: Context): Boolean {
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
return preferences.getInt(TAG_VERSION, 0) != VERSION
}
private fun updateVersion(context: Context) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(TAG_VERSION, VERSION).apply()
}
val filePaths: Array<String>
get() {
val filePaths = arrayListOf<String>()
for (w in configs.indices) {
filePaths += files!![w].filePath
}
return filePaths.toTypedArray()
}
fun onAppStart() {
Thread(Runnable {
val options = BitmapFactory.Options()
options.inSampleSize = 4
val inputStream: InputStream
try {
inputStream = assetManager!!.open(AssetUriModel().getUriContent(AssetImage.MEI_NV))
} catch (e: IOException) {
e.printStackTrace()
return@Runnable
}
val sourceBitmap = BitmapFactory.decodeStream(inputStream, null, options)
SketchUtils.close(inputStream)
if(sourceBitmap != null){
for (config in files!!) {
val file = File(config.filePath)
generatorTestFile(file, sourceBitmap, config.degrees, config.xScale, config.orientation)
}
sourceBitmap.recycle()
}
}).start()
}
private fun generatorTestFile(file: File, sourceBitmap: Bitmap, rotateDegrees: Int, xScale: Int, orientation: Int) {
if (file.exists()) {
return
}
val newBitmap = transformBitmap(sourceBitmap, rotateDegrees, xScale)
if (newBitmap == null || newBitmap.isRecycled) {
return
}
file.parentFile.mkdirs()
val outputStream: FileOutputStream
try {
outputStream = FileOutputStream(file)
} catch (e: FileNotFoundException) {
e.printStackTrace()
newBitmap.recycle()
return
}
newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
SketchUtils.close(outputStream)
newBitmap.recycle()
val exifInterface: ExifInterface
try {
exifInterface = ExifInterface(file.path)
} catch (e: IOException) {
e.printStackTrace()
file.delete()
return
}
exifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, orientation.toString())
try {
exifInterface.saveAttributes()
} catch (e: IOException) {
e.printStackTrace()
file.delete()
}
}
private fun transformBitmap(sourceBitmap: Bitmap, degrees: Int, xScale: Int): Bitmap? {
val matrix = Matrix()
matrix.setScale(xScale.toFloat(), 1f)
matrix.postRotate(degrees.toFloat())
// 根据旋转角度计算新的图片的尺寸
val newRect = RectF(0f, 0f, sourceBitmap.width.toFloat(), sourceBitmap.height.toFloat())
matrix.mapRect(newRect)
val newWidth = newRect.width().toInt()
val newHeight = newRect.height().toInt()
// 角度不能整除90°时新图片会是斜的,因此要支持透明度,这样倾斜导致露出的部分就不会是黑的
var config: Bitmap.Config? = if (sourceBitmap.config != null) sourceBitmap.config else null
if (degrees % 90 != 0 && config != Bitmap.Config.ARGB_8888) {
config = Bitmap.Config.ARGB_8888
}
val result = Bitmap.createBitmap(newWidth, newHeight, config!!)
matrix.postTranslate(-newRect.left, -newRect.top)
val canvas = Canvas(result)
val paint = Paint(Paint.DITHER_FLAG or Paint.FILTER_BITMAP_FLAG)
canvas.drawBitmap(sourceBitmap, matrix, paint)
return result
}
private class Config(internal var filePath: String, internal var degrees: Int, internal var xScale: Int, internal var orientation: Int)
companion object {
private val instance = ImageOrientationCorrectTestFileGenerator()
private val VERSION = 5
private val configs = arrayOf(
String.format("%s_%d.jpg,%d,%d,%d", "TEST_FILE_NAME_ROTATE_90", VERSION, -90, 1, ExifInterface.ORIENTATION_ROTATE_90),
String.format("%s_%d.jpg,%d,%d,%d", "TEST_FILE_NAME_ROTATE_180", VERSION, -180, 1, ExifInterface.ORIENTATION_ROTATE_180),
String.format("%s_%d.jpg,%d,%d,%d", "TEST_FILE_NAME_ROTATE_270", VERSION, -270, 1, ExifInterface.ORIENTATION_ROTATE_270),
String.format("%s_%d.jpg,%d,%d,%d", "TEST_FILE_NAME_FLIP_HORIZONTAL", VERSION, 0, -1, ExifInterface.ORIENTATION_FLIP_HORIZONTAL),
String.format("%s_%d.jpg,%d,%d,%d", "TEST_FILE_NAME_TRANSPOSE", VERSION, -90, -1, ExifInterface.ORIENTATION_TRANSPOSE),
String.format("%s_%d.jpg,%d,%d,%d", "TEST_FILE_NAME_FLIP_VERTICAL", VERSION, -180, -1, ExifInterface.ORIENTATION_FLIP_VERTICAL),
String.format("%s_%d.jpg,%d,%d,%d", "TEST_FILE_NAME_TRANSVERSE", VERSION, -270, -1, ExifInterface.ORIENTATION_TRANSVERSE))
private val TAG_VERSION = "TAG_VERSION"
fun getInstance(context: Context): ImageOrientationCorrectTestFileGenerator {
instance.init(context)
return instance
}
}
}
| apache-2.0 | 341ad7caa370dc192e4794cbd0e555a8 | 35.801047 | 145 | 0.611751 | 4.534839 | false | true | false | false |
square/duktape-android | zipline/src/commonMain/kotlin/app/cash/zipline/internal/bridge/passByReference.kt | 1 | 2356 | /*
* Copyright (C) 2022 Block, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.zipline.internal.bridge
import app.cash.zipline.ZiplineService
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
/**
* This is used with [ZiplineServiceAdapter] to pass services between runtimes by reference and not
* by value. This calls [Endpoint.bind] when serializing, and deserializers call [Endpoint.take].
*/
interface PassByReference
internal class ReceiveByReference(
var name: String,
var endpoint: Endpoint,
) : PassByReference {
fun <T : ZiplineService> take(adapter: ZiplineServiceAdapter<T>): T {
return endpoint.take(name, adapter)
}
}
internal class SendByReference<T : ZiplineService>(
val service: T,
val adapter: ZiplineServiceAdapter<T>,
) : PassByReference {
fun bind(endpoint: Endpoint, name: String) {
endpoint.bind(name, service, adapter)
}
}
internal class PassByReferenceSerializer(
val endpoint: Endpoint,
) : KSerializer<PassByReference> {
override val descriptor = PrimitiveSerialDescriptor("PassByReference", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: PassByReference) {
require(value is SendByReference<*>)
val serviceName = endpoint.generatePassByReferenceName()
endpoint.callCodec.encodedServiceNames += serviceName
value.bind(endpoint, serviceName)
encoder.encodeString(serviceName)
}
override fun deserialize(decoder: Decoder): PassByReference {
val serviceName = decoder.decodeString()
endpoint.callCodec.decodedServiceNames += serviceName
return ReceiveByReference(serviceName, endpoint)
}
}
| apache-2.0 | e8ed5ffc0633aa3e73a6287d47ece152 | 34.164179 | 99 | 0.770374 | 4.565891 | false | false | false | false |
simonlebras/Radio-France | app/src/main/kotlin/fr/simonlebras/radiofrance/utils/MediaMetadataUtils.kt | 1 | 478 | package fr.simonlebras.radiofrance.utils
object MediaMetadataUtils {
const val METADATA_KEY_WEBSITE = "__METADATA_KEY_WEBSITE__"
const val METADATA_KEY_TWITTER = "__METADATA_KEY_TWITTER__"
const val METADATA_KEY_FACEBOOK = "__METADATA_KEY_FACEBOOK__"
const val METADATA_KEY_SMALL_LOGO = "__METADATA_KEY_SMALL_LOGO__"
const val METADATA_KEY_MEDIUM_LOGO = "__METADATA_KEY_MEDIUM_LOGO__"
const val METADATA_KEY_LARGE_LOGO = "__METADATA_KEY_LARGE_LOGO__"
}
| mit | 9fdef8177d964e3ca2438cd88c6b3d53 | 46.8 | 71 | 0.711297 | 3.734375 | false | false | false | false |
joan-domingo/Podcasts-RAC1-Android | app/src/main/java/cat/xojan/random1/injection/module/AppModule.kt | 1 | 4698 | package cat.xojan.random1.injection.module
import android.app.DownloadManager
import android.content.Context
import cat.xojan.random1.Application
import cat.xojan.random1.BuildConfig
import cat.xojan.random1.data.*
import cat.xojan.random1.domain.interactor.PodcastDataInteractor
import cat.xojan.random1.domain.interactor.ProgramDataInteractor
import cat.xojan.random1.domain.model.CrashReporter
import cat.xojan.random1.domain.model.EventLogger
import cat.xojan.random1.domain.repository.PodcastPreferencesRepository
import cat.xojan.random1.domain.repository.PodcastRepository
import cat.xojan.random1.domain.repository.ProgramRepository
import cat.xojan.random1.feature.mediaplayback.MediaProvider
import cat.xojan.random1.feature.mediaplayback.QueueManager
import com.google.firebase.analytics.FirebaseAnalytics
import com.squareup.moshi.KotlinJsonAdapterFactory
import com.squareup.moshi.Moshi
import com.squareup.moshi.Rfc3339DateJsonAdapter
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.*
import javax.inject.Singleton
@Module
class AppModule(private val application: Application) {
companion object {
private const val BASE_URL = BuildConfig.BASE_URL
}
@Provides
@Singleton
fun provideDownloadManager(): DownloadManager {
return application.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
}
@Provides
@Singleton
fun provideRetrofitRac1Service(): ApiService {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
val httpClientBuilder = OkHttpClient.Builder()
if (BuildConfig.DEBUG) httpClientBuilder.addInterceptor(loggingInterceptor)
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe())
.build()
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(httpClientBuilder.build())
.build()
return retrofit.create(ApiService::class.java)
}
@Provides
@Singleton
fun provideProgramDataInteractor(programRepository: ProgramRepository) : ProgramDataInteractor {
return ProgramDataInteractor(programRepository)
}
@Provides
@Singleton
fun providePodcastDataInteractor(podcastRepository: PodcastRepository,
programRepository: ProgramRepository,
podcastPrefRepository: PodcastPreferencesRepository,
downloadManager: DownloadManager,
eventLogger: EventLogger)
: PodcastDataInteractor {
return PodcastDataInteractor(
programRepository,
podcastRepository,
podcastPrefRepository,
downloadManager,
application,
SharedPrefDownloadPodcastRepository(application),
eventLogger)
}
@Provides
@Singleton
fun provideEventLogger(): EventLogger {
return EventLogger(FirebaseAnalytics.getInstance(application))
}
@Provides
@Singleton
fun provideCrashReporter(): CrashReporter {
return CrashReporter()
}
@Provides
@Singleton
fun provideMediaProvider(programDataInteractor: ProgramDataInteractor,
podcastDataInteractor: PodcastDataInteractor,
queueManager: QueueManager
): MediaProvider {
return MediaProvider(programDataInteractor, podcastDataInteractor, queueManager)
}
@Provides
@Singleton
fun provideRemoteProgramRepository(service: ApiService): ProgramRepository {
return RemoteProgramRepository(service)
}
@Provides
@Singleton
fun provideRemotePodcastRepository(service: ApiService): PodcastRepository {
return RemotePodcastRepository(service)
}
@Provides
fun providesPodcastsPreferencesRepository(): PodcastPreferencesRepository {
return SharedPrefPodcastPreferencesRepository(application)
}
@Provides
@Singleton
fun provideQueueManager(eventLogger: EventLogger): QueueManager {
return QueueManager(eventLogger)
}
} | mit | f11ccb254f140a24714028ee120a13cb | 33.807407 | 100 | 0.712644 | 5.729268 | false | false | false | false |
Aidanvii7/Toolbox | adapterviews-databinding-recyclerpager/src/main/java/com/aidanvii/toolbox/adapterviews/databinding/recyclerpager/BindingRecyclerPagerBinder.kt | 1 | 4859 | package com.aidanvii.toolbox.adapterviews.databinding.recyclerpager
import android.content.Context
import android.os.Parcelable
import androidx.annotation.RestrictTo
import androidx.viewpager.widget.ViewPager
import com.aidanvii.toolbox.adapterviews.databinding.BindableAdapter
import com.aidanvii.toolbox.adapterviews.databinding.BindableAdapterDelegate
import com.aidanvii.toolbox.adapterviews.databinding.BindableAdapterItem
import com.aidanvii.toolbox.adapterviews.databinding.BindingInflater
import com.aidanvii.toolbox.adapterviews.databinding.ListBinder
import com.aidanvii.toolbox.adapterviews.databinding.defaultAreContentsSame
/**
* Intermediate class used to configure the [BindingRecyclerPagerAdapter]
*
* Example use case:
*
* Suppose you have a custom [BindingRecyclerPagerAdapter]:
* ```
* class MyCustomBindableAdapter(
* builder: Builder<MyAdapterItemViewModel>
* ) : BindingRecyclerPagerAdapter<MyAdapterItemViewModel>(builder) {
* //... custom optional overrides here ...
* }
* ```
* Where the [BindableAdapterItem] implementation looks like:
* ```
* class MyAdapterItemViewModel(
* val id: Int,
* val content: String
* ) : ObservableViewModel(), BindableAdapterItem {
* override val layoutId: Int get() = R.id.my_item
* override val bindingId: Int get() = BR.viewModel
* //... custom adapterBindable properties etc ...
* }
*
* ```
* Where [MyAdapterItemViewModel] has both [id] and [content] fields, the [BindingRecyclerPagerBinder] would be declared as follows:
* ```
* class MyListViewModel : ObservableViewModel() {
*
* @get:Bindable
* var items by bindable(emptyList<MyAdapterItemViewModel>())
*
* val binder = BindingRecyclerPagerBinder<MyAdapterItemViewModel>(
* hasMultipleViewTypes = false,
* areItemsAndContentsTheSame = { oldItem, newItem -> oldItem.id == newItem.id && oldItem.content == oldItem.content },
* adapterFactory = { MyCustomBindableAdapter(it) }
* )
* }
* ```
* Where [MyListViewModel] is a data-bound variable in xml that provides the [BindingRecyclerPagerBinder]:
* ```
* <variable
* name="listViewModel"
* type="com.example.MyListViewModel"/>
* ```
* And bound to the [ViewPager]:
* ```
* <android.support.v4.view.ViewPager
* android:layout_width="match_parent"
* android:layout_height="wrap_content"
* android:items="@{listViewModel.items}"
* android:binder="@{viewModel.binder}"/>
* ```
* @param hasMultipleViewTypes if the [BindingRecyclerViewAdapter] will have [BindableAdapterItem] with different [BindableAdapterItem.layoutId]s, set to true. False otherwise (minor optimisation)
* @param areItemAndContentsTheSame equivalent of [DiffUtil.Callback.areItemsTheSame] plus [DiffUtil.Callback.areContentsTheSame]. Internally forwards to [RecyclerPagerAdapter.OnDataSetChangedCallback.areItemsTheSame]
* @param adapterFactory optional factory to provide a custom implementation of [BindingRecyclerPagerAdapter], allowing you to override methods from [BindableAdapter]
*/
class BindingRecyclerPagerBinder<Item : BindableAdapterItem>(
hasMultipleViewTypes: Boolean = true,
val areItemAndContentsTheSame: ((oldItem: Item, newItem: Item) -> Boolean) = defaultAreContentsSame,
val adapterFactory: (BindingRecyclerPagerAdapter.Builder<Item>) -> BindingRecyclerPagerAdapter<Item> = { BindingRecyclerPagerAdapter(it) }
) : ListBinder<Item>(
hasMultipleViewTypes = hasMultipleViewTypes,
areItemsTheSame = areItemAndContentsTheSame,
areContentsTheSame = areItemAndContentsTheSame
) {
internal var adapterState: BindingRecyclerPagerAdapter.SavedState? = null
internal lateinit var applicationContext: Context
internal val adapter: BindingRecyclerPagerAdapter<Item>
get() = adapterFactory(
BindingRecyclerPagerAdapter.Builder(
delegate = BindableAdapterDelegate(),
viewTypeHandler = viewTypeHandler,
bindingInflater = BindingInflater,
areItemAndContentsTheSame = areItemAndContentsTheSame,
applicationContext = applicationContext
)
)
@RestrictTo(RestrictTo.Scope.TESTS)
fun testAdapter(
viewTypeHandler: BindableAdapter.ViewTypeHandler<Item> = this.viewTypeHandler,
bindingInflater: BindingInflater = BindingInflater,
areItemAndContentsTheSame: ((old: Item, new: Item) -> Boolean) = this.areItemAndContentsTheSame
) = BindingRecyclerPagerAdapter.Builder(
delegate = BindableAdapterDelegate(),
viewTypeHandler = viewTypeHandler,
bindingInflater = bindingInflater,
areItemAndContentsTheSame = areItemAndContentsTheSame,
applicationContext = applicationContext
).let { builder ->
adapterFactory(builder)
}
} | apache-2.0 | a0674c2c7166c734a3ee86a45a1bb016 | 43.181818 | 217 | 0.735542 | 5.174654 | false | false | false | false |
tfelix/worldgen | src/main/kotlin/de/tfelix/bestia/worldgen/description/Map2DDescription.kt | 1 | 1961 | package de.tfelix.bestia.worldgen.description
import de.tfelix.bestia.worldgen.map.Map2DDiscreteChunk
import de.tfelix.bestia.worldgen.map.Map2DDiscreteInfo
import de.tfelix.bestia.worldgen.map.MapChunk
import de.tfelix.bestia.worldgen.random.NoiseVectorBuilder
/**
* This map info implementation describes a discrete two dimensional map
* usable for tilemap creation.
*
* @author Thomas Felix
*/
class Map2DDescription(
builder: Builder
) : MapDescription {
private val width = builder.width
private val height = builder.height
private val chunkWidth = builder.partWidth
private val chunkHeight = builder.partHeight
override val noiseVectorBuilder = builder.noiseVectorBuilder
override val mapParts: Iterator<MapChunk>
get() = Map2DIterator()
override val mapPartCount: Long
get() {
val parts = width / chunkWidth * (height / chunkHeight)
return if (parts == 0L) 1 else parts
}
private inner class Map2DIterator : Iterator<MapChunk> {
private var i: Long = 0
override fun hasNext(): Boolean {
return i < mapPartCount
}
override fun next(): MapChunk {
val curX = i * chunkWidth
val curY = i * chunkHeight
i += 1
return Map2DDiscreteChunk(
curX,
curY,
chunkWidth,
chunkHeight,
Map2DDiscreteInfo(width, height)
)
}
}
/**
* Builder pattern used for the [Map2DDescription]. Use this builder
* to create an instance of the [MapDescription].
*
*/
class Builder(
var noiseVectorBuilder: NoiseVectorBuilder,
var width: Long = 0,
var height: Long = 0,
var partWidth: Long = 0,
var partHeight: Long = 0
) {
fun build(): Map2DDescription {
return Map2DDescription(this)
}
}
override fun toString(): String {
return "Map2DDescription[chunkWidth: $width, chunkHeight: $height: chunkWidth: $chunkWidth, chunkHeight: $chunkHeight]"
}
}
| mit | b0ef740c386b06b3aaedd5caae3b53ba | 25.146667 | 123 | 0.679245 | 4.190171 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/wildplot/android/rendering/YGrid.kt | 1 | 4890 | /****************************************************************************************
* Copyright (c) 2014 Michael Goldbach <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.wildplot.android.rendering
import com.wildplot.android.rendering.graphics.wrapper.ColorWrap
import com.wildplot.android.rendering.graphics.wrapper.GraphicsWrap
import com.wildplot.android.rendering.graphics.wrapper.RectangleWrap
import com.wildplot.android.rendering.interfaces.Drawable
/**
* This class represents grid lines parallel to the y-axis
*/
class YGrid
/**
* Constructor for an Y-Grid object
*
* @param plotSheet the sheet the grid will be drawn onto
* @param ticStart start point for relative positioning of grid
* @param tic the space between two grid lines
*/(
/**
* the Sheet the grid lines will be drawn onto
*/
private val plotSheet: PlotSheet,
/**
* start point for relative positioning of grid
*/
private val ticStart: Double,
/**
* the space between two grid lines
*/
private val tic: Double
) : Drawable {
/**
* the color of the grid lines
*/
private var color = ColorWrap.LIGHT_GRAY
/**
* maximal distance from x axis the grid will be drawn
*/
private var xLength = 10.0
/**
* maximal distance from y axis the grid will be drawn
*/
private var yLength = 2.0
private var mTickPositions: DoubleArray? = null
override fun paint(g: GraphicsWrap) {
val oldColor = g.color
g.color = color
xLength = Math.max(
Math.abs(plotSheet.getxRange()[0]),
Math.abs(
plotSheet.getxRange()[1]
)
)
yLength = Math.max(
Math.abs(plotSheet.getyRange()[0]),
Math.abs(
plotSheet.getyRange()[1]
)
)
val tics = ((ticStart - (0 - xLength)) / tic).toInt()
val leftStart = ticStart - tic * tics
if (mTickPositions == null) {
drawImplicitLines(g, leftStart)
} else {
drawExplicitLines(g)
}
g.color = oldColor
}
private fun drawImplicitLines(g: GraphicsWrap, leftStart: Double) {
val field = g.clipBounds
var currentX = leftStart
while (currentX <= xLength) {
drawGridLine(currentX, g, field)
currentX += tic
}
}
private fun drawExplicitLines(g: GraphicsWrap) {
val field = g.clipBounds
for (currentX in mTickPositions!!) {
drawGridLine(currentX, g, field)
}
}
/**
* Draw a grid line in specified graphics object
*
* @param x x-position the vertical line shall be drawn
* @param g graphic the line shall be drawn onto
* @param field definition of the graphic boundaries
*/
private fun drawGridLine(x: Double, g: GraphicsWrap, field: RectangleWrap) {
g.drawLine(
plotSheet.xToGraphic(x, field), plotSheet.yToGraphic(0.0, field),
plotSheet.xToGraphic(x, field), plotSheet.yToGraphic(yLength, field)
)
g.drawLine(
plotSheet.xToGraphic(x, field), plotSheet.yToGraphic(0.0, field),
plotSheet.xToGraphic(x, field), plotSheet.yToGraphic(-yLength, field)
)
}
override fun isOnFrame(): Boolean {
return false
}
override fun isClusterable(): Boolean {
return true
}
override fun isCritical(): Boolean {
return true
}
fun setColor(color: ColorWrap) {
this.color = color
}
fun setExplicitTicks(tickPositions: DoubleArray?) {
mTickPositions = tickPositions
}
}
| gpl-3.0 | 268c86920aa76beb52aea18d0d8ccfa9 | 33.928571 | 90 | 0.54683 | 4.756809 | false | false | false | false |
pavlospt/litho-lint-rules | litho-lint-detector/src/main/java/com/github/pavlospt/LithoLintIssuesDetector.kt | 1 | 8271 | package com.github.pavlospt
import com.android.tools.lint.client.api.UElementHandler
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.LintFix
import com.github.pavlospt.misc.IssuesInfo
import com.github.pavlospt.misc.LithoLintConstants
import com.github.pavlospt.utils.PsiUtils
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiModifier
import org.jetbrains.uast.UAnnotation
import org.jetbrains.uast.UClass
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UMethod
import org.jetbrains.uast.UNamedExpression
import org.jetbrains.uast.visitor.AbstractUastVisitor
class LithoLintIssuesDetector : Detector(), Detector.UastScanner {
override fun getApplicableUastTypes(): List<Class<out UElement>> {
return listOf<Class<out UElement>>(UClass::class.java)
}
override fun createUastHandler(context: JavaContext): UElementHandler? {
return object : UElementHandler() {
override fun visitClass(node: UClass) {
node.accept(LithoVisitor(context))
}
override fun visitMethod(node: UMethod) {
node.accept(LithoVisitor(context))
}
}
}
internal class LithoVisitor(private val context: JavaContext?) : AbstractUastVisitor() {
private val INVALID_POSITION = -1
override fun visitClass(node: UClass): Boolean {
detectAnnotatedClassNameIssue(context, node)
return super.visitClass(node)
}
override fun visitMethod(node: UMethod): Boolean {
detectMethodVisibilityIssue(node)
detectComponentContextNameIssue(node)
detectOptionalPropOrderIssue(node)
detectPossibleResourceTypesIssue(node)
return super.visitMethod(node)
}
// Detect annotated class name issue
private fun detectAnnotatedClassNameIssue(context: JavaContext?, uClass: UClass) {
if (!PsiUtils.hasAnnotations(uClass.modifierList)) return
val annotations = uClass.modifierList?.annotations ?: return
annotations.forEach {
val worthCheckingClass = LithoLintConstants.LAYOUT_SPEC_ANNOTATION == it.qualifiedName
val psiClassName = uClass.name ?: return@forEach
val notSuggestedName = LithoLintConstants.SUGGESTED_LAYOUT_COMPONENT_SPEC_NAME_FORMAT !in psiClassName
val shouldReportClass = worthCheckingClass && notSuggestedName
if (shouldReportClass) {
context?.report(IssuesInfo.LAYOUT_SPEC_NAME_ISSUE, it,
context.getLocation(uClass.psi.nameIdentifier as PsiElement),
IssuesInfo.LAYOUT_SPEC_CLASS_NAME_ISSUE_DESC)
}
}
}
// Detect possible resource types issue
private fun detectPossibleResourceTypesIssue(uMethod: UMethod) {
if (!worthCheckingMethod(uMethod)) return
val parametersList = uMethod.uastParameters
for (parameter in parametersList) {
if (parameter.type.canonicalText
!in LithoLintConstants.POSSIBLE_RESOURCE_PARAMETER_TYPES) continue
val annotations = parameter.annotations
annotations.filter {
LithoLintConstants.PROP_PARAMETER_ANNOTATION == it.qualifiedName
}.forEach {
context?.report(IssuesInfo.POSSIBLE_RESOURCE_TYPE_ISSUE, parameter as UElement,
context.getLocation(parameter as UElement),
IssuesInfo.POSSIBLE_RESOURCE_TYPE_ISSUE_DESC)
}
}
}
// Detect wrong props order issue
private fun detectOptionalPropOrderIssue(uMethod: UMethod) {
if (!worthCheckingMethod(uMethod)) return
val parametersList = uMethod.uastParameters
var indexOfFirstRequiredProp = INVALID_POSITION
var indexOfFirstOptionalProp = INVALID_POSITION
for (i in parametersList.indices) {
val parameter = parametersList[i]
if (!PsiUtils.hasAnnotations(parameter.modifierList)) continue
val annotations = parameter.annotations
val propAnnotation: UAnnotation = annotations.find {
LithoLintConstants.PROP_PARAMETER_ANNOTATION == it.qualifiedName
} ?: continue
val annotationParameters: List<UNamedExpression> = propAnnotation.attributeValues
if (annotationParameters.isEmpty()) {
indexOfFirstRequiredProp = assignPositionIfInvalid(indexOfFirstRequiredProp, i)
} else {
for (psiNameValuePair in annotationParameters) {
if (LithoLintConstants.OPTIONAL_PROP_ATTRIBUTE_NAME == psiNameValuePair.name) {
indexOfFirstOptionalProp = assignPositionIfInvalid(indexOfFirstOptionalProp, i)
} else {
indexOfFirstRequiredProp = assignPositionIfInvalid(indexOfFirstRequiredProp, i)
}
}
}
if (indexOfFirstOptionalProp != INVALID_POSITION
&& indexOfFirstRequiredProp != INVALID_POSITION
&& indexOfFirstOptionalProp < indexOfFirstRequiredProp) {
val psiParameter = parametersList[indexOfFirstOptionalProp]
context?.report(IssuesInfo.OPTIONAL_PROP_BEFORE_REQUIRED_ISSUE, psiParameter as UElement,
context.getLocation(psiParameter.psi.nameIdentifier as PsiElement),
IssuesInfo.OPTIONAL_PROP_BEFORE_REQUIRED_ISSUE_DESC)
break
}
}
}
// Detect component context name issue
private fun detectComponentContextNameIssue(uMethod: UMethod) {
if (!worthCheckingMethod(uMethod)) return
val parameters = uMethod.uastParameters
for (parameter in parameters) {
if (parameter.type
.canonicalText == LithoLintConstants.COMPONENT_CONTEXT_CLASS_NAME) {
val shouldReportParameter = LithoLintConstants.COMPONENT_CONTEXT_DESIRABLE_PARAMETER_NAME != parameter.name
if (shouldReportParameter) {
val lintFix = LintFix.create().replace().text(parameter.name).with("c").build()
context?.report(IssuesInfo.COMPONENT_CONTEXT_NAME_ISSUE_ISSUE, parameter as UElement,
context.getLocation(parameter.psi.nameIdentifier as PsiElement),
IssuesInfo.COMPONENT_CONTEXT_NAME_ISSUE_DESC, lintFix)
}
}
}
}
// Detect method visibility issue
private fun detectMethodVisibilityIssue(uMethod: UMethod) {
if (!PsiUtils.hasAnnotations(uMethod.modifierList)) return
val annotations = uMethod.annotations
for (annotation in annotations) {
val worthCheckingMethod = LithoLintConstants.ALL_METHOD_ANNOTATIONS
.contains(annotation.qualifiedName)
val notSuggestedVisibility = !uMethod.modifierList.hasModifierProperty(
PsiModifier.PACKAGE_LOCAL)
val missesStaticModifier = !uMethod.modifierList.hasExplicitModifier(PsiModifier.STATIC)
val shouldReportMethodVisibility = worthCheckingMethod && notSuggestedVisibility
val shouldReportMissingStaticModifier = worthCheckingMethod && missesStaticModifier
if (shouldReportMethodVisibility) {
context?.report(IssuesInfo.ANNOTATED_METHOD_VISIBILITY_ISSUE, uMethod as UElement,
context.getLocation(uMethod.psi.nameIdentifier as PsiElement),
IssuesInfo.ANNOTATED_METHOD_VISIBILITY_ISSUE_DESC)
}
if (shouldReportMissingStaticModifier) {
context?.report(IssuesInfo.MISSING_STATIC_MODIFIER_ISSUE, uMethod as UElement,
context.getLocation(uMethod.psi.nameIdentifier as PsiElement),
IssuesInfo.MISSING_STATIC_MODIFIER_ISSUE_DESC)
}
}
}
// Utility method
private fun worthCheckingMethod(uMethod: UMethod): Boolean {
if (!PsiUtils.hasAnnotations(uMethod.modifierList)) return false
val annotations = uMethod.annotations
var worthCheckingMethod = false
for (annotation in annotations) {
worthCheckingMethod = LithoLintConstants.ALL_METHOD_ANNOTATIONS
.contains(annotation.qualifiedName)
if (worthCheckingMethod) break
}
return worthCheckingMethod && PsiUtils.hasParameters(uMethod)
}
// Utility method
private fun assignPositionIfInvalid(assignable: Int, position: Int): Int {
return if (assignable == INVALID_POSITION) position else assignable
}
}
}
| mit | 88ae9b6a7b7f61ccd2f780ccd5342d11 | 36.256757 | 117 | 0.708379 | 5.23481 | false | false | false | false |
JotraN/shows-to-watch-android | app/src/main/java/io/josephtran/showstowatch/show_form/ShowFormFragment.kt | 1 | 4141 | package io.josephtran.showstowatch.show_form
import android.content.Context
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.josephtran.showstowatch.R
import io.josephtran.showstowatch.api.STWShow
import kotlinx.android.synthetic.main.activity_show_form.*
import kotlinx.android.synthetic.main.fragment_show_form.*
abstract class ShowFormFragment : Fragment(), ShowFormView {
private var listener: ShowFormFragmentListener? = null
interface ShowFormFragmentListener {
fun onFormInteracted(show: STWShow)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View?
= inflater!!.inflate(R.layout.fragment_show_form, container, false)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
activity.show_form_toolbar_btn.text = getFormButtonText()
activity.show_form_toolbar_btn.setOnClickListener {
val show = constructShow()
if (show != null)
handleShow(show)
}
}
/**
* Gets the text used for the form button.
*
* @return the text used for the form button
*/
abstract protected fun getFormButtonText(): String
/**
* Handle the {@code STWShow} constructed from the form.
*
* @param stwShow the constructed {@code STWShow} from the form
*/
abstract protected fun handleShow(stwShow: STWShow)
override fun onAttach(context: Context) {
super.onAttach(context)
try {
listener = activity as ShowFormFragmentListener?
} catch (e: ClassCastException) {
throw ClassCastException(activity.toString()
+ " must implement ShowFormFragmentListener")
}
}
/**
* Populates the form with the given {@code STWShow}.
*
* @param stwShow the {@code STWShow} to populate the form with
*/
protected fun populateForm(stwShow: STWShow) {
show_form_title_edit.setText(stwShow.title)
show_form_season_edit.setText(stwShow.season.toString())
show_form_episode_edit.setText(stwShow.episode.toString())
show_form_abandoned.isChecked = stwShow.abandoned
show_form_completed.isChecked = stwShow.completed
}
protected open fun constructShow(): STWShow? {
if (!fieldsValid())
return null
return STWShow(
id = null,
title = show_form_title_edit.text.toString(),
season = show_form_season_edit.text.toString().toInt(),
episode = show_form_episode_edit.text.toString().toInt(),
abandoned = show_form_abandoned.isChecked,
completed = show_form_completed.isChecked
)
}
private fun fieldsValid(): Boolean {
var message = ""
if (show_form_title_edit.text.isNullOrEmpty()) {
message = "Title required."
} else if (show_form_season_edit.text.isNullOrEmpty()) {
message = "Season required."
} else if (show_form_episode_edit.text.isNullOrEmpty()) {
message = "Episode required."
}
if (!message.isNullOrEmpty()) {
showErrorMessage(message)
return false
}
return true
}
private fun showMessage(message: String, color: String) {
if (view != null)
Snackbar.make(view!!,
Html.fromHtml("<font color=\"$color\">$message</font>"),
Snackbar.LENGTH_SHORT).show()
}
override fun showMessage(message: String) {
showMessage(message, "white")
}
override fun showErrorMessage(errorMessage: String) {
showMessage(errorMessage, "red")
}
override fun onShowHandled(show: STWShow) {
if (listener != null)
listener!!.onFormInteracted(show)
}
} | mit | 6dd2c2882d824841ebd8bde5b2dfc334 | 32.95082 | 79 | 0.63318 | 4.611359 | false | false | false | false |
songzhw/Hello-kotlin | Advanced_kb/src/rxjava2/Scan_Reduce_Diff.kt | 1 | 989 | package rxjava2
import io.reactivex.Observable
import java.util.*
import java.util.concurrent.Callable
import java.util.stream.Collectors
// scan和reduce都是把上一次操作的结果做为参数传递给第二次Observable使用
// 区别就在subscribe()是否被频繁调用. 见下面日志即知
fun main() {
Observable.range(0, 6)
.scan(12) { a, b ->
println(" szw a = $a, b = $b")
a + b
}
.subscribe { println(" $it") }
Observable.range(0, 6)
.reduce(12) { a, b ->
println("==> a = $a, b = $b")
a + b
}
.subscribe { v -> println("==> ${v}") }
}
/*
result:
12
szw a = 12, b = 0
12
szw a = 12, b = 1
13
szw a = 13, b = 2
15
szw a = 15, b = 3
18
szw a = 18, b = 4
22
szw a = 22, b = 5
27
==> a = 12, b = 0
==> a = 12, b = 1
==> a = 13, b = 2
==> a = 15, b = 3
==> a = 18, b = 4
==> a = 22, b = 5
==> 27
*/ | apache-2.0 | efdca261a67afded69f95c71ff18f769 | 14.894737 | 47 | 0.455249 | 2.767584 | false | false | false | false |
awslabs/serverless-photo-recognition | src/main/kotlin/com/budilov/AddPhotoLambda.kt | 1 | 2092 | package com.budilov
import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.lambda.runtime.RequestHandler
import com.amazonaws.services.lambda.runtime.events.S3Event
import com.budilov.db.ESPictureService
import com.budilov.pojo.PictureItem
import com.budilov.rekognition.RekognitionService
import java.net.URLDecoder
/**
* Created by Vladimir Budilov
*
* This Lambda function is invoked by S3 whenever an object is added to an S3 bucket.
*/
class AddPhotoLambda : RequestHandler<S3Event, String> {
private val rekognition = RekognitionService()
private val esService = ESPictureService()
/**
* 1. Get the s3 bucket and object name in question
* 2. Clean the object name
* 3. Run the RekognitionService service to get the labels
* 4. Save the bucket/object & labels into ElasticSearch
*/
override fun handleRequest(s3event: S3Event, context: Context): String {
val record = s3event.records.first()
val logger = context.logger
val srcBucket = record.s3.bucket.name
// Object key may have spaces or unicode non-ASCII characters.
val srcKeyEncoded = record.s3.`object`.key
.replace('+', ' ')
val srcKey = URLDecoder.decode(srcKeyEncoded, "UTF-8")
logger.log("bucket: ${srcBucket}, key: $srcKey")
// Get the cognito id from the object name (it's a prefix)...hacky, don't judge
val cognitoId = srcKey.split("/")[1]
logger.log("Cognito ID: $cognitoId")
val labels = rekognition.getLabels(srcBucket, srcKey)
if (labels.isNotEmpty()) {
val picture = PictureItem(srcKeyEncoded.hashCode().toString(), srcBucket + Properties._BUCKET_URL + "/" + srcKey, labels, null)
logger.log("Saving picture: $picture")
// Save the picture to ElasticSearch
esService.add(cognitoId, picture)
} else {
logger.log("No labels returned. Not saving to ES")
//todo: create an actionable event to replay the flow
}
return "Ok"
}
} | apache-2.0 | 8768d8e0c1904889a1b2c880d61c9900 | 35.086207 | 139 | 0.669216 | 4.134387 | false | false | false | false |
PaulWoitaschek/Voice | app/src/main/kotlin/voice/app/mvp/MvpController.kt | 1 | 1721 | package voice.app.mvp
import android.os.Bundle
import android.view.View
import androidx.viewbinding.ViewBinding
import com.bluelinelabs.conductor.Controller
import voice.common.checkMainThread
import voice.common.conductor.InflateBinding
import voice.common.conductor.ViewBindingController
/**
* Base controller that provides a convenient way for binding a view to a presenter
*/
abstract class MvpController<V : Any, out P, B : ViewBinding>(
inflateBinding: InflateBinding<B>,
args: Bundle = Bundle(),
) : ViewBindingController<B>(args, inflateBinding) where P : Presenter<V> {
private var internalPresenter: P? = null
val presenter: P
get() {
checkMainThread()
check(!isDestroyed) { "Must not call presenter when destroyed!" }
if (internalPresenter == null) {
internalPresenter = createPresenter()
}
return internalPresenter!!
}
init {
addLifecycleListener(
object : LifecycleListener() {
override fun onRestoreInstanceState(controller: Controller, savedInstanceState: Bundle) {
presenter.onRestore(savedInstanceState)
}
override fun postAttach(controller: Controller, view: View) {
presenter.attach(provideView())
}
override fun preDetach(controller: Controller, view: View) {
presenter.detach()
}
override fun onSaveInstanceState(controller: Controller, outState: Bundle) {
presenter.onSave(outState)
}
override fun postDestroy(controller: Controller) {
internalPresenter = null
}
},
)
}
@Suppress("UNCHECKED_CAST")
open fun provideView(): V = this as V
abstract fun createPresenter(): P
}
| gpl-3.0 | 6f0a2c3114e3faeda29a4e1a55eaf2d8 | 27.213115 | 97 | 0.686229 | 4.807263 | false | false | false | false |
i7c/cfm | server/recorder/src/main/kotlin/org/rliz/cfm/recorder/mbs/service/MbsService.kt | 1 | 3954 | package org.rliz.cfm.recorder.mbs.service
import org.rliz.cfm.recorder.common.exception.MbsLookupFailedException
import org.rliz.cfm.recorder.mbs.api.MbsIdentifiedPlaybackDto
import org.rliz.cfm.recorder.mbs.api.MbsIdentifiedPlaybackRes
import org.rliz.cfm.recorder.mbs.api.MbsRecordingViewListRes
import org.rliz.cfm.recorder.mbs.api.MbsReleaseGroupViewListRes
import org.springframework.beans.factory.annotation.Value
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Service
import org.springframework.web.client.RestTemplate
import org.springframework.web.util.UriComponentsBuilder
import java.util.UUID
import java.util.concurrent.CompletableFuture
@Service
class MbsService {
@Value("\${cfm.mbs.url}")
lateinit var mbsUrl: String
@Async
fun getRecordingView(ids: List<UUID>): CompletableFuture<MbsRecordingViewListRes> =
UriComponentsBuilder.fromHttpUrl(mbsUrl)
.pathSegment("mbs", "v1", "recordings")
.let { uriBuilder ->
ids.forEach { uriBuilder.queryParam("id", it) }
CompletableFuture.completedFuture(
RestTemplate().getForObject(
uriBuilder.build().toUri(),
MbsRecordingViewListRes::class.java
)
)
}
@Async
fun getReleaseGroupView(ids: List<UUID>): CompletableFuture<MbsReleaseGroupViewListRes> =
UriComponentsBuilder.fromHttpUrl(mbsUrl)
.pathSegment("mbs", "v2", "release-groups")
.let { uriBuilder ->
ids.forEach { uriBuilder.queryParam("id", it) }
CompletableFuture.completedFuture(
RestTemplate().getForObject(
uriBuilder.build().toUri(),
MbsReleaseGroupViewListRes::class.java
)
)
}
@Async
fun identifyPlayback(recordingTitle: String, releaseTitle: String, artists: List<String>):
CompletableFuture<MbsIdentifiedPlaybackDto> =
UriComponentsBuilder.fromHttpUrl(mbsUrl)
.pathSegment("mbs", "v1", "playbacks", "identify")
.queryParam("title", recordingTitle)
.queryParam("release", releaseTitle)
.apply {
artists.forEach { queryParam("artist", it) }
}
.build()
.toUri()
.let { uri ->
val future = CompletableFuture<MbsIdentifiedPlaybackDto>()
try {
future.complete(
RestTemplate().getForObject(
uri,
MbsIdentifiedPlaybackRes::class.java
)!!.toDto()
)
} catch (e: Exception) {
future.completeExceptionally(MbsLookupFailedException(e))
}
future
}
@Async
fun identifyPlayback(
artist: String,
release: String,
recording: String,
length: Long
): CompletableFuture<IdentifiedPlayback> =
UriComponentsBuilder.fromHttpUrl(mbsUrl)
.pathSegment("mbs", "v2", "playbacks", "best")
.queryParam("artist", artist)
.queryParam("release", release)
.queryParam("recording", recording)
.queryParam("length", length)
.build()
.encode()
.toUri()
.let { uri ->
val future = CompletableFuture<IdentifiedPlayback>()
try {
future.complete(
RestTemplate().getForObject(uri, IdentifiedPlayback::class.java)
)
} catch (e: Exception) {
future.completeExceptionally(MbsLookupFailedException(e))
}
future
}
}
| gpl-3.0 | 8832ea955afc02e41a764e1edc342d89 | 37.019231 | 94 | 0.570309 | 5.379592 | false | false | false | false |
FHannes/intellij-community | platform/script-debugger/debugger-ui/src/ScopeVariablesGroup.kt | 6 | 4370 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.xdebugger.XDebuggerBundle
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XValueChildrenList
import com.intellij.xdebugger.frame.XValueGroup
import org.jetbrains.concurrency.done
import org.jetbrains.concurrency.rejected
import org.jetbrains.concurrency.thenAsyncAccept
class ScopeVariablesGroup(val scope: Scope, parentContext: VariableContext, callFrame: CallFrame?) : XValueGroup(scope.createScopeNodeName()) {
private val context = createVariableContext(scope, parentContext, callFrame)
private val callFrame = if (scope.type == ScopeType.LOCAL) callFrame else null
override fun isAutoExpand() = scope.type == ScopeType.LOCAL || scope.type == ScopeType.CATCH
override fun getComment(): String? {
val className = scope.description
return if ("Object" == className) null else className
}
override fun computeChildren(node: XCompositeNode) {
val promise = processScopeVariables(scope, node, context, callFrame == null)
if (callFrame == null) {
return
}
promise
.done(node) {
context.memberFilter
.thenAsyncAccept(node) {
if (it.hasNameMappings()) {
it.sourceNameToRaw(RECEIVER_NAME)?.let {
return@thenAsyncAccept callFrame.evaluateContext.evaluate(it)
.done(node) {
VariableImpl(RECEIVER_NAME, it.value, null)
node.addChildren(XValueChildrenList.singleton(VariableView(VariableImpl(RECEIVER_NAME, it.value, null), context)), true)
}
}
}
context.viewSupport.computeReceiverVariable(context, callFrame, node)
}
.rejected(node) {
context.viewSupport.computeReceiverVariable(context, callFrame, node)
}
}
}
}
fun createAndAddScopeList(node: XCompositeNode, scopes: List<Scope>, context: VariableContext, callFrame: CallFrame?) {
val list = XValueChildrenList(scopes.size)
for (scope in scopes) {
list.addTopGroup(ScopeVariablesGroup(scope, context, callFrame))
}
node.addChildren(list, true)
}
fun createVariableContext(scope: Scope, parentContext: VariableContext, callFrame: CallFrame?): VariableContext {
if (callFrame == null || scope.type == ScopeType.LIBRARY) {
// functions scopes - we can watch variables only from global scope
return ParentlessVariableContext(parentContext, scope, scope.type == ScopeType.GLOBAL)
}
else {
return VariableContextWrapper(parentContext, scope)
}
}
private class ParentlessVariableContext(parentContext: VariableContext, scope: Scope, private val watchableAsEvaluationExpression: Boolean) : VariableContextWrapper(parentContext, scope) {
override fun watchableAsEvaluationExpression() = watchableAsEvaluationExpression
}
private fun Scope.createScopeNodeName(): String {
when (type) {
ScopeType.GLOBAL -> return XDebuggerBundle.message("scope.global")
ScopeType.LOCAL -> return XDebuggerBundle.message("scope.local")
ScopeType.WITH -> return XDebuggerBundle.message("scope.with")
ScopeType.CLOSURE -> return XDebuggerBundle.message("scope.closure")
ScopeType.CATCH -> return XDebuggerBundle.message("scope.catch")
ScopeType.LIBRARY -> return XDebuggerBundle.message("scope.library")
ScopeType.INSTANCE -> return XDebuggerBundle.message("scope.instance")
ScopeType.CLASS -> return XDebuggerBundle.message("scope.class")
ScopeType.BLOCK -> return XDebuggerBundle.message("scope.block")
ScopeType.SCRIPT -> return XDebuggerBundle.message("scope.script")
ScopeType.UNKNOWN -> return XDebuggerBundle.message("scope.unknown")
else -> throw IllegalArgumentException(type.name)
}
} | apache-2.0 | d517b778b122028ba92a5d6a5a088844 | 41.028846 | 188 | 0.729062 | 4.850166 | false | false | false | false |
clangen/musikcube | src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/tracks/fragment/TrackListFragment.kt | 1 | 11877 | package io.casey.musikcube.remote.ui.tracks.fragment
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.*
import androidx.appcompat.app.AppCompatActivity
import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView
import io.casey.musikcube.remote.R
import io.casey.musikcube.remote.service.playback.impl.remote.Metadata
import io.casey.musikcube.remote.service.websocket.model.IMetadataProxy
import io.casey.musikcube.remote.service.websocket.model.ITrack
import io.casey.musikcube.remote.service.websocket.model.ITrackListQueryFactory
import io.casey.musikcube.remote.ui.shared.activity.IFilterable
import io.casey.musikcube.remote.ui.shared.activity.IMenuProvider
import io.casey.musikcube.remote.ui.shared.activity.ITitleProvider
import io.casey.musikcube.remote.ui.shared.activity.ITransportObserver
import io.casey.musikcube.remote.ui.shared.constant.Shared
import io.casey.musikcube.remote.ui.shared.extension.*
import io.casey.musikcube.remote.ui.shared.fragment.BaseFragment
import io.casey.musikcube.remote.ui.shared.mixin.ItemContextMenuMixin
import io.casey.musikcube.remote.ui.shared.mixin.MetadataProxyMixin
import io.casey.musikcube.remote.ui.shared.mixin.PlaybackMixin
import io.casey.musikcube.remote.ui.shared.model.DefaultSlidingWindow
import io.casey.musikcube.remote.ui.shared.model.ITrackListSlidingWindow
import io.casey.musikcube.remote.ui.shared.view.EmptyListView
import io.casey.musikcube.remote.ui.tracks.activity.EditPlaylistActivity
import io.casey.musikcube.remote.ui.tracks.activity.TrackListActivity
import io.casey.musikcube.remote.ui.tracks.adapter.TrackListAdapter
import io.casey.musikcube.remote.ui.tracks.constant.Track
import io.casey.musikcube.remote.util.Debouncer
import io.reactivex.Observable
import io.reactivex.rxkotlin.subscribeBy
class TrackListFragment: BaseFragment(), IFilterable, ITitleProvider, ITransportObserver, IMenuProvider {
private lateinit var tracks: DefaultSlidingWindow
private lateinit var emptyView: EmptyListView
private lateinit var adapter: TrackListAdapter
private lateinit var queryFactory: ITrackListQueryFactory
private lateinit var data: MetadataProxyMixin
private lateinit var playback: PlaybackMixin
private var categoryType: String = ""
private var categoryId: Long = 0
private var titleId = R.string.songs_title
private var categoryValue: String = ""
private var lastFilter = ""
override fun onCreate(savedInstanceState: Bundle?) {
component.inject(this)
data = mixin(MetadataProxyMixin())
playback = mixin(PlaybackMixin())
extras.run {
categoryType = getString(Track.Extra.CATEGORY_TYPE, "")
categoryId = getLong(Track.Extra.SELECTED_ID, 0)
categoryValue = getString(Track.Extra.CATEGORY_VALUE, "")
titleId = getInt(Track.Extra.TITLE_ID, titleId)
}
/* needs to come after we extract categoryType -- otherwise menuListener
may get resolved to `null` */
mixin(ItemContextMenuMixin(appCompatActivity, menuListener, this))
queryFactory = createCategoryQueryFactory(categoryType, categoryId)
super.onCreate(savedInstanceState)
}
override fun onPause() {
super.onPause()
tracks.pause()
}
override fun onResume() {
tracks.resume() /* needs to happen first */
super.onResume()
requeryIfViewingOfflineCache()
}
override fun onInitObservables() {
disposables.add(data.provider.observeState().subscribeBy(
onNext = { states ->
val shouldRequery =
states.first === IMetadataProxy.State.Connected ||
(states.first === IMetadataProxy.State.Disconnected && isOfflineTracks)
if (shouldRequery) {
filterDebouncer.cancel()
tracks.requery()
}
else {
emptyView.update(states.first, adapter.itemCount)
}
},
onError = {
}))
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
inflater.inflate(this.getLayoutId(), container, false).apply {
val recyclerView = findViewById<FastScrollRecyclerView>(R.id.recycler_view)
tracks = DefaultSlidingWindow(recyclerView, data.provider, queryFactory)
adapter = TrackListAdapter(tracks, eventListener, playback, prefs)
setupDefaultRecyclerView(recyclerView, adapter)
emptyView = findViewById(R.id.empty_list_view)
emptyView.let {
it.capability = if (isOfflineTracks) EmptyListView.Capability.OfflineOk else EmptyListView.Capability.OnlineOnly
it.emptyMessage = emptyMessage
it.alternateView = recyclerView
}
tracks.setOnMetadataLoadedListener(slidingWindowListener)
}
private val editPlaylistLauncher = launcher { result ->
val data = result.data
if (result.resultCode == AppCompatActivity.RESULT_OK && data != null) {
val playlistName = data.getStringExtra(EditPlaylistActivity.EXTRA_PLAYLIST_NAME) ?: ""
val playlistId = data.getLongExtra(EditPlaylistActivity.EXTRA_PLAYLIST_ID, -1L)
if (categoryType != Metadata.Category.PLAYLISTS || playlistId != this.categoryId) {
showSnackbar(
appCompatActivity.findViewById(android.R.id.content),
getString(R.string.playlist_edit_save_success, playlistName),
buttonText = getString(R.string.button_view),
buttonCb = {
startActivity(TrackListActivity.getStartIntent(
appCompatActivity, Metadata.Category.PLAYLISTS, playlistId, playlistName))
})
}
}
}
override val title: String
get() = getTitleOverride(getString(titleId))
override val addFilterToToolbar: Boolean
get() = false
override fun setFilter(filter: String) {
lastFilter = filter
filterDebouncer.call()
}
override fun createOptionsMenu(menu: Menu): Boolean {
when (Metadata.Category.PLAYLISTS == categoryType) {
true -> appCompatActivity.menuInflater.inflate(R.menu.view_playlist_menu, menu)
false -> addFilterAction(menu, this)
}
return true
}
override fun optionsItemSelected(menuItem: MenuItem): Boolean =
when (menuItem.itemId == R.id.action_edit) {
true -> {
editPlaylistLauncher.launch(
EditPlaylistActivity.getStartIntent(
appCompatActivity,
categoryValue,
categoryId))
true
}
else -> false
}
override fun onTransportChanged() {
adapter.notifyDataSetChanged()
}
private val filterDebouncer = object : Debouncer<String>(350) {
override fun onDebounced(last: String?) {
if (!paused) {
tracks.requery()
}
}
}
private val emptyMessage: String
get() {
if (isOfflineTracks) {
return getString(R.string.empty_no_offline_tracks_message)
}
return getString(R.string.empty_no_items_format, getString(R.string.browse_type_tracks))
}
private val isOfflineTracks: Boolean
get() = Metadata.Category.OFFLINE == categoryType
private fun requeryIfViewingOfflineCache() {
if (isOfflineTracks) {
tracks.requery()
}
}
private fun createCategoryQueryFactory(categoryType: String?, categoryId: Long): ITrackListQueryFactory {
if (isValidCategory(categoryType, categoryId)) {
/* tracks for a specified category (album, artists, genres, etc */
return object : ITrackListQueryFactory {
override fun count(): Observable<Int> =
data.provider.getTrackCountByCategory(categoryType ?: "", categoryId, lastFilter)
override fun page(offset: Int, limit: Int): Observable<List<ITrack>> =
data.provider.getTracksByCategory(categoryType ?: "", categoryId, limit, offset, lastFilter)
override fun offline(): Boolean =
Metadata.Category.OFFLINE == categoryType
}
}
else {
/* all tracks */
return object : ITrackListQueryFactory {
override fun count(): Observable<Int> =
data.provider.getTrackCount(lastFilter)
override fun page(offset: Int, limit: Int): Observable<List<ITrack>> =
data.provider.getTracks(limit, offset, lastFilter)
override fun offline(): Boolean =
Metadata.Category.OFFLINE == categoryType
}
}
}
private val slidingWindowListener = object : ITrackListSlidingWindow.OnMetadataLoadedListener {
override fun onReloaded(count: Int) =
emptyView.update(data.provider.state, count)
override fun onMetadataLoaded(offset: Int, count: Int) {}
}
private val menuListener: ItemContextMenuMixin.EventListener?
get() {
if (categoryType == Metadata.Category.PLAYLISTS) {
return object: ItemContextMenuMixin.EventListener () {
override fun onPlaylistUpdated(id: Long, name: String) {
tracks.requery()
}
}
}
return null
}
private val eventListener = object: TrackListAdapter.EventListener {
override fun onItemClick(view: View, track: ITrack, position: Int) {
if (isValidCategory(categoryType, categoryId)) {
playback.service.play(categoryType, categoryId, position, lastFilter)
}
else {
playback.service.playAll(position, lastFilter)
}
}
override fun onActionItemClick(view: View, track: ITrack, position: Int) {
val mixin = mixin(ItemContextMenuMixin::class.java)!!
if (categoryType == Metadata.Category.PLAYLISTS) {
mixin.showForPlaylistTrack(track, position, categoryId, categoryValue, view)
}
else {
mixin.showForTrack(track, view)
}
}
}
companion object {
const val TAG = "TrackListFragment"
fun arguments(context: Context,
categoryType: String = "",
categoryId: Long = 0,
categoryValue: String = ""): Bundle = Bundle().apply {
putLong(Track.Extra.SELECTED_ID, categoryId)
putString(Track.Extra.CATEGORY_TYPE, categoryType)
putString(Track.Extra.CATEGORY_VALUE, categoryValue)
if (categoryValue.isNotEmpty()) {
putString(
Shared.Extra.TITLE_OVERRIDE,
context.getString(R.string.songs_from_category, categoryValue))
}
}
fun create(intent: Intent?): TrackListFragment =
create(intent?.extras?.getBundle(Track.Extra.FRAGMENT_ARGUMENTS) ?: Bundle())
fun create(arguments: Bundle = Bundle()): TrackListFragment =
TrackListFragment().apply {
this.arguments = arguments
}
private fun isValidCategory(categoryType: String?, categoryId: Long): Boolean =
categoryType != null && categoryType.isNotEmpty() && categoryId != -1L
}
} | bsd-3-clause | 4e9e0e873a3db15290c29eb933bc9ac1 | 38.593333 | 128 | 0.637114 | 5.141558 | false | false | false | false |
stepstone-tech/android-material-stepper | sample/src/main/java/com/stepstone/stepper/sample/CustomPageTransformerActivity.kt | 2 | 1680 | /*
Copyright 2016 StepStone Services
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.stepstone.stepper.sample
import android.os.Bundle
import android.support.v4.view.ViewPager
import android.view.View
class CustomPageTransformerActivity : AbstractStepperActivity() {
override val layoutResId: Int
get() = R.layout.activity_default_dots
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
stepperLayout.setPageTransformer(CrossFadePageTransformer())
}
private class CrossFadePageTransformer : ViewPager.PageTransformer {
override fun transformPage(view: View, position: Float) {
if (position <= -1.0f || position >= 1.0f) {
view.translationX = view.width * position
view.alpha = 0.0f
} else if (position == 0.0f) {
view.translationX = view.width * position
view.alpha = 1.0f
} else {
// position is between -1.0F & 0.0F OR 0.0F & 1.0F
view.translationX = view.width * -position
view.alpha = 1.0f - Math.abs(position)
}
}
}
}
| apache-2.0 | 6e45375e3299f9fb8adca6deee885e32 | 33.285714 | 72 | 0.670238 | 4.386423 | false | false | false | false |
AoEiuV020/PaNovel | local/src/main/java/cc/aoeiuv020/panovel/local/EpubExpoter.kt | 1 | 7027 | package cc.aoeiuv020.panovel.local
import cc.aoeiuv020.anull.notNull
import cc.aoeiuv020.log.debug
import cc.aoeiuv020.log.error
import cc.aoeiuv020.regex.pick
import cc.aoeiuv020.string.divide
import cc.aoeiuv020.string.lastDivide
import nl.siegmann.epublib.domain.Author
import nl.siegmann.epublib.domain.Book
import nl.siegmann.epublib.domain.Resource
import nl.siegmann.epublib.epub.EpubWriter
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File
/**
* TODO: 其他阅读器无法识别,
*
* Created by AoEiuV020 on 2018.06.19-22:53:24.
*/
class EpubExporter(
private val file: File
) : LocalNovelExporter {
private val imagePattern = "^!\\[img\\]\\((.*)\\)$"
private val logger: Logger = LoggerFactory.getLogger(this.javaClass.simpleName)
override fun export(info: LocalNovelInfo, contentProvider: ContentProvider, progressCallback: (Int, Int) -> Unit) {
val book = Book()
val indent = " "
val chapters = info.chapters
val total = chapters.size
progressCallback(0, total)
book.metadata.apply {
addPublisher("PaNovel")
language = "zh"
info.author?.also {
try {
val (first, last) = it.divide(' ')
val firstName = first.trim()
val lastName = last.trim()
addAuthor(Author(firstName, lastName))
logger.debug { "添加作者<$firstName $lastName>" }
} catch (e: Exception) {
addAuthor(Author(it))
logger.debug { "添加作者<$it>" }
}
}
info.name?.also {
addTitle(it)
logger.debug { "添加标题<$it>" }
}
info.introduction?.let { intro ->
try {
intro.split('\n').map(String::trim).filter(String::isNotEmpty)
.takeIf(List<*>::isNotEmpty)
?.fold(Element("div")) { div, it ->
// 没考虑简介有图片的情况,
div.appendElement("p")
.text("$indent$it")
}
} catch (e: Exception) {
// 按理说不会有失败,
logger.error(e) { "导出简介失败," }
null
}
}?.also { div ->
addDescription(div.outerHtml())
}
}
info.image?.let {
try {
val url = contentProvider.getImage(it)
// info.image或者url中一般有图片文件名,
// 但不可控,万一就出现重名的呢,
val fileName = try {
it.lastDivide('/').second
} catch (_: Exception) {
try {
url.toString().lastDivide('/').second
} catch (_: Exception) {
// 失败填充默认jpg一般没问题,
"cover.jpg"
}
}
val resource = url.openStream().use { input ->
Resource(input, fileName)
}
logger.debug {
"添加封面<$url, ${resource.href}>"
}
book.coverImage = resource
} catch (e: Exception) {
// 任何失败就不添加封面了,
logger.error(e) { "导出封面失败" }
}
}
var imageIndex = 0
chapters.forEachIndexed { index, chapter ->
progressCallback(index, total)
val content = contentProvider.getNovelContent(chapter)
// 空章节不导出,
if (content.isEmpty()) return@forEachIndexed
val name = chapter.name
val fileName = "chapter$index.html"
val root = Document.createShell(("file://$OPS_PATH/$fileName"))
root.title(name)
val div = root.body().appendElement("div")
.text("")
// 如果第一行不是章节名,就添加一行章节名,
// 正常正文应该是不包括章节名的,也就是会调用这个的,
if (content.firstOrNull() != name) {
div.appendElement("h2")
.text(name)
}
content.forEach { line ->
val extra = try {
line.pick(imagePattern).first()
} catch (_: Exception) {
// 不是图片就直接保存p标签,
div.appendElement("p")
.text("$indent$line")
return@forEach
}
try {
val url = contentProvider.getImage(extra)
// 如果打开图片输入流返回空,直接抛异常到下面的catch打印普通文本,
logger.debug { "adding image: $url" }
val resource = contentProvider.openImage(url).notNull().use { input ->
val suffix = try {
// 从url中拿文件后辍,
url.toString().lastDivide('.').second
} catch (e: Exception) {
// 失败填充默认jpg一般没问题,
"jpg"
}
Resource(input, "image${imageIndex++}.$suffix")
}
book.addResource(resource)
div.appendElement("p")
.appendElement("img")
.attr("src", resource.href)
// jsoup没有内容的标签不封闭,以防万一加上text就封闭了,
.text("")
} catch (e: Exception) {
logger.error(e) { "导出图片<$extra>出错," }
div.appendElement("p")
.text("$indent[image]")
}
}
val bytes = (root.outerHtml()).toByteArray(Charsets.UTF_8)
val resource = Resource(bytes, fileName)
book.addSection(name, resource)
// 这个guide不知道是否重要,
if (index == 0) {
book.guide.coverPage = resource
}
}
// EpubWriter不带缓冲,加个缓冲,不确定有多大效果,
// 这里use多余,write里面close了,
file.outputStream().buffered().use { output ->
EpubWriter().write(book, output)
}
progressCallback(total, total)
}
companion object {
const val OPS_PATH = "OEBPS"
}
} | gpl-3.0 | 1b7fdbde959cbece3d98f146698294a4 | 35.39548 | 119 | 0.456606 | 4.568085 | false | false | false | false |
rsiebert/TVHClient | data/src/main/java/org/tvheadend/data/source/ChannelDataSource.kt | 1 | 3769 | package org.tvheadend.data.source
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.tvheadend.data.db.AppRoomDatabase
import org.tvheadend.data.entity.Channel
import org.tvheadend.data.entity.ChannelEntity
import org.tvheadend.data.entity.EpgChannel
import timber.log.Timber
import java.util.*
class ChannelDataSource(private val db: AppRoomDatabase) : DataSourceInterface<Channel> {
private val ioScope = CoroutineScope(Dispatchers.IO)
override fun addItem(item: Channel) {
ioScope.launch { db.channelDao.insert(ChannelEntity.from(item)) }
}
fun addItems(items: List<Channel>) {
ioScope.launch { db.channelDao.insert(ArrayList(items.map { ChannelEntity.from(it) })) }
}
override fun updateItem(item: Channel) {
ioScope.launch { db.channelDao.update(ChannelEntity.from(item)) }
}
override fun removeItem(item: Channel) {
ioScope.launch { db.channelDao.delete(ChannelEntity.from(item)) }
}
fun removeItemById(id: Int) {
ioScope.launch { db.channelDao.deleteById(id) }
}
override fun getLiveDataItemCount(): LiveData<Int> {
return db.channelDao.itemCount
}
override fun getLiveDataItems(): LiveData<List<Channel>> {
return MutableLiveData()
}
override fun getLiveDataItemById(id: Any): LiveData<Channel> {
return MutableLiveData()
}
override fun getItemById(id: Any): Channel? {
var channel: Channel?
runBlocking(Dispatchers.IO) {
channel = db.channelDao.loadChannelByIdSync(id as Int)?.toChannel()
}
return channel
}
fun getChannels(sortOrder: Int = 0): List<Channel> {
val channels = ArrayList<Channel>()
runBlocking(Dispatchers.IO) {
channels.addAll(db.channelDao.loadAllChannelsSync(sortOrder).map { it.toChannel() })
}
return channels
}
override fun getItems(): List<Channel> {
return getChannels()
}
fun getItemByIdWithPrograms(id: Int, selectedTime: Long): Channel? {
var channel: Channel?
runBlocking(Dispatchers.IO) {
channel = db.channelDao.loadChannelByIdWithProgramsSync(id, selectedTime)?.toChannel()
}
return channel
}
fun getAllEpgChannels(channelSortOrder: Int, tagIds: List<Int>): LiveData<List<EpgChannel>> {
Timber.d("Loading epg channels with sort order $channelSortOrder and ${tagIds.size} tags")
return if (tagIds.isEmpty()) {
Transformations.map(db.channelDao.loadAllEpgChannels(channelSortOrder)) { entities ->
entities.map { it.toEpgChannel() }
}
} else {
Transformations.map(db.channelDao.loadAllEpgChannelsByTag(channelSortOrder, tagIds)) { entities ->
entities.map { it.toEpgChannel() }
}
}
}
fun getAllChannelsByTime(selectedTime: Long, channelSortOrder: Int, tagIds: List<Int>): LiveData<List<Channel>> {
Timber.d("Loading channels from time $selectedTime with sort order $channelSortOrder and ${tagIds.size} tags")
return if (tagIds.isEmpty()) {
Transformations.map(db.channelDao.loadAllChannelsByTime(selectedTime, channelSortOrder)) { entities ->
entities.map { it.toChannel() }
}
} else {
Transformations.map(db.channelDao.loadAllChannelsByTimeAndTag(selectedTime, channelSortOrder, tagIds)) { entities ->
entities.map { it.toChannel() }
}
}
}
}
| gpl-3.0 | 4eb9472fbb679b24677d90bee7e3eea4 | 34.556604 | 128 | 0.672592 | 4.519185 | false | false | false | false |
wiltonlazary/kotlin-native | samples/gitchurn/src/gitChurnMain/kotlin/GitCommit.kt | 1 | 1126 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package sample.gitchurn
import kotlinx.cinterop.*
import libgit2.*
class GitCommit(val repository: GitRepository, val commit: CPointer<git_commit>) {
fun close() = git_commit_free(commit)
val summary: String get() = git_commit_summary(commit)!!.toKString()
val time: git_time_t get() = git_commit_time(commit)
val tree: GitTree get() = memScoped {
val treePtr = allocPointerTo<git_tree>()
git_commit_tree(treePtr.ptr, commit).errorCheck()
GitTree(repository, treePtr.value!!)
}
val parents: List<GitCommit> get() = memScoped {
val count = git_commit_parentcount(commit).toInt()
val result = ArrayList<GitCommit>(count)
for (index in 0..count - 1) {
val commitPtr = allocPointerTo<git_commit>()
git_commit_parent(commitPtr.ptr, commit, index.toUInt()).errorCheck()
result.add(GitCommit(repository, commitPtr.value!!))
}
result
}
} | apache-2.0 | 80e7d1c3a897af2c106d040a51c94cff | 33.151515 | 101 | 0.655417 | 3.791246 | false | false | false | false |
nextcloud/android | app/src/main/java/com/nextcloud/client/database/entity/UploadEntity.kt | 1 | 2620 | /*
* Nextcloud Android client application
*
* @author Álvaro Brey
* Copyright (C) 2022 Álvaro Brey
* 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
* License as published by the Free Software Foundation; either
* version 3 of the License, or 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://www.gnu.org/licenses/>.
*
*/
package com.nextcloud.client.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
@Entity(tableName = ProviderTableMeta.UPLOADS_TABLE_NAME)
data class UploadEntity(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = ProviderTableMeta._ID)
val id: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_LOCAL_PATH)
val localPath: String?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_REMOTE_PATH)
val remotePath: String?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_ACCOUNT_NAME)
val accountName: String?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_FILE_SIZE)
val fileSize: Long?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_STATUS)
val status: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_LOCAL_BEHAVIOUR)
val localBehaviour: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_UPLOAD_TIME)
val uploadTime: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_NAME_COLLISION_POLICY)
val nameCollisionPolicy: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_IS_CREATE_REMOTE_FOLDER)
val isCreateRemoteFolder: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_UPLOAD_END_TIMESTAMP)
val uploadEndTimestamp: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_LAST_RESULT)
val lastResult: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_IS_WHILE_CHARGING_ONLY)
val isWhileChargingOnly: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_IS_WIFI_ONLY)
val isWifiOnly: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_CREATED_BY)
val createdBy: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_FOLDER_UNLOCK_TOKEN)
val folderUnlockToken: String?
)
| gpl-2.0 | 9a99e9c6e0ed28dc2ec8883084bc5593 | 39.276923 | 80 | 0.749427 | 4.25 | false | false | false | false |
goodwinnk/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/eventLog/LogEventRecordRequest.kt | 2 | 3905 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.eventLog
import com.google.gson.JsonSyntaxException
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.PermanentInstallationID
import com.intellij.openapi.diagnostic.Logger
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.io.IOException
import java.util.*
class LogEventRecordRequest(val product : String, val user: String, val records: List<LogEventRecord>) {
companion object {
private const val RECORD_SIZE = 1000 * 1000 // 1000KB
private val LOG = Logger.getInstance(LogEventRecordRequest::class.java)
fun create(file: File, filter: LogEventFilter): LogEventRecordRequest? {
try {
return create(file, ApplicationInfo.getInstance().build.productCode, PermanentInstallationID.get(), RECORD_SIZE, filter)
}
catch (e: Exception) {
LOG.warn("Failed reading event log file", e)
return null
}
}
fun create(file: File, product: String, user: String, maxRecordSize: Int, filter: LogEventFilter): LogEventRecordRequest? {
try {
val records = ArrayList<LogEventRecord>()
BufferedReader(FileReader(file.path)).use { reader ->
val sizeEstimator = LogEventRecordSizeEstimator(product, user)
var events = ArrayList<LogEvent>()
var line = fillNextBatch(reader, reader.readLine(), events, sizeEstimator, maxRecordSize, filter)
while (!events.isEmpty()) {
records.add(LogEventRecord(events))
events = ArrayList()
line = fillNextBatch(reader, line, events, sizeEstimator, maxRecordSize, filter)
}
}
return LogEventRecordRequest(product, user, records)
}
catch (e: JsonSyntaxException) {
LOG.warn(e)
}
catch (e: IOException) {
LOG.warn(e)
}
return null
}
private fun fillNextBatch(reader: BufferedReader,
firstLine: String?,
events: MutableList<LogEvent>,
estimator: LogEventRecordSizeEstimator,
maxRecordSize: Int,
filter: LogEventFilter) : String? {
var recordSize = 0
var line = firstLine
while (line != null && recordSize + estimator.estimate(line) < maxRecordSize) {
val event = LogEventSerializer.fromString(line)
if (event != null && filter.accepts(event)) {
recordSize += estimator.estimate(line)
events.add(event)
}
line = reader.readLine()
}
return line
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEventRecordRequest
if (product != other.product) return false
if (user != other.user) return false
if (records != other.records) return false
return true
}
override fun hashCode(): Int {
var result = product.hashCode()
result = 31 * result + user.hashCode()
result = 31 * result + records.hashCode()
return result
}
}
class LogEventRecord(val events: List<LogEvent>) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEventRecord
if (events != other.events) return false
return true
}
override fun hashCode(): Int {
return events.hashCode()
}
}
class LogEventRecordSizeEstimator(product : String, user: String) {
private val formatAdditionalSize = product.length + user.length + 2
fun estimate(line: String) : Int {
return line.length + formatAdditionalSize
}
} | apache-2.0 | 47165331863c996b5f87bd4f0afc91df | 32.101695 | 140 | 0.652497 | 4.682254 | false | false | false | false |
Kerr1Gan/ShareBox | share/src/main/java/com/ethan/and/ui/main/MainActivity.kt | 1 | 19271 | package com.ethan.and.ui.main
import android.animation.ObjectAnimator
import android.content.*
import android.graphics.drawable.RotateDrawable
import android.net.NetworkInfo
import android.net.wifi.WifiInfo
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.os.Message
import android.preference.PreferenceManager
import android.support.v7.widget.Toolbar
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import com.bumptech.glide.Glide
import com.common.componentes.activity.ImmersiveFragmentActivity
import com.flybd.sharebox.Constants
import com.flybd.sharebox.PreferenceInfo
import com.flybd.sharebox.R
import com.ethan.and.getMainApplication
import com.flybd.sharebox.presenter.MainActivityDelegate
import com.ethan.and.service.MainService
import com.ethan.and.ui.fragment.SplashFragment
import com.flybd.sharebox.util.admob.AdmobCallback
import com.flybd.sharebox.util.admob.AdmobManager
import org.ecjtu.easyserver.IAidlInterface
import org.ecjtu.easyserver.server.DeviceInfo
import org.ecjtu.easyserver.server.impl.service.EasyServerService
import org.ecjtu.easyserver.server.util.cache.ServerInfoParcelableHelper
class MainActivity : ImmersiveFragmentActivity(), MainContract.View {
companion object {
private const val TAG = "MainActivity"
private const val MSG_SERVICE_STARTED = 0x10
const val MSG_START_SERVER = 0x11
const val MSG_STOP_SERVER = 0x14
private const val MSG_LOADING_SERVER = 0x12
const val MSG_CLOSE_APP = -1
const val DEBUG = true
private const val CLOSE_TIME = 3 * 1000
}
private var mDelegate: MainActivityDelegate? = null
private var mAnimator: ObjectAnimator? = null
private var mReceiver: WifiApReceiver? = null
var refreshing = true
private var mService: IAidlInterface? = null
private var mAdManager: AdmobManager? = null
private var mMainService: MainService? = null
private lateinit var presenter: MainContract.Presenter
private var lastBackPressTime = -1L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// loadSplash()
setContentView(R.layout.activity_main)
var toolbar = findViewById<View>(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
mDelegate = MainActivityDelegate(this)
var drawer = findViewById<View>(R.id.drawer_view)
if (isNavigationBarShow(this)) {
drawer.setPadding(drawer.paddingLeft, drawer.paddingTop, drawer.paddingRight,
drawer.paddingBottom + getNavigationBarHeight(this))
val recyclerView = mDelegate?.getRecyclerView()
recyclerView?.setPadding(recyclerView.paddingLeft, recyclerView.paddingTop, recyclerView.paddingRight,
recyclerView.paddingBottom + getNavigationBarHeight(this))
}
// ad
initAd()
mReceiver = WifiApReceiver()
var filter = IntentFilter()
filter.addAction(mReceiver?.ACTION_WIFI_AP_CHANGED)
filter.addAction(mReceiver?.WIFI_STATE_CHANGED_ACTION)
filter.addAction(mReceiver?.NETWORK_STATE_CHANGED_ACTION)
filter.addAction(mReceiver?.CONNECTIVITY_ACTION)
filter.addAction(org.ecjtu.easyserver.server.Constants.ACTION_CLOSE_SERVER)
filter.addAction(org.ecjtu.easyserver.server.Constants.ACTION_UPDATE_SERVER)
registerReceiver(mReceiver, filter)
presenter = MainPresenter()
}
override fun onResume() {
super.onResume()
presenter.takeView(this)
getMainApplication().closeActivitiesByIndex(1)
var name = PreferenceManager.getDefaultSharedPreferences(this).getString(PreferenceInfo.PREF_DEVICE_NAME, Build.MODEL)
(findViewById<View>(R.id.text_name) as TextView).setText(name)
//resume service
val intent = Intent(this, MainService::class.java)
startService(intent)
bindService(intent, mMainServiceConnection, Context.BIND_AUTO_CREATE)
}
override fun onStop() {
super.onStop()
}
override fun onPause() {
super.onPause()
presenter.dropView()
}
override fun onDestroy() {
refreshing = false
mDelegate?.onDestroy()
getHandler()?.removeMessages(MSG_LOADING_SERVER)
unregisterReceiver(mReceiver)
try {
unbindService(mServiceConnection)
} catch (ignore: java.lang.Exception) {
}
try {
unbindService(mMainServiceConnection)
} catch (ignore: java.lang.Exception) {
}
// release main process
System.exit(0)
Glide.get(this).clearMemory()
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main_activity, menu)
var item = menu!!.findItem(R.id.refresh)
var rotateDrawable = item.icon as RotateDrawable
mAnimator = ObjectAnimator.ofInt(rotateDrawable, "level", 0, 10000) as ObjectAnimator?
mAnimator?.setRepeatMode(ObjectAnimator.RESTART)
mAnimator?.repeatCount = ObjectAnimator.INFINITE
mAnimator?.setDuration(1000)
mAnimator?.start()
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.refresh -> {
if (mAnimator?.isRunning == true) {
refreshing = false
mAnimator?.cancel()
} else {
refreshing = true
mAnimator?.start()
}
}
}
var result = mDelegate?.onOptionsItemSelected(item) ?: false
if (result) {
return result
}
return super.onOptionsItemSelected(item)
}
private inner class WifiApReceiver : BroadcastReceiver() {
val WIFI_AP_STATE_DISABLING = 10
val WIFI_AP_STATE_DISABLED = 11
val WIFI_AP_STATE_ENABLING = 12
val WIFI_AP_STATE_ENABLED = 13
val WIFI_AP_STATE_FAILED = 14
val WIFI_STATE_ENABLED = 3
val WIFI_STATE_DISABLED = 1
val EXTRA_WIFI_AP_STATE = "wifi_state"
val EXTRA_WIFI_STATE = "wifi_state"
val ACTION_WIFI_AP_CHANGED = "android.net.wifi.WIFI_AP_STATE_CHANGED"
val WIFI_STATE_CHANGED_ACTION = "android.net.wifi.WIFI_STATE_CHANGED"
val NETWORK_STATE_CHANGED_ACTION = "android.net.wifi.STATE_CHANGE"
val CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"
val EXTRA_WIFI_INFO = "wifiInfo"
val EXTRA_NETWORK_INFO = "networkInfo"
val TYPE_MOBILE = 0
override fun onReceive(context: Context, intent: Intent) {
val state = intent.getIntExtra(EXTRA_WIFI_AP_STATE, -1)
val action = intent.action
if (action == ACTION_WIFI_AP_CHANGED) {
when (state) {
WIFI_AP_STATE_ENABLED -> {
if (mDelegate?.checkCurrentNetwork(null) ?: false) {
if (mService != null) {
getHandler()?.obtainMessage(MSG_START_SERVER)?.sendToTarget()
} else {
startServerService()
}
}
var s = ""
when (state) {
WIFI_AP_STATE_DISABLED -> s = "WIFI_AP_STATE_DISABLED"
WIFI_AP_STATE_DISABLING -> s = "WIFI_AP_STATE_DISABLING"
WIFI_AP_STATE_ENABLED -> s = "WIFI_AP_STATE_ENABLED"
WIFI_AP_STATE_ENABLING -> s = "WIFI_AP_STATE_ENABLED"
WIFI_AP_STATE_FAILED -> s = "WIFI_AP_STATE_FAILED"
}
Log.i("WifiApReceiver", "ap " + s)
}
WIFI_AP_STATE_DISABLED -> {
getHandler()?.obtainMessage(MSG_STOP_SERVER)?.sendToTarget()
mDelegate?.checkCurrentNetwork(null)
}
else -> {
var s = ""
when (state) {
WIFI_AP_STATE_DISABLED -> s = "WIFI_AP_STATE_DISABLED"
WIFI_AP_STATE_DISABLING -> s = "WIFI_AP_STATE_DISABLING"
WIFI_AP_STATE_ENABLED -> s = "WIFI_AP_STATE_ENABLED"
WIFI_AP_STATE_ENABLING -> s = "WIFI_AP_STATE_ENABLED"
WIFI_AP_STATE_FAILED -> s = "WIFI_AP_STATE_FAILED"
}
Log.i("WifiApReceiver", "ap " + s)
}
}
} else if (action == WIFI_STATE_CHANGED_ACTION) { // wifi 连接上时,有可能不会回调
val localState = intent.getIntExtra(EXTRA_WIFI_STATE, -1)
when (localState) {
WIFI_STATE_ENABLED -> {
if (mDelegate?.checkCurrentNetwork(null) ?: false) {
if (mService != null) {
getHandler()?.obtainMessage(MSG_START_SERVER)?.sendToTarget()
} else {
startServerService()
}
}
}
WIFI_STATE_DISABLED -> {
getHandler()?.obtainMessage(MSG_STOP_SERVER)?.sendToTarget()
mDelegate?.checkCurrentNetwork(null)
}
}
} else if (action.equals(NETWORK_STATE_CHANGED_ACTION)) {
var wifiInfo = intent.getParcelableExtra<WifiInfo>(EXTRA_WIFI_INFO)
Log.i("WifiApReceiver", "WifiInfo " + wifiInfo?.toString() ?: "null")
if (wifiInfo != null) {
if (wifiInfo.bssid != null && !wifiInfo.bssid.equals("<none>")) // is a bug in ui
mDelegate?.checkCurrentNetwork(wifiInfo)
}
} else if (action.equals(CONNECTIVITY_ACTION)) {
var info = intent.getParcelableExtra<NetworkInfo>(EXTRA_NETWORK_INFO)
Log.i("WifiApReceiver", "NetworkInfo " + info?.toString() ?: "null")
if (info != null && info.type == TYPE_MOBILE && (info.state == NetworkInfo.State.CONNECTED ||
info.state == NetworkInfo.State.DISCONNECTED)) {
mDelegate?.checkCurrentNetwork(null)
} else if (info != null && (info.state == NetworkInfo.State.CONNECTED)) {
if (mDelegate?.checkCurrentNetwork(null) == true) {
startServerService()
}
}
} else if (action == org.ecjtu.easyserver.server.Constants.ACTION_CLOSE_SERVER) {
getHandler()?.sendEmptyMessage(MSG_CLOSE_APP)
} else if (action == org.ecjtu.easyserver.server.Constants.ACTION_UPDATE_SERVER) {
val pref = PreferenceManager.getDefaultSharedPreferences(this@MainActivity)
val name = pref.getString(PreferenceInfo.PREF_DEVICE_NAME, Build.MODEL)
val hostIP = pref.getString(org.ecjtu.easyserver.server.Constants.PREF_KEY_HOST_IP, "")
val port = pref.getInt(org.ecjtu.easyserver.server.Constants.PREF_KEY_HOST_PORT, 0)
if (!TextUtils.isEmpty(hostIP)) {
registerServerInfo(hostIP, port, name, mutableMapOf())
val deviceInfo = getMainApplication().getSavedInstance().get(Constants.KEY_INFO_OBJECT) as DeviceInfo
val helper = ServerInfoParcelableHelper([email protected])
helper.put(Constants.KEY_INFO_OBJECT, deviceInfo)
val intent = EasyServerService.getSetupServerIntent(this@MainActivity, Constants.KEY_INFO_OBJECT)
[email protected](intent)
getHandler()?.removeMessages(MSG_LOADING_SERVER)
getHandler()?.sendEmptyMessage(MSG_START_SERVER)
}
runOnUiThread { mDelegate?.doSearch() }
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
mDelegate?.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
private val mServiceConnection = object : ServiceConnection {
override fun onServiceDisconnected(name: ComponentName?) {
Log.e(TAG, "onServiceDisconnected " + name.toString()) // 子进程服务挂掉后会被回调
}
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
Log.e(TAG, "onServiceConnected " + name.toString())
mService = IAidlInterface.Stub.asInterface(service)
getHandler()?.obtainMessage(MSG_SERVICE_STARTED)?.sendToTarget()
}
}
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
when (msg.what) {
MSG_SERVICE_STARTED -> {
if (mDelegate?.checkCurrentNetwork(null) ?: false) {
getHandler()?.obtainMessage(MSG_START_SERVER)?.sendToTarget()
}
}
MSG_START_SERVER -> {
if (mService == null) return
var flag = false
if (mService?.isServerAlive() == false && getHandler()?.hasMessages(MSG_LOADING_SERVER) == false) {
flag = true
Log.e(TAG, "isServerAlive false,start server")
var intent = EasyServerService.getApIntent(this)
startService(intent)
getHandler()?.sendEmptyMessageDelayed(MSG_LOADING_SERVER, Int.MAX_VALUE.toLong())
} else if (getHandler()?.hasMessages(MSG_LOADING_SERVER) == false) {
// PreferenceManager.getDefaultSharedPreferences(this).edit().remove(Constants.PREF_SERVER_PORT).apply()
}
if (!flag && mDelegate != null) {
var name = PreferenceManager.getDefaultSharedPreferences(this).getString(PreferenceInfo.PREF_DEVICE_NAME, Build.MODEL)
if (mService != null && mService!!.ip != null && mService!!.port != 0) {
val deviceInfo = getMainApplication().getSavedInstance().get(Constants.KEY_INFO_OBJECT) as DeviceInfo?
deviceInfo?.let {
registerServerInfo(mService!!.ip, mService!!.port, name,
deviceInfo.fileMap)
}
}
runOnUiThread { mDelegate?.doSearch() }
}
}
MSG_STOP_SERVER -> {
stopServerService()
}
MSG_CLOSE_APP -> {
try {
unbindService(mServiceConnection)
unbindService(mMainServiceConnection)
} catch (e: java.lang.Exception) {
} finally {
stopService(Intent(this, EasyServerService::class.java))
stopService(Intent(this, MainService::class.java))
getMainApplication().closeApp()
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
mDelegate?.onActivityResult(requestCode, resultCode, data)
}
fun registerServerInfo(hostIP: String, port: Int, name: String, mutableMap: MutableMap<String, List<String>>) {
PreferenceManager.getDefaultSharedPreferences(this).edit().putInt(Constants.PREF_SERVER_PORT, port).apply()
val deviceInfo = getMainApplication().getSavedInstance().get(Constants.KEY_INFO_OBJECT) as DeviceInfo
deviceInfo.apply {
this.name = name
this.ip = hostIP
this.port = port
this.icon = "/API/Icon"
this.fileMap = mutableMap
this.updateTime = System.currentTimeMillis()
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (!DEBUG) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
this.moveTaskToBack(true)
return true
}
}
return super.onKeyDown(keyCode, event)
}
override fun onBackPressed() {
if (lastBackPressTime < 0) {
lastBackPressTime = System.currentTimeMillis()
return
}
if (System.currentTimeMillis() - lastBackPressTime < CLOSE_TIME) {
super.onBackPressed()
}
}
private fun initAd() {
mAdManager = AdmobManager(this)
mAdManager?.loadInterstitialAd(getString(R.string.admob_ad_02), object : AdmobCallback {
override fun onLoaded() {
mAdManager?.getLatestInterstitialAd()?.show()
}
override fun onError() {
mAdManager?.loadInterstitialAd(getString(R.string.admob_ad_02), this)
}
override fun onOpened() {
}
override fun onClosed() {
mAdManager = null
}
})
}
private fun loadSplash() {
val intent = ImmersiveFragmentActivity.newInstance(this, SplashFragment::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NO_ANIMATION
startActivity(intent)
}
private val mMainServiceConnection = object : ServiceConnection {
override fun onServiceDisconnected(name: ComponentName?) {
mMainService = null
}
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
mMainService = (service as MainService.MainServiceBinder).service
//start server
startServerService()
}
}
fun getMainService(): MainService? {
return mMainService
}
fun getServerService(): IAidlInterface? {
return mService
}
fun stopServerService() {
Log.i(TAG, "stopServerService")
if (mService == null) return
try {
unbindService(mServiceConnection)
} catch (ex: Exception) {
ex.printStackTrace()
} finally {
stopService(Intent(this, EasyServerService::class.java))
mService = null
}
}
fun startServerService() {
Log.i(TAG, "startServerService")
if (mService == null) {
var intent = Intent(this@MainActivity, EasyServerService::class.java)
startService(intent)
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE)
}
}
}
| apache-2.0 | 09f23d4d7022f8cf7ade6636c5cb7260 | 38.230612 | 138 | 0.58378 | 5.034835 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/nbt/tags/TagDouble.kt | 1 | 1192 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.tags
import java.io.DataOutputStream
import java.text.DecimalFormat
import java.text.NumberFormat
import java.util.Locale
class TagDouble(override val value: Double) : NbtValueTag<Double>(Double::class.java) {
override val payloadSize = 8
override val typeId = NbtTypeId.DOUBLE
override fun write(stream: DataOutputStream) {
stream.writeDouble(value)
}
override fun toString() = toString(StringBuilder(), 0, WriterState.COMPOUND).toString()
override fun toString(sb: StringBuilder, indentLevel: Int, writerState: WriterState): StringBuilder {
return sb.append(FORMATTER.format(value))
}
companion object {
val FORMATTER = (NumberFormat.getInstance(Locale.ROOT) as DecimalFormat).apply {
minimumFractionDigits = 1 // Default NBTT double format always uses a fraction, like in Kotlin
maximumFractionDigits = 20 // Should be more than enough, but let's use 20 just in case
groupingSize = 0 // Disables thousands separator
}
}
}
| mit | e31108ba002292547f3033a09c8da128 | 29.564103 | 106 | 0.704698 | 4.431227 | false | false | false | false |
equeim/tremotesf-android | app/src/main/kotlin/org/equeim/tremotesf/ui/torrentslistfragment/TrackersViewAdapter.kt | 1 | 2651 | /*
* Copyright (C) 2017-2022 Alexey Rochev <[email protected]>
*
* This file is part of Tremotesf.
*
* Tremotesf is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Tremotesf is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.equeim.tremotesf.ui.torrentslistfragment
import android.content.Context
import android.widget.AutoCompleteTextView
import org.equeim.tremotesf.R
import org.equeim.tremotesf.torrentfile.rpc.Torrent
import org.equeim.tremotesf.rpc.GlobalRpc
import org.equeim.tremotesf.common.AlphanumericComparator
import org.equeim.tremotesf.ui.utils.AutoCompleteTextViewDynamicAdapter
class TrackersViewAdapter(
private val context: Context,
textView: AutoCompleteTextView
) : AutoCompleteTextViewDynamicAdapter(textView) {
private val trackersMap = mutableMapOf<String, Int>()
val trackers = mutableListOf<String>()
private val comparator = AlphanumericComparator()
private var trackerFilter = ""
override fun getItem(position: Int): String {
if (position == 0) {
return context.getString(R.string.torrents_all, GlobalRpc.torrents.value.size)
}
val tracker = trackers[position - 1]
val torrents = trackersMap[tracker]
return context.getString(R.string.trackers_spinner_text, tracker, torrents)
}
override fun getCount(): Int {
return trackers.size + 1
}
override fun getCurrentItem(): CharSequence {
return getItem(trackers.indexOf(trackerFilter) + 1)
}
fun getTrackerFilter(position: Int): String {
return if (position == 0) {
""
} else {
trackers[position - 1]
}
}
fun update(torrents: List<Torrent>, trackerFilter: String) {
this.trackerFilter = trackerFilter
trackersMap.clear()
for (torrent in torrents) {
for (tracker in torrent.trackerSites) {
trackersMap[tracker] = trackersMap.getOrElse(tracker) { 0 } + 1
}
}
trackers.clear()
trackers.addAll(trackersMap.keys.sortedWith(comparator))
notifyDataSetChanged()
}
} | gpl-3.0 | 68c2bf7b8fbe85cdd8c3b863e7301206 | 32.56962 | 90 | 0.694078 | 4.500849 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/controllers/dialogs/CreateTicketDialog.kt | 1 | 9202 | package de.xikolo.controllers.dialogs
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.DialogInterface
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.Html
import android.text.InputType
import android.text.TextWatcher
import android.util.Patterns
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.browser.customtabs.CustomTabsIntent
import androidx.core.content.ContextCompat
import butterknife.BindView
import com.yatatsu.autobundle.AutoBundleField
import de.xikolo.App
import de.xikolo.R
import de.xikolo.config.Feature
import de.xikolo.controllers.dialogs.base.ViewModelDialogFragment
import de.xikolo.managers.UserManager
import de.xikolo.models.TicketTopic
import de.xikolo.models.dao.CourseDao
import de.xikolo.utils.extensions.getString
import de.xikolo.utils.extensions.isOnline
import de.xikolo.utils.extensions.showToast
import de.xikolo.viewmodels.helpdesk.TicketViewModel
class CreateTicketDialog : ViewModelDialogFragment<TicketViewModel>(), HelpdeskTopicDialog.HelpdeskTopicListener, ConfirmCancelDialog.ConfirmCancelListener {
companion object {
@JvmField
val TAG: String = CreateTicketDialog::class.java.simpleName
}
@AutoBundleField(required = false)
var courseId: String? = null
@BindView(R.id.ticketContent)
lateinit var messageEditText: EditText
@BindView(R.id.textInputLayoutEmail)
lateinit var emailContainer: ViewGroup
@BindView(R.id.ticketEmail)
lateinit var emailEditText: EditText
@BindView(R.id.ticketTitle)
lateinit var titleEditText: EditText
@BindView(R.id.ticketTopic)
lateinit var ticketTopicEditText: EditText
@BindView(R.id.ticketInfoText)
lateinit var ticketInfoText: TextView
@BindView(R.id.infoCard)
lateinit var infoCard: ViewGroup
@BindView(R.id.infoCardText)
lateinit var infoCardText: TextView
private var topic: TicketTopic = TicketTopic.NONE
override val layoutResource = R.layout.dialog_helpdesk_create_ticket
override fun createViewModel(): TicketViewModel {
return TicketViewModel()
}
@SuppressLint("SetTextI18n")
override fun onDialogViewCreated(view: View, savedInstanceState: Bundle?) {
super.onDialogViewCreated(view, savedInstanceState)
if (!context.isOnline) {
showToast(R.string.toast_no_network)
dialog?.cancel()
return
}
networkStateHelper.enableSwipeRefresh(false)
if (courseId == null) {
changeTopic(false)
} else {
ticketTopicEditText.setText(CourseDao.Unmanaged.find(courseId)?.title)
topic = TicketTopic.COURSE
}
if (UserManager.isAuthorized) {
emailContainer.visibility = View.GONE
ticketInfoText.text = getString(R.string.helpdesk_info_text_logged_in)
}
if (Feature.enabled("url_faq")) {
var text = getString(R.string.helpdesk_info_text_faq) +
" " + getString(R.string.helpdesk_info_text_forum)
var html = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(text, Html.FROM_HTML_MODE_COMPACT)
} else {
Html.fromHtml(text)
}
infoCardText.text = html
infoCard.setOnClickListener {
activity?.let {
CustomTabsIntent.Builder()
.setToolbarColor(ContextCompat.getColor(
App.instance,
R.color.apptheme_primary
))
.build()
.launchUrl(it, Uri.parse(it.getString("url_faq")))
}
}
} else {
infoCardText.text = getString(R.string.helpdesk_info_text_forum)
}
//listeners for wrong entries in EditTexts after focusing another view
titleEditText.setOnFocusChangeListener { _, b ->
if (titleEditText.text.isEmpty() && !b) {
titleEditText.error = getString(R.string.helpdesk_title_error)
}
setPositiveButton()
}
messageEditText.setOnFocusChangeListener { _, b ->
if (messageEditText.text.isEmpty() && !b) {
messageEditText.error = getString(R.string.helpdesk_message_error)
}
setPositiveButton()
}
emailEditText.setOnFocusChangeListener { _, b ->
if ((!Patterns.EMAIL_ADDRESS.matcher(emailEditText.text).matches() || emailEditText.text.isEmpty()) &&
emailContainer.visibility != View.GONE && !b) {
emailEditText.error = getString(R.string.helpdesk_email_error)
}
}
//listeners for positive button to change while typing
val textWatcher = object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
setPositiveButton()
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
}
messageEditText.addTextChangedListener(textWatcher)
emailEditText.addTextChangedListener(textWatcher)
titleEditText.addTextChangedListener(textWatcher)
ticketTopicEditText.addTextChangedListener(textWatcher)
ticketTopicEditText.setOnClickListener {
changeTopic(true)
}
ticketTopicEditText.inputType = InputType.TYPE_NULL
showContent()
}
override fun onResume() {
super.onResume()
(dialog as? AlertDialog)?.apply {
getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener {
cancel(this)
}
getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
if (context.isOnline) {
viewModel.send(titleEditText.text.toString(), messageEditText.text.toString(), topic, emailEditText.text.toString(), courseId)
dialog?.dismiss()
} else {
showToast(R.string.toast_no_network)
}
}
}
//needed for initial disabling of positive button
setPositiveButton()
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(requireActivity())
.setNegativeButton(R.string.dialog_negative) { _: DialogInterface, _: Int ->
//see onResume
}
.setPositiveButton(R.string.dialog_send) { _: DialogInterface, _: Int ->
//see onResume
}
.setView(dialogView)
.setTitle(R.string.helpdesk_dialog_header)
.setOnCancelListener { dialog: DialogInterface ->
cancel(dialog)
}
.setOnKeyListener { dialog, keyCode, keyEvent ->
if (keyEvent.action == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
cancel(dialog)
return@setOnKeyListener true
}
false
}
.create()
}
private fun cancel(dialog: DialogInterface) {
if (atLeastOneFieldHasInput) {
confirmCancel()
} else {
dialog.dismiss()
}
}
private fun changeTopic(isChange: Boolean) {
val dialog = HelpdeskTopicDialogAutoBundle.builder().fromTicketDialog(isChange).build()
dialog.listener = this
dialog.show(fragmentManager!!, HelpdeskTopicDialog.TAG)
}
override fun onTopicChosen(title: String?, topic: TicketTopic, courseId: String?) {
this.courseId = courseId
this.topic = topic
ticketTopicEditText.setText(title)
}
fun setPositiveButton() {
(dialog as AlertDialog).getButton(AlertDialog.BUTTON_POSITIVE)?.isEnabled = allFieldsHaveInput
}
override fun closeTicketDialog() {
dialog?.dismiss()
}
override fun onConfirmCancel() {
closeTicketDialog()
}
private val atLeastOneFieldHasInput: Boolean
get() =
(titleEditText.text.isNotEmpty() ||
messageEditText.text.isNotEmpty() ||
emailEditText.text.isNotEmpty())
private val allFieldsHaveInput: Boolean
get() = titleEditText.text.isNotEmpty() &&
messageEditText.text.isNotEmpty() &&
ticketTopicEditText.text.isNotEmpty() &&
((emailEditText.text.isNotEmpty() && Patterns.EMAIL_ADDRESS.matcher(emailEditText.text).matches()) ||
emailContainer.visibility == View.GONE) && topic !== TicketTopic.NONE
private fun confirmCancel() {
val dialog = ConfirmCancelDialog()
dialog.listener = this
dialog.show(fragmentManager!!, ConfirmCancelDialog.TAG)
}
}
| bsd-3-clause | f9de0f2c92995a0c6eed23d8e2651f11 | 33.081481 | 157 | 0.63171 | 5.058824 | false | false | false | false |
bozaro/git-as-svn | src/main/kotlin/svnserver/repository/git/path/matcher/name/SimpleMatcher.kt | 1 | 1808 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.repository.git.path.matcher.name
import svnserver.repository.git.path.NameMatcher
/**
* Simple matcher for mask with only one asterisk.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class SimpleMatcher constructor(private val prefix: String, private val suffix: String, private val dirOnly: Boolean) : NameMatcher {
override fun isMatch(name: String, isDir: Boolean): Boolean {
return (!dirOnly || isDir) && (name.length >= prefix.length + suffix.length) && name.startsWith(prefix) && name.endsWith(suffix)
}
override val isRecursive: Boolean
get() {
return false
}
override val svnMask: String
get() {
return "$prefix*$suffix"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val that: SimpleMatcher = other as SimpleMatcher
return ((dirOnly == that.dirOnly)
&& ((prefix == that.prefix))
&& (suffix == that.suffix))
}
override fun hashCode(): Int {
var result: Int = prefix.hashCode()
result = 31 * result + suffix.hashCode()
result = 31 * result + (if (dirOnly) 1 else 0)
return result
}
override fun toString(): String {
return prefix + "*" + suffix + (if (dirOnly) "/" else "")
}
}
| gpl-2.0 | 33ff001e6d727dfdc9bdce3989c256dd | 35.16 | 136 | 0.634956 | 4.214452 | false | false | false | false |
panpf/sketch | sketch/src/androidTest/java/com/github/panpf/sketch/test/request/internal/CombinedListenerTest.kt | 1 | 4862 | /*
* Copyright (C) 2022 panpf <[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.github.panpf.sketch.test.request.internal
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.panpf.sketch.datasource.DataFrom.MEMORY
import com.github.panpf.sketch.request.DownloadData
import com.github.panpf.sketch.request.DownloadRequest
import com.github.panpf.sketch.request.DownloadResult
import com.github.panpf.sketch.request.Listener
import com.github.panpf.sketch.request.internal.CombinedListener
import com.github.panpf.sketch.test.utils.getTestContext
import com.github.panpf.sketch.util.UnknownException
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class CombinedListenerTest {
@Test
fun test() {
val listenerCallbackList = mutableListOf<String>()
Assert.assertEquals(listOf<String>(), listenerCallbackList)
val listener1 =
object : Listener<DownloadRequest, DownloadResult.Success, DownloadResult.Error> {
override fun onStart(request: DownloadRequest) {
super.onStart(request)
listenerCallbackList.add("onStart1")
}
override fun onSuccess(request: DownloadRequest, result: DownloadResult.Success) {
super.onSuccess(request, result)
listenerCallbackList.add("onSuccess1")
}
override fun onError(request: DownloadRequest, result: DownloadResult.Error) {
super.onError(request, result)
listenerCallbackList.add("onError1")
}
override fun onCancel(request: DownloadRequest) {
super.onCancel(request)
listenerCallbackList.add("onCancel1")
}
}
val listener2 =
object : Listener<DownloadRequest, DownloadResult.Success, DownloadResult.Error> {
override fun onStart(request: DownloadRequest) {
super.onStart(request)
listenerCallbackList.add("onStart2")
}
override fun onSuccess(request: DownloadRequest, result: DownloadResult.Success) {
super.onSuccess(request, result)
listenerCallbackList.add("onSuccess2")
}
override fun onError(request: DownloadRequest, result: DownloadResult.Error) {
super.onError(request, result)
listenerCallbackList.add("onError2")
}
override fun onCancel(request: DownloadRequest) {
super.onCancel(request)
listenerCallbackList.add("onCancel2")
}
}
val context = getTestContext()
val request = DownloadRequest(context, "http://sample.com/sample.jpeg")
val combinedListener = CombinedListener(listener1, listener2)
Assert.assertSame(listener1, combinedListener.fromProviderListener)
Assert.assertSame(listener2, combinedListener.fromBuilderListener)
combinedListener.onStart(request)
Assert.assertEquals(listOf("onStart1", "onStart2"), listenerCallbackList)
combinedListener.onError(request, DownloadResult.Error(request, UnknownException("")))
Assert.assertEquals(
listOf("onStart1", "onStart2", "onError1", "onError2"),
listenerCallbackList
)
combinedListener.onCancel(request)
Assert.assertEquals(
listOf(
"onStart1",
"onStart2",
"onError1",
"onError2",
"onCancel1",
"onCancel2"
), listenerCallbackList
)
combinedListener.onSuccess(
request,
DownloadResult.Success(request, DownloadData(byteArrayOf(), MEMORY))
)
Assert.assertEquals(
listOf(
"onStart1",
"onStart2",
"onError1",
"onError2",
"onCancel1",
"onCancel2",
"onSuccess1",
"onSuccess2"
), listenerCallbackList
)
}
} | apache-2.0 | e1a13eb48cdb6c163f6acbe99c7794b5 | 36.697674 | 98 | 0.616002 | 5.348735 | false | true | false | false |
marcelgross90/Cineaste | app/src/main/kotlin/de/cineaste/android/activity/AbstractSearchActivity.kt | 1 | 7069 | package de.cineaste.android.activity
import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Pair
import android.view.Menu
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
import com.google.gson.JsonParser
import de.cineaste.android.R
import de.cineaste.android.listener.ItemClickListener
import de.cineaste.android.network.NetworkCallback
import de.cineaste.android.network.NetworkResponse
import de.cineaste.android.util.DateAwareGson
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.lang.reflect.Type
abstract class AbstractSearchActivity : AppCompatActivity(), ItemClickListener {
internal val gson = DateAwareGson.gson
internal lateinit var recyclerView: RecyclerView
internal lateinit var progressBar: ProgressBar
private lateinit var searchView: SearchView
private var searchText: String? = null
protected abstract val layout: Int
protected abstract val listAdapter: RecyclerView.Adapter<*>
protected abstract val listType: Type
val networkCallback: NetworkCallback
get() = object : NetworkCallback {
override fun onFailure() {
GlobalScope.launch(Main) { showNetworkError() }
}
override fun onSuccess(response: NetworkResponse) {
val responseObject = JsonParser.parseReader(response.responseReader).asJsonObject
val json = responseObject.get("results").toString()
val listType = listType
GlobalScope.launch(Main) { getRunnable(json, listType).run() }
}
}
protected abstract fun getIntentForDetailActivity(itemId: Long): Intent
protected abstract fun initAdapter()
protected abstract fun getSuggestions()
protected abstract fun searchRequest(searchQuery: String)
protected abstract fun getRunnable(json: String, listType: Type): Runnable
override fun onItemClickListener(itemId: Long, views: Array<View>) {
val intent = getIntentForDetailActivity(itemId)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val options = ActivityOptions.makeSceneTransitionAnimation(
this,
Pair.create(views[0], "card"),
Pair.create(views[1], "poster")
)
this.startActivity(intent, options.toBundle())
} else {
this.startActivity(intent)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(layout)
initToolbar()
if (savedInstanceState != null) {
searchText = savedInstanceState.getString("query", "").replace("+", " ")
}
progressBar = findViewById(R.id.progressBar)
recyclerView = findViewById(R.id.search_recycler_view)
val layoutManager = LinearLayoutManager(this)
val divider = ContextCompat.getDrawable(recyclerView.context, R.drawable.divider)
val itemDecor = DividerItemDecoration(
recyclerView.context,
layoutManager.orientation
)
divider?.let {
itemDecor.setDrawable(it)
}
recyclerView.addItemDecoration(itemDecor)
initAdapter()
recyclerView.itemAnimator = DefaultItemAnimator()
recyclerView.layoutManager = layoutManager
recyclerView.adapter = listAdapter
progressBar.visibility = View.VISIBLE
getSuggestions()
}
private fun initToolbar() {
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val actionBar = supportActionBar
actionBar?.setDisplayHomeAsUpEnabled(true)
}
public override fun onSaveInstanceState(outState: Bundle) {
if (!TextUtils.isEmpty(searchText)) {
outState.putString("query", searchText)
}
super.onSaveInstanceState(outState)
}
public override fun onPause() {
super.onPause()
val outState = Bundle()
outState.putString("query", searchText)
onSaveInstanceState(outState)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val menuInflater = menuInflater
menuInflater.inflate(R.menu.search_menu, menu)
val searchItem = menu.findItem(R.id.action_search)
if (searchItem != null) {
searchView = searchItem.actionView as SearchView
searchView.isFocusable = true
searchView.isIconified = false
searchView.requestFocusFromTouch()
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
return false
}
override fun onQueryTextChange(query: String): Boolean {
var myQuery = query
if (myQuery.isNotEmpty()) {
myQuery = myQuery.replace(" ", "+")
progressBar.visibility = View.VISIBLE
scheduleSearchRequest(myQuery)
searchText = myQuery
} else {
getSuggestions()
}
return false
}
})
if (!TextUtils.isEmpty(searchText))
searchView.setQuery(searchText, false)
}
return super.onCreateOptionsMenu(menu)
}
private fun scheduleSearchRequest(query: String) {
searchView.removeCallbacks(getSearchRunnable(query))
searchView.postDelayed(getSearchRunnable(query), 500)
}
private fun getSearchRunnable(searchQuery: String): Runnable {
return Runnable { searchRequest(searchQuery) }
}
private fun showNetworkError() {
val snackBar = Snackbar
.make(recyclerView, R.string.noInternet, Snackbar.LENGTH_LONG)
snackBar.show()
}
override fun onStop() {
super.onStop()
val view = currentFocus
if (view != null) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromInputMethod(view.windowToken, 0)
}
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return super.onSupportNavigateUp()
}
}
| gpl-3.0 | 4cd61e2c242245f5c41cdadf2bd02421 | 34.169154 | 97 | 0.666007 | 5.514041 | false | false | false | false |
kotlinz/kotlinz | src/main/kotlin/com/github/kotlinz/kotlinz/data/identity/IdentityMonadOps.kt | 1 | 1048 | package com.github.kotlinz.kotlinz.data.identity
import com.github.kotlinz.kotlinz.K1
import com.github.kotlinz.kotlinz.type.monad.MonadOps
interface IdentityMonadOps: MonadOps<Identity.T>, IdentityMonad {
override fun <A, B> liftM(f: (A) -> B): (K1<Identity.T, A>) -> K1<Identity.T, B> {
return { m ->
val i = Identity.narrow(m)
i bind { x -> Identity.pure(f(x)) }
}
}
override fun <A, B, C> liftM2(f: (A, B) -> C): (K1<Identity.T, A>, K1<Identity.T, B>) -> K1<Identity.T, C> {
return { m1, m2 ->
val i1 = Identity.narrow(m1)
val i2 = Identity.narrow(m2)
i1 bind { x1 -> i2 bind { x2 -> Identity.pure(f(x1, x2)) } }
}
}
override fun <A, B, C, D> liftM3(f: (A, B, C) -> D): (K1<Identity.T, A>, K1<Identity.T, B>, K1<Identity.T, C>) -> K1<Identity.T, D> {
return { m1, m2, m3 ->
val i1 = Identity.narrow(m1)
val i2 = Identity.narrow(m2)
val i3 = Identity.narrow(m3)
i1 bind { x1 -> i2 bind { x2 -> i3 bind { x3 -> Identity.pure(f(x1, x2, x3)) } } }
}
}
} | apache-2.0 | 3b081f832dd8555c0300ef2880f9966b | 33.966667 | 135 | 0.574427 | 2.531401 | false | false | false | false |
ice1000/OI-codes | codewars/authoring/kotlin/Immortal.kt | 1 | 1706 | private var p = 1e9.toInt().toLong()
/**
* set true to enable debug
*/
internal var debug = false
private fun log2(x: Long): Int {
var x = x
var ans = 0
while (true) {
x = x shr 1
if (x == 0L) break
ans++
}
return ans
}
private fun mul(x: Long, y: Long, z: Long): Long {
var x = x
var y = y
if (z == 2L) {
when {
x and 1 != 0L -> y = y shr 1
y and 1 != 0L -> x = x shr 1
else -> throw RuntimeException("shit")
}
}
return x % p * (y % p) % p
}
private fun sumTimes(first: Long, n: Long, k: Long, t: Long): Long {
var first = first
var n = n
first -= k
if (first < 1) {
n -= 1 - first
first = 1
}
return if (n <= 0) 0 else mul(mul(first + first + n - 1, n, 2L), t, 1)
}
internal fun elderAge(n: Long, m: Long, k: Long, newp: Long): Long {
var n = n
var m = m
var k = k
if (n == 0L || m == 0L) return 0
if (k < 0) k = 0
if (n < m) {
val tmp = n
n = m
m = tmp
}
p = newp
if (n == m && n and -n == n) return sumTimes(1, n - 1, k, m)
val N = log2(n)
val M = log2(m)
val centerWidth = 1L shl N
val centerHeight = 1L shl M
if (N == M) {
val rightWidth = n - centerWidth
val bottomHeight = m - centerHeight
val bottomSum = sumTimes(centerHeight, centerWidth, k, bottomHeight)
return ((sumTimes(centerWidth, centerHeight, k, rightWidth) + bottomSum) % p + (elderAge(rightWidth, bottomHeight, k, p) + elderAge(centerWidth, centerHeight, k, p)) % p) % p
} else {
val leftWidth = 1L shl N
val leftSum = sumTimes(0, leftWidth, k, m)
var rightSum = elderAge(n - leftWidth, m, k - leftWidth, p)
if (leftWidth > k) {
rightSum += mul(mul(leftWidth - k, m, 1), n - leftWidth, 1)
rightSum %= p
}
return (leftSum + rightSum) % p
}
}
| agpl-3.0 | 2ef4f09ea148c6b25bda35fbe71979b2 | 21.746667 | 176 | 0.57796 | 2.468886 | false | false | false | false |
exponent/exponent | packages/expo-modules-core/android/src/main/java/expo/modules/kotlin/ModuleRegistry.kt | 2 | 1560 | package expo.modules.kotlin
import expo.modules.kotlin.events.EventName
import expo.modules.kotlin.modules.Module
import java.lang.ref.WeakReference
class ModuleRegistry(
private val appContext: WeakReference<AppContext>
) : Iterable<ModuleHolder> {
private val registry = mutableMapOf<String, ModuleHolder>()
fun register(module: Module) {
val holder = ModuleHolder(module)
module._appContext = requireNotNull(appContext.get()) { "Cannot create a module for invalid app context." }
holder.post(EventName.MODULE_CREATE)
registry[holder.name] = holder
}
fun register(provider: ModulesProvider) = apply {
provider.getModulesList().forEach { type ->
val module = type.newInstance()
register(module)
}
}
fun hasModule(name: String): Boolean = registry.containsKey(name)
fun getModule(name: String): Module? = registry[name]?.module
fun getModuleHolder(name: String): ModuleHolder? = registry[name]
fun getModuleHolder(module: Module): ModuleHolder? =
registry.values.find { it.module === module }
fun post(eventName: EventName) {
forEach {
it.post(eventName)
}
}
@Suppress("UNCHECKED_CAST")
fun <Sender> post(eventName: EventName, sender: Sender) {
forEach {
it.post(eventName, sender)
}
}
@Suppress("UNCHECKED_CAST")
fun <Sender, Payload> post(eventName: EventName, sender: Sender, payload: Payload) {
forEach {
it.post(eventName, sender, payload)
}
}
override fun iterator(): Iterator<ModuleHolder> = registry.values.iterator()
}
| bsd-3-clause | 90614d194c5f37e52a592f0eeeeecf97 | 26.857143 | 111 | 0.704487 | 4.094488 | false | false | false | false |
afollestad/photo-affix | engine/src/test/java/com/afollestad/photoaffix/engine/AffixEngineTest.kt | 1 | 5662 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.afollestad.photoaffix.engine
import android.graphics.Bitmap
import android.graphics.Bitmap.CompressFormat.PNG
import com.afollestad.photoaffix.engine.bitmaps.BitmapIterator
import com.afollestad.photoaffix.engine.bitmaps.BitmapManipulator
import com.afollestad.photoaffix.engine.photos.Photo
import com.afollestad.photoaffix.engine.subengines.DimensionsEngine
import com.afollestad.photoaffix.engine.subengines.ProcessingResult
import com.afollestad.photoaffix.engine.subengines.Size
import com.afollestad.photoaffix.engine.subengines.SizingResult
import com.afollestad.photoaffix.engine.subengines.StitchEngine
import com.afollestad.photoaffix.utilities.IoManager
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.doAnswer
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import kotlinx.coroutines.runBlocking
import org.junit.Test
import java.io.File
class AffixEngineTest {
private val photos = listOf(
Photo(0, "file://idk/1", 0, testUriParser),
Photo(0, "file://idk/2", 0, testUriParser)
)
private val ioManager = mock<IoManager>()
private val bitmapManipulator = mock<BitmapManipulator>()
private val bitmapIterator = BitmapIterator(photos, bitmapManipulator)
private val dimensionsEngine = mock<DimensionsEngine>()
private val stitchEngine = mock<StitchEngine>()
private val engine = RealAffixEngine(
ioManager,
bitmapManipulator,
dimensionsEngine,
stitchEngine
)
// Process
@Test fun process() = runBlocking {
val size = Size(width = 1, height = 1)
val sizingResult = SizingResult(size = size)
whenever(dimensionsEngine.calculateSize(any()))
.doReturn(sizingResult)
val processResult = engine.process(photos)
assertThat(engine.getBitmapIterator().size()).isEqualTo(photos.size)
assertThat(processResult).isEqualTo(sizingResult)
}
// Commit results
@Test fun commitResult_noProcessed() = runBlocking {
engine.setBitmapIterator(bitmapIterator)
val bitmap = mock<Bitmap>()
val processingResult = ProcessingResult(
processedCount = 0,
output = bitmap
)
whenever(
stitchEngine.stitch(
bitmapIterator = bitmapIterator,
selectedScale = 1.0,
resultWidth = 1,
resultHeight = 1,
format = PNG,
quality = 100
)
).doReturn(processingResult)
val result = engine.commit(
scale = 1.0,
width = 1,
height = 1,
format = PNG,
quality = 100
)
assertThat(result.error).isNotNull()
assertThat(result.outputFile).isNull()
verify(bitmap).recycle()
}
@Test fun commitResult() = runBlocking {
engine.setBitmapIterator(bitmapIterator)
val bitmap = mock<Bitmap>()
val processingResult = ProcessingResult(
processedCount = 1,
output = bitmap
)
val outputFile = mock<File>()
whenever(ioManager.makeTempFile(".png"))
.doReturn(outputFile)
whenever(
stitchEngine.stitch(
bitmapIterator = bitmapIterator,
selectedScale = 1.0,
resultWidth = 1,
resultHeight = 1,
format = PNG,
quality = 100
)
).doReturn(processingResult)
val result = engine.commit(
scale = 1.0,
width = 1,
height = 1,
format = PNG,
quality = 100
)
assertThat(result.error).isNull()
assertThat(result.outputFile).isEqualTo(outputFile)
verify(bitmap).recycle()
verify(outputFile, never()).delete()
verify(bitmapManipulator).encodeBitmap(
bitmap = bitmap,
format = PNG,
quality = 100,
file = outputFile
)
}
@Test fun commitResult_encodeError() = runBlocking {
engine.setBitmapIterator(bitmapIterator)
val bitmap = mock<Bitmap>()
val processingResult = ProcessingResult(
processedCount = 0,
output = bitmap
)
val outputFile = mock<File>()
whenever(ioManager.makeTempFile(".png"))
.doReturn(outputFile)
whenever(
stitchEngine.stitch(
bitmapIterator = bitmapIterator,
selectedScale = 1.0,
resultWidth = 1,
resultHeight = 1,
format = PNG,
quality = 100
)
).doReturn(processingResult)
val error = Exception("Oh no!")
whenever(
bitmapManipulator.encodeBitmap(
any(), any(), any(), any()
)
).doAnswer { throw error }
val result = engine.commit(
scale = 1.0,
width = 1,
height = 1,
format = PNG,
quality = 100
)
verify(bitmap).recycle()
//verify(outputFile).delete()
assertThat(result.error).isNotNull()
assertThat(result.outputFile).isNull()
}
}
| apache-2.0 | 78f83084f4a1066c1b05fbf74d955e30 | 28.035897 | 75 | 0.672201 | 4.533227 | false | false | false | false |
tbaxter120/Restdroid | app/src/main/java/com/ridocula/restdroid/fragments/AddRequestCollectionDialog.kt | 1 | 2427 | package com.ridocula.restdroid.fragments
import android.app.Dialog
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.app.AlertDialog
import android.widget.EditText
import com.ridocula.restdroid.R
import com.ridocula.restdroid.models.RequestCollection
import com.ridocula.restdroid.persistence.repository.LocalRequestRepository
import com.ridocula.restdroid.util.Utility
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
/**
* Created by tbaxter on 9/9/17.
*/
class AddRequestCollectionDialog : DialogFragment() {
private lateinit var etRequestCollectionName: EditText
companion object {
fun newInstance(title: String): AddRequestCollectionDialog {
val frag = AddRequestCollectionDialog()
val args = Bundle()
args.putString("title", title)
frag.arguments = args
return frag
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(activity)
val title = arguments.getString("title")
// Get the layout inflater
val inflater = activity.layoutInflater
val view = inflater.inflate(R.layout.dialog_add_request_collection, null)
etRequestCollectionName = view.findViewById(R.id.etRequestCollectionName)
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(view)
// Add action buttons
.setPositiveButton("Save", { dialog, id ->
// Save request collection
addRequestCollection()
})
.setNegativeButton("Cancel", { dialog, id -> this.dialog.cancel() })
return builder.create()
}
private fun addRequestCollection() {
// Save request collection
val requestCollection = RequestCollection(Utility.generateId(), etRequestCollectionName.text.toString())
val requestRepo = LocalRequestRepository(activity.applicationContext)
Single.fromCallable {
requestRepo.insertRequestCollection(requestCollection)
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe()
return
}
} | apache-2.0 | f16fa18be92f80cd77c00c1cee260174 | 32.260274 | 112 | 0.681912 | 5.17484 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/actions/RsCreateCrateAction.kt | 2 | 2331 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.rust.cargo.CargoConstants
import org.rust.cargo.project.model.cargoProjects
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.runconfig.command.RunCargoCommandActionBase
import org.rust.cargo.toolchain.RsToolchainBase
import org.rust.cargo.toolchain.tools.cargoOrWrapper
import org.rust.ide.actions.ui.showCargoNewCrateUI
import org.rust.openapiext.pathAsPath
import org.rust.stdext.unwrapOrThrow
class RsCreateCrateAction : RunCargoCommandActionBase() {
override fun actionPerformed(e: AnActionEvent) {
val dataContext = e.dataContext
val project = CommonDataKeys.PROJECT.getData(dataContext) ?: return
val root = getRootFolder(dataContext) ?: return
val toolchain = project.toolchain ?: return
val ui = showCargoNewCrateUI(project, root)
ui.selectCargoCrateSettings()?.let {
createProject(project, toolchain, root, it.crateName, it.binary)
}
}
private fun getRootFolder(dataContext: DataContext): VirtualFile? {
val file = CommonDataKeys.VIRTUAL_FILE.getData(dataContext) ?: return null
return if (!file.isDirectory) {
file.parent
} else file
}
private fun createProject(
project: Project,
toolchain: RsToolchainBase,
root: VirtualFile,
name: String,
binary: Boolean
) {
val cargo = toolchain.cargoOrWrapper(
project.cargoProjects.findProjectForFile(root)?.workspaceRootDir?.pathAsPath)
val targetDir = runWriteAction {
root.createChildDirectory(this, name)
}
cargo.init(project, project, targetDir, name, binary, "none").unwrapOrThrow()
val manifest = targetDir.findChild(CargoConstants.MANIFEST_FILE)
manifest?.let {
project.cargoProjects.attachCargoProject(it.pathAsPath)
}
}
}
| mit | dc7b0697328944b26ea9af48bbd2083d | 34.861538 | 89 | 0.723724 | 4.588583 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsModItem.kt | 3 | 1806 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.search.SearchScope
import com.intellij.psi.stubs.IStubElementType
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.macros.RsExpandedElement
import org.rust.lang.core.psi.RsModItem
import org.rust.lang.core.psi.RsPsiImplUtil
import org.rust.lang.core.stubs.RsModItemStub
import javax.swing.Icon
val RsModItem.hasMacroUse: Boolean get() = MOD_ITEM_HAS_MACRO_USE_PROP.getByPsi(this)
val MOD_ITEM_HAS_MACRO_USE_PROP: StubbedAttributeProperty<RsModItem, RsModItemStub> =
StubbedAttributeProperty({ it.hasAttribute("macro_use") }, RsModItemStub::mayHaveMacroUse)
abstract class RsModItemImplMixin : RsStubbedNamedElementImpl<RsModItemStub>,
RsModItem {
constructor(node: ASTNode) : super(node)
constructor(stub: RsModItemStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getIcon(flags: Int): Icon =
iconWithVisibility(flags, RsIcons.MODULE)
override val `super`: RsMod get() = containingMod
override val modName: String? get() = name
override val pathAttribute: String? get() = queryAttributes.lookupStringValueForKey("path")
override val crateRelativePath: String? get() = RsPsiImplUtil.modCrateRelativePath(this)
override val ownsDirectory: Boolean = true // Any inline nested mod owns a directory
override val isCrateRoot: Boolean = false
override fun getContext(): PsiElement? = RsExpandedElement.getContextImpl(this)
override fun getUseScope(): SearchScope = RsPsiImplUtil.getDeclarationUseScope(this) ?: super.getUseScope()
}
| mit | dd05d40678f0c8168b50d35cb54c0950 | 35.857143 | 111 | 0.756921 | 4.2 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/ui/ConsoleDimensions.kt | 1 | 2367 | /*
Copyright 2017-2020 Charles Korn.
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 batect.ui
import batect.logging.Logger
import batect.os.Dimensions
import batect.os.NativeMethodException
import batect.os.NativeMethods
import batect.os.NoConsoleException
import batect.os.SignalListener
import batect.os.data
import jnr.constants.platform.Signal
import java.util.concurrent.atomic.AtomicReference
class ConsoleDimensions(
private val nativeMethods: NativeMethods,
private val signalListener: SignalListener,
private val logger: Logger
) {
private val currentDimensions: AtomicReference<Result<Dimensions?>> = AtomicReference(Result.success(null))
private val listeners = mutableListOf<Listener>()
init {
signalListener.start(Signal.SIGWINCH, ::updateCachedDimensions)
updateCachedDimensions()
}
val current: Dimensions?
get() = currentDimensions.get().getOrThrow()
fun registerListener(listener: Listener): AutoCloseable {
listeners.add(listener)
return AutoCloseable { listeners.remove(listener) }
}
private fun updateCachedDimensions() {
try {
val newDimensions = nativeMethods.getConsoleDimensions()
currentDimensions.set(Result.success(newDimensions))
logger.info {
message("Got console dimensions.")
data("dimensions", newDimensions)
}
} catch (e: NoConsoleException) {
currentDimensions.set(Result.success(null))
} catch (e: NativeMethodException) {
logger.warn {
message("Getting console dimensions failed.")
exception(e)
}
currentDimensions.set(Result.failure(e))
}
listeners.forEach { it() }
}
}
private typealias Listener = () -> Unit
| apache-2.0 | e180ab1d2588d283edc53522ef52e448 | 30.144737 | 111 | 0.69117 | 4.93125 | false | false | false | false |
androidx/androidx | window/integration-tests/configuration-change-tests/src/androidTest/java/androidx/window/integration/TestConsumer.kt | 3 | 2685 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.window.integration
import androidx.annotation.GuardedBy
import androidx.core.util.Consumer
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
import org.junit.Assert.assertTrue
/**
* Data structure to hold values in a mutable list.
*/
internal class TestConsumer<T>(count: Int) : Consumer<T> {
private val valueLock = ReentrantLock()
@GuardedBy("valueLock")
private val values = mutableListOf<T>()
private val countDownLock = ReentrantLock()
@GuardedBy("countDownLock")
private var valueLatch = CountDownLatch(count)
private val waitTimeSeconds: Long = 3L
/**
* Appends the new value at the end of the mutable list values.
*/
override fun accept(numLayoutFeatures: T) {
valueLock.withLock {
values.add(numLayoutFeatures)
}
countDownLock.withLock {
valueLatch.countDown()
}
}
/**
* Returns the current number of values stored.
*/
private fun size(): Int {
valueLock.withLock {
return values.size
}
}
/**
* Waits for the mutable list's length to be at a certain number (count).
* The method will wait waitTimeSeconds for the count before asserting false.
*/
fun waitForValueCount() {
assertTrue(
// Wait a total of waitTimeSeconds for the count before throwing an assertion error.
try {
valueLatch.await(waitTimeSeconds, TimeUnit.SECONDS)
} catch (e: InterruptedException) {
false
}
)
}
/**
* Returns {@code true} if there are no stored values, {@code false} otherwise.
*/
fun isEmpty(): Boolean {
return size() == 0
}
/**
* Returns the object in the mutable list at the requested index.
*/
fun get(valueIndex: Int): T {
valueLock.withLock {
return values[valueIndex]
}
}
} | apache-2.0 | b78c4c6f2b39cdb98d1f59ad2b1d2cc6 | 28.516484 | 96 | 0.653631 | 4.566327 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/TextLayoutResult.kt | 3 | 21359 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.createFontFamilyResolver
import androidx.compose.ui.text.font.toFontFamily
import androidx.compose.ui.text.platform.SynchronizedObject
import androidx.compose.ui.text.platform.createSynchronizedObject
import androidx.compose.ui.text.platform.synchronized
import androidx.compose.ui.text.style.ResolvedTextDirection
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
/**
* The data class which holds the set of parameters of the text layout computation.
*/
class TextLayoutInput private constructor(
/**
* The text used for computing text layout.
*/
val text: AnnotatedString,
/**
* The text layout used for computing this text layout.
*/
val style: TextStyle,
/**
* A list of [Placeholder]s inserted into text layout that reserves space to embed icons or
* custom emojis. A list of bounding boxes will be returned in
* [TextLayoutResult.placeholderRects] that corresponds to this input.
*
* @see TextLayoutResult.placeholderRects
* @see MultiParagraph
* @see MultiParagraphIntrinsics
*/
val placeholders: List<AnnotatedString.Range<Placeholder>>,
/**
* The maxLines param used for computing this text layout.
*/
val maxLines: Int,
/**
* The maxLines param used for computing this text layout.
*/
val softWrap: Boolean,
/**
* The overflow param used for computing this text layout
*/
val overflow: TextOverflow,
/**
* The density param used for computing this text layout.
*/
val density: Density,
/**
* The layout direction used for computing this text layout.
*/
val layoutDirection: LayoutDirection,
/**
* The font resource loader used for computing this text layout.
*
* This is no longer used.
*
* @see fontFamilyResolver
*/
@Suppress("DEPRECATION") resourceLoader: Font.ResourceLoader?,
/**
* The font resolver used for computing this text layout.
*/
val fontFamilyResolver: FontFamily.Resolver,
/**
* The minimum width provided while calculating this text layout.
*/
val constraints: Constraints
) {
private var _developerSuppliedResourceLoader = resourceLoader
@Deprecated("Replaced with FontFamily.Resolver",
replaceWith = ReplaceWith("fontFamilyResolver"),
)
@Suppress("DEPRECATION")
val resourceLoader: Font.ResourceLoader
get() {
return _developerSuppliedResourceLoader
?: DeprecatedBridgeFontResourceLoader.from(fontFamilyResolver)
}
@Deprecated(
"Font.ResourceLoader is replaced with FontFamily.Resolver",
replaceWith = ReplaceWith("TextLayoutInput(text, style, placeholders, " +
"maxLines, softWrap, overflow, density, layoutDirection, fontFamilyResolver, " +
"constraints")
)
@Suppress("DEPRECATION")
constructor(
text: AnnotatedString,
style: TextStyle,
placeholders: List<AnnotatedString.Range<Placeholder>>,
maxLines: Int,
softWrap: Boolean,
overflow: TextOverflow,
density: Density,
layoutDirection: LayoutDirection,
resourceLoader: Font.ResourceLoader,
constraints: Constraints
) : this(
text,
style,
placeholders,
maxLines,
softWrap,
overflow,
density,
layoutDirection,
resourceLoader,
createFontFamilyResolver(resourceLoader),
constraints
)
constructor(
text: AnnotatedString,
style: TextStyle,
placeholders: List<AnnotatedString.Range<Placeholder>>,
maxLines: Int,
softWrap: Boolean,
overflow: TextOverflow,
density: Density,
layoutDirection: LayoutDirection,
fontFamilyResolver: FontFamily.Resolver,
constraints: Constraints
) : this(
text,
style,
placeholders,
maxLines,
softWrap,
overflow,
density,
layoutDirection,
@Suppress("DEPRECATION") null,
fontFamilyResolver,
constraints
)
@Deprecated("Font.ResourceLoader is deprecated",
replaceWith = ReplaceWith("TextLayoutInput(text, style, placeholders," +
" maxLines, softWrap, overFlow, density, layoutDirection, fontFamilyResolver, " +
"constraints)")
)
// Unfortunately, there's no way to deprecate and add a parameter to a copy chain such that the
// resolution is valid.
//
// However, as this was never intended to be a public function we will not replace it. There is
// no use case for calling this method directly.
fun copy(
text: AnnotatedString = this.text,
style: TextStyle = this.style,
placeholders: List<AnnotatedString.Range<Placeholder>> = this.placeholders,
maxLines: Int = this.maxLines,
softWrap: Boolean = this.softWrap,
overflow: TextOverflow = this.overflow,
density: Density = this.density,
layoutDirection: LayoutDirection = this.layoutDirection,
@Suppress("DEPRECATION") resourceLoader: Font.ResourceLoader = this.resourceLoader,
constraints: Constraints = this.constraints
): TextLayoutInput {
return TextLayoutInput(
text = text,
style = style,
placeholders = placeholders,
maxLines = maxLines,
softWrap = softWrap,
overflow = overflow,
density = density,
layoutDirection = layoutDirection,
resourceLoader = resourceLoader,
fontFamilyResolver = fontFamilyResolver,
constraints = constraints
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is TextLayoutInput) return false
if (text != other.text) return false
if (style != other.style) return false
if (placeholders != other.placeholders) return false
if (maxLines != other.maxLines) return false
if (softWrap != other.softWrap) return false
if (overflow != other.overflow) return false
if (density != other.density) return false
if (layoutDirection != other.layoutDirection) return false
if (fontFamilyResolver != other.fontFamilyResolver) return false
if (constraints != other.constraints) return false
return true
}
override fun hashCode(): Int {
var result = text.hashCode()
result = 31 * result + style.hashCode()
result = 31 * result + placeholders.hashCode()
result = 31 * result + maxLines
result = 31 * result + softWrap.hashCode()
result = 31 * result + overflow.hashCode()
result = 31 * result + density.hashCode()
result = 31 * result + layoutDirection.hashCode()
result = 31 * result + fontFamilyResolver.hashCode()
result = 31 * result + constraints.hashCode()
return result
}
override fun toString(): String {
return "TextLayoutInput(" +
"text=$text, " +
"style=$style, " +
"placeholders=$placeholders, " +
"maxLines=$maxLines, " +
"softWrap=$softWrap, " +
"overflow=$overflow, " +
"density=$density, " +
"layoutDirection=$layoutDirection, " +
"fontFamilyResolver=$fontFamilyResolver, " +
"constraints=$constraints" +
")"
}
}
@Suppress("DEPRECATION")
private class DeprecatedBridgeFontResourceLoader private constructor(
private val fontFamilyResolver: FontFamily.Resolver
) : Font.ResourceLoader {
@Deprecated(
"Replaced by FontFamily.Resolver, this method should not be called",
ReplaceWith("FontFamily.Resolver.resolve(font, )"),
)
override fun load(font: Font): Any {
return fontFamilyResolver.resolve(
font.toFontFamily(),
font.weight,
font.style
).value
}
companion object {
// In normal usage will be a map of size 1.
//
// To fill this map with a large number of entries an app must:
//
// 1. Repeatedly change FontFamily.Resolver
// 2. Call the deprecated method getFontResourceLoader on TextLayoutInput
//
// If this map is found to be large in profiling of an app, please modify your code to not
// call getFontResourceLoader, and evaluate if FontFamily.Resolver is being correctly cached
// (via e.g. remember)
var cache = mutableMapOf<FontFamily.Resolver, Font.ResourceLoader>()
val lock: SynchronizedObject = createSynchronizedObject()
fun from(fontFamilyResolver: FontFamily.Resolver): Font.ResourceLoader {
synchronized(lock) {
// the same resolver to return the same ResourceLoader
cache[fontFamilyResolver]?.let { return it }
val deprecatedBridgeFontResourceLoader = DeprecatedBridgeFontResourceLoader(
fontFamilyResolver
)
cache[fontFamilyResolver] = deprecatedBridgeFontResourceLoader
return deprecatedBridgeFontResourceLoader
}
}
}
}
/**
* The data class which holds text layout result.
*/
class TextLayoutResult constructor(
/**
* The parameters used for computing this text layout result.
*/
val layoutInput: TextLayoutInput,
/**
* The multi paragraph object.
*
* This is the result of the text layout computation.
*/
val multiParagraph: MultiParagraph,
/**
* The amount of space required to paint this text in Int.
*/
val size: IntSize
) {
/**
* The distance from the top to the alphabetic baseline of the first line.
*/
val firstBaseline: Float = multiParagraph.firstBaseline
/**
* The distance from the top to the alphabetic baseline of the last line.
*/
val lastBaseline: Float = multiParagraph.lastBaseline
/**
* Returns true if the text is too tall and couldn't fit with given height.
*/
val didOverflowHeight: Boolean get() = multiParagraph.didExceedMaxLines ||
size.height < multiParagraph.height
/**
* Returns true if the text is too wide and couldn't fit with given width.
*/
val didOverflowWidth: Boolean get() = size.width < multiParagraph.width
/**
* Returns true if either vertical overflow or horizontal overflow happens.
*/
val hasVisualOverflow: Boolean get() = didOverflowWidth || didOverflowHeight
/**
* Returns a list of bounding boxes that is reserved for [TextLayoutInput.placeholders].
* Each [Rect] in this list corresponds to the [Placeholder] passed to
* [TextLayoutInput.placeholders] and it will have the height and width specified in the
* [Placeholder]. It's guaranteed that [TextLayoutInput.placeholders] and
* [TextLayoutResult.placeholderRects] will have same length and order.
*
* @see TextLayoutInput.placeholders
* @see Placeholder
*/
val placeholderRects: List<Rect?> = multiParagraph.placeholderRects
/**
* Returns a number of lines of this text layout
*/
val lineCount: Int get() = multiParagraph.lineCount
/**
* Returns the start offset of the given line, inclusive.
*
* The start offset represents a position in text before the first character in the given line.
* For example, `getLineStart(1)` will return 4 for the text below
* <pre>
* ┌────┐
* │abcd│
* │efg │
* └────┘
* </pre>
*
* @param lineIndex the line number
* @return the start offset of the line
*/
fun getLineStart(lineIndex: Int): Int = multiParagraph.getLineStart(lineIndex)
/**
* Returns the end offset of the given line.
*
* The end offset represents a position in text after the last character in the given line.
* For example, `getLineEnd(0)` will return 4 for the text below
* <pre>
* ┌────┐
* │abcd│
* │efg │
* └────┘
* </pre>
*
* Characters being ellipsized are treated as invisible characters. So that if visibleEnd is
* false, it will return line end including the ellipsized characters and vice versa.
*
* @param lineIndex the line number
* @param visibleEnd if true, the returned line end will not count trailing whitespaces or
* linefeed characters. Otherwise, this function will return the logical line end. By default
* it's false.
* @return an exclusive end offset of the line.
*/
fun getLineEnd(lineIndex: Int, visibleEnd: Boolean = false): Int =
multiParagraph.getLineEnd(lineIndex, visibleEnd)
/**
* Returns true if the given line is ellipsized, otherwise returns false.
*
* @param lineIndex a 0 based line index
* @return true if the given line is ellipsized, otherwise false
*/
fun isLineEllipsized(lineIndex: Int): Boolean = multiParagraph.isLineEllipsized(lineIndex)
/**
* Returns the top y coordinate of the given line.
*
* @param lineIndex the line number
* @return the line top y coordinate
*/
fun getLineTop(lineIndex: Int): Float = multiParagraph.getLineTop(lineIndex)
/**
* Returns the bottom y coordinate of the given line.
*
* @param lineIndex the line number
* @return the line bottom y coordinate
*/
fun getLineBottom(lineIndex: Int): Float = multiParagraph.getLineBottom(lineIndex)
/**
* Returns the left x coordinate of the given line.
*
* @param lineIndex the line number
* @return the line left x coordinate
*/
fun getLineLeft(lineIndex: Int): Float = multiParagraph.getLineLeft(lineIndex)
/**
* Returns the right x coordinate of the given line.
*
* @param lineIndex the line number
* @return the line right x coordinate
*/
fun getLineRight(lineIndex: Int): Float = multiParagraph.getLineRight(lineIndex)
/**
* Returns the line number on which the specified text offset appears.
*
* If you ask for a position before 0, you get 0; if you ask for a position
* beyond the end of the text, you get the last line.
*
* @param offset a character offset
* @return the 0 origin line number.
*/
fun getLineForOffset(offset: Int): Int = multiParagraph.getLineForOffset(offset)
/**
* Returns line number closest to the given graphical vertical position.
*
* If you ask for a vertical position before 0, you get 0; if you ask for a vertical position
* beyond the last line, you get the last line.
*
* @param vertical the vertical position
* @return the 0 origin line number.
*/
fun getLineForVerticalPosition(vertical: Float): Int =
multiParagraph.getLineForVerticalPosition(vertical)
/**
* Get the horizontal position for the specified text [offset].
*
* Returns the relative distance from the text starting offset. For example, if the paragraph
* direction is Left-to-Right, this function returns positive value as a distance from the
* left-most edge. If the paragraph direction is Right-to-Left, this function returns negative
* value as a distance from the right-most edge.
*
* [usePrimaryDirection] argument is taken into account only when the offset is in the BiDi
* directional transition point. [usePrimaryDirection] is true means use the primary
* direction run's coordinate, and use the secondary direction's run's coordinate if false.
*
* @param offset a character offset
* @param usePrimaryDirection true for using the primary run's coordinate if the given
* offset is in the BiDi directional transition point.
* @return the relative distance from the text starting edge.
* @see MultiParagraph.getHorizontalPosition
*/
fun getHorizontalPosition(offset: Int, usePrimaryDirection: Boolean): Float =
multiParagraph.getHorizontalPosition(offset, usePrimaryDirection)
/**
* Get the text direction of the paragraph containing the given offset.
*
* @param offset a character offset
* @return the paragraph direction
*/
fun getParagraphDirection(offset: Int): ResolvedTextDirection =
multiParagraph.getParagraphDirection(offset)
/**
* Get the text direction of the resolved BiDi run that the character at the given offset
* associated with.
*
* @param offset a character offset
* @return the direction of the BiDi run of the given character offset.
*/
fun getBidiRunDirection(offset: Int): ResolvedTextDirection =
multiParagraph.getBidiRunDirection(offset)
/**
* Returns the character offset closest to the given graphical position.
*
* @param position a graphical position in this text layout
* @return a character offset that is closest to the given graphical position.
*/
fun getOffsetForPosition(position: Offset): Int =
multiParagraph.getOffsetForPosition(position)
/**
* Returns the bounding box of the character for given character offset.
*
* @param offset a character offset
* @return a bounding box for the character in pixels.
*/
fun getBoundingBox(offset: Int): Rect = multiParagraph.getBoundingBox(offset)
/**
* Returns the text range of the word at the given character offset.
*
* Characters not part of a word, such as spaces, symbols, and punctuation, have word breaks on
* both sides. In such cases, this method will return a text range that contains the given
* character offset.
*
* Word boundaries are defined more precisely in Unicode Standard Annex #29
* <http://www.unicode.org/reports/tr29/#Word_Boundaries>.
*/
fun getWordBoundary(offset: Int): TextRange = multiParagraph.getWordBoundary(offset)
/**
* Returns the rectangle of the cursor area
*
* @param offset An character offset of the cursor
* @return a rectangle of cursor region
*/
fun getCursorRect(offset: Int): Rect = multiParagraph.getCursorRect(offset)
/**
* Returns path that enclose the given text range.
*
* @param start an inclusive start character offset
* @param end an exclusive end character offset
* @return a drawing path
*/
fun getPathForRange(start: Int, end: Int): Path = multiParagraph.getPathForRange(start, end)
fun copy(
layoutInput: TextLayoutInput = this.layoutInput,
size: IntSize = this.size
): TextLayoutResult {
return TextLayoutResult(
layoutInput = layoutInput,
multiParagraph = multiParagraph,
size = size
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is TextLayoutResult) return false
if (layoutInput != other.layoutInput) return false
if (multiParagraph != other.multiParagraph) return false
if (size != other.size) return false
if (firstBaseline != other.firstBaseline) return false
if (lastBaseline != other.lastBaseline) return false
if (placeholderRects != other.placeholderRects) return false
return true
}
override fun hashCode(): Int {
var result = layoutInput.hashCode()
result = 31 * result + multiParagraph.hashCode()
result = 31 * result + size.hashCode()
result = 31 * result + firstBaseline.hashCode()
result = 31 * result + lastBaseline.hashCode()
result = 31 * result + placeholderRects.hashCode()
return result
}
override fun toString(): String {
return "TextLayoutResult(" +
"layoutInput=$layoutInput, " +
"multiParagraph=$multiParagraph, " +
"size=$size, " +
"firstBaseline=$firstBaseline, " +
"lastBaseline=$lastBaseline, " +
"placeholderRects=$placeholderRects" +
")"
}
} | apache-2.0 | 8333f5c58ce1dfea4f08489158a61eef | 34.31675 | 100 | 0.656116 | 5.028335 | false | false | false | false |
slegrand45/todomvc | examples/kotlin-react/src/app/App.kt | 4 | 4601 | package app
import components.headerInput
import components.info
import components.todoBar
import components.todoList
import kotlinx.html.InputType
import kotlinx.html.id
import kotlinx.html.js.onChangeFunction
import kotlinx.html.title
import model.Todo
import model.TodoFilter
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.get
import org.w3c.dom.set
import react.*
import react.dom.input
import react.dom.label
import react.dom.section
import utils.translate
import kotlin.browser.document
import kotlin.browser.localStorage
object AppOptions {
var language = "no-language"
var localStorageKey = "todos-koltin-react"
}
class App : RComponent<App.Props, App.State>() {
override fun componentWillMount() {
console.log("component will mount app")
setState {
todos = loadTodos()
}
}
override fun RBuilder.render() {
val currentFilter = when (props.route) {
"pending" -> TodoFilter.PENDING
"completed" -> TodoFilter.COMPLETED
else -> TodoFilter.ANY
}
section("todoapp") {
headerInput(::createTodo)
if (state.todos.isNotEmpty()) {
val allChecked = isAllCompleted()
section("main") {
input(InputType.checkBox, classes = "toggle-all") {
attrs {
id = "toggle-all"
checked = allChecked
onChangeFunction = {event ->
val isChecked = (event.currentTarget as HTMLInputElement).checked
setAllStatus(isChecked)
}
}
}
label {
attrs["htmlFor"] = "toggle-all"
attrs.title = "Mark all as complete".translate()
}
todoList(::removeTodo, ::updateTodo, state.todos, currentFilter)
}
todoBar(pendingCount = countPending(),
anyCompleted = state.todos.any { todo -> todo.completed },
clearCompleted = ::clearCompleted,
currentFilter = currentFilter,
updateFilter = ::updateFilter)
}
}
info()
}
private fun loadTodos(): List<Todo> {
val storedTodosJSON = localStorage[AppOptions.localStorageKey]
return if (storedTodosJSON != null) {
JSON.parse<Array<Todo>>(storedTodosJSON).map {
Todo(it.id, it.title, it.completed)
}.toList()
} else {
emptyList()
}
}
private fun updateFilter(newFilter: TodoFilter) {
document.location!!.href = "#?route=${newFilter.name.toLowerCase()}"
}
private fun countPending() = pendingTodos().size
private fun removeTodo(todo: Todo) {
console.log("removeTodo [${todo.id}] ${todo.title}")
saveTodos(state.todos - todo)
}
private fun createTodo(todo: Todo) {
console.log("createTodo [${todo.id}] ${todo.title}")
saveTodos(state.todos + todo)
}
private fun updateTodo(todo: Todo) {
console.log("updateTodo [${todo.id}] ${todo.title}")
val newTodos = state.todos.map { oldTodo ->
if (todo.id == oldTodo.id) {
todo
} else {
oldTodo
}
}
saveTodos(newTodos)
}
private fun setAllStatus(newStatus: Boolean) {
saveTodos(state.todos.map { todo -> todo.copy(completed = newStatus) })
}
private fun saveTodos(updatedTodos: List<Todo>) {
console.log("saving: ${updatedTodos.toTypedArray()}")
storeTodos(updatedTodos)
setState {
todos = updatedTodos
}
}
private fun storeTodos(todos: List<Todo>) {
localStorage.setItem(AppOptions.localStorageKey, JSON.stringify(todos.toTypedArray()))
}
private fun clearCompleted() {
saveTodos(pendingTodos())
}
private fun isAllCompleted(): Boolean {
return state.todos.fold(true) { allCompleted, todo ->
allCompleted && todo.completed
}
}
private fun pendingTodos() : List<Todo> {
return state.todos.filter { todo -> !todo.completed }
}
class State(var todos: List<Todo>) : RState
class Props(var route: String) : RProps
}
fun RBuilder.app(route: String) = child(App::class) {
attrs.route = route
}
| mit | 07f26b755dba09e1de082e78bf2408e9 | 26.386905 | 97 | 0.560748 | 4.624121 | false | false | false | false |
esofthead/mycollab | mycollab-server-runner/src/main/java/com/mycollab/installation/servlet/AssetHttpServletRequestHandler.kt | 3 | 2619 | /**
* 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.installation.servlet
import com.mycollab.core.utils.MimeTypesUtil
import org.slf4j.LoggerFactory
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.IOException
import javax.servlet.ServletException
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* @author MyCollab Ltd.
* @since 3.0
*/
class AssetHttpServletRequestHandler : HttpServlet() {
@Throws(ServletException::class, IOException::class)
override fun doGet(request: HttpServletRequest, response: HttpServletResponse) {
val path = request.pathInfo
var resourcePath = "assets$path"
var inputStream = AssetHttpServletRequestHandler::class.java.classLoader.getResourceAsStream(resourcePath)
if (inputStream == null) {
resourcePath = "VAADIN/themes/mycollab$path"
inputStream = AssetHttpServletRequestHandler::class.java.classLoader.getResourceAsStream(resourcePath)
}
if (inputStream != null) {
response.setHeader("Content-Type", MimeTypesUtil.detectMimeType(path))
response.setHeader("Content-Length", inputStream.available().toString())
BufferedInputStream(inputStream).use { input ->
BufferedOutputStream(response.outputStream).use { output ->
val buffer = ByteArray(8192)
var length = input.read(buffer)
while (length > 0) {
output.write(buffer, 0, length)
length = input.read(buffer)
}
}
}
} else {
LOG.error("Can not find resource has path $path")
}
}
companion object {
private val LOG = LoggerFactory.getLogger(AssetHttpServletRequestHandler::class.java)
}
}
| agpl-3.0 | 6ef0068442d9442d844f1477b5098944 | 36.942029 | 114 | 0.681436 | 4.866171 | false | false | false | false |
y2k/JoyReactor | core/src/main/kotlin/y2k/joyreactor/common/http/HttpRequestBuilder.kt | 1 | 1505 | package y2k.joyreactor.common.http
import okhttp3.MediaType
import okhttp3.RequestBody
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import y2k.joyreactor.common.stream
import java.net.URLEncoder
import java.util.*
class HttpRequestBuilder(private val httpClient: DefaultHttpClient) : RequestBuilder {
private val form = HashMap<String, String>()
private val headers = HashMap<String, String>()
override fun addField(key: String, value: String): HttpRequestBuilder {
form.put(key, value)
return this
}
override fun putHeader(name: String, value: String): HttpRequestBuilder {
headers.put(name, value)
return this
}
override fun get(url: String): Document {
val response = httpClient.executeRequest(url) {
headers.forEach { header(it.key, it.value) }
}
return response.stream().use { Jsoup.parse(it, "utf-8", url) }
}
override fun post(url: String): Document {
val response = httpClient.executeRequest(url) {
headers.forEach { header(it.key, it.value) }
post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), serializeForm()))
}
return response.stream().use { Jsoup.parse(it, "utf-8", url) }
}
private fun serializeForm(): ByteArray {
return form
.map { it.key + "=" + URLEncoder.encode(it.value, "UTF-8") }
.joinToString (separator = "&")
.toByteArray()
}
} | gpl-2.0 | 8f5e458936c7e0aed7ec606a7fcf3b4c | 31.042553 | 107 | 0.648505 | 4.168975 | false | false | false | false |
BoD/CineToday | app/src/debug/kotlin/org/jraf/android/cinetoday/app/tile/preview/TilePreviewActivity.kt | 1 | 1926 | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2021-present Benoit 'BoD' Lubek ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jraf.android.cinetoday.app.tile.preview
import android.content.ComponentName
import android.os.Bundle
import android.widget.FrameLayout
import androidx.activity.ComponentActivity
import androidx.wear.tiles.manager.TileUiClient
import org.jraf.android.cinetoday.R
import org.jraf.android.cinetoday.app.tile.MoviesTodayTile
class TilePreviewActivity : ComponentActivity() {
private lateinit var tileUiClient: TileUiClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.tile_preview_activity)
val rootLayout = findViewById<FrameLayout>(R.id.conRoot)
tileUiClient = TileUiClient(
context = this,
component = ComponentName(this, MoviesTodayTile::class.java),
parentView = rootLayout
)
tileUiClient.connect()
}
override fun onDestroy() {
super.onDestroy()
tileUiClient.close()
}
} | gpl-3.0 | 8be7de66608df8f51ddeb34c4e36ec97 | 34.685185 | 73 | 0.659398 | 4.318386 | false | false | false | false |
qiuxiang/react-native-amap3d | lib/android/src/main/java/qiuxiang/amap3d/map_view/HeatMap.kt | 1 | 850 | package qiuxiang.amap3d.map_view
import android.content.Context
import com.amap.api.maps.AMap
import com.amap.api.maps.model.HeatmapTileProvider
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.TileOverlay
import com.amap.api.maps.model.TileOverlayOptions
import com.facebook.react.views.view.ReactViewGroup
class HeatMap(context: Context) : ReactViewGroup(context), Overlay {
private var overlay: TileOverlay? = null
var data: List<LatLng> = emptyList()
var opacity: Double = 0.6
var radius: Int = 12
override fun add(map: AMap) {
overlay = map.addTileOverlay(
TileOverlayOptions().tileProvider(
HeatmapTileProvider.Builder()
.data(data)
.radius(radius)
.transparency(opacity)
.build()
)
)
}
override fun remove() {
overlay?.remove()
}
} | mit | a232101efa817d6a90d9339030c34aa9 | 25.59375 | 68 | 0.702353 | 3.72807 | false | false | false | false |
naosim/RPGSample | rpglib/src/main/kotlin/com/naosim/rpglib/android/ItemSelectDialogFactory.kt | 1 | 1531 | package com.naosim.rpglib.android
import android.app.Dialog
import android.content.Context
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.widget.AdapterView
import android.widget.ListView
import android.widget.Toast
import com.naosim.rpglib.R
import com.naosim.rpglib.model.value.Item
class ItemSelectDialogFactory {
fun showItemListDialog(context: Context, itemList: List<Item>, onItemSelectedListener: (Item) -> Unit) {
if (itemList.size == 0) {
Toast.makeText(context, "どうぐがありません", Toast.LENGTH_SHORT).show()
return
}
createItemListDialog(context, itemList, onItemSelectedListener).show()
}
fun createItemListDialog(context: Context, itemList: List<Item>, onItemSelectedListener: (Item) -> Unit): Dialog {
val view = LayoutInflater.from(context).inflate(R.layout.view_item, null)
val alertDialog = AlertDialog.Builder(context).setView(view).create()
val listView = view.findViewById(R.id.itemListView) as ListView
listView.adapter = ItemListAdapter(context, itemList)
listView.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, i, l ->
val selectedItem = adapterView.adapter.getItem(i) as Item
onItemSelectedListener.invoke(selectedItem)
alertDialog.dismiss()
}
view.findViewById(R.id.cancelButton).setOnClickListener { alertDialog.dismiss() }
return alertDialog
}
}
| mit | d8c0d2dec3538c8ae7a80d4a570df032 | 35.02381 | 118 | 0.717779 | 4.557229 | false | false | false | false |
xdtianyu/CallerInfo | app/src/main/java/org/xdty/callerinfo/settings/PluginBinder.kt | 1 | 6806 | package org.xdty.callerinfo.settings
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.IBinder
import android.os.RemoteException
import android.preference.PreferenceScreen
import android.util.Log
import org.xdty.callerinfo.R
import org.xdty.callerinfo.exporter.Exporter
import org.xdty.callerinfo.plugin.IPluginService
import org.xdty.callerinfo.plugin.IPluginServiceCallback
import org.xdty.callerinfo.utils.Toasts.show
class PluginBinder(private val context: Context, private val preferenceDialogs: PreferenceDialogs,
private val preferenceActions: PreferenceActions) : ServiceConnection {
private val mPluginIntent = Intent().setComponent(ComponentName(
"org.xdty.callerinfo.plugin",
"org.xdty.callerinfo.plugin.PluginService"))
private var mPluginService: IPluginService? = null
fun bindPluginService() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(mPluginIntent)
} else {
context.startService(mPluginIntent)
}
context.bindService(mPluginIntent, this, Context.BIND_AUTO_CREATE)
} catch (e: Exception) {
e.printStackTrace()
}
}
fun unBindPluginService() {
try {
context.unbindService(this)
context.stopService(mPluginIntent)
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onServiceConnected(name: ComponentName, service: IBinder) {
Log.d(TAG, "onServiceConnected: $name")
mPluginService = IPluginService.Stub.asInterface(service)
try {
mPluginService?.registerCallback(object : IPluginServiceCallback.Stub() {
@Throws(RemoteException::class)
override fun onCallPermissionResult(success: Boolean) {
Log.d(TAG, "onCallPermissionResult: $success")
(context as Activity).runOnUiThread { preferenceActions.setChecked(R.string.auto_hangup_key, success) }
}
@Throws(RemoteException::class)
override fun onCallLogPermissionResult(success: Boolean) {
Log.d(TAG, "onCallLogPermissionResult: $success")
(context as Activity).runOnUiThread {
if (PluginStatus.isCheckRingOnce) {
preferenceActions.setChecked(R.string.ring_once_and_auto_hangup_key, success)
} else {
preferenceActions.setChecked(R.string.add_call_log_key, success)
}
}
}
@Throws(RemoteException::class)
override fun onStoragePermissionResult(success: Boolean) {
Log.d(TAG, "onStoragePermissionResult: $success")
if (success) {
if (PluginStatus.isCheckStorageExport) {
exportData()
} else {
importData()
}
} else {
show(context, R.string.storage_permission_failed)
}
}
})
enablePluginPreference()
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun enablePluginPreference() {
val pluginPref = preferenceActions.findPreference(context.getString(R.string.plugin_key)) as PreferenceScreen?
pluginPref!!.isEnabled = true
pluginPref.summary = ""
}
override fun onServiceDisconnected(name: ComponentName) {
Log.d(TAG, "onServiceDisconnected: $name")
mPluginService = null
}
fun checkStoragePermission() {
try {
if (mPluginService != null) {
mPluginService!!.checkStoragePermission()
} else {
Log.e(TAG, "PluginService is stopped!!")
}
} catch (e: Exception) {
e.printStackTrace()
}
}
@SuppressLint("CheckResult")
private fun importData() {
try {
if (mPluginService != null) {
val data = mPluginService!!.importData()
if (data.contains("Error:")) {
preferenceDialogs.showTextDialog(R.string.import_data,
context.getString(R.string.import_failed, data))
} else {
val exporter = Exporter(context)
exporter.fromString(data).subscribe { s ->
if (s == null) {
preferenceDialogs.showTextDialog(R.string.import_data,
R.string.import_succeed)
} else {
preferenceDialogs.showTextDialog(R.string.import_data,
context.getString(R.string.import_failed, s))
}
}
}
} else {
Log.e(TAG, "PluginService is stopped!!")
}
} catch (e: Exception) {
e.printStackTrace()
}
}
@SuppressLint("CheckResult")
private fun exportData() {
val exporter = Exporter(context)
exporter.export().subscribe { s ->
try {
val res = mPluginService!!.exportData(s)
if (res.contains("Error")) {
preferenceDialogs.showTextDialog(R.string.export_data,
context.getString(R.string.export_failed, res))
} else {
preferenceDialogs.showTextDialog(R.string.export_data,
context.getString(R.string.export_succeed, res))
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
fun checkCallPermission() {
try {
mPluginService?.checkCallPermission()
} catch (e: Exception) {
e.printStackTrace()
}
}
fun checkCallLogPermission() {
try {
mPluginService?.checkCallLogPermission()
} catch (e: Exception) {
e.printStackTrace()
}
}
fun setIconStatus(show: Boolean) {
try {
mPluginService?.setIconStatus(show)
} catch (e: Exception) {
e.printStackTrace()
}
}
companion object {
private const val TAG = "PluginBinder"
}
} | gpl-3.0 | 0f32efea7c5c1de3fd9bbcb99a5317df | 34.638743 | 123 | 0.548193 | 5.308892 | false | false | false | false |
HabitRPG/habitica-android | common/src/main/java/com/habitrpg/common/habitica/extensions/DataBindingUtils.kt | 1 | 6830 | package com.habitrpg.common.habitica.extensions
import android.content.Context
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.view.View
import android.view.animation.Animation
import android.view.animation.Transformation
import android.widget.LinearLayout
import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.drawable.toBitmap
import coil.imageLoader
import coil.request.ImageRequest
import com.habitrpg.android.habitica.extensions.setTintWith
import com.habitrpg.common.habitica.R
import com.habitrpg.common.habitica.extensions.DataBindingUtils.BASE_IMAGE_URL
import com.habitrpg.common.habitica.helpers.AppConfigManager
import com.habitrpg.common.habitica.views.PixelArtView
import java.util.Collections
import java.util.Date
fun PixelArtView.loadImage(imageName: String?, imageFormat: String? = null) {
if (imageName != null) {
val fullname = DataBindingUtils.getFullFilename(imageName, imageFormat)
if (tag == fullname) {
return
}
tag = fullname
bitmap = null
DataBindingUtils.loadImage(context, imageName, imageFormat) {
if (tag == fullname) {
bitmap = it.toBitmap()
}
}
}
}
fun PixelArtView.loadGif(
imageName: String?,
builder: ImageRequest.Builder.() -> Unit = {}
) {
if (imageName != null) {
val fullname = BASE_IMAGE_URL + DataBindingUtils.getFullFilename(imageName)
val request = ImageRequest.Builder(context)
.data(fullname)
.target(this)
.apply(builder)
.build()
context.imageLoader.enqueue(request)
}
}
object DataBindingUtils {
fun loadImage(context: Context, imageName: String, imageResult: (Drawable) -> Unit) {
loadImage(context, imageName, null, imageResult)
}
fun loadImage(
context: Context,
imageName: String,
imageFormat: String?,
imageResult: (Drawable) -> Unit
) {
val request = ImageRequest.Builder(context)
.data(BASE_IMAGE_URL + getFullFilename(imageName, imageFormat))
.target()
.target {
imageResult(it)
}
.build()
context.imageLoader.enqueue(request)
}
fun getFullFilename(imageName: String, imageFormat: String? = null): String {
val name = when {
spriteSubstitutions.containsKey(imageName) -> spriteSubstitutions[imageName]
FILENAME_MAP.containsKey(imageName) -> FILENAME_MAP[imageName]
imageName.startsWith("handleless") -> "chair_$imageName"
else -> imageName
}
return name + if (imageFormat == null && FILEFORMAT_MAP.containsKey(imageName)) {
"." + FILEFORMAT_MAP[imageName]
} else {
".${imageFormat ?: "png"}"
}
}
fun setRoundedBackground(view: View, color: Int) {
val drawable = ResourcesCompat.getDrawable(view.resources, R.drawable.layout_rounded_bg, null)
drawable?.setTintWith(color, PorterDuff.Mode.MULTIPLY)
view.background = drawable
}
class LayoutWeightAnimation(internal var view: View, internal var targetWeight: Float) : Animation() {
private var initializeWeight: Float = 0.toFloat()
private var layoutParams: LinearLayout.LayoutParams = view.layoutParams as LinearLayout.LayoutParams
init {
initializeWeight = layoutParams.weight
}
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
layoutParams.weight = initializeWeight + (targetWeight - initializeWeight) * interpolatedTime
view.requestLayout()
}
override fun willChangeBounds(): Boolean = true
}
const val BASE_IMAGE_URL = "https://habitica-assets.s3.amazonaws.com/mobileApp/images/"
private val FILEFORMAT_MAP: Map<String, String>
private val FILENAME_MAP: Map<String, String>
private var spriteSubstitutions: Map<String, String> = HashMap()
get() {
if (Date().time - (lastSubstitutionCheck?.time ?: 0) > 180000) {
field = AppConfigManager().spriteSubstitutions()["generic"] ?: HashMap()
lastSubstitutionCheck = Date()
}
return field
}
private var lastSubstitutionCheck: Date? = null
init {
val tempMap = HashMap<String, String>()
tempMap["head_special_1"] = "gif"
tempMap["broad_armor_special_1"] = "gif"
tempMap["slim_armor_special_1"] = "gif"
tempMap["head_special_0"] = "gif"
tempMap["slim_armor_special_0"] = "gif"
tempMap["broad_armor_special_0"] = "gif"
tempMap["weapon_special_critical"] = "gif"
tempMap["weapon_special_0"] = "gif"
tempMap["shield_special_0"] = "gif"
tempMap["Pet-Wolf-Cerberus"] = "gif"
tempMap["armor_special_ks2019"] = "gif"
tempMap["slim_armor_special_ks2019"] = "gif"
tempMap["broad_armor_special_ks2019"] = "gif"
tempMap["eyewear_special_ks2019"] = "gif"
tempMap["head_special_ks2019"] = "gif"
tempMap["shield_special_ks2019"] = "gif"
tempMap["weapon_special_ks2019"] = "gif"
tempMap["Pet-Gryphon-Gryphatrice"] = "gif"
tempMap["Mount_Head_Gryphon-Gryphatrice"] = "gif"
tempMap["Mount_Body_Gryphon-Gryphatrice"] = "gif"
tempMap["background_clocktower"] = "gif"
tempMap["background_airship"] = "gif"
tempMap["background_steamworks"] = "gif"
tempMap["Pet_HatchingPotion_Veggie"] = "gif"
tempMap["Pet_HatchingPotion_Dessert"] = "gif"
tempMap["Pet-HatchingPotion-Dessert"] = "gif"
tempMap["quest_windup"] = "gif"
tempMap["Pet-HatchingPotion_Windup"] = "gif"
tempMap["Pet_HatchingPotion_Windup"] = "gif"
tempMap["quest_solarSystem"] = "gif"
tempMap["quest_virtualpet"] = "gif"
tempMap["Pet_HatchingPotion_VirtualPet"] = "gif"
FILEFORMAT_MAP = Collections.unmodifiableMap(tempMap)
val tempNameMap = HashMap<String, String>()
tempNameMap["head_special_1"] = "ContributorOnly-Equip-CrystalHelmet"
tempNameMap["armor_special_1"] = "ContributorOnly-Equip-CrystalArmor"
tempNameMap["head_special_0"] = "BackerOnly-Equip-ShadeHelmet"
tempNameMap["armor_special_0"] = "BackerOnly-Equip-ShadeArmor"
tempNameMap["shield_special_0"] = "BackerOnly-Shield-TormentedSkull"
tempNameMap["weapon_special_0"] = "BackerOnly-Weapon-DarkSoulsBlade"
tempNameMap["weapon_special_critical"] = "weapon_special_critical"
tempNameMap["Pet-Wolf-Cerberus"] = "Pet-Wolf-Cerberus"
FILENAME_MAP = Collections.unmodifiableMap(tempNameMap)
}
}
| gpl-3.0 | 4529c2d864db73930a2071fbefcf5ea6 | 38.252874 | 108 | 0.646413 | 4.263421 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/evaluate/intrinsics.kt | 2 | 1230 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
@Retention(AnnotationRetention.RUNTIME)
annotation class Ann(
val p1: Int,
val p2: Short,
val p3: Byte,
val p4: Int,
val p5: Int,
val p6: Int
)
val prop1: Int = 1 or 1
val prop2: Short = 1 and 1
val prop3: Byte = 1 xor 1
val prop4: Int = 1 shl 1
val prop5: Int = 1 shr 1
val prop6: Int = 1 ushr 1
@Ann(1 or 1, 1 and 1, 1 xor 1, 1 shl 1, 1 shr 1, 1 ushr 1) class MyClass
fun box(): String {
val annotation = MyClass::class.java.getAnnotation(Ann::class.java)!!
if (annotation.p1 != prop1) return "fail 1, expected = ${prop1}, actual = ${annotation.p1}"
if (annotation.p2 != prop2) return "fail 2, expected = ${prop2}, actual = ${annotation.p2}"
if (annotation.p3 != prop3) return "fail 3, expected = ${prop3}, actual = ${annotation.p3}"
if (annotation.p4 != prop4) return "fail 4, expected = ${prop4}, actual = ${annotation.p4}"
if (annotation.p5 != prop5) return "fail 5, expected = ${prop5}, actual = ${annotation.p5}"
if (annotation.p6 != prop6) return "fail 6, expected = ${prop6}, actual = ${annotation.p6}"
return "OK"
}
| apache-2.0 | ddcc70e852f7306bb2fafc4c2d860333 | 35.176471 | 95 | 0.630894 | 3.137755 | false | false | false | false |
robfletcher/orca | keiko-core/src/main/kotlin/com/netflix/spinnaker/q/metrics/QueueMetricsPublisher.kt | 4 | 4760 | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.q.metrics
import com.netflix.spectator.api.Counter
import com.netflix.spectator.api.Registry
import com.netflix.spectator.api.patterns.PolledMeter
import com.netflix.spinnaker.q.Queue
import java.time.Clock
import java.time.Duration
import java.time.Instant
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
/**
* - can be registered as a queue EventPublisher
* - publishes metrics based on queue events
*/
class QueueMetricsPublisher(
val registry: Registry,
val clock: Clock
) : EventPublisher {
init {
PolledMeter.using(registry)
.withName("queue.last.poll.age")
.monitorValue(
this,
{
Duration
.between(it.lastQueuePoll, clock.instant())
.toMillis()
.toDouble()
}
)
PolledMeter.using(registry)
.withName("queue.last.retry.check.age")
.monitorValue(
this,
{
Duration
.between(it.lastRetryPoll, clock.instant())
.toMillis()
.toDouble()
}
)
}
override fun publishEvent(event: QueueEvent) {
when (event) {
QueuePolled -> _lastQueuePoll.set(clock.instant())
is MessageProcessing -> {
registry.timer("queue.message.lag").record(event.lag.toMillis(), TimeUnit.MILLISECONDS)
}
is RetryPolled -> _lastRetryPoll.set(clock.instant())
is MessagePushed -> event.counter.increment()
is MessageAcknowledged -> event.counter.increment()
is MessageRetried -> event.counter.increment()
is MessageDead -> event.counter.increment()
is MessageDuplicate -> event.counter.increment()
is LockFailed -> event.counter.increment()
is MessageRescheduled -> event.counter.increment()
is MessageNotFound -> event.counter.increment()
}
}
/**
* Count of messages pushed to the queue.
*/
private val MessagePushed.counter: Counter
get() = registry.counter("queue.pushed.messages")
/**
* Count of messages successfully processed and acknowledged.
*/
private val MessageAcknowledged.counter: Counter
get() = registry.counter("queue.acknowledged.messages")
/**
* Count of messages that have been retried. This does not mean unique
* messages, so retrying the same message again will still increment this
* count.
*/
private val MessageRetried.counter: Counter
get() = registry.counter("queue.retried.messages")
/**
* Count of messages that have exceeded [Queue.maxRetries] retry
* attempts and have been sent to the dead message handler.
*/
private val MessageDead.counter: Counter
get() = registry.counter("queue.dead.messages")
/**
* Count of messages that have been pushed or re-delivered while an identical
* message is already on the queue.
*/
private val MessageDuplicate.counter: Counter
get() = registry.counter(
"queue.duplicate.messages",
"messageType", payload.javaClass.simpleName
)
/**
* Count of attempted message reads that failed to acquire a lock (in other
* words, multiple Orca instance tried to read the same message).
*/
private val LockFailed.counter: Counter
get() = registry.counter("queue.lock.failed")
/**
* Count of attempted message rescheduling that succeeded (in other words,
* that message existed on the queue).
*/
private val MessageRescheduled.counter: Counter
get() = registry.counter("queue.reschedule.succeeded")
/**
* Count of attempted message rescheduling that failed (in other words,
* that message did not exist on the queue).
*/
private val MessageNotFound.counter: Counter
get() = registry.counter("queue.message.notfound")
/**
* The last time the [Queue.poll] method was executed.
*/
val lastQueuePoll: Instant
get() = _lastQueuePoll.get()
private val _lastQueuePoll = AtomicReference<Instant>(clock.instant())
/**
* The time the last [Queue.retry] method was executed.
*/
val lastRetryPoll: Instant
get() = _lastRetryPoll.get()
private val _lastRetryPoll = AtomicReference<Instant>(clock.instant())
}
| apache-2.0 | f55fb9ff1e7ef973d0b84007c4bb558c | 30.315789 | 95 | 0.688235 | 4.29991 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/source/SourceExtensions.kt | 1 | 1345 | package eu.kanade.tachiyomi.source
import android.graphics.drawable.Drawable
import eu.kanade.domain.source.model.SourceData
import eu.kanade.domain.source.service.SourcePreferences
import eu.kanade.tachiyomi.extension.ExtensionManager
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
fun Source.icon(): Drawable? = Injekt.get<ExtensionManager>().getAppIconForSource(this.id)
fun Source.getPreferenceKey(): String = "source_$id"
fun Source.toSourceData(): SourceData = SourceData(id = id, lang = lang, name = name)
fun Source.getNameForMangaInfo(): String {
val preferences = Injekt.get<SourcePreferences>()
val enabledLanguages = preferences.enabledLanguages().get()
.filterNot { it in listOf("all", "other") }
val hasOneActiveLanguages = enabledLanguages.size == 1
val isInEnabledLanguages = lang in enabledLanguages
return when {
// For edge cases where user disables a source they got manga of in their library.
hasOneActiveLanguages && !isInEnabledLanguages -> toString()
// Hide the language tag when only one language is used.
hasOneActiveLanguages && isInEnabledLanguages -> name
else -> toString()
}
}
fun Source.isLocal(): Boolean = id == LocalSource.ID
fun Source.isLocalOrStub(): Boolean = isLocal() || this is SourceManager.StubSource
| apache-2.0 | e9187588667f01a2dda7c1506bc9b8d2 | 39.757576 | 90 | 0.742751 | 4.424342 | false | false | false | false |
da1z/intellij-community | uast/uast-common/src/org/jetbrains/uast/evaluation/AbstractEvaluatorExtension.kt | 7 | 4442 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.evaluation
import com.intellij.lang.Language
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.*
import org.jetbrains.uast.values.UUndeterminedValue
import org.jetbrains.uast.values.UValue
abstract class AbstractEvaluatorExtension(override val language: Language) : UEvaluatorExtension {
override fun evaluatePostfix(
operator: UastPostfixOperator,
operandValue: UValue,
state: UEvaluationState
): UEvaluationInfo = UUndeterminedValue to state
override fun evaluatePrefix(
operator: UastPrefixOperator,
operandValue: UValue,
state: UEvaluationState
): UEvaluationInfo = UUndeterminedValue to state
override fun evaluateBinary(
binaryExpression: UBinaryExpression,
leftValue: UValue,
rightValue: UValue,
state: UEvaluationState
): UEvaluationInfo = UUndeterminedValue to state
override fun evaluateQualified(
accessType: UastQualifiedExpressionAccessType,
receiverInfo: UEvaluationInfo,
selectorInfo: UEvaluationInfo
): UEvaluationInfo = UUndeterminedValue to selectorInfo.state
override fun evaluateMethodCall(
target: PsiMethod,
argumentValues: List<UValue>,
state: UEvaluationState
): UEvaluationInfo = UUndeterminedValue to state
override fun evaluateVariable(
variable: UVariable,
state: UEvaluationState
): UEvaluationInfo = UUndeterminedValue to state
}
abstract class SimpleEvaluatorExtension : AbstractEvaluatorExtension(Language.ANY) {
override final fun evaluatePostfix(operator: UastPostfixOperator, operandValue: UValue, state: UEvaluationState): UEvaluationInfo {
val result = evaluatePostfix(operator, operandValue)
return if (result != UUndeterminedValue)
result.toConstant() to state
else
super.evaluatePostfix(operator, operandValue, state)
}
open fun evaluatePostfix(operator: UastPostfixOperator, operandValue: UValue): Any? = UUndeterminedValue
override final fun evaluatePrefix(operator: UastPrefixOperator, operandValue: UValue, state: UEvaluationState): UEvaluationInfo {
val result = evaluatePrefix(operator, operandValue)
return if (result != UUndeterminedValue)
result.toConstant() to state
else
super.evaluatePrefix(operator, operandValue, state)
}
open fun evaluatePrefix(operator: UastPrefixOperator, operandValue: UValue): Any? = UUndeterminedValue
override final fun evaluateBinary(binaryExpression: UBinaryExpression,
leftValue: UValue,
rightValue: UValue,
state: UEvaluationState): UEvaluationInfo {
val result = evaluateBinary(binaryExpression, leftValue, rightValue)
return if (result != UUndeterminedValue)
result.toConstant() to state
else
super.evaluateBinary(binaryExpression, leftValue, rightValue, state)
}
open fun evaluateBinary(binaryExpression: UBinaryExpression, leftValue: UValue, rightValue: UValue): Any? = UUndeterminedValue
override final fun evaluateMethodCall(target: PsiMethod, argumentValues: List<UValue>, state: UEvaluationState): UEvaluationInfo {
val result = evaluateMethodCall(target, argumentValues)
return if (result != UUndeterminedValue)
result.toConstant() to state
else
super.evaluateMethodCall(target, argumentValues, state)
}
open fun evaluateMethodCall(target: PsiMethod, argumentValues: List<UValue>): Any? = UUndeterminedValue
override final fun evaluateVariable(variable: UVariable, state: UEvaluationState): UEvaluationInfo {
val result = evaluateVariable(variable)
return if (result != UUndeterminedValue)
result.toConstant() to state
else
super.evaluateVariable(variable, state)
}
open fun evaluateVariable(variable: UVariable): Any? = UUndeterminedValue
}
| apache-2.0 | 1a3cade9ec4c166f5988df42fc5d3fee | 37.626087 | 133 | 0.752364 | 5.531756 | false | false | false | false |
kvakil/venus | src/main/kotlin/venus/riscv/insts/addi.kt | 1 | 251 | package venus.riscv.insts
import venus.riscv.insts.dsl.ITypeInstruction
val addi = ITypeInstruction(
name = "addi",
opcode = 0b0010011,
funct3 = 0b000,
eval32 = { a, b -> a + b },
eval64 = { a, b -> a + b }
)
| mit | 52f29a22d40e2e59f9bc031d8765a572 | 21.818182 | 45 | 0.553785 | 3.1375 | false | false | false | false |
rolandvitezhu/TodoCloud | app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/fragment/MainListFragment.kt | 1 | 36681 | package com.rolandvitezhu.todocloud.ui.activity.main.fragment
import android.content.Context
import android.os.Bundle
import android.view.*
import android.view.ContextMenu.ContextMenuInfo
import android.view.View.OnCreateContextMenuListener
import android.view.View.OnTouchListener
import android.view.ViewTreeObserver.OnScrollChangedListener
import android.widget.AbsListView
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.AdapterView.OnItemLongClickListener
import android.widget.ExpandableListView
import android.widget.ExpandableListView.*
import androidx.appcompat.view.ActionMode
import androidx.fragment.app.ListFragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import com.google.android.material.snackbar.Snackbar
import com.rolandvitezhu.todocloud.R
import com.rolandvitezhu.todocloud.app.AppController
import com.rolandvitezhu.todocloud.app.AppController.Companion.isActionModeEnabled
import com.rolandvitezhu.todocloud.app.AppController.Companion.showWhiteTextSnackbar
import com.rolandvitezhu.todocloud.data.Category
import com.rolandvitezhu.todocloud.data.PredefinedList
import com.rolandvitezhu.todocloud.database.TodoCloudDatabaseDao
import com.rolandvitezhu.todocloud.databinding.FragmentMainlistBinding
import com.rolandvitezhu.todocloud.repository.CategoryRepository
import com.rolandvitezhu.todocloud.repository.ListRepository
import com.rolandvitezhu.todocloud.repository.TodoRepository
import com.rolandvitezhu.todocloud.ui.activity.main.MainActivity
import com.rolandvitezhu.todocloud.ui.activity.main.adapter.CategoryAdapter
import com.rolandvitezhu.todocloud.ui.activity.main.adapter.ListAdapter
import com.rolandvitezhu.todocloud.ui.activity.main.adapter.PredefinedListAdapter
import com.rolandvitezhu.todocloud.ui.activity.main.dialogfragment.*
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.CategoriesViewModel
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.ListsViewModel
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.PredefinedListsViewModel
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.UserViewModel
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.viewmodelfactory.ListsViewModelFactory
import kotlinx.android.synthetic.main.fragment_mainlist.*
import kotlinx.android.synthetic.main.fragment_mainlist.view.*
import kotlinx.coroutines.launch
import java.util.*
import javax.inject.Inject
class MainListFragment() : ListFragment(), OnRefreshListener {
private val TAG: String = javaClass.simpleName
@Inject
lateinit var todoCloudDatabaseDao: TodoCloudDatabaseDao
@Inject
lateinit var todoRepository: TodoRepository
@Inject
lateinit var listDataSynchronizer: ListRepository
@Inject
lateinit var categoryRepository: CategoryRepository
@Inject
lateinit var predefinedListAdapter: PredefinedListAdapter
@Inject
lateinit var categoryAdapter: CategoryAdapter
@Inject
lateinit var listAdapter: ListAdapter
private var actionMode: ActionMode? = null
private var actionModeStartedWithELV: Boolean = false
private val selectedCategories: ArrayList<Category> = ArrayList()
private val selectedListsInCategory: ArrayList<com.rolandvitezhu.todocloud.data.List> = ArrayList()
private val selectedLists: ArrayList<com.rolandvitezhu.todocloud.data.List> = ArrayList()
private val categoriesViewModel by lazy {
activity?.let { ViewModelProvider(it).get(CategoriesViewModel::class.java) }
}
private val listsViewModel by lazy {
activity?.let {
ViewModelProvider(it, ListsViewModelFactory(categoriesViewModel)).
get(ListsViewModel::class.java)
}
}
private val predefinedListsViewModel by lazy {
activity?.let { ViewModelProvider(it).get(PredefinedListsViewModel::class.java) }
}
private val userViewModel by lazy {
activity?.let { ViewModelProvider(it).get(UserViewModel::class.java) }
}
private val isNoSelectedItems: Boolean
private get() {
val checkedItemCount: Int = checkedItemCount
return checkedItemCount == 0
}
private val checkedItemCount: Int
private get() {
return selectedCategories.size + selectedListsInCategory.size + selectedLists.size
}
override fun onAttach(context: Context) {
super.onAttach(context)
(requireActivity().application as AppController).appComponent.
fragmentComponent().create().inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
categoriesViewModel?.lhmCategories?.observe(
this,
{
lhmCategories ->
categoryAdapter.update(lhmCategories)
categoryAdapter.notifyDataSetChanged()
}
)
listsViewModel?.lists?.observe(
this,
{
lists ->
listAdapter.update(lists)
listAdapter.notifyDataSetChanged()
}
)
predefinedListsViewModel?.predefinedLists?.observe(
this,
{ predefinedLists ->
predefinedListAdapter.update(predefinedLists)
predefinedListAdapter.notifyDataSetChanged()
}
)
userViewModel?.user?.observe(
this,
{
user ->
// We do not need to do anything here. We use the userViewModel to bind the data,
// so it will automatically update on the UI. Use it as an example when implementing
// the same for the other viewmodels.
}
)
([email protected] as MainActivity).onPrepareNavigationHeader()
updateLists()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val fragmentMainListBinding: FragmentMainlistBinding =
FragmentMainlistBinding.inflate(inflater, container, false)
val view: View = fragmentMainListBinding.root
prepareExpandableListView(view)
prepareSwipeRefreshLayout(view)
syncData(view)
fragmentMainListBinding.mainListFragment = this
fragmentMainListBinding.executePendingBindings()
return view
}
private fun prepareSwipeRefreshLayout(view: View) {
setScrollViewSwipeRefreshBehavior(view)
view.swiperefreshlayout_mainlist?.setOnRefreshListener(this)
}
private fun setScrollViewSwipeRefreshBehavior(view: View) {
view.scrollview_mainlist?.viewTreeObserver?.addOnScrollChangedListener(
object : OnScrollChangedListener {
override fun onScrollChanged() {
try {
val scrollY: Int? = view.scrollview_mainlist?.scrollY
if (shouldSwipeRefresh(scrollY))
// We can only start the swipe refresh, when we are on the top of
// the list - which means scroll position y == 0 - and the action
// mode is disabled.
view.swiperefreshlayout_mainlist?.isEnabled = true
} catch (e: NullPointerException) {
// ScrollView nor SwipeRefreshLayout doesn't exists already.
}
}
private fun shouldSwipeRefresh(scrollY: Int?): Boolean {
return scrollY != null && scrollY == 0 && !isActionModeEnabled
}
})
}
private fun prepareExpandableListView(view: View) {
view.expandableheightexpandablelistview_mainlist_category?.setAdapter(categoryAdapter)
view.expandableheightexpandablelistview_mainlist_category?.
setOnChildClickListener(expLVChildClicked)
view.expandableheightexpandablelistview_mainlist_category?.
setOnGroupClickListener(expLVGroupClicked)
applyExpLVLongClickEvents(view)
}
private fun applyExpLVLongClickEvents(view: View) {
view.expandableheightexpandablelistview_mainlist_category?.
setOnCreateContextMenuListener(expLVCategoryContextMenuListener)
}
private val callback: ActionMode.Callback = object : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
isActionModeEnabled = true
actionMode = mode
fixExpandableListViewBehavior()
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
val actionModeTitle: String = prepareActionModeTitle()
actionMode?.title = actionModeTitle
prepareMenu(mode, menu)
return true
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
applyActionItemBehavior(item)
return true
}
override fun onDestroyActionMode(mode: ActionMode) {
deselectItems()
selectedCategories.clear()
selectedListsInCategory.clear()
selectedLists.clear()
listAdapter.clearSelection()
isActionModeEnabled = false
view?.expandableheightexpandablelistview_mainlist_category?.choiceMode =
AbsListView.CHOICE_MODE_NONE
view?.expandableheightlistview_mainlist_predefinedlist?.choiceMode =
AbsListView.CHOICE_MODE_NONE
}
/**
* If ActionMode has started with ExpandableListView, it may stop it accidentally. It can cause
* an unwanted click event after started the ActionMode. This method prevent that.
*/
private fun fixExpandableListViewBehavior() {
if (actionModeStartedWithELV) {
preventUnwantedClickEvent()
actionModeStartedWithELV = false
}
}
private fun preventUnwantedClickEvent() {
view?.expandableheightexpandablelistview_mainlist_category?.setOnTouchListener(
object : OnTouchListener {
override fun onTouch(v: View, event: MotionEvent): Boolean {
if (unwantedClickEventPassOut(event)) restoreDefaultBehavior()
return true
}
})
}
private fun unwantedClickEventPassOut(event: MotionEvent): Boolean {
return event.action == MotionEvent.ACTION_UP ||
event.action == MotionEvent.ACTION_CANCEL
}
private fun restoreDefaultBehavior() {
view?.expandableheightexpandablelistview_mainlist_category?.setOnTouchListener(null)
}
private fun prepareActionModeTitle(): String {
return checkedItemCount.toString() + " " + getString(R.string.all_selected)
}
private fun prepareMenu(mode: ActionMode, menu: Menu) {
if (oneCategorySelected()) {
menu.clear()
mode.menuInflater.inflate(R.menu.layout_appbar_mainlist_group, menu)
} else if (oneListInCategorySelected()) {
menu.clear()
mode.menuInflater.inflate(R.menu.layout_appbar_mainlist_child, menu)
} else if (oneListSelected()) {
menu.clear()
mode.menuInflater.inflate(R.menu.layout_appbar_mainlist_item, menu)
} else if (manyCategoriesSelected()) {
menu.clear()
mode.menuInflater.inflate(R.menu.layout_appbar_mainlist_many_group, menu)
} else if (manyListsInCategorySelected()) {
menu.clear()
mode.menuInflater.inflate(R.menu.layout_appbar_mainlist_many_child, menu)
} else if (manyListsSelected()) {
menu.clear()
mode.menuInflater.inflate(R.menu.layout_appbar_mainlist_many_item, menu)
} else if (manyCategoriesAndListsInCategorySelected()) {
menu.clear()
} else if (manyCategoriesAndListsSelected()) {
menu.clear()
} else if (manyListsInCategoryAndListsSelected()) {
menu.clear()
} else if (manyCategoriesAndListsInCategoryAndListsSelected()) {
menu.clear()
}
}
private fun applyActionItemBehavior(item: MenuItem) {
if (oneCategorySelected()) {
when (item.itemId) {
R.id.menuitem_layoutappbarmainlistgroup_createlist ->
openCreateListInCategoryDialogFragment()
R.id.menuitem_layoutappbarmainlistgroup_modify ->
openModifyCategoryDialogFragment()
R.id.menuitem_layoutappbarmainlistgroup_delete ->
openConfirmDeleteCategoryDialog()
}
} else if (oneListInCategorySelected()) {
when (item.itemId) {
R.id.menuitem_layoutappbarmainlistchild_modify ->
openModifyListInCategoryDialog()
R.id.menuitem_layoutappbarmainlistchild_delete ->
openConfirmDeleteListInCategoryDialog()
R.id.menuitem_layoutappbarmainlistchild_move -> openMoveListInCategoryDialog()
}
} else if (oneListSelected()) {
when (item.itemId) {
R.id.menuitem_layoutappbarmainlistitem_modify -> openModifyListDialog()
R.id.menuitem_layoutappbarmainlistitem_delete -> openConfirmDeleteListDialog()
R.id.menuitem_layoutappbarmainlistitem_move ->
openMoveListIntoAnotherCategoryDialog()
}
} else if (manyCategoriesSelected()) {
if (item.itemId == R.id.menuitem_layoutappbarmainlistmanygroup_delete)
openConfirmDeleteCategoriesDialog()
} else if (manyListsInCategorySelected()) {
if (item.itemId == R.id.menuitem_layoutappbarmainlistmanychild_delete)
openConfirmDeleteListsInCategoryDialog()
} else if (manyListsSelected()) {
if (item.itemId == R.id.menuitem_layoutappbarmainlistmanyitem_delete)
openConfirmDeleteListsDialog()
} else if (manyCategoriesAndListsInCategorySelected()) {
} else if (manyCategoriesAndListsSelected()) {
} else if (manyListsInCategoryAndListsSelected()) {
} else if (manyCategoriesAndListsInCategoryAndListsSelected()) {
}
}
private fun oneCategorySelected(): Boolean {
return (selectedCategories.size == 1) && (selectedListsInCategory.size == 0) && (selectedLists.size == 0)
}
private fun oneListInCategorySelected(): Boolean {
return (selectedCategories.size == 0) && (selectedListsInCategory.size == 1) && (selectedLists.size == 0)
}
private fun oneListSelected(): Boolean {
return (selectedCategories.size == 0) && (selectedListsInCategory.size == 0) && (selectedLists.size == 1)
}
private fun manyCategoriesSelected(): Boolean {
return (selectedCategories.size > 1) && (selectedListsInCategory.size == 0) && (selectedLists.size == 0)
}
private fun manyListsInCategorySelected(): Boolean {
return (selectedCategories.size == 0) && (selectedListsInCategory.size > 1) && (selectedLists.size == 0)
}
private fun manyListsSelected(): Boolean {
return (selectedCategories.size == 0) && (selectedListsInCategory.size == 0) && (selectedLists.size > 1)
}
private fun manyCategoriesAndListsInCategorySelected(): Boolean {
return (selectedCategories.size > 0) && (selectedListsInCategory.size > 0) && (selectedLists.size == 0)
}
private fun manyCategoriesAndListsSelected(): Boolean {
return (selectedCategories.size > 0) && (selectedListsInCategory.size == 0) && (selectedLists.size > 0)
}
private fun manyListsInCategoryAndListsSelected(): Boolean {
return (selectedCategories.size == 0) && (selectedListsInCategory.size > 0) && (selectedLists.size > 0)
}
private fun manyCategoriesAndListsInCategoryAndListsSelected(): Boolean {
return (selectedCategories.size > 0) && (selectedListsInCategory.size > 0) && (selectedLists.size > 0)
}
private fun deselectItems() {
deselectListItems()
deselectExpandableListViewVisibleItems()
}
private fun deselectListItems() {
for (i in 0 until listAdapter.count) {
view?.expandableheightlistview_mainlist_list?.setItemChecked(i, false)
}
}
/**
* Should deselect the visible items. Visible items are the group items, and the child
* items of expanded group items.
*/
private fun deselectExpandableListViewVisibleItems() {
if (view?.expandableheightexpandablelistview_mainlist_category != null) {
for (i in 0..view?.expandableheightexpandablelistview_mainlist_category!!.lastVisiblePosition) {
view!!.expandableheightexpandablelistview_mainlist_category!!.setItemChecked(i, false)
categoriesViewModel?.deselectItems()
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.fragment_mainlist, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menuitem_mainlist_search ->
([email protected] as MainActivity).onSearchActionItemClick()
}
return super.onOptionsItemSelected(item)
}
private fun openCreateListDialogFragment() {
val createListDialogFragment = CreateListDialogFragment()
createListDialogFragment.setTargetFragment(this, 0)
createListDialogFragment.show(parentFragmentManager, "CreateListDialogFragment")
}
private fun openCreateCategoryDialogFragment() {
val createCategoryDialogFragment = CreateCategoryDialogFragment()
createCategoryDialogFragment.setTargetFragment(this, 0)
createCategoryDialogFragment.show(parentFragmentManager, "CreateCategoryDialogFragment")
}
private fun openCreateListInCategoryDialogFragment() {
categoriesViewModel?.category = selectedCategories.get(0)
val createListInCategoryDialogFragment = CreateListInCategoryDialogFragment()
createListInCategoryDialogFragment.setTargetFragment(this, 0)
createListInCategoryDialogFragment.show(parentFragmentManager, "CreateListInCategoryDialogFragment")
}
private fun openModifyListInCategoryDialog() {
listsViewModel?.list = selectedListsInCategory.get(0)
listsViewModel?.isInCategory = true
openModifyListDialogFragment()
}
private fun openConfirmDeleteListInCategoryDialog() {
val list: com.rolandvitezhu.todocloud.data.List = selectedListsInCategory.get(0)
val onlineId: String? = list.listOnlineId
val title: String? = list.title
val arguments = Bundle()
arguments.putString("itemType", "listInCategory")
arguments.putString("itemTitle", title)
arguments.putString("onlineId", onlineId)
listsViewModel?.isInCategory = true
openConfirmDeleteDialogFragment(arguments)
}
private fun openConfirmDeleteListsInCategoryDialog() {
val arguments = Bundle()
arguments.putString("itemType", "listInCategory")
arguments.putParcelableArrayList("itemsToDelete", selectedListsInCategory)
listsViewModel?.isInCategory = true
openConfirmDeleteDialogFragment(arguments)
}
private fun openMoveListInCategoryDialog() {
lifecycleScope.launch {
val list: com.rolandvitezhu.todocloud.data.List = selectedListsInCategory.get(0)
categoriesViewModel?.category =
list.categoryOnlineId?.let{
todoCloudDatabaseDao.getCategoryByCategoryOnlineId(it)
}?: Category()
listsViewModel?.list = list
}
openMoveListDialogFragment()
}
private fun openMoveListIntoAnotherCategoryDialog() {
categoriesViewModel?.category = Category(getString(R.string.movelist_spinneritemlistnotincategory))
listsViewModel?.list = selectedLists.get(0)
openMoveListDialogFragment()
}
private fun openMoveListDialogFragment() {
val moveListDialogFragment = MoveListDialogFragment()
moveListDialogFragment.setTargetFragment(this, 0)
moveListDialogFragment.show(parentFragmentManager, "MoveListDialogFragment")
}
private fun openConfirmDeleteCategoryDialog() {
val category: Category = selectedCategories.get(0)
val onlineId: String? = category.categoryOnlineId
val title: String? = category.title
val arguments = Bundle()
arguments.putString("itemType", "category")
arguments.putString("itemTitle", title)
arguments.putString("onlineId", onlineId)
openConfirmDeleteDialogFragment(arguments)
}
private fun openConfirmDeleteCategoriesDialog() {
val arguments = Bundle()
arguments.putString("itemType", "category")
arguments.putParcelableArrayList("itemsToDelete", selectedCategories)
openConfirmDeleteDialogFragment(arguments)
}
private fun openConfirmDeleteDialogFragment(arguments: Bundle) {
val confirmDeleteDialogFragment = ConfirmDeleteDialogFragment()
confirmDeleteDialogFragment.setTargetFragment(this, 0)
confirmDeleteDialogFragment.arguments = arguments
confirmDeleteDialogFragment.show(parentFragmentManager, "ConfirmDeleteDialogFragment")
}
private fun openConfirmDeleteListDialog() {
val list: com.rolandvitezhu.todocloud.data.List = selectedLists.get(0)
val onlineId: String? = list.listOnlineId
val title: String? = list.title
val arguments = Bundle()
arguments.putString("itemType", "list")
arguments.putString("itemTitle", title)
arguments.putString("onlineId", onlineId)
listsViewModel?.isInCategory = false
openConfirmDeleteDialogFragment(arguments)
}
private fun openConfirmDeleteListsDialog() {
val arguments = Bundle()
arguments.putString("itemType", "list")
arguments.putParcelableArrayList("itemsToDelete", selectedLists)
listsViewModel?.isInCategory = false
openConfirmDeleteDialogFragment(arguments)
}
private fun openModifyCategoryDialogFragment() {
categoriesViewModel?.category = selectedCategories.get(0)
val modifyCategoryDialogFragment = ModifyCategoryDialogFragment()
modifyCategoryDialogFragment.setTargetFragment(this, 0)
modifyCategoryDialogFragment.show(parentFragmentManager, "ModifyCategoryDialogFragment")
}
private fun openModifyListDialog() {
listsViewModel?.list = selectedLists.get(0)
openModifyListDialogFragment()
}
private fun openModifyListDialogFragment() {
val modifyListDialogFragment = ModifyListDialogFragment()
modifyListDialogFragment.setTargetFragment(this, 0)
modifyListDialogFragment.show(parentFragmentManager, "ModifyListDialogFragment")
}
/**
* Show the circle icon as the synchronization starts and hide it as the synchronization
* finishes. Synchronizes all the entities - categories, lists, todos - between the local and
* remote database. Refreshes the UI to show the up-to-date data. Shows the error messages.
*/
private fun syncData(view: View?) {
lifecycleScope.launch {
try {
if (view != null)
view.swiperefreshlayout_mainlist?.isRefreshing = true
else
[email protected]_mainlist?.isRefreshing = true
categoriesViewModel?.onSynchronization()
listsViewModel?.onSynchronization()
categoriesViewModel?.updateCategoriesViewModel()
todoRepository.syncTodoData()
} catch (cause: Throwable) {
showErrorMessage(cause.message)
categoriesViewModel?.updateCategoriesViewModel()
listsViewModel?.updateListsViewModel()
} finally {
if (view != null)
view.swiperefreshlayout_mainlist?.isRefreshing = false
else
[email protected]_mainlist?.isRefreshing = false
}
}
}
/**
* Update all of the lists: predefined lists, lists, categories.
*/
private fun updateLists() {
lifecycleScope.launch {
predefinedListsViewModel?.updatePredefinedListsViewModel()
categoriesViewModel?.updateCategoriesViewModel()
listsViewModel?.updateListsViewModel()
}
}
val predefinedListItemClicked: OnItemClickListener = object : OnItemClickListener {
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
if (!isActionModeEnabled) {
val predefinedList: PredefinedList = parent.adapter.getItem(
position) as PredefinedList
([email protected] as MainActivity).onClickPredefinedList(predefinedList)
}
}
}
val listItemClicked: OnItemClickListener = object : OnItemClickListener {
override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
val clickedList: com.rolandvitezhu.todocloud.data.List =
listAdapter.getItem(position) as com.rolandvitezhu.todocloud.data.List
if (!isActionModeEnabled) {
([email protected] as MainActivity).onClickList(clickedList)
} else {
handleItemSelection(position, clickedList)
}
}
private fun handleItemSelection(position: Int, clickedList: com.rolandvitezhu.todocloud.data.List) {
// Item checked state being set automatically on item click event. We should track
// the changes only.
if (view?.expandableheightlistview_mainlist_list?.isItemChecked(position) == true) {
selectedLists.add(clickedList)
listAdapter.toggleSelection(position)
} else {
selectedLists.remove(clickedList)
listAdapter.toggleSelection(position)
}
if (isNoSelectedItems) {
actionMode?.finish()
listAdapter.clearSelection()
} else {
actionMode?.invalidate()
}
}
}
val listItemLongClicked: OnItemLongClickListener = object : OnItemLongClickListener {
override fun onItemLongClick(parent: AdapterView<*>?, view: View, position: Int, id: Long):
Boolean {
if (!isActionModeEnabled) {
startActionMode(position)
listAdapter.toggleSelection(position)
}
return true
}
private fun startActionMode(position: Int) {
([email protected] as MainActivity).onStartActionMode(callback)
view?.expandableheightlistview_mainlist_list?.choiceMode =
AbsListView.CHOICE_MODE_MULTIPLE
view?.expandableheightlistview_mainlist_list?.setItemChecked(position, true)
val selectedList: com.rolandvitezhu.todocloud.data.List =
view?.expandableheightlistview_mainlist_list?.getItemAtPosition(position) as
com.rolandvitezhu.todocloud.data.List
selectedLists.add(selectedList)
view?.expandableheightlistview_mainlist_list?.choiceMode =
AbsListView.CHOICE_MODE_MULTIPLE
actionMode?.invalidate()
}
}
private val expLVChildClicked: OnChildClickListener = object : OnChildClickListener {
override fun onChildClick(parent: ExpandableListView, v: View, groupPosition: Int,
childPosition: Int, id: Long): Boolean {
val clickedList: com.rolandvitezhu.todocloud.data.List = categoryAdapter.getChild(
groupPosition,
childPosition
) as com.rolandvitezhu.todocloud.data.List
if (!isActionModeEnabled) {
([email protected] as MainActivity).onClickList(clickedList)
} else {
handleItemSelection(clickedList)
}
return true
}
private fun handleItemSelection(clickedList: com.rolandvitezhu.todocloud.data.List) {
categoriesViewModel?.toggleListSelected(clickedList)
if (clickedList.isSelected) {
selectedListsInCategory.add(clickedList)
} else {
selectedListsInCategory.remove(clickedList)
}
if (isNoSelectedItems) {
actionMode?.finish()
} else {
actionMode?.invalidate()
}
}
}
private val expLVGroupClicked: OnGroupClickListener = object : OnGroupClickListener {
override fun onGroupClick(parent: ExpandableListView, v: View, groupPosition: Int, id: Long): Boolean {
val packedPosition: Long = getPackedPositionForGroup(groupPosition)
val position: Int = parent.getFlatListPosition(packedPosition)
if (!isActionModeEnabled) {
handleGroupExpanding(parent, groupPosition)
} else {
handleItemSelection(parent, position)
}
return true
}
private fun handleItemSelection(
parent: ExpandableListView,
position: Int
) {
val clickedCategory: Category = parent.getItemAtPosition(position) as Category
categoriesViewModel?.toggleCategorySelected(clickedCategory)
if (clickedCategory.isSelected) {
selectedCategories.add(clickedCategory)
} else {
selectedCategories.remove(clickedCategory)
}
if (isNoSelectedItems) {
actionMode?.finish()
} else {
actionMode?.invalidate()
}
}
private fun handleGroupExpanding(parent: ExpandableListView, groupPosition: Int) {
if (!parent.isGroupExpanded(groupPosition)) {
parent.expandGroup(groupPosition)
} else {
parent.collapseGroup(groupPosition)
}
}
}
private val expLVCategoryContextMenuListener: OnCreateContextMenuListener =
object : OnCreateContextMenuListener {
override fun onCreateContextMenu(menu: ContextMenu, v: View,
menuInfo: ContextMenuInfo) {
if (!isActionModeEnabled &&
view?.expandableheightexpandablelistview_mainlist_category != null) {
val info: ExpandableListContextMenuInfo = menuInfo as ExpandableListContextMenuInfo
val packedPosition: Long = info.packedPosition
val position: Int = view?.expandableheightexpandablelistview_mainlist_category!!.
getFlatListPosition(packedPosition)
val packedPositionType: Int = getPackedPositionType(packedPosition)
if (categoryClicked(packedPositionType)) {
startActionModeWithCategory(position)
} else if (listClicked(packedPositionType)) {
startActionModeWithList(position)
}
}
}
private fun startActionModeWithList(position: Int) {
if (view?.expandableheightexpandablelistview_mainlist_category != null) {
actionModeStartedWithELV = true
([email protected] as MainActivity).onStartActionMode(callback)
val clickedList: com.rolandvitezhu.todocloud.data.List =
view?.expandableheightexpandablelistview_mainlist_category?.
getItemAtPosition(position) as com.rolandvitezhu.todocloud.data.List
categoriesViewModel?.toggleListSelected(clickedList)
selectedListsInCategory.add(clickedList)
view?.expandableheightlistview_mainlist_list?.choiceMode =
AbsListView.CHOICE_MODE_MULTIPLE
actionMode?.invalidate()
}
}
private fun startActionModeWithCategory(position: Int) {
if (view?.expandableheightexpandablelistview_mainlist_category != null) {
actionModeStartedWithELV = true
([email protected] as MainActivity).onStartActionMode(callback)
val clickedCategory: Category =
view?.expandableheightexpandablelistview_mainlist_category!!.
getItemAtPosition(position) as Category
categoriesViewModel?.toggleCategorySelected(clickedCategory)
selectedCategories.add(clickedCategory)
view?.expandableheightlistview_mainlist_list?.choiceMode =
AbsListView.CHOICE_MODE_MULTIPLE
actionMode?.invalidate()
}
}
private fun listClicked(packedPositionType: Int): Boolean {
return packedPositionType == PACKED_POSITION_TYPE_CHILD
}
private fun categoryClicked(packedPositionType: Int): Boolean {
return packedPositionType == PACKED_POSITION_TYPE_GROUP
}
}
/**
* Finish the action mode if the screen is in it.
*/
fun finishActionMode() {
actionMode?.finish()
}
override fun onRefresh() {
syncData(null)
}
private fun showErrorMessage(errorMessage: String?) {
if (errorMessage != null) {
val upperCaseErrorMessage = errorMessage.toUpperCase()
if (upperCaseErrorMessage.contains("FAILED TO CONNECT") ||
upperCaseErrorMessage.contains("UNABLE TO RESOLVE HOST") ||
upperCaseErrorMessage.contains("TIMEOUT")) {
showFailedToConnectError()
} else {
showAnErrorOccurredError()
}
}
}
private fun showFailedToConnectError() {
// Android Studio hotswap/coldswap may cause getView == null
try {
val snackbar: Snackbar = Snackbar.make(
view?.constraintlayout_mainlist!!,
R.string.all_failedtoconnect,
Snackbar.LENGTH_LONG
)
showWhiteTextSnackbar(snackbar)
} catch (e: NullPointerException) {
// Snackbar or constraintLayout doesn't exists already.
}
}
private fun showAnErrorOccurredError() {
try {
val snackbar: Snackbar = Snackbar.make(
view?.constraintlayout_mainlist!!,
R.string.all_anerroroccurred,
Snackbar.LENGTH_LONG
)
showWhiteTextSnackbar(snackbar)
} catch (e: NullPointerException) {
// Snackbar or constraintLayout doesn't exists already.
}
}
fun onFABCreateCategoryClick() {
openCreateCategoryDialogFragment()
this.main_fam.close(true)
}
fun onFABCreateListClick() {
openCreateListDialogFragment()
this.main_fam.close(true)
}
}
| mit | 05339288186f5b30367bb925d172b391 | 41.602787 | 117 | 0.641613 | 6.014265 | false | false | false | false |
Maccimo/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildSampleEntityImpl.kt | 2 | 8486 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildSampleEntityImpl: ChildSampleEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(SampleEntity::class.java, ChildSampleEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
@JvmField var _data: String? = null
override val data: String
get() = _data!!
override val parentEntity: SampleEntity?
get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ChildSampleEntityData?): ModifiableWorkspaceEntityBase<ChildSampleEntity>(), ChildSampleEntity.Builder {
constructor(): this(ChildSampleEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildSampleEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isDataInitialized()) {
error("Field ChildSampleEntity#data should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field ChildSampleEntity#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData().data = value
changedProperty.add("data")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var parentEntity: SampleEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? SampleEntity
} else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? SampleEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityData(): ChildSampleEntityData = result ?: super.getEntityData() as ChildSampleEntityData
override fun getEntityClass(): Class<ChildSampleEntity> = ChildSampleEntity::class.java
}
}
class ChildSampleEntityData : WorkspaceEntityData<ChildSampleEntity>() {
lateinit var data: String
fun isDataInitialized(): Boolean = ::data.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildSampleEntity> {
val modifiable = ChildSampleEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ChildSampleEntity {
val entity = ChildSampleEntityImpl()
entity._data = data
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildSampleEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildSampleEntityData
if (this.data != other.data) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildSampleEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
} | apache-2.0 | f06483741557424a6dfebaf84cea1125 | 39.802885 | 187 | 0.628683 | 5.992938 | false | false | false | false |
android/renderscript-intrinsics-replacement-toolkit | test-app/src/main/java/com/google/android/renderscript_test/IntrinsicBlend.kt | 1 | 7002 | /*
* 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.google.android.renderscript_test
import android.graphics.Bitmap
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.Script
import android.renderscript.ScriptIntrinsicBlend
import android.renderscript.Type
import com.google.android.renderscript.BlendingMode
import com.google.android.renderscript.Range2d
/**
* Does a Blend operation using the RenderScript Intrinsics.
*/
fun intrinsicBlend(
context: RenderScript,
mode: BlendingMode,
sourceArray: ByteArray,
destArray: ByteArray,
sizeX: Int,
sizeY: Int,
restriction: Range2d?
) {
val scriptBlend = ScriptIntrinsicBlend.create(context, Element.U8_4(context))
val builder = Type.Builder(context, Element.U8_4(context))
builder.setX(sizeX)
builder.setY(sizeY)
val arrayType = builder.create()
val sourceAllocation = Allocation.createTyped(context, arrayType)
val destAllocation = Allocation.createTyped(context, arrayType)
sourceAllocation.copyFrom(sourceArray)
destAllocation.copyFrom(destArray)
callBlendForEach(scriptBlend, sourceAllocation, destAllocation, mode, restriction)
destAllocation.copyTo(destArray)
sourceAllocation.destroy()
destAllocation.destroy()
arrayType.destroy()
scriptBlend.destroy()
}
fun intrinsicBlend(
context: RenderScript,
mode: BlendingMode,
sourceBitmap: Bitmap,
destBitmap: Bitmap,
restriction: Range2d?
) {
val scriptBlend = ScriptIntrinsicBlend.create(context, Element.U8_4(context))
val sourceAllocation = Allocation.createFromBitmap(context, sourceBitmap)
val destAllocation = Allocation.createFromBitmap(context, destBitmap)
sourceAllocation.copyFrom(sourceBitmap)
destAllocation.copyFrom(destBitmap)
callBlendForEach(scriptBlend, sourceAllocation, destAllocation, mode, restriction)
destAllocation.copyTo(destBitmap)
sourceAllocation.destroy()
destAllocation.destroy()
scriptBlend.destroy()
}
private fun callBlendForEach(
scriptBlend: ScriptIntrinsicBlend,
sourceAllocation: Allocation,
destAllocation: Allocation,
mode: BlendingMode,
restriction: Range2d?
) {
if (restriction != null) {
val options = Script.LaunchOptions()
options.setX(restriction.startX, restriction.endX)
options.setY(restriction.startY, restriction.endY)
when (mode) {
BlendingMode.CLEAR -> scriptBlend.forEachClear(
sourceAllocation, destAllocation, options
)
BlendingMode.SRC -> scriptBlend.forEachSrc(
sourceAllocation, destAllocation, options
)
BlendingMode.DST -> scriptBlend.forEachDst(
sourceAllocation, destAllocation, options
)
BlendingMode.SRC_OVER -> scriptBlend.forEachSrcOver(
sourceAllocation, destAllocation, options
)
BlendingMode.DST_OVER -> scriptBlend.forEachDstOver(
sourceAllocation, destAllocation, options
)
BlendingMode.SRC_IN -> scriptBlend.forEachSrcIn(
sourceAllocation, destAllocation, options
)
BlendingMode.DST_IN -> scriptBlend.forEachDstIn(
sourceAllocation, destAllocation, options
)
BlendingMode.SRC_OUT -> scriptBlend.forEachSrcOut(
sourceAllocation, destAllocation, options
)
BlendingMode.DST_OUT -> scriptBlend.forEachDstOut(
sourceAllocation, destAllocation, options
)
BlendingMode.SRC_ATOP -> scriptBlend.forEachSrcAtop(
sourceAllocation, destAllocation, options
)
BlendingMode.DST_ATOP -> scriptBlend.forEachDstAtop(
sourceAllocation, destAllocation, options
)
BlendingMode.XOR -> scriptBlend.forEachXor(
sourceAllocation, destAllocation, options
)
BlendingMode.MULTIPLY -> scriptBlend.forEachMultiply(
sourceAllocation, destAllocation, options
)
BlendingMode.ADD -> scriptBlend.forEachAdd(
sourceAllocation, destAllocation, options
)
BlendingMode.SUBTRACT -> scriptBlend.forEachSubtract(
sourceAllocation, destAllocation, options
)
}
} else {
when (mode) {
BlendingMode.CLEAR -> scriptBlend.forEachClear(
sourceAllocation, destAllocation
)
BlendingMode.SRC -> scriptBlend.forEachSrc(
sourceAllocation, destAllocation
)
BlendingMode.DST -> scriptBlend.forEachDst(
sourceAllocation, destAllocation
)
BlendingMode.SRC_OVER -> scriptBlend.forEachSrcOver(
sourceAllocation, destAllocation
)
BlendingMode.DST_OVER -> scriptBlend.forEachDstOver(
sourceAllocation, destAllocation
)
BlendingMode.SRC_IN -> scriptBlend.forEachSrcIn(
sourceAllocation, destAllocation
)
BlendingMode.DST_IN -> scriptBlend.forEachDstIn(
sourceAllocation, destAllocation
)
BlendingMode.SRC_OUT -> scriptBlend.forEachSrcOut(
sourceAllocation, destAllocation
)
BlendingMode.DST_OUT -> scriptBlend.forEachDstOut(
sourceAllocation, destAllocation
)
BlendingMode.SRC_ATOP -> scriptBlend.forEachSrcAtop(
sourceAllocation, destAllocation
)
BlendingMode.DST_ATOP -> scriptBlend.forEachDstAtop(
sourceAllocation, destAllocation
)
BlendingMode.XOR -> scriptBlend.forEachXor(
sourceAllocation, destAllocation
)
BlendingMode.MULTIPLY -> scriptBlend.forEachMultiply(
sourceAllocation, destAllocation
)
BlendingMode.ADD -> scriptBlend.forEachAdd(
sourceAllocation, destAllocation
)
BlendingMode.SUBTRACT -> scriptBlend.forEachSubtract(
sourceAllocation, destAllocation
)
}
}
}
| apache-2.0 | 6be914731c59067688a48ecbd2895707 | 36.244681 | 86 | 0.652242 | 5.697315 | false | false | false | false |
Hexworks/zircon | zircon.jvm.libgdx/src/main/kotlin/org/hexworks/zircon/internal/tileset/transformer/LibgdxTextureCloner.kt | 1 | 767 | package org.hexworks.zircon.internal.tileset.transformer
import com.badlogic.gdx.graphics.g2d.TextureRegion
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.tileset.TextureTransformer
import org.hexworks.zircon.api.tileset.TileTexture
import org.hexworks.zircon.internal.tileset.impl.DefaultTileTexture
class LibgdxTextureCloner : TextureTransformer<TextureRegion> {
override val targetType = TextureRegion::class
override fun transform(texture: TileTexture<TextureRegion>, tile: Tile): TileTexture<TextureRegion> {
return DefaultTileTexture(
width = texture.width,
height = texture.height,
texture = TextureRegion(texture.texture),
cacheKey = tile.cacheKey
)
}
}
| apache-2.0 | 779efe9daa1979714ca0e00e45505410 | 35.52381 | 105 | 0.74837 | 4.648485 | false | false | false | false |
ligi/PassAndroid | android/src/main/java/org/ligi/passandroid/functions/AddToCalendar.kt | 1 | 2260 | package org.ligi.passandroid.functions
import android.content.ActivityNotFoundException
import android.content.Intent
import android.provider.CalendarContract
import androidx.annotation.VisibleForTesting
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AlertDialog
import android.view.View
import org.ligi.passandroid.R
import org.ligi.passandroid.model.pass.Pass
import org.ligi.passandroid.model.pass.PassImpl
const val DEFAULT_EVENT_LENGTH_IN_HOURS = 8L
fun tryAddDateToCalendar(pass: Pass, contextView: View, timeSpan: PassImpl.TimeSpan) {
if (pass.calendarTimespan == null) {
AlertDialog.Builder(contextView.context).setMessage(R.string.expiration_date_to_calendar_warning_message)
.setTitle(R.string.expiration_date_to_calendar_warning_title)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok) { _, _ -> reallyAddToCalendar(pass, contextView, timeSpan) }
.show()
} else {
reallyAddToCalendar(pass, contextView, timeSpan)
}
}
private fun reallyAddToCalendar(pass: Pass, contextView: View, timeSpan: PassImpl.TimeSpan) = try {
val intent = createIntent(pass, timeSpan)
contextView.context.startActivity(intent)
} catch (exception: ActivityNotFoundException) {
// TODO maybe action to install calendar app
Snackbar.make(contextView, R.string.no_calendar_app_found, Snackbar.LENGTH_LONG).show()
}
@VisibleForTesting
fun createIntent(pass: Pass, timeSpan: PassImpl.TimeSpan) = Intent(Intent.ACTION_EDIT).apply {
if (timeSpan.from == null && timeSpan.to == null) {
throw IllegalArgumentException("span must have either a to or a from")
}
type = "vnd.android.cursor.item/event"
val from = timeSpan.from ?: timeSpan.to!!.minusHours(DEFAULT_EVENT_LENGTH_IN_HOURS)
putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, from.toEpochSecond() * 1000)
val to = timeSpan.to ?: timeSpan.from!!.plusHours(DEFAULT_EVENT_LENGTH_IN_HOURS)
putExtra(CalendarContract.EXTRA_EVENT_END_TIME, to.toEpochSecond() * 1000)
putExtra("title", pass.description)
pass.locations.firstOrNull()?.name?.let {
putExtra("eventLocation", it)
}
}
| gpl-3.0 | eacb77a51b89646e78804da2039b1035 | 36.666667 | 116 | 0.735398 | 4.050179 | false | false | false | false |
ingokegel/intellij-community | java/java-tests/testSrc/com/intellij/internal/statistic/libraryUsage/LibraryUsageStatisticStorageTest.kt | 8 | 3865 | // 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.internal.statistic.libraryUsage
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase
import com.intellij.util.xmlb.XmlSerializer
class LibraryUsageStatisticStorageTest : LightJavaCodeInsightFixtureTestCase() {
fun testFiles() {
val txtFile = myFixture.addFileToProject("Text.txt", "").virtualFile
val javaFile = myFixture.addFileToProject("JavaFile.java", "").virtualFile
val filesStorageService = ProcessedFilesStorageService.getInstance(project)
val state = filesStorageService.state
val timestamps = state.timestamps
assertFalse(filesStorageService.isVisited(txtFile))
assertTrue(filesStorageService.visit(txtFile))
assertTrue(filesStorageService.isVisited(txtFile))
assertFalse(filesStorageService.visit(txtFile))
assertTrue(filesStorageService.isVisited(txtFile))
filesStorageService.visit(txtFile)
assertTrue(filesStorageService.isVisited(txtFile))
assertFalse(filesStorageService.isVisited(javaFile))
assertTrue(filesStorageService.visit(javaFile))
assertTrue(filesStorageService.isVisited(javaFile))
assertTrue(timestamps.isNotEmpty())
val serializedState = XmlSerializer.serialize(state)
val deserializedState = XmlSerializer.deserialize(
serializedState,
ProcessedFilesStorageService.MyState::class.java,
)
assertEquals(timestamps, deserializedState.timestamps)
filesStorageService.loadState(deserializedState)
assertEquals(timestamps, filesStorageService.state.timestamps)
}
fun testLibraries() {
val txtFile = myFixture.addFileToProject("Text.txt", "").virtualFile
val javaFile = myFixture.addFileToProject("JavaFile.java", "").virtualFile
val storageService = LibraryUsageStatisticsStorageService.getInstance(project)
val txtLib = createLib(txtFile)
storageService.increaseUsage(txtLib)
storageService.increaseUsage(txtLib)
storageService.increaseUsage(createLib(javaFile))
storageService.increaseUsages(listOf(txtLib, createLib(txtFile, version = "1.0.0"), createLib(txtFile, name = "otherName")))
val copyOfState = storageService.state
assertTrue(copyOfState.statistics.isNotEmpty())
assertEquals(copyOfState.statistics, storageService.state.statistics)
val expectedSet = mapOf(
LibraryUsage("myLibName", "1.1.1", "PLAIN_TEXT") to 3,
LibraryUsage("myLibName", "1.0.0", "PLAIN_TEXT") to 1,
LibraryUsage("myLibName", "1.1.1", "JAVA") to 1,
LibraryUsage("otherName", "1.1.1", "PLAIN_TEXT") to 1,
)
assertEquals(expectedSet, copyOfState.statistics)
assertEquals(expectedSet, storageService.getStatisticsAndResetState())
assertTrue(storageService.state.statistics.isEmpty())
storageService.loadState(copyOfState)
val state = storageService.state
val statistics = storageService.getStatisticsAndResetState()
assertEquals(expectedSet, statistics)
assertTrue(storageService.state.statistics.isEmpty())
val serializedState = XmlSerializer.serialize(state)
val deserializedState = XmlSerializer.deserialize(
serializedState,
LibraryUsageStatisticsStorageService.LibraryUsageStatisticsState::class.java,
)
assertEquals(expectedSet, deserializedState.statistics)
storageService.loadState(deserializedState)
assertEquals(expectedSet, storageService.state.statistics)
}
}
private fun LibraryUsageStatisticsStorageService.increaseUsage(lib: LibraryUsage) {
increaseUsages(listOf(lib))
}
private fun createLib(
vFile: VirtualFile,
name: String = "myLibName",
version: String = "1.1.1",
): LibraryUsage = LibraryUsage(name = name, version = version, fileType = vFile.fileType) | apache-2.0 | e455051d125cf4e9c0c46329cc52acde | 39.694737 | 128 | 0.774127 | 4.948784 | false | true | false | false |
android/play-billing-samples | ClassyTaxiAppKotlin/app/src/main/java/com/example/subscriptions/ui/SubscriptionBindingAdapter.kt | 1 | 13651 | /**
* Copyright 2018 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.subscriptions.ui
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.Target
import com.example.subscriptions.Constants
import com.example.subscriptions.R
import com.example.subscriptions.billing.isAccountHold
import com.example.subscriptions.billing.isBasicContent
import com.example.subscriptions.billing.isGracePeriod
import com.example.subscriptions.billing.isPaused
import com.example.subscriptions.billing.isPremiumContent
import com.example.subscriptions.billing.isPrepaid
import com.example.subscriptions.billing.isSubscriptionRestore
import com.example.subscriptions.billing.isTransferRequired
import com.example.subscriptions.data.ContentResource
import com.example.subscriptions.data.SubscriptionStatus
import com.example.subscriptions.utils.basicTextForSubscription
import com.example.subscriptions.utils.premiumTextForSubscription
import java.text.SimpleDateFormat
import java.util.Calendar
private const val TAG = "BindingAdapter"
/**
* Update a loading progress bar when the status changes.
*
* When the network state changes, the binding adapter triggers this view in the layout XML.
* See the layout XML files for the app:loadingProgressBar attribute.
*/
@BindingAdapter("loadingProgressBar")
fun ProgressBar.loadingProgressBar(loading: Boolean?) {
visibility = if (loading == true) View.VISIBLE else View.GONE
}
/**
* Load image with original size. If url is null, hide [ImageView]
*/
@BindingAdapter("loadImageOrHide")
fun ImageView.loadImageOrHide(url: String?) {
if (url != null) {
Log.d(TAG, "Loading image for content: $url")
visibility = View.VISIBLE
Glide.with(context)
.load(url)
.override(Target.SIZE_ORIGINAL)
.into(this)
} else {
visibility = View.GONE
}
}
/**
* Update basic content when the URL changes.
*/
@BindingAdapter("basicContent")
fun TextView.updateBasicContent(basicContent: ContentResource?) {
text = if (basicContent?.url != null)
resources.getString(R.string.basic_auto_message)
else
resources.getString(R.string.no_basic_content)
}
/**
* Update premium content on the Premium fragment when the URL changes.
*/
@BindingAdapter("premiumContent")
fun TextView.updatePremiumContent(premiumContent: ContentResource?) {
text = if (premiumContent?.url != null)
resources.getString(R.string.premium_content_text)
else
resources.getString(R.string.no_premium_content)
}
/**
* Update subscription views on the Home fragment when the subscription changes.
*
* When the subscription changes, the binding adapter triggers this view in the layout XML.
* See the layout XML files for the app:updateHomeViews attribute.
*/
@BindingAdapter("updateHomeViews")
fun LinearLayout.updateHomeViews(subscriptions: List<SubscriptionStatus>?) {
val paywallMessage = findViewById<View>(R.id.home_paywall_message)
val restoreMessage = findViewById<TextView>(R.id.home_restore_message)
val gracePeriodMessage = findViewById<View>(R.id.home_grace_period_message)
val transferMessage = findViewById<View>(R.id.home_transfer_message)
val accountHoldMessage = findViewById<View>(R.id.home_account_hold_message)
val accountPausedMessage = findViewById<View>(R.id.home_account_paused_message)
val basicMessage = findViewById<View>(R.id.home_basic_message)
val downgradeMessage = findViewById<View>(R.id.basic_downgrade_message)
val prepaidMessage = findViewById<View>(R.id.prepaid_basic_content)
val accountPausedMessageText = findViewById<TextView>(R.id.home_account_paused_message_text)
// Set visibility assuming no subscription is available.
// If a subscription is found that meets certain criteria, then the visibility of the paywall
// will be changed to View.GONE.
paywallMessage.visibility = View.VISIBLE
// The remaining views start hidden. If a subscription is found that meets each criteria,
// then the visibility will be changed to View.VISIBLE.
listOf(
restoreMessage, gracePeriodMessage, transferMessage, accountHoldMessage,
accountPausedMessage, basicMessage, prepaidMessage, downgradeMessage
).forEach { it.visibility = View.GONE }
// Update based on subscription information.
subscriptions?.forEach { subscription ->
if (subscription.isBasicContent && isSubscriptionRestore(subscription) && !subscription.isPrepaid) {
Log.d(TAG, "restore VISIBLE")
restoreMessage.run {
visibility = View.VISIBLE
val expiryDate = getHumanReadableDate(subscription.activeUntilMillisec)
text = resources.getString(R.string.restore_message_with_date, expiryDate)
}
paywallMessage.visibility = View.GONE // Paywall gone.
}
if (isGracePeriod(subscription)) {
Log.d(TAG, "grace period VISIBLE")
gracePeriodMessage.visibility = View.VISIBLE
paywallMessage.visibility = View.GONE // Paywall gone.
}
if (isTransferRequired(subscription) && subscription.product == Constants.BASIC_PRODUCT) {
Log.d(TAG, "transfer VISIBLE")
transferMessage.visibility = View.VISIBLE
paywallMessage.visibility = View.GONE // Paywall gone.
}
if (isAccountHold(subscription)) {
Log.d(TAG, "account hold VISIBLE")
accountHoldMessage.visibility = View.VISIBLE
paywallMessage.visibility = View.GONE // Paywall gone.
}
if (isPaused(subscription)) {
Log.d(TAG, "account paused VISIBLE")
accountPausedMessageText.run {
val autoResumeDate = getHumanReadableDate(subscription.autoResumeTimeMillis)
text = resources.getString(R.string.account_paused_message, autoResumeDate)
}
accountPausedMessage.visibility = View.VISIBLE
paywallMessage.visibility = View.GONE // Paywall gone.
}
if (subscription.isBasicContent && !isPremiumContent(subscription) && !subscription.isPrepaid) {
Log.d(TAG, "Downgrade VISIBLE")
basicMessage.visibility = View.VISIBLE
paywallMessage.visibility = View.GONE // Paywall gone.
}
if (subscription.isPrepaid && subscription.isBasicContent && !isPremiumContent(subscription)) {
Log.d(TAG, "Basic Prepaid VISIBLE")
prepaidMessage.visibility = View.VISIBLE
paywallMessage.visibility = View.GONE
}
if (!subscription.isBasicContent && isPremiumContent(subscription)) {
Log.d(TAG, "Downgrade VISIBLE")
downgradeMessage.visibility = View.VISIBLE
paywallMessage.visibility = View.GONE
}
}
}
/**
* Update subscription views on the Premium fragment when the subscription changes.
*
* When the subscription changes, the binding adapter triggers this view in the layout XML.
* See the layout XML files for the app:updatePremiumViews attribute.
*/
@BindingAdapter("updatePremiumViews")
fun LinearLayout.updatePremiumViews(subscriptions: List<SubscriptionStatus>?) {
val paywallMessage = findViewById<View>(R.id.premium_paywall_message)
val restoreMessage = findViewById<TextView>(R.id.premium_restore_message)
val gracePeriodMessage = findViewById<TextView>(R.id.premium_grace_period_message)
val transferMessage = findViewById<View>(R.id.premium_transfer_message)
val accountHoldMessage = findViewById<View>(R.id.premium_account_hold_message)
val accountPausedMessage = findViewById<View>(R.id.premium_account_paused_message)
val premiumContent = findViewById<View>(R.id.premium_premium_content)
val upgradeMessage = findViewById<View>(R.id.premium_upgrade_message)
val prepaidMessage = findViewById<View>(R.id.prepaid_premium_content)
val accountPausedMessageText = findViewById<TextView>(R.id.premium_account_paused_message_text)
// Set visibility assuming no subscription is available.
// If a subscription is found that meets certain criteria, then the visibility of the paywall
// will be changed to View.GONE.
paywallMessage.visibility = View.VISIBLE
// The remaining views start hidden. If a subscription is found that meets each criteria,
// then the visibility will be changed to View.VISIBLE.
listOf(
restoreMessage, gracePeriodMessage, transferMessage, accountHoldMessage,
accountPausedMessage, premiumContent, upgradeMessage, prepaidMessage
).forEach { it.visibility = View.GONE }
// The Upgrade button should appear if the user has a basic subscription, but does not
// have a premium subscription. This variable keeps track of whether a premium subscription
// has been found when looking through the list of subscriptions.
// Update based on subscription information.
subscriptions?.let {
for (subscription in subscriptions) {
if (isPremiumContent(subscription) && isSubscriptionRestore(subscription) && !subscription.isPrepaid) {
Log.d(TAG, "restore VISIBLE")
restoreMessage.run {
visibility = View.VISIBLE
val expiryDate = getHumanReadableDate(subscription.activeUntilMillisec)
text = resources.getString(R.string.restore_message_with_date, expiryDate)
}
paywallMessage.visibility = View.GONE // Paywall gone.
}
if (isGracePeriod(subscription)) {
Log.d(TAG, "grace period VISIBLE")
gracePeriodMessage.visibility = View.VISIBLE
paywallMessage.visibility = View.GONE // Paywall gone.
}
if (isTransferRequired(subscription) && subscription.product == Constants.PREMIUM_PRODUCT) {
Log.d(TAG, "transfer VISIBLE")
transferMessage.visibility = View.VISIBLE
paywallMessage.visibility = View.GONE // Paywall gone.
}
if (isAccountHold(subscription)) {
Log.d(TAG, "account hold VISIBLE")
accountHoldMessage.visibility = View.VISIBLE
paywallMessage.visibility = View.GONE // Paywall gone.
}
if (isPaused(subscription)) {
Log.d(TAG, "account paused VISIBLE")
accountPausedMessageText.run {
val autoResumeDate = getHumanReadableDate(subscription.autoResumeTimeMillis)
text = resources.getString(R.string.account_paused_message, autoResumeDate)
}
accountPausedMessage.visibility = View.VISIBLE
paywallMessage.visibility = View.GONE // Paywall gone.
}
// The upgrade message must be shown if there is a basic subscription
// and there are zero premium subscriptions. We need to keep track of the premium
// subscriptions and hide the upgrade message if we find any.
if (isPremiumContent(subscription) && !subscription.isPrepaid && !subscription.isBasicContent) {
Log.d(TAG, "premium VISIBLE")
premiumContent.visibility = View.VISIBLE
paywallMessage.visibility = View.GONE // Paywall gone.
}
if (isPremiumContent(subscription) && !subscription.isBasicContent && subscription.isPrepaid) {
Log.d(TAG, "Premium Prepaid VISIBLE")
prepaidMessage.visibility = View.VISIBLE
paywallMessage.visibility = View.GONE
}
if (!isPremiumContent(subscription) && subscription.isBasicContent) {
Log.d(TAG, "Upgrade VISIBLE")
upgradeMessage.visibility = View.VISIBLE
paywallMessage.visibility = View.GONE
}
}
}
}
/**
* Update views on the Settings fragment when the subscription changes.
*
* When the subscription changes, the binding adapter triggers this view in the layout XML.
* See the layout XML files for the app:updateSettingsViews attribute.
* TODO(232165789): update method to update settings view
*/
@BindingAdapter("updateSettingsViews")
fun LinearLayout.updateSettingsViews(subscriptions: List<SubscriptionStatus>?) {
}
/**
* Get a readable date from the time in milliseconds.
*/
fun getHumanReadableDate(milliSeconds: Long): String {
val formatter = SimpleDateFormat.getDateInstance()
val calendar = Calendar.getInstance()
calendar.timeInMillis = milliSeconds
if (milliSeconds == 0L) {
Log.d(TAG, "Suspicious time: 0 milliseconds.")
} else {
Log.d(TAG, "Milliseconds: $milliSeconds")
}
return formatter.format(calendar.time)
} | apache-2.0 | b16377212dbf720e999fa17ea649865c | 45.753425 | 115 | 0.698557 | 4.894586 | false | false | false | false |
Carighan/kotlin-koans | src/i_introduction/_0_Hello_World/n00Start.kt | 5 | 1103 | package i_introduction._0_Hello_World
import util.TODO
import util.doc0
fun todoTask0(): Nothing = TODO(
"""
Task 0.
Read README.md to learn how to work with this project and check your solutions.
Using 'documentation =' below the task description you can open the related part of the online documentation.
Press 'Ctrl+Q'(Windows) or 'F1'(Mac OS) on 'doc0()' to call the "Quick Documentation" action;
"See also" section gives you a link.
You can see the shortcut for the "Quick Documentation" action used in your IntelliJ IDEA
by choosing "Help -> Find Action..." (in the top menu), and typing the action name ("Quick Documentation").
The shortcut in use will be written next to the action name.
Using 'references =' you can navigate to the code mentioned in the task description.
Let's start! Make the function 'task0' return "OK". Note that you can return expression directly.
""",
documentation = doc0(),
references = { task0(); "OK" }
)
fun task0(): String {
return "OK"
} | mit | 982792cade73debfe3b10de3b70ab320 | 37.068966 | 119 | 0.658205 | 4.394422 | false | false | false | false |
AberrantFox/hotbot | src/main/kotlin/me/aberrantfox/hotbot/commandframework/commands/permissions/PermissionsCommands.kt | 1 | 6548 | package me.aberrantfox.hotbot.commandframework.commands.permissions
import me.aberrantfox.hotbot.commandframework.parsing.ArgumentType
import me.aberrantfox.hotbot.dsls.command.Command
import me.aberrantfox.hotbot.dsls.command.CommandSet
import me.aberrantfox.hotbot.dsls.command.commands
import me.aberrantfox.hotbot.dsls.embed.embed
import me.aberrantfox.hotbot.extensions.stdlib.sanitiseMentions
import me.aberrantfox.hotbot.permissions.PermissionLevel
import me.aberrantfox.hotbot.services.CommandDescriptor
import me.aberrantfox.hotbot.services.HelpConf
import net.dv8tion.jda.core.entities.Role
import java.awt.Color
@CommandSet
fun permissionCommands() =
commands {
command("setPermission") {
expect(ArgumentType.Command, ArgumentType.PermissionLevel)
execute {
val command = it.args.component1() as Command
val level = it.args.component2() as PermissionLevel
it.manager.setPermission(command.name, level)
it.safeRespond("${command.name} is now accessible to ${level.name} and higher")
}
}
command("getPermission") {
expect(ArgumentType.Command)
execute {
val name = (it.args.component1() as Command).name
it.safeRespond("The required role is: ${it.manager.roleRequired(name).name}")
}
}
command("listcommandperms") {
execute {
it.respond(it.manager.listAvailableCommands(it.author))
}
}
command("roleids") {
execute {
it.safeRespond(it.guild.roles.joinToString("\n") { role -> "${role.name} :: ${role.id}" })
}
}
command("setallPermissions") {
expect(ArgumentType.PermissionLevel)
execute {
val level = it.args.component1() as PermissionLevel
if (it.config.serverInformation.ownerID != it.author.id) {
it.respond("Sorry, this command can only be run by the owner marked in the configuration file.")
return@execute
}
it.container.listCommands().forEach { command -> it.manager.setPermission(command, level) }
}
}
command("setPermissions") {
expect(ArgumentType.Category, ArgumentType.PermissionLevel)
execute {
val category = it.args.component1() as String
val level = it.args.component2() as PermissionLevel
val commands = HelpConf.listCommandsinCategory(category).map { it.name }
if (commands.isEmpty()) {
it.respond("Either this category ($category) contains 0 commands, or it is not a real category :thinking:")
return@execute
}
commands.forEach { command -> it.manager.setPermission(command, level) }
it.safeRespond("${level.name} now has access to: ${commands.joinToString(prefix = "`", postfix = "`")}")
}
}
command("viewpermissions") {
execute {
it.respond(embed {
title("Command Permissions")
description("Below you can see all of the different command categories, along with all of their " +
"respective commands and the associated permission required to use those commands.")
HelpConf.listCategories()
.map { cat ->
val commandsInCategory = HelpConf.listCommandsinCategory(cat)
val text = commandsInCategory.joinToString("\n") { cmd -> "${cmd.name} -- ${it.manager.roleRequired(cmd.name)}" }
Pair(cat, text)
}
.forEach {
field {
name = it.first
value = it.second.sanitiseMentions()
inline = false
}
}
})
}
}
command("listavailable") {
execute {
val available = HelpConf.listCategories().map { cat ->
val cmds = HelpConf.listCommandsinCategory(cat)
.filter { cmd -> it.manager.canUseCommand(it.author, cmd.name) }
.map(CommandDescriptor::name)
.joinToString()
Pair(cat, cmds)
}.filter { it.second.isNotEmpty() }
it.respond(embed {
title("Commands available to you")
setColor(Color.green)
setThumbnail(it.author.effectiveAvatarUrl)
available.forEach {
field {
name = it.first
value = it.second
inline = false
}
}
})
}
}
command("setRoleLevel") {
expect(ArgumentType.Role, ArgumentType.PermissionLevel)
execute {
val role = it.args.component1() as Role
val level = it.args.component2() as PermissionLevel
it.manager.assignRoleLevel(role, level)
it.respond("${role.name} is now assigned the permission level ${level.name}")
}
}
command("viewRoleAssignments") {
execute {
it.respond(embed {
title("Role Assignments")
description("Below you can see what roles have been assigned what permission levels")
val assignments = it.manager.roleAssignemts()
val assignmentsText = if(assignments.isEmpty()) {
"None"
} else {
assignments.joinToString("\n") { pair ->
val roleName = it.guild.getRoleById(pair.key).name
"$roleName :: PermissionLevel.${pair.value}"
}
}
field {
this.name = "Assignments"
this.value = assignmentsText
inline = false
}
})
}
}
} | mit | d31fd3f9e9f875ff84bba53988e6c4a8 | 37.751479 | 141 | 0.509163 | 5.493289 | false | false | false | false |
GunoH/intellij-community | plugins/full-line/src/org/jetbrains/completion/full/line/settings/ui/panels/LanguageCloudModelPanel.kt | 2 | 1886 | package org.jetbrains.completion.full.line.settings.ui.panels
import com.intellij.lang.Language
import com.intellij.ui.components.JBPasswordField
import com.intellij.ui.layout.*
import org.jetbrains.completion.full.line.models.ModelType
import org.jetbrains.completion.full.line.settings.state.MLServerCompletionSettings
import org.jetbrains.completion.full.line.settings.ui.components.LoadingComponent
import org.jetbrains.completion.full.line.settings.ui.components.languageCheckBox
import org.jetbrains.completion.full.line.settings.ui.components.loadingStatus
import org.jetbrains.completion.full.line.settings.ui.components.pingButton
import org.jetbrains.completion.full.line.settings.ui.fullRow
class LanguageCloudModelPanel(
languages: Collection<Language>,
private val flccEnabled: ComponentPredicate,
authTokenTextField: JBPasswordField? = null,
) : ComplexPanel {
private val rows = languages.map {
LanguageRow(
it,
authTokenTextField,
MLServerCompletionSettings.getInstance().state.langStates.keys.maxByOrNull { it.length },
)
}
override val panel = panel {
rows.forEach {
it.row(this).enableIf(flccEnabled)
}
}.apply {
name = ModelType.Cloud.name
}
private class LanguageRow(val language: Language, val authTokenTextField: JBPasswordField?, biggestLang: String?) : ComplexRow {
private val checkBox = languageCheckBox(language, biggestLang)
private val loadingIcon = LoadingComponent()
override fun row(builder: LayoutBuilder) = builder.fullRow {
component(checkBox)
.withSelectedBinding(MLServerCompletionSettings.getInstance().getLangState(language)::enabled.toBinding())
component(pingButton(language, loadingIcon, authTokenTextField))
.enableIf(checkBox.selected)
loadingStatus(loadingIcon)
.forEach { it.enableIf(checkBox.selected) }
}
}
}
| apache-2.0 | 7226e3b92931554d661266b3f5de112f | 37.489796 | 130 | 0.774125 | 4.345622 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/TypeParameters.kt | 2 | 2363 | // 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.j2k.ast
import com.intellij.psi.PsiTypeParameter
import com.intellij.psi.PsiTypeParameterList
import org.jetbrains.kotlin.j2k.CodeBuilder
import org.jetbrains.kotlin.j2k.Converter
import org.jetbrains.kotlin.j2k.append
import org.jetbrains.kotlin.j2k.buildList
class TypeParameter(val name: Identifier, private val extendsTypes: List<Type>) : Element() {
fun hasWhere(): Boolean = extendsTypes.size > 1
fun whereToKotlin(builder: CodeBuilder) {
if (hasWhere()) {
builder append name append " : " append extendsTypes[1]
}
}
override fun generateCode(builder: CodeBuilder) {
builder append name
if (extendsTypes.isNotEmpty()) {
builder append " : " append extendsTypes[0]
}
}
}
class TypeParameterList(val parameters: List<TypeParameter>) : Element() {
override fun generateCode(builder: CodeBuilder) {
if (parameters.isNotEmpty()) builder.append(parameters, ", ", "<", ">")
}
fun appendWhere(builder: CodeBuilder): CodeBuilder {
if (hasWhere()) {
builder.buildList(generators = parameters.map { { it.whereToKotlin(builder) } },
separator = ", ",
prefix = " where ",
suffix = "")
}
return builder
}
override val isEmpty: Boolean
get() = parameters.isEmpty()
private fun hasWhere(): Boolean = parameters.any { it.hasWhere() }
companion object {
val Empty = TypeParameterList(listOf())
}
}
private fun Converter.convertTypeParameter(typeParameter: PsiTypeParameter): TypeParameter {
return TypeParameter(typeParameter.declarationIdentifier(),
typeParameter.extendsListTypes.map { typeConverter.convertType(it) }).assignPrototype(typeParameter)
}
fun Converter.convertTypeParameterList(typeParameterList: PsiTypeParameterList?): TypeParameterList {
return if (typeParameterList != null)
TypeParameterList(typeParameterList.typeParameters.toList().map { convertTypeParameter(it) }).assignPrototype(typeParameterList)
else
TypeParameterList.Empty
}
| apache-2.0 | 7aadac5312fa619407452726dbab9f43 | 35.921875 | 158 | 0.674143 | 4.922917 | false | false | false | false |
GunoH/intellij-community | jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/junit/JUnit5AssertionsConverterInspection.kt | 2 | 7333 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInspection.test.junit
import com.intellij.analysis.JvmAnalysisBundle
import com.intellij.codeInsight.TestFrameworks
import com.intellij.codeInspection.*
import com.intellij.codeInspection.test.junit.HamcrestCommonClassNames.ORG_HAMCREST_MATCHER_ASSERT
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdkVersion
import com.intellij.openapi.projectRoots.JavaVersionService
import com.intellij.psi.*
import com.intellij.uast.UastHintedVisitorAdapter
import com.siyeh.ig.junit.JUnitCommonClassNames.ORG_JUNIT_JUPITER_API_ASSERTIONS
import com.siyeh.ig.junit.JUnitCommonClassNames.ORG_JUNIT_JUPITER_API_ASSUMPTIONS
import com.siyeh.ig.testFrameworks.AbstractAssertHint
import com.siyeh.ig.testFrameworks.UAssertHint
import org.jetbrains.annotations.NonNls
import org.jetbrains.uast.*
import org.jetbrains.uast.generate.getUastElementFactory
import org.jetbrains.uast.generate.replace
import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor
class JUnit5AssertionsConverterInspection(val frameworkName: @NonNls String = "JUnit5") : AbstractBaseUastLocalInspectionTool() {
private fun shouldInspect(file: PsiFile): Boolean =
JavaVersionService.getInstance().isAtLeast(file, JavaSdkVersion.JDK_1_8)
&& isJUnit4InScope(file) && isJUnit5InScope(file)
&& (file as? PsiClassOwner)?.classes?.all { TestFrameworks.detectFramework(it)?.name != frameworkName } == false
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
if (!shouldInspect(holder.file)) return PsiElementVisitor.EMPTY_VISITOR
return UastHintedVisitorAdapter.create(
holder.file.language,
JUnit5AssertionsConverterVisitor(holder),
arrayOf(UCallExpression::class.java, UCallableReferenceExpression::class.java),
true
)
}
private fun getNewAssertClassName(methodName: @NonNls String): String = when {
methodName == "assertThat" -> ORG_HAMCREST_MATCHER_ASSERT
methodName.startsWith("assume") -> ORG_JUNIT_JUPITER_API_ASSUMPTIONS
else -> ORG_JUNIT_JUPITER_API_ASSERTIONS
}
inner class JUnit5AssertionsConverterVisitor(private val holder: ProblemsHolder) : AbstractUastNonRecursiveVisitor() {
override fun visitCallExpression(node: UCallExpression): Boolean {
if (node.methodIdentifier == null) return true
doCheck(node, { node.methodIdentifier?.sourcePsi }) {
UAssertHint.create(node) { AbstractAssertHint.ASSERT_METHOD_2_PARAMETER_COUNT[it] }
}
return true
}
override fun visitCallableReferenceExpression(node: UCallableReferenceExpression): Boolean {
doCheck(node, { node.sourcePsi }) {
UAssertHint.create(node) { AbstractAssertHint.ASSERT_METHOD_2_PARAMETER_COUNT[it] }
}
return true
}
private fun doCheck(node: UExpression, toHighlight: () -> PsiElement?, createHint: () -> AbstractAssertHint<UExpression>?) {
val sourcePsi = node.sourcePsi ?: return
val hint = createHint() ?: return
val psiMethod = hint.method
if (!psiMethod.hasModifierProperty(PsiModifier.STATIC)) return
if (!hint.isMessageOnFirstPosition) return
val file = sourcePsi.containingFile as PsiClassOwner
for (psiClass in file.classes) {
val testFramework = TestFrameworks.detectFramework(psiClass) ?: continue
if (frameworkName == testFramework.name) {
val highlight = toHighlight() ?: return
registerError(psiMethod, highlight)
break
}
}
}
private fun registerError(psiMethod: PsiMethod, toHighlight: PsiElement) {
val containingClass = psiMethod.containingClass ?: return
val methodName = psiMethod.name
val assertClassName = getNewAssertClassName(methodName)
val message = JvmAnalysisBundle.message("jvm.inspections.junit5.assertions.converter.problem.descriptor", containingClass.name, assertClassName)
if (!absentInJUnit5(psiMethod, methodName)) holder.registerProblem(
toHighlight, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, ReplaceObsoleteAssertsFix(getNewAssertClassName(methodName))
)
else holder.registerProblem(toHighlight, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
}
private fun absentInJUnit5(psiMethod: PsiMethod, methodName: @NonNls String): Boolean {
if ("assertNotEquals" == methodName) {
val parameters = psiMethod.parameterList.parameters
if (parameters.isNotEmpty()) {
val lastParamIdx = if (parameters.first().type.equalsToText(CommonClassNames.JAVA_LANG_STRING)) 3 else 2
if (parameters.size > lastParamIdx && parameters[lastParamIdx].type is PsiPrimitiveType) return true
}
}
return false
}
}
inner class ReplaceObsoleteAssertsFix(private val baseClassName: String) : LocalQuickFix {
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement
when (val uElement = element.toUElement()) {
is UCallableReferenceExpression -> {
val methodName = uElement.callableName
val newClassName = JavaPsiFacade.getInstance(project).findClass(
getNewAssertClassName(methodName), element.resolveScope
)?.qualifiedName ?: return
val psiFactory = uElement.getUastElementFactory(project) ?: return
val newQualifier = psiFactory.createQualifiedReference(newClassName, element) ?: return
val newCallableReferences = psiFactory.createCallableReferenceExpression(newQualifier, methodName, null) ?: return
uElement.replace(newCallableReferences) ?: return
}
is UIdentifier -> { // UCallExpression
val methodCall = uElement.getParentOfType<UCallExpression>() ?: return
val methodName = methodCall.methodName ?: return
val assertHint = UAssertHint.create(methodCall) {
AbstractAssertHint.ASSERT_METHOD_2_PARAMETER_COUNT[it]
} ?: return
val arguments = methodCall.valueArguments.toMutableList()
if ("assertThat" != methodName) {
assertHint.message?.let {
arguments.remove(it)
arguments.add(it)
}
}
val psiFactory = methodCall.getUastElementFactory(project) ?: return
val clazz = JavaPsiFacade.getInstance(project).findClass(
getNewAssertClassName(methodName), element.resolveScope
) ?: return
val newClassName = clazz.qualifiedName ?: return
val newReceiver = psiFactory.createQualifiedReference(newClassName, methodCall.sourcePsi)
val newCall = psiFactory.createCallExpression(
newReceiver, methodName, arguments, null, methodCall.kind, null
) ?: return
val qualifiedCall = methodCall.getQualifiedParentOrThis()
qualifiedCall.replace(newCall)
}
}
}
override fun getName(): String = JvmAnalysisBundle.message("jvm.inspections.junit5.assertions.converter.quickfix", baseClassName)
override fun getFamilyName(): String = JvmAnalysisBundle.message("jvm.inspections.junit5.assertions.converter.familyName")
}
} | apache-2.0 | 0b4b160475cc513f75e40c9c3e0fab09 | 48.891156 | 150 | 0.729851 | 5.064227 | false | true | false | false |
walleth/kethereum | rlp/src/main/kotlin/org/kethereum/functions/rlp/RLPTypeConverter.kt | 1 | 1114 | package org.kethereum.functions.rlp
import org.kethereum.extensions.removeLeadingZero
import org.kethereum.extensions.toMinimalByteArray
import java.math.BigInteger
import java.math.BigInteger.ZERO
/**
RLP as of Appendix B. Recursive Length Prefix at https://github.com/ethereum/yellowpaper
*/
// to RLP
fun String.toRLP() = RLPElement(toByteArray())
fun Int.toRLP() = RLPElement(toMinimalByteArray())
fun BigInteger.toRLP() = RLPElement(toByteArray().removeLeadingZero())
fun ByteArray.toRLP() = RLPElement(this)
fun Byte.toRLP() = RLPElement(kotlin.ByteArray(1) { this })
// from RLP
fun RLPElement.toIntFromRLP() = if (bytes.isEmpty()) {
0
} else {
bytes.mapIndexed { index, byte -> (byte.toInt() and 0xff).shl((bytes.size - 1 - index) * 8) }
.reduce { acc, i -> acc + i }
}
fun RLPElement.toUnsignedBigIntegerFromRLP(): BigInteger = if (bytes.isEmpty()) ZERO else BigInteger(1, bytes)
fun RLPElement.toByteFromRLP(): Byte {
require(bytes.size == 1) { "trying to convert RLP with != 1 byte to Byte" }
return bytes.first()
}
fun RLPElement.toStringFromRLP() = String(bytes)
| mit | ac08c94c78feb5b948d48193984ef99c | 29.944444 | 110 | 0.719031 | 3.688742 | false | false | false | false |
brianwernick/PlaylistCore | library/src/main/kotlin/com/devbrackets/android/playlistcore/components/mediasession/DefaultMediaSessionProvider.kt | 1 | 5065 | package com.devbrackets.android.playlistcore.components.mediasession
import android.app.PendingIntent
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaSessionCompat
import android.util.Log
import com.devbrackets.android.playlistcore.data.MediaInfo
import com.devbrackets.android.playlistcore.data.RemoteActions
open class DefaultMediaSessionProvider(
val context: Context,
val serviceClass: Class<out Service>
) : MediaSessionCompat.Callback(), MediaSessionProvider {
companion object {
const val SESSION_TAG = "DefaultMediaSessionProvider.Session"
const val RECEIVER_EXTRA_CLASS = "com.devbrackets.android.playlistcore.RECEIVER_EXTRA_CLASS"
}
@Deprecated("These class level intents are no-longer used. If you need to override these values use the onPlay()/onPause()")
protected var playPausePendingIntent = createPendingIntent(RemoteActions.ACTION_PLAY_PAUSE, serviceClass)
@Deprecated("These class level intents are no-longer used. If you need to override these values use the onSkipToNext()")
protected var nextPendingIntent = createPendingIntent(RemoteActions.ACTION_NEXT, serviceClass)
@Deprecated("These class level intents are no-longer used. If you need to override these values use the onSkipToPrevious()")
protected var previousPendingIntent = createPendingIntent(RemoteActions.ACTION_PREVIOUS, serviceClass)
protected val mediaSession: MediaSessionCompat by lazy {
val componentName = ComponentName(context, DefaultMediaSessionControlsReceiver::class.java.name)
MediaSessionCompat(context, SESSION_TAG, componentName, getMediaButtonReceiverPendingIntent(componentName))
}
override fun get(): MediaSessionCompat {
return mediaSession
}
override fun update(mediaInfo: MediaInfo) {
mediaSession.setCallback(this)
// Updates the current media MetaData
val builder = MediaMetadataCompat.Builder()
builder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, mediaInfo.title)
builder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, mediaInfo.album)
builder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, mediaInfo.artist)
builder.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, mediaInfo.playbackDurationMs)
// Updates the icon
BitmapFactory.decodeResource(context.resources, mediaInfo.appIcon)?.let {
builder.putBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON, it)
}
// Updates the artwork
if (mediaInfo.artwork != null) {
builder.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, mediaInfo.artwork)
}
mediaSession.setMetadata(builder.build())
}
override fun onPlay() {
val intent = createPendingIntent(RemoteActions.ACTION_PLAY_PAUSE, serviceClass)
sendPendingIntent(intent)
}
override fun onPause() {
val intent = createPendingIntent(RemoteActions.ACTION_PLAY_PAUSE, serviceClass)
sendPendingIntent(intent)
}
override fun onSkipToNext() {
val intent = createPendingIntent(RemoteActions.ACTION_NEXT, serviceClass)
sendPendingIntent(intent)
}
override fun onSkipToPrevious() {
val intent = createPendingIntent(RemoteActions.ACTION_PREVIOUS, serviceClass)
sendPendingIntent(intent) }
override fun onSeekTo(pos: Long) {
val intent = Intent(context, serviceClass)
intent.action = RemoteActions.ACTION_SEEK_ENDED
intent.putExtra(RemoteActions.ACTION_EXTRA_SEEK_POSITION, pos)
val pi = PendingIntent.getService(context, 0, intent, getIntentFlags())
sendPendingIntent(pi)
}
/**
* Creates a PendingIntent for the given action to the specified service
*
* @param action The action to use
* @param serviceClass The service class to notify of intents
* @return The resulting PendingIntent
*/
protected open fun createPendingIntent(action: String, serviceClass: Class<out Service>): PendingIntent {
val intent = Intent(context, serviceClass)
intent.action = action
return PendingIntent.getService(context, 0, intent, getIntentFlags())
}
protected open fun getMediaButtonReceiverPendingIntent(componentName: ComponentName): PendingIntent {
val mediaButtonIntent = Intent(Intent.ACTION_MEDIA_BUTTON)
mediaButtonIntent.component = componentName
mediaButtonIntent.putExtra(RECEIVER_EXTRA_CLASS, serviceClass.name)
return PendingIntent.getBroadcast(context, 0, mediaButtonIntent, getIntentFlags())
}
protected open fun sendPendingIntent(pi: PendingIntent) {
try {
pi.send()
} catch (e: Exception) {
Log.d("DefaultMediaSessionPro", "Error sending media controls pending intent", e)
}
}
protected open fun getIntentFlags(): Int {
return when {
Build.VERSION.SDK_INT < Build.VERSION_CODES.M -> PendingIntent.FLAG_UPDATE_CURRENT
else -> PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
}
}
} | apache-2.0 | 9384e7f27c4bf8118a85230a6d9f2ac8 | 38.578125 | 126 | 0.773346 | 4.865514 | false | false | false | false |
ktorio/ktor | ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/TLSClientSessionJvm.kt | 1 | 2858 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.network.tls
import io.ktor.network.sockets.*
import io.ktor.network.util.*
import io.ktor.utils.io.*
import io.ktor.utils.io.core.*
import io.ktor.utils.io.pool.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import java.nio.*
import kotlin.coroutines.*
internal actual suspend fun openTLSSession(
socket: Socket,
input: ByteReadChannel,
output: ByteWriteChannel,
config: TLSConfig,
context: CoroutineContext
): Socket {
val handshake = TLSClientHandshake(input, output, config, context)
try {
handshake.negotiate()
} catch (cause: ClosedSendChannelException) {
throw TLSException("Negotiation failed due to EOS", cause)
}
return TLSSocket(handshake.input, handshake.output, socket, context)
}
private class TLSSocket(
private val input: ReceiveChannel<TLSRecord>,
private val output: SendChannel<TLSRecord>,
private val socket: Socket,
override val coroutineContext: CoroutineContext
) : CoroutineScope, Socket by socket {
override fun attachForReading(channel: ByteChannel): WriterJob =
writer(coroutineContext + CoroutineName("cio-tls-input-loop"), channel) {
appDataInputLoop(this.channel)
}
override fun attachForWriting(channel: ByteChannel): ReaderJob =
reader(coroutineContext + CoroutineName("cio-tls-output-loop"), channel) {
appDataOutputLoop(this.channel)
}
@OptIn(ExperimentalCoroutinesApi::class)
private suspend fun appDataInputLoop(pipe: ByteWriteChannel) {
try {
input.consumeEach { record ->
val packet = record.packet
val length = packet.remaining
when (record.type) {
TLSRecordType.ApplicationData -> {
pipe.writePacket(record.packet)
pipe.flush()
}
else -> throw TLSException("Unexpected record ${record.type} ($length bytes)")
}
}
} catch (cause: Throwable) {
} finally {
pipe.close()
}
}
private suspend fun appDataOutputLoop(
pipe: ByteReadChannel
): Unit = DefaultByteBufferPool.useInstance { buffer: ByteBuffer ->
try {
while (true) {
buffer.clear()
val rc = pipe.readAvailable(buffer)
if (rc == -1) break
buffer.flip()
output.send(TLSRecord(TLSRecordType.ApplicationData, packet = buildPacket { writeFully(buffer) }))
}
} finally {
output.close()
}
}
override fun dispose() {
socket.dispose()
}
}
| apache-2.0 | ab4503d1115bf747e9aa3b54e9783e6d | 30.755556 | 118 | 0.619314 | 4.763333 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/mixin/insight/OverwriteLineMarkerProvider.kt | 1 | 2907 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.insight
import com.demonwav.mcdev.platform.mixin.util.findFirstOverwriteTarget
import com.demonwav.mcdev.platform.mixin.util.findOverwriteTargets
import com.intellij.codeHighlighting.Pass
import com.intellij.codeInsight.daemon.GutterIconNavigationHandler
import com.intellij.codeInsight.daemon.LineMarkerInfo
import com.intellij.codeInsight.daemon.LineMarkerProviderDescriptor
import com.intellij.codeInsight.daemon.MergeableLineMarkerInfo
import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator
import com.intellij.icons.AllIcons
import com.intellij.ide.util.MethodCellRenderer
import com.intellij.openapi.editor.markup.GutterIconRenderer
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiIdentifier
import com.intellij.psi.PsiMethod
import com.intellij.util.FunctionUtil
import java.awt.event.MouseEvent
class OverwriteLineMarkerProvider : LineMarkerProviderDescriptor(), GutterIconNavigationHandler<PsiIdentifier> {
companion object {
private val ICON = AllIcons.Gutter.OverridingMethod!!
private val TOOLTIP_FUNCTION = FunctionUtil.constant<Any, String>("Go to target method")
}
override fun getName() = "Mixin @Overwrite line marker"
override fun getIcon() = ICON
override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<PsiIdentifier>? {
if (element !is PsiMethod) {
return null
}
val identifier = element.nameIdentifier ?: return null
// Check if @Overwrite actually has a target
element.findFirstOverwriteTarget() ?: return null
return LineMarker(identifier, this)
}
override fun collectSlowLineMarkers(elements: List<PsiElement>, result: Collection<LineMarkerInfo<PsiElement>>) {
}
override fun navigate(e: MouseEvent, elt: PsiIdentifier) {
val method = elt.parent as? PsiMethod ?: return
val targets = method.findOverwriteTargets() ?: return
if (targets.isNotEmpty()) {
PsiElementListNavigator.openTargets(e, targets.toTypedArray(),
"Choose target method of ${method.name}", null, MethodCellRenderer(false))
}
}
private class LineMarker(identifier: PsiIdentifier, navHandler: GutterIconNavigationHandler<PsiIdentifier>)
: MergeableLineMarkerInfo<PsiIdentifier>(identifier, identifier.textRange, ICON,
Pass.LINE_MARKERS, TOOLTIP_FUNCTION, navHandler, GutterIconRenderer.Alignment.LEFT) {
override fun canMergeWith(info: MergeableLineMarkerInfo<*>) = info is LineMarker
override fun getCommonTooltip(infos: List<MergeableLineMarkerInfo<PsiElement>>) = TOOLTIP_FUNCTION
override fun getCommonIcon(infos: List<MergeableLineMarkerInfo<PsiElement>>) = ICON
}
}
| mit | 1f3612d49225a8bd86a95ad0d03c8776 | 39.375 | 117 | 0.755418 | 4.969231 | false | false | false | false |
Talentica/AndroidWithKotlin | networking/src/main/java/com/talentica/androidkotlin/networking/repoui/UserRepositories.kt | 1 | 2417 | package com.talentica.androidkotlin.networking.repoui
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.talentica.androidkotlin.networking.R
import com.talentica.androidkotlin.networking.dto.Repository
class UserRepositories : AppCompatActivity(), RepositoryContract.View {
val progressBar: ProgressBar by lazy {
findViewById<ProgressBar>(R.id.progress_bar)
}
val repoList: RecyclerView by lazy {
findViewById<RecyclerView>(R.id.rv_repo_list)
}
val mPresenter: RepositoryContract.Presenter by lazy {
RepoPresenter(this, this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_user_repositories)
repoList.layoutManager = LinearLayoutManager(this)
if (!intent.hasExtra("username")) {
finish()
}
val username = intent.getStringExtra("username")
val libType = intent.getStringExtra("libraryType")
if (libType != null && username != null) {
mPresenter.start(libType, username)
}
}
override fun onDestroy() {
super.onDestroy()
mPresenter.destroy()
}
override fun onReposAvailable(repos: Array<Repository>) {
val handler = Handler(Looper.getMainLooper())
handler.post({
val repoAdapter = RepoAdapter(repos)
repoList.adapter = repoAdapter
})
}
override fun showLoading() {
val handler = Handler(Looper.getMainLooper())
handler.post({
progressBar.visibility = View.VISIBLE
repoList.alpha = 0.4f
})
}
override fun hideLoading() {
val handler = Handler(Looper.getMainLooper())
handler.post({
progressBar.visibility = View.GONE
repoList.alpha = 1.0f
})
}
override fun displayError(message: String) {
val handler = Handler(Looper.getMainLooper())
handler.post({
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
})
}
override fun destroy() {
finish()
}
}
| apache-2.0 | d8cd4b876738c609754d8a13042ce2f1 | 27.77381 | 71 | 0.659082 | 4.834 | false | false | false | false |
McMoonLakeDev/MoonLake | API/src/main/kotlin/com/mcmoonlake/api/packet/PacketInPosition.kt | 1 | 1457 | /*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.api.packet
data class PacketInPosition(
var x: Double,
var y: Double,
var z: Double,
var isOnGround: Boolean
) : PacketInBukkitAbstract("PacketPlayInFlying\$PacketPlayInPosition", "PacketPlayInPosition") {
@Deprecated("")
constructor() : this(.0, .0, .0, false)
override fun read(data: PacketBuffer) {
this.x = data.readDouble()
this.y = data.readDouble()
this.z = data.readDouble()
this.isOnGround = data.readUnsignedByte().toInt() != 0
}
override fun write(data: PacketBuffer) {
data.writeDouble(x)
data.writeDouble(y)
data.writeDouble(z)
data.writeByte(if(isOnGround) 1 else 0)
}
}
| gpl-3.0 | 2c08dcd28a0d2235432f624f31702d56 | 32.883721 | 96 | 0.682224 | 4.115819 | false | false | false | false |
mcdimus/mate-wp | src/test/kotlin/ee/mcdimus/matewp/service/OpSysServiceFactorySpec.kt | 1 | 2116 | package ee.mcdimus.matewp.service
import junit.framework.Assert.assertEquals
import junit.framework.Assert.assertTrue
import org.junit.jupiter.api.assertThrows
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.gherkin.Feature
/**
* @author Dmitri Maksimov
*/
object OpSysServiceFactorySpec : Spek({
Feature("OpSysServiceFactory") {
val subject by memoized { OpSysServiceFactory }
Scenario("running on Linux") {
Given("os.name == Linux") {
System.setProperty("os.name", "Linux")
}
Then("should return instance of LinuxMateService") {
assertTrue(subject.get() is LinuxMateService)
}
}
Scenario("guessing that running on any Linux") {
Given("os.name == Linux") {
System.setProperty("os.name", "SomeLinuxDistro")
}
Then("should return instance of LinuxMateService") {
assertTrue(subject.get() is LinuxMateService)
}
}
Scenario("running on Windows 7") {
Given("os.name == Windows 7") {
System.setProperty("os.name", "Windows 7")
}
Then("should return instance of LinuxMateService") {
assertTrue(subject.get() is WindowsService)
}
}
Scenario("guessing that running on any Linux") {
Given("os.name == Linux") {
System.setProperty("os.name", "AnyOtherWindows")
}
Then("should return instance of WindowsService") {
assertTrue(subject.get() is WindowsService)
}
}
Scenario("running on unsupported OS") {
Given("os.name == FreeBSD") {
System.setProperty("os.name", "FreeBSD")
}
Then("should throw IllegalStateException") {
assertThrows<IllegalStateException> { subject.get() }.also {
assertEquals("unsupported operating system: FreeBSD", it.message)
}
}
}
}
})
| mit | 4f94eb8007caa128cca28ca053c50a49 | 31.553846 | 85 | 0.560491 | 4.92093 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/utils/ScoreUtils.kt | 1 | 3559 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.utils
import androidx.core.util.Pair
import de.dreier.mytargets.base.db.dao.EndDAO
import de.dreier.mytargets.base.db.dao.RoundDAO
import de.dreier.mytargets.shared.models.SelectableZone
import de.dreier.mytargets.shared.models.Target
import de.dreier.mytargets.shared.models.db.Round
import de.dreier.mytargets.shared.models.db.Shot
import de.dreier.mytargets.shared.targets.scoringstyle.ArrowAwareScoringStyle
import java.util.*
object ScoreUtils {
fun getTopScoreDistribution(sortedScore: List<Map.Entry<SelectableZone, Int>>): List<Pair<String, Int>> {
val result = sortedScore.map { Pair(it.key.text, it.value) }.toMutableList()
// Collapse first two entries if they yield the same score points,
// e.g. 10 and X => {X, 10+X, 9, ...}
if (sortedScore.size > 1) {
val first = sortedScore[0]
val second = sortedScore[1]
if (first.key.points == second.key.points) {
val newTitle = second.key.text + "+" + first.key.text
result[1] = Pair(newTitle, second.value + first.value)
}
}
return result
}
/**
* Compound 9ers are already collapsed to one SelectableZone.
*/
fun getSortedScoreDistribution(
roundDAO: RoundDAO,
endDAO: EndDAO,
rounds: List<Round>
): List<Map.Entry<SelectableZone, Int>> {
return getRoundScores(roundDAO, endDAO, rounds).entries.sortedBy { it.key }
}
private fun getRoundScores(
roundDAO: RoundDAO,
endDAO: EndDAO,
rounds: List<Round>
): Map<SelectableZone, Int> {
val t = rounds[0].target
val scoreCount = getAllPossibleZones(t)
rounds.flatMap { roundDAO.loadEnds(it.id) }
.forEach {
endDAO.loadShots(it.id).forEach { s ->
if (s.scoringRing != Shot.NOTHING_SELECTED) {
val tuple = SelectableZone(
s.scoringRing,
t.model.getZone(s.scoringRing),
t.zoneToString(s.scoringRing, s.index),
t.getScoreByZone(s.scoringRing, s.index)
)
val integer = scoreCount[tuple]
if (integer != null) {
val count = integer + 1
scoreCount[tuple] = count
}
}
}
}
return scoreCount
}
private fun getAllPossibleZones(t: Target): MutableMap<SelectableZone, Int> {
val scoreCount = HashMap<SelectableZone, Int>()
for (arrow in 0..2) {
val zoneList = t.getSelectableZoneList(arrow)
for (selectableZone in zoneList) {
scoreCount[selectableZone] = 0
}
if (t.getScoringStyle() !is ArrowAwareScoringStyle) {
break
}
}
return scoreCount
}
}
| gpl-2.0 | aa06e1bbb6b30abe6cb09cb5103933aa | 35.316327 | 109 | 0.589491 | 4.399258 | false | false | false | false |
DreierF/MyTargets | shared/src/main/java/de/dreier/mytargets/shared/targets/decoration/BeursaultDecorator.kt | 1 | 8232 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.shared.targets.decoration
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.text.TextPaint
import de.dreier.mytargets.shared.targets.drawable.CanvasWrapper
import de.dreier.mytargets.shared.targets.models.Beursault
import de.dreier.mytargets.shared.utils.Color
import de.dreier.mytargets.shared.utils.Color.DARK_GRAY
class BeursaultDecorator(private val model: Beursault) : CenterMarkDecorator(DARK_GRAY, 500f, 6, false) {
private val paintFill: Paint by lazy {
val paintFill = Paint()
paintFill.isAntiAlias = true
paintFill.color = Color.WHITE
paintFill
}
private val paintText: TextPaint by lazy {
val paintText = TextPaint()
paintText.isAntiAlias = true
paintText.color = Color.BLACK
paintText
}
override fun drawDecoration(canvas: CanvasWrapper) {
super.drawDecoration(canvas)
drawPathsForZone(canvas, 6, 6, 2.4f, one, oneBounds)
drawPathsForZone(canvas, 4, 4, 2.4f, two, twoBounds)
drawPathsForZone(canvas, 2, 3, 1.05f, three, threeBounds)
}
private fun drawPathsForZone(canvas: CanvasWrapper, innerZoneIndex: Int, outerZoneIndex: Int, scale: Float, path: Path, pathBounds: RectF) {
val outerZone = model.getZone(outerZoneIndex)
val innerZone = model.getZone(innerZoneIndex)
val outerRadius = outerZone.radius - outerZone.strokeWidth * 0.5f
val innerRadius = innerZone.radius + innerZone.strokeWidth * 0.5f
val rel = (outerRadius + innerRadius) * 0.5f
drawFilledPath(canvas, 0f, -rel, scale, path, pathBounds) // top
drawFilledPath(canvas, -rel, 0f, scale, path, pathBounds) // left
drawFilledPath(canvas, 0f, rel, scale, path, pathBounds) // bottom
drawFilledPath(canvas, rel, 0f, scale, path, pathBounds) // right
}
private fun drawFilledPath(canvas: CanvasWrapper, x: Float, y: Float, scaleFactor: Float, path: Path, bounds: RectF) {
var rectSize = 0.012f * 2f * scaleFactor
val bgRect = RectF(x - rectSize, y - rectSize, x + rectSize, y + rectSize)
canvas.drawRect(bgRect, paintFill)
rectSize = 0.007f * 2f * scaleFactor
val numberRect = RectF(x - rectSize, y - rectSize, x + rectSize, y + rectSize)
val scaleMatrix = Matrix()
scaleMatrix.setRectToRect(bounds, numberRect, Matrix.ScaleToFit.CENTER)
val tmp = Path(path)
tmp.transform(scaleMatrix)
canvas.drawPath(tmp, paintText)
}
companion object {
private val one = Path()
private val two = Path()
private val three = Path()
private val oneBounds: RectF
private val twoBounds: RectF
private val threeBounds: RectF
init {
one.moveTo(-9.3f, 30.7f)
one.lineTo(-11.9f, 30.7f)
one.lineTo(-11.9f, 20.900002f)
one.cubicTo(-12.9f, 21.800001f, -14.0f, 22.400002f, -15.299999f, 22.900002f)
one.lineTo(-15.299999f, 20.500002f)
one.cubicTo(-14.599999f, 20.300001f, -13.9f, 19.900002f, -13.099999f, 19.200003f)
one.cubicTo(-12.299999f, 18.600002f, -11.799999f, 17.900003f, -11.499999f, 17.000002f)
one.lineTo(-9.4f, 17.000002f)
one.lineTo(-9.3f, 30.7f)
one.lineTo(-9.3f, 30.7f)
one.close()
oneBounds = RectF()
one.computeBounds(oneBounds, true)
}
init {
two.moveTo(-5.2f, 28.4f)
two.lineTo(-5.2f, 30.8f)
two.lineTo(-14.3f, 30.8f)
two.cubicTo(-14.2f, 29.9f, -13.900001f, 29.0f, -13.400001f, 28.199999f)
two.cubicTo(-12.900001f, 27.4f, -11.900001f, 26.3f, -10.5f, 24.9f)
two.cubicTo(-9.3f, 23.8f, -8.6f, 23.1f, -8.3f, 22.699999f)
two.cubicTo(-7.9f, 22.199999f, -7.8f, 21.599998f, -7.8f, 21.099998f)
two.cubicTo(-7.8f, 20.499998f, -8.0f, 20.099998f, -8.3f, 19.8f)
two.cubicTo(-8.6f, 19.5f, -9.0f, 19.3f, -9.6f, 19.3f)
two.cubicTo(-10.1f, 19.3f, -10.6f, 19.5f, -10.900001f, 19.8f)
two.cubicTo(-11.200001f, 20.099998f, -11.400001f, 20.699999f, -11.500001f, 21.4f)
two.lineTo(-14.000001f, 21.199999f)
two.cubicTo(-13.800001f, 19.8f, -13.400001f, 18.699999f, -12.500001f, 18.099998f)
two.cubicTo(-11.700001f, 17.499998f, -10.700001f, 17.199999f, -9.400002f, 17.199999f)
two.cubicTo(-8.100001f, 17.199999f, -7.0000014f, 17.599998f, -6.2000017f, 18.3f)
two.cubicTo(-5.4f, 19.0f, -5.0f, 19.9f, -5.0f, 21.0f)
two.cubicTo(-5.0f, 21.6f, -5.1f, 22.2f, -5.3f, 22.7f)
two.cubicTo(-5.5f, 23.300001f, -5.9f, 23.800001f, -6.3f, 24.400002f)
two.cubicTo(-6.6000004f, 24.800001f, -7.2000003f, 25.400002f, -8.0f, 26.100002f)
two.cubicTo(-8.8f, 26.900002f, -9.3f, 27.400002f, -9.6f, 27.600002f)
two.cubicTo(-9.8f, 27.800003f, -10.0f, 28.100002f, -10.1f, 28.300003f)
two.lineTo(-5.2f, 28.4f)
two.lineTo(-5.2f, 28.4f)
two.close()
twoBounds = RectF()
two.computeBounds(twoBounds, true)
}
init {
three.moveTo(-14.1f, 26.8f)
three.lineTo(-11.6f, 26.5f)
three.cubicTo(-11.5f, 27.1f, -11.3f, 27.6f, -11.0f, 28.0f)
three.cubicTo(-10.7f, 28.4f, -10.2f, 28.5f, -9.7f, 28.5f)
three.cubicTo(-9.2f, 28.5f, -8.7f, 28.3f, -8.3f, 27.9f)
three.cubicTo(-7.9f, 27.5f, -7.7000003f, 26.9f, -7.7000003f, 26.199999f)
three.cubicTo(-7.7000003f, 25.499998f, -7.9f, 24.999998f, -8.200001f, 24.599998f)
three.cubicTo(-8.6f, 24.2f, -9.0f, 24.0f, -9.5f, 24.0f)
three.cubicTo(-9.8f, 24.0f, -10.2f, 24.1f, -10.7f, 24.2f)
three.lineTo(-10.4f, 22.1f)
three.cubicTo(-9.7f, 22.1f, -9.2f, 22.0f, -8.799999f, 21.6f)
three.cubicTo(-8.4f, 21.300001f, -8.199999f, 20.800001f, -8.199999f, 20.300001f)
three.cubicTo(-8.199999f, 19.800001f, -8.299999f, 19.500002f, -8.599998f, 19.2f)
three.cubicTo(-8.899999f, 18.900002f, -9.199999f, 18.800001f, -9.699999f, 18.800001f)
three.cubicTo(-10.099998f, 18.800001f, -10.499999f, 19.000002f, -10.799999f, 19.300001f)
three.cubicTo(-11.099999f, 19.6f, -11.299999f, 20.1f, -11.4f, 20.7f)
three.lineTo(-13.799999f, 20.300001f)
three.cubicTo(-13.599999f, 19.500002f, -13.4f, 18.800001f, -12.999999f, 18.300001f)
three.cubicTo(-12.699999f, 17.800001f, -12.199999f, 17.400002f, -11.599999f, 17.1f)
three.cubicTo(-10.999999f, 16.800001f, -10.299999f, 16.7f, -9.599999f, 16.7f)
three.cubicTo(-8.299999f, 16.7f, -7.299999f, 17.1f, -6.4999995f, 17.900002f)
three.cubicTo(-5.8999996f, 18.600002f, -5.4999995f, 19.300001f, -5.4999995f, 20.2f)
three.cubicTo(-5.4999995f, 21.400002f, -6.1999993f, 22.300001f, -7.4999995f, 23.1f)
three.cubicTo(-6.6999993f, 23.300001f, -6.0999994f, 23.6f, -5.5999994f, 24.2f)
three.cubicTo(-5.0999994f, 24.800001f, -4.8999996f, 25.5f, -4.8999996f, 26.300001f)
three.cubicTo(-4.8999996f, 27.500002f, -5.2999997f, 28.500002f, -6.2f, 29.400002f)
three.cubicTo(-7.1f, 30.300001f, -8.2f, 30.7f, -9.5f, 30.7f)
three.cubicTo(-10.7f, 30.7f, -11.8f, 30.300001f, -12.6f, 29.6f)
three.cubicTo(-13.5f, 28.9f, -13.9f, 28.0f, -14.1f, 26.8f)
three.close()
threeBounds = RectF()
three.computeBounds(threeBounds, true)
}
}
}
| gpl-2.0 | 785dd151dc8c7685d18d1a53aaf90c5a | 49.503067 | 144 | 0.613095 | 2.848443 | false | false | false | false |
JuliaSoboleva/SmartReceiptsLibrary | app/src/main/java/co/smartreceipts/android/model/utils/ModelUtils.kt | 1 | 6738 | package co.smartreceipts.android.model.utils
import android.content.Context
import android.text.TextUtils
import android.text.format.DateFormat
import co.smartreceipts.android.date.DateUtils
import co.smartreceipts.android.model.Price
import co.smartreceipts.android.model.Price.Companion.moneyFormatter
import org.joda.money.BigMoney
import org.joda.money.CurrencyUnit
import java.math.BigDecimal
import java.math.RoundingMode
import java.sql.Date
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.*
object ModelUtils {
private const val EPSILON = 0.0001f
val decimalFormat: DecimalFormat
get() {
// check for the case when Locale has changed
if (_decimalFormat.decimalFormatSymbols != DecimalFormatSymbols()) {
_decimalFormat = initDecimalFormat()
}
return _decimalFormat
}
val decimalSeparator: Char
get() = decimalFormat.decimalFormatSymbols.decimalSeparator
private var _decimalFormat: DecimalFormat = initDecimalFormat()
private fun initDecimalFormat(): DecimalFormat {
val format = DecimalFormat()
format.isParseBigDecimal = true
format.isGroupingUsed = true
return format
}
@JvmStatic
fun getFormattedDate(date: java.util.Date, timeZone: TimeZone, context: Context, separator: String): String =
getFormattedDate(Date(date.time), timeZone, context, separator)
/**
* Gets a formatted version of a date based on the timezone and locale for a given separator. In the US,
* we might expect to see a result like "10/23/2014" returned if we set the separator as "/"
*
* @param date - the [Date] to format
* @param timeZone - the [TimeZone] to use for this date
* @param context - the current [Context]
* @param separator - the date separator (e.g. "/", "-", ".")
* @return the formatted date string for the start date
*/
fun getFormattedDate(date: Date, timeZone: TimeZone, context: Context, separator: String): String {
val format = DateFormat.getDateFormat(context)
format.timeZone = timeZone // Hack to shift the timezone appropriately
val formattedDate = format.format(date)
return formattedDate.replace(DateUtils.getDateSeparator(context), separator)
}
/**
* Generates "decimal-formatted" value, which would appear to the end user as "25.20" or "25,20" instead of
* showing naively as "25.2" or "25.2001910"
* By default, this assumes a decimal precision of {@link PriceNew#TOTAL_DECIMAL_PRECISION}
*
* @param decimal - the [BigDecimal] to format
* @param precision - the decimal places count
* @return the decimal formatted price [String]
*/
@JvmStatic
@JvmOverloads
fun getDecimalFormattedValue(decimal: BigDecimal, precision: Int = Price.TOTAL_DECIMAL_PRECISION): String {
val money = BigMoney.of(CurrencyUtils.getDefaultCurrency(), decimal)
return moneyFormatter.print(money.withScale(precision, RoundingMode.HALF_EVEN))
}
/**
* The "currency-formatted" value, which would appear as "$25.20" or "$25,20" as determined by the user's locale.
*
* @param decimal - the [BigDecimal] to format
* @param currency - the [CurrencyUnit] to use
* @param precision - the desired decimal precision to use (eg 2 => "$25.20", 3 => "$25.200")
* @return - the currency formatted price [String]
*/
@JvmStatic
fun getCurrencyFormattedValue(decimal: BigDecimal, currency: CurrencyUnit, precision: Int = -1): String {
val money = BigMoney.of(currency, decimal)
val decimalPlaces =
when (precision) {
-1 -> currency.decimalPlaces
else -> precision
}
return money.currencyUnit.symbol + moneyFormatter.print(money.withScale(decimalPlaces, RoundingMode.HALF_EVEN))
}
/**
* The "currency-code-formatted" value, which would appear as "USD 25.20" or "USD 25,20" as determined by the user's locale.
*
* @param decimal - the [BigDecimal] to format
* @param currency - the [CurrencyUnit] to use. If this is {@code null}, return {@link #getDecimalFormattedValue(BigDecimal)}
* @param precision - the desired decimal precision to use (eg 2 => "USD 25.20", 3 => "USD 25.200")
* @return - the currency formatted price [String]
*/
@JvmStatic
fun getCurrencyCodeFormattedValue(decimal: BigDecimal, currency: CurrencyUnit, precision: Int = -1): String {
val money = BigMoney.of(currency, decimal)
val decimalPlaces =
when (precision) {
-1 -> currency.decimalPlaces
else -> precision
}
return currency.code + " " + moneyFormatter.print(money.withScale(decimalPlaces, RoundingMode.HALF_EVEN))
}
/**
* Tries to parse a string to find the underlying numerical value
*
* @param number the string containing a number (hopefully)
* @return the [BigDecimal] value
* @throws NumberFormatException if we cannot parse this number
*/
@JvmStatic
@Throws(NumberFormatException::class)
fun parseOrThrow(number: String?): BigDecimal {
if (number == null || TextUtils.isEmpty(number)) {
throw NumberFormatException("Cannot parse an empty string")
}
// Note: for some locales grouping separator symbol is non-breaking space (code = 160),
// but incoming string may contain general space => need to prepare such string before parsing
val groupingSeparator = decimalFormat.decimalFormatSymbols.groupingSeparator.toString()
val nonBreakingSpace = ("\u00A0").toString()
val parsedNumber =
when (groupingSeparator) {
nonBreakingSpace -> decimalFormat.parse(number.replace(" ", nonBreakingSpace))
else -> decimalFormat.parse(number)
}
return BigDecimal(parsedNumber.toString())
}
/**
* Tries to parse a string to find the underlying numerical value
*
* @param number the string containing a number (hopefully)
* @return the [BigDecimal] value or "0" if it cannot be found
*/
@JvmStatic
@JvmOverloads
fun tryParse(number: String?, defaultValue: BigDecimal = BigDecimal.ZERO): BigDecimal {
return try {
parseOrThrow(number)
} catch (e: NumberFormatException) {
defaultValue
}
}
@JvmStatic
fun isPriceZero(price: Price): Boolean {
return price.priceAsFloat < EPSILON && price.priceAsFloat > -1 * EPSILON
}
} | agpl-3.0 | 661a775f5ab715f38726d962802bdc43 | 37.729885 | 137 | 0.660285 | 4.634113 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/internship/statistics/InternshipStatisticsController.kt | 1 | 44757 | package top.zbeboy.isy.web.internship.statistics
import com.alibaba.fastjson.JSON
import org.apache.commons.lang.StringUtils
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Controller
import org.springframework.ui.ModelMap
import org.springframework.util.ObjectUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import top.zbeboy.isy.config.Workbook
import top.zbeboy.isy.domain.tables.pojos.*
import top.zbeboy.isy.service.cache.CacheManageService
import top.zbeboy.isy.service.common.UploadService
import top.zbeboy.isy.service.export.*
import top.zbeboy.isy.service.internship.*
import top.zbeboy.isy.service.util.DateTimeUtils
import top.zbeboy.isy.service.util.RequestUtils
import top.zbeboy.isy.web.bean.export.ExportBean
import top.zbeboy.isy.web.bean.internship.release.InternshipReleaseBean
import top.zbeboy.isy.web.bean.internship.statistics.InternshipChangeCompanyHistoryBean
import top.zbeboy.isy.web.bean.internship.statistics.InternshipChangeHistoryBean
import top.zbeboy.isy.web.bean.internship.statistics.InternshipStatisticsBean
import top.zbeboy.isy.web.common.MethodControllerCommon
import top.zbeboy.isy.web.internship.common.InternshipMethodControllerCommon
import top.zbeboy.isy.web.util.AjaxUtils
import top.zbeboy.isy.web.util.DataTablesUtils
import top.zbeboy.isy.web.util.PaginationUtils
import java.io.IOException
import java.util.*
import javax.annotation.Resource
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* Created by zbeboy 2017-12-28 .
**/
@Controller
open class InternshipStatisticsController {
private val log = LoggerFactory.getLogger(InternshipStatisticsController::class.java)
@Resource
open lateinit var internshipReleaseService: InternshipReleaseService
@Resource
open lateinit var internshipTypeService: InternshipTypeService
@Resource
open lateinit var internshipStatisticsService: InternshipStatisticsService
@Resource
open lateinit var internshipCollegeService: InternshipCollegeService
@Resource
open lateinit var internshipCompanyService: InternshipCompanyService
@Resource
open lateinit var graduationPracticeCompanyService: GraduationPracticeCompanyService
@Resource
open lateinit var graduationPracticeCollegeService: GraduationPracticeCollegeService
@Resource
open lateinit var graduationPracticeUnifyService: GraduationPracticeUnifyService
@Resource
open lateinit var methodControllerCommon: MethodControllerCommon
@Resource
open lateinit var internshipChangeHistoryService: InternshipChangeHistoryService
@Resource
open lateinit var internshipChangeCompanyHistoryService: InternshipChangeCompanyHistoryService
@Resource
open lateinit var internshipMethodControllerCommon: InternshipMethodControllerCommon
@Resource
open lateinit var cacheManageService: CacheManageService
@Resource
open lateinit var uploadService: UploadService
/**
* 实习统计
*
* @return 实习统计页面
*/
@RequestMapping(value = ["/web/menu/internship/statistical"], method = [(RequestMethod.GET)])
fun internshipStatistical(): String {
return "web/internship/statistics/internship_statistics::#page-wrapper"
}
/**
* 已提交列表
*
* @return 已提交列表 统计页面
*/
@RequestMapping(value = ["/web/internship/statistical/submitted"], method = [(RequestMethod.GET)])
fun statisticalSubmitted(@RequestParam("id") internshipReleaseId: String, modelMap: ModelMap): String {
modelMap.addAttribute("internshipReleaseId", internshipReleaseId)
return "web/internship/statistics/internship_submitted::#page-wrapper"
}
/**
* 申请记录列表
*
* @return 申请记录列表页面
*/
@RequestMapping(value = ["/web/internship/statistical/record/apply"], method = [(RequestMethod.GET)])
fun changeHistory(@RequestParam("id") internshipReleaseId: String, @RequestParam("studentId") studentId: Int, modelMap: ModelMap): String {
modelMap.addAttribute("internshipReleaseId", internshipReleaseId)
modelMap.addAttribute("studentId", studentId)
return "web/internship/statistics/internship_change_history::#page-wrapper"
}
/**
* 单位变更记录列表
*
* @return 单位变更记录列表页面
*/
@RequestMapping(value = ["/web/internship/statistical/record/company"], method = [(RequestMethod.GET)])
fun changeCompanyHistory(@RequestParam("id") internshipReleaseId: String, @RequestParam("studentId") studentId: Int, modelMap: ModelMap): String {
modelMap.addAttribute("internshipReleaseId", internshipReleaseId)
modelMap.addAttribute("studentId", studentId)
return "web/internship/statistics/internship_change_company_history::#page-wrapper"
}
/**
* 未提交列表
*
* @return 未提交列表 统计页面
*/
@RequestMapping(value = ["/web/internship/statistical/unsubmitted"], method = [(RequestMethod.GET)])
fun statisticalUnSubmitted(@RequestParam("id") internshipReleaseId: String, modelMap: ModelMap): String {
modelMap.addAttribute("internshipReleaseId", internshipReleaseId)
return "web/internship/statistics/internship_unsubmitted::#page-wrapper"
}
/**
* 数据列表
*
* @return 数据列表 统计页面
*/
@RequestMapping(value = ["/web/internship/statistical/data_list"], method = [(RequestMethod.GET)])
fun statisticalDataList(@RequestParam("id") internshipReleaseId: String, modelMap: ModelMap): String {
val internshipRelease = internshipReleaseService.findById(internshipReleaseId)
return if (!ObjectUtils.isEmpty(internshipRelease)) {
modelMap.addAttribute("internshipReleaseId", internshipReleaseId)
val internshipType = internshipTypeService.findByInternshipTypeId(internshipRelease.internshipTypeId!!)
when (internshipType.internshipTypeName) {
Workbook.INTERNSHIP_COLLEGE_TYPE -> "web/internship/statistics/internship_college_data::#page-wrapper"
Workbook.INTERNSHIP_COMPANY_TYPE -> "web/internship/statistics/internship_company_data::#page-wrapper"
Workbook.GRADUATION_PRACTICE_COLLEGE_TYPE -> "web/internship/statistics/graduation_practice_college_data::#page-wrapper"
Workbook.GRADUATION_PRACTICE_UNIFY_TYPE -> "web/internship/statistics/graduation_practice_unify_data::#page-wrapper"
Workbook.GRADUATION_PRACTICE_COMPANY_TYPE -> "web/internship/statistics/graduation_practice_company_data::#page-wrapper"
else -> methodControllerCommon.showTip(modelMap, "未找到相关实习类型页面")
}
} else {
methodControllerCommon.showTip(modelMap, "您不符合进入条件")
}
}
/**
* 获取实习统计数据
*
* @return 数据
*/
@RequestMapping(value = ["/web/internship/statistical/internship/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun internshipListDatas(paginationUtils: PaginationUtils): AjaxUtils<InternshipReleaseBean> {
val ajaxUtils = internshipMethodControllerCommon.internshipListDatas(paginationUtils)
val internshipReleaseBeens = ajaxUtils.listResult
internshipReleaseBeens!!.forEach { r ->
val internshipStatisticsBean = InternshipStatisticsBean()
internshipStatisticsBean.internshipReleaseId = r.internshipReleaseId
r.submittedTotalData = internshipStatisticsService.submittedCountAll(internshipStatisticsBean)
r.unsubmittedTotalData = internshipStatisticsService.unsubmittedCountAll(internshipStatisticsBean)
}
return ajaxUtils.listData(internshipReleaseBeens)
}
/**
* 已提交列表 数据
*
* @param request 请求
* @return 数据
*/
@RequestMapping(value = ["/web/internship/statistical/submitted/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun submittedDatas(request: HttpServletRequest): DataTablesUtils<InternshipStatisticsBean> {
// 前台数据标题 注:要和前台标题顺序一致,获取order用
val headers = ArrayList<String>()
headers.add("student_name")
headers.add("student_number")
headers.add("science_name")
headers.add("organize_name")
headers.add("internship_apply_state")
headers.add("operator")
val dataTablesUtils = DataTablesUtils<InternshipStatisticsBean>(request, headers)
val internshipStatisticsBean = InternshipStatisticsBean()
val internshipReleaseId = request.getParameter("internshipReleaseId")
if (!ObjectUtils.isEmpty(internshipReleaseId)) {
internshipStatisticsBean.internshipReleaseId = request.getParameter("internshipReleaseId")
val records = internshipStatisticsService.submittedFindAllByPage(dataTablesUtils, internshipStatisticsBean)
var internshipStatisticsBeens: List<InternshipStatisticsBean> = ArrayList()
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
internshipStatisticsBeens = records.into(InternshipStatisticsBean::class.java)
}
dataTablesUtils.data = internshipStatisticsBeens
dataTablesUtils.setiTotalRecords(internshipStatisticsService.submittedCountAll(internshipStatisticsBean).toLong())
dataTablesUtils.setiTotalDisplayRecords(internshipStatisticsService.submittedCountByCondition(dataTablesUtils, internshipStatisticsBean).toLong())
}
return dataTablesUtils
}
/**
* 申请变更记录数据
*
* @param internshipReleaseId 实习发布id
* @param studentId 学生id
* @return 数据
*/
@RequestMapping(value = ["/web/internship/statistical/record/apply/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun changeHistoryDatas(@RequestParam("internshipReleaseId") internshipReleaseId: String, @RequestParam("studentId") studentId: Int): AjaxUtils<InternshipChangeHistoryBean> {
val ajaxUtils = AjaxUtils.of<InternshipChangeHistoryBean>()
var internshipChangeHistoryBeans: List<InternshipChangeHistoryBean> = ArrayList()
val records = internshipChangeHistoryService.findByInternshipReleaseIdAndStudentId(internshipReleaseId, studentId)
if (records.isNotEmpty) {
internshipChangeHistoryBeans = records.into(InternshipChangeHistoryBean::class.java)
internshipChangeHistoryBeans.forEach { i ->
i.applyTimeStr = DateTimeUtils.formatDate(i.applyTime)
if (!ObjectUtils.isEmpty(i.changeFillStartTime)) {
i.changeFillStartTimeStr = DateTimeUtils.formatDate(i.changeFillStartTime)
}
if (!ObjectUtils.isEmpty(i.changeFillEndTime)) {
i.changeFillEndTimeStr = DateTimeUtils.formatDate(i.changeFillEndTime)
}
}
}
return ajaxUtils.success().msg("获取数据成功").listData(internshipChangeHistoryBeans)
}
/**
* 单位变更记录数据
*
* @param internshipReleaseId 实习发布id
* @param studentId 学生id
* @return 数据
*/
@RequestMapping(value = ["/web/internship/statistical/record/company/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun changeCompanyDatas(@RequestParam("internshipReleaseId") internshipReleaseId: String, @RequestParam("studentId") studentId: Int): AjaxUtils<InternshipChangeCompanyHistoryBean> {
val ajaxUtils = AjaxUtils.of<InternshipChangeCompanyHistoryBean>()
var internshipChangeCompanyHistoryBeans: List<InternshipChangeCompanyHistoryBean> = ArrayList()
val records = internshipChangeCompanyHistoryService.findByInternshipReleaseIdAndStudentId(internshipReleaseId, studentId)
if (records.isNotEmpty) {
internshipChangeCompanyHistoryBeans = records.into(InternshipChangeCompanyHistoryBean::class.java)
internshipChangeCompanyHistoryBeans.forEach { i -> i.changeTimeStr = DateTimeUtils.formatDate(i.changeTime) }
}
return ajaxUtils.success().msg("获取数据成功").listData(internshipChangeCompanyHistoryBeans)
}
/**
* 未提交列表 数据
*
* @param request 请求
* @return 数据
*/
@RequestMapping(value = ["/web/internship/statistical/unsubmitted/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun unsubmittedDatas(request: HttpServletRequest): DataTablesUtils<InternshipStatisticsBean> {
// 前台数据标题 注:要和前台标题顺序一致,获取order用
val headers = ArrayList<String>()
headers.add("student_name")
headers.add("student_number")
headers.add("science_name")
headers.add("organize_name")
headers.add("operator")
val dataTablesUtils = DataTablesUtils<InternshipStatisticsBean>(request, headers)
val internshipStatisticsBean = InternshipStatisticsBean()
val internshipReleaseId = request.getParameter("internshipReleaseId")
if (!ObjectUtils.isEmpty(internshipReleaseId)) {
internshipStatisticsBean.internshipReleaseId = request.getParameter("internshipReleaseId")
val records = internshipStatisticsService.unsubmittedFindAllByPage(dataTablesUtils, internshipStatisticsBean)
var internshipStatisticsBeens: List<InternshipStatisticsBean> = ArrayList()
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
internshipStatisticsBeens = records.into(InternshipStatisticsBean::class.java)
}
dataTablesUtils.data = internshipStatisticsBeens
dataTablesUtils.setiTotalRecords(internshipStatisticsService.unsubmittedCountAll(internshipStatisticsBean).toLong())
dataTablesUtils.setiTotalDisplayRecords(internshipStatisticsService.unsubmittedCountByCondition(dataTablesUtils, internshipStatisticsBean).toLong())
}
return dataTablesUtils
}
/**
* 数据列表 顶岗实习(留学院) 数据
*
* @param request 请求
* @return 数据
*/
@RequestMapping(value = ["/web/internship/statistical/college/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun collegeData(request: HttpServletRequest): DataTablesUtils<InternshipCollege> {
// 前台数据标题 注:要和前台标题顺序一致,获取order用
val headers = ArrayList<String>()
headers.add("student_name")
headers.add("college_class")
headers.add("student_sex")
headers.add("student_number")
headers.add("phone_number")
headers.add("qq_mailbox")
headers.add("parental_contact")
headers.add("headmaster")
headers.add("headmaster_contact")
headers.add("internship_college_name")
headers.add("internship_college_address")
headers.add("internship_college_contacts")
headers.add("internship_college_tel")
headers.add("school_guidance_teacher")
headers.add("school_guidance_teacher_tel")
headers.add("start_time")
headers.add("end_time")
headers.add("commitment_book")
headers.add("safety_responsibility_book")
headers.add("practice_agreement")
headers.add("internship_application")
headers.add("practice_receiving")
headers.add("security_education_agreement")
headers.add("parental_consent")
val dataTablesUtils = DataTablesUtils<InternshipCollege>(request, headers)
val internshipCollege = InternshipCollege()
val internshipReleaseId = request.getParameter("internshipReleaseId")
if (!ObjectUtils.isEmpty(internshipReleaseId)) {
internshipCollege.internshipReleaseId = request.getParameter("internshipReleaseId")
val records = internshipCollegeService.findAllByPage(dataTablesUtils, internshipCollege)
var internshipColleges: List<InternshipCollege> = ArrayList()
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
internshipColleges = records.into(InternshipCollege::class.java)
internshipColleges.forEach { data ->
val usersKey = cacheManageService.getUsersKey(data.studentUsername!!)
data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey)
data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey)
}
}
dataTablesUtils.data = internshipColleges
dataTablesUtils.setiTotalRecords(internshipCollegeService.countAll(internshipCollege).toLong())
dataTablesUtils.setiTotalDisplayRecords(internshipCollegeService.countByCondition(dataTablesUtils, internshipCollege).toLong())
}
return dataTablesUtils
}
/**
* 导出 顶岗实习(留学院) 数据
*
* @param request 请求
*/
@RequestMapping(value = ["/web/internship/statistical/college/data/export"], method = [(RequestMethod.GET)])
fun collegeDataExport(request: HttpServletRequest, response: HttpServletResponse) {
try {
var fileName: String? = "顶岗实习(留学院)"
var ext: String? = Workbook.XLSX_FILE
val exportBean = JSON.parseObject(request.getParameter("exportFile"), ExportBean::class.java)
val extraSearchParam = request.getParameter("extra_search")
val dataTablesUtils = DataTablesUtils.of<InternshipCollege>()
if (StringUtils.isNotBlank(extraSearchParam)) {
dataTablesUtils.search = JSON.parseObject(extraSearchParam)
}
val internshipCollege = InternshipCollege()
val internshipReleaseId = request.getParameter("internshipReleaseId")
if (!ObjectUtils.isEmpty(internshipReleaseId)) {
internshipCollege.internshipReleaseId = request.getParameter("internshipReleaseId")
val records = internshipCollegeService.exportData(dataTablesUtils, internshipCollege)
var internshipColleges: List<InternshipCollege> = ArrayList()
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
internshipColleges = records.into(InternshipCollege::class.java)
internshipColleges.forEach { data ->
val usersKey = cacheManageService.getUsersKey(data.studentUsername!!)
data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey)
data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey)
}
}
if (StringUtils.isNotBlank(exportBean.fileName)) {
fileName = exportBean.fileName
}
if (StringUtils.isNotBlank(exportBean.ext)) {
ext = exportBean.ext
}
val internshipRelease = internshipReleaseService.findById(internshipReleaseId)
if (!ObjectUtils.isEmpty(internshipRelease)) {
val export = InternshipCollegeExport(internshipColleges)
val schoolInfoPath = cacheManageService.schoolInfoPath(internshipRelease.departmentId!!)
val path = Workbook.internshipPath(schoolInfoPath) + fileName + "." + ext
export.exportExcel(RequestUtils.getRealPath(request) + Workbook.internshipPath(schoolInfoPath), fileName!!, ext!!)
uploadService.download(fileName, path, response, request)
}
}
} catch (e: IOException) {
log.error("Export file error, error is {}", e)
}
}
/**
* 数据列表 校外自主实习(去单位) 数据
*
* @param request 请求
* @return 数据
*/
@RequestMapping(value = ["/web/internship/statistical/company/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun companyData(request: HttpServletRequest): DataTablesUtils<InternshipCompany> {
// 前台数据标题 注:要和前台标题顺序一致,获取order用
val headers = ArrayList<String>()
headers.add("student_name")
headers.add("college_class")
headers.add("student_sex")
headers.add("student_number")
headers.add("phone_number")
headers.add("qq_mailbox")
headers.add("parental_contact")
headers.add("headmaster")
headers.add("headmaster_contact")
headers.add("internship_company_name")
headers.add("internship_company_address")
headers.add("internship_company_contacts")
headers.add("internship_company_tel")
headers.add("school_guidance_teacher")
headers.add("school_guidance_teacher_tel")
headers.add("start_time")
headers.add("end_time")
headers.add("commitment_book")
headers.add("safety_responsibility_book")
headers.add("practice_agreement")
headers.add("internship_application")
headers.add("practice_receiving")
headers.add("security_education_agreement")
headers.add("parental_consent")
val dataTablesUtils = DataTablesUtils<InternshipCompany>(request, headers)
val internshipCompany = InternshipCompany()
val internshipReleaseId = request.getParameter("internshipReleaseId")
if (!ObjectUtils.isEmpty(internshipReleaseId)) {
internshipCompany.internshipReleaseId = request.getParameter("internshipReleaseId")
val records = internshipCompanyService.findAllByPage(dataTablesUtils, internshipCompany)
var internshipCompanies: List<InternshipCompany> = ArrayList()
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
internshipCompanies = records.into(InternshipCompany::class.java)
internshipCompanies.forEach { data ->
val usersKey = cacheManageService.getUsersKey(data.studentUsername!!)
data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey)
data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey)
}
}
dataTablesUtils.data = internshipCompanies
dataTablesUtils.setiTotalRecords(internshipCompanyService.countAll(internshipCompany).toLong())
dataTablesUtils.setiTotalDisplayRecords(internshipCompanyService.countByCondition(dataTablesUtils, internshipCompany).toLong())
}
return dataTablesUtils
}
/**
* 导出 校外自主实习(去单位) 数据
*
* @param request 请求
*/
@RequestMapping(value = ["/web/internship/statistical/company/data/export"], method = [(RequestMethod.GET)])
fun companyDataExport(request: HttpServletRequest, response: HttpServletResponse) {
try {
var fileName: String? = "校外自主实习(去单位)"
var ext: String? = Workbook.XLSX_FILE
val exportBean = JSON.parseObject(request.getParameter("exportFile"), ExportBean::class.java)
val extraSearchParam = request.getParameter("extra_search")
val dataTablesUtils = DataTablesUtils.of<InternshipCompany>()
if (StringUtils.isNotBlank(extraSearchParam)) {
dataTablesUtils.search = JSON.parseObject(extraSearchParam)
}
val internshipCompany = InternshipCompany()
val internshipReleaseId = request.getParameter("internshipReleaseId")
if (!ObjectUtils.isEmpty(internshipReleaseId)) {
internshipCompany.internshipReleaseId = request.getParameter("internshipReleaseId")
val records = internshipCompanyService.exportData(dataTablesUtils, internshipCompany)
var internshipCompanies: List<InternshipCompany> = ArrayList()
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
internshipCompanies = records.into(InternshipCompany::class.java)
internshipCompanies.forEach { data ->
val usersKey = cacheManageService.getUsersKey(data.studentUsername!!)
data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey)
data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey)
}
}
if (StringUtils.isNotBlank(exportBean.fileName)) {
fileName = exportBean.fileName
}
if (StringUtils.isNotBlank(exportBean.ext)) {
ext = exportBean.ext
}
val internshipRelease = internshipReleaseService.findById(internshipReleaseId)
if (!ObjectUtils.isEmpty(internshipRelease)) {
val export = InternshipCompanyExport(internshipCompanies)
val schoolInfoPath = cacheManageService.schoolInfoPath(internshipRelease.departmentId!!)
val path = Workbook.internshipPath(schoolInfoPath) + fileName + "." + ext
export.exportExcel(RequestUtils.getRealPath(request) + Workbook.internshipPath(schoolInfoPath), fileName!!, ext!!)
uploadService.download(fileName, path, response, request)
}
}
} catch (e: IOException) {
log.error("Export file error, error is {}", e)
}
}
/**
* 数据列表 毕业实习(校外) 数据
*
* @param request 请求
* @return 数据
*/
@RequestMapping(value = ["/web/internship/statistical/graduation_practice_company/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun graduationPracticeCompanyData(request: HttpServletRequest): DataTablesUtils<GraduationPracticeCompany> {
// 前台数据标题 注:要和前台标题顺序一致,获取order用
val headers = ArrayList<String>()
headers.add("student_name")
headers.add("college_class")
headers.add("student_sex")
headers.add("student_number")
headers.add("phone_number")
headers.add("qq_mailbox")
headers.add("parental_contact")
headers.add("headmaster")
headers.add("headmaster_contact")
headers.add("graduation_practice_company_name")
headers.add("graduation_practice_company_address")
headers.add("graduation_practice_company_contacts")
headers.add("graduation_practice_company_tel")
headers.add("school_guidance_teacher")
headers.add("school_guidance_teacher_tel")
headers.add("start_time")
headers.add("end_time")
headers.add("commitment_book")
headers.add("safety_responsibility_book")
headers.add("practice_agreement")
headers.add("internship_application")
headers.add("practice_receiving")
headers.add("security_education_agreement")
headers.add("parental_consent")
val dataTablesUtils = DataTablesUtils<GraduationPracticeCompany>(request, headers)
val graduationPracticeCompany = GraduationPracticeCompany()
val internshipReleaseId = request.getParameter("internshipReleaseId")
if (!ObjectUtils.isEmpty(internshipReleaseId)) {
graduationPracticeCompany.internshipReleaseId = request.getParameter("internshipReleaseId")
val records = graduationPracticeCompanyService.findAllByPage(dataTablesUtils, graduationPracticeCompany)
var graduationPracticeCompanies: List<GraduationPracticeCompany> = ArrayList()
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
graduationPracticeCompanies = records.into(GraduationPracticeCompany::class.java)
graduationPracticeCompanies.forEach { data ->
val usersKey = cacheManageService.getUsersKey(data.studentUsername!!)
data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey)
data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey)
}
}
dataTablesUtils.data = graduationPracticeCompanies
dataTablesUtils.setiTotalRecords(graduationPracticeCompanyService.countAll(graduationPracticeCompany).toLong())
dataTablesUtils.setiTotalDisplayRecords(graduationPracticeCompanyService.countByCondition(dataTablesUtils, graduationPracticeCompany).toLong())
}
return dataTablesUtils
}
/**
* 导出 毕业实习(校外) 数据
*
* @param request 请求
*/
@RequestMapping(value = ["/web/internship/statistical/graduation_practice_company/data/export"], method = [(RequestMethod.GET)])
fun graduationPracticeCompanyDataExport(request: HttpServletRequest, response: HttpServletResponse) {
try {
var fileName: String? = "毕业实习(校外)"
var ext: String? = Workbook.XLSX_FILE
val exportBean = JSON.parseObject(request.getParameter("exportFile"), ExportBean::class.java)
val extraSearchParam = request.getParameter("extra_search")
val dataTablesUtils = DataTablesUtils.of<GraduationPracticeCompany>()
if (StringUtils.isNotBlank(extraSearchParam)) {
dataTablesUtils.search = JSON.parseObject(extraSearchParam)
}
val graduationPracticeCompany = GraduationPracticeCompany()
val internshipReleaseId = request.getParameter("internshipReleaseId")
if (!ObjectUtils.isEmpty(internshipReleaseId)) {
graduationPracticeCompany.internshipReleaseId = request.getParameter("internshipReleaseId")
val records = graduationPracticeCompanyService.exportData(dataTablesUtils, graduationPracticeCompany)
var graduationPracticeCompanies: List<GraduationPracticeCompany> = ArrayList()
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
graduationPracticeCompanies = records.into(GraduationPracticeCompany::class.java)
graduationPracticeCompanies.forEach { data ->
val usersKey = cacheManageService.getUsersKey(data.studentUsername!!)
data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey)
data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey)
}
}
if (StringUtils.isNotBlank(exportBean.fileName)) {
fileName = exportBean.fileName
}
if (StringUtils.isNotBlank(exportBean.ext)) {
ext = exportBean.ext
}
val internshipRelease = internshipReleaseService.findById(internshipReleaseId)
if (!ObjectUtils.isEmpty(internshipRelease)) {
val export = GraduationPracticeCompanyExport(graduationPracticeCompanies)
val schoolInfoPath = cacheManageService.schoolInfoPath(internshipRelease.departmentId!!)
val path = Workbook.internshipPath(schoolInfoPath) + fileName + "." + ext
export.exportExcel(RequestUtils.getRealPath(request) + Workbook.internshipPath(schoolInfoPath), fileName!!, ext!!)
uploadService.download(fileName, path, response, request)
}
}
} catch (e: IOException) {
log.error("Export file error, error is {}", e)
}
}
/**
* 数据列表 毕业实习(校内) 数据
*
* @param request 请求
* @return 数据
*/
@RequestMapping(value = ["/web/internship/statistical/graduation_practice_college/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun graduationPracticeCollegeData(request: HttpServletRequest): DataTablesUtils<GraduationPracticeCollege> {
// 前台数据标题 注:要和前台标题顺序一致,获取order用
val headers = ArrayList<String>()
headers.add("student_name")
headers.add("college_class")
headers.add("student_sex")
headers.add("student_number")
headers.add("phone_number")
headers.add("qq_mailbox")
headers.add("parental_contact")
headers.add("headmaster")
headers.add("headmaster_contact")
headers.add("graduation_practice_college_name")
headers.add("graduation_practice_college_address")
headers.add("graduation_practice_college_contacts")
headers.add("graduation_practice_college_tel")
headers.add("school_guidance_teacher")
headers.add("school_guidance_teacher_tel")
headers.add("start_time")
headers.add("end_time")
headers.add("commitment_book")
headers.add("safety_responsibility_book")
headers.add("practice_agreement")
headers.add("internship_application")
headers.add("practice_receiving")
headers.add("security_education_agreement")
headers.add("parental_consent")
val dataTablesUtils = DataTablesUtils<GraduationPracticeCollege>(request, headers)
val graduationPracticeCollege = GraduationPracticeCollege()
val internshipReleaseId = request.getParameter("internshipReleaseId")
if (!ObjectUtils.isEmpty(internshipReleaseId)) {
graduationPracticeCollege.internshipReleaseId = request.getParameter("internshipReleaseId")
val records = graduationPracticeCollegeService.findAllByPage(dataTablesUtils, graduationPracticeCollege)
var graduationPracticeColleges: List<GraduationPracticeCollege> = ArrayList()
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
graduationPracticeColleges = records.into(GraduationPracticeCollege::class.java)
graduationPracticeColleges.forEach { data ->
val usersKey = cacheManageService.getUsersKey(data.studentUsername!!)
data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey)
data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey)
}
}
dataTablesUtils.data = graduationPracticeColleges
dataTablesUtils.setiTotalRecords(graduationPracticeCollegeService.countAll(graduationPracticeCollege).toLong())
dataTablesUtils.setiTotalDisplayRecords(graduationPracticeCollegeService.countByCondition(dataTablesUtils, graduationPracticeCollege).toLong())
}
return dataTablesUtils
}
/**
* 导出 毕业实习(校内) 数据
*
* @param request 请求
*/
@RequestMapping(value = ["/web/internship/statistical/graduation_practice_college/data/export"], method = [(RequestMethod.GET)])
fun graduationPracticeCollegeDataExport(request: HttpServletRequest, response: HttpServletResponse) {
try {
var fileName: String? = "毕业实习(校内)"
var ext: String? = Workbook.XLSX_FILE
val exportBean = JSON.parseObject(request.getParameter("exportFile"), ExportBean::class.java)
val extraSearchParam = request.getParameter("extra_search")
val dataTablesUtils = DataTablesUtils.of<GraduationPracticeCollege>()
if (StringUtils.isNotBlank(extraSearchParam)) {
dataTablesUtils.search = JSON.parseObject(extraSearchParam)
}
val graduationPracticeCollege = GraduationPracticeCollege()
val internshipReleaseId = request.getParameter("internshipReleaseId")
if (!ObjectUtils.isEmpty(internshipReleaseId)) {
graduationPracticeCollege.internshipReleaseId = request.getParameter("internshipReleaseId")
val records = graduationPracticeCollegeService.exportData(dataTablesUtils, graduationPracticeCollege)
var graduationPracticeColleges: List<GraduationPracticeCollege> = ArrayList()
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
graduationPracticeColleges = records.into(GraduationPracticeCollege::class.java)
graduationPracticeColleges.forEach { data ->
val usersKey = cacheManageService.getUsersKey(data.studentUsername!!)
data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey)
data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey)
}
}
if (StringUtils.isNotBlank(exportBean.fileName)) {
fileName = exportBean.fileName
}
if (StringUtils.isNotBlank(exportBean.ext)) {
ext = exportBean.ext
}
val internshipRelease = internshipReleaseService.findById(internshipReleaseId)
if (!ObjectUtils.isEmpty(internshipRelease)) {
val export = GraduationPracticeCollegeExport(graduationPracticeColleges)
val schoolInfoPath = cacheManageService.schoolInfoPath(internshipRelease.departmentId!!)
val path = Workbook.internshipPath(schoolInfoPath) + fileName + "." + ext
export.exportExcel(RequestUtils.getRealPath(request) + Workbook.internshipPath(schoolInfoPath), fileName!!, ext!!)
uploadService.download(fileName, path, response, request)
}
}
} catch (e: IOException) {
log.error("Export file error, error is {}", e)
}
}
/**
* 数据列表 毕业实习(学校统一组织校外实习) 数据
*
* @param request 请求
* @return 数据
*/
@RequestMapping(value = ["/web/internship/statistical/graduation_practice_unify/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun graduationPracticeUnifyData(request: HttpServletRequest): DataTablesUtils<GraduationPracticeUnify> {
// 前台数据标题 注:要和前台标题顺序一致,获取order用
val headers = ArrayList<String>()
headers.add("student_name")
headers.add("college_class")
headers.add("student_sex")
headers.add("student_number")
headers.add("phone_number")
headers.add("qq_mailbox")
headers.add("parental_contact")
headers.add("headmaster")
headers.add("headmaster_contact")
headers.add("graduation_practice_unify_name")
headers.add("graduation_practice_unify_address")
headers.add("graduation_practice_unify_contacts")
headers.add("graduation_practice_unify_tel")
headers.add("school_guidance_teacher")
headers.add("school_guidance_teacher_tel")
headers.add("start_time")
headers.add("end_time")
headers.add("commitment_book")
headers.add("safety_responsibility_book")
headers.add("practice_agreement")
headers.add("internship_application")
headers.add("practice_receiving")
headers.add("security_education_agreement")
headers.add("parental_consent")
val dataTablesUtils = DataTablesUtils<GraduationPracticeUnify>(request, headers)
val graduationPracticeUnify = GraduationPracticeUnify()
val internshipReleaseId = request.getParameter("internshipReleaseId")
if (!ObjectUtils.isEmpty(internshipReleaseId)) {
graduationPracticeUnify.internshipReleaseId = request.getParameter("internshipReleaseId")
val records = graduationPracticeUnifyService.findAllByPage(dataTablesUtils, graduationPracticeUnify)
var graduationPracticeUnifies: List<GraduationPracticeUnify> = ArrayList()
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
graduationPracticeUnifies = records.into(GraduationPracticeUnify::class.java)
graduationPracticeUnifies.forEach { data ->
val usersKey = cacheManageService.getUsersKey(data.studentUsername!!)
data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey)
data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey)
}
}
dataTablesUtils.data = graduationPracticeUnifies
dataTablesUtils.setiTotalRecords(graduationPracticeUnifyService.countAll(graduationPracticeUnify).toLong())
dataTablesUtils.setiTotalDisplayRecords(graduationPracticeUnifyService.countByCondition(dataTablesUtils, graduationPracticeUnify).toLong())
}
return dataTablesUtils
}
/**
* 导出 毕业实习(学校统一组织校外实习) 数据
*
* @param request 请求
*/
@RequestMapping(value = ["/web/internship/statistical/graduation_practice_unify/data/export"], method = [(RequestMethod.GET)])
fun graduationPracticeUnifyDataExport(request: HttpServletRequest, response: HttpServletResponse) {
try {
var fileName: String? = "毕业实习(学校统一组织校外实习)"
var ext: String? = Workbook.XLSX_FILE
val exportBean = JSON.parseObject(request.getParameter("exportFile"), ExportBean::class.java)
val extraSearchParam = request.getParameter("extra_search")
val dataTablesUtils = DataTablesUtils.of<GraduationPracticeUnify>()
if (StringUtils.isNotBlank(extraSearchParam)) {
dataTablesUtils.search = JSON.parseObject(extraSearchParam)
}
val graduationPracticeUnify = GraduationPracticeUnify()
val internshipReleaseId = request.getParameter("internshipReleaseId")
if (!ObjectUtils.isEmpty(internshipReleaseId)) {
graduationPracticeUnify.internshipReleaseId = request.getParameter("internshipReleaseId")
val records = graduationPracticeUnifyService.exportData(dataTablesUtils, graduationPracticeUnify)
var graduationPracticeUnifies: List<GraduationPracticeUnify> = ArrayList()
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
graduationPracticeUnifies = records.into(GraduationPracticeUnify::class.java)
graduationPracticeUnifies.forEach { data ->
val usersKey = cacheManageService.getUsersKey(data.studentUsername!!)
data.studentSex = methodControllerCommon.decryptPersonalData(data.studentSex, usersKey)
data.parentalContact = methodControllerCommon.decryptPersonalData(data.parentalContact, usersKey)
}
}
if (StringUtils.isNotBlank(exportBean.fileName)) {
fileName = exportBean.fileName
}
if (StringUtils.isNotBlank(exportBean.ext)) {
ext = exportBean.ext
}
val internshipRelease = internshipReleaseService.findById(internshipReleaseId)
if (!ObjectUtils.isEmpty(internshipRelease)) {
val export = GraduationPracticeUnifyExport(graduationPracticeUnifies)
val schoolInfoPath = cacheManageService.schoolInfoPath(internshipRelease.departmentId!!)
val path = Workbook.internshipPath(schoolInfoPath) + fileName + "." + ext
export.exportExcel(RequestUtils.getRealPath(request) + Workbook.internshipPath(schoolInfoPath), fileName!!, ext!!)
uploadService.download(fileName, path, response, request)
}
}
} catch (e: IOException) {
log.error("Export file error, error is {}", e)
}
}
} | mit | d83b6de81e52e120b56a65eda7442c8d | 50.635934 | 184 | 0.678822 | 5.817419 | false | false | false | false |
akhbulatov/wordkeeper | app/src/main/java/com/akhbulatov/wordkeeper/presentation/ui/global/base/ConfirmDialog.kt | 1 | 1690 | package com.akhbulatov.wordkeeper.presentation.ui.global.base
import android.app.Dialog
import android.os.Bundle
import androidx.annotation.StringRes
import androidx.core.os.bundleOf
import androidx.fragment.app.setFragmentResult
import com.google.android.material.dialog.MaterialAlertDialogBuilder
class ConfirmDialog : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val args = requireArguments()
return MaterialAlertDialogBuilder(requireContext())
.setTitle(args.getInt(ARG_TITLE))
.setMessage(args.getInt(ARG_MESSAGE))
.setPositiveButton(args.getInt(ARG_POSITIVE_BUTTON)) { _, _ ->
setFragmentResult(REQUEST_OK, bundleOf())
}
.setNegativeButton(args.getInt(ARG_NEGATIVE_BUTTON)) { _, _ -> dismiss() }
.create()
}
companion object {
const val REQUEST_OK = "request_ok"
private const val ARG_TITLE = "title"
private const val ARG_MESSAGE = "message"
private const val ARG_POSITIVE_BUTTON = "positive_button"
private const val ARG_NEGATIVE_BUTTON = "negative_button"
fun newInstance(
@StringRes title: Int,
@StringRes message: Int,
@StringRes positiveButton: Int = android.R.string.ok,
@StringRes negativeButton: Int = android.R.string.cancel
) = ConfirmDialog().apply {
arguments = bundleOf(
ARG_TITLE to title,
ARG_MESSAGE to message,
ARG_POSITIVE_BUTTON to positiveButton,
ARG_NEGATIVE_BUTTON to negativeButton
)
}
}
}
| apache-2.0 | 35ce01e8a29056c3cd9ea4e27474124b | 36.555556 | 86 | 0.638462 | 4.898551 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Inventory.kt | 1 | 1306 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Instruction2
import org.objectweb.asm.Opcodes.PUTFIELD
@DependsOn(Node::class)
class Inventory : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == type<Node>() }
.and { it.interfaces.isEmpty() }
.and { it.instanceMethods.isEmpty() }
.and { it.instanceFields.count { it.type == IntArray::class.type } == 2 }
.and { it.instanceFields.size == 2 }
class ids : OrderMapper.InConstructor.Field(Inventory::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type }
}
class quantities : OrderMapper.InConstructor.Field(Inventory::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type }
}
} | mit | e998f4aad91f68b78d34325dc1f16dab | 45.678571 | 124 | 0.730475 | 4.055901 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/ide/wizard/AbstractNewProjectWizardMultiStepWithAddButton.kt | 6 | 3810 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.wizard
import com.intellij.icons.AllIcons
import com.intellij.ide.plugins.PluginManagerConfigurable
import com.intellij.ide.projectWizard.NewProjectWizardCollector
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys.CONTEXT_COMPONENT
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.IdeaActionButtonLook
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.InstallPluginTask
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.UIBundle
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.dsl.builder.BottomGap
import com.intellij.ui.dsl.builder.Panel
import com.intellij.ui.dsl.builder.components.SegmentedButtonBorder
import java.util.function.Consumer
import java.util.function.Supplier
import javax.swing.JComponent
abstract class AbstractNewProjectWizardMultiStepWithAddButton<S : NewProjectWizardStep, F: NewProjectWizardMultiStepFactory<S>>(
parent: NewProjectWizardStep,
epName: ExtensionPointName<F>
) : AbstractNewProjectWizardMultiStep<S, F>(parent, epName) {
abstract var additionalStepPlugins: Map<String, String>
override fun setupSwitcherUi(builder: Panel) {
with(builder) {
row(label) {
createAndSetupSwitcher(this@row)
if (additionalStepPlugins.isNotEmpty()) {
val plus = AdditionalStepsAction()
val actionButton = ActionButton(
plus,
plus.templatePresentation,
ActionPlaces.getPopupPlace("NEW_PROJECT_WIZARD"),
ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE
)
actionButton.setLook(IdeaActionButtonLook())
actionButton.border = SegmentedButtonBorder()
cell(actionButton)
}
}.bottomGap(BottomGap.SMALL)
}
}
private inner class AdditionalStepsAction : DumbAwareAction(null, null, AllIcons.General.Add) {
override fun actionPerformed(e: AnActionEvent) {
NewProjectWizardCollector.logAddPlugin(context)
val additionalSteps = (additionalStepPlugins.keys - steps.keys).sorted().map { OpenMarketPlaceAction(it) }
JBPopupFactory.getInstance().createActionGroupPopup(
UIBundle.message("new.project.wizard.popup.title.install.plugin"), DefaultActionGroup(additionalSteps),
e.dataContext,
JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false
).show(RelativePoint.getSouthOf(e.getData(CONTEXT_COMPONENT) as JComponent))
}
}
private inner class OpenMarketPlaceAction(private val step: String) : DumbAwareAction(Supplier { step }) {
override fun actionPerformed(e: AnActionEvent) {
NewProjectWizardCollector.logPluginSelected(context, step)
val pluginId = PluginId.getId(additionalStepPlugins[step]!!)
val component = e.dataContext.getData(CONTEXT_COMPONENT)!!
if (Registry.`is`("new.project.wizard.modal.plugin.install", false)) {
ProgressManager.getInstance().run(InstallPluginTask(setOf(pluginId), ModalityState.stateForComponent(component)))
}
else {
ShowSettingsUtil.getInstance().editConfigurable(null, PluginManagerConfigurable(), Consumer {
it.openMarketplaceTab("/tag: \"Programming Language\" $step")
})
}
}
}
} | apache-2.0 | 43d53263db3283797e626a816509171c | 44.369048 | 128 | 0.767192 | 4.727047 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/StaticOrderMapper.kt | 1 | 1299 | package org.runestar.client.updater.mapper
import java.lang.reflect.Modifier
abstract class StaticOrderMapper<T>(val position: Int) : Mapper<T>(), InstructionResolver<T> {
override fun match(jar: Jar2): T {
val n = position.takeUnless { it < 0 } ?: position * -1 - 1
val instructions = jar.classes.asSequence()
.flatMap { it.methods.asSequence() }
.filter { Modifier.isStatic(it.access) }
.flatMap { it.instructions }
val relativeInstructions = if (position >= 0) {
instructions
} else {
instructions.toList().asReversed().asSequence()
}
val instructionMatches = relativeInstructions.filter(predicate).toList()
instructionMatches.mapTo(HashSet()) { it.method }.single()
return resolve(instructionMatches[n])
}
abstract val predicate: Predicate<Instruction2>
abstract class Class(position: Int) : StaticOrderMapper<Class2>(position), ElementMatcher.Class, InstructionResolver.Class
abstract class Field(position: Int) : StaticOrderMapper<Field2>(position), ElementMatcher.Field, InstructionResolver.Field
abstract class Method(position: Int) : StaticOrderMapper<Method2>(position), ElementMatcher.Method, InstructionResolver.Method
} | mit | 196cbe9477a781e9f28fe8a313af2292 | 42.333333 | 130 | 0.684373 | 4.639286 | false | false | false | false |
google/intellij-community | plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/UseExpressionBodyIntention.kt | 3 | 5661 | // 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.k2.codeinsight.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.*
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
internal class UseExpressionBodyIntention : AbstractKotlinApplicatorBasedIntention<KtDeclarationWithBody, UseExpressionBodyIntention.Input>(
KtDeclarationWithBody::class,
) {
class Input : KotlinApplicatorInput
override fun getApplicator() = applicator<KtDeclarationWithBody, Input> {
familyAndActionName(KotlinBundle.lazyMessage(("convert.body.to.expression")))
isApplicableByPsi { declaration ->
// Check if either property accessor or named function
if (declaration !is KtNamedFunction && declaration !is KtPropertyAccessor) return@isApplicableByPsi false
// Check if a named function has explicit type
if (declaration is KtNamedFunction && !declaration.hasDeclaredReturnType()) return@isApplicableByPsi false
// Check if function has block with single non-empty KtReturnExpression
val returnedExpression = declaration.singleReturnedExpressionOrNull ?: return@isApplicableByPsi false
// Check if the returnedExpression actually always returns (early return is possible)
// TODO: take into consideration other cases (???)
if (returnedExpression.anyDescendantOfType<KtReturnExpression>(
canGoInside = { it !is KtFunctionLiteral && it !is KtNamedFunction && it !is KtPropertyAccessor })
)
return@isApplicableByPsi false
true
}
applyToWithEditorRequired { declaration, _, _, editor ->
val newFunctionBody = declaration.replaceWithPreservingComments()
editor.correctRightMargin(declaration, newFunctionBody)
if (declaration is KtNamedFunction) editor.selectFunctionColonType(declaration)
}
}
override fun getApplicabilityRange() = applicabilityRanges { declaration: KtDeclarationWithBody ->
val returnExpression = declaration.singleReturnExpressionOrNull ?: return@applicabilityRanges emptyList()
val resultTextRanges = mutableListOf(TextRange(0, returnExpression.returnKeyword.endOffset - declaration.startOffset))
// Adding applicability to the end of the declaration block
val rBraceTextRange = declaration.rBraceOffSetTextRange ?: return@applicabilityRanges resultTextRanges
resultTextRanges.add(rBraceTextRange)
resultTextRanges
}
override fun getInputProvider() = inputProvider<KtDeclarationWithBody, _> { Input() }
override fun skipProcessingFurtherElementsAfter(element: PsiElement) = false
}
private fun KtDeclarationWithBody.replaceWithPreservingComments(): KtExpression {
val bodyBlock = bodyBlockExpression ?: return this
val returnedExpression = singleReturnedExpressionOrNull ?: return this
val commentSaver = CommentSaver(bodyBlock)
val factory = KtPsiFactory(this)
val eq = addBefore(factory.createEQ(), bodyBlockExpression)
addAfter(factory.createWhiteSpace(), eq)
val newBody = bodyBlock.replaced(returnedExpression)
commentSaver.restore(newBody)
return newBody
}
/**
* This function guarantees that the function with its old body replaced by returned expression
* will have this expression placed on the next line to the function's signature or property accessor's 'get() =' statement
* in case it goes beyond IDEA editor's right margin
* @param[declaration] the PSI element used as an anchor, as no indexes are built for newly generated body yet
* @param[newBody] the new "= <returnedExpression>" like body, which replaces the old one
*/
private fun Editor.correctRightMargin(
declaration: KtDeclarationWithBody, newBody: KtExpression
) {
val kotlinFactory = KtPsiFactory(declaration)
val startOffset = newBody.startOffset
val startLine = document.getLineNumber(startOffset)
val rightMargin = settings.getRightMargin(project)
if (document.getLineEndOffset(startLine) - document.getLineStartOffset(startLine) >= rightMargin) {
declaration.addBefore(kotlinFactory.createNewLine(), newBody)
}
}
private fun Editor.selectFunctionColonType(newFunctionBody: KtNamedFunction) {
val colon = newFunctionBody.colon ?: return
val typeReference = newFunctionBody.typeReference ?: return
selectionModel.setSelection(colon.startOffset, typeReference.endOffset)
caretModel.moveToOffset(typeReference.endOffset)
}
private val KtDeclarationWithBody.singleReturnExpressionOrNull: KtReturnExpression?
get() = bodyBlockExpression?.statements?.singleOrNull() as? KtReturnExpression
private val KtDeclarationWithBody.singleReturnedExpressionOrNull: KtExpression?
get() = singleReturnExpressionOrNull?.returnedExpression
private val KtDeclarationWithBody.rBraceOffSetTextRange: TextRange?
get() {
val rightBlockBodyBrace = bodyBlockExpression?.rBrace ?: return null
return rightBlockBodyBrace.textRange.shiftLeft(startOffset)
} | apache-2.0 | 181ae783c97f1cf27966a10ead6d123e | 45.03252 | 158 | 0.762233 | 5.512171 | false | false | false | false |
JetBrains/intellij-community | platform/platform-impl/src/com/intellij/ide/minimap/settings/MinimapConfigurable.kt | 1 | 5252 | // 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.minimap.settings
import com.intellij.ide.minimap.utils.MiniMessagesBundle
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl
import com.intellij.openapi.options.BoundConfigurable
import com.intellij.openapi.ui.ComboBox
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.dsl.builder.bind
import com.intellij.ui.dsl.builder.bindSelected
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.layout.selected
import java.awt.Component
import javax.swing.BoxLayout
import javax.swing.DefaultListCellRenderer
import javax.swing.JList
import javax.swing.JPanel
class MinimapConfigurable : BoundConfigurable(MiniMessagesBundle.message("settings.name")) {
companion object {
const val ID = "com.intellij.minimap"
}
private val state = MinimapSettingsState() // todo remove
private val fileTypes = mutableListOf<String>()
private lateinit var fileTypeComboBox: ComboBox<FileType>
override fun createPanel() = panel {
MinimapSettings.getInstance().state.let {
// todo remove except fileTypes
state.enabled = it.enabled
state.rightAligned = it.rightAligned
state.width = it.width
fileTypes.clear()
fileTypes.addAll(it.fileTypes)
}
lateinit var enabled: JBCheckBox
row {
enabled = checkBox(MiniMessagesBundle.message("settings.enable"))
.applyToComponent {
toolTipText = MiniMessagesBundle.message("settings.enable.hint")
}
.bindSelected(state::enabled)
.component
}
indent {
buttonsGroup {
row(MiniMessagesBundle.message("settings.alignment")) {
radioButton(MiniMessagesBundle.message("settings.left"), false)
radioButton(MiniMessagesBundle.message("settings.right"), true)
}
}.bind(state::rightAligned)
row(MiniMessagesBundle.message("settings.file.types")) {
val textFileTypes = (FileTypeManager.getInstance() as FileTypeManagerImpl).registeredFileTypes
.filter { !it.isBinary && it.defaultExtension.isNotBlank() }.distinctBy { it.defaultExtension }
.sortedBy { it.defaultExtension.lowercase() }
.sortedBy { if (fileTypes.contains(it.defaultExtension)) 0 else 1 }
fileTypeComboBox = comboBox(textFileTypes, FileTypeListCellRenderer())
.applyToComponent {
isSwingPopup = false
addActionListener {
val fileType = fileTypeComboBox.item ?: return@addActionListener
if (!fileTypes.remove(fileType.defaultExtension)) {
fileTypes.add(fileType.defaultExtension)
}
fileTypeComboBox.repaint()
}
}.component
}
}.enabledIf(enabled.selected)
}
override fun isModified(): Boolean {
return super.isModified() || fileTypes != MinimapSettings.getInstance().state.fileTypes
}
override fun apply() {
if (!isModified) {
return
}
super.apply()
state.fileTypes = fileTypes.toList()
val settings = MinimapSettings.getInstance()
val currentState = settings.state
val needToRebuildUI = currentState.rightAligned != state.rightAligned ||
currentState.enabled != state.enabled ||
currentState.fileTypes != state.fileTypes
settings.state = state.copy()
settings.settingsChangeCallback.notify(if (needToRebuildUI)
MinimapSettings.SettingsChangeType.WithUiRebuild
else
MinimapSettings.SettingsChangeType.Normal)
}
override fun reset() {
super.reset()
fileTypes.clear()
fileTypes.addAll(MinimapSettings.getInstance().state.fileTypes)
fileTypeComboBox.repaint()
}
private inner class FileTypeListCellRenderer : DefaultListCellRenderer() {
private val container = JPanel(null)
private val checkBox = JBCheckBox()
init {
isOpaque = false
container.isOpaque = false
checkBox.isOpaque = false
container.layout = BoxLayout(container, BoxLayout.X_AXIS)
container.add(checkBox)
container.add(this)
}
override fun getListCellRendererComponent(list: JList<*>?,
value: Any?,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean): Component {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
if (index == -1) {
checkBox.isVisible = false
text = fileTypes.joinToString(",")
return container
}
checkBox.isVisible = true
val fileType = value as? FileType ?: return container
text = fileType.defaultExtension
icon = fileType.icon
checkBox.isSelected = fileTypes.contains(fileType.defaultExtension)
return container
}
}
} | apache-2.0 | d1aff97064c89025f0f5fe1aee5ca2ec | 34.979452 | 120 | 0.658797 | 5.299697 | false | false | false | false |
StephaneBg/ScoreIt | core/src/main/kotlin/com/sbgapps/scoreit/core/widget/GenericRecyclerViewAdapter.kt | 1 | 1731 | /*
* Copyright 2020 Stéphane Baiget
*
* 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.sbgapps.scoreit.core.widget
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.sbgapps.scoreit.core.ext.inflate
class GenericRecyclerViewAdapter(initialItems: List<ItemAdapter> = emptyList()) :
RecyclerView.Adapter<BaseViewHolder>() {
var items: List<ItemAdapter> = initialItems
private set
fun updateItems(newItems: List<ItemAdapter>, diffResult: DiffUtil.DiffResult? = null) {
items = newItems
diffResult?.dispatchUpdatesTo(this) ?: notifyDataSetChanged()
}
override fun getItemCount(): Int = items.size
override fun getItemViewType(position: Int): Int = items[position].layoutId
override fun onCreateViewHolder(parent: ViewGroup, @LayoutRes layoutId: Int): BaseViewHolder {
val itemView = parent.inflate(layoutId)
return items.first { it.layoutId == layoutId }.onCreateViewHolder(itemView)
}
override fun onBindViewHolder(holder: BaseViewHolder, position: Int) =
items[position].onBindViewHolder(holder)
}
| apache-2.0 | 3da5271756d1968cc8f4e1d2a44d13b1 | 35.808511 | 98 | 0.747977 | 4.688347 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/ProblemFilter.kt | 1 | 2558 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.analysis.problemsView.toolWindow
import com.intellij.analysis.problemsView.Problem
import com.intellij.codeInsight.daemon.impl.SeverityRegistrar
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareToggleAction
import com.intellij.profile.codeInspection.ui.SingleInspectionProfilePanel.renderSeverity
import com.intellij.util.ui.tree.TreeUtil.promiseExpandAll
import org.jetbrains.annotations.Nls
internal class ProblemFilter(val state: ProblemsViewState) : (Problem) -> Boolean {
override fun invoke(problem: Problem): Boolean {
val highlighting = problem as? HighlightingProblem ?: return true
return !(state.hideBySeverity.contains(highlighting.severity))
}
}
internal class SeverityFiltersActionGroup : DumbAware, ActionGroup() {
override fun getChildren(event: AnActionEvent?): Array<AnAction> {
val project = event?.project ?: return AnAction.EMPTY_ARRAY
if (project.isDisposed) return AnAction.EMPTY_ARRAY
val panel = ProblemsView.getSelectedPanel(project) as? HighlightingPanel ?: return AnAction.EMPTY_ARRAY
return SeverityRegistrar.getSeverityRegistrar(project).allSeverities.reversed()
.filter { it != HighlightSeverity.INFO && it > HighlightSeverity.INFORMATION && it < HighlightSeverity.ERROR }
.map {
SeverityFilterAction(ProblemsViewBundle.message("problems.view.highlighting.severity.show", renderSeverity(it)), it.myVal, panel)
}
.toTypedArray()
}
}
private class SeverityFilterAction(@Nls name: String, val severity: Int, val panel: HighlightingPanel) : DumbAwareToggleAction(name) {
override fun isSelected(event: AnActionEvent) = !panel.state.hideBySeverity.contains(severity)
override fun setSelected(event: AnActionEvent, selected: Boolean) {
val changed = with(panel.state.hideBySeverity) { if (selected) remove(severity) else add(severity) }
if (changed) {
val wasEmpty = panel.tree.isEmpty
panel.state.intIncrementModificationCount()
panel.treeModel.structureChanged(null)
panel.powerSaveStateChanged()
// workaround to expand a root without handle
if (wasEmpty) promiseExpandAll(panel.tree)
}
}
}
| apache-2.0 | 100e1a1e1a6ae11ba793173ec9bed89b | 50.16 | 140 | 0.781861 | 4.527434 | false | false | false | false |
allotria/intellij-community | platform/built-in-server/src/org/jetbrains/ide/ToolboxUpdateNotificationHandler.kt | 1 | 1236 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.ide
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.intellij.openapi.Disposable
internal class ToolboxUpdateNotificationHandler : ToolboxServiceHandler<ToolboxUpdateNotificationHandler.UpdateNotification> {
data class UpdateNotification(val version: String, val build: String)
override val requestName: String = "update-notification"
override fun parseRequest(request: JsonElement): UpdateNotification {
require(request.isJsonObject) { "JSON Object was expected" }
val obj = request.asJsonObject
val build = obj["build"]?.asString
val version = obj["version"]?.asString
require(!build.isNullOrBlank()) { "the `build` attribute must not be blank" }
require(!version.isNullOrBlank()) { "the `version` attribute must not be blank" }
return UpdateNotification(version = version, build = build)
}
override fun handleToolboxRequest(lifetime: Disposable, request: UpdateNotification, onResult: (JsonElement) -> Unit) {
onResult(JsonObject().apply { addProperty("status", "not implemented") })
}
}
| apache-2.0 | a878eb9abf320677987286aae91b3634 | 43.142857 | 140 | 0.760518 | 4.560886 | false | false | false | false |
mrlem/happy-cows | core/src/org/mrlem/happycows/ui/screens/splash/SplashScreen.kt | 1 | 2559 | package org.mrlem.happycows.ui.screens.splash
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType
import org.mrlem.happycows.HappyCowsGame
import org.mrlem.happycows.ui.Styles.BACKGROUND_COLOR
import org.mrlem.happycows.ui.Styles.LIGHT_ORANGE_COLOR
import org.mrlem.happycows.ui.Styles.MASK_COLOR
import org.mrlem.happycows.ui.screens.AbstractScreen
private const val GRADIENT_SIZE = 256
/**
* @author Sébastien Guillemin <[email protected]>
*/
class SplashScreen(game: HappyCowsGame) : AbstractScreen(game), SplashNavigation {
private val ui = SplashUi()
private val animations = SplashAnimations(ui, this)
init {
stage = ui
animations.play()
}
///////////////////////////////////////////////////////////////////////////
// Screen implementation
///////////////////////////////////////////////////////////////////////////
override fun doUpdate(delta: Float) {
ui.act(delta)
}
override fun doRender(delta: Float) {
// render top/bottom gradient bars
shapeRenderer.internalRenderer.apply {
begin(ShapeType.Filled)
rect(0f, ui.height / 2 + GRADIENT_SIZE, ui.width, ui.height / 2 - GRADIENT_SIZE, LIGHT_ORANGE_COLOR, LIGHT_ORANGE_COLOR, BACKGROUND_COLOR, BACKGROUND_COLOR)
rect(0f, 0f, ui.width, ui.height / 2 - GRADIENT_SIZE, Color.WHITE, Color.WHITE, LIGHT_ORANGE_COLOR, LIGHT_ORANGE_COLOR)
end()
if (animations.uiAlpha < 1) {
MASK_COLOR.a = 1 - animations.uiAlpha
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA)
Gdx.gl.glEnable(GL20.GL_BLEND)
begin(ShapeType.Filled)
rect(0f, 0f, ui.width, ui.height, MASK_COLOR, MASK_COLOR, MASK_COLOR, MASK_COLOR)
end()
Gdx.gl.glDisable(GL20.GL_BLEND)
}
}
ui.draw()
}
override fun resize(width: Int, height: Int) {
ui.viewport.update(width, height, true)
}
override fun show() {
Gdx.input.isCursorCatched = true
}
override fun hide() {
Gdx.input.isCursorCatched = false
}
///////////////////////////////////////////////////////////////////////////
// Navigation implementation
///////////////////////////////////////////////////////////////////////////
override fun gotoMenu() {
game.screen = game.menuScreen
}
}
| gpl-3.0 | 1b5f09c160b3944ebff3f43c60662b53 | 32.220779 | 168 | 0.566849 | 4.249169 | false | false | false | false |
Kotlin/kotlinx.coroutines | reactive/kotlinx-coroutines-reactor/test/MonoTest.kt | 1 | 12201 | /*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.reactor
import kotlinx.coroutines.*
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.reactive.*
import org.junit.*
import org.junit.Test
import org.reactivestreams.*
import reactor.core.publisher.*
import reactor.util.context.*
import java.time.Duration.*
import java.util.function.*
import kotlin.test.*
class MonoTest : TestBase() {
@Before
fun setup() {
ignoreLostThreads("timer-", "parallel-")
Hooks.onErrorDropped { expectUnreached() }
}
@Test
fun testBasicSuccess() = runBlocking {
expect(1)
val mono = mono(currentDispatcher()) {
expect(4)
"OK"
}
expect(2)
mono.subscribe { value ->
expect(5)
assertEquals("OK", value)
}
expect(3)
yield() // to started coroutine
finish(6)
}
@Test
fun testBasicFailure() = runBlocking {
expect(1)
val mono = mono(currentDispatcher()) {
expect(4)
throw RuntimeException("OK")
}
expect(2)
mono.subscribe({
expectUnreached()
}, { error ->
expect(5)
assertTrue(error is RuntimeException)
assertEquals("OK", error.message)
})
expect(3)
yield() // to started coroutine
finish(6)
}
@Test
fun testBasicEmpty() = runBlocking {
expect(1)
val mono = mono(currentDispatcher()) {
expect(4)
null
}
expect(2)
mono.subscribe({}, { throw it }, {
expect(5)
})
expect(3)
yield() // to started coroutine
finish(6)
}
@Test
fun testBasicUnsubscribe() = runBlocking {
expect(1)
val mono = mono(currentDispatcher()) {
expect(4)
yield() // back to main, will get cancelled
expectUnreached()
}
expect(2)
// nothing is called on a disposed mono
val sub = mono.subscribe({
expectUnreached()
}, {
expectUnreached()
})
expect(3)
yield() // to started coroutine
expect(5)
sub.dispose() // will cancel coroutine
yield()
finish(6)
}
@Test
fun testMonoNoWait() {
val mono = mono {
"OK"
}
checkMonoValue(mono) {
assertEquals("OK", it)
}
}
@Test
fun testMonoAwait() = runBlocking {
assertEquals("OK", Mono.just("O").awaitSingle() + "K")
assertEquals("OK", Mono.just("O").awaitSingleOrNull() + "K")
assertFailsWith<NoSuchElementException>{ Mono.empty<String>().awaitSingle() }
assertNull(Mono.empty<Int>().awaitSingleOrNull())
}
/** Tests that calls to [awaitSingleOrNull] (and, thus, to the rest of such functions) throw [CancellationException]
* and unsubscribe from the publisher when their [Job] is cancelled. */
@Test
fun testAwaitCancellation() = runTest {
expect(1)
val mono = mono { delay(Long.MAX_VALUE) }.doOnSubscribe { expect(3) }.doOnCancel { expect(5) }
val job = launch(start = CoroutineStart.UNDISPATCHED) {
try {
expect(2)
mono.awaitSingleOrNull()
} catch (e: CancellationException) {
expect(6)
throw e
}
}
expect(4)
job.cancelAndJoin()
finish(7)
}
@Test
fun testMonoEmitAndAwait() {
val mono = mono {
Mono.just("O").awaitSingle() + "K"
}
checkMonoValue(mono) {
assertEquals("OK", it)
}
}
@Test
fun testMonoWithDelay() {
val mono = mono {
Flux.just("O").delayElements(ofMillis(50)).awaitSingle() + "K"
}
checkMonoValue(mono) {
assertEquals("OK", it)
}
}
@Test
fun testMonoException() {
val mono = mono {
Flux.just("O", "K").awaitSingle() + "K"
}
checkErroneous(mono) {
assert(it is IllegalArgumentException)
}
}
@Test
fun testAwaitFirst() {
val mono = mono {
Flux.just("O", "#").awaitFirst() + "K"
}
checkMonoValue(mono) {
assertEquals("OK", it)
}
}
@Test
fun testAwaitLast() {
val mono = mono {
Flux.just("#", "O").awaitLast() + "K"
}
checkMonoValue(mono) {
assertEquals("OK", it)
}
}
@Test
fun testExceptionFromFlux() {
val mono = mono {
try {
Flux.error<String>(RuntimeException("O")).awaitFirst()
} catch (e: RuntimeException) {
Flux.just(e.message!!).awaitLast() + "K"
}
}
checkMonoValue(mono) {
assertEquals("OK", it)
}
}
@Test
fun testExceptionFromCoroutine() {
val mono = mono<String> {
throw IllegalStateException(Flux.just("O").awaitSingle() + "K")
}
checkErroneous(mono) {
assert(it is IllegalStateException)
assertEquals("OK", it.message)
}
}
@Test
fun testSuppressedException() = runTest {
val mono = mono(currentDispatcher()) {
launch(start = CoroutineStart.ATOMIC) {
throw TestException() // child coroutine fails
}
try {
delay(Long.MAX_VALUE)
} finally {
throw TestException2() // but parent throws another exception while cleaning up
}
}
try {
mono.awaitSingle()
expectUnreached()
} catch (e: TestException) {
assertTrue(e.suppressed[0] is TestException2)
}
}
@Test
fun testUnhandledException() = runTest {
expect(1)
var subscription: Subscription? = null
val handler = BiFunction<Throwable, Any?, Throwable> { t, _ ->
assertTrue(t is TestException)
expect(5)
t
}
val mono = mono(currentDispatcher()) {
expect(4)
subscription!!.cancel() // cancel our own subscription, so that delay will get cancelled
try {
delay(Long.MAX_VALUE)
} finally {
throw TestException() // would not be able to handle it since mono is disposed
}
}.contextWrite { Context.of("reactor.onOperatorError.local", handler) }
mono.subscribe(object : Subscriber<Unit> {
override fun onSubscribe(s: Subscription) {
expect(2)
subscription = s
}
override fun onNext(t: Unit?) { expectUnreached() }
override fun onComplete() { expectUnreached() }
override fun onError(t: Throwable) { expectUnreached() }
})
expect(3)
yield() // run coroutine
finish(6)
}
@Test
fun testIllegalArgumentException() {
assertFailsWith<IllegalArgumentException> { mono(Job()) { } }
}
@Test
fun testExceptionAfterCancellation() = runTest {
// Test exception is not reported to global handler
Flux
.interval(ofMillis(1))
.switchMap {
mono(coroutineContext) {
timeBomb().awaitSingle()
}
}
.onErrorReturn({
expect(1)
true
}, 42)
.blockLast()
finish(2)
}
private fun timeBomb() = Mono.delay(ofMillis(1)).doOnSuccess { throw Exception("something went wrong") }
@Test
fun testLeakedException() = runBlocking {
// Test exception is not reported to global handler
val flow = mono<Unit> { throw TestException() }.toFlux().asFlow()
repeat(10000) {
combine(flow, flow) { _, _ -> }
.catch {}
.collect { }
}
}
/** Test that cancelling a [mono] due to a timeout does throw an exception. */
@Test
fun testTimeout() {
val mono = mono {
withTimeout(1) { delay(100) }
}
try {
mono.doOnSubscribe { expect(1) }
.doOnNext { expectUnreached() }
.doOnSuccess { expectUnreached() }
.doOnError { expect(2) }
.doOnCancel { expectUnreached() }
.block()
} catch (e: CancellationException) {
expect(3)
}
finish(4)
}
/** Test that when the reason for cancellation of a [mono] is that the downstream doesn't want its results anymore,
* this is considered normal behavior and exceptions are not propagated. */
@Test
fun testDownstreamCancellationDoesNotThrow() = runTest {
var i = 0
/** Attach a hook that handles exceptions from publishers that are known to be disposed of. We don't expect it
* to be fired in this case, as the reason for the publisher in this test to accept an exception is simply
* cancellation from the downstream. */
Hooks.onOperatorError("testDownstreamCancellationDoesNotThrow") { t, a ->
expectUnreached()
t
}
/** A Mono that doesn't emit a value and instead waits indefinitely. */
val mono = mono(Dispatchers.Unconfined) { expect(5 * i + 3); delay(Long.MAX_VALUE) }
.doOnSubscribe { expect(5 * i + 2) }
.doOnNext { expectUnreached() }
.doOnSuccess { expectUnreached() }
.doOnError { expectUnreached() }
.doOnCancel { expect(5 * i + 4) }
val n = 1000
repeat(n) {
i = it
expect(5 * i + 1)
mono.awaitCancelAndJoin()
expect(5 * i + 5)
}
finish(5 * n + 1)
Hooks.resetOnOperatorError("testDownstreamCancellationDoesNotThrow")
}
/** Test that, when [Mono] is cancelled by the downstream and throws during handling the cancellation, the resulting
* error is propagated to [Hooks.onOperatorError]. */
@Test
fun testRethrowingDownstreamCancellation() = runTest {
var i = 0
/** Attach a hook that handles exceptions from publishers that are known to be disposed of. We expect it
* to be fired in this case. */
Hooks.onOperatorError("testDownstreamCancellationDoesNotThrow") { t, a ->
expect(i * 6 + 5)
t
}
/** A Mono that doesn't emit a value and instead waits indefinitely, and, when cancelled, throws. */
val mono = mono(Dispatchers.Unconfined) {
expect(i * 6 + 3)
try {
delay(Long.MAX_VALUE)
} catch (e: CancellationException) {
throw TestException()
}
}
.doOnSubscribe { expect(i * 6 + 2) }
.doOnNext { expectUnreached() }
.doOnSuccess { expectUnreached() }
.doOnError { expectUnreached() }
.doOnCancel { expect(i * 6 + 4) }
val n = 1000
repeat(n) {
i = it
expect(i * 6 + 1)
mono.awaitCancelAndJoin()
expect(i * 6 + 6)
}
finish(n * 6 + 1)
Hooks.resetOnOperatorError("testDownstreamCancellationDoesNotThrow")
}
/** Run the given [Mono], cancel it, wait for the cancellation handler to finish, and return only then.
*
* Will not work in the general case, but here, when the publisher uses [Dispatchers.Unconfined], this seems to
* ensure that the cancellation handler will have nowhere to execute but serially with the cancellation. */
private suspend fun <T> Mono<T>.awaitCancelAndJoin() = coroutineScope {
async(start = CoroutineStart.UNDISPATCHED) {
awaitSingleOrNull()
}.cancelAndJoin()
}
}
| apache-2.0 | 12e03e8097f2d692dc62e8b1e8c6173c | 28.977887 | 120 | 0.537005 | 4.814917 | false | true | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/SequencePresentation.kt | 1 | 3896 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hints.presentation
import com.intellij.codeInsight.hints.dimension
import com.intellij.openapi.editor.markup.TextAttributes
import java.awt.Dimension
import java.awt.Graphics2D
import java.awt.Point
import java.awt.Rectangle
import java.awt.event.MouseEvent
class SequencePresentation(val presentations: List<InlayPresentation>) : BasePresentation() {
init {
if (presentations.isEmpty()) throw IllegalArgumentException()
for (presentation in presentations) {
presentation.addListener(InternalListener(presentation))
}
}
fun calcDimensions() {
width = presentations.sumBy { it.width }
height = presentations.maxBy { it.height }!!.height
}
override var width: Int = 0
override var height: Int = 0
init {
calcDimensions()
}
private var presentationUnderCursor: InlayPresentation? = null
override fun paint(g: Graphics2D, attributes: TextAttributes) {
var xOffset = 0
try {
for (presentation in presentations) {
presentation.paint(g, attributes)
xOffset += presentation.width
g.translate(presentation.width, 0)
}
}
finally {
g.translate(-xOffset, 0)
}
}
private fun handleMouse(
original: Point,
action: (InlayPresentation, Point) -> Unit
) {
val x = original.x
val y = original.y
if (x < 0 || x >= width || y < 0 || y >= height) return
var xOffset = 0
for (presentation in presentations) {
val presentationWidth = presentation.width
if (x < xOffset + presentationWidth) {
val translated = original.translateNew(-xOffset, 0)
action(presentation, translated)
return
}
xOffset += presentationWidth
}
}
override fun mouseClicked(event: MouseEvent, translated: Point) {
handleMouse(translated) { presentation, point ->
presentation.mouseClicked(event, point)
}
}
override fun mouseMoved(event: MouseEvent, translated: Point) {
handleMouse(translated) { presentation, point ->
if (presentation != presentationUnderCursor) {
presentationUnderCursor?.mouseExited()
presentationUnderCursor = presentation
}
presentation.mouseMoved(event, point)
}
}
override fun mouseExited() {
try {
presentationUnderCursor?.mouseExited()
}
finally {
presentationUnderCursor = null
}
}
override fun updateState(previousPresentation: InlayPresentation): Boolean {
if (previousPresentation !is SequencePresentation) return true
if (previousPresentation.presentations.size != presentations.size) return true
val previousPresentations = previousPresentation.presentations
var changed = false
for ((index, presentation) in presentations.withIndex()) {
if (presentation.updateState(previousPresentations[index])) {
changed = true
}
}
return changed
}
override fun toString(): String = presentations.joinToString(" ", "[", "]") { "$it" }
inner class InternalListener(private val currentPresentation: InlayPresentation) : PresentationListener {
override fun contentChanged(area: Rectangle) {
area.add(shiftOfCurrent(), 0)
[email protected](area)
}
override fun sizeChanged(previous: Dimension, current: Dimension) {
val old = dimension()
calcDimensions()
val new = dimension()
[email protected](old, new)
}
private fun shiftOfCurrent(): Int {
var shift = 0
for (presentation in presentations) {
if (presentation === currentPresentation) {
return shift
}
shift += presentation.width
}
throw IllegalStateException()
}
}
} | apache-2.0 | a8dfdfbbcd0395b0c9fd634737b08613 | 28.748092 | 140 | 0.684292 | 4.77451 | false | false | false | false |
leafclick/intellij-community | java/java-indexing-impl/src/com/intellij/psi/impl/JavaSimplePropertyIndex.kt | 1 | 9983 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.lang.LighterASTNode
import com.intellij.lang.java.JavaParserDefinition
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.JavaTokenType
import com.intellij.psi.PsiField
import com.intellij.psi.impl.cache.RecordUtil
import com.intellij.psi.impl.source.JavaLightStubBuilder
import com.intellij.psi.impl.source.JavaLightTreeUtil
import com.intellij.psi.impl.source.PsiMethodImpl
import com.intellij.psi.impl.source.tree.ElementType
import com.intellij.psi.impl.source.tree.JavaElementType
import com.intellij.psi.impl.source.tree.LightTreeUtil
import com.intellij.psi.impl.source.tree.RecursiveLighterASTNodeWalkingVisitor
import com.intellij.psi.stub.JavaStubImplUtil
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.PropertyUtil
import com.intellij.psi.util.PropertyUtilBase
import com.intellij.util.indexing.*
import com.intellij.util.io.DataExternalizer
import com.intellij.util.io.DataInputOutputUtil
import com.intellij.util.io.EnumeratorStringDescriptor
import gnu.trove.TIntObjectHashMap
import java.io.DataInput
import java.io.DataOutput
private val indexId = ID.create<Int, TIntObjectHashMap<PropertyIndexValue>>("java.simple.property")
private object EmptyTIntObjectHashMap : TIntObjectHashMap<PropertyIndexValue>() {
override fun put(key: Int, value: PropertyIndexValue?)= throw UnsupportedOperationException()
}
fun getFieldOfGetter(method: PsiMethodImpl): PsiField? = resolveFieldFromIndexValue(method, true)
fun getFieldOfSetter(method: PsiMethodImpl): PsiField? = resolveFieldFromIndexValue(method, false)
private fun resolveFieldFromIndexValue(method: PsiMethodImpl, isGetter: Boolean): PsiField? {
val id = JavaStubImplUtil.getMethodStubIndex(method)
if (id != -1) {
val virtualFile = method.containingFile.virtualFile
val data = FileBasedIndex.getInstance().getFileData(indexId, virtualFile, method.project)
return data.values.firstOrNull()?.get(id)?.let { indexValue ->
if (isGetter != indexValue.getter) return null
val psiClass = method.containingClass
val project = psiClass!!.project
val expr = JavaPsiFacade.getElementFactory(project).createExpressionFromText(indexValue.propertyRefText, psiClass)
return PropertyUtil.getSimplyReturnedField(expr)
}
}
return null
}
data class PropertyIndexValue(val propertyRefText: String, val getter: Boolean)
class JavaSimplePropertyIndex : SingleEntryFileBasedIndexExtension<TIntObjectHashMap<PropertyIndexValue>>() {
private val allowedExpressions by lazy {
TokenSet.create(ElementType.REFERENCE_EXPRESSION, ElementType.THIS_EXPRESSION, ElementType.SUPER_EXPRESSION)
}
override fun getIndexer(): SingleEntryIndexer<TIntObjectHashMap<PropertyIndexValue>> = object : SingleEntryIndexer<TIntObjectHashMap<PropertyIndexValue>>(false) {
override fun computeValue(inputData: FileContent): TIntObjectHashMap<PropertyIndexValue>? {
var result: TIntObjectHashMap<PropertyIndexValue>? = null
val tree = (inputData as PsiDependentFileContent).lighterAST
object : RecursiveLighterASTNodeWalkingVisitor(tree) {
var methodIndex = 0
override fun visitNode(element: LighterASTNode) {
if (JavaLightStubBuilder.isCodeBlockWithoutStubs(element)) return
if (element.tokenType === JavaElementType.METHOD) {
extractProperty(element)?.let {
if (result == null) {
result = TIntObjectHashMap<PropertyIndexValue>()
}
result!!.put(methodIndex, it)
}
methodIndex++
}
super.visitNode(element)
}
private fun extractProperty(method: LighterASTNode): PropertyIndexValue? {
var isConstructor = true
var isGetter = true
var isBooleanReturnType = false
var isVoidReturnType = false
var setterParameterName: String? = null
var refText: String? = null
for (child in tree.getChildren(method)) {
when (child.tokenType) {
JavaElementType.TYPE -> {
val children = tree.getChildren(child)
if (children.size != 1) return null
val typeElement = children[0]
if (typeElement.tokenType == JavaTokenType.VOID_KEYWORD) isVoidReturnType = true
if (typeElement.tokenType == JavaTokenType.BOOLEAN_KEYWORD) isBooleanReturnType = true
isConstructor = false
}
JavaElementType.PARAMETER_LIST -> {
if (isGetter) {
if (LightTreeUtil.firstChildOfType(tree, child, JavaElementType.PARAMETER) != null) return null
} else {
val parameters = LightTreeUtil.getChildrenOfType(tree, child, JavaElementType.PARAMETER)
if (parameters.size != 1) return null
setterParameterName = JavaLightTreeUtil.getNameIdentifierText(tree, parameters[0])
if (setterParameterName == null) return null
}
}
JavaElementType.CODE_BLOCK -> {
refText = if (isGetter) getGetterPropertyRefText(child) else getSetterPropertyRefText(child, setterParameterName!!)
if (refText == null) return null
}
JavaTokenType.IDENTIFIER -> {
if (isConstructor) return null
val name = RecordUtil.intern(tree.charTable, child)
val flavour = PropertyUtil.getMethodNameGetterFlavour(name)
when (flavour) {
PropertyUtilBase.GetterFlavour.NOT_A_GETTER -> {
if (PropertyUtil.isSetterName(name)) {
isGetter = false
}
else {
return null
}
}
PropertyUtilBase.GetterFlavour.BOOLEAN -> if (!isBooleanReturnType) return null
else -> { }
}
if (isVoidReturnType && isGetter) return null
}
}
}
return refText?.let { PropertyIndexValue(it, isGetter) }
}
private fun getSetterPropertyRefText(codeBlock: LighterASTNode, setterParameterName: String): String? {
val assignment = tree
.getChildren(codeBlock)
.singleOrNull { ElementType.JAVA_STATEMENT_BIT_SET.contains(it.tokenType) }
?.takeIf { it.tokenType == JavaElementType.EXPRESSION_STATEMENT }
?.let { LightTreeUtil.firstChildOfType(tree, it, JavaElementType.ASSIGNMENT_EXPRESSION) }
if (assignment == null || LightTreeUtil.firstChildOfType(tree, assignment, JavaTokenType.EQ) == null) return null
val operands = LightTreeUtil.getChildrenOfType(tree, assignment, ElementType.EXPRESSION_BIT_SET)
if (operands.size != 2 || LightTreeUtil.toFilteredString(tree, operands[1], null) != setterParameterName) return null
val lhsText = LightTreeUtil.toFilteredString(tree, operands[0], null)
if (lhsText == setterParameterName) return null
return lhsText
}
private fun getGetterPropertyRefText(codeBlock: LighterASTNode): String? {
return tree
.getChildren(codeBlock)
.singleOrNull { ElementType.JAVA_STATEMENT_BIT_SET.contains(it.tokenType) }
?.takeIf { it.tokenType == JavaElementType.RETURN_STATEMENT}
?.let { LightTreeUtil.firstChildOfType(tree, it, allowedExpressions) }
?.takeIf(this::checkQualifiers)
?.let { LightTreeUtil.toFilteredString(tree, it, null) }
}
private fun checkQualifiers(expression: LighterASTNode): Boolean {
if (!allowedExpressions.contains(expression.tokenType)) {
return false
}
val qualifier = JavaLightTreeUtil.findExpressionChild(tree, expression)
return qualifier == null || checkQualifiers(qualifier)
}
}.visitNode(tree.root)
return result
}
}
override fun getValueExternalizer(): DataExternalizer<TIntObjectHashMap<PropertyIndexValue>> = object: DataExternalizer<TIntObjectHashMap<PropertyIndexValue>> {
override fun save(out: DataOutput, values: TIntObjectHashMap<PropertyIndexValue>) {
DataInputOutputUtil.writeINT(out, values.size())
values.forEachEntry { id, value ->
DataInputOutputUtil.writeINT(out, id)
EnumeratorStringDescriptor.INSTANCE.save(out, value.propertyRefText)
out.writeBoolean(value.getter)
return@forEachEntry true
}
}
override fun read(input: DataInput): TIntObjectHashMap<PropertyIndexValue> {
val size = DataInputOutputUtil.readINT(input)
if (size == 0) return EmptyTIntObjectHashMap
val values = TIntObjectHashMap<PropertyIndexValue>(size)
repeat(size) {
val id = DataInputOutputUtil.readINT(input)
val value = PropertyIndexValue(EnumeratorStringDescriptor.INSTANCE.read(input), input.readBoolean())
values.put(id, value)
}
return values
}
}
override fun getName(): ID<Int, TIntObjectHashMap<PropertyIndexValue>> = indexId
override fun getInputFilter(): FileBasedIndex.InputFilter = object : DefaultFileTypeSpecificInputFilter(JavaFileType.INSTANCE) {
override fun acceptInput(file: VirtualFile): Boolean = JavaParserDefinition.JAVA_FILE.shouldBuildStubFor(file)
}
override fun getVersion(): Int = 3
} | apache-2.0 | 83c3c933ecc99fecbab4d43503ba236d | 46.09434 | 164 | 0.672343 | 5.404981 | false | false | false | false |