repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mdaniel/intellij-community | tools/ideTestingFramework/intellij.tools.ide.starter/src/com/intellij/ide/starter/community/ProductInfoRequestParameters.kt | 1 | 740 | package com.intellij.ide.starter.community
import org.apache.http.client.utils.URIBuilder
data class ProductInfoRequestParameters(
val code: String,
val type: String = "release",
// e.g "2022.2"
val majorVersion: String = "",
// e.g "221.5591.52",
val build: String = "",
// e.g "2022.1.1"
val version: String = ""
) {
fun toUriQuery(): URIBuilder {
val builder = URIBuilder()
// API seems to filter only by code and type. It doesn't respond to majorVersion, build or version params
if (code.isNotBlank()) builder.addParameter("code", code)
if (type.isNotBlank()) builder.addParameter("type", type)
return builder
}
override fun toString(): String {
return toUriQuery().toString()
}
}
| apache-2.0 | b100a15c63d36f003dc73d34c45ec129 | 24.517241 | 109 | 0.671622 | 3.756345 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/gradle/gradle-tooling/impl/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinDependencyMapper.kt | 2 | 939 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleTooling
import org.jetbrains.kotlin.idea.projectModel.KotlinDependencyId
class KotlinDependencyMapper {
private var currentIndex: KotlinDependencyId = 0
private val idToDependency = HashMap<KotlinDependencyId, KotlinDependency>()
private val dependencyToId = HashMap<KotlinDependency, KotlinDependencyId>()
fun getDependency(id: KotlinDependencyId) = idToDependency[id]
fun getId(dependency: KotlinDependency): KotlinDependencyId {
return dependencyToId[dependency] ?: let {
currentIndex++
dependencyToId[dependency] = currentIndex
idToDependency[currentIndex] = dependency
return currentIndex
}
}
fun toDependencyMap(): Map<KotlinDependencyId, KotlinDependency> = idToDependency
} | apache-2.0 | 85557e00fcb91d3678ca2ee34e4b7e62 | 39.869565 | 120 | 0.744409 | 5.760736 | false | false | false | false |
jk1/intellij-community | plugins/stats-collector/src/com/intellij/stats/completion/CompletionFileLoggerProvider.kt | 2 | 1861 | /*
* 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 com.intellij.stats.completion
import com.intellij.openapi.components.ApplicationComponent
import com.intellij.stats.logger.EventLoggerWithValidation
import com.intellij.stats.logger.LogFileManager
import com.intellij.stats.logger.ClientSessionValidator
import com.intellij.stats.storage.FilePathProvider
import java.util.*
class CompletionFileLoggerProvider(
filePathProvider: FilePathProvider,
private val installationIdProvider: InstallationIdProvider
) : ApplicationComponent, CompletionLoggerProvider() {
private val logFileManager = LogFileManager(filePathProvider)
private val eventLogger = EventLoggerWithValidation(logFileManager, ClientSessionValidator())
override fun disposeComponent() {
eventLogger.dispose()
logFileManager.flush()
}
override fun newCompletionLogger(): CompletionLogger {
val installationUID = installationIdProvider.installationId()
val completionUID = UUID.randomUUID().toString()
return CompletionFileLogger(installationUID.shortedUUID(), completionUID.shortedUUID(), eventLogger)
}
}
private fun String.shortedUUID(): String {
val start = this.lastIndexOf('-')
if (start > 0 && start + 1 < this.length) {
return this.substring(start + 1)
}
return this
} | apache-2.0 | 768c0c203f36c1c1662f6c1cc3ba8faf | 35.509804 | 104 | 0.77324 | 4.640898 | false | false | false | false |
SpineEventEngine/base | base/src/main/kotlin/io/spine/protobuf/DescriptorExtensions.kt | 1 | 2825 | /*
* Copyright 2022, TeamDev. 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
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@file:JvmName("DescriptorExtensions")
package io.spine.protobuf
import com.google.protobuf.Descriptors.FileDescriptor
import com.google.protobuf.ExtensionRegistry
import io.spine.code.java.ClassName
/**
* A [binary][ClassName.binaryName] name of the outer Java class associated with this file.
*/
public val FileDescriptor.outerClassName: String
get() {
val outerClass = ClassName.outerClass(this)
return outerClass.binaryName()
}
/**
* An outer Java class associated with this proto file, if such a class already exists.
* Otherwise, returns `null`.
*/
public val FileDescriptor.outerClass: Class<*>?
get() {
return try {
val classLoader = javaClass.classLoader
val outerClass = classLoader.loadClass(outerClassName)
outerClass
} catch (ignored: ClassNotFoundException) {
null
}
}
/**
* Reflectively calls the static `registerAllExtensions(..)` method, such as
* [io.spine.option.OptionsProto.registerAllExtensions], on the [outerClass] generated for
* this Protobuf file with the custom options declared.
*
* @throws IllegalStateException
* if the outer class for this proto file does not exist
*/
public fun FileDescriptor.registerAllExtensions(registry: ExtensionRegistry) {
check(outerClass != null) {
"The outer class `$outerClassName` for the file `$name` does not exist."
}
val method = outerClass!!.getDeclaredMethod(
"registerAllExtensions", ExtensionRegistry::class.java
)
method.invoke(null, registry)
}
| apache-2.0 | ec6e1e0e184899b8d86ee638e4be8c50 | 36.666667 | 91 | 0.726372 | 4.51278 | false | false | false | false |
marius-m/wt4 | app/src/main/java/lt/markmerkk/widgets/tickets/TicketBasicSearchWidget.kt | 1 | 7692 | package lt.markmerkk.widgets.tickets
import com.jfoenix.controls.JFXButton
import com.jfoenix.controls.JFXTextField
import com.jfoenix.svg.SVGGlyph
import javafx.beans.property.SimpleStringProperty
import javafx.geometry.Pos
import javafx.scene.Parent
import javafx.scene.control.TableView
import javafx.scene.input.KeyCode
import javafx.scene.layout.Priority
import javafx.scene.paint.Color
import lt.markmerkk.*
import lt.markmerkk.entities.Ticket
import lt.markmerkk.events.EventMainCloseTickets
import lt.markmerkk.events.EventSuggestTicket
import lt.markmerkk.mvp.HostServicesInteractor
import lt.markmerkk.tickets.TicketApi
import lt.markmerkk.tickets.TicketLoaderBasic
import lt.markmerkk.ui_2.views.ContextMenuTicketSelect
import lt.markmerkk.ui_2.views.cfxPrefixSelectionComboBox
import lt.markmerkk.ui_2.views.jfxButton
import lt.markmerkk.ui_2.views.jfxTextField
import lt.markmerkk.utils.AccountAvailablility
import org.controlsfx.control.PrefixSelectionComboBox
import rx.observables.JavaFxObservable
import tornadofx.*
import javax.inject.Inject
class TicketBasicSearchWidget: Fragment(), TicketLoaderBasic.Listener {
@Inject lateinit var ticketStorage: TicketStorage
@Inject lateinit var ticketApi: TicketApi
@Inject lateinit var timeProvider: TimeProvider
@Inject lateinit var graphics: Graphics<SVGGlyph>
@Inject lateinit var userSettings: UserSettings
@Inject lateinit var eventBus: WTEventBus
@Inject lateinit var schedulerProvider: SchedulerProvider
@Inject lateinit var hostServicesInteractor: HostServicesInteractor
@Inject lateinit var accountAvailablility: AccountAvailablility
init {
Main.component().inject(this)
}
private lateinit var viewTextFieldTicketSearch: JFXTextField
private lateinit var viewProgress: TicketProgressWidget
private lateinit var viewTable: TableView<TicketViewModelBasic>
private lateinit var viewButtonClear: JFXButton
private val ticketViewModels = mutableListOf<TicketViewModelBasic>()
.asObservable()
private val contextMenuTicketSelect: ContextMenuTicketSelect = ContextMenuTicketSelect(
graphics = graphics,
eventBus = eventBus,
hostServicesInteractor = hostServicesInteractor,
accountAvailablility = accountAvailablility
)
private lateinit var ticketLoaderBasic: TicketLoaderBasic
override val root: Parent = borderpane {
// setOnKeyReleased { keyEvent ->
// if (keyEvent.code == KeyCode.ENTER) {
// val selectTicket = viewTable.selectionModel.selectedItems.firstOrNull()?.ticket
// if (selectTicket != null) {
// eventBus.post(EventSuggestTicket(selectTicket))
// eventBus.post(EventMainCloseTickets())
// }
// }
// }
addClass(Styles.sidePanelContainer)
top {
label("Tickets") {
addClass(Styles.sidePanelHeader)
}
}
center {
vbox(spacing = 4) {
hbox(spacing = 4) {
viewTextFieldTicketSearch = jfxTextField {
hgrow = Priority.ALWAYS
addClass(Styles.inputTextField)
focusColor = Styles.cActiveRed
isLabelFloat = true
promptText = "Ticket search by project code or description"
}
viewButtonClear = jfxButton {
graphic = graphics.from(Glyph.CLEAR, Color.BLACK, 12.0)
setOnAction {
viewTextFieldTicketSearch.text = ""
viewTextFieldTicketSearch.requestFocus()
}
isFocusTraversable = false
}
viewProgress = find<TicketProgressWidget>() {}
viewProgress.viewButtonStop.setOnAction {
// TicketSideDrawerWidget.logger.debug("Trigger stop fetch")
// presenter.stopFetch()
}
viewProgress.viewButtonStop.isFocusTraversable = false
viewProgress.viewButtonRefresh.setOnAction {
// TicketSideDrawerWidget.logger.debug("Trigger fetching ")
// presenter.fetchTickets(
// forceFetch = true,
// filter = viewTextFieldTicketSearch.text,
// projectCode = viewComboProjectCodes.selectionModel.selectedItem ?: ""
// )
}
viewProgress.viewButtonRefresh.isFocusTraversable = false
add(viewProgress)
}
viewTable = tableview(ticketViewModels) {
contextMenu = contextMenuTicketSelect.root
hgrow = Priority.ALWAYS
vgrow = Priority.ALWAYS
setOnMouseClicked { mouseEvent ->
val selectTicket = viewTable.selectionModel.selectedItems.firstOrNull()?.ticket
if (mouseEvent.clickCount >= 2 && selectTicket != null) {
eventBus.post(EventSuggestTicket(selectTicket))
eventBus.post(EventMainCloseTickets())
}
}
columnResizePolicy = TableView.CONSTRAINED_RESIZE_POLICY
readonlyColumn("Description", TicketViewModelBasic::description) { }
}
label("For more options - press secondary button on the ticket") {
addClass(Styles.labelMini)
}
}
}
bottom {
hbox(alignment = Pos.CENTER_RIGHT, spacing = 4) {
addClass(Styles.dialogContainerActionsButtons)
jfxButton("Filter".toUpperCase()) {
setOnAction {
find<TicketFilterSettingsWidget>()
.openModal()
}
}
jfxButton("Close".toUpperCase()) {
setOnAction {
eventBus.post(EventMainCloseTickets())
}
}
}
}
}
override fun onDock() {
super.onDock()
ticketLoaderBasic = TicketLoaderBasic(
listener = this,
ticketStorage = ticketStorage,
ticketApi = ticketApi,
timeProvider = timeProvider,
userSettings = userSettings,
ioScheduler = schedulerProvider.io(),
uiScheduler = schedulerProvider.ui()
)
ticketLoaderBasic.onAttach()
val filterChangeStream = JavaFxObservable.valuesOf(viewTextFieldTicketSearch.textProperty())
ticketLoaderBasic
.changeFilterStream(filterChangeStream)
ticketLoaderBasic.loadTickets(inputFilter = "")
}
override fun onUndock() {
ticketLoaderBasic.onDetach()
super.onUndock()
}
override fun onLoadStart() { }
override fun onLoadFinish() { }
override fun onFoundTickets(tickets: List<Ticket>) {
ticketViewModels.clear()
val ticketVms = tickets
.map { TicketViewModelBasic(it) }
ticketViewModels.addAll(ticketVms)
}
override fun onNoTickets() {
ticketViewModels.clear()
}
override fun onError(throwable: Throwable) {
ticketViewModels.clear()
}
} | apache-2.0 | f39231fed0d8b29b039713ec08e56820 | 39.277487 | 103 | 0.596464 | 5.409283 | false | false | false | false |
oldergod/android-architecture | app/src/main/java/com/example/android/architecture/blueprints/todoapp/statistics/StatisticsFragment.kt | 1 | 4576 | /*
* Copyright 2016, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp.statistics
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.example.android.architecture.blueprints.todoapp.R
import com.example.android.architecture.blueprints.todoapp.mvibase.MviIntent
import com.example.android.architecture.blueprints.todoapp.mvibase.MviView
import com.example.android.architecture.blueprints.todoapp.mvibase.MviViewModel
import com.example.android.architecture.blueprints.todoapp.mvibase.MviViewState
import com.example.android.architecture.blueprints.todoapp.util.ToDoViewModelFactory
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import kotlin.LazyThreadSafetyMode.NONE
/**
* Main UI for the statistics screen.
*/
class StatisticsFragment : Fragment(), MviView<StatisticsIntent, StatisticsViewState> {
private lateinit var statisticsTV: TextView
// Used to manage the data flow lifecycle and avoid memory leak.
private val disposables: CompositeDisposable = CompositeDisposable()
private val viewModel: StatisticsViewModel by lazy(NONE) {
ViewModelProviders
.of(this, ToDoViewModelFactory.getInstance(context!!))
.get(StatisticsViewModel::class.java)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.statistics_frag, container, false)
.also { statisticsTV = it.findViewById(R.id.statistics) }
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
bind()
}
/**
* Connect the [MviView] with the [MviViewModel].
* We subscribe to the [MviViewModel] before passing it the [MviView]'s [MviIntent]s.
* If we were to pass [MviIntent]s to the [MviViewModel] before listening to it,
* emitted [MviViewState]s could be lost.
*/
private fun bind() {
// Subscribe to the ViewModel and call render for every emitted state
disposables.add(
viewModel.states().subscribe { this.render(it) }
)
// Pass the UI's intents to the ViewModel
viewModel.processIntents(intents())
}
override fun onDestroy() {
super.onDestroy()
disposables.dispose()
}
override fun intents(): Observable<StatisticsIntent> = initialIntent()
/**
* The initial Intent the [MviView] emit to convey to the [MviViewModel]
* that it is ready to receive data.
* This initial Intent is also used to pass any parameters the [MviViewModel] might need
* to render the initial [MviViewState] (e.g. the task id to load).
*/
private fun initialIntent(): Observable<StatisticsIntent> {
return Observable.just(StatisticsIntent.InitialIntent)
}
override fun render(state: StatisticsViewState) {
if (state.isLoading) statisticsTV.text = getString(R.string.loading)
if (state.error != null) {
statisticsTV.text = resources.getString(R.string.statistics_error)
}
if (state.error == null && !state.isLoading) {
showStatistics(state.activeCount, state.completedCount)
}
}
private fun showStatistics(numberOfActiveTasks: Int, numberOfCompletedTasks: Int) {
if (numberOfCompletedTasks == 0 && numberOfActiveTasks == 0) {
statisticsTV.text = resources.getString(R.string.statistics_no_tasks)
} else {
val displayString = (resources.getString(R.string.statistics_active_tasks)
+ " "
+ numberOfActiveTasks
+ "\n"
+ resources.getString(R.string.statistics_completed_tasks)
+ " "
+ numberOfCompletedTasks)
statisticsTV.text = displayString
}
}
companion object {
operator fun invoke(): StatisticsFragment = StatisticsFragment()
}
}
| apache-2.0 | 487d6c0ee6d6234caea580f1f7fd3e33 | 35.903226 | 90 | 0.736014 | 4.4 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/i18n/actions/ConvertToTranslationAction.kt | 1 | 1327 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.i18n.actions
import com.demonwav.mcdev.i18n.intentions.ConvertToTranslationIntention
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.psi.PsiLiteral
class ConvertToTranslationAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val file = e.getData(LangDataKeys.PSI_FILE) ?: return
val editor = e.getData(PlatformDataKeys.EDITOR) ?: return
val element = file.findElementAt(editor.caretModel.offset) ?: return
ConvertToTranslationIntention().invoke(editor.project ?: return, editor, element)
}
override fun update(e: AnActionEvent) {
val file = e.getData(LangDataKeys.PSI_FILE)
val editor = e.getData(PlatformDataKeys.EDITOR)
if (file == null || editor == null) {
e.presentation.isEnabled = false
return
}
val element = file.findElementAt(editor.caretModel.offset)
e.presentation.isEnabled = (element?.parent as? PsiLiteral)?.value is String
}
}
| mit | 9b6e9a9da422d7fe219c8fe73a10543e | 33.921053 | 89 | 0.718161 | 4.379538 | false | false | false | false |
google/ground-android | ground/src/main/java/com/google/android/ground/system/NotificationManager.kt | 1 | 2927 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.system
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import com.google.android.ground.R
import com.google.android.ground.persistence.remote.TransferProgress.UploadState
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton
private const val CHANNEL_ID = "channel_id"
private const val CHANNEL_NAME = "sync channel"
@Singleton
class NotificationManager
@Inject
internal constructor(@param:ApplicationContext private val context: Context) {
init {
if (VERSION.SDK_INT >= VERSION_CODES.O) {
createNotificationChannels(context)
}
}
@RequiresApi(api = VERSION_CODES.O)
private fun createNotificationChannels(context: Context) {
val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW)
context.getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
}
fun createSyncNotification(
state: UploadState,
title: String,
total: Int,
progress: Int
): Notification {
val notification =
NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_sync)
.setContentTitle(title)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setOnlyAlertOnce(false)
.setOngoing(false)
.setProgress(total, progress, false)
when (state) {
UploadState.STARTING -> notification.setContentText(context.getString(R.string.starting))
UploadState.IN_PROGRESS ->
notification
.setContentText(
context.getString(R.string.in_progress)
) // only alert once and don't allow cancelling it
.setOnlyAlertOnce(true)
.setOngoing(true)
UploadState.PAUSED -> notification.setContentText(context.getString(R.string.paused))
UploadState.FAILED -> notification.setContentText(context.getString(R.string.failed))
UploadState.COMPLETED -> notification.setContentText(context.getString(R.string.completed))
}
return notification.build()
}
}
| apache-2.0 | 8bd225529b96f9e99709063e6332d9cf | 35.135802 | 99 | 0.748206 | 4.489264 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/views/WikiArticleCardView.kt | 1 | 2396 | package org.wikipedia.views
import android.content.Context
import android.net.Uri
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.util.Pair
import org.wikipedia.databinding.ViewWikiArticleCardBinding
import org.wikipedia.page.PageTitle
import org.wikipedia.settings.Prefs
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.L10nUtil
import org.wikipedia.util.StringUtil
import org.wikipedia.util.TransitionUtil
class WikiArticleCardView constructor(context: Context, attrs: AttributeSet? = null) : ConstraintLayout(context, attrs) {
val binding = ViewWikiArticleCardBinding.inflate(LayoutInflater.from(context), this)
fun setTitle(title: String) {
binding.articleTitle.text = StringUtil.fromHtml(title)
}
fun setDescription(description: String?) {
binding.articleDescription.text = description
}
fun getImageView(): FaceAndColorDetectImageView {
return binding.articleImage
}
fun setExtract(extract: String?, maxLines: Int) {
binding.articleExtract.text = StringUtil.fromHtml(extract)
binding.articleExtract.maxLines = maxLines
}
fun getSharedElements(): Array<Pair<View, String>> {
return TransitionUtil.getSharedElements(context, binding.articleTitle, binding.articleDescription, binding.articleImage)
}
fun setImageUri(uri: Uri?, hideInLandscape: Boolean = true) {
if (uri == null || (DimenUtil.isLandscape(context) && hideInLandscape) || !Prefs.isImageDownloadEnabled()) {
binding.articleImageContainer.visibility = GONE
} else {
binding.articleImageContainer.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT,
DimenUtil.leadImageHeightForDevice(context) - DimenUtil.getToolbarHeightPx(context))
binding.articleImageContainer.visibility = VISIBLE
binding.articleImage.loadImage(uri)
}
}
fun prepareForTransition(title: PageTitle) {
setImageUri(if (title.thumbUrl.isNullOrEmpty()) null else Uri.parse(title.thumbUrl))
setTitle(title.displayText)
setDescription(title.description)
binding.articleDivider.visibility = View.GONE
L10nUtil.setConditionalLayoutDirection(this, title.wikiSite.languageCode())
}
}
| apache-2.0 | 55586ee1ff3f5cd90da70b70a3959c1d | 38.278689 | 128 | 0.744157 | 4.661479 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/evaluation-plugin/core/src/com/intellij/cce/workspace/EvaluationWorkspace.kt | 8 | 2688 | package com.intellij.cce.workspace
import com.google.gson.Gson
import com.intellij.cce.workspace.storages.*
import java.io.FileWriter
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.text.SimpleDateFormat
import java.util.*
class EvaluationWorkspace private constructor(private val basePath: Path) {
companion object {
private const val DEFAULT_REPORT_TYPE = "html"
private val gson = Gson()
private val formatter = SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")
fun open(workspaceDir: String): EvaluationWorkspace {
return EvaluationWorkspace(Paths.get(workspaceDir).toAbsolutePath())
}
fun create(config: Config): EvaluationWorkspace {
val workspace = EvaluationWorkspace(Paths.get(config.outputDir).toAbsolutePath().resolve(formatter.format(Date())))
workspace.writeConfig(config)
return workspace
}
}
private val sessionsDir = subdir("data")
private val logsDir = subdir("logs")
private val featuresDir = subdir("features")
private val actionsDir = subdir("actions")
private val errorsDir = subdir("errors")
private val reportsDir = subdir("reports")
private val pathToConfig = path().resolve(ConfigFactory.DEFAULT_CONFIG_NAME)
private val _reports: MutableMap<String, MutableMap<String, Path>> = mutableMapOf()
val sessionsStorage: SessionsStorage = SessionsStorage(sessionsDir.toString())
val actionsStorage: ActionsStorage = ActionsStorage(actionsDir.toString())
val errorsStorage: FileErrorsStorage = FileErrorsStorage(errorsDir.toString())
val logsStorage: LogsStorage = LogsStorage(logsDir.toString())
val featuresStorage: FeaturesStorage = FeaturesStorageImpl(featuresDir.toString())
override fun toString(): String = "Evaluation workspace: $basePath"
fun reportsDirectory(): String = reportsDir.toString()
fun path(): Path = basePath
fun readConfig(): Config = ConfigFactory.load(pathToConfig)
fun saveAdditionalStats(name: String, stats: Map<String, Any>) {
FileWriter(basePath.resolve("$name.json").toString()).use { it.write(gson.toJson(stats)) }
}
fun addReport(reportType: String, filterName: String, comparisonFilterName: String, reportPath: Path) {
_reports.getOrPut(reportType) { mutableMapOf() }["$filterName $comparisonFilterName"] = reportPath
}
fun getReports(reportType: String = DEFAULT_REPORT_TYPE): Map<String, Path> = _reports.getOrDefault(reportType, emptyMap())
private fun writeConfig(config: Config) = ConfigFactory.save(config, basePath)
private fun subdir(name: String): Path {
val directory = basePath.resolve(name)
Files.createDirectories(directory)
return directory
}
} | apache-2.0 | 261fc7f818963cb2943cf9488cf6bc70 | 35.835616 | 125 | 0.752604 | 4.356564 | false | true | false | false |
kohry/gorakgarakANPR | app/src/main/java/com/gorakgarak/anpr/ml/SupportVector.kt | 1 | 2018 | package com.gorakgarak.anpr.ml
import android.content.Context
import android.util.Log
import android.util.Xml
import com.gorakgarak.anpr.MainActivity
import com.gorakgarak.anpr.R
import com.gorakgarak.anpr.parser.GorakgarakXMLParser
import org.opencv.core.Mat
import org.opencv.core.TermCriteria
import org.opencv.ml.Ml.ROW_SAMPLE
import org.opencv.ml.SVM
import org.xmlpull.v1.XmlPullParser
import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader
/**
* Created by kohry on 2017-10-16.
*/
object SupportVector {
private const val TAG = "SVM Object"
private val svm: SVM? = null
fun getSvmClassifier(): SVM? = svm
//Sadly, Android opencv sdk does not support FileStorage.
//This is one method to read XML file from assets.
//Pretty sucks.
private fun readXML(context:Context, fileName: String): Pair<Mat, Mat> {
// val fs = opencv_core.FileStorage()
// fs.open(fileName, opencv_core.FileStorage.READ)
//
// val train = Mat(fs["TrainingData"].mat().address())
// val classes = Mat(fs["classes"].mat().address())
//
// return Pair(train, classes)
return GorakgarakXMLParser.parse(context.resources.openRawResource(R.raw.svm),"TrainingData")
}
//Train data when application first turn on.
//Actually, this part should be outside of the Android system.
//Don't you think?? KKUL KKUL
fun train(context: Context) {
var svm = SVM.create()
if (svm.isTrained) return
val data = readXML(context, "SVM.xml")
Log.d(TAG, "Set initial SVM Params")
val dataMat = data.first
val classes = data.second
svm.type = SVM.C_SVC
svm.degree = 0.0
svm.gamma = 1.0
svm.coef0 = 0.0
svm.c = 1.0
svm.nu = 0.0
svm.p = 0.0
svm.termCriteria = TermCriteria(TermCriteria.MAX_ITER, 1000, 0.01)
svm.setKernel(SVM.LINEAR)
svm.train(dataMat ,ROW_SAMPLE, classes)
svm.isTrained
}
} | mit | 10712d89b594093818df8c3e97bb549d | 26.283784 | 101 | 0.662537 | 3.270665 | false | false | false | false |
georocket/georocket | src/main/kotlin/io/georocket/util/MimeTypeUtils.kt | 1 | 3244 | package io.georocket.util
import org.apache.commons.io.input.BOMInputStream
import java.io.BufferedInputStream
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream
import java.util.zip.GZIPInputStream
/**
* Utility methods for mime types
* @author Andrej Sajenko
* @author Michel Kraemer
*/
object MimeTypeUtils {
/**
* Mime type for XML
*/
const val XML = "application/xml"
/**
* Mime type for JSON
*/
const val JSON = "application/json"
/**
* Check if the given mime type belongs to another one.
*
* Examples:
*
* * belongsTo("application/gml+xml", "application", "xml") == true
* * belongsTo("application/exp+xml", "application", "xml") == true
* * belongsTo("application/xml", "application", "xml") == true
* * belongsTo("application/exp+xml", "text", "xml") == false
* * belongsTo("application/exp+xml", "application", "json") == false
*
* @param mimeType the mime type
* @param otherType the general type of the other mime type
* @param otherStructuredSyntaxSuffix the structured syntax suffix of the other subtype (subtype = example+structuredSyntaxSuffix)
* @return true if the mime type belongs to the other one
*/
fun belongsTo(
mimeType: String, otherType: String,
otherStructuredSyntaxSuffix: String
): Boolean {
val regex = "${Regex.escape(otherType)}/(.*\\+)?${Regex.escape(otherStructuredSyntaxSuffix)}(;.*)?"
return mimeType matches regex.toRegex()
}
/**
* Read the first bytes of the given file and try to determine the file
* format. Read up to 100 KB before giving up.
* @param f the file to read
* @return the file format (or `null` if the format
* could not be determined)
* @throws IOException if the input stream could not be read
*/
fun detect(f: File, gzip: Boolean = false): String? {
if (!f.exists()) {
return null
}
var inputStream: InputStream? = null
try {
inputStream = FileInputStream(f)
if (gzip) {
inputStream = GZIPInputStream(inputStream)
}
BufferedInputStream(BOMInputStream(inputStream)).use { bis -> return determineFileFormat(bis) }
} finally {
inputStream?.close()
}
}
/**
* Read the first bytes of the given input stream and try to
* determine the file format. Reset the input stream to the position
* it had when the method was called. Read up to 100 KB before
* giving up.
* @param bis a buffered input stream that supports the mark and reset
* methods
* @return the file format (or `null` if the format
* could not be determined)
* @throws IOException if the input stream could not be read
*/
private fun determineFileFormat(bis: BufferedInputStream): String? {
var len = 1024 * 100
bis.mark(len)
try {
while (true) {
val c = bis.read()
--len
if (c < 0 || len < 2) {
return null
}
if (!Character.isWhitespace(c)) {
if (c == '['.code || c == '{'.code) {
return JSON
} else if (c == '<'.code) {
return XML
}
return null
}
}
} finally {
bis.reset()
}
}
}
| apache-2.0 | 68bb07db01a07efe01228bed0afd372e | 28.761468 | 132 | 0.631628 | 4.049938 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/MainEntityParentListImpl.kt | 1 | 8926 | package com.intellij.workspaceModel.storage.entities.test.api
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.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class MainEntityParentListImpl(val dataSource: MainEntityParentListData) : MainEntityParentList, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(MainEntityParentList::class.java,
AttachedEntityParentList::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
override val x: String
get() = dataSource.x
override val children: List<AttachedEntityParentList>
get() = snapshot.extractOneToManyChildren<AttachedEntityParentList>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: MainEntityParentListData?) : ModifiableWorkspaceEntityBase<MainEntityParentList>(), MainEntityParentList.Builder {
constructor() : this(MainEntityParentListData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity MainEntityParentList 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().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isXInitialized()) {
error("Field MainEntityParentList#x should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field MainEntityParentList#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field MainEntityParentList#children should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as MainEntityParentList
this.entitySource = dataSource.entitySource
this.x = dataSource.x
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var x: String
get() = getEntityData().x
set(value) {
checkModificationAllowed()
getEntityData().x = value
changedProperty.add("x")
}
// List of non-abstract referenced types
var _children: List<AttachedEntityParentList>? = emptyList()
override var children: List<AttachedEntityParentList>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<AttachedEntityParentList>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(
true, CHILDREN_CONNECTION_ID)] as? List<AttachedEntityParentList> ?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<AttachedEntityParentList> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override fun getEntityData(): MainEntityParentListData = result ?: super.getEntityData() as MainEntityParentListData
override fun getEntityClass(): Class<MainEntityParentList> = MainEntityParentList::class.java
}
}
class MainEntityParentListData : WorkspaceEntityData<MainEntityParentList>() {
lateinit var x: String
fun isXInitialized(): Boolean = ::x.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<MainEntityParentList> {
val modifiable = MainEntityParentListImpl.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): MainEntityParentList {
return getCached(snapshot) {
val entity = MainEntityParentListImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return MainEntityParentList::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return MainEntityParentList(x, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as MainEntityParentListData
if (this.entitySource != other.entitySource) return false
if (this.x != other.x) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as MainEntityParentListData
if (this.x != other.x) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + x.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + x.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | a1bcc1d7227d2e54fe3b015cb75547a7 | 34.561753 | 142 | 0.697289 | 5.325776 | false | false | false | false |
google/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/ui/actions/styling/BaseToggleStateAction.kt | 3 | 6437 | package org.intellij.plugins.markdown.ui.actions.styling
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.command.executeCommand
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.elementType
import org.intellij.plugins.markdown.editor.runForEachCaret
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.MarkdownTokenTypes
import org.intellij.plugins.markdown.ui.actions.MarkdownActionUtil
import org.intellij.plugins.markdown.ui.actions.MarkdownActionUtil.getCommonParentOfType
import org.intellij.plugins.markdown.ui.actions.MarkdownActionUtil.getElementsUnderCaretOrSelection
abstract class BaseToggleStateAction: ToggleAction(), DumbAware {
protected abstract fun getBoundString(text: CharSequence, selectionStart: Int, selectionEnd: Int): String
protected open fun getExistingBoundString(text: CharSequence, startOffset: Int): String? {
return text[startOffset].toString()
}
protected abstract fun shouldMoveToWordBounds(): Boolean
protected abstract val targetNodeType: IElementType
override fun update(event: AnActionEvent) {
val editor = MarkdownActionUtil.findMarkdownEditor(event)
event.presentation.isEnabled = editor != null
super.update(event)
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun isSelected(event: AnActionEvent): Boolean {
if (MarkdownActionUtil.findMarkdownEditor(event) == null) {
return false
}
val file = event.getData(CommonDataKeys.PSI_FILE) ?: return false
val caretSnapshots = SelectionUtil.obtainCaretSnapshots(this, event)?.asSequence() ?: return false
val selectionElements = caretSnapshots.map { getElementsUnderCaretOrSelection(file, it.selectionStart, it.selectionEnd) }
val commonParents = selectionElements.map { (left, right) -> getCommonParentOfType(left, right, targetNodeType) }
val hasMissingParents = commonParents.any { it == null }
val hasValidParents = commonParents.any { it != null }
if (hasMissingParents && hasValidParents) {
event.presentation.isEnabled = false
return false
}
event.presentation.isEnabled = true
return !hasMissingParents
}
override fun setSelected(event: AnActionEvent, state: Boolean) {
val editor = MarkdownActionUtil.findMarkdownEditor(event) ?: return
val file = event.getData(CommonDataKeys.PSI_FILE) ?: return
runWriteAction {
executeCommand(file.project, templatePresentation.text) {
editor.caretModel.runForEachCaret(reverseOrder = true) { caret ->
processCaret(file, editor, caret, state)
}
}
}
}
private fun processCaret(file: PsiFile, editor: Editor, caret: Caret, state: Boolean) {
val (first, second) = getElementsUnderCaretOrSelection(file, caret)
if (!state) {
val parent = getCommonParentOfType(first, second, targetNodeType)
if (parent == null) {
thisLogger().warn("Could not find enclosing element on its destruction")
return
}
removeEmphasisFromSelection(editor.document, caret, parent.textRange)
return
}
val parent = PsiTreeUtil.findCommonParent(first, second)
if (parent.elementType !in elementsToIgnore) {
addEmphasisToSelection(editor.document, caret)
}
}
protected fun removeEmphasisFromSelection(document: Document, caret: Caret, nodeRange: TextRange) {
val text = document.charsSequence
val boundString = getExistingBoundString(text, nodeRange.startOffset)
if (boundString == null) {
thisLogger().warn("Could not fetch bound string from found node")
return
}
val boundLength = boundString.length
// Easy case --- selection corresponds to some emph
if (nodeRange.startOffset + boundLength == caret.selectionStart
&& nodeRange.endOffset - boundLength == caret.selectionEnd) {
document.deleteString(nodeRange.endOffset - boundLength, nodeRange.endOffset)
document.deleteString(nodeRange.startOffset, nodeRange.startOffset + boundLength)
return
}
var from = caret.selectionStart
var to = caret.selectionEnd
if (shouldMoveToWordBounds()) {
while (from - boundLength > nodeRange.startOffset && Character.isWhitespace(text[from - 1])) {
from--
}
while (to + boundLength < nodeRange.endOffset && Character.isWhitespace(text[to])) {
to++
}
}
if (to + boundLength == nodeRange.endOffset) {
document.deleteString(nodeRange.endOffset - boundLength, nodeRange.endOffset)
}
else {
document.insertString(to, boundString)
}
if (from - boundLength == nodeRange.startOffset) {
document.deleteString(nodeRange.startOffset, nodeRange.startOffset + boundLength)
}
else {
document.insertString(from, boundString)
}
}
protected fun addEmphasisToSelection(document: Document, caret: Caret) {
var from = caret.selectionStart
var to = caret.selectionEnd
val text = document.charsSequence
if (shouldMoveToWordBounds()) {
while (from < to && Character.isWhitespace(text[from])) {
from++
}
while (to > from && Character.isWhitespace(text[to - 1])) {
to--
}
if (from == to) {
from = caret.selectionStart
to = caret.selectionEnd
}
}
val boundString = getBoundString(text, from, to)
document.insertString(to, boundString)
document.insertString(from, boundString)
if (caret.selectionStart == caret.selectionEnd) {
caret.moveCaretRelatively(boundString.length, 0, false, false)
}
}
companion object {
private val elementsToIgnore = setOf(
MarkdownElementTypes.LINK_DESTINATION,
MarkdownElementTypes.AUTOLINK,
MarkdownTokenTypes.GFM_AUTOLINK
)
}
}
| apache-2.0 | b3a0e3af95cab37d45c83b75257e4290 | 38.012121 | 125 | 0.734193 | 4.549117 | false | false | false | false |
square/okhttp | samples/tlssurvey/src/main/kotlin/okhttp3/survey/RunSurvey.kt | 2 | 3741 | /*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.survey
import java.security.Security
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.survey.ssllabs.SslLabsScraper
import okhttp3.survey.types.Client
import okhttp3.survey.types.SuiteId
import okio.FileSystem
import okio.Path.Companion.toPath
import org.conscrypt.Conscrypt
suspend fun main() {
val includeConscrypt = false
val client = OkHttpClient.Builder()
.cache(Cache("build/okhttp_cache".toPath(), 100_000_000, FileSystem.SYSTEM))
.build()
val sslLabsScraper = SslLabsScraper(client)
try {
val ianaSuitesNew = fetchIanaSuites(client)
val sslLabsClients = sslLabsScraper.query()
val android5 = sslLabsClients.first { it.userAgent == "Android" && it.version == "5.0.0" }
val android9 = sslLabsClients.first { it.userAgent == "Android" && it.version == "9.0" }
val chrome33 = sslLabsClients.first { it.userAgent == "Chrome" && it.version == "33" }
val chrome57 = sslLabsClients.first { it.userAgent == "Chrome" && it.version == "57" }
val chrome80 = sslLabsClients.first { it.userAgent == "Chrome" && it.version == "80" }
val firefox34 = sslLabsClients.first { it.userAgent == "Firefox" && it.version == "34" }
val firefox53 = sslLabsClients.first { it.userAgent == "Firefox" && it.version == "53" }
val firefox73 = sslLabsClients.first { it.userAgent == "Firefox" && it.version == "73" }
val java7 = sslLabsClients.first { it.userAgent == "Java" && it.version == "7u25" }
val java12 = sslLabsClients.first { it.userAgent == "Java" && it.version == "12.0.1" }
val safari12iOS = sslLabsClients.first { it.userAgent == "Safari" && it.platform == "iOS 12.3.1" }
val safari12Osx = sslLabsClients.first { it.userAgent == "Safari" && it.platform == "MacOS 10.14.6 Beta" }
val okhttp = currentOkHttp(ianaSuitesNew)
val okHttp_4_10 = historicOkHttp("4.10")
val okHttp_3_14 = historicOkHttp("3.14")
val okHttp_3_13 = historicOkHttp("3.13")
val okHttp_3_11 = historicOkHttp("3.11")
val okHttp_3_9 = historicOkHttp("3.9")
val currentVm = currentVm(ianaSuitesNew)
val conscrypt = if (includeConscrypt) {
Security.addProvider(Conscrypt.newProvider())
conscrypt(ianaSuitesNew)
} else {
Client("Conscrypt", "Disabled", null, listOf())
}
val clients = listOf(
okhttp,
chrome80,
firefox73,
android9,
safari12iOS,
conscrypt,
currentVm,
okHttp_3_9,
okHttp_3_11,
okHttp_3_13,
okHttp_3_14,
okHttp_4_10,
android5,
java7,
java12,
firefox34,
firefox53,
chrome33,
chrome57,
safari12Osx
)
val orderBy = okhttp.enabled + chrome80.enabled + safari12Osx.enabled + rest(clients)
val survey = CipherSuiteSurvey(clients = clients, ianaSuites = ianaSuitesNew, orderBy = orderBy)
survey.printGoogleSheet()
} finally {
client.dispatcher.executorService.shutdown()
client.connectionPool.evictAll()
}
}
fun rest(clients: List<Client>): List<SuiteId> {
// combine all ciphers to get these near the top
return clients.flatMap { it.enabled }
}
| apache-2.0 | 431c8418d9adccb5bc6ab2fc8389846f | 33.638889 | 110 | 0.677894 | 3.496262 | false | false | false | false |
nielsutrecht/adventofcode | src/main/kotlin/com/nibado/projects/advent/y2021/Day06.kt | 1 | 759 | package com.nibado.projects.advent.y2021
import com.nibado.projects.advent.*
object Day06 : Day {
private val values = resourceString(2021, 6).split(',').map { it.toInt() }
private fun simulate(turns: Int) : Long {
var fish = values.groupBy { it }.map { (k, v) -> k to v.size.toLong() }.toMap().toMutableMap()
repeat(turns) {
val updates = fish.map { (age, amount) ->
if(age == 0) (6 to amount) else (age - 1 to amount)
} + (8 to (fish[0] ?: 0))
fish.clear()
updates.forEach { (age, amount) -> fish[age] = (fish[age] ?: 0) + amount }
}
return fish.values.sum()
}
override fun part1() = simulate(80)
override fun part2() = simulate(256)
} | mit | 98a3f581acbdfbe252f94f3cf4884a8a | 32.043478 | 102 | 0.550725 | 3.497696 | false | false | false | false |
allotria/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/HideProjectRefreshAction.kt | 4 | 1158 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.autoimport
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.project.DumbAwareAction
class HideProjectRefreshAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val notificationAware = ProjectNotificationAware.getInstance(project)
notificationAware.hideNotification()
}
override fun update(e: AnActionEvent) {
val project = e.project ?: return
val notificationAware = ProjectNotificationAware.getInstance(project)
e.presentation.isEnabled = notificationAware.isNotificationVisible()
}
init {
templatePresentation.text = ExternalSystemBundle.message("external.system.reload.notification.action.hide.text")
templatePresentation.icon = AllIcons.Actions.Close
templatePresentation.hoveredIcon = AllIcons.Actions.CloseHovered
}
} | apache-2.0 | 79b1b05f6d44fdbcd7ee0fd739db8c4b | 41.925926 | 140 | 0.800518 | 4.92766 | false | false | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/analysis/htl/callchain/typedescriptor/java/JavaPsiClassTypeDescriptor.kt | 1 | 5450 | package com.aemtools.analysis.htl.callchain.typedescriptor.java
import com.aemtools.analysis.htl.callchain.typedescriptor.base.TypeDescriptor
import com.aemtools.common.util.allScope
import com.aemtools.common.util.elFields
import com.aemtools.common.util.elMethods
import com.aemtools.common.util.elName
import com.aemtools.common.util.findElMemberByName
import com.aemtools.common.util.psiManager
import com.aemtools.common.util.resolveReturnType
import com.aemtools.common.util.withPriority
import com.aemtools.completion.htl.CompletionPriority
import com.aemtools.completion.htl.model.ResolutionResult
import com.aemtools.lang.java.JavaSearch
import com.aemtools.lang.java.JavaUtilities
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.psi.PsiArrayType
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiPrimitiveType
import com.intellij.psi.PsiType
import com.intellij.psi.impl.source.PsiClassReferenceType
import java.util.ArrayList
/**
* Type descriptor which uses given [PsiClass] to provide type information.
*
* @author Dmytro_Troynikov
*/
open class JavaPsiClassTypeDescriptor(open val psiClass: PsiClass,
open val psiMember: PsiMember? = null,
open val originalType: PsiType? = null) : TypeDescriptor {
override fun isArray(): Boolean = originalType is PsiArrayType
override fun isIterable(): Boolean = JavaUtilities.isIterable(psiClass)
override fun isMap(): Boolean = JavaUtilities.isMap(psiClass)
override fun myVariants(): List<LookupElement> {
val methods = psiClass.elMethods()
val fields = psiClass.elFields()
val methodNames = ArrayList<String>()
val result = ArrayList<LookupElement>()
methods.forEach {
var name = it.elName()
if (methodNames.contains(name)) {
name = it.name
} else {
methodNames.add(name)
}
var lookupElement = LookupElementBuilder.create(name)
.withIcon(it.getIcon(0))
.withTailText(" ${it.name}()", true)
val returnType = it.returnType
if (returnType != null) {
lookupElement = lookupElement.withTypeText(returnType.presentableText, true)
}
result.add(lookupElement.withPriority(extractPriority(it, psiClass)))
}
fields.forEach {
val lookupElement = LookupElementBuilder.create(it.name.toString())
.withIcon(it.getIcon(0))
.withTypeText(it.type.presentableText, true)
result.add(lookupElement.withPriority(extractPriority(it, psiClass)))
}
return result
}
private fun extractPriority(member: PsiMember, clazz: PsiMember) = when {
member.containingClass == clazz ->
CompletionPriority.CONTAINING_CLASS
member.containingClass?.qualifiedName == "java.lang.Object" ->
CompletionPriority.OBJECT_CLASS
else -> CompletionPriority.MIDDLE_CLASS
}
override fun subtype(identifier: String): TypeDescriptor {
val psiMember = psiClass.findElMemberByName(identifier)
?: return TypeDescriptor.empty()
val psiType = psiMember.resolveReturnType()
?: return TypeDescriptor.empty()
val className = with(psiType) {
when {
this is PsiClassReferenceType -> {
this.rawType().canonicalText
}
this is PsiClassType -> this.className
this is PsiPrimitiveType -> this.getBoxedType(
psiClass.project.psiManager(),
psiClass.project.allScope()
)?.canonicalText
this is PsiArrayType -> {
this.componentType.canonicalText
}
else -> null
}
} ?: return TypeDescriptor.empty()
val typeClass = JavaSearch.findClass(className, psiClass.project)
?: return TypeDescriptor.unresolved(psiMember)
return JavaPsiClassTypeDescriptor.create(typeClass, psiMember, psiType)
}
override fun referencedElement(): PsiElement? =
psiMember
override fun asResolutionResult(): ResolutionResult =
ResolutionResult(psiClass, myVariants())
companion object {
/**
* Build method for [JavaPsiClassTypeDescriptor].
*
* @param psiClass the psi class
* @param psiMember the psi member (_null_ by default)
* @param psiType the psi type (_null_ by default)
*
* @return new java psi class type descriptor
*/
fun create(psiClass: PsiClass,
psiMember: PsiMember? = null,
psiType: PsiType? = null): JavaPsiClassTypeDescriptor {
return when (psiType) {
is PsiClassReferenceType -> {
when {
JavaUtilities.isIterable(psiClass)
|| JavaUtilities.isIterator(psiClass) ->
IterableJavaTypeDescriptor(psiClass, psiMember, psiType)
JavaUtilities.isMap(psiClass) ->
MapJavaTypeDescriptor(psiClass, psiMember, psiType)
else -> JavaPsiClassTypeDescriptor(psiClass, psiMember, psiType)
}
}
is PsiClassType,
is PsiPrimitiveType ->
JavaPsiClassTypeDescriptor(psiClass, psiMember, psiType)
is PsiArrayType ->
ArrayJavaTypeDescriptor(psiClass, psiMember, psiType)
else -> JavaPsiClassTypeDescriptor(psiClass, psiMember, psiType)
}
}
}
}
| gpl-3.0 | 7914c2521799951523b38728f88020c1 | 33.493671 | 96 | 0.694128 | 4.853072 | false | false | false | false |
allotria/intellij-community | plugins/ide-features-trainer/src/training/learn/NewLearnProjectUtil.kt | 3 | 2022 | // 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 training.learn
import com.intellij.ide.util.TipDialog
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import training.lang.LangSupport
import training.learn.exceptons.NoSdkException
import training.project.ProjectUtils
object NewLearnProjectUtil {
private val LOG = logger<NewLearnProjectUtil>()
fun createLearnProject(projectToClose: Project?, langSupport: LangSupport, postInitCallback: (learnProject: Project) -> Unit) {
val unitTestMode = ApplicationManager.getApplication().isUnitTestMode
ProjectUtils.importOrOpenProject(langSupport, projectToClose) { newProject ->
TipDialog.DISABLE_TIPS_FOR_PROJECT.set(newProject, true)
try {
val sdkForProject = langSupport.getSdkForProject(newProject)
if (sdkForProject != null) {
langSupport.applyProjectSdk(sdkForProject, newProject)
}
}
catch (e: NoSdkException) {
LOG.error(e)
}
if (!unitTestMode) newProject.save()
newProject.save()
postInitCallback(newProject)
}
}
fun showDialogOpenLearnProject(project: Project): Boolean {
return Messages.showOkCancelDialog(project,
LearnBundle.message("dialog.learnProjectWarning.message",
ApplicationNamesInfo.getInstance().fullProductName),
LearnBundle.message("dialog.learnProjectWarning.title"),
LearnBundle.message("dialog.learnProjectWarning.ok"),
Messages.getCancelButton(),
null) == Messages.OK
}
}
| apache-2.0 | fab4e049d1b4e45c39c028c9101f4f7c | 41.125 | 140 | 0.673096 | 5.197943 | false | true | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/notification/impl/NotificationSettings.kt | 3 | 3206 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.notification.impl
import com.intellij.notification.NotificationDisplayType
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import org.jdom.Element
/**
* @author spleaner
* @author Konstantin Bulenkov
*/
data class NotificationSettings @JvmOverloads constructor(var groupId: String,
var displayType: NotificationDisplayType,
var isShouldLog: Boolean,
var isShouldReadAloud: Boolean,
var isPlaySound: Boolean = false) {
fun withShouldLog(shouldLog: Boolean) = copy(isShouldLog = shouldLog)
fun withShouldReadAloud(shouldReadAloud: Boolean) = copy(isShouldReadAloud = shouldReadAloud)
fun withPlaySound(playSound: Boolean) = copy(isPlaySound = playSound)
fun withDisplayType(type: NotificationDisplayType) = copy(displayType = type)
fun save(): Element {
return Element("notification").apply {
setAttribute("groupId", groupId)
if (displayType != NotificationDisplayType.BALLOON) setAttribute("displayType", displayType.toString())
if (!isShouldLog) setAttribute("shouldLog", "false")
if (isShouldReadAloud) setAttribute("shouldReadAloud", "true")
if (isPlaySound) setAttribute("playSound", "true")
}
}
companion object {
fun load(element: Element): NotificationSettings? {
val displayTypeString = element.getAttributeValue("displayType")
var displayType = NotificationDisplayType.BALLOON
var shouldLog = "false" != element.getAttributeValue("shouldLog")
val shouldReadAloud = "true" == element.getAttributeValue("shouldReadAloud")
val playSound = "true" == element.getAttributeValue("playSound")
if ("BALLOON_ONLY" == displayTypeString) {
shouldLog = false
displayType = NotificationDisplayType.BALLOON
}
else if (displayTypeString != null) {
try {
displayType = NotificationDisplayType.valueOf(StringUtil.toUpperCase(displayTypeString))
}
catch (ignored: IllegalArgumentException) {
}
}
val groupId = element.getAttributeValue("groupId")
return groupId?.let { NotificationSettings(it, displayType, shouldLog, shouldReadAloud, playSound) }
}
}
}
fun isReadAloudEnabled() = SystemInfo.isMac
fun isSoundEnabled() = Registry.`is`("ide.notifications.sound.enabled") | apache-2.0 | f9ecdc25475a81c12a0ea07e5c55bd36 | 40.649351 | 109 | 0.682782 | 4.806597 | false | false | false | false |
JetBrains/teamcity-dnx-plugin | plugin-dotnet-agent/src/test/kotlin/jetbrains/buildServer/dotnet/test/dotnet/VSTestCommandTest.kt | 1 | 4238 | package jetbrains.buildServer.dotnet.test.dotnet
import jetbrains.buildServer.agent.CommandLineArgument
import jetbrains.buildServer.agent.Path
import jetbrains.buildServer.agent.ToolPath
import jetbrains.buildServer.dotnet.*
import jetbrains.buildServer.dotnet.test.agent.runner.ParametersServiceStub
import org.testng.Assert
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
class VSTestCommandTest {
@DataProvider
fun argumentsData(): Array<Array<Any>> {
return arrayOf(
arrayOf(mapOf(Pair(DotnetConstants.PARAM_PATHS, "path/")),
listOf("vstestlog", "customArg1")),
arrayOf(mapOf(
DotnetConstants.PARAM_TEST_SETTINGS_FILE to "myconfig.txt",
DotnetConstants.PARAM_TEST_FILTER to "filter",
DotnetConstants.PARAM_PLATFORM to "x86",
DotnetConstants.PARAM_FRAMEWORK to "net45",
DotnetConstants.PARAM_TEST_CASE_FILTER to "myfilter"),
listOf("/Settings:myconfig.txt", "/TestCaseFilter:myfilter", "/Platform:x86", "/Framework:net45", "vstestlog", "customArg1")),
arrayOf(mapOf(DotnetConstants.PARAM_PATHS to "my.dll",
DotnetConstants.PARAM_TEST_FILTER to "name",
DotnetConstants.PARAM_TEST_NAMES to "test1 test2; test3"),
listOf("/Tests:test1,test2,test3", "vstestlog", "customArg1")))
}
@Test(dataProvider = "argumentsData")
fun shouldGetArguments(
parameters: Map<String, String>,
expectedArguments: List<String>) {
// Given
val command = createCommand(parameters = parameters, targets = sequenceOf("my.dll"), arguments = sequenceOf(CommandLineArgument("customArg1")))
// When
val actualArguments = command.getArguments(DotnetBuildContext(ToolPath(Path("wd")), command)).map { it.value }.toList()
// Then
Assert.assertEquals(actualArguments, expectedArguments)
}
@DataProvider
fun projectsArgumentsData(): Array<Array<Any>> {
return arrayOf(
arrayOf(listOf("my.dll") as Any, listOf(listOf("my.dll"))),
arrayOf(emptyList<String>() as Any, emptyList<List<String>>()),
arrayOf(listOf("my.dll", "my2.dll") as Any, listOf(listOf("my.dll"), listOf("my2.dll"))))
}
@Test(dataProvider = "projectsArgumentsData")
fun shouldProvideProjectsArguments(targets: List<String>, expectedArguments: List<List<String>>) {
// Given
val command = createCommand(targets = targets.asSequence())
// When
val actualArguments = command.targetArguments.map { it.arguments.map { it.value }.toList() }.toList()
// Then
Assert.assertEquals(actualArguments, expectedArguments)
}
@Test
fun shouldProvideCommandType() {
// Given
val command = createCommand()
// When
val actualCommand = command.commandType
// Then
Assert.assertEquals(actualCommand, DotnetCommandType.VSTest)
}
@Test
fun shouldProvideToolExecutableFile() {
// Given
val command = createCommand()
// When
val actualExecutable = command.toolResolver.executable
// Then
Assert.assertEquals(actualExecutable, ToolPath(Path("vstest.console.exe")))
}
fun createCommand(
parameters: Map<String, String> = emptyMap(),
targets: Sequence<String> = emptySequence(),
arguments: Sequence<CommandLineArgument> = emptySequence(),
testsResultsAnalyzer: ResultsAnalyzer = TestsResultsAnalyzerStub()): DotnetCommand =
VSTestCommand(
ParametersServiceStub(parameters),
testsResultsAnalyzer,
TargetServiceStub(targets.map { CommandTarget(Path(it)) }.asSequence()),
ArgumentsProviderStub(sequenceOf(CommandLineArgument("vstestlog"))),
ArgumentsProviderStub(arguments),
DotnetToolResolverStub(ToolPlatform.Windows, ToolPath(Path("vstest.console.exe")), true))
} | apache-2.0 | a1837b85c903e4f923179cff8f380932 | 40.970297 | 151 | 0.63261 | 4.933644 | false | true | false | false |
JetBrains/teamcity-dnx-plugin | plugin-dotnet-server/src/main/kotlin/jetbrains/buildServer/dotnet/discovery/MSBuildSolutionDeserializer.kt | 1 | 2442 | package jetbrains.buildServer.dotnet.discovery
import java.util.regex.Pattern
class MSBuildSolutionDeserializer(
private val _readerFactory: ReaderFactory,
private val _msBuildProjectDeserializer: SolutionDeserializer) : SolutionDeserializer {
override fun accept(path: String): Boolean = PathPattern.matcher(path).find()
override fun deserialize(path: String, streamFactory: StreamFactory): Solution =
streamFactory.tryCreate(path)?.let {
it.use {
_readerFactory.create(it).use {
val projects = it
.readLines()
.asSequence()
.map { ProjectPathPattern.matcher(it) }
.filter { it.find() }
.map {
it?.let {
val projectPath = normalizePath(path, it.group(1))
if (_msBuildProjectDeserializer.accept(projectPath)) {
_msBuildProjectDeserializer.deserialize(projectPath, streamFactory).projects.asSequence()
} else {
emptySequence()
}
} ?: emptySequence()
}
.asSequence()
.flatMap { it }
.distinctBy { it.project }
.toList()
Solution(projects, path)
}
}
} ?: Solution(emptyList())
fun normalizePath(basePath: String, path: String): String {
val baseParent = basePath.replace('\\', '/').split('/').reversed().drop(1).reversed().joinToString("/")
val normalizedPath = path.replace('\\', '/')
if (baseParent.isBlank()) {
return normalizedPath
}
return "$baseParent/$normalizedPath"
}
private companion object {
private val ProjectPathPattern = Pattern.compile("^Project\\(.+\\)\\s*=\\s*\".+\"\\s*,\\s*\"(.+)\"\\s*,\\s*\".+\"\\s*\$", Pattern.CASE_INSENSITIVE)
private val PathPattern: Pattern = Pattern.compile("^.+\\.sln$", Pattern.CASE_INSENSITIVE)
}
} | apache-2.0 | cf0b48fdceba55089d0899325f39b8c4 | 45.09434 | 155 | 0.461916 | 5.870192 | false | false | false | false |
jeevatkm/FrameworkBenchmarks | frameworks/Kotlin/http4k/core/src/main/kotlin/Database.kt | 1 | 1998 | import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import java.sql.Connection
import java.sql.PreparedStatement
import java.sql.ResultSet
import javax.sql.DataSource
open class Database(private val dataSource: DataSource) {
companion object {
operator fun invoke(host: String): Database {
val postgresqlUrl = "jdbc:postgresql://$host:5432/hello_world?" +
"jdbcCompliantTruncation=false&" +
"elideSetAutoCommits=true&" +
"useLocalSessionState=true&" +
"cachePrepStmts=true&" +
"cacheCallableStmts=true&" +
"alwaysSendSetIsolation=false&" +
"prepStmtCacheSize=4096&" +
"cacheServerConfiguration=true&" +
"prepStmtCacheSqlLimit=2048&" +
"traceProtocol=false&" +
"useUnbufferedInput=false&" +
"useReadAheadInput=false&" +
"maintainTimeStats=false&" +
"useServerPrepStmts=true&" +
"cacheRSMetadata=true"
val config = HikariConfig()
config.jdbcUrl = postgresqlUrl
config.maximumPoolSize = 100
config.username = "benchmarkdbuser"
config.password = "benchmarkdbpass"
return Database(HikariDataSource(config))
}
}
fun <T> withConnection(fn: Connection.() -> T): T = dataSource.connection.use(fn)
fun <T> withStatement(stmt: String, fn: PreparedStatement.() -> T): T = withConnection { withStatement(stmt, fn) }
}
fun <T> Connection.withStatement(stmt: String, fn: PreparedStatement.() -> T): T = prepareStatement(stmt).use(fn)
fun <T> ResultSet.toList(fn: ResultSet.() -> T): List<T> =
use {
mutableListOf<T>().apply {
while (next()) {
add(fn(this@toList))
}
}
}
| bsd-3-clause | e326be5b76a9e6e883b1629a73933aa8 | 37.423077 | 118 | 0.562563 | 4.668224 | false | true | false | false |
walkingice/MomoDict | app/src/main/java/org/zeroxlab/momodict/widget/WordCardPresenter.kt | 1 | 1281 | package org.zeroxlab.momodict.widget
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import org.zeroxlab.momodict.R
import org.zeroxlab.momodict.model.Entry
class WordCardPresenter : SelectorAdapter.Presenter<Entry> {
override fun onCreateViewHolder(parent: ViewGroup): androidx.recyclerview.widget.RecyclerView.ViewHolder {
return LayoutInflater.from(parent.context)
.let { it.inflate(R.layout.list_item_word_row, parent, false) }
.let { InnerViewHolder(it) }
}
override fun onBindViewHolder(viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder, item: Entry) {
val holder = viewHolder as InnerViewHolder
holder.iText1.text = item.source
holder.iText2.text = item.data
}
override fun onUnbindViewHolder(viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder) {}
internal inner class InnerViewHolder(view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view) {
var iText1: TextView = view.findViewById<View>(R.id.text_1) as TextView
var iText2: TextView = view.findViewById<View>(R.id.text_2) as TextView
}
}
| mit | bb6fa87d4290647659a75d13ad9c64a1 | 39.03125 | 115 | 0.747073 | 4.284281 | false | false | false | false |
zdary/intellij-community | platform/platform-api/src/com/intellij/ide/plugins/advertiser/data.kt | 2 | 2671 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.plugins.advertiser
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.Comparing
import com.intellij.util.xmlb.annotations.*
@Tag("plugin")
class PluginData @JvmOverloads constructor(
@Attribute("pluginId") val pluginIdString: String = "",
@Attribute("pluginName") private val nullablePluginName: String? = null,
@Attribute("bundled") val isBundled: Boolean = false,
@Attribute("fromCustomRepository") val isFromCustomRepository: Boolean = false,
) : Comparable<PluginData> {
val pluginId: PluginId = PluginId.getId(pluginIdString)
val pluginName = nullablePluginName ?: pluginIdString
constructor(descriptor: PluginDescriptor) : this(
descriptor.pluginId.idString,
descriptor.name,
descriptor.isBundled,
)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as PluginData
return isBundled == other.isBundled
&& pluginIdString == other.pluginIdString
&& (nullablePluginName == null || nullablePluginName == other.nullablePluginName)
}
override fun hashCode(): Int {
var result = pluginIdString.hashCode()
result = 31 * result + isBundled.hashCode()
result = 31 * result + (nullablePluginName?.hashCode() ?: 0)
return result
}
override fun compareTo(other: PluginData): Int {
return if (isBundled && !other.isBundled) -1
else if (!isBundled && other.isBundled) 1
else Comparing.compare(pluginIdString, other.pluginIdString)
}
}
@Tag("featurePlugin")
class FeaturePluginData @JvmOverloads constructor(
@Attribute("displayName") val displayName: String = "",
@Property(surroundWithTag = false) val pluginData: PluginData = PluginData(),
)
@Tag("plugins")
class PluginDataSet @JvmOverloads constructor(dataSet: Set<PluginData> = setOf()) {
@JvmField
@XCollection(style = XCollection.Style.v2)
val dataSet = mutableSetOf<PluginData>()
init {
this.dataSet += dataSet
}
}
@Tag("extensions")
class KnownExtensions @JvmOverloads constructor(extensionsMap: Map<String, Set<PluginData>> = mapOf()) {
@JvmField
@XMap
val extensionsMap = mutableMapOf<String, PluginDataSet>()
init {
extensionsMap.entries.forEach { entry ->
this.extensionsMap[entry.key] = PluginDataSet(entry.value)
}
}
operator fun get(extension: String): Set<PluginData> = extensionsMap[extension]?.dataSet ?: setOf()
} | apache-2.0 | 4ad8df99ef4f370b762188810ffb32c8 | 31.192771 | 140 | 0.727069 | 4.393092 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-cli/src/main/kotlin/slatekit/cli/CLI.kt | 1 | 10543 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.cli
import java.nio.file.Paths
import java.util.concurrent.atomic.AtomicReference
import kotlinx.coroutines.runBlocking
import slatekit.common.args.Args
import slatekit.common.types.Content
import slatekit.common.types.ContentType
import slatekit.common.info.Folders
import slatekit.common.info.Info
import slatekit.common.utils.Loops.doUntil
import slatekit.results.*
import slatekit.results.builders.Tries
/**
* Core CLI( Command line interface ) shell provider with life-cycle events,
* functionality to handle user input commands, printing of data, checks for help requests,
* and exiting the shell. Derive from the class and override the onCommandExecuteInternal
* to handle the user input command converted to CliCommand.
*
* @param info : Metadata about the app used for displaying help about app
* @param folders : Used to write output to app directories
* @param settings : Settings for the shell functionality
* @param commands : Optional commands to run on startup
* @param reader : Optional interface to read a line ( abstracted out IO to support unit-testing )
* @param writer : Optional interface to write output ( abstracted out IO to support unit-testing )
*/
open class CLI(
val settings: CliSettings,
val info: Info,
val folders: Folders?,
val callback: ((CLI, CliRequest) -> CliResponse<*>)? = null,
commands: List<String?>? = listOf(),
ioReader: ((Unit) -> String?)? = null,
ioWriter: ((CliOutput) -> Unit)? = null,
val serializer:(Any?, ContentType) -> Content
) {
/**
* Display prompt
*/
val PROMPT = ":>"
/**
* Context to hold the reader, writer, help, io services
*/
val context = CliContext(info, commands, ioReader, ioWriter, serializer)
/**
* runs the shell command line with arguments
*/
suspend fun run(): Try<Boolean> {
// Convert line into a CliRequest
// Run the life-cycle methods ( before, execute, after )
val flow =
// 1. Initialize ( e.g. application code )
init().then {
// Startup commands
startUp()
}
// 2. Read, Eval, Print, Loop
.then {
repl()
}
// 3. End ( shutdown code )
.then {
end(it)
}
return flow
}
/**
* Hook for initialization for derived classes
*/
open suspend fun init(): Try<Boolean> {
// Hooks for before running anything.
return Tries.success(true)
}
/**
* Hook for shutdown for derived classes
*/
open suspend fun end(status: Status): Try<Boolean> {
return when(status){
is Passed.Succeeded -> Tries.success(true, status)
is Passed.Pending -> Tries.pending(true, status)
else -> Failure(Exception(status.desc), status.desc, status.code)
}
}
/**
* runs any start up commands
*/
suspend fun startUp(): Try<CliResponse<*>> {
val results = context.commands?.map { command ->
when (command) {
null -> Tries.success(CliResponse.empty)
"" -> Tries.success(CliResponse.empty)
else -> transform(command) { args ->
runBlocking {
executeRequest(CliUtils.convert(args))
}
}
}
} ?: listOf(Tries.success(CliResponse.empty))
// success if all succeeded, failure = 1st
val failed = results.firstOrNull { !it.success }
return when (failed) {
null -> if (results.isEmpty()) Tries.success(CliResponse.empty) else results.last()
else -> failed
}
}
/**
* Runs the shell continuously until "exit" or "quit" are entered.
*/
private val lastArgs = AtomicReference<Args>(Args.empty())
suspend fun repl(): Try<Status> {
// Keep reading from console until ( exit, quit ) is hit.
doUntil {
// Show prompt ":>"
context.writer.text(PROMPT, false)
// Get line
val raw = context.reader.perform(Unit)
val text = raw?.trim() ?: ""
val result = runBlocking { eval(text) }
// Track last line ( to allow for "retry" command )
result.onSuccess {
lastArgs.set(it.first)
}
// Only exit when user typed "exit"
val keepReading = result.success && result.status != Codes.EXIT
keepReading
}
return Tries.success(Codes.EXIT)
}
/**
* Evaluates the text read in from user input.
*/
suspend fun eval(text: String): Try<Pair<Args, Boolean>> {
// Use process for both handling interactive user supplied text
// and also the startup commands
return this.transform(text) { args ->
val evalResult = eval(args)
when (evalResult) {
// Transfer value back upstream with original parsed args
is Success -> {
val status = evalResult.status
when(status) {
is Passed.Pending -> Tries.pending(Pair(args, evalResult.value), status)
is Passed.Succeeded -> Tries.success(Pair(args, evalResult.value), status)
else -> Success(Pair(args, evalResult.value))
}
}
// Continue processing until exit | quit supplied
is Failure -> {
Success(Pair(args, true))
}
}
}
}
/**
* Evaluates the arguments read in from user input.
*/
suspend fun eval(args: Args): Try<Boolean> {
// Single command ( e.g. help, quit, about, version )
// These are typically system level
val res = if (args.parts.size == 1) {
when (args.line) {
Reserved.About.id -> { context.help.showAbout() ; Tries.success(true, Codes.ABOUT) }
Reserved.Help.id -> { context.help.showHelp() ; Tries.success(true, Codes.HELP) }
Reserved.Version.id -> { context.help.showVersion(); Tries.success(true, Codes.VERSION) }
Reserved.Last.id -> { context.writer.text(lastArgs.get().line, false); Tries.success(true) }
Reserved.Retry.id -> { executeRepl(lastArgs.get()) }
Reserved.Exit.id -> { Tries.success(false, Codes.EXIT) }
Reserved.Quit.id -> { Tries.success(false, Codes.EXIT) }
else -> executeRepl(args)
}
} else {
executeRepl(args)
}
return res
}
/**
* executes a line of text by handing it off to the executor
* This can be overridden in derived class
*/
suspend fun executeText(text: String): Try<CliResponse<*>> {
// Use process for both handling interactive user supplied text
// and also the startup commands
return this.transform(text) { args -> runBlocking { executeArgs(args) } }
}
/**
* Execute the command by delegating work to the actual executor.
* Clients can create their own executor to handle middleware / hooks etc
*/
suspend fun executeArgs(args: Args): Try<CliResponse<*>> {
val request = CliUtils.convert(args)
return executeRequest(request)
}
/**
* Execute the command by delegating work to the actual executor.
* Clients can create their own executor to handle middleware / hooks etc
*/
suspend fun executeRepl(args: Args): Try<Boolean> {
return try {
val request = CliUtils.convert(args)
val result = executeRequest(request)
// If the request was a help at the application level, the app
// should handle that, so don't let it propagate back up because
// we would end up showing help text at the global / CLI level.
val finalResult = when (result.status.code) {
// Even for failure, let the repl continue processing
Codes.HELP.code -> result.withStatus(Codes.SUCCESS, Codes.ERRORED)
else -> result
}
print(finalResult)
finalResult.map { true }
} catch (ex: Exception) {
context.writer.failure(ex.message ?: "", true)
context.writer.failure(ex.stackTrace.toString(), true)
// Keep going until user types exit | quit
Success(true)
}
}
/**
* executes a line of text by handing it off to the executor
* This can be overridden in derived class
*/
open suspend fun executeRequest(request: CliRequest): Try<CliResponse<*>> {
return when (callback) {
null -> CliExecutor().excecute(this, request)
else -> Success(callback.invoke(this, request))
}
}
/**
* Print the result of the CLI command
*/
open fun print(result: Try<CliResponse<*>>) {
val pathToOutputs = folders?.pathToOutputs ?: Paths.get("").toString()
when (result) {
is Success -> context.output.output(Success(result.value), pathToOutputs)
is Failure -> context.output.output(Failure(result.error), pathToOutputs)
}
}
/**
* Gets the last line of text entered
*/
fun last(): String = lastArgs.get().line
/**
* Evaluates the text read in from user input.
*/
private suspend fun <T> transform(text: String, callback: suspend (Args) -> Try<T>): Try<T> {
// Parse lexically into arguments
val argsResult = Args.parse(text, settings.argPrefix, settings.argSeparator, true)
return when (argsResult) {
is Success -> {
callback(argsResult.value)
}
is Failure -> {
context.writer.failure("Error evaluating : $text", true)
// This should never happen if the Args.parse works as expected
argsResult
}
}
}
}
| apache-2.0 | 822229a665e85a39fb25f277ad3746b1 | 33.34202 | 111 | 0.579342 | 4.50941 | false | false | false | false |
leafclick/intellij-community | uast/uast-common/src/org/jetbrains/uast/evaluation/TreeBasedEvaluator.kt | 1 | 31295 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.evaluation
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiType
import com.intellij.psi.PsiVariable
import org.jetbrains.uast.*
import org.jetbrains.uast.values.*
import org.jetbrains.uast.values.UNothingValue.JumpKind.BREAK
import org.jetbrains.uast.values.UNothingValue.JumpKind.CONTINUE
import org.jetbrains.uast.visitor.UastTypedVisitor
class TreeBasedEvaluator(
override val context: UastLanguagePlugin,
val extensions: List<UEvaluatorExtension>
) : UEvaluator {
override fun getDependents(dependency: UDependency): Set<UValue> {
return resultCache.values.map { it.value }.filter { dependency in it.dependencies }.toSet()
}
private val inputStateCache = mutableMapOf<UExpression, UEvaluationState>()
private val resultCache = mutableMapOf<UExpression, UEvaluationInfo>()
private val maxAnalyzeDepth get() = Registry.intValue("uast.evaluator.depth.limit", 15)
private val loopIterationLimit get() = Registry.intValue("uast.evaluator.loop.iteration.limit", 20)
override fun analyze(method: UMethod, state: UEvaluationState) {
method.uastBody?.accept(DepthLimitingEvaluatorVisitor(maxAnalyzeDepth, this::EvaluatingVisitor), state)
}
override fun analyze(field: UField, state: UEvaluationState) {
field.uastInitializer?.accept(DepthLimitingEvaluatorVisitor(maxAnalyzeDepth, this::EvaluatingVisitor), state)
}
internal fun getCached(expression: UExpression): UValue? {
return resultCache[expression]?.value
}
override fun evaluate(expression: UExpression, state: UEvaluationState?): UValue = getEvaluationInfo(expression, state).value
private fun getEvaluationInfo(expression: UExpression, state: UEvaluationState? = null): UEvaluationInfo {
if (state == null) {
val result = resultCache[expression]
if (result != null) return result
}
val inputState = state ?: inputStateCache[expression] ?: expression.createEmptyState()
return expression.accept(DepthLimitingEvaluatorVisitor(maxAnalyzeDepth, this::EvaluatingVisitor), inputState)
}
override fun evaluateVariableByReference(variableReference: UReferenceExpression, state: UEvaluationState?): UValue {
val target = variableReference.resolveToUElement() as? UVariable ?: return UUndeterminedValue
return getEvaluationInfo(variableReference, state).state[target]
}
// ----------------------- //
private infix fun UEvaluationInfo.storeResultFor(expression: UExpression) = apply {
resultCache[expression] = this
}
private inner class EvaluatingVisitor(chain: UastTypedVisitor<UEvaluationState, UEvaluationInfo>?) : UastTypedVisitor<UEvaluationState, UEvaluationInfo> {
private val chain = chain ?: this
override fun visitElement(node: UElement, data: UEvaluationState): UEvaluationInfo {
return UEvaluationInfo(UUndeterminedValue, data).apply {
if (node is UExpression) {
this storeResultFor node
}
}
}
override fun visitLiteralExpression(node: ULiteralExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
val value = node.value
return value.toConstant(node) to data storeResultFor node
}
private fun storeState(node: UExpression, data: UEvaluationState) {
ProgressManager.checkCanceled()
inputStateCache[node] = data
}
override fun visitClassLiteralExpression(node: UClassLiteralExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
return (node.type?.let { value -> UClassConstant(value, node) } ?: UUndeterminedValue) to data storeResultFor node
}
override fun visitReturnExpression(node: UReturnExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
val argument = node.returnExpression
return UValue.UNREACHABLE to (argument?.accept(chain, data)?.state ?: data) storeResultFor node
}
override fun visitBreakExpression(node: UBreakExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
return UNothingValue(node) to data storeResultFor node
}
override fun visitYieldExpression(node: UYieldExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
val value = node.expression?.accept(chain, data)?.let { UYieldResult(it.value, node) } ?: UUndeterminedValue
return value to data storeResultFor node
}
override fun visitContinueExpression(node: UContinueExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
return UNothingValue(node) to data storeResultFor node
}
override fun visitThrowExpression(node: UThrowExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
return UValue.UNREACHABLE to data storeResultFor node
}
// ----------------------- //
override fun visitSimpleNameReferenceExpression(
node: USimpleNameReferenceExpression,
data: UEvaluationState
): UEvaluationInfo {
storeState(node, data)
return when (val resolvedElement = node.resolveToUElement()) {
is UEnumConstant -> UEnumEntryValueConstant(resolvedElement, node)
is UField -> if (resolvedElement.hasModifierProperty(PsiModifier.FINAL)) {
data[resolvedElement].ifUndetermined {
val helper = JavaPsiFacade.getInstance(resolvedElement.project).constantEvaluationHelper
val evaluated = helper.computeConstantExpression(resolvedElement.initializer)
evaluated?.toConstant() ?: UUndeterminedValue
}
}
else {
return super.visitSimpleNameReferenceExpression(node, data)
}
is UVariable -> data[resolvedElement].ifUndetermined {
node.evaluateViaExtensions { evaluateVariable(resolvedElement, data) }?.value ?: UUndeterminedValue
}
else -> return super.visitSimpleNameReferenceExpression(node, data)
} to data storeResultFor node
}
override fun visitReferenceExpression(
node: UReferenceExpression,
data: UEvaluationState
): UEvaluationInfo {
storeState(node, data)
return UCallResultValue(node, emptyList()) to data storeResultFor node
}
// ----------------------- //
private fun UExpression.assign(
valueInfo: UEvaluationInfo,
operator: UastBinaryOperator.AssignOperator = UastBinaryOperator.ASSIGN
): UEvaluationInfo {
this.accept(chain, valueInfo.state)
if (this is UResolvable) {
val resolvedElement = resolve()
if (resolvedElement is PsiVariable) {
val variable = context.convertWithParent<UVariable>(resolvedElement)!!
val currentValue = valueInfo.state[variable]
val result = when (operator) {
UastBinaryOperator.ASSIGN -> valueInfo.value
UastBinaryOperator.PLUS_ASSIGN -> currentValue + valueInfo.value
UastBinaryOperator.MINUS_ASSIGN -> currentValue - valueInfo.value
UastBinaryOperator.MULTIPLY_ASSIGN -> currentValue * valueInfo.value
UastBinaryOperator.DIVIDE_ASSIGN -> currentValue / valueInfo.value
UastBinaryOperator.REMAINDER_ASSIGN -> currentValue % valueInfo.value
UastBinaryOperator.AND_ASSIGN -> currentValue bitwiseAnd valueInfo.value
UastBinaryOperator.OR_ASSIGN -> currentValue bitwiseOr valueInfo.value
UastBinaryOperator.XOR_ASSIGN -> currentValue bitwiseXor valueInfo.value
UastBinaryOperator.SHIFT_LEFT_ASSIGN -> currentValue shl valueInfo.value
UastBinaryOperator.SHIFT_RIGHT_ASSIGN -> currentValue shr valueInfo.value
UastBinaryOperator.UNSIGNED_SHIFT_RIGHT_ASSIGN -> currentValue ushr valueInfo.value
else -> UUndeterminedValue
}
return result to valueInfo.state.assign(variable, result, this)
}
}
return UUndeterminedValue to valueInfo.state
}
private fun UExpression.assign(
operator: UastBinaryOperator.AssignOperator,
value: UExpression,
data: UEvaluationState
) = assign(value.accept(chain, data), operator)
override fun visitPrefixExpression(node: UPrefixExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
val operandInfo = node.operand.accept(chain, data)
val operandValue = operandInfo.value
if (!operandValue.reachable) return operandInfo storeResultFor node
return when (node.operator) {
UastPrefixOperator.UNARY_PLUS -> operandValue
UastPrefixOperator.UNARY_MINUS -> -operandValue
UastPrefixOperator.LOGICAL_NOT -> !operandValue
UastPrefixOperator.INC -> {
val resultValue = operandValue.inc()
val newState = node.operand.assign(resultValue to operandInfo.state).state
return resultValue to newState storeResultFor node
}
UastPrefixOperator.DEC -> {
val resultValue = operandValue.dec()
val newState = node.operand.assign(resultValue to operandInfo.state).state
return resultValue to newState storeResultFor node
}
else -> {
return node.evaluateViaExtensions { evaluatePrefix(node.operator, operandValue, operandInfo.state) }
?: UUndeterminedValue to operandInfo.state storeResultFor node
}
} to operandInfo.state storeResultFor node
}
inline fun UElement.evaluateViaExtensions(block: UEvaluatorExtension.() -> UEvaluationInfo): UEvaluationInfo? {
for (ext in extensions) {
val extResult = ext.block()
if (extResult.value != UUndeterminedValue) return extResult
}
languageExtension()?.block()?.let { if (it.value != UUndeterminedValue) return it }
return null
}
override fun visitPostfixExpression(node: UPostfixExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
val operandInfo = node.operand.accept(chain, data)
val operandValue = operandInfo.value
if (!operandValue.reachable) return operandInfo storeResultFor node
return when (node.operator) {
UastPostfixOperator.INC -> {
operandValue to node.operand.assign(operandValue.inc() to operandInfo.state).state
}
UastPostfixOperator.DEC -> {
operandValue to node.operand.assign(operandValue.dec() to operandInfo.state).state
}
else -> {
return node.evaluateViaExtensions { evaluatePostfix(node.operator, operandValue, operandInfo.state) }
?: UUndeterminedValue to operandInfo.state storeResultFor node
}
} storeResultFor node
}
private fun UastBinaryOperator.evaluate(left: UValue, right: UValue): UValue? =
when (this) {
UastBinaryOperator.PLUS -> left + right
UastBinaryOperator.MINUS -> left - right
UastBinaryOperator.MULTIPLY -> left * right
UastBinaryOperator.DIV -> left / right
UastBinaryOperator.MOD -> left % right
UastBinaryOperator.EQUALS -> left valueEquals right
UastBinaryOperator.NOT_EQUALS -> left valueNotEquals right
UastBinaryOperator.IDENTITY_EQUALS -> left identityEquals right
UastBinaryOperator.IDENTITY_NOT_EQUALS -> left identityNotEquals right
UastBinaryOperator.GREATER -> left greater right
UastBinaryOperator.LESS -> left less right
UastBinaryOperator.GREATER_OR_EQUALS -> left greaterOrEquals right
UastBinaryOperator.LESS_OR_EQUALS -> left lessOrEquals right
UastBinaryOperator.LOGICAL_AND -> left and right
UastBinaryOperator.LOGICAL_OR -> left or right
UastBinaryOperator.BITWISE_AND -> left bitwiseAnd right
UastBinaryOperator.BITWISE_OR -> left bitwiseOr right
UastBinaryOperator.BITWISE_XOR -> left bitwiseXor right
UastBinaryOperator.SHIFT_LEFT -> left shl right
UastBinaryOperator.SHIFT_RIGHT -> left shr right
UastBinaryOperator.UNSIGNED_SHIFT_RIGHT -> left ushr right
else -> null
}
override fun visitBinaryExpression(node: UBinaryExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
val operator = node.operator
if (operator is UastBinaryOperator.AssignOperator) {
return node.leftOperand.assign(operator, node.rightOperand, data) storeResultFor node
}
val leftInfo = node.leftOperand.accept(chain, data)
if (!leftInfo.reachable) {
return leftInfo storeResultFor node
}
val rightInfo = node.rightOperand.accept(chain, leftInfo.state)
operator.evaluate(leftInfo.value, rightInfo.value)?.let {
return it to rightInfo.state storeResultFor node
}
return node.evaluateViaExtensions { evaluateBinary(node, leftInfo.value, rightInfo.value, rightInfo.state) }
?: UUndeterminedValue to rightInfo.state storeResultFor node
}
override fun visitPolyadicExpression(node: UPolyadicExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
val operator = node.operator
val infos = node.operands.map {
it.accept(chain, data).apply {
if (!reachable) {
return this storeResultFor node
}
}
}
val lastInfo = infos.last()
val firstValue = infos.first().value
val restInfos = infos.drop(1)
return restInfos.fold(firstValue) { accumulator, info ->
operator.evaluate(accumulator, info.value) ?: return UUndeterminedValue to info.state storeResultFor node
} to lastInfo.state storeResultFor node
}
private fun evaluateTypeCast(operandInfo: UEvaluationInfo, type: PsiType): UEvaluationInfo {
val constant = operandInfo.value.toConstant() ?: return UUndeterminedValue to operandInfo.state
val resultConstant = when (type) {
PsiType.BOOLEAN -> {
constant as? UBooleanConstant
}
PsiType.CHAR -> when (constant) {
// Join the following three in UNumericConstant
// when https://youtrack.jetbrains.com/issue/KT-14868 is fixed
is UIntConstant -> UCharConstant(constant.value.toChar())
is ULongConstant -> UCharConstant(constant.value.toChar())
is UFloatConstant -> UCharConstant(constant.value.toChar())
is UCharConstant -> constant
else -> null
}
PsiType.LONG -> {
(constant as? UNumericConstant)?.value?.toLong()?.let { value -> ULongConstant(value) }
}
PsiType.BYTE, PsiType.SHORT, PsiType.INT -> {
(constant as? UNumericConstant)?.value?.toInt()?.let { UIntConstant(it, type) }
}
PsiType.FLOAT, PsiType.DOUBLE -> {
(constant as? UNumericConstant)?.value?.toDouble()?.let { UFloatConstant.create(it, type) }
}
else -> when (type.name) {
"java.lang.String" -> UStringConstant(constant.asString())
else -> null
}
} ?: return UUndeterminedValue to operandInfo.state
return when (operandInfo.value) {
resultConstant -> return operandInfo
is UConstant -> resultConstant
is UDependentValue -> UDependentValue.create(resultConstant, operandInfo.value.dependencies)
else -> UUndeterminedValue
} to operandInfo.state
}
private fun evaluateTypeCheck(operandInfo: UEvaluationInfo, type: PsiType): UEvaluationInfo {
val constant = operandInfo.value.toConstant() ?: return UUndeterminedValue to operandInfo.state
val valid = when (type) {
PsiType.BOOLEAN -> constant is UBooleanConstant
PsiType.LONG -> constant is ULongConstant
PsiType.BYTE, PsiType.SHORT, PsiType.INT, PsiType.CHAR -> constant is UIntConstant
PsiType.FLOAT, PsiType.DOUBLE -> constant is UFloatConstant
else -> when (type.name) {
"java.lang.String" -> constant is UStringConstant
else -> false
}
}
return UBooleanConstant.valueOf(valid) to operandInfo.state
}
override fun visitBinaryExpressionWithType(
node: UBinaryExpressionWithType, data: UEvaluationState
): UEvaluationInfo {
storeState(node, data)
val operandInfo = node.operand.accept(chain, data)
if (!operandInfo.reachable || operandInfo.value == UUndeterminedValue) {
return operandInfo storeResultFor node
}
return when (node.operationKind) {
UastBinaryExpressionWithTypeKind.TYPE_CAST -> evaluateTypeCast(operandInfo, node.type)
UastBinaryExpressionWithTypeKind.INSTANCE_CHECK -> evaluateTypeCheck(operandInfo, node.type)
else -> UUndeterminedValue to operandInfo.state
} storeResultFor node
}
override fun visitParenthesizedExpression(node: UParenthesizedExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
return node.expression.accept(chain, data) storeResultFor node
}
override fun visitLabeledExpression(node: ULabeledExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
return node.expression.accept(chain, data) storeResultFor node
}
override fun visitCallExpression(node: UCallExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
var currentInfo = UUndeterminedValue to data
currentInfo = node.receiver?.accept(chain, currentInfo.state) ?: currentInfo
if (!currentInfo.reachable) return currentInfo storeResultFor node
val argumentValues = mutableListOf<UValue>()
for (valueArgument in node.valueArguments) {
currentInfo = valueArgument.accept(chain, currentInfo.state)
if (!currentInfo.reachable) return currentInfo storeResultFor node
argumentValues.add(currentInfo.value)
}
return (node.evaluateViaExtensions {
node.resolve()?.let { method -> evaluateMethodCall(method, argumentValues, currentInfo.state) }
?: UUndeterminedValue to currentInfo.state
} ?: UCallResultValue(node, argumentValues) to currentInfo.state) storeResultFor node
}
override fun visitQualifiedReferenceExpression(
node: UQualifiedReferenceExpression,
data: UEvaluationState
): UEvaluationInfo {
storeState(node, data)
var currentInfo = UUndeterminedValue to data
currentInfo = node.receiver.accept(chain, currentInfo.state)
if (!currentInfo.reachable) return currentInfo storeResultFor node
val selectorInfo = node.selector.accept(chain, currentInfo.state)
return when (node.accessType) {
UastQualifiedExpressionAccessType.SIMPLE -> {
selectorInfo
}
else -> {
return node.evaluateViaExtensions { evaluateQualified(node.accessType, currentInfo, selectorInfo) }
?: UUndeterminedValue to selectorInfo.state storeResultFor node
}
} storeResultFor node
}
override fun visitDeclarationsExpression(
node: UDeclarationsExpression,
data: UEvaluationState
): UEvaluationInfo {
storeState(node, data)
var currentInfo = UUndeterminedValue to data
for (variable in node.declarations) {
currentInfo = variable.accept(chain, currentInfo.state)
if (!currentInfo.reachable) return currentInfo storeResultFor node
}
return currentInfo storeResultFor node
}
override fun visitVariable(node: UVariable, data: UEvaluationState): UEvaluationInfo {
val initializer = node.uastInitializer
val initializerInfo = initializer?.accept(chain, data) ?: UUndeterminedValue to data
if (!initializerInfo.reachable) return initializerInfo
return UUndeterminedValue to initializerInfo.state.assign(node, initializerInfo.value, node)
}
// ----------------------- //
override fun visitBlockExpression(node: UBlockExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
var currentInfo = UUndeterminedValue to data
for (expression in node.expressions) {
currentInfo = expression.accept(chain, currentInfo.state)
if (!currentInfo.reachable) return currentInfo storeResultFor node
}
return currentInfo storeResultFor node
}
override fun visitIfExpression(node: UIfExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
val conditionInfo = node.condition.accept(chain, data)
if (!conditionInfo.reachable) return conditionInfo storeResultFor node
val thenInfo = node.thenExpression?.accept(chain, conditionInfo.state)
val elseInfo = node.elseExpression?.accept(chain, conditionInfo.state)
val conditionValue = conditionInfo.value
val defaultInfo = UUndeterminedValue to conditionInfo.state
val constantConditionValue = conditionValue.toConstant()
return when (constantConditionValue) {
is UBooleanConstant -> {
if (constantConditionValue.value) thenInfo ?: defaultInfo
else elseInfo ?: defaultInfo
}
else -> when {
thenInfo == null -> elseInfo?.merge(defaultInfo) ?: defaultInfo
elseInfo == null -> thenInfo.merge(defaultInfo)
else -> thenInfo.merge(elseInfo)
}
} storeResultFor node
}
override fun visitSwitchExpression(node: USwitchExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
val subjectInfo = node.expression?.accept(chain, data) ?: UUndeterminedValue to data
if (!subjectInfo.reachable) return subjectInfo storeResultFor node
var resultInfo: UEvaluationInfo? = null
var clauseInfo = subjectInfo
var fallThroughCondition: UValue = UBooleanConstant.False
fun List<UExpression>.evaluateAndFold(): UValue =
this.map {
clauseInfo = it.accept(chain, clauseInfo.state)
(clauseInfo.value valueEquals subjectInfo.value).toConstant() as? UValueBase ?: UUndeterminedValue
}.fold(UBooleanConstant.False) { previous: UValue, next -> previous or next }
clausesLoop@ for (expression in node.body.expressions) {
val switchClauseWithBody = expression as USwitchClauseExpressionWithBody
val caseCondition = switchClauseWithBody.caseValues.evaluateAndFold().or(fallThroughCondition)
if (caseCondition != UBooleanConstant.False) {
for (bodyExpression in switchClauseWithBody.body.expressions) {
clauseInfo = bodyExpression.accept(chain, clauseInfo.state)
if (!clauseInfo.reachable) break
}
val clauseValue = clauseInfo.value
if (exitingNode(clauseValue) == node) {
// break from switch
resultInfo = resultInfo merge getBreakResult(clauseInfo)
if (caseCondition == UBooleanConstant.True) break@clausesLoop
clauseInfo = subjectInfo
fallThroughCondition = UBooleanConstant.False
}
// TODO: jump out
else {
fallThroughCondition = caseCondition
clauseInfo = clauseInfo.merge(subjectInfo)
}
}
}
resultInfo = resultInfo ?: subjectInfo
val resultValue = resultInfo.value
if (resultValue is UNothingValue && resultValue.containingLoopOrSwitch == node) {
resultInfo = resultInfo.copy(UUndeterminedValue)
}
return resultInfo storeResultFor node
}
private fun exitingNode(uValue: UValue): UExpression? {
when (uValue) {
is UNothingValue -> return uValue.containingLoopOrSwitch
is UPhiValue -> {
for (value in uValue.values) if (value is UYieldResult) return value.containingLoopOrSwitch
for (value in uValue.values) if (value is UNothingValue) value.containingLoopOrSwitch?.let { return it }
return null
}
else -> return null
}
}
private fun getBreakResult(clauseInfo: UEvaluationInfo): UEvaluationInfo {
val clauseValue = clauseInfo.value
return when (clauseValue) {
is UYieldResult -> clauseValue.value to clauseInfo.state
is UPhiValue -> UPhiValue.create(clauseValue.values.map {
when (it) {
is UYieldResult -> it.value
else -> it
}
}) to clauseInfo.state
else -> clauseInfo
}
}
private fun evaluateLoop(
loop: ULoopExpression,
inputState: UEvaluationState,
condition: UExpression? = null,
infinite: Boolean = false,
update: UExpression? = null
): UEvaluationInfo {
fun evaluateCondition(inputState: UEvaluationState): UEvaluationInfo =
condition?.accept(chain, inputState)
?: (if (infinite) UBooleanConstant.True else UUndeterminedValue) to inputState
var resultInfo = UUndeterminedValue to inputState
var iterationsAllowed = loopIterationLimit
do {
ProgressManager.checkCanceled()
iterationsAllowed--
if (iterationsAllowed <= 0) {
LOG.error("evaluateLoop iterations count exceeded the limit $loopIterationLimit", Attachment("loop.txt", loop.sourcePsi?.text ?: "<no-info>"))
return UUndeterminedValue to inputState storeResultFor loop
}
val previousInfo = resultInfo
resultInfo = evaluateCondition(resultInfo.state)
val conditionConstant = resultInfo.value.toConstant()
if (conditionConstant == UBooleanConstant.False) {
return resultInfo.copy(UUndeterminedValue) storeResultFor loop
}
val bodyInfo = loop.body.accept(chain, resultInfo.state)
val bodyValue = bodyInfo.value
if (bodyValue is UNothingValue) {
if (bodyValue.kind == BREAK && bodyValue.containingLoopOrSwitch == loop) {
return if (conditionConstant == UBooleanConstant.True) {
bodyInfo.copy(UUndeterminedValue)
}
else {
bodyInfo.copy(UUndeterminedValue).merge(previousInfo)
} storeResultFor loop
}
else if (bodyValue.kind == CONTINUE && bodyValue.containingLoopOrSwitch == loop) {
val updateInfo = update?.accept(chain, bodyInfo.state) ?: bodyInfo
resultInfo = updateInfo.copy(UUndeterminedValue).merge(previousInfo)
}
else {
return if (conditionConstant == UBooleanConstant.True) {
bodyInfo
}
else {
resultInfo.copy(UUndeterminedValue)
} storeResultFor loop
}
}
else {
val updateInfo = update?.accept(chain, bodyInfo.state) ?: bodyInfo
resultInfo = updateInfo.merge(previousInfo)
}
}
while (previousInfo != resultInfo)
return resultInfo.copy(UUndeterminedValue) storeResultFor loop
}
override fun visitForEachExpression(node: UForEachExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
val iterableInfo = node.iteratedValue.accept(chain, data)
return evaluateLoop(node, iterableInfo.state)
}
override fun visitForExpression(node: UForExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
val initialState = node.declaration?.accept(chain, data)?.state ?: data
return evaluateLoop(node, initialState, node.condition, node.condition == null, node.update)
}
override fun visitWhileExpression(node: UWhileExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
return evaluateLoop(node, data, node.condition)
}
override fun visitDoWhileExpression(node: UDoWhileExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
val bodyInfo = node.body.accept(chain, data)
return evaluateLoop(node, bodyInfo.state, node.condition)
}
override fun visitTryExpression(node: UTryExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
val tryInfo = node.tryClause.accept(chain, data)
val mergedTryInfo = tryInfo.merge(UUndeterminedValue to data)
val catchInfoList = node.catchClauses.map { it.accept(chain, mergedTryInfo.state) }
val mergedTryCatchInfo = catchInfoList.fold(mergedTryInfo, UEvaluationInfo::merge)
val finallyInfo = node.finallyClause?.accept(chain, mergedTryCatchInfo.state) ?: mergedTryCatchInfo
return finallyInfo storeResultFor node
}
// ----------------------- //
override fun visitObjectLiteralExpression(node: UObjectLiteralExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
val objectInfo = node.declaration.accept(chain, data)
val resultState = data.merge(objectInfo.state)
return UUndeterminedValue to resultState storeResultFor node
}
override fun visitLambdaExpression(node: ULambdaExpression, data: UEvaluationState): UEvaluationInfo {
storeState(node, data)
val lambdaInfo = node.body.accept(chain, data)
val resultState = data.merge(lambdaInfo.state)
return UUndeterminedValue to resultState storeResultFor node
}
override fun visitClass(node: UClass, data: UEvaluationState): UEvaluationInfo {
// fields / initializers / nested classes?
var resultState = data
for (method in node.methods) {
resultState = resultState.merge(method.accept(chain, resultState).state)
}
return UUndeterminedValue to resultState
}
override fun visitMethod(node: UMethod, data: UEvaluationState): UEvaluationInfo {
return UUndeterminedValue to (node.uastBody?.accept(chain, data)?.state ?: data)
}
}
}
fun Any?.toConstant(node: ULiteralExpression? = null): UValueBase = when (this) {
null -> UNullConstant
is Float -> UFloatConstant.create(this.toDouble(), UNumericType.FLOAT, node)
is Double -> UFloatConstant.create(this, UNumericType.DOUBLE, node)
is Long -> ULongConstant(this, node)
is Int -> UIntConstant(this, UNumericType.INT, node)
is Short -> UIntConstant(this.toInt(), UNumericType.SHORT, node)
is Byte -> UIntConstant(this.toInt(), UNumericType.BYTE, node)
is Char -> UCharConstant(this, node)
is Boolean -> UBooleanConstant.valueOf(this)
is String -> UStringConstant(this, node)
else -> UUndeterminedValue
}
private val LOG = Logger.getInstance(TreeBasedEvaluator::class.java)
| apache-2.0 | 04f1deb7ca612f58e513d76bb5e829d0 | 43.015471 | 156 | 0.684454 | 5.424684 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/serialization/CapturedTypes.kt | 1 | 2687 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.serialization
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.*
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.name.*
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.resolve.calls.inference.*
private val konanInternalPackageName = FqName("konan.internal")
private val fakeCapturedTypeClassName = Name.identifier("FAKE_CAPTURED_TYPE_CLASS")
internal fun createFakeClass(packageName: FqName, className: Name)
= MutableClassDescriptor(
EmptyPackageFragmentDescriptor(
ErrorUtils.getErrorModule(),
packageName
),
ClassKind.INTERFACE,
/* isInner = */ false,
/* isExternal = */ false,
className,
SourceElement.NO_SOURCE
)
// We do the trick similar to FAKE_CONTINUATION_CLASS_DESCRIPTOR.
// To pack a captured type constructor as a type parameter
// of a fake class. We need it because type serialization
// protobuf is not expressive enough.
private val FAKE_CAPTURED_TYPE_CLASS_DESCRIPTOR
= createFakeClass(konanInternalPackageName, fakeCapturedTypeClassName)
.apply {
modality = Modality.ABSTRACT
visibility = Visibilities.PUBLIC
setTypeParameterDescriptors(
TypeParameterDescriptorImpl
.createWithDefaultBound(
this, Annotations.EMPTY,
false, Variance.IN_VARIANCE,
Name.identifier("Projection"),
/* index = */ 0
).let(::listOf)
)
createTypeConstructor()
}
internal fun packCapturedType(type: CapturedType): SimpleType =
KotlinTypeFactory.simpleType(
Annotations.EMPTY,
FAKE_CAPTURED_TYPE_CLASS_DESCRIPTOR.typeConstructor,
listOf(type.typeProjection),
nullable = false
)
internal fun unpackCapturedType(type: KotlinType)
= createCapturedType(type.arguments.single())
| apache-2.0 | 84dcdf1e57868fb406d9ab9ff6fde947 | 36.319444 | 83 | 0.684779 | 4.850181 | false | false | false | false |
googlearchive/android-ConstraintLayoutExamples | motionlayout/src/main/java/com/google/androidstudio/motionlayoutexample/fragmentsdemo/ListFragment.kt | 2 | 2556 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.androidstudio.motionlayoutexample.fragmentsdemo
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.androidstudio.motionlayoutexample.R
class ListFragment : Fragment() {
private lateinit var recyclerView: RecyclerView
companion object {
fun newInstance() = ListFragment()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
Log.i(ListFragment::class.java.simpleName, "onCreateView, container is $container")
return inflater.inflate(R.layout.motion_22_list_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
recyclerView = view.findViewById(R.id.list)
recyclerView.layoutManager = LinearLayoutManager(
context, RecyclerView.VERTICAL, false)
val users = ArrayList<User>()
users.add(User("Paul", "Mr"))
users.add(User("Jane", "Miss"))
users.add(User("John", "Dr"))
users.add(User("Amy", "Mrs"))
users.add(User("Paul", "Mr"))
users.add(User("Jane", "Miss"))
users.add(User("John", "Dr"))
users.add(User("Amy", "Mrs"))
users.add(User("Paul", "Mr"))
users.add(User("Jane", "Miss"))
users.add(User("John", "Dr"))
users.add(User("Amy", "Mrs"))
users.add(User("Paul", "Mr"))
users.add(User("Jane", "Miss"))
users.add(User("John", "Dr"))
users.add(User("Amy", "Mrs"))
val adapter = CustomAdapter(users)
recyclerView.adapter = adapter
super.onViewCreated(view, savedInstanceState)
}
}
| apache-2.0 | be6280b926794b4fb1ae11f8fb078f20 | 35 | 91 | 0.672535 | 4.190164 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/annotations/openSuspendFun.kt | 1 | 642 | // WITH_REFLECT
// IGNORE_BACKEND: JS, NATIVE
import kotlin.reflect.full.declaredMemberFunctions
import kotlin.test.assertEquals
import kotlin.test.assertTrue
annotation class Anno
open class Aaa {
@Anno
suspend open fun aaa() {}
}
class Bbb {
@Anno
suspend fun bbb() {}
}
fun box(): String {
val bbb = Bbb::class.declaredMemberFunctions.first { it.name == "bbb" }.annotations
assertEquals(1, bbb.size)
assertTrue(bbb.single() is Anno)
val aaa = Aaa::class.declaredMemberFunctions.first { it.name == "aaa" }.annotations
assertEquals(1, aaa.size)
assertTrue(aaa.single() is Anno)
return "OK"
}
| apache-2.0 | a4e1cdd4085f099d28841b99600404cd | 21.928571 | 87 | 0.690031 | 3.668571 | false | true | false | false |
smmribeiro/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/bridgeModelModifiableEntities.kt | 2 | 24508 | // 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.workspaceModel.storage.bridgeEntities
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageDiffBuilder
import com.intellij.workspaceModel.storage.impl.EntityDataDelegation
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.ModuleDependencyEntityDataDelegation
import com.intellij.workspaceModel.storage.impl.indices.VirtualFileUrlLibraryRootProperty
import com.intellij.workspaceModel.storage.impl.indices.VirtualFileUrlListProperty
import com.intellij.workspaceModel.storage.impl.indices.VirtualFileUrlNullableProperty
import com.intellij.workspaceModel.storage.impl.indices.VirtualFileUrlProperty
import com.intellij.workspaceModel.storage.impl.references.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
private val LOG = logger<WorkspaceEntityStorage>()
class ModifiableModuleEntity : ModifiableWorkspaceEntityBase<ModuleEntity>() {
internal var dependencyChanged = false
var name: String by EntityDataDelegation()
var type: String? by EntityDataDelegation()
var dependencies: List<ModuleDependencyItem> by ModuleDependencyEntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addModuleEntity(name: String, dependencies: List<ModuleDependencyItem>, source: EntitySource,
type: String? = null): ModuleEntity {
LOG.debug { "Add moduleEntity: $name" }
return addEntity(ModifiableModuleEntity::class.java, source) {
this.name = name
this.type = type
this.dependencies = dependencies
}
}
class ModifiableJavaModuleSettingsEntity : ModifiableWorkspaceEntityBase<JavaModuleSettingsEntity>() {
var inheritedCompilerOutput: Boolean by EntityDataDelegation()
var excludeOutput: Boolean by EntityDataDelegation()
var compilerOutput: VirtualFileUrl? by VirtualFileUrlNullableProperty()
var compilerOutputForTests: VirtualFileUrl? by VirtualFileUrlNullableProperty()
var languageLevelId: String? by EntityDataDelegation()
var module: ModuleEntity by MutableOneToOneChild.NotNull(JavaModuleSettingsEntity::class.java, ModuleEntity::class.java)
}
fun WorkspaceEntityStorageDiffBuilder.addJavaModuleSettingsEntity(inheritedCompilerOutput: Boolean,
excludeOutput: Boolean,
compilerOutput: VirtualFileUrl?,
compilerOutputForTests: VirtualFileUrl?,
languageLevelId: String?,
module: ModuleEntity,
source: EntitySource) = addEntity(
ModifiableJavaModuleSettingsEntity::class.java, source) {
this.inheritedCompilerOutput = inheritedCompilerOutput
this.excludeOutput = excludeOutput
this.compilerOutput = compilerOutput
this.compilerOutputForTests = compilerOutputForTests
this.languageLevelId = languageLevelId
this.module = module
}
class ModifiableModuleCustomImlDataEntity : ModifiableWorkspaceEntityBase<ModuleCustomImlDataEntity>() {
var rootManagerTagCustomData: String? by EntityDataDelegation()
var customModuleOptions: MutableMap<String, String> by EntityDataDelegation()
var module: ModuleEntity by MutableOneToOneChild.NotNull(ModuleCustomImlDataEntity::class.java, ModuleEntity::class.java)
}
fun WorkspaceEntityStorageDiffBuilder.addModuleCustomImlDataEntity(rootManagerTagCustomData: String?,
customModuleOptions: Map<String, String>,
module: ModuleEntity,
source: EntitySource) = addEntity(
ModifiableModuleCustomImlDataEntity::class.java, source) {
this.rootManagerTagCustomData = rootManagerTagCustomData
this.customModuleOptions = HashMap(customModuleOptions)
this.module = module
}
class ModifiableModuleGroupPathEntity : ModifiableWorkspaceEntityBase<ModuleGroupPathEntity>() {
var path: List<String> by EntityDataDelegation()
var module: ModuleEntity by MutableOneToOneChild.NotNull(ModuleGroupPathEntity::class.java, ModuleEntity::class.java)
}
fun WorkspaceEntityStorageDiffBuilder.addModuleGroupPathEntity(path: List<String>,
module: ModuleEntity, source: EntitySource) = addEntity(
ModifiableModuleGroupPathEntity::class.java, source) {
this.path = path
this.module = module
}
class ModifiableSourceRootEntity : ModifiableWorkspaceEntityBase<SourceRootEntity>() {
var contentRoot: ContentRootEntity by MutableManyToOne.NotNull(SourceRootEntity::class.java, ContentRootEntity::class.java)
var url: VirtualFileUrl by VirtualFileUrlProperty()
var rootType: String by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addSourceRootEntity(contentRoot: ContentRootEntity,
url: VirtualFileUrl,
rootType: String, source: EntitySource) = addEntity(
ModifiableSourceRootEntity::class.java, source) {
this.contentRoot = contentRoot
this.url = url
this.rootType = rootType
}
class ModifiableJavaSourceRootEntity : ModifiableWorkspaceEntityBase<JavaSourceRootEntity>() {
var sourceRoot: SourceRootEntity by MutableManyToOne.NotNull(JavaSourceRootEntity::class.java, SourceRootEntity::class.java)
var generated: Boolean by EntityDataDelegation()
var packagePrefix: String by EntityDataDelegation()
}
/**
* [JavaSourceRootEntity] has the same entity source as [SourceRootEntity].
* [JavaSourceRootEntityData] contains assertion for that. Please update an assertion in case you need a different entity source for these
* entities.
*/
fun WorkspaceEntityStorageDiffBuilder.addJavaSourceRootEntity(sourceRoot: SourceRootEntity,
generated: Boolean,
packagePrefix: String) = addEntity(
ModifiableJavaSourceRootEntity::class.java, sourceRoot.entitySource) {
this.sourceRoot = sourceRoot
this.generated = generated
this.packagePrefix = packagePrefix
}
class ModifiableJavaResourceRootEntity : ModifiableWorkspaceEntityBase<JavaResourceRootEntity>() {
var sourceRoot: SourceRootEntity by MutableManyToOne.NotNull(JavaResourceRootEntity::class.java, SourceRootEntity::class.java)
var generated: Boolean by EntityDataDelegation()
var relativeOutputPath: String by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addJavaResourceRootEntity(sourceRoot: SourceRootEntity,
generated: Boolean,
relativeOutputPath: String) = addEntity(
ModifiableJavaResourceRootEntity::class.java, sourceRoot.entitySource) {
this.sourceRoot = sourceRoot
this.generated = generated
this.relativeOutputPath = relativeOutputPath
}
class ModifiableCustomSourceRootPropertiesEntity : ModifiableWorkspaceEntityBase<CustomSourceRootPropertiesEntity>() {
var sourceRoot: SourceRootEntity by MutableManyToOne.NotNull(CustomSourceRootPropertiesEntity::class.java, SourceRootEntity::class.java)
var propertiesXmlTag: String by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addCustomSourceRootPropertiesEntity(sourceRoot: SourceRootEntity, propertiesXmlTag: String) = addEntity(
ModifiableCustomSourceRootPropertiesEntity::class.java, sourceRoot.entitySource) {
this.sourceRoot = sourceRoot
this.propertiesXmlTag = propertiesXmlTag
}
class ModifiableContentRootEntity : ModifiableWorkspaceEntityBase<ContentRootEntity>() {
var url: VirtualFileUrl by VirtualFileUrlProperty()
var excludedUrls: List<VirtualFileUrl> by VirtualFileUrlListProperty()
var excludedPatterns: List<String> by EntityDataDelegation()
var module: ModuleEntity by MutableManyToOne.NotNull(ContentRootEntity::class.java, ModuleEntity::class.java)
}
fun WorkspaceEntityStorageDiffBuilder.addContentRootEntity(url: VirtualFileUrl,
excludedUrls: List<VirtualFileUrl>,
excludedPatterns: List<String>,
module: ModuleEntity): ContentRootEntity {
return addContentRootEntityWithCustomEntitySource(url, excludedUrls, excludedPatterns, module, module.entitySource)
}
/**
* Entity source of content root is *almost* the same as the entity source of the corresponding module.
* Please update assertConsistency in [ContentRootEntityData] if you're using this method.
*/
fun WorkspaceEntityStorageDiffBuilder.addContentRootEntityWithCustomEntitySource(url: VirtualFileUrl,
excludedUrls: List<VirtualFileUrl>,
excludedPatterns: List<String>,
module: ModuleEntity, source: EntitySource) = addEntity(
ModifiableContentRootEntity::class.java, source) {
this.url = url
this.excludedUrls = excludedUrls
this.excludedPatterns = excludedPatterns
this.module = module
}
class ModifiableLibraryEntity : ModifiableWorkspaceEntityBase<LibraryEntity>() {
var tableId: LibraryTableId by EntityDataDelegation()
var name: String by EntityDataDelegation()
var roots: List<LibraryRoot> by VirtualFileUrlLibraryRootProperty()
var excludedRoots: List<VirtualFileUrl> by VirtualFileUrlListProperty()
}
fun WorkspaceEntityStorageDiffBuilder.addLibraryEntity(name: String, tableId: LibraryTableId, roots: List<LibraryRoot>,
excludedRoots: List<VirtualFileUrl>, source: EntitySource) = addEntity(
ModifiableLibraryEntity::class.java, source) {
this.tableId = tableId
this.name = name
this.roots = roots
this.excludedRoots = excludedRoots
}
class ModifiableLibraryPropertiesEntity : ModifiableWorkspaceEntityBase<LibraryPropertiesEntity>() {
var library: LibraryEntity by MutableOneToOneChild.NotNull(LibraryPropertiesEntity::class.java, LibraryEntity::class.java)
var libraryType: String by EntityDataDelegation()
var propertiesXmlTag: String? by EntityDataDelegation()
}
/**
* [LibraryPropertiesEntity] has the same entity source as [LibraryEntity].
* [LibraryPropertiesEntityData] contains assertion for that. Please update an assertion in case you need a different entity source for these
* entities.
*/
fun WorkspaceEntityStorageDiffBuilder.addLibraryPropertiesEntity(library: LibraryEntity,
libraryType: String,
propertiesXmlTag: String?) = addEntity(
ModifiableLibraryPropertiesEntity::class.java, library.entitySource) {
this.library = library
this.libraryType = libraryType
this.propertiesXmlTag = propertiesXmlTag
}
class ModifiableSdkEntity : ModifiableWorkspaceEntityBase<SdkEntity>() {
var library: LibraryEntity by MutableOneToOneChild.NotNull(SdkEntity::class.java, LibraryEntity::class.java)
var homeUrl: VirtualFileUrl by VirtualFileUrlProperty()
}
fun WorkspaceEntityStorageDiffBuilder.addSdkEntity(library: LibraryEntity,
homeUrl: VirtualFileUrl, source: EntitySource) = addEntity(ModifiableSdkEntity::class.java,
source) {
this.library = library
this.homeUrl = homeUrl
}
class ModifiableExternalSystemModuleOptionsEntity : ModifiableWorkspaceEntityBase<ExternalSystemModuleOptionsEntity>() {
var module: ModuleEntity by MutableOneToOneChild.NotNull(ExternalSystemModuleOptionsEntity::class.java, ModuleEntity::class.java)
var externalSystem: String? by EntityDataDelegation()
var externalSystemModuleVersion: String? by EntityDataDelegation()
var linkedProjectPath: String? by EntityDataDelegation()
var linkedProjectId: String? by EntityDataDelegation()
var rootProjectPath: String? by EntityDataDelegation()
var externalSystemModuleGroup: String? by EntityDataDelegation()
var externalSystemModuleType: String? by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.getOrCreateExternalSystemModuleOptions(module: ModuleEntity,
source: EntitySource): ExternalSystemModuleOptionsEntity =
module.externalSystemOptions ?: addEntity(ModifiableExternalSystemModuleOptionsEntity::class.java, source) {
this.module = module
}
class ModifiableFacetEntity : ModifiableWorkspaceEntityBase<FacetEntity>() {
var name: String by EntityDataDelegation()
var facetType: String by EntityDataDelegation()
var configurationXmlTag: String? by EntityDataDelegation()
var moduleId: ModuleId by EntityDataDelegation()
var module: ModuleEntity by MutableManyToOne.NotNull(FacetEntity::class.java, ModuleEntity::class.java)
var underlyingFacet: FacetEntity? by MutableManyToOne.Nullable(FacetEntity::class.java, FacetEntity::class.java)
}
fun WorkspaceEntityStorageDiffBuilder.addFacetEntity(name: String, facetType: String, configurationXmlTag: String?, module: ModuleEntity,
underlyingFacet: FacetEntity?, source: EntitySource) =
addEntity(ModifiableFacetEntity::class.java, source) {
this.name = name
this.facetType = facetType
this.configurationXmlTag = configurationXmlTag
this.module = module
this.underlyingFacet = underlyingFacet
this.moduleId = module.persistentId()
}
class ModifiableArtifactEntity : ModifiableWorkspaceEntityBase<ArtifactEntity>() {
var name: String by EntityDataDelegation()
var artifactType: String by EntityDataDelegation()
var includeInProjectBuild: Boolean by EntityDataDelegation()
var outputUrl: VirtualFileUrl? by VirtualFileUrlNullableProperty()
var rootElement: CompositePackagingElementEntity? by MutableOneToAbstractOneParent(ArtifactEntity::class.java,
CompositePackagingElementEntity::class.java)
var customProperties: Sequence<ArtifactPropertiesEntity> by customPropertiesDelegate
companion object {
val customPropertiesDelegate = MutableOneToMany<ArtifactEntity, ArtifactPropertiesEntity, ModifiableArtifactEntity>(ArtifactEntity::class.java, ArtifactPropertiesEntity::class.java, false)
}
}
fun WorkspaceEntityStorageDiffBuilder.addArtifactEntity(name: String,
artifactType: String,
includeInProjectBuild: Boolean,
outputUrl: VirtualFileUrl?,
rootElement: CompositePackagingElementEntity,
source: EntitySource): ArtifactEntity {
return addEntity(ModifiableArtifactEntity::class.java, source) {
this.name = name
this.artifactType = artifactType
this.includeInProjectBuild = includeInProjectBuild
this.outputUrl = outputUrl
this.rootElement = rootElement
}
}
class ModifiableArtifactPropertiesEntity : ModifiableWorkspaceEntityBase<ArtifactPropertiesEntity>() {
var artifact: ArtifactEntity by MutableManyToOne.NotNull(ArtifactPropertiesEntity::class.java, ArtifactEntity::class.java)
var providerType: String by EntityDataDelegation()
var propertiesXmlTag: String? by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addArtifactPropertiesEntity(artifact: ArtifactEntity,
providerType: String,
propertiesXmlTag: String?,
source: EntitySource): ArtifactPropertiesEntity {
return addEntity(ModifiableArtifactPropertiesEntity::class.java, source) {
this.artifact = artifact
this.providerType = providerType
this.propertiesXmlTag = propertiesXmlTag
}
}
abstract class ModifiableCompositePackagingElementEntity<T: CompositePackagingElementEntity>(clazz: Class<T>) : ModifiableWorkspaceEntityBase<T>() {
var children: Sequence<PackagingElementEntity> by MutableOneToAbstractMany(clazz, PackagingElementEntity::class.java)
}
class ModifiableArtifactRootElementEntity : ModifiableCompositePackagingElementEntity<ArtifactRootElementEntity>(
ArtifactRootElementEntity::class.java
)
fun WorkspaceEntityStorageDiffBuilder.addArtifactRootElementEntity(children: List<PackagingElementEntity>,
source: EntitySource): ArtifactRootElementEntity {
return addEntity(ModifiableArtifactRootElementEntity::class.java, source) {
this.children = children.asSequence()
}
}
class ModifiableDirectoryPackagingElementEntity : ModifiableCompositePackagingElementEntity<DirectoryPackagingElementEntity>(
DirectoryPackagingElementEntity::class.java) {
var directoryName: String by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addDirectoryPackagingElementEntity(directoryName: String,
children: List<PackagingElementEntity>,
source: EntitySource): DirectoryPackagingElementEntity {
return addEntity(ModifiableDirectoryPackagingElementEntity::class.java, source) {
this.directoryName = directoryName
this.children = children.asSequence()
}
}
class ModifiableArchivePackagingElementEntity : ModifiableCompositePackagingElementEntity<ArchivePackagingElementEntity>(
ArchivePackagingElementEntity::class.java) {
var fileName: String by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addArchivePackagingElementEntity(fileName: String,
children: List<PackagingElementEntity>,
source: EntitySource): ArchivePackagingElementEntity {
return addEntity(ModifiableArchivePackagingElementEntity::class.java, source) {
this.fileName = fileName
this.children = children.asSequence()
}
}
class ModifiableArtifactOutputPackagingElementEntity : ModifiableWorkspaceEntityBase<ArtifactOutputPackagingElementEntity>() {
var artifact: ArtifactId? by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addArtifactOutputPackagingElementEntity(artifact: ArtifactId?, source: EntitySource): ArtifactOutputPackagingElementEntity {
return addEntity(ModifiableArtifactOutputPackagingElementEntity::class.java, source) {
this.artifact = artifact
}
}
class ModifiableModuleOutputPackagingElementEntity : ModifiableWorkspaceEntityBase<ModuleOutputPackagingElementEntity>() {
var module: ModuleId? by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addModuleOutputPackagingElementEntity(module: ModuleId?, source: EntitySource): ModuleOutputPackagingElementEntity {
return addEntity(ModifiableModuleOutputPackagingElementEntity::class.java, source) {
this.module = module
}
}
class ModifiableLibraryFilesPackagingElementEntity : ModifiableWorkspaceEntityBase<LibraryFilesPackagingElementEntity>() {
var library: LibraryId? by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addLibraryFilesPackagingElementEntity(library: LibraryId?, source: EntitySource): LibraryFilesPackagingElementEntity {
return addEntity(ModifiableLibraryFilesPackagingElementEntity::class.java, source) {
this.library = library
}
}
class ModifiableModuleSourcePackagingElementEntity : ModifiableWorkspaceEntityBase<ModuleSourcePackagingElementEntity>() {
var module: ModuleId? by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addModuleSourcePackagingElementEntity(module: ModuleId?, source: EntitySource): ModuleSourcePackagingElementEntity {
return addEntity(ModifiableModuleSourcePackagingElementEntity::class.java, source) {
this.module = module
}
}
class ModifiableModuleTestOutputPackagingElementEntity : ModifiableWorkspaceEntityBase<ModuleTestOutputPackagingElementEntity>() {
var module: ModuleId? by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addModuleTestOutputPackagingElementEntity(module: ModuleId?, source: EntitySource): ModuleTestOutputPackagingElementEntity {
return addEntity(ModifiableModuleTestOutputPackagingElementEntity::class.java, source) {
this.module = module
}
}
abstract class ModifiableFileOrDirectoryPackagingElement<T : FileOrDirectoryPackagingElementEntity> : ModifiableWorkspaceEntityBase<T>() {
var filePath: VirtualFileUrl by VirtualFileUrlProperty()
}
class ModifiableDirectoryCopyPackagingElementEntity : ModifiableFileOrDirectoryPackagingElement<DirectoryCopyPackagingElementEntity>()
fun WorkspaceEntityStorageDiffBuilder.addDirectoryCopyPackagingElementEntity(filePath: VirtualFileUrl, source: EntitySource): DirectoryCopyPackagingElementEntity {
return addEntity(ModifiableDirectoryCopyPackagingElementEntity::class.java, source) {
this.filePath = filePath
}
}
class ModifiableExtractedDirectoryPackagingElementEntity : ModifiableFileOrDirectoryPackagingElement<ExtractedDirectoryPackagingElementEntity>() {
var pathInArchive: String by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addExtractedDirectoryPackagingElementEntity(filePath: VirtualFileUrl,
pathInArchive: String,
source: EntitySource): ExtractedDirectoryPackagingElementEntity {
return addEntity(ModifiableExtractedDirectoryPackagingElementEntity::class.java, source) {
this.filePath = filePath
this.pathInArchive = pathInArchive
}
}
class ModifiableFileCopyPackagingElementEntity : ModifiableFileOrDirectoryPackagingElement<FileCopyPackagingElementEntity>() {
var renamedOutputFileName: String? by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addFileCopyPackagingElementEntity(filePath: VirtualFileUrl,
renamedOutputFileName: String?,
source: EntitySource): FileCopyPackagingElementEntity {
return addEntity(ModifiableFileCopyPackagingElementEntity::class.java, source) {
this.filePath = filePath
this.renamedOutputFileName = renamedOutputFileName
}
}
class ModifiableCustomPackagingElementEntity : ModifiableCompositePackagingElementEntity<CustomPackagingElementEntity>(CustomPackagingElementEntity::class.java) {
var typeId: String by EntityDataDelegation()
var propertiesXmlTag: String by EntityDataDelegation()
}
fun WorkspaceEntityStorageDiffBuilder.addCustomPackagingElementEntity(typeId: String,
propertiesXmlTag: String,
children: List<PackagingElementEntity>,
source: EntitySource): CustomPackagingElementEntity {
return addEntity(ModifiableCustomPackagingElementEntity::class.java, source) {
this.typeId = typeId
this.propertiesXmlTag = propertiesXmlTag
this.children = children.asSequence()
}
}
| apache-2.0 | b8b529adb9a63e84debfe62ac2f3db01 | 52.16269 | 192 | 0.7185 | 7.010297 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameParameterToMatchOverriddenMethodFix.kt | 5 | 2049 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.refactoring.rename.RenameProcessor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToParameterDescriptorIfAny
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class RenameParameterToMatchOverriddenMethodFix(
parameter: KtParameter,
private val newName: String
) : KotlinQuickFixAction<KtParameter>(parameter) {
override fun getFamilyName() = KotlinBundle.message("rename.identifier.fix.text")
override fun getText() = KotlinBundle.message("rename.parameter.to.match.overridden.method")
override fun startInWriteAction(): Boolean = false
public override fun invoke(project: Project, editor: Editor?, file: KtFile) {
RenameProcessor(project, element ?: return, newName, false, false).run()
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val parameter = diagnostic.psiElement.getNonStrictParentOfType<KtParameter>() ?: return null
val parameterDescriptor = parameter.resolveToParameterDescriptorIfAny(BodyResolveMode.FULL) ?: return null
val parameterFromSuperclassName = parameterDescriptor.overriddenDescriptors
.map { it.name.asString() }
.distinct()
.singleOrNull() ?: return null
return RenameParameterToMatchOverriddenMethodFix(parameter, parameterFromSuperclassName)
}
}
}
| apache-2.0 | cb4daf5766aa5be2cbe1c85fa33b1b0a | 47.785714 | 158 | 0.768668 | 5.084367 | false | false | false | false |
smmribeiro/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/model/completion/MavenGroupIdCompletionContributor.kt | 10 | 2944 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.dom.model.completion
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.NlsContexts
import org.jetbrains.concurrency.Promise
import org.jetbrains.idea.maven.dom.converters.MavenDependencyCompletionUtil
import org.jetbrains.idea.maven.dom.model.MavenDomShortArtifactCoordinates
import org.jetbrains.idea.maven.dom.model.completion.insert.MavenDependencyInsertionHandler
import org.jetbrains.idea.maven.indices.IndicesBundle
import org.jetbrains.idea.maven.onlinecompletion.model.MavenRepositoryArtifactInfo
import org.jetbrains.idea.reposearch.DependencySearchService
import org.jetbrains.idea.reposearch.RepositoryArtifactData
import java.util.concurrent.ConcurrentLinkedDeque
import java.util.function.Consumer
import java.util.function.Predicate
class MavenGroupIdCompletionContributor : MavenCoordinateCompletionContributor("groupId") {
override fun handleEmptyLookup(parameters: CompletionParameters, editor: Editor): @NlsContexts.HintText String? {
return if (PlaceChecker(parameters).checkPlace().isCorrectPlace()) {
IndicesBundle.message("maven.dependency.completion.group.empty")
}
else null
}
override fun find(service: DependencySearchService,
coordinates: MavenDomShortArtifactCoordinates,
parameters: CompletionParameters,
consumer: Consumer<RepositoryArtifactData>): Promise<Int> {
val searchParameters = createSearchParameters(parameters)
val groupId = trimDummy(coordinates.groupId.stringValue)
val artifactId = trimDummy(coordinates.artifactId.stringValue)
return service.suggestPrefix(groupId, artifactId, searchParameters, withPredicate(consumer,
Predicate { it is MavenRepositoryArtifactInfo && (artifactId.isEmpty() || artifactId == it.artifactId) }))
}
override fun fillResults(result: CompletionResultSet,
coordinates: MavenDomShortArtifactCoordinates,
cld: ConcurrentLinkedDeque<RepositoryArtifactData>,
promise: Promise<Int>) {
val set = HashSet<String>()
while (promise.state == Promise.State.PENDING || !cld.isEmpty()) {
ProgressManager.checkCanceled()
val item = cld.poll()
if (item is MavenRepositoryArtifactInfo && set.add(item.groupId)) {
result
.addElement(
MavenDependencyCompletionUtil.lookupElement(item, item.groupId).withInsertHandler(MavenDependencyInsertionHandler.INSTANCE))
}
}
}
}
| apache-2.0 | a7df8a8f07f273e2f2d2639d110ee4d5 | 51.571429 | 192 | 0.745245 | 5.294964 | false | false | false | false |
kpi-ua/ecampus-client-android | app/src/main/java/com/goldenpiedevs/schedule/app/ui/base/BaseFragment.kt | 1 | 1744 | package com.goldenpiedevs.schedule.app.ui.base
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.Nullable
import com.goldenpiedevs.schedule.app.ui.view.hideSoftKeyboard
import java.util.concurrent.atomic.AtomicLong
abstract class BaseFragment : androidx.fragment.app.Fragment(), BaseView {
companion object {
const val KEY_FRAGMENT_ID = "KEY_ACTIVITY_ID"
}
private var root: View? = null
private var nextId = AtomicLong(0)
private var fragmentId: Long = 0
abstract fun getFragmentLayout(): Int
override fun getContext(): Context {
return this.activity!!
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
}
override fun getIt() = this
@Nullable
override fun onCreateView(inflater: LayoutInflater, @Nullable container: ViewGroup?, @Nullable savedInstanceState: Bundle?): View? {
fragmentId = savedInstanceState?.getLong(BaseFragment.KEY_FRAGMENT_ID)
?: nextId.getAndIncrement()
root = inflater.inflate(getFragmentLayout(), container, false)
return root
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putLong(KEY_FRAGMENT_ID, fragmentId)
}
override fun showProgressDialog() {
if (isAdded) {
hideSoftKeyboard()
(activity as BaseActivity<*, *>).showProgressDialog()
}
}
override fun dismissProgressDialog() {
if (isAdded) (activity as BaseActivity<*, *>).dismissProgressDialog()
}
} | apache-2.0 | 0c68c9464062d4ec802d4f09d4ed3828 | 28.576271 | 136 | 0.695528 | 4.94051 | false | false | false | false |
smmribeiro/intellij-community | java/java-impl/src/com/intellij/lang/java/actions/FieldExpression.kt | 5 | 2236 | // 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.lang.java.actions
import com.intellij.codeInsight.completion.JavaLookupElementBuilder
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.codeInsight.lookup.LookupFocusDegree
import com.intellij.codeInsight.template.Expression
import com.intellij.codeInsight.template.ExpressionContext
import com.intellij.codeInsight.template.Result
import com.intellij.codeInsight.template.TextResult
import com.intellij.icons.AllIcons
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.util.createSmartPointer
import com.intellij.ui.LayeredIcon
private val newFieldIcon by lazy { LayeredIcon.create(AllIcons.Nodes.Field, AllIcons.Actions.New) }
internal class FieldExpression(
project: Project,
target: PsiClass,
private val fieldName: String,
private val typeText: () -> String
) : Expression() {
private val myClassPointer = target.createSmartPointer(project)
private val myFactory = JavaPsiFacade.getElementFactory(project)
override fun calculateResult(context: ExpressionContext): Result? = TextResult(fieldName)
override fun calculateLookupItems(context: ExpressionContext): Array<LookupElement> {
val psiClass = myClassPointer.element ?: return LookupElement.EMPTY_ARRAY
val userType = myFactory.createTypeFromText(typeText(), psiClass)
val result = LinkedHashSet<LookupElement>()
if (psiClass.findFieldByName(fieldName, false) == null) {
result += LookupElementBuilder.create(fieldName).withIcon(newFieldIcon).withTypeText(userType.presentableText)
}
for (field in psiClass.fields) {
val fieldType = field.type
if (userType == fieldType) {
result += JavaLookupElementBuilder.forField(field).withTypeText(fieldType.presentableText)
}
}
return if (result.size < 2) LookupElement.EMPTY_ARRAY else result.toTypedArray()
}
override fun getLookupFocusDegree(): LookupFocusDegree {
return LookupFocusDegree.UNFOCUSED
}
}
| apache-2.0 | 207a9a69eb465b49adf4fac8cc7331e3 | 41.188679 | 140 | 0.793381 | 4.639004 | false | false | false | false |
Flank/flank | common/src/main/kotlin/flank/common/OutputLogger.kt | 1 | 481 | package flank.common
fun setLogLevel(logLevel: OutputLogLevel) {
minimumLogLevel = logLevel
}
fun log(message: Any, level: OutputLogLevel = OutputLogLevel.SIMPLE) {
if (minimumLogLevel >= level) print(message)
}
fun logLn(message: Any = "", level: OutputLogLevel = OutputLogLevel.SIMPLE) {
if (minimumLogLevel >= level) println(message)
}
private var minimumLogLevel: OutputLogLevel = OutputLogLevel.DETAILED
enum class OutputLogLevel {
SIMPLE,
DETAILED
}
| apache-2.0 | 9f07adc8f1774691bd132b1eb04b7899 | 23.05 | 77 | 0.742204 | 3.942623 | false | false | false | false |
nonylene/PhotoLinkViewer-Core | photolinkviewer-core/src/main/java/net/nonylene/photolinkviewer/core/tool/Initialize.kt | 1 | 2912 | package net.nonylene.photolinkviewer.core.tool
import android.content.Context
import android.content.SharedPreferences
import android.net.http.HttpResponseCache
import android.preference.PreferenceManager
object Initialize {
private val sites = arrayOf("flickr", "twitter", "twipple", "imgly", "instagram", "nicoseiga", "tumblr")
fun initialize39(context: Context) {
// ver 39 (clear old cache)
HttpResponseCache.getInstalled()?.delete()
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putBoolean("initialized39", true)
.apply()
}
fun initialize47(context: Context) {
// ver 47 (move preference keys)
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val zoomSpeed = pref.getString("zoom_speed", "1.4")
val isVideoPlay = pref.getBoolean("video_play", true)
val isAdjustZoom = pref.getBoolean("adjust_zoom", false)
val downloadDir = pref.getString("download_dir", "PLViewer/")
val downloadDirType = pref.getString("download_file", "mkdir-username")
val isSkipDialog = pref.getBoolean("skip_dialog", false)
val isLeaveNotify = pref.getBoolean("leave_notify", true)
val isDoubleZoomDisabled= pref.getBoolean("double_zoom", false)
val imageViewMaxSize = pref.getInt("imageview_max_size", 2)
val isOriginalEnabledWifi = pref.getBoolean("original_switch_wifi", false)
val isOriginalEnabled3g = pref.getBoolean("original_switch_3g", false)
val isWifiEnabled = pref.getBoolean("wifi_switch", false)
val sitesWifi = sites.associateBy({it}, { pref.getQualityOld(it, true) })
val sites3g = sites.associateBy({it}, { pref.getQualityOld(it, false) })
pref.edit().putZoomSpeed(zoomSpeed.toFloat())
.putIsVideoAutoPlay(isVideoPlay)
.putIsAdjustZoom(isAdjustZoom)
.putDownloadDir(downloadDir)
.putDownloadDirType(downloadDirType)
.putIsSkipDialog(isSkipDialog)
.putIsLeaveNotify(isLeaveNotify)
.putIsDoubleZoomDisabled(isDoubleZoomDisabled)
.putImageViewMaxSize(imageViewMaxSize)
.putIsOriginalEnabled(isOriginalEnabledWifi, true)
.putIsOriginalEnabled(isOriginalEnabled3g, false)
.putIsWifiEnabled(isWifiEnabled)
.apply()
val prefEdit = pref.edit()
sitesWifi.forEach { prefEdit.putQuality(it.value, it.key, true) }
sites3g.forEach { prefEdit.putQuality(it.value, it.key, false) }
prefEdit.putIsInitialized47(true)
prefEdit.apply()
}
private fun SharedPreferences.getQualityOld(siteName: String, isWifi: Boolean, defaultValue: String = "large"): String {
return getString("${siteName}_quality_" + if (isWifi) "wifi" else "3g", defaultValue)
}
}
| gpl-2.0 | acdf9b886237c4e2aa7a72149d4c2aed | 45.967742 | 124 | 0.669643 | 4.339791 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/ContinuationHolder.kt | 4 | 6340 | // 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.debugger.coroutine.proxy
import com.intellij.debugger.engine.JavaValue
import com.sun.jdi.ObjectReference
import com.sun.jdi.VMDisconnectedException
import org.jetbrains.kotlin.idea.debugger.coroutine.data.*
import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror.*
import org.jetbrains.kotlin.idea.debugger.coroutine.util.isAbstractCoroutine
import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger
import org.jetbrains.kotlin.idea.debugger.base.util.evaluate.DefaultExecutionContext
class ContinuationHolder private constructor(val context: DefaultExecutionContext) {
private val debugMetadata: DebugMetadata? = DebugMetadata.instance(context)
private val locationCache = LocationCache(context)
private val debugProbesImpl = DebugProbesImpl.instance(context)
private val javaLangObjectToString = JavaLangObjectToString(context)
fun extractCoroutineInfoData(continuation: ObjectReference): CompleteCoroutineInfoData? {
try {
val consumer = mutableListOf<CoroutineStackFrameItem>()
val continuationStack = debugMetadata?.fetchContinuationStack(continuation, context) ?: return null
for (frame in continuationStack.coroutineStack) {
val coroutineStackFrame = createStackFrameItem(frame)
if (coroutineStackFrame != null)
consumer.add(coroutineStackFrame)
}
val lastRestoredFrame = continuationStack.coroutineStack.lastOrNull()
return findCoroutineInformation(lastRestoredFrame?.baseContinuationImpl?.coroutineOwner, consumer)
} catch (e: VMDisconnectedException) {
} catch (e: Exception) {
log.warn("Error while looking for stack frame", e)
}
return null
}
private fun findCoroutineInformation(
coroutineOwner: ObjectReference?,
stackFrameItems: List<CoroutineStackFrameItem>
): CompleteCoroutineInfoData? {
val creationStackTrace = mutableListOf<CreationCoroutineStackFrameItem>()
val realState = if (coroutineOwner?.type()?.isAbstractCoroutine() == true) {
state(coroutineOwner) ?: return null
} else {
val ci = debugProbesImpl?.getCoroutineInfo(coroutineOwner, context)
if (ci != null) {
val providedCreationStackTrace = ci.creationStackTraceProvider.getStackTrace()
if (providedCreationStackTrace != null)
for (index in providedCreationStackTrace.indices) {
val frame = providedCreationStackTrace[index]
val ste = frame.stackTraceElement()
val location = locationCache.createLocation(ste)
creationStackTrace.add(CreationCoroutineStackFrameItem(ste, location, index == 0))
}
CoroutineDescriptor.instance(ci)
} else {
CoroutineDescriptor(CoroutineInfoData.DEFAULT_COROUTINE_NAME, "-1", State.UNKNOWN, null)
}
}
return CompleteCoroutineInfoData(realState, stackFrameItems, creationStackTrace)
}
fun state(value: ObjectReference?): CoroutineDescriptor? {
value ?: return null
val standaloneCoroutine = StandaloneCoroutine.instance(context) ?: return null
val standAloneCoroutineMirror = standaloneCoroutine.mirror(value, context)
if (standAloneCoroutineMirror?.context is MirrorOfCoroutineContext) {
val id = standAloneCoroutineMirror.context.id
val name = standAloneCoroutineMirror.context.name ?: CoroutineInfoData.DEFAULT_COROUTINE_NAME
val toString = javaLangObjectToString.mirror(value, context) ?: return null
// trying to get coroutine information by calling JobSupport.toString(), ${nameString()}{${stateString(state)}}@$hexAddress
val r = """\w+\{(\w+)}@([\w\d]+)""".toRegex()
val matcher = r.toPattern().matcher(toString)
if (matcher.matches()) {
val state = stateOf(matcher.group(1))
val hexAddress = matcher.group(2)
return CoroutineDescriptor(name, id?.toString() ?: hexAddress, state, standAloneCoroutineMirror.context.dispatcher)
}
}
return null
}
private fun createStackFrameItem(
frame: MirrorOfStackFrame
): DefaultCoroutineStackFrameItem? {
val stackTraceElement = frame.baseContinuationImpl.stackTraceElement?.stackTraceElement() ?: return null
val locationClass = context.findClassSafe(stackTraceElement.className) ?: return null
val generatedLocation = locationCache.createLocation(locationClass, stackTraceElement.methodName, stackTraceElement.lineNumber)
val spilledVariables = frame.baseContinuationImpl.spilledValues(context)
return DefaultCoroutineStackFrameItem(generatedLocation, spilledVariables)
}
companion object {
val log by logger
fun instance(context: DefaultExecutionContext) =
ContinuationHolder(context)
private fun stateOf(state: String?): State =
when (state) {
"Active" -> State.RUNNING
"Cancelling" -> State.SUSPENDED_CANCELLING
"Completing" -> State.SUSPENDED_COMPLETING
"Cancelled" -> State.CANCELLED
"Completed" -> State.COMPLETED
"New" -> State.NEW
else -> State.UNKNOWN
}
}
}
fun MirrorOfBaseContinuationImpl.spilledValues(context: DefaultExecutionContext): List<JavaValue> {
return fieldVariables.map {
it.toJavaValue(that, context)
}
}
fun FieldVariable.toJavaValue(continuation: ObjectReference, context: DefaultExecutionContext): JavaValue {
val valueDescriptor = ContinuationVariableValueDescriptorImpl(
context,
continuation,
fieldName,
variableName
)
return JavaValue.create(
null,
valueDescriptor,
context.evaluationContext,
context.debugProcess.xdebugProcess!!.nodeManager,
false
)
}
| apache-2.0 | 1f0319e206a002e2654bf6739f0579ca | 46.669173 | 158 | 0.679022 | 5.45611 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/adapters/LinkDetailsAdapter.kt | 1 | 5754 | package io.github.feelfreelinux.wykopmobilny.ui.adapters
import android.view.ViewGroup
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Link
import io.github.feelfreelinux.wykopmobilny.models.dataclass.LinkComment
import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.BaseLinkCommentViewHolder
import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.BlockedViewHolder
import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.LinkCommentViewHolder
import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.LinkHeaderViewHolder
import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.RecyclableViewHolder
import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.TopLinkCommentViewHolder
import io.github.feelfreelinux.wykopmobilny.ui.fragments.link.LinkHeaderActionListener
import io.github.feelfreelinux.wykopmobilny.ui.fragments.linkcomments.LinkCommentActionListener
import io.github.feelfreelinux.wykopmobilny.ui.fragments.linkcomments.LinkCommentViewListener
import io.github.feelfreelinux.wykopmobilny.ui.modules.NewNavigatorApi
import io.github.feelfreelinux.wykopmobilny.utils.preferences.SettingsPreferencesApi
import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi
import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.WykopLinkHandlerApi
import javax.inject.Inject
class LinkDetailsAdapter @Inject constructor(
val userManagerApi: UserManagerApi,
val navigatorApi: NewNavigatorApi,
val linkHandlerApi: WykopLinkHandlerApi,
val settingsPreferencesApi: SettingsPreferencesApi
) : androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() {
var link: Link? = null
var highlightCommentId = -1
lateinit var linkCommentViewListener: LinkCommentViewListener
lateinit var linkCommentActionListener: LinkCommentActionListener
lateinit var linkHeaderActionListener: LinkHeaderActionListener
private val commentsList: List<LinkComment>?
get() = link?.comments?.filterNot {
it.isParentCollapsed || (it.isBlocked && settingsPreferencesApi.hideBlacklistedViews)
}
override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
try { // Suppresing, need more information to reproduce this crash.
if (holder.itemViewType == LinkHeaderViewHolder.TYPE_HEADER) {
link?.let { (holder as LinkHeaderViewHolder).bindView(link!!) }
} else if (holder is BlockedViewHolder) {
holder.bindView(commentsList!![position - 1])
} else {
val comment = commentsList!![position - 1]
if (holder is TopLinkCommentViewHolder) {
holder.bindView(comment, link!!.author?.nick == comment.author.nick, highlightCommentId)
holder.containerView.tag =
if (comment.childCommentCount > 0 && !comment.isCollapsed) RecyclableViewHolder.SEPARATOR_SMALL else RecyclableViewHolder.SEPARATOR_NORMAL
} else if (holder is LinkCommentViewHolder) {
val parent = commentsList!!.first { it.id == comment.parentId }
val index = commentsList!!.subList(commentsList!!.indexOf(parent), position - 1).size
holder.bindView(comment, link!!.author?.nick == comment.author.nick, highlightCommentId)
holder.itemView.tag =
if (parent.childCommentCount == index) RecyclableViewHolder.SEPARATOR_NORMAL else RecyclableViewHolder.SEPARATOR_SMALL
}
}
} catch (e: Exception) {
}
}
override fun getItemViewType(position: Int): Int {
return if (position == 0) LinkHeaderViewHolder.TYPE_HEADER
else BaseLinkCommentViewHolder.getViewTypeForComment(commentsList!![position - 1])
}
override fun getItemCount(): Int {
commentsList?.let {
return it.size + 1
}
return 1
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
return when (viewType) {
LinkHeaderViewHolder.TYPE_HEADER -> LinkHeaderViewHolder.inflateView(
parent,
userManagerApi,
navigatorApi,
linkHandlerApi,
linkHeaderActionListener
)
TopLinkCommentViewHolder.TYPE_TOP_EMBED, TopLinkCommentViewHolder.TYPE_TOP_NORMAL -> TopLinkCommentViewHolder.inflateView(
parent,
viewType,
userManagerApi,
settingsPreferencesApi,
navigatorApi,
linkHandlerApi,
linkCommentActionListener,
linkCommentViewListener
)
LinkCommentViewHolder.TYPE_EMBED, LinkCommentViewHolder.TYPE_NORMAL -> LinkCommentViewHolder.inflateView(
parent,
viewType,
userManagerApi,
settingsPreferencesApi,
navigatorApi,
linkHandlerApi,
linkCommentActionListener,
linkCommentViewListener
)
else -> BlockedViewHolder.inflateView(parent) { notifyItemChanged(it) }
}
}
fun updateLinkComment(comment: LinkComment) {
val position = link!!.comments.indexOf(comment)
link!!.comments[position] = comment
notifyItemChanged(commentsList!!.indexOf(comment) + 1)
}
fun updateLinkHeader(link: Link) {
this.link = link
notifyItemChanged(0)
}
}
| mit | c9bb17a0edd1153ab6dc5577ec0ceb88 | 48.179487 | 166 | 0.692909 | 5.327778 | false | false | false | false |
JetBrains/kotlin-native | performance/ring/src/main/kotlin/org/jetbrains/ring/ClassListBenchmark.kt | 4 | 3340 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.ring
open class ClassListBenchmark {
private var _data: ArrayList<Value>? = null
val data: ArrayList<Value>
get() = _data!!
init {
val list = ArrayList<Value>(BENCHMARK_SIZE)
for (n in classValues(BENCHMARK_SIZE))
list.add(n)
_data = list
}
//Benchmark
fun copy(): List<Value> {
return data.toList()
}
//Benchmark
fun copyManual(): List<Value> {
val list = ArrayList<Value>(data.size)
for (item in data) {
list.add(item)
}
return list
}
//Benchmark
fun filterAndCount(): Int {
return data.filter { filterLoad(it) }.count()
}
//Benchmark
fun filterAndCountWithLambda(): Int {
return data.filter { it.value % 2 == 0 }.count()
}
//Benchmark
fun filterWithLambda(): List<Value> {
return data.filter { it.value % 2 == 0 }
}
//Benchmark
fun mapWithLambda(): List<String> {
return data.map { it.toString() }
}
//Benchmark
fun countWithLambda(): Int {
return data.count { it.value % 2 == 0 }
}
//Benchmark
fun filterAndMapWithLambda(): List<String> {
return data.filter { it.value % 2 == 0 }.map { it.toString() }
}
//Benchmark
fun filterAndMapWithLambdaAsSequence(): List<String> {
return data.asSequence().filter { it.value % 2 == 0 }.map { it.toString() }.toList()
}
//Benchmark
fun filterAndMap(): List<String> {
return data.filter { filterLoad(it) }.map { mapLoad(it) }
}
//Benchmark
fun filterAndMapManual(): ArrayList<String> {
val list = ArrayList<String>()
for (it in data) {
if (filterLoad(it)) {
val value = mapLoad(it)
list.add(value)
}
}
return list
}
//Benchmark
fun filter(): List<Value> {
return data.filter { filterLoad(it) }
}
//Benchmark
fun filterManual(): List<Value> {
val list = ArrayList<Value>()
for (it in data) {
if (filterLoad(it))
list.add(it)
}
return list
}
//Benchmark
fun countFilteredManual(): Int {
var count = 0
for (it in data) {
if (filterLoad(it))
count++
}
return count
}
//Benchmark
fun countFiltered(): Int {
return data.count { filterLoad(it) }
}
//Benchmark
// fun countFilteredLocal(): Int {
// return data.cnt { filterLoad(it) }
// }
//Benchmark
fun reduce(): Int {
return data.fold(0) { acc, it -> if (filterLoad(it)) acc + 1 else acc }
}
}
| apache-2.0 | 0bbe94de9cfa3b1b430b061f0f4654a6 | 23.558824 | 92 | 0.565868 | 4.06326 | false | false | false | false |
JetBrains/kotlin-native | build-tools/src/main/kotlin/org/jetbrains/kotlin/klib/metadata/KmComparatorUtils.kt | 4 | 2170 | /*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.klib.metadata
import kotlinx.metadata.*
private fun render(element: Any?): String = when (element) {
is KmTypeAlias -> "typealias ${element.name}"
is KmFunction -> "function ${element.name}"
is KmProperty -> "property ${element.name}"
is KmClass -> "class ${element.name}"
is KmType -> "`type ${element.classifier}`"
else -> element.toString()
}
internal fun <T> serialComparator(
vararg comparators: Pair<(T, T) -> MetadataCompareResult, String>?
): (T, T) -> MetadataCompareResult = { o1, o2 ->
comparators.filterNotNull().map { (comparator, message) ->
comparator(o1, o2).let { result ->
if (result is Fail) Fail(message, result) else result
}
}.wrap()
}
internal fun <T> serialComparator(
vararg comparators: (T, T) -> MetadataCompareResult
): (T, T) -> MetadataCompareResult = { o1, o2 ->
comparators
.map { comparator -> comparator(o1, o2) }
.wrap()
}
internal fun Collection<MetadataCompareResult>.wrap(): MetadataCompareResult =
filterIsInstance<Fail>().let { fails ->
when (fails.size) {
0 -> Ok
else -> Fail(fails)
}
}
internal fun <T> compareNullable(
comparator: (T, T) -> MetadataCompareResult
): (T?, T?) -> MetadataCompareResult = { a, b ->
when {
a != null && b != null -> comparator(a, b)
a == null && b == null -> Ok
else -> Fail("${render(a)} ${render(b)}")
}
}
internal fun <T> compareLists(elementComparator: (T, T) -> MetadataCompareResult, sortBy: T.() -> String? = { null }) =
{ list1: List<T>, list2: List<T> -> compareLists(list1.sortedBy(sortBy), list2.sortedBy(sortBy), elementComparator) }
private fun <T> compareLists(l1: List<T>, l2: List<T>, comparator: (T, T) -> MetadataCompareResult) = when {
l1.size != l2.size -> Fail("${l1.size} != ${l2.size}")
else -> l1.zip(l2).map { comparator(it.first, it.second) }.wrap()
} | apache-2.0 | 1b8525e09d3c37cda5b67bc7e59950e7 | 35.183333 | 125 | 0.605069 | 3.622705 | false | false | false | false |
nonylene/PhotoLinkViewer-Core | photolinkviewer-core/src/main/java/net/nonylene/photolinkviewer/core/tool/TwitterUtil.kt | 1 | 2033 | package net.nonylene.photolinkviewer.core.tool
import android.content.Context
import android.net.Uri
import android.preference.PreferenceManager
import twitter4j.Status
fun twitterSmallUrl(url: String): String {
return url + ":small"
}
fun twitterBiggestUrl(url: String): String {
return url + ":orig"
}
fun twitterDisplayUrl(url: String, quality: String): String {
return when (quality) {
"original" -> twitterBiggestUrl(url)
"large" -> url + ":large"
"medium" -> url
"small" -> twitterSmallUrl(url)
else -> url
}
}
private fun getId(url: String): String {
val lastPath = Uri.parse(url).lastPathSegment
val index = lastPath.lastIndexOf('.')
return lastPath.substring(0, if (index > 0) index else lastPath.length)
}
fun createTwitterPLVUrls(status: Status, context: Context): List<PLVUrl> {
return status.mediaEntities.map { mediaEntity ->
val url = mediaEntity.mediaURLHttps
if (mediaEntity.type in arrayOf("animated_gif", "video")) {
val displayUrl = mediaEntity.videoVariants.filter {
("video/mp4") == it.contentType
}.maxBy { it.bitrate }!!.url
val plvUrl = PLVUrl(url, "twitter", getId(displayUrl), null, status.user.screenName)
plvUrl.type = "mp4"
plvUrl.displayUrl = displayUrl
plvUrl.thumbUrl = mediaEntity.mediaURLHttps
plvUrl.isVideo = true
plvUrl
} else {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val quality = sharedPreferences.getQuality("twitter", useWifiPreference(context))
val plvUrl = PLVUrl(url, "twitter", getId(url), quality, status.user.screenName)
plvUrl.type = getFileTypeFromUrl(url)
plvUrl.biggestUrl = twitterBiggestUrl(url)
plvUrl.thumbUrl = twitterSmallUrl(url)
plvUrl.displayUrl = twitterDisplayUrl(url, quality)
plvUrl
}
}
}
| gpl-2.0 | 29ed8fee15da639835a9276dcc566a6c | 34.051724 | 96 | 0.640925 | 4.090543 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/introduceTypeAliasImpl.kt | 1 | 14262 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.introduce.introduceTypeAlias
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.PsiElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.util.containers.LinkedMultiMap
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.descriptors.TypeAliasDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.analysis.analyzeInContext
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.CollectingNameValidator
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.core.compareDescriptors
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.refactoring.introduce.insertDeclaration
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiRange
import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiUnifier
import org.jetbrains.kotlin.idea.util.psi.patternMatching.UnifierParameter
import org.jetbrains.kotlin.idea.util.psi.patternMatching.toRange
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens.*
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
import org.jetbrains.kotlin.types.TypeUtils
sealed class IntroduceTypeAliasAnalysisResult {
class Error(@NlsContexts.DialogMessage val message: String) : IntroduceTypeAliasAnalysisResult()
class Success(val descriptor: IntroduceTypeAliasDescriptor) : IntroduceTypeAliasAnalysisResult()
}
private fun IntroduceTypeAliasData.getTargetScope() = targetSibling.getResolutionScope(bindingContext, resolutionFacade)
fun IntroduceTypeAliasData.analyze(): IntroduceTypeAliasAnalysisResult {
val psiFactory = KtPsiFactory(originalTypeElement)
val contextExpression = originalTypeElement.getStrictParentOfType<KtExpression>()!!
val targetScope = getTargetScope()
val dummyVar = psiFactory.createProperty("val a: Int").apply {
typeReference!!.replace(
originalTypeElement.parent as? KtTypeReference ?: if (originalTypeElement is KtTypeElement) psiFactory.createType(
originalTypeElement
) else psiFactory.createType(originalTypeElement.text)
)
}
val newTypeReference = dummyVar.typeReference!!
val newReferences = newTypeReference.collectDescendantsOfType<KtTypeReference> { it.resolveInfo != null }
val newContext = dummyVar.analyzeInContext(targetScope, contextExpression)
val project = originalTypeElement.project
val unifier = KotlinPsiUnifier.DEFAULT
val groupedReferencesToExtract = LinkedMultiMap<TypeReferenceInfo, TypeReferenceInfo>()
val forcedCandidates = if (extractTypeConstructor) newTypeReference.typeElement!!.typeArgumentsAsTypes else emptyList()
for (newReference in newReferences) {
val resolveInfo = newReference.resolveInfo!!
if (newReference !in forcedCandidates) {
val originalDescriptor = resolveInfo.type.constructor.declarationDescriptor
val newDescriptor = newContext[BindingContext.TYPE, newReference]?.constructor?.declarationDescriptor
if (compareDescriptors(project, originalDescriptor, newDescriptor)) continue
}
val equivalenceRepresentative = groupedReferencesToExtract
.keySet()
.firstOrNull { unifier.unify(it.reference, resolveInfo.reference).matched }
if (equivalenceRepresentative != null) {
groupedReferencesToExtract.putValue(equivalenceRepresentative, resolveInfo)
} else {
groupedReferencesToExtract.putValue(resolveInfo, resolveInfo)
}
val referencesToExtractIterator = groupedReferencesToExtract.values().iterator()
while (referencesToExtractIterator.hasNext()) {
val referenceToExtract = referencesToExtractIterator.next()
if (resolveInfo.reference.isAncestor(referenceToExtract.reference, true)) {
referencesToExtractIterator.remove()
}
}
}
val typeParameterNameValidator = CollectingNameValidator()
val brokenReferences = groupedReferencesToExtract.keySet().filter { groupedReferencesToExtract[it].isNotEmpty() }
val typeParameterNames = KotlinNameSuggester.suggestNamesForTypeParameters(brokenReferences.size, typeParameterNameValidator)
val typeParameters = (typeParameterNames zip brokenReferences).map { TypeParameter(it.first, groupedReferencesToExtract[it.second]) }
if (typeParameters.any { it.typeReferenceInfos.any { info -> info.reference.typeElement == originalTypeElement } }) {
return IntroduceTypeAliasAnalysisResult.Error(KotlinBundle.message("text.type.alias.cannot.refer.to.types.which.aren.t.accessible.in.the.scope.where.it.s.defined"))
}
val descriptor = IntroduceTypeAliasDescriptor(this, "Dummy", null, typeParameters)
val initialName = KotlinNameSuggester.suggestTypeAliasNameByPsi(descriptor.generateTypeAlias(true).getTypeReference()!!.typeElement!!) {
targetScope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null
}
return IntroduceTypeAliasAnalysisResult.Success(descriptor.copy(name = initialName))
}
fun IntroduceTypeAliasData.getApplicableVisibilities(): List<KtModifierKeywordToken> = when (targetSibling.parent) {
is KtClassBody -> listOf(PRIVATE_KEYWORD, PUBLIC_KEYWORD, INTERNAL_KEYWORD, PROTECTED_KEYWORD)
is KtFile -> listOf(PRIVATE_KEYWORD, PUBLIC_KEYWORD, INTERNAL_KEYWORD)
else -> emptyList()
}
fun IntroduceTypeAliasDescriptor.validate(): IntroduceTypeAliasDescriptorWithConflicts {
val conflicts = MultiMap<PsiElement, String>()
val originalType = originalData.originalTypeElement
when {
name.isEmpty() ->
conflicts.putValue(originalType, KotlinBundle.message("text.no.name.provided.for.type.alias"))
!name.isIdentifier() ->
conflicts.putValue(originalType, KotlinBundle.message("text.type.alias.name.must.be.a.valid.identifier.0", name))
originalData.getTargetScope().findClassifier(Name.identifier(name), NoLookupLocation.FROM_IDE) != null ->
conflicts.putValue(originalType, KotlinBundle.message("text.type.already.exists.in.the.target.scope", name))
}
if (typeParameters.distinctBy { it.name }.size != typeParameters.size) {
conflicts.putValue(originalType, KotlinBundle.message("text.type.parameter.names.must.be.distinct"))
}
if (visibility != null && visibility !in originalData.getApplicableVisibilities()) {
conflicts.putValue(originalType, KotlinBundle.message("text.0.is.not.allowed.in.the.target.context", visibility))
}
return IntroduceTypeAliasDescriptorWithConflicts(this, conflicts)
}
fun findDuplicates(typeAlias: KtTypeAlias): Map<KotlinPsiRange, () -> Unit> {
val aliasName = typeAlias.name?.quoteIfNeeded() ?: return emptyMap()
val aliasRange = typeAlias.textRange
val typeAliasDescriptor = typeAlias.unsafeResolveToDescriptor() as TypeAliasDescriptor
val unifierParameters = typeAliasDescriptor.declaredTypeParameters.map { UnifierParameter(it, null) }
val unifier = KotlinPsiUnifier(unifierParameters)
val psiFactory = KtPsiFactory(typeAlias)
fun replaceTypeElement(occurrence: KtTypeElement, typeArgumentsText: String) {
occurrence.replace(psiFactory.createType("$aliasName$typeArgumentsText").typeElement!!)
}
fun replaceOccurrence(occurrence: PsiElement, arguments: List<KtTypeElement>) {
val typeArgumentsText = if (arguments.isNotEmpty()) "<${arguments.joinToString { it.text }}>" else ""
when (occurrence) {
is KtTypeElement -> {
replaceTypeElement(occurrence, typeArgumentsText)
}
is KtSuperTypeCallEntry -> {
occurrence.calleeExpression.typeReference?.typeElement?.let { replaceTypeElement(it, typeArgumentsText) }
}
is KtCallElement -> {
val qualifiedExpression = occurrence.parent as? KtQualifiedExpression
val callExpression = if (qualifiedExpression != null && qualifiedExpression.selectorExpression == occurrence) {
qualifiedExpression.replaced(occurrence)
} else occurrence
val typeArgumentList = callExpression.typeArgumentList
if (arguments.isNotEmpty()) {
val newTypeArgumentList = psiFactory.createTypeArguments(typeArgumentsText)
typeArgumentList?.replace(newTypeArgumentList) ?: callExpression.addAfter(
newTypeArgumentList,
callExpression.calleeExpression
)
} else {
typeArgumentList?.delete()
}
callExpression.calleeExpression?.replace(psiFactory.createExpression(aliasName))
}
is KtExpression -> occurrence.replace(psiFactory.createExpression(aliasName))
}
}
val rangesWithReplacers = ArrayList<Pair<KotlinPsiRange, () -> Unit>>()
val originalTypePsi = typeAliasDescriptor.underlyingType.constructor.declarationDescriptor?.let {
DescriptorToSourceUtilsIde.getAnyDeclaration(typeAlias.project, it)
}
if (originalTypePsi != null) {
for (reference in ReferencesSearch.search(originalTypePsi, LocalSearchScope(typeAlias.parent))) {
val element = reference.element as? KtSimpleNameExpression ?: continue
if ((element.textRange.intersects(aliasRange))) continue
val arguments: List<KtTypeElement>
val occurrence: KtElement
val callElement = element.getParentOfTypeAndBranch<KtCallElement> { calleeExpression }
if (callElement != null) {
occurrence = callElement
arguments = callElement.typeArguments.mapNotNull { it.typeReference?.typeElement }
} else {
val userType = element.getParentOfTypeAndBranch<KtUserType> { referenceExpression }
if (userType != null) {
occurrence = userType
arguments = userType.typeArgumentsAsTypes.mapNotNull { it.typeElement }
} else continue
}
if (arguments.size != typeAliasDescriptor.declaredTypeParameters.size) continue
if (TypeUtils.isNullableType(typeAliasDescriptor.underlyingType)
&& occurrence is KtUserType
&& occurrence.parent !is KtNullableType
) continue
rangesWithReplacers += occurrence.toRange() to { replaceOccurrence(occurrence, arguments) }
}
}
typeAlias
.getTypeReference()
?.typeElement
.toRange()
.match(typeAlias.parent, unifier)
.asSequence()
.filter { !(it.range.getTextRange().intersects(aliasRange)) }
.mapNotNullTo(rangesWithReplacers) { match ->
val occurrence = match.range.elements.singleOrNull() as? KtTypeElement ?: return@mapNotNullTo null
val arguments = unifierParameters.mapNotNull { (match.substitution[it] as? KtTypeReference)?.typeElement }
if (arguments.size != unifierParameters.size) return@mapNotNullTo null
match.range to { replaceOccurrence(occurrence, arguments) }
}
return rangesWithReplacers.toMap()
}
private var KtTypeReference.typeParameterInfo: TypeParameter? by CopyablePsiUserDataProperty(Key.create("TYPE_PARAMETER_INFO"))
fun IntroduceTypeAliasDescriptor.generateTypeAlias(previewOnly: Boolean = false): KtTypeAlias {
val originalElement = originalData.originalTypeElement
val psiFactory = KtPsiFactory(originalElement)
for (typeParameter in typeParameters)
for (it in typeParameter.typeReferenceInfos) {
it.reference.typeParameterInfo = typeParameter
}
val typeParameterNames = typeParameters.map { it.name }
val typeAlias = if (originalElement is KtTypeElement) {
psiFactory.createTypeAlias(name, typeParameterNames, originalElement)
} else {
psiFactory.createTypeAlias(name, typeParameterNames, originalElement.text)
}
if (visibility != null && visibility != DEFAULT_VISIBILITY_KEYWORD) {
typeAlias.addModifier(visibility)
}
for (typeParameter in typeParameters)
for (it in typeParameter.typeReferenceInfos) {
it.reference.typeParameterInfo = null
}
fun replaceUsage() {
val aliasInstanceText = if (typeParameters.isNotEmpty()) {
"$name<${typeParameters.joinToString { it.typeReferenceInfos.first().reference.text }}>"
} else {
name
}
when (originalElement) {
is KtTypeElement -> originalElement.replace(psiFactory.createType(aliasInstanceText).typeElement!!)
is KtExpression -> originalElement.replace(psiFactory.createExpression(aliasInstanceText))
}
}
fun introduceTypeParameters() {
typeAlias.getTypeReference()!!.forEachDescendantOfType<KtTypeReference> {
val typeParameter = it.typeParameterInfo ?: return@forEachDescendantOfType
val typeParameterReference = psiFactory.createType(typeParameter.name)
it.replace(typeParameterReference)
}
}
return if (previewOnly) {
introduceTypeParameters()
typeAlias
} else {
replaceUsage()
introduceTypeParameters()
insertDeclaration(typeAlias, originalData.targetSibling)
}
} | apache-2.0 | f8a94cd3dad6fbca8bf586b1056ebb68 | 48.013746 | 172 | 0.724372 | 5.590749 | false | false | false | false |
80998062/Fank | presentation/src/main/java/com/sinyuk/fanfou/ui/search/HistoryView.kt | 1 | 6278 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.ui.search
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.Observer
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import cn.dreamtobe.kpswitch.util.KeyboardUtil
import com.sinyuk.fanfou.R
import com.sinyuk.fanfou.base.AbstractActivity
import com.sinyuk.fanfou.base.AbstractFragment
import com.sinyuk.fanfou.di.Injectable
import com.sinyuk.fanfou.domain.DO.Keyword
import com.sinyuk.fanfou.domain.SUGGESTION_HISTORY_LIMIT
import com.sinyuk.fanfou.ui.MarginDecoration
import com.sinyuk.fanfou.ui.search.event.InputEvent
import com.sinyuk.fanfou.util.Objects
import com.sinyuk.fanfou.util.obtainViewModelFromActivity
import com.sinyuk.fanfou.viewmodel.FanfouViewModelFactory
import com.sinyuk.fanfou.viewmodel.SearchViewModel
import com.sinyuk.myutils.system.ToastUtils
import kotlinx.android.synthetic.main.histyory_view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject
/**
* Created by sinyuk on 2018/1/4.
*
*/
class HistoryView : AbstractFragment(), Injectable {
companion object {
fun newInstance(collapsed: Boolean, query: String? = null) = HistoryView().apply {
arguments = Bundle().apply {
putBoolean("collapsed", collapsed)
putString("query", query)
}
}
}
@Inject lateinit var factory: FanfouViewModelFactory
@Inject lateinit var toast: ToastUtils
private val searchViewModel by lazy { obtainViewModelFromActivity(factory, SearchViewModel::class.java) }
private var query: String? = null
private val adapter = SuggestionAdapter()
private val collapsed by lazy { arguments!!.getBoolean("collapsed") }
override fun layoutId() = R.layout.histyory_view
private lateinit var listing: LiveData<MutableList<Keyword>?>
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
val limit = if (collapsed) SUGGESTION_HISTORY_LIMIT else null
listing = searchViewModel.listing(query = arguments!!.getString("query"), limit = limit)
.apply {
observe(this@HistoryView, Observer {
adapter.setNewData(it)
if (collapsed) showMore(it?.size ?: 0)
})
}
}
private fun showMore(size: Int) {
if (size < SUGGESTION_HISTORY_LIMIT) {
if (adapter.footerLayoutCount != 0) {
adapter.removeFooterView(footer!!)
}
} else {
if (adapter.footerLayoutCount == 0) {
adapter.addFooterView(footer)
}
}
}
private val footer by lazy {
LayoutInflater.from(context).inflate(R.layout.suggestion_list_footer, recyclerView, false).apply {
setOnClickListener {
(activity as AbstractActivity).start(HistoryManagerView.newInstance(query = query))
KeyboardUtil.hideKeyboard(recyclerView)
}
}
}
private fun setupRecyclerView() {
if (collapsed) {
recyclerView.layoutManager = object : LinearLayoutManager(context) {
override fun canScrollVertically() = false
}.apply { isAutoMeasureEnabled = true }
} else {
recyclerView.layoutManager = LinearLayoutManager(context).apply { isAutoMeasureEnabled = true }
}
recyclerView.setHasFixedSize(true)
recyclerView.addItemDecoration(MarginDecoration(R.dimen.divider_size, false, context!!))
if (collapsed) {
LayoutInflater.from(context).inflate(R.layout.suggestion_list_header, recyclerView, false).apply {
adapter.addHeaderView(this)
}
} else {
LayoutInflater.from(context).inflate(R.layout.suggestion_list_footer_swipe, recyclerView, false).apply {
adapter.addFooterView(this)
}
}
adapter.setHeaderFooterEmpty(false, false)
LayoutInflater.from(context).inflate(R.layout.suggestion_list_empty, recyclerView, false).apply {
adapter.emptyView = this
}
adapter.setOnItemChildClickListener { _, view, position ->
when (view.id) {
R.id.deleteButton -> {
adapter.closeItem(position)
adapter.getItem(position)?.let { searchViewModel.delete(it.query) }
}
}
}
recyclerView.adapter = adapter
}
override fun onPause() {
super.onPause()
EventBus.getDefault().unregister(this)
}
override fun onResume() {
super.onResume()
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this)
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onQueryChanged(event: InputEvent) {
if (!collapsed) return
if (!Objects.equals(event.text, query)) {
listing.removeObservers(this@HistoryView)
listing = searchViewModel.listing(query = event.text, limit = SUGGESTION_HISTORY_LIMIT)
.apply {
observe(this@HistoryView, Observer {
adapter.setNewData(it)
showMore(it?.size ?: 0)
})
}
}
}
}
| mit | 62592162e28a9382b0f7c61f8730ef00 | 34.269663 | 116 | 0.640491 | 4.660728 | false | false | false | false |
nicolas-raoul/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/review/ReviewActivityTest.kt | 1 | 3200 | package fr.free.nrw.commons.review
import android.content.Context
import android.view.Menu
import android.view.MenuItem
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.soloader.SoLoader
import fr.free.nrw.commons.TestAppAdapter
import fr.free.nrw.commons.TestCommonsApplication
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.MockitoAnnotations
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.fakes.RoboMenu
import org.robolectric.fakes.RoboMenuItem
import org.wikipedia.AppAdapter
import java.lang.reflect.Method
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [21], application = TestCommonsApplication::class)
class ReviewActivityTest {
private lateinit var activity: ReviewActivity
private lateinit var menuItem: MenuItem
private lateinit var menu: Menu
private lateinit var context: Context
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
context = RuntimeEnvironment.application.applicationContext
AppAdapter.set(TestAppAdapter())
SoLoader.setInTestMode()
Fresco.initialize(context)
activity = Robolectric.buildActivity(ReviewActivity::class.java).create().get()
menuItem = RoboMenuItem(null)
menu = RoboMenu(context)
}
@Test
@Throws(Exception::class)
fun checkActivityNotNull() {
Assert.assertNotNull(activity)
}
@Test
@Throws(Exception::class)
fun testOnSupportNavigateUp() {
activity.onSupportNavigateUp()
}
@Test
@Throws(Exception::class)
fun testSwipeToNext() {
activity.swipeToNext()
}
@Test
@Throws(Exception::class)
fun testOnDestroy() {
activity.onDestroy()
}
@Test
@Throws(Exception::class)
fun testShowSkipImageInfo() {
activity.showSkipImageInfo()
}
@Test
@Throws(Exception::class)
fun testShowReviewImageInfo() {
activity.showReviewImageInfo()
}
@Test
@Throws(Exception::class)
fun testOnCreateOptionsMenu() {
activity.onCreateOptionsMenu(menu)
}
@Test
@Throws(Exception::class)
fun testOnOptionsItemSelected() {
activity.onOptionsItemSelected(menuItem)
}
@Test
@Throws(Exception::class)
fun testSetUpMediaDetailFragment() {
var setUpMediaDetailFragment: Method =
ReviewActivity::class.java.getDeclaredMethod("setUpMediaDetailFragment")
setUpMediaDetailFragment.isAccessible = true
setUpMediaDetailFragment.invoke(activity)
}
@Test
@Throws(Exception::class)
fun testSetUpMediaDetailOnOrientation() {
var setUpMediaDetailFragment: Method =
ReviewActivity::class.java.getDeclaredMethod("setUpMediaDetailOnOrientation")
setUpMediaDetailFragment.isAccessible = true
setUpMediaDetailFragment.invoke(activity)
}
@Test
@Throws(Exception::class)
fun testOnBackPressed() {
activity.onBackPressed()
}
} | apache-2.0 | 6e50dd192e6ea1664949b2ad5580a2cb | 23.813953 | 89 | 0.715 | 4.733728 | false | true | false | false |
ThiagoGarciaAlves/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUClassInitializer.kt | 1 | 1466 | /*
* 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.java
import com.intellij.psi.PsiClassInitializer
import org.jetbrains.uast.*
import org.jetbrains.uast.java.internal.JavaUElementWithComments
class JavaUClassInitializer(
psi: PsiClassInitializer,
uastParent: UElement?
) : JavaAbstractUElement(uastParent), UClassInitializer, JavaUElementWithComments, PsiClassInitializer by psi {
override val psi
get() = javaPsi
override val javaPsi = unwrap<UClassInitializer, PsiClassInitializer>(psi)
override val uastAnchor: UElement?
get() = null
override val uastBody by lz {
getLanguagePlugin().convertElement(psi.body, this, null) as? UExpression ?: UastEmptyExpression(this)
}
override val annotations by lz { psi.annotations.map { JavaUAnnotation(it, this) } }
override fun equals(other: Any?) = this === other
override fun hashCode() = psi.hashCode()
} | apache-2.0 | 4b561a969e745aead561eade2ab65d84 | 33.116279 | 111 | 0.755798 | 4.455927 | false | false | false | false |
WYKCode/WYK-Android | app/src/main/java/college/wyk/app/model/sns/SnsPostManager.kt | 1 | 5045 | package college.wyk.app.model.sns
import android.util.Log
import college.wyk.app.model.sns.facebook.Facebook
import college.wyk.app.model.sns.facebook.PostType
import college.wyk.app.model.sns.facebook.WykFacebookPages
import college.wyk.app.model.sns.instagram.WykInstagramUsers
import college.wyk.app.model.sns.youtube.WykYouTubeChannels
import college.wyk.app.model.sns.youtube.YouTube
import college.wyk.app.ui.feed.sns.MILLIS_IN_A_MONTH
import rx.Observable
import java.util.*
class SnsPostManager {
// Pull a month's data from specified since
fun pullStack(id: String, sinceMillis: Long, period: Long = MILLIS_IN_A_MONTH * 6): Observable<SnsStack> {
val facebookPage = when (id) {
"CampusTV" -> WykFacebookPages.campusTV
"SA" -> WykFacebookPages.studentsAssociation
"MA" -> WykFacebookPages.musicAssociation
else -> null
}
val instagramAccount = when (id) {
"SA" -> WykInstagramUsers.wykchivalry
else -> null
}
val youtubeChannel = when (id) {
"CampusTV" -> WykYouTubeChannels.campusTV
else -> null
}
return Observable.create {
subscriber ->
val newSinceMillis = sinceMillis
val beforeMillis = sinceMillis + period
val allPosts = ArrayList<SnsPost>()
var lastResponse = false
var useUrl = false
var nextUrl = ""
while (facebookPage != null && !lastResponse) {
val callResponse = if (!useUrl) facebookPage.api.getPosts(count = 100, since = newSinceMillis / 1000L, until = beforeMillis / 1000L)
else Facebook.getPagePostsByUrl(nextUrl)
val response = callResponse.execute()
if (response.isSuccessful) {
val root = response.body()
if (root.paging == null) {
lastResponse = true
} else {
useUrl = true // we only construct the first request
nextUrl = root.paging.next
}
if (id == "CampusTV") {
root.data.filter { it.type != PostType.video }.forEach { allPosts.add(it) }
} else {
allPosts.addAll(root.data)
}
} else {
subscriber.onError(Throwable(response.message()))
}
}
lastResponse = false
while (instagramAccount != null && !lastResponse) {
val callResponse = instagramAccount.api.getPosts(100) // FIXME: Oops
val response = callResponse.execute()
if (response.isSuccessful) {
val root = response.body()
if (root.pagination.nextUrl == null) lastResponse = true
root.data.filter { it.computeCreationTime() >= sinceMillis && it.computeCreationTime() < beforeMillis }.forEach { allPosts.add(it) }
} else {
subscriber.onError(Throwable(response.message()))
}
}
lastResponse = false
var pageToken: String? = null
while (youtubeChannel != null && !lastResponse) {
val callResponse = youtubeChannel.api.getVideos(pageToken, newSinceMillis, beforeMillis)
val response = callResponse.execute()
if (response.isSuccessful) {
val root = response.body()
if (root.nextPageToken == null) lastResponse = true
else pageToken = root.nextPageToken
for (item in root.items) {
if (item.id.videoId == null) continue
// fetch statistics
val statsCallResponse = YouTube.api.getStatistics(YouTube.key, item.id.videoId)
val statsResponse = statsCallResponse.execute()
if (statsResponse.isSuccessful) {
statsResponse.body().items.getOrNull(0)?.let {
item.statistics = it.statistics
}
} else {
Log.e("WYK", statsResponse.errorBody().string())
continue
}
}
allPosts.addAll(root.items)
} else {
subscriber.onError(Throwable(response.errorBody().string()))
}
}
allPosts.sortByDescending { it.computeCreationTime() }
subscriber.onNext(
SnsStack(
allPosts,
newSinceMillis,
false // Move logic here
)
)
subscriber.onCompleted()
}
}
} | mit | d5885d0813bbb2f0ad477190b5c38bac | 33.561644 | 152 | 0.514172 | 5.0249 | false | false | false | false |
getsentry/raven-java | sentry/src/test/java/io/sentry/NoOpHubTest.kt | 1 | 2146 | package io.sentry
import com.nhaarman.mockitokotlin2.mock
import io.sentry.protocol.SentryId
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertSame
class NoOpHubTest {
private var sut: NoOpHub = NoOpHub.getInstance()
@Test
fun `getLastEventId returns empty SentryId`() =
assertEquals(SentryId.EMPTY_ID, sut.lastEventId)
@Test
fun `addBreadcrumb is doesn't throw on null breadcrumb`() =
sut.addBreadcrumb("breadcrumb")
@Test
fun `hub is always disabled`() = assertFalse(sut.isEnabled)
@Test
fun `hub is returns empty SentryId`() =
assertEquals(SentryId.EMPTY_ID, sut.captureEvent(SentryEvent()))
@Test
fun `captureException is returns empty SentryId`() =
assertEquals(SentryId.EMPTY_ID, sut.captureException(RuntimeException()))
@Test
fun `captureMessage is returns empty SentryId`() =
assertEquals(SentryId.EMPTY_ID, sut.captureMessage("message"))
@Test
fun `close does not affect captureEvent`() {
sut.close()
assertEquals(SentryId.EMPTY_ID, sut.captureEvent(SentryEvent()))
}
@Test
fun `close does not affect captureException`() {
sut.close()
assertEquals(SentryId.EMPTY_ID, sut.captureException(RuntimeException()))
}
@Test
fun `close does not affect captureMessage`() {
sut.close()
assertEquals(SentryId.EMPTY_ID, sut.captureMessage("message"))
}
@Test
fun `pushScope is no op`() = sut.pushScope()
@Test
fun `popScope is no op`() = sut.popScope()
@Test
fun `flush doesn't throw on null param`() = sut.flush(30000)
@Test
fun `clone returns the same instance`() = assertSame(NoOpHub.getInstance(), sut.clone())
@Test
fun `traceHeaders is not null`() {
assertNotNull(sut.traceHeaders())
}
@Test
fun `getSpan returns null`() {
assertNull(sut.span)
}
@Test
fun `setSpanContext doesnt throw`() = sut.setSpanContext(RuntimeException(), mock(), "")
}
| bsd-3-clause | 4db64b6b106b50e3c5979bd7da3f207a | 25.825 | 92 | 0.67055 | 4.241107 | false | true | false | false |
aosp-mirror/platform_frameworks_support | jetifier/jetifier/processor/src/main/kotlin/com/android/tools/build/jetifier/processor/transform/bytecode/CoreRemapperImpl.kt | 1 | 3966 | /*
* Copyright 2017 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.android.tools.build.jetifier.processor.transform.bytecode
import com.android.tools.build.jetifier.core.type.JavaType
import com.android.tools.build.jetifier.core.type.TypesMap
import com.android.tools.build.jetifier.core.utils.Log
import com.android.tools.build.jetifier.processor.transform.TransformationContext
import com.android.tools.build.jetifier.processor.transform.bytecode.asm.CustomRemapper
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.commons.ClassRemapper
import java.nio.file.Path
/**
* Applies mappings defined in [TypesMap] during the remapping process.
*/
class CoreRemapperImpl(
private val context: TransformationContext,
visitor: ClassVisitor
) : CoreRemapper {
companion object {
const val TAG = "CoreRemapperImpl"
}
private val typesMap = context.config.typesMap
var changesDone = false
private set
val classRemapper = ClassRemapper(visitor, CustomRemapper(this))
override fun rewriteType(type: JavaType): JavaType {
val result = context.typeRewriter.rewriteType(type)
if (result != null) {
changesDone = changesDone || result != type
return result
}
context.reportNoMappingFoundFailure(TAG, type)
return type
}
override fun rewriteString(value: String): String {
val type = JavaType.fromDotVersion(value)
if (!context.config.isEligibleForRewrite(type)) {
return value
}
val result = context.config.typesMap.mapType(type)
if (result != null) {
changesDone = changesDone || result != type
Log.i(TAG, "Map string: '%s' -> '%s'", type, result)
return result.toDotNotation()
}
// We might be working with an internal type or field reference, e.g.
// AccessibilityNodeInfoCompat.PANE_TITLE_KEY. So we try to remove last segment to help it.
if (value.contains(".")) {
val subTypeResult = context.config.typesMap.mapType(type.getParentType())
if (subTypeResult != null) {
val result = subTypeResult.toDotNotation() + '.' + value.substringAfterLast('.')
Log.i(TAG, "Map string: '%s' -> '%s' via type fallback", value, result)
return result
}
}
// Try rewrite rules
if (context.useFallbackIfTypeIsMissing) {
val result = context.config.rulesMap.rewriteType(type)
if (result != null) {
Log.i(TAG, "Map string: '%s' -> '%s' via fallback", value, result)
return result.toDotNotation()
}
}
// We do not treat string content mismatches as errors
Log.i(TAG, "Found string '%s' but failed to rewrite", value)
return value
}
fun rewritePath(path: Path): Path {
val owner = path.toFile().path.replace('\\', '/').removeSuffix(".class")
val type = JavaType(owner)
val result = context.typeRewriter.rewriteType(type)
if (result == null) {
context.reportNoMappingFoundFailure("PathRewrite", type)
return path
}
if (result != type) {
changesDone = true
return path.fileSystem.getPath(result.fullName + ".class")
}
return path
}
}
| apache-2.0 | f536327ed3018b7e98340dcac08b326f | 34.097345 | 99 | 0.646747 | 4.372657 | false | false | false | false |
etissieres/MoonPi | src/main/kotlin/moonpi/gui/pictures.kt | 1 | 4705 | package moonpi.gui
import moonpi.*
import net.miginfocom.swing.MigLayout
import java.awt.Color
import java.awt.Dimension
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.image.BufferedImage
import java.nio.file.Path
import java.util.concurrent.ExecutorService
import javax.imageio.ImageIO
import javax.swing.*
class PictureGui(
parent: JFrame,
private val pictureService: PictureService,
eventBus: EventBus,
worker: ExecutorService
) {
val commandPanel = CommandPanel()
val picturePanel = PicturePanel()
val historyNavigationPanel = HistoryNavigationPanel()
init {
assignActivePicture()
commandPanel.processButton.addActionListener {
commandPanel.processButton.isEnabled = false
worker.submit { pictureService.takePicture(commandPanel.getOptions()) }
}
eventBus.onGui(PictureProcessingSucceded::class) {
commandPanel.processButton.isEnabled = true
}
eventBus.onGui(PictureProcessingFailed::class) {
commandPanel.processButton.isEnabled = true
GuiUtils.showErrorDialog(
parent,
"Failed to process picture with options [${it.options}]\nCause: ${it.cause}"
)
}
historyNavigationPanel.previousButton.addActionListener { pictureService.selectPreviousPicture() }
historyNavigationPanel.nextButton.addActionListener { pictureService.selectNextPicture() }
historyNavigationPanel.removeButton.addActionListener { pictureService.removeActivePicture() }
eventBus.onGui(PictureSelected::class) { assignActivePicture() }
}
private fun assignActivePicture() {
pictureService.activePicture?.let {
picturePanel.setPicture(it.filePath)
historyNavigationPanel.populateWithPicture(
it,
pictureService.history.getPictures().indexOf(it),
pictureService.history.getPictures().size
)
}
}
}
class CommandPanel : JPanel(MigLayout("fill", "[][grow][]")) {
private val optionsInput = JTextField()
internal val processButton = JButton(GuiUtils.loadIcon("run"))
init {
add(JLabel("Command"))
add(optionsInput, "grow")
add(processButton)
}
fun getOptions(): String {
return optionsInput.text
}
}
class PicturePanel : JPanel() {
private var picture: BufferedImage? = null
init {
preferredSize = Dimension(640, 480)
}
fun setPicture(filepath: Path) {
picture = ImageIO.read(filepath.toFile())
repaint()
}
override fun paintComponent(g: Graphics?) {
val g2 = g as Graphics2D
picture?.let {
g2.color = Color.BLACK
g2.fillRect(0, 0, width, height)
val heightRatio = it.height.toDouble() / height.toDouble()
val widthRatio = it.width.toDouble() / width.toDouble()
val ratio = arrayOf(heightRatio, widthRatio).max()!!
val drawW = it.width / ratio
val drawH = it.height / ratio
val drawX = (width - drawW) / 2
val drawY = (height - drawH) / 2
g2.drawImage(it, drawX.toInt(), drawY.toInt(), drawW.toInt(), drawH.toInt(), this)
}
}
}
class HistoryNavigationPanel : JPanel(MigLayout("fillx", "[min][center,grow][min]")) {
private val optionsLabel = JLabel()
private val dateLabel = JLabel()
private val counterLabel = JLabel("", JLabel.CENTER)
internal val previousButton = JButton("<")
internal val nextButton = JButton(">")
internal val removeButton = JButton("Remove")
init {
previousButton.isEnabled = false
nextButton.isEnabled = false
removeButton.isEnabled = false
val navigationPanel = JPanel()
navigationPanel.add(previousButton)
navigationPanel.add(counterLabel)
navigationPanel.add(nextButton)
add(optionsLabel, "span")
add(dateLabel)
add(navigationPanel)
add(removeButton, "wrap")
}
fun populateWithPicture(picture: Picture, picturePosition: Int, picturesCount: Int) {
removeButton.isEnabled = true
if (picturesCount > 1) {
previousButton.isEnabled = true
nextButton.isEnabled = true
} else {
nextButton.isEnabled = false
removeButton.isEnabled = false
}
optionsLabel.text = "Options: ${picture.options}"
dateLabel.text = picture.date.format(localDateTimeFormatter)
counterLabel.text = "${picturePosition + 1}/$picturesCount"
}
}
| mit | ffa01a54139ec36b4c9028cebed515ee | 29.751634 | 106 | 0.637832 | 4.630906 | false | false | false | false |
koma-im/koma | src/main/kotlin/koma/koma_app/state.kt | 1 | 3029 | package koma.koma_app
import io.requery.Persistable
import io.requery.sql.KotlinEntityDataStore
import koma.gui.view.window.chatroom.messaging.reading.display.GuestAccessUpdateView
import koma.gui.view.window.chatroom.messaging.reading.display.HistoryVisibilityEventView
import koma.gui.view.window.chatroom.messaging.reading.display.room_event.m_message.MRoomMessageViewNode
import koma.gui.view.window.chatroom.messaging.reading.display.room_event.m_message.content.MEmoteViewNode
import koma.gui.view.window.chatroom.messaging.reading.display.room_event.m_message.content.MImageViewNode
import koma.gui.view.window.chatroom.messaging.reading.display.room_event.m_message.content.MNoticeViewNode
import koma.gui.view.window.chatroom.messaging.reading.display.room_event.m_message.content.MTextViewNode
import koma.gui.view.window.chatroom.messaging.reading.display.room_event.member.MRoomMemberViewNode
import koma.matrix.MatrixApi
import koma.storage.persistence.settings.AppSettings
import koma.storage.users.UserStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import link.continuum.desktop.database.*
import link.continuum.desktop.gui.list.user.UserDataStore
import link.continuum.desktop.gui.message.FallbackCell
import link.continuum.desktop.gui.util.UiPool
import mu.KotlinLogging
private val logger = KotlinLogging.logger {}
object appState {
lateinit var store: AppStore
val job = SupervisorJob()
val coroutineScope = CoroutineScope(Dispatchers.Main + job)
var apiClient: MatrixApi? = null
init {
}
}
typealias AppStore = AppData
/**
* data
*/
class AppData(
db: KotlinEntityDataStore<Persistable>,
val keyValueStore: KeyValueStore,
val settings: AppSettings
) {
val database = KDataStore(db)
@Deprecated("")
val userStore = UserStore()
/**
* users on the network
*/
val userData = UserDataStore(database)
/**
* any known rooms on the network
*/
val roomStore = RoomDataStorage(database, this, userData)
val roomMemberships = RoomMemberships(database)
/**
* map of room id to message manager
*/
val messages = RoomMessages(database)
// reuse components in ListView of events
val messageCells = UiPool{ MRoomMessageViewNode(this) }
val membershipCells = UiPool{ MRoomMemberViewNode(this) }
val guestAccessCells = UiPool{ GuestAccessUpdateView(this) }
val historyVisibilityCells = UiPool{ HistoryVisibilityEventView(this)}
val fallbackCells = UiPool{ FallbackCell() }
val uiPools = ComponentPools(this)
}
/**
* some components need to access data to get avatar urls, etc.
*/
class ComponentPools(private val data: AppData){
// UI for content of messages
val msgEmote = UiPool { MEmoteViewNode(data.userData) }
val msgNotice = UiPool { MNoticeViewNode(data.userData) }
val msgText = UiPool { MTextViewNode(data.userData) }
val msgImage = UiPool { MImageViewNode() }
}
| gpl-3.0 | 99d45a1db6654cdc3d29658de916adcd | 36.395062 | 107 | 0.76725 | 4.006614 | false | false | false | false |
aosp-mirror/platform_frameworks_support | core/ktx/src/androidTest/java/androidx/core/util/LruCacheTest.kt | 1 | 1521 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.util
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class LruCacheTest {
private data class TestData(val x: String = "bla")
@Test fun size() {
val cache = lruCache<String, TestData>(200, { k, (x) -> k.length * x.length })
cache.put("long", TestData())
assertEquals(cache.size(), 12)
}
@Test fun create() {
val cache = lruCache<String, TestData>(200, create = { key -> TestData("$key foo") })
assertEquals(cache.get("kung"), TestData("kung foo"))
}
@Test fun onEntryRemoved() {
var wasCalled = false
val cache = lruCache<String, TestData>(200, onEntryRemoved = { _, _, _, _ ->
wasCalled = true
})
val initial = TestData()
cache.put("a", initial)
cache.remove("a")
assertTrue(wasCalled)
}
}
| apache-2.0 | c6ef14af3dd4c760e7b8d493c63a3cc2 | 30.6875 | 93 | 0.649573 | 4.034483 | false | true | false | false |
cmcpasserby/MayaCharm | src/main/kotlin/utils/Event.kt | 1 | 796 | package utils
interface Event<out TA> {
operator fun plusAssign(m: (TA) -> Unit)
operator fun minusAssign(m: (TA) -> Unit)
}
class Delegate<TA> : Event<TA> {
private var invocationList: MutableList<(TA) -> Unit>? = null
override fun plusAssign(m: (TA) -> Unit) {
val list = invocationList ?: mutableListOf<(TA) -> Unit>().apply { invocationList = this }
list.add(m)
}
override fun minusAssign(m: (TA) -> Unit) {
val list = invocationList
if (list != null) {
list.remove(m)
if (list.isEmpty()) {
invocationList = null
}
}
}
operator fun invoke(source: TA) {
val list = invocationList ?: return
for (m in list) {
m(source)
}
}
}
| mit | 3136fa289a7fc56993378dc0a1a4daa8 | 23.875 | 98 | 0.53392 | 3.921182 | false | false | false | false |
solokot/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/pro/helpers/MediaFetcher.kt | 1 | 32418 | package com.simplemobiletools.gallery.pro.helpers
import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.BaseColumns
import android.provider.MediaStore
import android.provider.MediaStore.Files
import android.provider.MediaStore.Images
import android.text.format.DateFormat
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.*
import com.simplemobiletools.gallery.pro.models.Medium
import com.simplemobiletools.gallery.pro.models.ThumbnailItem
import com.simplemobiletools.gallery.pro.models.ThumbnailSection
import java.io.File
import java.util.*
class MediaFetcher(val context: Context) {
var shouldStop = false
fun getFilesFrom(
curPath: String, isPickImage: Boolean, isPickVideo: Boolean, getProperDateTaken: Boolean, getProperLastModified: Boolean,
getProperFileSize: Boolean, favoritePaths: ArrayList<String>, getVideoDurations: Boolean,
lastModifieds: HashMap<String, Long>, dateTakens: HashMap<String, Long>
): ArrayList<Medium> {
val filterMedia = context.config.filterMedia
if (filterMedia == 0) {
return ArrayList()
}
val curMedia = ArrayList<Medium>()
if (context.isPathOnOTG(curPath)) {
if (context.hasOTGConnected()) {
val newMedia = getMediaOnOTG(curPath, isPickImage, isPickVideo, filterMedia, favoritePaths, getVideoDurations)
curMedia.addAll(newMedia)
}
} else {
val newMedia = getMediaInFolder(
curPath, isPickImage, isPickVideo, filterMedia, getProperDateTaken, getProperLastModified, getProperFileSize,
favoritePaths, getVideoDurations, lastModifieds.clone() as HashMap<String, Long>, dateTakens.clone() as HashMap<String, Long>
)
curMedia.addAll(newMedia)
}
sortMedia(curMedia, context.config.getFolderSorting(curPath))
return curMedia
}
fun getFoldersToScan(): ArrayList<String> {
return try {
val OTGPath = context.config.OTGPath
val folders = getLatestFileFolders()
folders.addAll(arrayListOf(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString(),
"${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)}/Camera",
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()
).filter { context.getDoesFilePathExist(it, OTGPath) })
val filterMedia = context.config.filterMedia
val uri = Files.getContentUri("external")
val projection = arrayOf(Images.Media.DATA)
val selection = getSelectionQuery(filterMedia)
val selectionArgs = getSelectionArgsQuery(filterMedia).toTypedArray()
val cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null)
folders.addAll(parseCursor(cursor!!))
val config = context.config
val shouldShowHidden = config.shouldShowHidden
val excludedPaths = config.excludedFolders
val includedPaths = config.includedFolders
val folderNoMediaStatuses = HashMap<String, Boolean>()
val distinctPathsMap = HashMap<String, String>()
val distinctPaths = folders.distinctBy {
when {
distinctPathsMap.containsKey(it) -> distinctPathsMap[it]
else -> {
val distinct = it.getDistinctPath()
distinctPathsMap[it.getParentPath()] = distinct.getParentPath()
distinct
}
}
}
val noMediaFolders = context.getNoMediaFoldersSync()
noMediaFolders.forEach { folder ->
folderNoMediaStatuses["$folder/$NOMEDIA"] = true
}
distinctPaths.filter {
it.shouldFolderBeVisible(excludedPaths, includedPaths, shouldShowHidden, folderNoMediaStatuses) { path, hasNoMedia ->
folderNoMediaStatuses[path] = hasNoMedia
}
}.toMutableList() as ArrayList<String>
} catch (e: Exception) {
ArrayList()
}
}
@SuppressLint("NewApi")
private fun getLatestFileFolders(): LinkedHashSet<String> {
val uri = Files.getContentUri("external")
val projection = arrayOf(Images.ImageColumns.DATA)
val parents = LinkedHashSet<String>()
var cursor: Cursor? = null
try {
if (isRPlus()) {
val bundle = Bundle().apply {
putInt(ContentResolver.QUERY_ARG_LIMIT, 10)
putStringArray(ContentResolver.QUERY_ARG_SORT_COLUMNS, arrayOf(BaseColumns._ID))
putInt(ContentResolver.QUERY_ARG_SORT_DIRECTION, ContentResolver.QUERY_SORT_DIRECTION_DESCENDING)
}
cursor = context.contentResolver.query(uri, projection, bundle, null)
if (cursor?.moveToFirst() == true) {
do {
val path = cursor.getStringValue(Images.ImageColumns.DATA) ?: continue
parents.add(path.getParentPath())
} while (cursor.moveToNext())
}
} else {
val sorting = "${BaseColumns._ID} DESC LIMIT 10"
cursor = context.contentResolver.query(uri, projection, null, null, sorting)
if (cursor?.moveToFirst() == true) {
do {
val path = cursor.getStringValue(Images.ImageColumns.DATA) ?: continue
parents.add(path.getParentPath())
} while (cursor.moveToNext())
}
}
} catch (e: Exception) {
context.showErrorToast(e)
} finally {
cursor?.close()
}
return parents
}
private fun getSelectionQuery(filterMedia: Int): String {
val query = StringBuilder()
if (filterMedia and TYPE_IMAGES != 0) {
photoExtensions.forEach {
query.append("${Images.Media.DATA} LIKE ? OR ")
}
}
if (filterMedia and TYPE_PORTRAITS != 0) {
query.append("${Images.Media.DATA} LIKE ? OR ")
query.append("${Images.Media.DATA} LIKE ? OR ")
}
if (filterMedia and TYPE_VIDEOS != 0) {
videoExtensions.forEach {
query.append("${Images.Media.DATA} LIKE ? OR ")
}
}
if (filterMedia and TYPE_GIFS != 0) {
query.append("${Images.Media.DATA} LIKE ? OR ")
}
if (filterMedia and TYPE_RAWS != 0) {
rawExtensions.forEach {
query.append("${Images.Media.DATA} LIKE ? OR ")
}
}
if (filterMedia and TYPE_SVGS != 0) {
query.append("${Images.Media.DATA} LIKE ? OR ")
}
return query.toString().trim().removeSuffix("OR")
}
private fun getSelectionArgsQuery(filterMedia: Int): ArrayList<String> {
val args = ArrayList<String>()
if (filterMedia and TYPE_IMAGES != 0) {
photoExtensions.forEach {
args.add("%$it")
}
}
if (filterMedia and TYPE_PORTRAITS != 0) {
args.add("%.jpg")
args.add("%.jpeg")
}
if (filterMedia and TYPE_VIDEOS != 0) {
videoExtensions.forEach {
args.add("%$it")
}
}
if (filterMedia and TYPE_GIFS != 0) {
args.add("%.gif")
}
if (filterMedia and TYPE_RAWS != 0) {
rawExtensions.forEach {
args.add("%$it")
}
}
if (filterMedia and TYPE_SVGS != 0) {
args.add("%.svg")
}
return args
}
private fun parseCursor(cursor: Cursor): LinkedHashSet<String> {
val foldersToIgnore = arrayListOf("/storage/emulated/legacy")
val config = context.config
val includedFolders = config.includedFolders
val OTGPath = config.OTGPath
val foldersToScan = config.everShownFolders.filter { it == FAVORITES || it == RECYCLE_BIN || context.getDoesFilePathExist(it, OTGPath) }.toHashSet()
cursor.use {
if (cursor.moveToFirst()) {
do {
val path = cursor.getStringValue(Images.Media.DATA)
val parentPath = File(path).parent ?: continue
if (!includedFolders.contains(parentPath) && !foldersToIgnore.contains(parentPath)) {
foldersToScan.add(parentPath)
}
} while (cursor.moveToNext())
}
}
includedFolders.forEach {
addFolder(foldersToScan, it)
}
return foldersToScan.toMutableSet() as LinkedHashSet<String>
}
private fun addFolder(curFolders: HashSet<String>, folder: String) {
curFolders.add(folder)
val files = File(folder).listFiles() ?: return
for (file in files) {
if (file.isDirectory) {
addFolder(curFolders, file.absolutePath)
}
}
}
private fun getMediaInFolder(
folder: String, isPickImage: Boolean, isPickVideo: Boolean, filterMedia: Int, getProperDateTaken: Boolean,
getProperLastModified: Boolean, getProperFileSize: Boolean, favoritePaths: ArrayList<String>,
getVideoDurations: Boolean, lastModifieds: HashMap<String, Long>, dateTakens: HashMap<String, Long>
): ArrayList<Medium> {
val media = ArrayList<Medium>()
val isRecycleBin = folder == RECYCLE_BIN
val deletedMedia = if (isRecycleBin) {
context.getUpdatedDeletedMedia()
} else {
ArrayList()
}
val config = context.config
val checkProperFileSize = getProperFileSize || config.fileLoadingPriority == PRIORITY_COMPROMISE
val checkFileExistence = config.fileLoadingPriority == PRIORITY_VALIDITY
val showHidden = config.shouldShowHidden
val showPortraits = filterMedia and TYPE_PORTRAITS != 0
val fileSizes = if (checkProperFileSize || checkFileExistence) getFolderSizes(folder) else HashMap()
val files = when (folder) {
FAVORITES -> favoritePaths.filter { showHidden || !it.contains("/.") }.map { File(it) }.toMutableList() as ArrayList<File>
RECYCLE_BIN -> deletedMedia.map { File(it.path) }.toMutableList() as ArrayList<File>
else -> File(folder).listFiles()?.toMutableList() ?: return media
}
for (curFile in files) {
var file = curFile
if (shouldStop) {
break
}
var path = file.absolutePath
var isPortrait = false
val isImage = path.isImageFast()
val isVideo = if (isImage) false else path.isVideoFast()
val isGif = if (isImage || isVideo) false else path.isGif()
val isRaw = if (isImage || isVideo || isGif) false else path.isRawFast()
val isSvg = if (isImage || isVideo || isGif || isRaw) false else path.isSvg()
if (!isImage && !isVideo && !isGif && !isRaw && !isSvg) {
if (showPortraits && file.name.startsWith("img_", true) && file.isDirectory) {
val portraitFiles = file.listFiles() ?: continue
val cover = portraitFiles.firstOrNull { it.name.contains("cover", true) } ?: portraitFiles.firstOrNull()
if (cover != null && !files.contains(cover)) {
file = cover
path = cover.absolutePath
isPortrait = true
} else {
continue
}
} else {
continue
}
}
if (isVideo && (isPickImage || filterMedia and TYPE_VIDEOS == 0))
continue
if (isImage && (isPickVideo || filterMedia and TYPE_IMAGES == 0))
continue
if (isGif && filterMedia and TYPE_GIFS == 0)
continue
if (isRaw && filterMedia and TYPE_RAWS == 0)
continue
if (isSvg && filterMedia and TYPE_SVGS == 0)
continue
val filename = file.name
if (!showHidden && filename.startsWith('.'))
continue
var size = 0L
if (checkProperFileSize || checkFileExistence) {
var newSize = fileSizes.remove(path)
if (newSize == null) {
newSize = file.length()
}
size = newSize
}
if ((checkProperFileSize || checkFileExistence) && size <= 0L) {
continue
}
if (checkFileExistence && (!file.exists() || !file.isFile)) {
continue
}
if (isRecycleBin) {
deletedMedia.firstOrNull { it.path == path }?.apply {
media.add(this)
}
} else {
var lastModified: Long
var newLastModified = lastModifieds.remove(path)
if (newLastModified == null) {
newLastModified = if (getProperLastModified) {
file.lastModified()
} else {
0L
}
}
lastModified = newLastModified
var dateTaken = lastModified
val videoDuration = if (getVideoDurations && isVideo) context.getDuration(path) ?: 0 else 0
if (getProperDateTaken) {
var newDateTaken = dateTakens.remove(path)
if (newDateTaken == null) {
newDateTaken = if (getProperLastModified) {
lastModified
} else {
file.lastModified()
}
}
dateTaken = newDateTaken
}
val type = when {
isVideo -> TYPE_VIDEOS
isGif -> TYPE_GIFS
isRaw -> TYPE_RAWS
isSvg -> TYPE_SVGS
isPortrait -> TYPE_PORTRAITS
else -> TYPE_IMAGES
}
val isFavorite = favoritePaths.contains(path)
val medium = Medium(null, filename, path, file.parent, lastModified, dateTaken, size, type, videoDuration, isFavorite, 0L)
media.add(medium)
}
}
return media
}
@SuppressLint("InlinedApi")
fun getAndroid11FolderMedia(
isPickImage: Boolean, isPickVideo: Boolean, favoritePaths: ArrayList<String>
): HashMap<String, ArrayList<Medium>> {
val media = HashMap<String, ArrayList<Medium>>()
val filterMedia = context.config.filterMedia
val showHidden = context.config.shouldShowHidden
val projection = arrayOf(
Images.Media.DISPLAY_NAME,
Images.Media.DATA,
Images.Media.DATE_MODIFIED,
Images.Media.DATE_TAKEN,
Images.Media.SIZE,
MediaStore.MediaColumns.DURATION
)
val uri = Files.getContentUri("external")
context.queryCursor(uri, projection) { cursor ->
if (shouldStop) {
return@queryCursor
}
try {
val filename = cursor.getStringValue(Images.Media.DISPLAY_NAME)
val path = cursor.getStringValue(Images.Media.DATA)
val lastModified = cursor.getLongValue(Images.Media.DATE_MODIFIED) * 1000
val dateTaken = cursor.getLongValue(Images.Media.DATE_TAKEN)
val size = cursor.getLongValue(Images.Media.SIZE)
val videoDuration = Math.round(cursor.getIntValue(MediaStore.MediaColumns.DURATION) / 1000.toDouble()).toInt()
val isPortrait = false
val isImage = path.isImageFast()
val isVideo = if (isImage) false else path.isVideoFast()
val isGif = if (isImage || isVideo) false else path.isGif()
val isRaw = if (isImage || isVideo || isGif) false else path.isRawFast()
val isSvg = if (isImage || isVideo || isGif || isRaw) false else path.isSvg()
if (!isImage && !isVideo && !isGif && !isRaw && !isSvg) {
return@queryCursor
}
if (isVideo && (isPickImage || filterMedia and TYPE_VIDEOS == 0))
return@queryCursor
if (isImage && (isPickVideo || filterMedia and TYPE_IMAGES == 0))
return@queryCursor
if (isGif && filterMedia and TYPE_GIFS == 0)
return@queryCursor
if (isRaw && filterMedia and TYPE_RAWS == 0)
return@queryCursor
if (isSvg && filterMedia and TYPE_SVGS == 0)
return@queryCursor
if (!showHidden && filename.startsWith('.'))
return@queryCursor
if (size <= 0L) {
return@queryCursor
}
val type = when {
isVideo -> TYPE_VIDEOS
isGif -> TYPE_GIFS
isRaw -> TYPE_RAWS
isSvg -> TYPE_SVGS
isPortrait -> TYPE_PORTRAITS
else -> TYPE_IMAGES
}
val isFavorite = favoritePaths.contains(path)
val medium = Medium(null, filename, path, path.getParentPath(), lastModified, dateTaken, size, type, videoDuration, isFavorite, 0L)
val parent = medium.parentPath.lowercase(Locale.getDefault())
val currentFolderMedia = media[parent]
if (currentFolderMedia == null) {
media[parent] = ArrayList<Medium>()
}
media[parent]?.add(medium)
} catch (e: Exception) {
}
}
return media
}
private fun getMediaOnOTG(
folder: String, isPickImage: Boolean, isPickVideo: Boolean, filterMedia: Int, favoritePaths: ArrayList<String>,
getVideoDurations: Boolean
): ArrayList<Medium> {
val media = ArrayList<Medium>()
val files = context.getDocumentFile(folder)?.listFiles() ?: return media
val checkFileExistence = context.config.fileLoadingPriority == PRIORITY_VALIDITY
val showHidden = context.config.shouldShowHidden
val OTGPath = context.config.OTGPath
for (file in files) {
if (shouldStop) {
break
}
val filename = file.name ?: continue
val isImage = filename.isImageFast()
val isVideo = if (isImage) false else filename.isVideoFast()
val isGif = if (isImage || isVideo) false else filename.isGif()
val isRaw = if (isImage || isVideo || isGif) false else filename.isRawFast()
val isSvg = if (isImage || isVideo || isGif || isRaw) false else filename.isSvg()
if (!isImage && !isVideo && !isGif && !isRaw && !isSvg)
continue
if (isVideo && (isPickImage || filterMedia and TYPE_VIDEOS == 0))
continue
if (isImage && (isPickVideo || filterMedia and TYPE_IMAGES == 0))
continue
if (isGif && filterMedia and TYPE_GIFS == 0)
continue
if (isRaw && filterMedia and TYPE_RAWS == 0)
continue
if (isSvg && filterMedia and TYPE_SVGS == 0)
continue
if (!showHidden && filename.startsWith('.'))
continue
val size = file.length()
if (size <= 0L || (checkFileExistence && !context.getDoesFilePathExist(file.uri.toString(), OTGPath)))
continue
val dateTaken = file.lastModified()
val dateModified = file.lastModified()
val type = when {
isVideo -> TYPE_VIDEOS
isGif -> TYPE_GIFS
isRaw -> TYPE_RAWS
isSvg -> TYPE_SVGS
else -> TYPE_IMAGES
}
val path = Uri.decode(
file.uri.toString().replaceFirst("${context.config.OTGTreeUri}/document/${context.config.OTGPartition}%3A", "${context.config.OTGPath}/")
)
val videoDuration = if (getVideoDurations) context.getDuration(path) ?: 0 else 0
val isFavorite = favoritePaths.contains(path)
val medium = Medium(null, filename, path, folder, dateModified, dateTaken, size, type, videoDuration, isFavorite, 0L)
media.add(medium)
}
return media
}
fun getFolderDateTakens(folder: String): HashMap<String, Long> {
val dateTakens = HashMap<String, Long>()
if (folder != FAVORITES) {
val projection = arrayOf(
Images.Media.DISPLAY_NAME,
Images.Media.DATE_TAKEN
)
val uri = Files.getContentUri("external")
val selection = "${Images.Media.DATA} LIKE ? AND ${Images.Media.DATA} NOT LIKE ?"
val selectionArgs = arrayOf("$folder/%", "$folder/%/%")
context.queryCursor(uri, projection, selection, selectionArgs) { cursor ->
try {
val dateTaken = cursor.getLongValue(Images.Media.DATE_TAKEN)
if (dateTaken != 0L) {
val name = cursor.getStringValue(Images.Media.DISPLAY_NAME)
dateTakens["$folder/$name"] = dateTaken
}
} catch (e: Exception) {
}
}
}
val dateTakenValues = try {
if (folder == FAVORITES) {
context.dateTakensDB.getAllDateTakens()
} else {
context.dateTakensDB.getDateTakensFromPath(folder)
}
} catch (e: Exception) {
return dateTakens
}
dateTakenValues.forEach {
dateTakens[it.fullPath] = it.taken
}
return dateTakens
}
fun getDateTakens(): HashMap<String, Long> {
val dateTakens = HashMap<String, Long>()
val projection = arrayOf(
Images.Media.DATA,
Images.Media.DATE_TAKEN
)
val uri = Files.getContentUri("external")
try {
context.queryCursor(uri, projection) { cursor ->
try {
val dateTaken = cursor.getLongValue(Images.Media.DATE_TAKEN)
if (dateTaken != 0L) {
val path = cursor.getStringValue(Images.Media.DATA)
dateTakens[path] = dateTaken
}
} catch (e: Exception) {
}
}
val dateTakenValues = context.dateTakensDB.getAllDateTakens()
dateTakenValues.forEach {
dateTakens[it.fullPath] = it.taken
}
} catch (e: Exception) {
}
return dateTakens
}
fun getFolderLastModifieds(folder: String): HashMap<String, Long> {
val lastModifieds = HashMap<String, Long>()
if (folder != FAVORITES) {
val projection = arrayOf(
Images.Media.DISPLAY_NAME,
Images.Media.DATE_MODIFIED
)
val uri = Files.getContentUri("external")
val selection = "${Images.Media.DATA} LIKE ? AND ${Images.Media.DATA} NOT LIKE ?"
val selectionArgs = arrayOf("$folder/%", "$folder/%/%")
context.queryCursor(uri, projection, selection, selectionArgs) { cursor ->
try {
val lastModified = cursor.getLongValue(Images.Media.DATE_MODIFIED) * 1000
if (lastModified != 0L) {
val name = cursor.getStringValue(Images.Media.DISPLAY_NAME)
lastModifieds["$folder/$name"] = lastModified
}
} catch (e: Exception) {
}
}
}
return lastModifieds
}
fun getLastModifieds(): HashMap<String, Long> {
val lastModifieds = HashMap<String, Long>()
val projection = arrayOf(
Images.Media.DATA,
Images.Media.DATE_MODIFIED
)
val uri = Files.getContentUri("external")
try {
context.queryCursor(uri, projection) { cursor ->
try {
val lastModified = cursor.getLongValue(Images.Media.DATE_MODIFIED) * 1000
if (lastModified != 0L) {
val path = cursor.getStringValue(Images.Media.DATA)
lastModifieds[path] = lastModified
}
} catch (e: Exception) {
}
}
} catch (e: Exception) {
}
return lastModifieds
}
private fun getFolderSizes(folder: String): HashMap<String, Long> {
val sizes = HashMap<String, Long>()
if (folder != FAVORITES) {
val projection = arrayOf(
Images.Media.DISPLAY_NAME,
Images.Media.SIZE
)
val uri = Files.getContentUri("external")
val selection = "${Images.Media.DATA} LIKE ? AND ${Images.Media.DATA} NOT LIKE ?"
val selectionArgs = arrayOf("$folder/%", "$folder/%/%")
context.queryCursor(uri, projection, selection, selectionArgs) { cursor ->
try {
val size = cursor.getLongValue(Images.Media.SIZE)
if (size != 0L) {
val name = cursor.getStringValue(Images.Media.DISPLAY_NAME)
sizes["$folder/$name"] = size
}
} catch (e: Exception) {
}
}
}
return sizes
}
fun sortMedia(media: ArrayList<Medium>, sorting: Int) {
if (sorting and SORT_BY_RANDOM != 0) {
media.shuffle()
return
}
media.sortWith { o1, o2 ->
o1 as Medium
o2 as Medium
var result = when {
sorting and SORT_BY_NAME != 0 -> {
if (sorting and SORT_USE_NUMERIC_VALUE != 0) {
AlphanumericComparator().compare(o1.name.toLowerCase(), o2.name.toLowerCase())
} else {
o1.name.toLowerCase().compareTo(o2.name.toLowerCase())
}
}
sorting and SORT_BY_PATH != 0 -> {
if (sorting and SORT_USE_NUMERIC_VALUE != 0) {
AlphanumericComparator().compare(o1.path.toLowerCase(), o2.path.toLowerCase())
} else {
o1.path.toLowerCase().compareTo(o2.path.toLowerCase())
}
}
sorting and SORT_BY_SIZE != 0 -> o1.size.compareTo(o2.size)
sorting and SORT_BY_DATE_MODIFIED != 0 -> o1.modified.compareTo(o2.modified)
else -> o1.taken.compareTo(o2.taken)
}
if (sorting and SORT_DESCENDING != 0) {
result *= -1
}
result
}
}
fun groupMedia(media: ArrayList<Medium>, path: String): ArrayList<ThumbnailItem> {
val pathToCheck = if (path.isEmpty()) SHOW_ALL else path
val currentGrouping = context.config.getFolderGrouping(pathToCheck)
if (currentGrouping and GROUP_BY_NONE != 0) {
return media as ArrayList<ThumbnailItem>
}
val thumbnailItems = ArrayList<ThumbnailItem>()
if (context.config.scrollHorizontally) {
media.mapTo(thumbnailItems) { it }
return thumbnailItems
}
val mediumGroups = LinkedHashMap<String, ArrayList<Medium>>()
media.forEach {
val key = it.getGroupingKey(currentGrouping)
if (!mediumGroups.containsKey(key)) {
mediumGroups[key] = ArrayList()
}
mediumGroups[key]!!.add(it)
}
val sortDescending = currentGrouping and GROUP_DESCENDING != 0
val sorted = if (currentGrouping and GROUP_BY_LAST_MODIFIED_DAILY != 0 || currentGrouping and GROUP_BY_LAST_MODIFIED_MONTHLY != 0 ||
currentGrouping and GROUP_BY_DATE_TAKEN_DAILY != 0 || currentGrouping and GROUP_BY_DATE_TAKEN_MONTHLY != 0
) {
mediumGroups.toSortedMap(if (sortDescending) compareByDescending {
it.toLongOrNull() ?: 0L
} else {
compareBy { it.toLongOrNull() ?: 0L }
})
} else {
mediumGroups.toSortedMap(if (sortDescending) compareByDescending { it } else compareBy { it })
}
mediumGroups.clear()
for ((key, value) in sorted) {
mediumGroups[key] = value
}
val today = formatDate(System.currentTimeMillis().toString(), true)
val yesterday = formatDate((System.currentTimeMillis() - DAY_SECONDS * 1000).toString(), true)
for ((key, value) in mediumGroups) {
var currentGridPosition = 0
val sectionKey = getFormattedKey(key, currentGrouping, today, yesterday)
thumbnailItems.add(ThumbnailSection(sectionKey))
value.forEach {
it.gridPosition = currentGridPosition++
}
thumbnailItems.addAll(value)
}
return thumbnailItems
}
private fun getFormattedKey(key: String, grouping: Int, today: String, yesterday: String): String {
var result = when {
grouping and GROUP_BY_LAST_MODIFIED_DAILY != 0 || grouping and GROUP_BY_DATE_TAKEN_DAILY != 0 -> getFinalDate(
formatDate(key, true),
today,
yesterday
)
grouping and GROUP_BY_LAST_MODIFIED_MONTHLY != 0 || grouping and GROUP_BY_DATE_TAKEN_MONTHLY != 0 -> formatDate(key, false)
grouping and GROUP_BY_FILE_TYPE != 0 -> getFileTypeString(key)
grouping and GROUP_BY_EXTENSION != 0 -> key.toUpperCase()
grouping and GROUP_BY_FOLDER != 0 -> context.humanizePath(key)
else -> key
}
if (result.isEmpty()) {
result = context.getString(R.string.unknown)
}
return result
}
private fun getFinalDate(date: String, today: String, yesterday: String): String {
return when (date) {
today -> context.getString(R.string.today)
yesterday -> context.getString(R.string.yesterday)
else -> date
}
}
private fun formatDate(timestamp: String, showDay: Boolean): String {
return if (timestamp.areDigitsOnly()) {
val cal = Calendar.getInstance(Locale.ENGLISH)
cal.timeInMillis = timestamp.toLong()
val format = if (showDay) context.config.dateFormat else "MMMM yyyy"
DateFormat.format(format, cal).toString()
} else {
""
}
}
private fun getFileTypeString(key: String): String {
val stringId = when (key.toInt()) {
TYPE_IMAGES -> R.string.images
TYPE_VIDEOS -> R.string.videos
TYPE_GIFS -> R.string.gifs
TYPE_RAWS -> R.string.raw_images
TYPE_SVGS -> R.string.svgs
else -> R.string.portraits
}
return context.getString(stringId)
}
}
| gpl-3.0 | b8c6206e20d860025fa98e5611f3fcf1 | 36.960187 | 156 | 0.543926 | 4.938757 | false | false | false | false |
ekoshkin/teamcity-kubernetes-plugin | teamcity-kubernetes-plugin-server/src/main/java/jetbrains/buildServer/clouds/kubernetes/auth/OIDCAuthStrategy.kt | 1 | 4583 | package jetbrains.buildServer.clouds.kubernetes.auth
import com.google.gson.JsonParser
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.io.StreamUtil
import jetbrains.buildServer.clouds.kubernetes.KubeCloudException
import jetbrains.buildServer.clouds.kubernetes.KubeParametersConstants.*
import jetbrains.buildServer.clouds.kubernetes.connector.KubeApiConnection
import jetbrains.buildServer.util.FileUtil
import jetbrains.buildServer.util.StringUtil
import jetbrains.buildServer.util.TimeService
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.message.BasicNameValuePair
import org.springframework.security.crypto.codec.Base64
import java.io.InputStream
import java.net.URI
import java.util.*
class OIDCAuthStrategy(myTimeService: TimeService) : RefreshableStrategy<OIDCData>(myTimeService) {
override fun retrieveNewToken(dataHolder: OIDCData): Pair<String, Long>? {
var stream: InputStream? = null
try {
val providerConfigurationURL = URI(dataHolder.myIssuerUrl).resolve("/.well-known/openid-configuration").toURL()
stream = providerConfigurationURL.openStream()
val text = StreamUtil.readText(stream!!)
println()
val parser = JsonParser()
val element = parser.parse(text)
val tokenEndpoint = element.asJsonObject.get("token_endpoint").asString
val clientBuilder = HttpClientBuilder.create()
val build = clientBuilder.build()
val request = HttpPost(tokenEndpoint)
request.entity = UrlEncodedFormEntity(Arrays.asList(BasicNameValuePair("refresh_token", dataHolder.myRefreshToken),
BasicNameValuePair("grant_type", "refresh_token")))
request.setHeader("Authorization", "Basic " + String(Base64.encode((dataHolder.myClientId + ":" + dataHolder.myClientSecret).toByteArray())))
val response = build.execute(request)
if (response.statusLine != null && response.statusLine.statusCode == 200) {
val tokenData = StreamUtil.readText(response.entity.content)
val tokenRequestElement = parser.parse(tokenData)
val tokenRequestObj = tokenRequestElement.asJsonObject
val idToken = tokenRequestObj.get("id_token").asString
val expireSec: Long
if (tokenRequestObj.has("expires_in")) {
expireSec = tokenRequestObj.get("expires_in").asLong
} else {
expireSec = 365 * 24 * 86400L //one year
}
LOG.info("Retrieved new token for user ${dataHolder.myClientId} from ${dataHolder.myIssuerUrl}. Token expires in ${expireSec} sec")
return Pair.create(idToken, expireSec)
}
} catch (e: Exception) {
LOG.warnAndDebugDetails("An error occurred while retrieving token for user ${dataHolder.myClientId} from ${dataHolder.myIssuerUrl}", e)
} finally {
FileUtil.close(stream)
}
return null
}
override fun createKey(dataHolder: OIDCData): Pair<String, String> {
return Pair.create(dataHolder.myClientId, dataHolder.myIssuerUrl)
}
override fun createData(connection: KubeApiConnection): OIDCData {
val clientId = connection.getCustomParameter(OIDC_CLIENT_ID) ?: throw KubeCloudException("Client ID is empty for connection to " + connection.apiServerUrl)
val clientSecret = connection.getCustomParameter(OIDC_CLIENT_SECRET) ?: throw KubeCloudException("Client secret is empty for connection to " + connection.apiServerUrl)
val issuerUrl = connection.getCustomParameter(OIDC_ISSUER_URL) ?: throw KubeCloudException("Issuer URL is empty for connection to " + connection.apiServerUrl)
val refreshToken = connection.getCustomParameter(OIDC_REFRESH_TOKEN) ?: throw KubeCloudException("Refresh token is empty for connection to " + connection.apiServerUrl)
return OIDCData(clientId, clientSecret, issuerUrl, refreshToken)
}
override fun getId() = "oidc"
override fun getDisplayName() = "Open ID"
override fun getDescription() = "Authenticate with Open ID provider"
}
data class OIDCData(val myClientId: String,
val myClientSecret: String,
val myIssuerUrl: String,
val myRefreshToken: String) | apache-2.0 | f5f570b3324311fb8304955ed01042a0 | 50.505618 | 175 | 0.700633 | 4.7394 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/quickfixes/CreateAssetQuickfix.kt | 1 | 3688 | package com.gmail.blueboxware.libgdxplugin.filetypes.skin.quickfixes
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.LibGDXSkinLanguage
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinElement
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.impl.SkinFileImpl
import com.gmail.blueboxware.libgdxplugin.utils.COLOR_CLASS_NAME
import com.gmail.blueboxware.libgdxplugin.utils.DRAWABLE_CLASS_NAME
import com.gmail.blueboxware.libgdxplugin.utils.DollarClassName
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.intention.FileModifier
import com.intellij.codeInspection.LocalQuickFixOnPsiElement
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
/*
* Copyright 2018 Blue Box Ware
*
* 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.
*/
class CreateAssetQuickFix(
element: SkinElement,
private val assetName: String,
@FileModifier.SafeFieldForPreview val className: DollarClassName,
val filename: String? = null
) : LocalQuickFixOnPsiElement(element) {
override fun getFamilyName(): String = FAMILY_NAME
override fun getText(): String = "Create resource '$assetName'" + if (filename != null) " in '$filename'" else ""
override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) {
val skinFile = startElement.containingFile as? SkinFileImpl ?: return
FileEditorManager.getInstance(project).openFile(skinFile.virtualFile, true, true)
val (_, position) = when (className.plainName) {
DRAWABLE_CLASS_NAME -> skinFile.addTintedDrawable(assetName, startElement as? SkinElement)
COLOR_CLASS_NAME -> skinFile.addColor(assetName, startElement as? SkinElement)
else -> skinFile.addResource(className, assetName, startElement as? SkinElement)
} ?: return
FileEditorManager.getInstance(project).selectedTextEditor?.let { editor ->
FileDocumentManager.getInstance().let { fileDocumentManager ->
if (fileDocumentManager.getFile(editor.document) == file.virtualFile) {
editor.caretModel.moveToOffset(position)
if (
className.plainName != DRAWABLE_CLASS_NAME
&& className.plainName != COLOR_CLASS_NAME
&& CodeStyle
.getLanguageSettings(file, LibGDXSkinLanguage.INSTANCE)
.SPACE_WITHIN_BRACES
) {
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document)
editor.document.insertString(editor.caretModel.offset, " ")
editor.caretModel.moveToOffset(editor.caretModel.offset - 2)
}
}
}
}
}
companion object {
const val FAMILY_NAME = "Create resource"
}
}
| apache-2.0 | 6241506ceab33a771032293f6f6b7ed9 | 41.390805 | 120 | 0.703633 | 4.904255 | false | false | false | false |
eurofurence/ef-app_android | app/src/main/kotlin/org/eurofurence/connavigator/ui/fragments/EventFeedbackFragment.kt | 1 | 8334 | package org.eurofurence.connavigator.ui.fragments
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import io.swagger.client.model.EventFeedbackRecord
import io.swagger.client.model.EventRecord
import nl.komponents.kovenant.then
import nl.komponents.kovenant.ui.failUi
import nl.komponents.kovenant.ui.promiseOnUi
import nl.komponents.kovenant.ui.successUi
import org.eurofurence.connavigator.BuildConfig
import org.eurofurence.connavigator.R
import org.eurofurence.connavigator.database.HasDb
import org.eurofurence.connavigator.database.lazyLocateDb
import org.eurofurence.connavigator.ui.LayoutConstants
import org.eurofurence.connavigator.ui.filters.start
import org.eurofurence.connavigator.util.extensions.*
import org.eurofurence.connavigator.services.apiService
import org.jetbrains.anko.*
import org.jetbrains.anko.support.v4.UI
import org.jetbrains.anko.support.v4.longToast
import java.util.*
class EventFeedbackFragment : Fragment(), HasDb {
val ui = EventFeedbackUi()
private val args: EventFeedbackFragmentArgs by navArgs()
val eventId by lazy { UUID.fromString(args.eventId) }
val event: EventRecord? by lazy { db.events[eventId] }
val conferenceRoom by lazy { db.rooms[event?.conferenceRoomId] }
override val db by lazyLocateDb()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
UI { ui.createView(this) }.view
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
event?.let {
if (!it.isAcceptingFeedback && !BuildConfig.DEBUG)
findNavController().popBackStack()
ui.apply {
titleView.text = it.fullTitle()
dateView.text = getString(R.string.event_weekday_from_to, it.start.dayOfWeek().asText, it.startTimeString(), it.endTimeString())
hostView.text = it.ownerString()
locationView.text = getString(R.string.misc_room_number, conferenceRoom?.name
?: getString(R.string.event_unable_to_locate_room))
submitButton.setOnClickListener { submit() }
}
}
}
private fun submit() = promiseOnUi {
ui.loading()
} then {
val rating = ui.ratingBar.rating.toInt()
val comments = ui.textInput.text.toString()
if(rating == 0) {
throw Exception()
}
val eventFeedback = EventFeedbackRecord().apply {
this.eventId = [email protected]
this.message = comments
this.rating = rating
}
apiService.feedbacks.apiEventFeedbackPost(eventFeedback)
} successUi {
ui.done()
} failUi {
if(ui.ratingBar.rating == 0f ) {
longToast("You have to select a rating!")
} else {
longToast("Failed to send feedback! Try again.")
}
ui.dataInput()
}
}
class EventFeedbackUi : AnkoComponent<Fragment> {
lateinit var titleView: TextView
lateinit var dateView: TextView
lateinit var locationView: TextView
lateinit var hostView: TextView
lateinit var submitButton: Button
lateinit var textInput: EditText
lateinit var ratingBar: RatingBar
lateinit var dataInputLayout: LinearLayout
lateinit var loadingLayout: LinearLayout
lateinit var doneLayout: LinearLayout
fun dataInput() {
dataInputLayout.visibility = View.VISIBLE
loadingLayout.visibility = View.GONE
doneLayout.visibility = View.GONE
}
fun loading() {
}
fun done() {
dataInputLayout.visibility = View.GONE
loadingLayout.visibility = View.GONE
doneLayout.visibility = View.VISIBLE
}
override fun createView(ui: AnkoContext<Fragment>) = with(ui) {
scrollView {
backgroundResource = R.color.backgroundGrey
verticalLayout {
// Event Info
linearLayout {
weightSum = 10F
padding = dip(LayoutConstants.MARGIN_LARGE)
verticalLayout {
fontAwesomeView {
verticalPadding = dip(LayoutConstants.MARGIN_LARGE)
text = "{fa-comments 30sp}"
textSize = LayoutConstants.TEXT_ICON_SIZE
textColorResource = R.color.primaryDark
gravity = Gravity.CENTER
}
}.weight(2F)
verticalLayout {
titleView = textView() {
verticalPadding = dip(LayoutConstants.MARGIN_SMALL)
textAppearance = android.R.style.TextAppearance_DeviceDefault_Large
}
dateView = textView()
locationView = textView()
hostView = textView()
}.weight(8F)
}.lparams(matchParent, wrapContent)
// End Event info
// Event Feedback
verticalLayout {
padding = dip(LayoutConstants.MARGIN_LARGE)
backgroundResource = R.color.lightBackground
dataInputLayout = verticalLayout {
textView(R.string.event_feedback_rate_title) {
textColorResource = R.color.textBlack
textAppearance = android.R.style.TextAppearance_DeviceDefault_Medium
}
ratingBar = ratingBar {
verticalPadding = dip(LayoutConstants.MARGIN_LARGE)
numStars = 5
stepSize = 1F
}.lparams(wrapContent, wrapContent)
textView(R.string.event_feedback_comment_header) {
textColorResource = R.color.textBlack
textAppearance = android.R.style.TextAppearance_DeviceDefault_Medium
}
textInput = editText {
hint = context.getString(R.string.event_feedback_comment_hint)
}
textView(R.string.event_feedback_anonymous_help) {
verticalPadding = dip(LayoutConstants.MARGIN_LARGE)
textAppearance = android.R.style.TextAppearance_DeviceDefault_Small
}
linearLayout {
weightSum = 10F
view().lparams(dip(0), wrapContent, 6F)
submitButton = button(R.string.event_feedback_submit) {
backgroundResource = R.color.primaryLight
textColorResource = R.color.textWhite
}.lparams(dip(0), wrapContent, 4F)
}.lparams(matchParent, wrapContent) {
topMargin = dip(LayoutConstants.MARGIN_LARGE)
}
}
loadingLayout = verticalLayout {
visibility = View.GONE
progressBar()
}
doneLayout = verticalLayout {
visibility = View.GONE
textView(R.string.event_feedback_thank) {
textColorResource = R.color.textBlack
textAppearance = android.R.style.TextAppearance_DeviceDefault_Medium
}
}
}
}
}
}
}
| mit | 45e7e50ee6301c947f3819f852ef88e2 | 36.762791 | 144 | 0.555316 | 5.482895 | false | false | false | false |
google/private-compute-libraries | java/com/google/android/libraries/pcc/chronicle/codegen/backend/api/DaggerModuleProvider.kt | 1 | 2609 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.codegen.backend.api
import com.squareup.javapoet.AnnotationSpec
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.TypeSpec
import javax.lang.model.element.Modifier
/**
* Tool to aide in generating dagger modules as abstract java classes.
*
* **Example:**
* ```kotlin
* DaggerModuleProvider("MyModule", contents = myListOfContentsProviders)
* .provideModule()
* ```
*
* Generates:
* ```java
* @Module
* @InstallIn(SingletonComponent.class)
* public abstract class MyModule {
* /* provides/binds methods from myListOfContentsProviders */
* }
* ```
*
* @param name the name of the module class itself.
* @param installInComponent the hilt component the generated module should be installed into.
* @param contents list of [DaggerModuleContentsProviders][DaggerModuleContentsProvider],
* responsible for generating the individual provides/binds methods for the generated module.
*/
class DaggerModuleProvider(
private val name: String,
private val installInComponent: ClassName = SINGLETON_COMPONENT,
private val contents: List<DaggerModuleContentsProvider>
) {
/** Generates a [TypeSpec] of the dagger module to use in creating a [JavaFile]. */
fun provideModule(): TypeSpec {
return TypeSpec.classBuilder(name)
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.addAnnotation(MODULE_ANNOTATION)
.addAnnotation(
AnnotationSpec.builder(INSTALL_IN_ANNOTATION)
.addMember("value", "\$T.class", installInComponent)
.build()
)
.apply { contents.forEach { it.provideContentsInto(this) } }
.build()
}
companion object {
/** [ClassName] of the hilt SingletonComponent. */
val SINGLETON_COMPONENT: ClassName =
ClassName.get("dagger.hilt.components", "SingletonComponent")
private val MODULE_ANNOTATION = ClassName.get("dagger", "Module")
private val INSTALL_IN_ANNOTATION = ClassName.get("dagger.hilt", "InstallIn")
}
}
| apache-2.0 | 36acb607c2a6d282052ea2b16e3a792c | 34.256757 | 94 | 0.728632 | 4.3267 | false | false | false | false |
arcao/Geocaching4Locus | geocaching-api/src/main/java/com/arcao/geocaching4locus/data/api/model/User.kt | 1 | 2772 | package com.arcao.geocaching4locus.data.api.model
import com.arcao.geocaching4locus.data.api.model.enums.MembershipType
import com.arcao.geocaching4locus.data.api.util.ReferenceCode
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class User(
val referenceCode: String?, // string
val findCount: Int = 0, // 0
val hideCount: Int = 0, // 0
val favoritePoints: Int = 0, // 0
val username: String?, // string
@Json(name = "membershipLevelId") val membership: MembershipType = MembershipType.UNKNOWN, // 0
val avatarUrl: String?, // string
val bannerUrl: String?, // string
val profileText: String?, // string
val url: String?, // string
val homeCoordinates: Coordinates?,
val geocacheLimits: GeocacheLimits?
) {
val id by lazy {
ReferenceCode.toId(requireNotNull(referenceCode) {
"Reference code is null."
})
}
companion object {
private const val FIELD_REFERENCE_CODE = "referenceCode"
private const val FIELD_FIND_COUNT = "findCount"
private const val FIELD_HIDE_COUNT = "hideCount"
private const val FIELD_FAVORITE_POINTS = "favoritePoints"
private const val FIELD_USERNAME = "username"
private const val FIELD_MEMBERSHIP = "membershipLevelId"
private const val FIELD_AVATAR_URL = "avatarUrl"
private const val FIELD_BANNER_URL = "bannerUrl"
private const val FIELD_PROFILE_TEXT = "profileText"
private const val FIELD_URL = "url"
private const val FIELD_HOME_COORDINATES = "homeCoordinates"
private const val FIELD_GEOCACHE_LIMITS = "geocacheLimits"
// GDPR safe fields
val FIELDS_ALL_NO_HOME_COORDINATES = fieldsOf(
FIELD_REFERENCE_CODE,
FIELD_FIND_COUNT,
FIELD_HIDE_COUNT,
FIELD_FAVORITE_POINTS,
FIELD_USERNAME,
FIELD_MEMBERSHIP,
FIELD_AVATAR_URL,
FIELD_BANNER_URL,
FIELD_PROFILE_TEXT,
FIELD_URL,
FIELD_GEOCACHE_LIMITS
)
val FIELDS_ALL = fieldsOf(
FIELD_REFERENCE_CODE,
FIELD_FIND_COUNT,
FIELD_HIDE_COUNT,
FIELD_FAVORITE_POINTS,
FIELD_USERNAME,
FIELD_MEMBERSHIP,
FIELD_AVATAR_URL,
FIELD_BANNER_URL,
FIELD_PROFILE_TEXT,
FIELD_URL,
FIELD_HOME_COORDINATES,
FIELD_GEOCACHE_LIMITS
)
val FIELDS_MIN = fieldsOf(
FIELD_REFERENCE_CODE,
FIELD_USERNAME
)
val FIELDS_LIMITS = fieldsOf(
FIELD_MEMBERSHIP,
FIELD_GEOCACHE_LIMITS
)
}
}
| gpl-3.0 | d886895cdf59a7dd2bd4da52069f4e13 | 32.39759 | 99 | 0.613276 | 4.311042 | false | false | false | false |
industrial-data-space/trusted-connector | ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/ContainerManagerService.kt | 1 | 4797 | /*-
* ========================LICENSE_START=================================
* ids-container-manager
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.cm
import de.fhg.aisec.ids.api.cm.ApplicationContainer
import de.fhg.aisec.ids.api.cm.ContainerManager
import de.fhg.aisec.ids.api.cm.Decision
import de.fhg.aisec.ids.api.cm.Direction
import de.fhg.aisec.ids.api.cm.NoContainerExistsException
import de.fhg.aisec.ids.api.cm.Protocol
import de.fhg.aisec.ids.cm.impl.docker.DockerCM
import de.fhg.aisec.ids.cm.impl.docker.DockerCM.Companion.isSupported
import de.fhg.aisec.ids.cm.impl.dummy.DummyCM
import de.fhg.aisec.ids.cm.impl.trustx.TrustXCM
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
/**
* Main entry point of the Container Management Layer.
*
*
* This class is mainly a facade for the actual CML implementation, which can either be Docker or
* trust-X.
*
* @author Julian Schütte ([email protected])
*/
@Component("idsContainerManager")
class ContainerManagerService : ContainerManager {
private val containerManager: ContainerManager
private val defaultCM: ContainerManager
get() {
return when {
TrustXCM.isSupported -> {
TrustXCM()
}
isSupported -> {
DockerCM()
}
else -> {
LOG.warn("No supported container management layer found. Using dummy")
DummyCM()
}
}
}
override fun list(onlyRunning: Boolean): List<ApplicationContainer> {
return containerManager.list(onlyRunning)
}
override fun wipe(containerID: String) {
try {
containerManager.wipe(containerID)
} catch (e: NoContainerExistsException) {
LOG.error(e.message, e)
}
}
override fun startContainer(containerID: String, key: String?) {
try {
containerManager.startContainer(containerID, key)
} catch (e: NoContainerExistsException) {
LOG.error(e.message, e)
}
}
override fun stopContainer(containerID: String) {
try {
containerManager.stopContainer(containerID)
} catch (e: NoContainerExistsException) {
LOG.error(e.message, e)
}
}
override fun restartContainer(containerID: String) {
try {
containerManager.restartContainer(containerID)
} catch (e: NoContainerExistsException) {
LOG.error(e.message, e)
}
}
override fun pullImage(app: ApplicationContainer): String? {
try {
return containerManager.pullImage(app)
} catch (e: NoContainerExistsException) {
LOG.error(e.message, e)
}
return null
}
override fun inspectContainer(containerID: String): String? {
try {
return containerManager.inspectContainer(containerID)
} catch (e: NoContainerExistsException) {
LOG.error(e.message, e)
}
return ""
}
override fun getMetadata(containerID: String): Any? {
try {
return containerManager.getMetadata(containerID)
} catch (e: NoContainerExistsException) {
LOG.error(e.message, e)
}
return null
}
override fun setIpRule(
containerID: String,
direction: Direction,
srcPort: Int,
dstPort: Int,
srcDstRange: String,
protocol: Protocol,
decision: Decision
) {
containerManager.setIpRule(
containerID, direction, srcPort, dstPort, srcDstRange, protocol, decision
)
}
override val version: String
get() = containerManager.version
companion object {
private val LOG = LoggerFactory.getLogger(ContainerManagerService::class.java)
}
init {
// When activated, try to set container management instance
containerManager = defaultCM
LOG.info("Default container management is {}", containerManager)
}
}
| apache-2.0 | 74ba3ee16b239077afe30d04b6d85252 | 30.552632 | 97 | 0.621977 | 4.35604 | false | false | false | false |
google-developer-training/basic-android-kotlin-compose-training-dessert-release | app/src/main/java/com/example/dessertrelease/ui/theme/Type.kt | 1 | 1066 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dessertrelease.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
h1 = TextStyle(
fontWeight = FontWeight.SemiBold,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
)
)
| apache-2.0 | 847b058d6f132b78f128e7d64bfd812c | 32.3125 | 75 | 0.73546 | 4.164063 | false | false | false | false |
square/kotlinpoet | interop/ksp/src/main/kotlin/com/squareup/kotlinpoet/ksp/KsTypes.kt | 1 | 7277 | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.kotlinpoet.ksp
import com.google.devtools.ksp.symbol.ClassKind
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSType
import com.google.devtools.ksp.symbol.KSTypeAlias
import com.google.devtools.ksp.symbol.KSTypeArgument
import com.google.devtools.ksp.symbol.KSTypeParameter
import com.google.devtools.ksp.symbol.KSTypeReference
import com.google.devtools.ksp.symbol.Variance
import com.google.devtools.ksp.symbol.Variance.CONTRAVARIANT
import com.google.devtools.ksp.symbol.Variance.COVARIANT
import com.google.devtools.ksp.symbol.Variance.INVARIANT
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.STAR
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeVariableName
import com.squareup.kotlinpoet.WildcardTypeName
import com.squareup.kotlinpoet.tags.TypeAliasTag
/** Returns the [ClassName] representation of this [KSType] IFF it's a [KSClassDeclaration]. */
public fun KSType.toClassName(): ClassName {
val decl = declaration
check(decl is KSClassDeclaration) {
"Declaration was not a KSClassDeclaration: $this"
}
return decl.toClassName()
}
/**
* Returns the [TypeName] representation of this [KSType].
*
* @see toTypeParameterResolver
* @param typeParamResolver an optional resolver for enclosing declarations' type parameters. Parent
* declarations can be anything with generics that child nodes declare as
* defined by [KSType.arguments].
*/
public fun KSType.toTypeName(
typeParamResolver: TypeParameterResolver = TypeParameterResolver.EMPTY,
): TypeName = toTypeName(typeParamResolver, emptyList())
internal fun KSType.toTypeName(
typeParamResolver: TypeParameterResolver,
typeArguments: List<KSTypeArgument>,
): TypeName {
require(!isError) {
"Error type '$this' is not resolvable in the current round of processing."
}
val type = when (val decl = declaration) {
is KSClassDeclaration -> {
val arguments = if (decl.classKind == ClassKind.ANNOTATION_CLASS) {
arguments
} else {
typeArguments
}
decl.toClassName().withTypeArguments(arguments.map { it.toTypeName(typeParamResolver) })
}
is KSTypeParameter -> typeParamResolver[decl.name.getShortName()]
is KSTypeAlias -> {
var typeAlias: KSTypeAlias = decl
var arguments = arguments
var resolvedType: KSType
var mappedArgs: List<KSTypeArgument>
var extraResolver: TypeParameterResolver = typeParamResolver
while (true) {
resolvedType = typeAlias.type.resolve()
mappedArgs = mapTypeArgumentsFromTypeAliasToAbbreviatedType(
typeAlias = typeAlias,
typeAliasTypeArguments = arguments,
abbreviatedType = resolvedType,
)
extraResolver = if (typeAlias.typeParameters.isEmpty()) {
extraResolver
} else {
typeAlias.typeParameters.toTypeParameterResolver(extraResolver)
}
typeAlias = resolvedType.declaration as? KSTypeAlias ?: break
arguments = mappedArgs
}
val abbreviatedType = resolvedType
.toTypeName(extraResolver)
.copy(nullable = isMarkedNullable)
.rawType()
.withTypeArguments(mappedArgs.map { it.toTypeName(extraResolver) })
val aliasArgs = typeArguments.map { it.toTypeName(typeParamResolver) }
decl.toClassNameInternal()
.withTypeArguments(aliasArgs)
.copy(tags = mapOf(TypeAliasTag::class to TypeAliasTag(abbreviatedType)))
}
else -> error("Unsupported type: $declaration")
}
return type.copy(nullable = isMarkedNullable)
}
private fun mapTypeArgumentsFromTypeAliasToAbbreviatedType(
typeAlias: KSTypeAlias,
typeAliasTypeArguments: List<KSTypeArgument>,
abbreviatedType: KSType,
): List<KSTypeArgument> {
return abbreviatedType.arguments
.map { typeArgument ->
// Check if type argument is a reference to a typealias type parameter, and not an actual type.
val typeAliasTypeParameterIndex = typeAlias.typeParameters.indexOfFirst { typeAliasTypeParameter ->
typeAliasTypeParameter.name.asString() == typeArgument.type.toString()
}
if (typeAliasTypeParameterIndex >= 0) {
typeAliasTypeArguments[typeAliasTypeParameterIndex]
} else {
typeArgument
}
}
}
/**
* Returns a [TypeVariableName] representation of this [KSTypeParameter].
*
* @see toTypeParameterResolver
* @param typeParamResolver an optional resolver for enclosing declarations' type parameters. Parent
* declarations can be anything with generics that child nodes declare as
* defined by [KSType.arguments].
*/
public fun KSTypeParameter.toTypeVariableName(
typeParamResolver: TypeParameterResolver = TypeParameterResolver.EMPTY,
): TypeVariableName {
val typeVarName = name.getShortName()
val typeVarBounds = bounds.map { it.toTypeName(typeParamResolver) }.toList()
val typeVarVariance = when (variance) {
COVARIANT -> KModifier.OUT
CONTRAVARIANT -> KModifier.IN
else -> null
}
return TypeVariableName(typeVarName, bounds = typeVarBounds, variance = typeVarVariance)
}
/**
* Returns a [TypeName] representation of this [KSTypeArgument].
*
* @see toTypeParameterResolver
* @param typeParamResolver an optional resolver for enclosing declarations' type parameters. Parent
* declarations can be anything with generics that child nodes declare as
* defined by [KSType.arguments].
*/
public fun KSTypeArgument.toTypeName(
typeParamResolver: TypeParameterResolver = TypeParameterResolver.EMPTY,
): TypeName {
val type = this.type ?: return STAR
return when (variance) {
COVARIANT -> WildcardTypeName.producerOf(type.toTypeName(typeParamResolver))
CONTRAVARIANT -> WildcardTypeName.consumerOf(type.toTypeName(typeParamResolver))
Variance.STAR -> STAR
INVARIANT -> type.toTypeName(typeParamResolver)
}
}
/**
* Returns a [TypeName] representation of this [KSTypeReference].
*
* @see toTypeParameterResolver
* @param typeParamResolver an optional resolver for enclosing declarations' type parameters. Parent
* declarations can be anything with generics that child nodes declare as
* defined by [KSType.arguments].
*/
public fun KSTypeReference.toTypeName(
typeParamResolver: TypeParameterResolver = TypeParameterResolver.EMPTY,
): TypeName {
return resolve().toTypeName(typeParamResolver, element?.typeArguments.orEmpty())
}
| apache-2.0 | d8612b5dc77d64f06c0ffd1e47a9d65b | 37.3 | 105 | 0.728734 | 4.728395 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/GitLogParser/src/test/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/input/metrics/NumberOfAuthorsTest.kt | 1 | 1535 | package de.maibornwolff.codecharta.importer.gitlogparser.input.metrics
import de.maibornwolff.codecharta.importer.gitlogparser.input.Commit
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.time.OffsetDateTime
class NumberOfAuthorsTest {
@Test
fun should_have_initial_value_zero() {
// when
val metric = NumberOfAuthors()
// then
assertThat(metric.value()).isEqualTo(0)
}
@Test
fun should_increase_by_first_author() {
// given
val metric = NumberOfAuthors()
// when
metric.registerCommit(Commit("An author", emptyList(), OffsetDateTime.now()))
// then
assertThat(metric.value()).isEqualTo(1)
}
@Test
fun should_increase_only_once_for_an_author() {
// given
val metric = NumberOfAuthors()
// when
val author = "An author"
metric.registerCommit(Commit(author, emptyList(), OffsetDateTime.now()))
metric.registerCommit(Commit(author, emptyList(), OffsetDateTime.now()))
// then
assertThat(metric.value()).isEqualTo(1)
}
@Test
fun should_increase_for_different_author() {
// given
val metric = NumberOfAuthors()
// when
metric.registerCommit(Commit("An author", emptyList(), OffsetDateTime.now()))
metric.registerCommit(Commit("Another author", emptyList(), OffsetDateTime.now()))
// then
assertThat(metric.value()).isEqualTo(2)
}
}
| bsd-3-clause | a8c625fde69d74c8912374a93255b7f1 | 26.410714 | 90 | 0.637134 | 4.475219 | false | true | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/discord/webhook/WebhookSendJsonExecutor.kt | 1 | 1540 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.discord.webhook
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.discord.declarations.WebhookCommand
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions
class WebhookSendJsonExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) {
inner class Options : LocalizedApplicationCommandOptions(loritta) {
val webhookUrl = string("webhook_url", WebhookCommand.I18N_PREFIX.Options.WebhookUrl.Text)
val json = string("json", WebhookCommand.I18N_PREFIX.Options.Json.Text)
}
override val options = Options()
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
context.deferChannelMessageEphemerally() // Defer the message ephemerally because we don't want users looking at the webhook URL
val webhookUrl = args[options.webhookUrl]
val message = args[options.json]
WebhookCommandUtils.sendMessageViaWebhook(context, webhookUrl) {
WebhookCommandUtils.decodeRequestFromString(context, message)
}
}
} | agpl-3.0 | a9379ee6d9166cb5679880f7166d0c05 | 52.137931 | 136 | 0.808442 | 5.133333 | false | false | false | false |
emrekose26/RecordButton | recordbuttonlib/src/main/java/com/emrekose/recordbutton/RecordButton.kt | 1 | 8828 | package com.emrekose.recordbutton
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.drawable.Animatable
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.animation.LinearInterpolator
/**
* Created by emrekose on 18.10.2017.
*/
class RecordButton : View, Animatable {
/**
* values to draw
*/
private var buttonPaint: Paint? = null
private var progressEmptyPaint: Paint? = null
private var progressPaint: Paint? = null
private var rectF: RectF? = null
/**
* Bitmap for record icon
*/
private var bitmap: Bitmap? = null
/**
* record button radius
*/
var buttonRadius: Float = 0.toFloat()
private set
/**
* progress ring stroke
*/
var progressStroke: Int = 0
/**
* spacing for button and progress ring
*/
var buttonGap: Float = 0.toFloat()
private set
/**
* record button fill color
*/
var buttonColor: Int = 0
/**
* progress ring background color
*/
var progressEmptyColor: Int = 0
/**
* progress ring arc color
*/
var progressColor: Int = 0
/**
* record icon res id
*/
var recordIcon: Int = 0
private var isRecording = false
private var currentMilliSecond = 0
private var maxMilliSecond = 0
/**
* progress starting degress for arc
*/
private val startAngle = 270
/**
* progress sweep angle degress for arc
*/
private var sweepAngle: Int = 0
/**
* Listener that notify on record and record finish
*/
private var recordListener: OnRecordListener? = null
constructor(context: Context) : super(context) {
init(context, null)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(context, attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(context, attrs)
}
@SuppressLint("NewApi")
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
init(context, attrs)
}
/**
* Initialize view
* @param context
* @param attrs
*/
private fun init(context: Context, attrs: AttributeSet?) {
val resource = context.obtainStyledAttributes(attrs, R.styleable.RecordButton)
buttonRadius = resource.getDimension(R.styleable.RecordButton_buttonRadius, resources.displayMetrics.scaledDensity * 40f)
progressStroke = resource.getInt(R.styleable.RecordButton_progressStroke, 10)
buttonGap = resource.getDimension(R.styleable.RecordButton_buttonGap, resources.displayMetrics.scaledDensity * 8f)
buttonColor = resource.getColor(R.styleable.RecordButton_buttonColor, Color.RED)
progressEmptyColor = resource.getColor(R.styleable.RecordButton_progressEmptyColor, Color.LTGRAY)
progressColor = resource.getColor(R.styleable.RecordButton_progressColor, Color.BLUE)
recordIcon = resource.getResourceId(R.styleable.RecordButton_recordIcon, -1)
maxMilliSecond = resource.getInt(R.styleable.RecordButton_maxMilisecond, 5000)
resource.recycle()
buttonPaint = Paint(Paint.ANTI_ALIAS_FLAG)
buttonPaint?.color = buttonColor
buttonPaint?.style = Paint.Style.FILL
progressEmptyPaint = Paint(Paint.ANTI_ALIAS_FLAG)
progressEmptyPaint?.color = progressEmptyColor
progressEmptyPaint?.style = Paint.Style.STROKE
progressEmptyPaint?.strokeWidth = progressStroke.toFloat()
progressPaint = Paint(Paint.ANTI_ALIAS_FLAG)
progressPaint?.color = progressColor
progressPaint?.style = Paint.Style.STROKE
progressPaint?.strokeWidth = progressStroke.toFloat()
progressPaint?.strokeCap = Paint.Cap.ROUND
rectF = RectF()
bitmap = BitmapFactory.decodeResource(context.resources, recordIcon)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val cx = width / 2
val cy = height / 2
canvas.drawCircle(cx.toFloat(), cy.toFloat(), buttonRadius, buttonPaint!!)
canvas.drawCircle(cx.toFloat(), cy.toFloat(), buttonRadius + buttonGap, progressEmptyPaint!!)
if (recordIcon != -1) {
canvas.drawBitmap(bitmap!!, (cx - bitmap!!.height / 2).toFloat(), (cy - bitmap!!.width / 2).toFloat(), null)
}
sweepAngle = 360 * currentMilliSecond / maxMilliSecond
rectF?.set(cx.toFloat() - buttonRadius - buttonGap, cy.toFloat() - buttonRadius - buttonGap, cx.toFloat() + buttonRadius + buttonGap, cy.toFloat() + buttonRadius + buttonGap)
canvas.drawArc(rectF, startAngle.toFloat(), sweepAngle.toFloat(), false, progressPaint!!)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val size = buttonRadius.toInt() * 2 + buttonGap.toInt() * 2 + progressStroke + 30
val widthMode = View.MeasureSpec.getMode(widthMeasureSpec)
val widthSize = View.MeasureSpec.getSize(widthMeasureSpec)
val heightMode = View.MeasureSpec.getMode(heightMeasureSpec)
val heightSize = View.MeasureSpec.getSize(heightMeasureSpec)
val width: Int
val height: Int
width = when (widthMode) {
View.MeasureSpec.EXACTLY -> widthSize
View.MeasureSpec.AT_MOST -> Math.min(size, widthSize)
View.MeasureSpec.UNSPECIFIED -> size
else -> size
}
height = when (heightMode) {
View.MeasureSpec.EXACTLY -> heightSize
View.MeasureSpec.AT_MOST -> Math.min(size, heightSize)
View.MeasureSpec.UNSPECIFIED -> size
else -> size
}
setMeasuredDimension(width, height)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
start()
progressAnimate().start()
return true
}
MotionEvent.ACTION_UP -> {
stop()
return true
}
}
return false
}
/**
* record button scale animation starting
*/
override fun start() {
isRecording = true
scaleAnimation(1.1f, 1.1f)
}
/**
* record button scale animation stopping
*/
override fun stop() {
isRecording = false
currentMilliSecond = 0
scaleAnimation(1f, 1f)
}
override fun isRunning(): Boolean {
return isRecording
}
/**
* This method provides scale animation to view
* between scaleX and scale Y values
* @param scaleX
* @param scaleY
*/
private fun scaleAnimation(scaleX: Float, scaleY: Float) {
this.animate().scaleX(scaleX).scaleY(scaleY).start()
}
/**
* Progress starting animation
* @return progress animate
*/
@SuppressLint("ObjectAnimatorBinding")
private fun progressAnimate(): ObjectAnimator {
val animator = ObjectAnimator.ofInt(this, "progress", currentMilliSecond, maxMilliSecond)
animator.addUpdateListener { animation ->
val value = (animation.animatedValue as Float).toInt()
if (isRecording) {
setCurrentMilliSecond(value)
if (recordListener != null) recordListener?.onRecord()
} else {
animation.cancel()
isRecording = false
if (recordListener != null) recordListener?.onRecordCancel()
}
if (value == maxMilliSecond) {
if (recordListener != null) recordListener?.onRecordFinish()
stop()
}
}
animator.interpolator = LinearInterpolator()
animator.duration = maxMilliSecond.toLong()
return animator
}
private fun setCurrentMilliSecond(currentMilliSecond: Int) {
this.currentMilliSecond = currentMilliSecond
postInvalidate()
}
fun getCurrentMiliSecond(): Int {
return currentMilliSecond
}
fun setButtonRadius(buttonRadius: Int) {
this.buttonRadius = buttonRadius.toFloat()
}
fun setButtonGap(buttonGap: Int) {
this.buttonGap = buttonGap.toFloat()
}
fun setRecordListener(recordListener: OnRecordListener) {
this.recordListener = recordListener
}
}
| apache-2.0 | 175cf54fffbf878c5036085023e2eff5 | 29.027211 | 182 | 0.639103 | 4.70325 | false | false | false | false |
luiqn2007/miaowo | app/src/main/java/org/miaowo/miaowo/handler/WelcomeHandler.kt | 1 | 12401 | package org.miaowo.miaowo.handler
import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Intent
import android.view.View
import com.blankj.utilcode.util.KeyboardUtils
import com.sdsmdg.tastytoast.TastyToast
import okhttp3.ResponseBody
import org.json.JSONObject
import org.miaowo.miaowo.API
import org.miaowo.miaowo.R
import org.miaowo.miaowo.activity.MainActivity
import org.miaowo.miaowo.activity.WelcomeActivity
import org.miaowo.miaowo.base.extra.toast
import org.miaowo.miaowo.data.bean.Index
import org.miaowo.miaowo.data.bean.SearchResult
import org.miaowo.miaowo.data.bean.User
import org.miaowo.miaowo.other.BaseHttpCallback
import org.miaowo.miaowo.other.Const
import org.miaowo.miaowo.other.template.EmptyAnimatorListener
import org.miaowo.miaowo.ui.processView.ProcessButton
import retrofit2.Call
import retrofit2.Response
class WelcomeHandler(activity: WelcomeActivity) {
private val mButtonAlphaBegins = mutableMapOf<Int, Float>()
private val mButtonEnableTargets = mutableMapOf<Int, Boolean>()
private val mButtonEnableAnimator = ValueAnimator.ofFloat(0f, 1f)
private val mActivity = activity
var inputPwd = ""
var inputName = ""
var inputEmail = ""
var loginUid: Int? = null
// 登录注册等功能
fun login() {
val processView = mActivity.findViewById<ProcessButton>(R.id.login)
KeyboardUtils.hideSoftInput(mActivity)
val stepIndex = object : BaseHttpCallback<Index>() {
override fun onSucceed(call: Call<Index>?, response: Response<Index>) {
setInputEnable(true)
processView.setProcess(100f, mActivity.getString(R.string.process_login_over, API.user.username), false)
MainActivity.CATEGORY_LIST = response.body()?.categories
mActivity.startActivity(Intent(mActivity.applicationContext, MainActivity::class.java))
mActivity.finish()
}
override fun onFailure(call: Call<Index>?, t: Throwable?, errMsg: Any?) {
val error = when(errMsg) {
is String -> errMsg
is JSONObject -> errMsg.getString("message") ?: errMsg.getString("code")
else -> {
t?.printStackTrace()
t?.message
}
}
setInputEnable(true)
processView.setProcess(100f, error, true)
}
}
val stepUser = object : BaseHttpCallback<User>() {
override fun onSucceed(call: Call<User>?, response: Response<User>) {
val user = response.body()
if (user != null) {
API.user = user
API.Docs.index().enqueue(stepIndex)
}
processView.setProcess(80f, mActivity.getString(R.string.process_category), false)
}
override fun onFailure(call: Call<User>?, t: Throwable?, errMsg: Any?) {
val error = when(errMsg) {
is String -> errMsg
is JSONObject -> errMsg.getString("message") ?: errMsg.getString("code")
else -> {
t?.printStackTrace()
t?.message
}
}
setInputEnable(true)
processView.setProcess(60f, error, true)
}
}
val stepToken = object : BaseHttpCallback<ResponseBody>() {
override fun onSucceed(call: Call<ResponseBody>?, response: Response<ResponseBody>) {
val obj = JSONObject(response.body()?.string())
if (obj.getString("code").toUpperCase() == Const.RET_OK) {
val newToken = obj.getJSONObject("payload").getString("token")
API.token.clear()
API.token.add(newToken)
API.Docs.user(inputName.replace(" ", "-")).enqueue(stepUser)
} else {
processView.setProcess(40f, "无法获取 Token", true)
}
processView.setProcess(60f, mActivity.getString(R.string.process_user), false)
}
override fun onFailure(call: Call<ResponseBody>?, t: Throwable?, errMsg: Any?) {
val error = when(errMsg) {
is String -> errMsg
is JSONObject -> errMsg.getString("message") ?: errMsg.getString("code")
else -> {
t?.printStackTrace()
t?.message
}
}
setInputEnable(true)
processView.setProcess(40f, error, true)
}
}
val stepSearch = object : BaseHttpCallback<SearchResult>() {
override fun onSucceed(call: Call<SearchResult>?, response: Response<SearchResult>) {
if (response.body()?.matchCount ?: -1 <= 0) {
processView.setProcess(0f, "无此用户", true)
setInputEnable(true)
} else {
val uid = response.body()?.users?.firstOrNull()?.uid ?: -1
API.Users.tokenCreate(inputPwd, uid).enqueue(stepToken)
}
processView.setProcess(40f, mActivity.getString(R.string.process_get_token), false)
}
override fun onFailure(call: Call<SearchResult>?, t: Throwable?, errMsg: Any?) {
val error = when(errMsg) {
is String -> errMsg
is JSONObject -> errMsg.getString("message") ?: errMsg.getString("code")
else -> {
t?.printStackTrace()
t?.message
}
}
setInputEnable(true)
processView.setProcess(20f, error, true)
}
}
val uid = loginUid
loginUid = null
if (uid == null) {
processView.setProcess(20f, "搜索用户", false)
API.Docs.searchUserMaster(inputName).enqueue(stepSearch)
setInputEnable(false)
} else {
API.Users.tokenCreate(inputPwd, uid).enqueue(stepToken)
}
}
fun register() {
val processView = mActivity.findViewById<ProcessButton>(R.id.register)
KeyboardUtils.hideSoftInput(mActivity)
processView.setProcess(0f, mActivity.getString(R.string.process_reg), false)
API.Users.create(inputName, inputPwd, inputEmail).enqueue(object : BaseHttpCallback<ResponseBody>() {
override fun onSucceed(call: Call<ResponseBody>?, response: Response<ResponseBody>) {
val obj = JSONObject(response.body()?.string())
if (obj.getString("code").toUpperCase() == Const.RET_OK) {
loginUid = obj.getJSONObject("payload").getInt("uid")
login()
processView.setProcess(100f, mActivity.getString(R.string.process_reg_over), false)
} else {
processView.setProcess(100f, obj.getString("code"), true)
}
}
override fun onFailure(call: Call<ResponseBody>?, t: Throwable?, errMsg: Any?) {
val error = when(errMsg) {
is String -> errMsg
is JSONObject -> errMsg.getString("message") ?: errMsg.getString("code")
else -> {
t?.printStackTrace()
t?.message
}
}
processView.setProcess(100f, error, true)
}
})
}
fun forget() {
val processView = mActivity.findViewById<ProcessButton>(R.id.forget)
KeyboardUtils.hideSoftInput(mActivity)
API.Users.password(API.user.password, inputPwd).enqueue(object : BaseHttpCallback<ResponseBody>() {
override fun onFailure(call: Call<ResponseBody>?, t: Throwable?, errMsg: Any?) {
val error = when(errMsg) {
is String -> errMsg
is JSONObject -> errMsg.getString("message")
else -> {
t?.printStackTrace()
t?.message
}
}
processView.setProcess(100f, error, true)
}
override fun onSucceed(call: Call<ResponseBody>?, response: Response<ResponseBody>) {
val msg = response.body()?.string()
if (msg == null) {
processView.setProcess(100f, mActivity.getString(R.string.err_ill), true)
} else {
if (msg.startsWith("[[") && msg.endsWith("]]")) {
processView.setProcess(100f, msg.substring(2, msg.length - 2), true)
} else {
val obj = JSONObject(msg)
if (obj.getString("code").toUpperCase() == Const.RET_OK) {
processView.setProcess(100f, mActivity.getString(R.string.pwd_reset_success), false)
} else {
processView.setProcess(100f, obj.getString("code"), true)
}
}
}
}
})
}
fun github() {
val processView = mActivity.findViewById<ProcessButton>(R.id.github)
KeyboardUtils.hideSoftInput(mActivity)
mActivity.toast("暂未实现", TastyToast.ERROR)
}
private fun setInputEnable(isEnable: Boolean) {
mActivity.findViewById<View>(R.id.user).isEnabled = isEnable
mActivity.findViewById<View>(R.id.pwd).isEnabled = isEnable
mActivity.findViewById<View>(R.id.email).isEnabled = isEnable
mActivity.findViewById<View>(R.id.save).isEnabled = isEnable
}
// 动画相关
fun initAnimator() {
mButtonEnableAnimator.addUpdateListener {
mButtonEnableTargets.forEach { kv ->
val id = kv.key
val target = kv.value
val btn = mActivity.findViewById<View>(id)!!
if (!mButtonAlphaBegins.containsKey(id))
mButtonAlphaBegins[id] = btn.alpha
val alpha = mButtonAlphaBegins[id]!!
if (target) {
btn.alpha = alpha + (1f - alpha) * (it.animatedValue as Float)
} else {
btn.alpha = alpha - (alpha - 0.3f) * (it.animatedValue as Float)
}
}
}
mButtonEnableAnimator.addListener(object : EmptyAnimatorListener() {
override fun onAnimationEnd(animation: Animator?) {
mButtonAlphaBegins.clear()
}
})
mButtonEnableAnimator.duration = 300
}
fun playButtonAnimator() {
mActivity.findViewById<ProcessButton>(R.id.login).hideProcess()
mActivity.findViewById<ProcessButton>(R.id.forget).hideProcess()
mActivity.findViewById<ProcessButton>(R.id.github).hideProcess()
mActivity.findViewById<ProcessButton>(R.id.register).hideProcess()
if (inputName.isNotBlank() && inputPwd.isNotBlank()) {
// +login, +github
mButtonEnableTargets[R.id.login] = true
mButtonEnableTargets[R.id.github] = true
if (inputEmail.isNotBlank()) {
// +register, +forget
mButtonEnableTargets[R.id.forget] = true
mButtonEnableTargets[R.id.register] = true
} else {
// -register, -forget
mButtonEnableTargets[R.id.forget] = false
mButtonEnableTargets[R.id.register] = false
}
} else {
// -login, -register, -github
mButtonEnableTargets[R.id.login] = false
mButtonEnableTargets[R.id.github] = false
mButtonEnableTargets[R.id.forget] = inputEmail.isNotBlank()
mButtonEnableTargets[R.id.register] = false
}
mButtonEnableTargets.forEach {
mActivity.findViewById<View>(it.key).isEnabled = it.value
}
if (mButtonEnableAnimator.isRunning)
mButtonEnableAnimator.cancel()
mButtonEnableAnimator.start()
}
} | apache-2.0 | bfd2230969fb7d650ba61ab347dbc228 | 42.787234 | 120 | 0.551632 | 4.796814 | false | false | false | false |
AlmasB/GroupNet | src/main/kotlin/icurves/diagram/EulerDiagram.kt | 1 | 5280 | package icurves.diagram
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
import icurves.description.*
import icurves.diagram.curve.CircleCurve
import icurves.util.Bug
import icurves.util.Log
import icurves.util.Logable
import javafx.geometry.Point2D
import javafx.geometry.Rectangle2D
import java.util.*
/**
* An Euler diagram, d = (C, l).
*
* @author Almas Baimagambetov ([email protected])
*/
@JsonIgnoreProperties("zones", "shadedZones", "outsideZone")
class EulerDiagram(val originalDescription: Description,
val actualDescription: Description,
@JsonProperty("curves") curvesInternal: Set<Curve>) : Logable {
//val curves: SortedSet<Curve> = Collections.unmodifiableSortedSet(curvesInternal.toSortedSet())
val curves = Collections.unmodifiableSet(curvesInternal)
/**
* All zones of this Euler diagram, including shaded zones.
* Does not include the outside zone.
*/
val zones = actualDescription.abstractZones.minus(azEmpty).map { Zone(it, curves) }.toSet()
val shadedZones = zones.filter { !originalDescription.includesZone(it.abstractZone) }
val outsideZone = Zone(azEmpty, curves)
fun numCircles() = curves.count { it is CircleCurve }
fun copyWithNewLabels(map: Map<String, String>): EulerDiagram {
return EulerDiagram(
originalDescription.copyWithNewLabels(map),
actualDescription.copyWithNewLabels(map),
curves.map { it.copyWithNewLabel(map[it.label]!!) }.toSet()
)
}
fun embedIntoZone(az: AbstractZone, diagram: EulerDiagram): EulerDiagram {
Log.d("Embedding into $az", diagram)
val zone = zones.find { it.abstractZone == az } ?: throw Bug("No zone $az found in $diagram")
val minRadius = zone.shortestDistanceToOtherZone(zone.center)
val bbox = diagram.bbox()
val diagramCenter = Point2D(bbox.minX + bbox.maxX / 2, bbox.minY + bbox.maxY / 2)
val actualRadius = maxOf(bbox.width, bbox.height)
val scaleRatio = minRadius / actualRadius
val scaledCurves = diagram.curves.map { it.scale(scaleRatio, diagramCenter) }
val newCurves = curves.plus(scaledCurves.map { it.translate(zone.center.subtract(diagramCenter)) })
return EulerDiagram(originalDescription + diagram.originalDescription, actualDescription + diagram.actualDescription, newCurves)
}
fun bbox(): Rectangle2D {
val polygons = curves.map { it.getPolygon() }
val vertices = polygons.flatMap { it.vertices() }
val minX = vertices.minBy { it.x() }!!.x()
val minY = vertices.minBy { it.y() }!!.y()
val maxX = vertices.maxBy { it.x() }!!.x()
val maxY = vertices.maxBy { it.y() }!!.y()
return Rectangle2D(minX, minY, maxX - minX, maxY - minY)
}
fun size(): Double {
val bbox = bbox()
return maxOf(bbox.width, bbox.height)
}
fun center(): Point2D {
val bbox = bbox()
return Point2D(bbox.minX + bbox.maxX / 2, bbox.minY + bbox.maxY / 2)
}
fun translate(vector: Point2D): EulerDiagram {
return EulerDiagram(originalDescription, actualDescription, curves.map { it.translate(vector) }.toSet())
}
fun scale(pivot: Point2D, ratio: Double): EulerDiagram {
return EulerDiagram(originalDescription, actualDescription, curves.map { it.scale(ratio, pivot) }.toSet())
}
override fun toLog(): String {
return "ED[o=$originalDescription, actual=$actualDescription, curves=$curves, zones=$zones]"
}
override fun hashCode(): Int {
return Objects.hash(originalDescription, actualDescription, curves, zones, shadedZones, outsideZone)
}
override fun equals(other: Any?): Boolean {
if (other !is EulerDiagram)
return false
return originalDescription == other.originalDescription &&
actualDescription == other.actualDescription &&
curves == other.curves &&
zones == other.zones &&
shadedZones == other.shadedZones &&
outsideZone == other.outsideZone
}
override fun toString(): String {
return "EulerDiagram[D=$actualDescription]"
}
}
// Logic DSL
fun C(d: EulerDiagram) = d.curves
fun Z(d: EulerDiagram) = d.zones
fun combine(original: Description, diagrams: List<EulerDiagram>): EulerDiagram {
val actual = diagrams.map { it.actualDescription.getInformalDescription() }.joinToString(" ")
println(actual)
println(original)
var index = 0
return EulerDiagram(original, D(actual), diagrams.flatMap {
val translate = Point2D((index % 3) * 7000.0, (index++ / 3) * 7000.0)
it.curves.map { it.translate(translate) }
}.toSet())
}
fun combineNoTranslate(original: Description, diagrams: List<EulerDiagram>): EulerDiagram {
val actual = diagrams.map { it.actualDescription.getInformalDescription() }.joinToString(" ")
println(actual)
println(original)
var index = 0
return EulerDiagram(original, D(actual), diagrams.flatMap {
val translate = Point2D.ZERO
it.curves.map { it.translate(translate) }
}.toSet())
} | apache-2.0 | 209f681e8a0d360e51705c98e69d8e21 | 32.636943 | 136 | 0.663636 | 4.115355 | false | false | false | false |
eugeis/ee | ee-lang/src/main/kotlin/ee/lang/gen/kt/LangKotlinContextFactory.kt | 1 | 1501 | package ee.lang.gen.kt
import ee.lang.*
import ee.lang.ContextBuilder
import ee.lang.gen.KotlinContext
import ee.lang.gen.KotlinContextBuilder
import ee.lang.gen.common.LangCommonContextFactory
open class LangKotlinContextFactory(targetAsSingleModule: Boolean) : LangCommonContextFactory(targetAsSingleModule) {
open fun buildForImplOnly(scope: String = "main"): ContextBuilder<StructureUnitI<*>> {
val controller = DerivedController()
controller.registerKinds(listOf(LangDerivedKind.API, LangDerivedKind.IMPL), { name() }, isNotPartOfNativeTypes)
return contextBuilder(controller, scope)
}
open fun buildForDslBuilder(scope: String = "main"): ContextBuilder<StructureUnitI<*>> {
val controller = DerivedController()
controller.registerKind(LangDerivedKind.API, { "${name()}I" }, isNotPartOfNativeTypes)
controller.registerKind(LangDerivedKind.IMPL, { name() }, isNotPartOfNativeTypes)
controller.registerKind(LangDerivedKind.MANUAL, { "${name()}B" }, isNotPartOfNativeTypes)
return contextBuilder(controller, scope)
}
protected open fun contextBuilder(controller: DerivedController, scope: String): ContextBuilder<StructureUnitI<*>> {
return KotlinContextBuilder(CONTEXT_COMMON, scope, macroController) {
KotlinContext(namespace().toLowerCase(), artifact(), "src-gen/$scope/kotlin",
derivedController = controller, macroController = macroController)
}
}
} | apache-2.0 | 489205cbaae696a434bdc04a889a0669 | 41.914286 | 120 | 0.731512 | 4.521084 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/items/list/ItemListActivity.kt | 2 | 7968 | package com.lasthopesoftware.bluewater.client.browsing.items.list
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.Handler
import android.view.Menu
import android.view.MenuItem
import android.widget.ProgressBar
import android.widget.ViewAnimator
import androidx.appcompat.app.AppCompatActivity
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lasthopesoftware.bluewater.R
import com.lasthopesoftware.bluewater.client.browsing.items.access.CachedItemProvider
import com.lasthopesoftware.bluewater.client.browsing.items.list.menus.changes.handlers.ItemListMenuChangeHandler
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.parameters.FileListParameters
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.stringlist.FileStringListProvider
import com.lasthopesoftware.bluewater.client.browsing.items.menu.LongClickViewAnimatorListener
import com.lasthopesoftware.bluewater.client.browsing.items.menu.MenuNotifications
import com.lasthopesoftware.bluewater.client.browsing.library.access.session.SelectedBrowserLibraryIdentifierProvider
import com.lasthopesoftware.bluewater.client.connection.HandleViewIoException
import com.lasthopesoftware.bluewater.client.connection.selected.InstantiateSelectedConnectionActivity.Companion.restoreSelectedConnection
import com.lasthopesoftware.bluewater.client.connection.selected.SelectedConnectionProvider
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.NowPlayingFloatingActionButton
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.NowPlayingFloatingActionButton.Companion.addNowPlayingFloatingActionButton
import com.lasthopesoftware.bluewater.client.stored.library.items.StoredItemAccess
import com.lasthopesoftware.bluewater.settings.repository.access.CachingApplicationSettingsRepository.Companion.getApplicationSettingsRepository
import com.lasthopesoftware.bluewater.shared.MagicPropertyBuilder
import com.lasthopesoftware.bluewater.shared.android.messages.MessageBus
import com.lasthopesoftware.bluewater.shared.android.view.LazyViewFinder
import com.lasthopesoftware.bluewater.shared.android.view.ViewUtils
import com.lasthopesoftware.bluewater.shared.exceptions.UnexpectedExceptionToasterResponse
import com.lasthopesoftware.bluewater.shared.promises.extensions.LoopedInPromise.Companion.response
import com.lasthopesoftware.bluewater.shared.promises.extensions.keepPromise
import com.namehillsoftware.handoff.promises.Promise
class ItemListActivity : AppCompatActivity(), IItemListViewContainer {
private var connectionRestoreCode: Int? = null
private val handler by lazy { Handler(mainLooper) }
private val itemListView by lazy {
val recyclerView = findViewById<RecyclerView>(R.id.loadedRecyclerView)
promisedItemListAdapter.eventually(response({ adapter ->
recyclerView.adapter = adapter
val layoutManager = LinearLayoutManager(this)
recyclerView.layoutManager = layoutManager
recyclerView.addItemDecoration(DividerItemDecoration(this, layoutManager.orientation))
}, handler))
recyclerView
}
private val pbLoading = LazyViewFinder<ProgressBar>(this, R.id.recyclerLoadingProgress)
private val browserLibraryIdProvider by lazy { SelectedBrowserLibraryIdentifierProvider(getApplicationSettingsRepository()) }
private val lazyFileStringListProvider by lazy { FileStringListProvider(SelectedConnectionProvider(this)) }
private val itemProvider by lazy { CachedItemProvider.getInstance(this) }
private val messageBus by lazy { MessageBus(LocalBroadcastManager.getInstance(this)) }
private val promisedItemListAdapter: Promise<ItemListAdapter?> by lazy {
browserLibraryIdProvider.selectedLibraryId
.then {
it?.let { l ->
val storedItemAccess = StoredItemAccess(this)
ItemListAdapter(
this,
messageBus,
FileListParameters.getInstance(),
lazyFileStringListProvider,
ItemListMenuChangeHandler(this),
storedItemAccess,
itemProvider,
l
)
}
}
}
private lateinit var nowPlayingFloatingActionButton: NowPlayingFloatingActionButton
private var viewAnimator: ViewAnimator? = null
private var itemId = 0
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_list_view)
setSupportActionBar(findViewById(R.id.listViewToolbar))
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val intentFilter = IntentFilter()
intentFilter.addAction(MenuNotifications.launchingActivity)
intentFilter.addAction(MenuNotifications.launchingActivityHalted)
messageBus.registerReceiver(
object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val isLaunching = intent?.action == MenuNotifications.launchingActivity
itemListView.visibility = ViewUtils.getVisibility(!isLaunching)
pbLoading.findView().visibility = ViewUtils.getVisibility(isLaunching)
}
},
intentFilter
)
itemId = savedInstanceState?.getInt(KEY) ?: intent.getIntExtra(KEY, 0)
title = intent.getStringExtra(VALUE)
nowPlayingFloatingActionButton = addNowPlayingFloatingActionButton(findViewById(R.id.asynchronousRecyclerViewContainer))
}
public override fun onStart() {
super.onStart()
restoreSelectedConnection(this).eventually(response({
connectionRestoreCode = it
if (it == null) hydrateItems()
}, handler))
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == connectionRestoreCode) hydrateItems()
super.onActivityResult(requestCode, resultCode, data)
}
private fun hydrateItems() {
itemListView.visibility = ViewUtils.getVisibility(false)
pbLoading.findView().visibility = ViewUtils.getVisibility(true)
browserLibraryIdProvider.selectedLibraryId
.eventually { l ->
l?.let { itemProvider.promiseItems(l, itemId) }.keepPromise(emptyList())
}
.eventually { items ->
promisedItemListAdapter.eventually { adapter ->
adapter?.updateListEventually(items).keepPromise(Unit)
}
}
.eventually(response({
itemListView.visibility = ViewUtils.getVisibility(true)
pbLoading.findView().visibility = ViewUtils.getVisibility(false)
}, handler))
.excuse(HandleViewIoException(this, ::hydrateItems))
.eventuallyExcuse(response(UnexpectedExceptionToasterResponse(this), handler))
.then { finish() }
}
public override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
savedInstanceState.putInt(KEY, itemId)
}
public override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
itemId = savedInstanceState.getInt(KEY)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean = ViewUtils.buildStandardMenu(this, menu)
override fun onOptionsItemSelected(item: MenuItem): Boolean =
ViewUtils.handleNavMenuClicks(this, item) || super.onOptionsItemSelected(item)
override fun onBackPressed() {
if (LongClickViewAnimatorListener.tryFlipToPreviousView(viewAnimator)) return
super.onBackPressed()
}
override fun updateViewAnimator(viewAnimator: ViewAnimator) {
this.viewAnimator = viewAnimator
}
override fun getNowPlayingFloatingActionButton(): NowPlayingFloatingActionButton = nowPlayingFloatingActionButton
override fun onDestroy() {
messageBus.clear()
super.onDestroy()
}
companion object {
private val magicPropertyBuilder = MagicPropertyBuilder(ItemListActivity::class.java)
@JvmField
val KEY = magicPropertyBuilder.buildProperty("key")
@JvmField
val VALUE = magicPropertyBuilder.buildProperty("value")
}
}
| lgpl-3.0 | d1bcd9b639672ffc1680c347371c97e2 | 41.15873 | 144 | 0.821787 | 4.678802 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/playback/file/exoplayer/progress/ExoPlayerFileProgressReader.kt | 2 | 1203 | package com.lasthopesoftware.bluewater.client.playback.file.exoplayer.progress
import com.lasthopesoftware.bluewater.client.playback.exoplayer.PromisingExoPlayer
import com.lasthopesoftware.bluewater.client.playback.file.progress.ReadFileProgress
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import com.namehillsoftware.handoff.promises.Promise
import org.joda.time.Duration
class ExoPlayerFileProgressReader(private val exoPlayer: PromisingExoPlayer) : ReadFileProgress {
private var currentDurationPromise: Promise<Duration> = Promise.empty()
private var fileProgress = Duration.ZERO
@get:Synchronized
override val progress: Promise<Duration>
get() =
currentDurationPromise
.eventually({ promiseProgress() }, { promiseProgress() })
.also { currentDurationPromise = it }
private fun promiseProgress(): Promise<Duration> =
exoPlayer.getPlayWhenReady().eventually { isPlaying ->
if (!isPlaying) fileProgress.toPromise()
else {
exoPlayer.getCurrentPosition().then { currentPosition ->
if (currentPosition != fileProgress.millis)
Duration.millis(currentPosition).also { fileProgress = it }
else fileProgress
}
}
}
}
| lgpl-3.0 | f4afb356428ca50254e2d9251571c268 | 36.59375 | 97 | 0.784705 | 4.390511 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/registry/TileEntities.kt | 2 | 2158 | package com.cout970.magneticraft.registry
import com.cout970.magneticraft.Debug
import com.cout970.magneticraft.MOD_ID
import com.cout970.magneticraft.Magneticraft
import com.cout970.magneticraft.misc.RegisterTileEntity
import com.cout970.magneticraft.misc.info
import com.cout970.magneticraft.misc.logError
import com.cout970.magneticraft.misc.resource
import com.cout970.magneticraft.systems.tileentities.TileBase
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.ResourceLocation
import net.minecraft.util.datafix.FixTypes
import net.minecraft.util.datafix.IFixableData
import net.minecraftforge.fml.common.FMLCommonHandler
import net.minecraftforge.fml.common.registry.GameRegistry
/**
* Created by cout970 on 2017/06/12.
*/
fun initTileEntities() {
val map = mutableMapOf<Class<out TileBase>, String>()
val data = Magneticraft.asmData.getAll(RegisterTileEntity::class.java.canonicalName)
data.forEach {
try {
@Suppress("UNCHECKED_CAST")
val clazz = Class.forName(it.className) as Class<TileBase>
map += clazz to (it.annotationInfo["name"] as String)
if (Debug.DEBUG) {
info("Registering TileEntity: ${clazz.simpleName}")
}
} catch (e: Exception) {
logError("Error auto-registering tileEntity: $it")
e.printStackTrace()
}
}
val datafixer = FMLCommonHandler.instance().dataFixer.init(MOD_ID, 2)
datafixer.registerFix(FixTypes.BLOCK_ENTITY, FixTileEntityId)
map.forEach { clazz, name ->
GameRegistry.registerTileEntity(clazz, resource(name))
}
}
object FixTileEntityId : IFixableData {
override fun getFixVersion(): Int = 2
override fun fixTagCompound(compound: NBTTagCompound): NBTTagCompound {
val oldId = compound.getString("id")
val loc = ResourceLocation(oldId)
if (loc.resourceDomain != MOD_ID && loc.resourcePath.startsWith("${MOD_ID}_")) {
val newId = resource(loc.resourcePath.replaceFirst("${MOD_ID}_", ""))
compound.setString("id", newId.toString())
}
return compound
}
}
| gpl-2.0 | 04eafde29286341d89da4c54f153c106 | 31.208955 | 88 | 0.701112 | 4.182171 | false | false | false | false |
wireapp/wire-android | app/src/main/kotlin/com/waz/zclient/feature/backup/di/BackUpModule.kt | 1 | 14041 | package com.waz.zclient.feature.backup.di
import com.waz.zclient.core.utilities.converters.JsonConverter
import com.waz.zclient.feature.backup.BackUpRepository
import com.waz.zclient.feature.backup.BackUpViewModel
import com.waz.zclient.feature.backup.assets.AssetsBackUpModel
import com.waz.zclient.feature.backup.assets.AssetsBackupDataSource
import com.waz.zclient.feature.backup.assets.AssetsBackupMapper
import com.waz.zclient.feature.backup.buttons.ButtonsBackUpModel
import com.waz.zclient.feature.backup.buttons.ButtonsBackupDataSource
import com.waz.zclient.feature.backup.buttons.ButtonsBackupMapper
import com.waz.zclient.feature.backup.conversations.ConversationFoldersBackUpModel
import com.waz.zclient.feature.backup.conversations.ConversationFoldersBackupDataSource
import com.waz.zclient.feature.backup.conversations.ConversationFoldersBackupMapper
import com.waz.zclient.feature.backup.conversations.ConversationMembersBackUpModel
import com.waz.zclient.feature.backup.conversations.ConversationMembersBackupDataSource
import com.waz.zclient.feature.backup.conversations.ConversationMembersBackupMapper
import com.waz.zclient.feature.backup.conversations.ConversationRoleActionBackUpModel
import com.waz.zclient.feature.backup.conversations.ConversationRoleBackupMapper
import com.waz.zclient.feature.backup.conversations.ConversationRolesBackupDataSource
import com.waz.zclient.feature.backup.conversations.ConversationsBackUpModel
import com.waz.zclient.feature.backup.conversations.ConversationsBackupDataSource
import com.waz.zclient.feature.backup.conversations.ConversationsBackupMapper
import com.waz.zclient.feature.backup.crypto.Crypto
import com.waz.zclient.feature.backup.crypto.CryptoWrapper
import com.waz.zclient.feature.backup.crypto.decryption.DecryptionHandler
import com.waz.zclient.feature.backup.crypto.encryption.EncryptionHandler
import com.waz.zclient.feature.backup.crypto.header.CryptoHeaderMetaData
import com.waz.zclient.feature.backup.crypto.header.EncryptionHeaderMapper
import com.waz.zclient.feature.backup.folders.FoldersBackUpModel
import com.waz.zclient.feature.backup.folders.FoldersBackupDataSource
import com.waz.zclient.feature.backup.folders.FoldersBackupMapper
import com.waz.zclient.feature.backup.io.database.BatchDatabaseIOHandler
import com.waz.zclient.feature.backup.io.file.BackUpFileIOHandler
import com.waz.zclient.feature.backup.keyvalues.KeyValuesBackUpDataSource
import com.waz.zclient.feature.backup.keyvalues.KeyValuesBackUpMapper
import com.waz.zclient.feature.backup.keyvalues.KeyValuesBackUpModel
import com.waz.zclient.feature.backup.messages.LikesBackUpModel
import com.waz.zclient.feature.backup.messages.LikesBackupDataSource
import com.waz.zclient.feature.backup.messages.LikesBackupMapper
import com.waz.zclient.feature.backup.messages.MessagesBackUpDataMapper
import com.waz.zclient.feature.backup.messages.MessagesBackUpDataSource
import com.waz.zclient.feature.backup.messages.MessagesBackUpModel
import com.waz.zclient.feature.backup.metadata.BackupMetaData
import com.waz.zclient.feature.backup.metadata.MetaDataHandler
import com.waz.zclient.feature.backup.properties.PropertiesBackUpDataSource
import com.waz.zclient.feature.backup.properties.PropertiesBackUpMapper
import com.waz.zclient.feature.backup.properties.PropertiesBackUpModel
import com.waz.zclient.feature.backup.receipts.ReadReceiptsBackUpModel
import com.waz.zclient.feature.backup.receipts.ReadReceiptsBackupDataSource
import com.waz.zclient.feature.backup.receipts.ReadReceiptsBackupMapper
import com.waz.zclient.feature.backup.usecase.CreateBackUpUseCase
import com.waz.zclient.feature.backup.usecase.RestoreBackUpUseCase
import com.waz.zclient.feature.backup.users.UsersBackUpDataMapper
import com.waz.zclient.feature.backup.users.UsersBackUpDataSource
import com.waz.zclient.feature.backup.users.UsersBackUpModel
import com.waz.zclient.feature.backup.zip.ZipHandler
import com.waz.zclient.storage.db.UserDatabase
import org.koin.android.ext.koin.androidContext
import org.koin.android.viewmodel.dsl.viewModel
import org.koin.core.module.Module
import org.koin.core.qualifier.named
import org.koin.dsl.bind
import org.koin.dsl.module
private const val METADATA = "Metadata"
private const val KEY_VALUES = "KeyValues"
private const val MESSAGES = "Messages"
private const val FOLDERS = "Folders"
private const val CONVERSATIONS = "Conversations"
private const val CONVERSATION_FOLDERS = "ConversationFolders"
private const val CONVERSATION_ROLE_ACTION = "ConversationRoleAction"
private const val ASSETS = "Assets"
private const val BUTTONS = "Buttons"
private const val CONVERSATION_MEMBERS = "ConversationMembers"
private const val LIKES = "Likes"
private const val PROPERTIES = "Properties"
private const val READ_RECEIPTS = "ReadReceipts"
private const val USERS = "Users"
private const val JSON = "Json"
private const val FILE = "File"
private const val DB = "Db"
private const val MAPPER = "Mapper"
private const val BACKUP_VERSION = 1
val backupModules: List<Module>
get() = listOf(backUpModule)
val backUpModule = module {
single { androidContext().externalCacheDir }
single { ZipHandler(get()) }
single { EncryptionHandler(get(), get()) }
single { DecryptionHandler(get(), get()) }
factory { Crypto(get()) }
factory { CryptoWrapper() }
factory { CryptoHeaderMetaData(get(), get()) }
factory { EncryptionHeaderMapper() }
factory { CreateBackUpUseCase(getAll(), get(), get(), get(), BACKUP_VERSION) } //this resolves all instances of type BackUpRepository
factory { RestoreBackUpUseCase(getAll(), get(), get(), get(), BACKUP_VERSION) }
viewModel { BackUpViewModel(get(), get()) }
// MetaData
factory(named(METADATA + JSON)) { JsonConverter(BackupMetaData.serializer()) }
factory { MetaDataHandler(get(named(METADATA + JSON)), get()) }
// KeyValues
factory(named(KEY_VALUES + JSON)) { JsonConverter(KeyValuesBackUpModel.serializer()) }
factory(named(KEY_VALUES + FILE)) { BackUpFileIOHandler<KeyValuesBackUpModel>(KEY_VALUES, get(named(KEY_VALUES + JSON)), get()) }
factory(named(KEY_VALUES + DB)) { BatchDatabaseIOHandler((get<UserDatabase>()).keyValuesDao()) }
factory(named(KEY_VALUES + MAPPER)) { KeyValuesBackUpMapper() }
factory {
KeyValuesBackUpDataSource(get(named(KEY_VALUES + DB)), get(named(KEY_VALUES + FILE)), get(named(KEY_VALUES + MAPPER)))
} bind BackUpRepository::class
// Folders
factory(named(FOLDERS + JSON)) { JsonConverter(FoldersBackUpModel.serializer()) }
factory(named(FOLDERS + DB)) { BatchDatabaseIOHandler(get<UserDatabase>().foldersDao()) }
factory(named(FOLDERS + FILE)) { BackUpFileIOHandler<FoldersBackUpModel>(FOLDERS, get(named(FOLDERS + JSON)), get()) }
factory(named(FOLDERS + MAPPER)) { FoldersBackupMapper() }
factory {
FoldersBackupDataSource(get(named(FOLDERS + DB)), get(named(FOLDERS + FILE)), get(named(FOLDERS + MAPPER)))
} bind BackUpRepository::class
// Conversation Roles
factory(named(CONVERSATION_ROLE_ACTION + JSON)) { JsonConverter(ConversationRoleActionBackUpModel.serializer()) }
factory(named(CONVERSATION_ROLE_ACTION + DB)) { BatchDatabaseIOHandler(get<UserDatabase>().conversationRoleActionDao()) }
factory(named(CONVERSATION_ROLE_ACTION + FILE)) {
BackUpFileIOHandler<ConversationRoleActionBackUpModel>(CONVERSATION_ROLE_ACTION, get(named(CONVERSATION_ROLE_ACTION + JSON)), get())
}
factory(named(CONVERSATION_ROLE_ACTION + MAPPER)) { ConversationRoleBackupMapper() }
factory {
ConversationRolesBackupDataSource(
get(named(CONVERSATION_ROLE_ACTION + DB)),
get(named(CONVERSATION_ROLE_ACTION + FILE)),
get(named(CONVERSATION_ROLE_ACTION + MAPPER))
)
} bind BackUpRepository::class
// Conversation Folders
factory(named(CONVERSATION_FOLDERS + JSON)) { JsonConverter(ConversationFoldersBackUpModel.serializer()) }
factory(named(CONVERSATION_FOLDERS + DB)) { BatchDatabaseIOHandler(get<UserDatabase>().conversationFoldersDao()) }
factory(named(CONVERSATION_FOLDERS + FILE)) {
BackUpFileIOHandler<ConversationFoldersBackUpModel>(CONVERSATION_FOLDERS, get(named(CONVERSATION_FOLDERS + JSON)), get())
}
factory(named(CONVERSATION_FOLDERS + MAPPER)) { ConversationFoldersBackupMapper() }
factory {
ConversationFoldersBackupDataSource(
get(named(CONVERSATION_FOLDERS + DB)),
get(named(CONVERSATION_FOLDERS + FILE)),
get(named(CONVERSATION_FOLDERS + MAPPER))
)
} bind BackUpRepository::class
// Conversations
factory(named(CONVERSATIONS + JSON)) { JsonConverter(ConversationsBackUpModel.serializer()) }
factory(named(CONVERSATIONS + DB)) { BatchDatabaseIOHandler(get<UserDatabase>().conversationsDao()) }
factory(named(CONVERSATIONS + FILE)) {
BackUpFileIOHandler<ConversationsBackUpModel>(CONVERSATIONS, get(named(CONVERSATIONS + JSON)), get())
}
factory(named(CONVERSATIONS + MAPPER)) { ConversationsBackupMapper() }
factory {
ConversationsBackupDataSource(
get(named(CONVERSATIONS + DB)),
get(named(CONVERSATIONS + FILE)),
get(named(CONVERSATIONS + MAPPER))
)
} bind BackUpRepository::class
// Assets
factory(named(ASSETS + JSON)) { JsonConverter(AssetsBackUpModel.serializer()) }
factory(named(ASSETS + DB)) { BatchDatabaseIOHandler(get<UserDatabase>().assetsDao()) }
factory(named(ASSETS + FILE)) { BackUpFileIOHandler<AssetsBackUpModel>(ASSETS, get(named(ASSETS + JSON)), get()) }
factory(named(ASSETS + MAPPER)) { AssetsBackupMapper() }
factory {
AssetsBackupDataSource(get(named(ASSETS + DB)), get(named(ASSETS + FILE)), get(named(ASSETS + MAPPER)))
} bind BackUpRepository::class
// Messages
factory(named(MESSAGES + JSON)) { JsonConverter(MessagesBackUpModel.serializer()) }
factory(named(MESSAGES + DB)) { BatchDatabaseIOHandler(get<UserDatabase>().messagesDao()) }
factory(named(MESSAGES + FILE)) { BackUpFileIOHandler<MessagesBackUpModel>(MESSAGES, get(named(MESSAGES + JSON)), get()) }
factory(named(MESSAGES + MAPPER)) { MessagesBackUpDataMapper() }
factory {
MessagesBackUpDataSource(get(named(MESSAGES + DB)), get(named(MESSAGES + FILE)), get(named(MESSAGES + MAPPER)))
} bind BackUpRepository::class
// Buttons
factory(named(BUTTONS + JSON)) { JsonConverter(ButtonsBackUpModel.serializer()) }
factory(named(BUTTONS + DB)) { BatchDatabaseIOHandler(get<UserDatabase>().buttonsDao()) }
factory(named(BUTTONS + FILE)) { BackUpFileIOHandler<ButtonsBackUpModel>(BUTTONS, get(named(BUTTONS + JSON)), get()) }
factory(named(BUTTONS + MAPPER)) { ButtonsBackupMapper() }
factory {
ButtonsBackupDataSource(get(named(BUTTONS + DB)), get(named(BUTTONS + FILE)), get(named(BUTTONS + MAPPER)))
} bind BackUpRepository::class
// ConversationMembers
factory(named(CONVERSATION_MEMBERS + JSON)) { JsonConverter(ConversationMembersBackUpModel.serializer()) }
factory(named(CONVERSATION_MEMBERS + DB)) { BatchDatabaseIOHandler(get<UserDatabase>().conversationMembersDao()) }
factory(named(CONVERSATION_MEMBERS + FILE)) {
BackUpFileIOHandler<ConversationMembersBackUpModel>(CONVERSATION_MEMBERS, get(named(CONVERSATION_MEMBERS + JSON)), get())
}
factory(named(CONVERSATION_MEMBERS + MAPPER)) { ConversationMembersBackupMapper() }
factory {
ConversationMembersBackupDataSource(
get(named(CONVERSATION_MEMBERS + DB)),
get(named(CONVERSATION_MEMBERS + FILE)),
get(named(CONVERSATION_MEMBERS + MAPPER))
)
} bind BackUpRepository::class
// Likes
factory(named(LIKES + JSON)) { JsonConverter(LikesBackUpModel.serializer()) }
factory(named(LIKES + DB)) { BatchDatabaseIOHandler(get<UserDatabase>().likesDao()) }
factory(named(LIKES + FILE)) { BackUpFileIOHandler<LikesBackUpModel>(LIKES, get(named(LIKES + JSON)), get()) }
factory(named(LIKES + MAPPER)) { LikesBackupMapper() }
factory {
LikesBackupDataSource(get(named(LIKES + DB)), get(named(LIKES + FILE)), get(named(LIKES + MAPPER)))
} bind BackUpRepository::class
// Properties
factory(named(PROPERTIES + JSON)) { JsonConverter(PropertiesBackUpModel.serializer()) }
factory(named(PROPERTIES + DB)) { BatchDatabaseIOHandler((get<UserDatabase>()).propertiesDao()) }
factory(named(PROPERTIES + FILE)) { BackUpFileIOHandler<PropertiesBackUpModel>(PROPERTIES, get(named(PROPERTIES + JSON)), get()) }
factory(named(PROPERTIES + MAPPER)) { PropertiesBackUpMapper() }
factory {
PropertiesBackUpDataSource(get(named(PROPERTIES + DB)), get(named(PROPERTIES + FILE)), get(named(PROPERTIES + MAPPER)))
} bind BackUpRepository::class
// ReadReceipts
factory(named(READ_RECEIPTS + JSON)) { JsonConverter(ReadReceiptsBackUpModel.serializer()) }
factory(named(READ_RECEIPTS + DB)) { BatchDatabaseIOHandler(get<UserDatabase>().readReceiptsDao()) }
factory(named(READ_RECEIPTS + FILE)) {
BackUpFileIOHandler<ReadReceiptsBackUpModel>(READ_RECEIPTS, get(named(READ_RECEIPTS + JSON)), get())
}
factory(named(READ_RECEIPTS + MAPPER)) { ReadReceiptsBackupMapper() }
factory {
ReadReceiptsBackupDataSource(get(named(READ_RECEIPTS + DB)), get(named(READ_RECEIPTS + FILE)), get(named(READ_RECEIPTS + MAPPER)))
} bind BackUpRepository::class
// Users
factory(named(USERS + JSON)) { JsonConverter(UsersBackUpModel.serializer()) }
factory(named(USERS + DB)) { BatchDatabaseIOHandler((get<UserDatabase>()).usersDao()) }
factory(named(USERS + FILE)) { BackUpFileIOHandler<UsersBackUpModel>(USERS, get(named(USERS + JSON)), get()) }
factory(named(USERS + MAPPER)) { UsersBackUpDataMapper() }
factory {
UsersBackUpDataSource(get(named(USERS + DB)), get(named(USERS + FILE)), get(named(USERS + MAPPER)))
} bind BackUpRepository::class
}
| gpl-3.0 | dbe451528dd946b6a90b95aa2c57f296 | 54.498024 | 140 | 0.758635 | 4.296512 | false | false | false | false |
wireapp/wire-android | storage/src/androidTest/kotlin/com/waz/zclient/storage/userdatabase/messages/MessageDeletionTableTestHelper.kt | 1 | 932 | package com.waz.zclient.storage.userdatabase.messages
import android.content.ContentValues
import com.waz.zclient.storage.DbSQLiteOpenHelper
class MessageDeletionTableTestHelper private constructor() {
companion object {
private const val MESSAGE_DELETION_TABLE_NAME = "MsgDeletion"
private const val MESSAGE_DELETION_MESSAGE_ID_COL = "message_id"
private const val MESSAGE_DELETION_TIMESTAMP_COL = "timestamp"
fun insertMessageDeletion(messageId: String, timestamp: Int, openHelper: DbSQLiteOpenHelper) {
val contentValues = ContentValues().also {
it.put(MESSAGE_DELETION_MESSAGE_ID_COL, messageId)
it.put(MESSAGE_DELETION_TIMESTAMP_COL, timestamp)
}
openHelper.insertWithOnConflict(
tableName = MESSAGE_DELETION_TABLE_NAME,
contentValues = contentValues
)
}
}
}
| gpl-3.0 | efac1ee998c44248d73dff871cedaabe | 32.285714 | 102 | 0.672747 | 4.957447 | false | false | false | false |
JMedinilla/JODERKotlin | app/src/main/java/ncatz/jvm/jodergenerator/MainActivity.kt | 1 | 7225 | package ncatz.jvm.jodergenerator
import android.app.Dialog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.text.TextWatcher
import android.text.method.ScrollingMovementMethod
import android.view.View
import android.view.Window
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
class MainActivity : AppCompatActivity() {
companion object {
const val JODER_MAX: Int = 150000
}
private val joder = JODER()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(activityMain_toolbar)
supportActionBar?.title = null
activityMain_JODER.movementMethod = ScrollingMovementMethod()
activityMain_actionCopy.setOnClickListener {
val joder = activityMain_JODER.text.toString()
when (joder) {
"- - -" -> Toast.makeText(this, getString(R.string.joderToCopy), Toast.LENGTH_SHORT).show()
else -> {
val clipboard: ClipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip: ClipData = ClipData.newPlainText(getString(R.string.joder), joder)
clipboard.primaryClip = clip
Toast.makeText(this, getString(R.string.joderCopied), Toast.LENGTH_SHORT).show()
}
}
}
activityMain_actionShare.setOnClickListener {
val joder = activityMain_JODER.text.toString()
when (joder) {
"- - -" -> Toast.makeText(this, getString(R.string.joderToShare), Toast.LENGTH_SHORT).show()
else -> {
val shareIntent = Intent()
shareIntent.action = Intent.ACTION_SEND
shareIntent.putExtra(Intent.EXTRA_TEXT, joder)
shareIntent.type = "text/plain"
startActivity(shareIntent)
}
}
}
activityMain_generate.setOnClickListener {
val inputManager: InputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(currentFocus.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
var min = 0
var max = 0
if (activityMain_generateEdtMin.text.toString() != "") {
min = Integer.parseInt(activityMain_generateEdtMin.text.toString())
}
if (activityMain_generateEdtMax.text.toString() != "") {
max = Integer.parseInt(activityMain_generateEdtMax.text.toString())
}
when {
min < 5 -> Toast.makeText(this, getString(R.string.minFiveChar), Toast.LENGTH_SHORT).show()
min > JODER_MAX -> Toast.makeText(this, getString(R.string.minHighChar), Toast.LENGTH_SHORT).show()
max < 5 -> Toast.makeText(this, getString(R.string.maxFiveChar), Toast.LENGTH_SHORT).show()
max > JODER_MAX -> Toast.makeText(this, getString(R.string.maxHighChar), Toast.LENGTH_SHORT).show()
min > max -> Toast.makeText(this, getString(R.string.minAndMaxChar), Toast.LENGTH_SHORT).show()
else -> {
activityMain_JODER.text = "- - -"
activityMain_JODER.scrollTo(0, 0)
activityMain_generate.isEnabled = false
activityMain_generate.visibility = View.GONE
joder.generate(min, max)
activityMain_JODER.scrollTo(0, 0)
}
}
}
activityMain_generate.setOnLongClickListener {
activityMain_JODER.text = "- - -"
activityMain_JODER.scrollTo(0, 0)
true
}
activityMain_generateEdtMin.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun afterTextChanged(s: Editable?) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val number = s.toString().toInt()
if (number > JODER_MAX) {
activityMain_generateEdtMin.setText(JODER_MAX.toString())
}
}
})
activityMain_generateEdtMax.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun afterTextChanged(s: Editable?) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val number = s.toString().toInt()
if (number > JODER_MAX) {
activityMain_generateEdtMax.setText(JODER_MAX.toString())
}
}
})
activityMain_toolbarInfo.setOnClickListener {
val dialog = Dialog(this)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setContentView(R.layout.dialog_info)
dialog.window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
val githubJM = dialog.findViewById<TextView>(R.id.activityInfo_gitJM)
val githubAPU = dialog.findViewById<TextView>(R.id.activityInfo_gitAPU)
val twitterAPU = dialog.findViewById<TextView>(R.id.activityInfo_twAPU)
val intent = Intent(Intent.ACTION_VIEW)
githubJM.setOnClickListener {
val url = "https://github.com/JMedinilla"
intent.data = Uri.parse(url)
startActivity(intent)
}
githubAPU.setOnClickListener {
val url = "https://github.com/alexpowerup"
intent.data = Uri.parse(url)
startActivity(intent)
}
twitterAPU.setOnClickListener {
val url = "https://twitter.com/alexpowerup"
intent.data = Uri.parse(url)
startActivity(intent)
}
dialog.show()
}
}
override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
override fun onStop() {
super.onStop()
EventBus.getDefault().unregister(this)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onJoderEvent(event: JODER.JoderEvent) {
activityMain_JODER.text = event.joderGenerated
activityMain_generate.visibility = View.VISIBLE
activityMain_generate.isEnabled = true
}
}
| mit | 2a45de0f725d18ed415812bb5041a110 | 41.005814 | 119 | 0.611073 | 4.697659 | false | false | false | false |
ScienceYuan/WidgetNote | app/src/main/java/com/rousci/androidapp/widgetnote/viewPresenter/config.kt | 1 | 629 | package com.rousci.androidapp.widgetnote.viewPresenter
/**
* Created by rousci on 17-10-23.
*
* to replace the flag word by val
*/
const val noteId = "position"
const val stringRequest = 1
const val getLocal = 2
const val passString = "String"
const val singleDataPreference = "lastNote"
const val lastChoicedNote = "lastChoicedNote"
const val frequency = "frequency"
const val timeCounter = "timeCounter"
const val defaultFrequency = 1
const val fontSP = "fontSP"
const val fontSPDefault = 20.0.toFloat()
const val backupFolderPath = "/WidgetNote/"
const val backupFileName = "backup"
const val writeFilePermission = 3 | mit | 262947df18553d1b4d758b190c21a9fb | 23.230769 | 54 | 0.759936 | 3.456044 | false | false | false | false |
fython/PackageTracker | mobile/src/main/kotlin/info/papdt/express/helper/support/ScreenUtils.kt | 1 | 2696 | package info.papdt.express.helper.support
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.TypedValue
object ScreenUtils {
fun isChrome(): Boolean {
return Build.BRAND == "chromium" || Build.BRAND == "chrome"
}
fun getStatusBarHeight(context: Context): Int {
var result = 0
val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
if (resourceId > 0) {
result = context.resources.getDimensionPixelSize(resourceId)
}
return result
}
private fun getMiddleValue(prev: Int, next: Int, factor: Float): Int {
return Math.round(prev + (next - prev) * factor)
}
fun getMiddleColor(prevColor: Int, curColor: Int, factor: Float): Int {
if (prevColor == curColor) {
return curColor
}
if (factor == 0f) {
return prevColor
} else if (factor == 1f) {
return curColor
}
val a = getMiddleValue(Color.alpha(prevColor), Color.alpha(curColor), factor)
val r = getMiddleValue(Color.red(prevColor), Color.red(curColor), factor)
val g = getMiddleValue(Color.green(prevColor), Color.green(curColor), factor)
val b = getMiddleValue(Color.blue(prevColor), Color.blue(curColor), factor)
return Color.argb(a, r, g, b)
}
fun getColor(baseColor: Int, alphaPercent: Float): Int {
val alpha = Math.round(Color.alpha(baseColor) * alphaPercent)
return baseColor and 0x00FFFFFF or (alpha shl 24)
}
fun dpToPx(context: Context, dp: Float): Float {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp,
context.resources.displayMetrics
) + 0.5f
}
fun drawableToBitmap(drawable: Drawable): Bitmap {
if (drawable is BitmapDrawable) {
if (drawable.bitmap != null) {
return drawable.bitmap
}
}
val bitmap = if (drawable.intrinsicWidth <= 0 || drawable.intrinsicHeight <= 0) {
Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888) // Single color bitmap will be created of 1x1 pixel
} else {
Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
}
val canvas = Canvas(bitmap!!)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}
}
| gpl-3.0 | 70d16e460f7de903954009cf51eaf710 | 31.481928 | 114 | 0.631306 | 4.265823 | false | false | false | false |
RyotaMurohoshi/android_playground | android/app/src/main/kotlin/com/muhron/playground/activity/ViewPagerExampleActivity.kt | 1 | 1699 | package com.muhron.playground.activity
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import java.util.ArrayList
import java.util.Arrays
class ViewPagerExampleActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val viewPager = ViewPager(this)
viewPager.adapter = SamplePagerAdapter(this, Arrays.asList(
"http://placehold.jp/aaaaaa/ffffff/192x192.png",
"http://placehold.jp/aa0000/ffffff/192x192.png",
"http://placehold.jp/0000aa/ffffff/192x192.png",
"http://placehold.jp/00aa00/ffffff/192x192.png"))
setContentView(viewPager)
}
}
internal class SamplePagerAdapter(private val context: Context, private val urls: List<String>) : PagerAdapter() {
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val url = urls[position]
val imageView = ImageView(context)
Glide.with(this.context).load(url).into(imageView)
container.addView(imageView)
return imageView
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
container.removeView(`object` as View)
}
override fun getCount(): Int {
return urls.size
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view === `object` as ImageView
}
} | mit | b6bb5da024fa96f4b208b2b66b599cec | 30.481481 | 114 | 0.699235 | 4.205446 | false | false | false | false |
meh/watch_doge | src/main/java/meh/watchdoge/request/Sniffer.kt | 1 | 1437 | package meh.watchdoge.request;
import meh.watchdoge.backend.Command as C;
import android.os.Message;
class Sniffer(id: Int?): Family(C.SNIFFER) {
private val _id = id;
fun create() {
create() { }
}
fun create(body: Create.() -> Unit) {
val next = Create();
next.body();
_command = next;
}
fun start() {
_command = Start(_id!!);
}
fun filter(filter: String?) {
_command = Filter(_id!!, filter);
}
fun subscribe() {
_command = Subscribe(_id!!);
}
fun unsubscribe() {
_command = Unsubscribe(_id!!);
}
fun list() {
_command = List();
}
class Create(): Command(C.Sniffer.CREATE) {
var ip: String? = null;
var truncate: Int = 0;
override fun build(msg: Message) {
super.build(msg);
if (ip != null) {
msg.getData().putString("ip", ip);
}
if (truncate != 0) {
msg.getData().putInt("truncate", truncate);
}
}
}
class Start(id: Int): CommandWithId(id, C.Sniffer.START);
class Stop(id: Int): CommandWithId(id, C.Sniffer.STOP);
class Filter(id: Int, filter: String?): CommandWithId(id, C.Sniffer.FILTER) {
val filter = filter;
override fun build(msg: Message) {
super.build(msg);
if (filter != null) {
msg.getData().putString("filter", filter);
}
}
}
class List(): Command(C.Sniffer.LIST);
class Subscribe(id: Int): CommandWithId(id, C.Sniffer.SUBSCRIBE);
class Unsubscribe(id: Int): CommandWithId(id, C.Sniffer.UNSUBSCRIBE);
}
| agpl-3.0 | b30e259e7cad00b378aab15b46ce4f12 | 18.16 | 78 | 0.620042 | 2.856859 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | fluxc/src/main/java/org/wordpress/android/fluxc/store/WhatsNewStore.kt | 1 | 4440 | package org.wordpress.android.fluxc.store
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.Payload
import org.wordpress.android.fluxc.action.WhatsNewAction
import org.wordpress.android.fluxc.action.WhatsNewAction.FETCH_CACHED_ANNOUNCEMENT
import org.wordpress.android.fluxc.action.WhatsNewAction.FETCH_REMOTE_ANNOUNCEMENT
import org.wordpress.android.fluxc.annotations.action.Action
import org.wordpress.android.fluxc.model.whatsnew.WhatsNewAnnouncementModel
import org.wordpress.android.fluxc.network.BaseRequest.BaseNetworkError
import org.wordpress.android.fluxc.network.rest.wpcom.whatsnew.WhatsNewRestClient
import org.wordpress.android.fluxc.persistence.WhatsNewSqlUtils
import org.wordpress.android.fluxc.store.WhatsNewStore.WhatsNewErrorType.GENERIC_ERROR
import org.wordpress.android.fluxc.tools.CoroutineEngine
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
import org.wordpress.android.util.AppLog.T.API
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class WhatsNewStore @Inject constructor(
private val whatsNewRestClient: WhatsNewRestClient,
private val whatsNewSqlUtils: WhatsNewSqlUtils,
private val coroutineEngine: CoroutineEngine,
dispatcher: Dispatcher
) : Store(dispatcher) {
@Subscribe(threadMode = ThreadMode.ASYNC)
override fun onAction(action: Action<*>) {
val actionType = action.type as? WhatsNewAction ?: return
when (actionType) {
FETCH_REMOTE_ANNOUNCEMENT -> {
val versionName = (action.payload as WhatsNewFetchPayload).versionName
val appId = (action.payload as WhatsNewFetchPayload).appId
coroutineEngine.launch(AppLog.T.API, this, "FETCH_REMOTE_ANNOUNCEMENT") {
emitChange(fetchRemoteAnnouncements(versionName, appId))
}
}
FETCH_CACHED_ANNOUNCEMENT -> {
coroutineEngine.launch(AppLog.T.API, this, "FETCH_CACHED_ANNOUNCEMENT") {
emitChange(fetchCachedAnnouncements())
}
}
}
}
suspend fun fetchCachedAnnouncements() =
coroutineEngine.withDefaultContext(T.API, this, "fetchWhatsNew") {
return@withDefaultContext OnWhatsNewFetched(whatsNewSqlUtils.getAnnouncements(), true)
}
suspend fun fetchRemoteAnnouncements(versionName: String, appId: WhatsNewAppId) =
coroutineEngine.withDefaultContext(T.API, this, "fetchWhatsNew") {
val fetchedWhatsNewPayload = whatsNewRestClient.fetchWhatsNew(versionName, appId)
return@withDefaultContext if (!fetchedWhatsNewPayload.isError) {
val fetchedAnnouncements = fetchedWhatsNewPayload.whatsNewItems
whatsNewSqlUtils.updateAnnouncementCache(fetchedAnnouncements)
OnWhatsNewFetched(fetchedAnnouncements)
} else {
OnWhatsNewFetched(
fetchError = WhatsNewFetchError(GENERIC_ERROR, fetchedWhatsNewPayload.error.message)
)
}
}
override fun onRegister() {
AppLog.d(API, WhatsNewStore::class.java.simpleName + " onRegister")
}
class WhatsNewFetchPayload(
val versionName: String,
val appId: WhatsNewAppId
) : Payload<BaseNetworkError>()
class WhatsNewFetchedPayload(
val whatsNewItems: List<WhatsNewAnnouncementModel>? = null
) : Payload<BaseNetworkError>()
data class OnWhatsNewFetched(
val whatsNewItems: List<WhatsNewAnnouncementModel>? = null,
val isFromCache: Boolean = false,
val fetchError: WhatsNewFetchError? = null
) : Store.OnChanged<WhatsNewFetchError>() {
init {
// we allow setting error from constructor, so it will be a part of data class
// and used during comparison, so we can test error events
this.error = fetchError
}
}
data class WhatsNewFetchError(
val type: WhatsNewErrorType,
val message: String = ""
) : OnChangedError
enum class WhatsNewErrorType {
GENERIC_ERROR
}
enum class WhatsNewAppId(val id: Int) {
WP_ANDROID(1),
WOO_ANDROID(3),
JP_ANDROID(5)
}
}
| gpl-2.0 | e2308036d3c706b9a5d1bd3997593d7b | 40.111111 | 112 | 0.690991 | 4.698413 | false | false | false | false |
icarumbas/bagel | core/src/ru/icarumbas/bagel/engine/entities/BodyContactListener.kt | 1 | 7572 | package ru.icarumbas.bagel.engine.entities
import com.badlogic.ashley.core.Engine
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.Family
import com.badlogic.gdx.physics.box2d.Contact
import com.badlogic.gdx.physics.box2d.ContactImpulse
import com.badlogic.gdx.physics.box2d.ContactListener
import com.badlogic.gdx.physics.box2d.Manifold
import ru.icarumbas.bagel.engine.components.physics.WeaponComponent
import ru.icarumbas.bagel.engine.controller.PlayerMoveController
import ru.icarumbas.bagel.utils.*
import kotlin.experimental.or
class BodyContactListener(
private val playerController: PlayerMoveController,
private val engine: Engine,
private val playerEntity: Entity
) : ContactListener {
private lateinit var defendingEntity: Entity
private lateinit var attackingEntity: Entity
private lateinit var contactEntityA: Entity
private lateinit var contactEntityB: Entity
private fun findAttackerAndDefender() {
engine.getEntitiesFor(Family.all(WeaponComponent::class.java).get()).forEach{
if (weapon[it].entityLeft === contactEntityA || weapon[it].entityRight === contactEntityA){
attackingEntity = it
defendingEntity = contactEntityB
}
if (weapon[it].entityLeft === contactEntityB || weapon[it].entityRight === contactEntityB){
attackingEntity = it
defendingEntity = contactEntityA
}
}
}
private fun findAttackerAndDefenderForSharp(){
if (player.has(contactEntityA) || AI.has(contactEntityA)) {
defendingEntity = contactEntityA
attackingEntity = contactEntityB
}
if (player.has(contactEntityB) || AI.has(contactEntityB)) {
defendingEntity = contactEntityB
attackingEntity = contactEntityA
}
}
private fun attackEntity(){
if (damage[defendingEntity].hitTimer > damage[defendingEntity].canBeDamagedTime) {
damage[defendingEntity].damage = attack[attackingEntity].strength
damage[defendingEntity].knockback.set(attack[attackingEntity].knockback)
if (!attackingEntity.rotatedRight())
damage[defendingEntity].knockback.scl(-1f, 1f)
if (weapon.has(attackingEntity)) damage[defendingEntity].isWeaponContact = true
}
}
private fun findContactEntities(contact: Contact){
contactEntityA = contact.fixtureA.body.userData as Entity
contactEntityB = contact.fixtureB.body.userData as Entity
}
override fun postSolve(contact: Contact, impulse: ContactImpulse) {
}
override fun preSolve(contact: Contact, oldManifold: Manifold) {
findContactEntities(contact)
when (contact.fixtureA.filterData.categoryBits or contact.fixtureB.filterData.categoryBits) {
PLAYER_BIT or PLATFORM_BIT, PLAYER_FEET_BIT or PLATFORM_BIT -> {
if (playerEntity == contactEntityA) {
if (body[contactEntityA].body.position.y <
body[contactEntityB].body.position.y + size[contactEntityB].rectSize.y * 2|| playerController.isDownPressed()) {
contact.isEnabled = false
}
} else {
if (body[contactEntityB].body.position.y <
body[contactEntityA].body.position.y + size[contactEntityA].rectSize.y * 2 || playerController.isDownPressed()) {
contact.isEnabled = false
}
}
player[playerEntity].standindOnGround = true
}
AI_BIT or PLATFORM_BIT -> {
if (AI.has(contactEntityA)) {
if (body[contactEntityA].body.position.y <
body[contactEntityB].body.position.y + size[contactEntityB].rectSize.y / 2 + size[playerEntity].rectSize.y / 2) {
contact.isEnabled = false
}
} else {
if (body[contactEntityB].body.position.y <
body[contactEntityA].body.position.y + size[contactEntityA].rectSize.y / 2 + size[playerEntity].rectSize.y / 2) {
contact.isEnabled = false
}
}
}
PLAYER_BIT or GROUND_BIT -> {
player[playerEntity].collidingWithGround = true
}
PLAYER_FEET_BIT or GROUND_BIT -> {
player[playerEntity].standindOnGround = true
}
SHARP_BIT or PLAYER_FEET_BIT, SHARP_BIT or AI_BIT, SHARP_BIT or PLAYER_BIT -> {
contact.isEnabled = false
findAttackerAndDefenderForSharp()
attackEntity()
}
PLAYER_BIT or KEY_OPEN_BIT -> {
contact.isEnabled = false
if (contactEntityA === playerEntity) {
open[contactEntityB].isCollidingWithPlayer = true
} else {
open[contactEntityA].isCollidingWithPlayer = true
}
// hud.setOpenButtonVisible(true)
}
WEAPON_BIT or BREAKABLE_BIT, WEAPON_BIT or AI_BIT, WEAPON_BIT or PLAYER_BIT -> {
contact.isEnabled = false
findAttackerAndDefender()
if (!damage[defendingEntity].isWeaponContact) {
if (!(state.has(defendingEntity) &&
state[defendingEntity].currentState == EntityState.NOTHING &&
state[defendingEntity].currentState == EntityState.APPEARING &&
state[defendingEntity].currentState == EntityState.DEAD)) {
attackEntity()
if (AI.has(defendingEntity)) AI[defendingEntity].entityTarget = attackingEntity
}
}
}
PLAYER_BIT or AI_BIT -> {
contact.isEnabled = false
if (contactEntityA === playerEntity){
defendingEntity = contactEntityA
attackingEntity = contactEntityB
} else {
defendingEntity = contactEntityB
attackingEntity = contactEntityA
}
attackEntity()
}
}
}
override fun beginContact(contact: Contact) {}
override fun endContact(contact: Contact) {
findContactEntities(contact)
when (contact.fixtureA.filterData.categoryBits or contact.fixtureB.filterData.categoryBits) {
PLAYER_BIT or GROUND_BIT -> {
player[playerEntity].collidingWithGround = false
}
PLAYER_FEET_BIT or GROUND_BIT, PLAYER_FEET_BIT or PLATFORM_BIT -> {
player[playerEntity].standindOnGround = false
}
WEAPON_BIT or BREAKABLE_BIT, WEAPON_BIT or AI_BIT, WEAPON_BIT or PLAYER_BIT -> {
findAttackerAndDefender()
damage[defendingEntity].isWeaponContact = false
}
PLAYER_BIT or KEY_OPEN_BIT -> {
if (contactEntityA === playerEntity) {
open[contactEntityB].isCollidingWithPlayer = false
} else {
open[contactEntityA].isCollidingWithPlayer = false
}
// hud.setOpenButtonVisible(false)
}
}
}
}
| apache-2.0 | 0ee0612d62635af572f031f787af7b5c | 35.757282 | 141 | 0.580428 | 4.631193 | false | false | false | false |
google/ksp | test-utils/testData/api/allFunctions_kt_inherits_java.kt | 1 | 2721 | /*
* Copyright 2022 Google LLC
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* 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.
*/
// WITH_RUNTIME
// TEST PROCESSOR: AllFunctionsProcessor
// EXPECTED:
// class: C
// aFromC
// bFromC
// cFromC
// <init>(): C
// equals(kotlin.Any): kotlin.Boolean
// hashCode(): kotlin.Int
// javaListFun(): kotlin.collections.MutableCollection
// javaPrivateFun(): kotlin.Unit
// javaStrFun(): kotlin.String
// toString(): kotlin.String
// class: Foo
// aFromC
// cFromC
// size
// <init>(): Foo
// bar(): kotlin.Boolean
// baz(kotlin.String,kotlin.String(hasDefault),kotlin.String(hasDefault)): kotlin.Boolean
// contains(kotlin.Number): kotlin.Boolean
// containsAll(kotlin.collections.Collection): kotlin.Boolean
// equals(kotlin.Any): kotlin.Boolean
// forEach(java.util.function.Consumer): kotlin.Unit
// get(kotlin.Int): kotlin.Number
// hashCode(): kotlin.Int
// indexOf(kotlin.Number): kotlin.Int
// isEmpty(): kotlin.Boolean
// iterator(): kotlin.collections.Iterator
// javaListFun(): kotlin.collections.List
// javaStrFun(): kotlin.String
// lastIndexOf(kotlin.Number): kotlin.Int
// listIterator(): kotlin.collections.ListIterator
// listIterator(kotlin.Int): kotlin.collections.ListIterator
// parallelStream(): java.util.stream.Stream
// spliterator(): java.util.Spliterator
// stream(): java.util.stream.Stream
// subList(kotlin.Int,kotlin.Int): kotlin.collections.List
// toArray(java.util.function.IntFunction): kotlin.Array
// toString(): kotlin.String
// END
// FILE: a.kt
abstract class Foo : C(), List<out Number> {
override fun javaListFun(): List<Int> {
throw java.lang.IllegalStateException()
}
fun bar(): Boolean {
return false
}
fun baz(input: String, input2: String? = null, input3: String = ""): Boolean {
return false
}
}
// FILE: C.java
import java.util.Collection;
class C {
public int aFromC = 1;
private int bFromC = 2;
protected int cFromC = 3;
private void javaPrivateFun() {
}
protected Collection<Integer> javaListFun() {
return Arrays.asList(1,2,3)
}
public String javaStrFun() {
return "str"
}
}
| apache-2.0 | a7dbe4945dacd7129693785b612d9b7a | 28.258065 | 89 | 0.702683 | 3.784423 | false | false | false | false |
zalando/tracer | opentracing-kotlin/src/test/kotlin/org/zalando/opentracing/kotlin/TracerExtensionsTest.kt | 1 | 2360 | package org.zalando.opentracing.kotlin
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.collections.atLeastSize
import io.kotest.matchers.maps.shouldContainAll
import io.kotest.matchers.maps.shouldContainExactly
import io.kotest.matchers.maps.shouldNotContainKey
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldHave
import io.opentracing.Span
import io.opentracing.mock.MockSpan
import io.opentracing.mock.MockTracer
import io.opentracing.tag.Tags
import org.junit.jupiter.api.assertThrows
class TracerExtensionsTest : FunSpec({
test("trace successful") {
val tracer = MockTracer()
var span: Span? = null
tracer.trace(
operation = "mock",
component = "test"
) {
it.setTag("works", true)
span = it
}
(span as MockSpan)
.tags() shouldContainAll mapOf<String, Any>(
"works" to true,
Tags.COMPONENT.key to "test"
)
(span as MockSpan).let {
tracer.injectToMap(it)?.shouldContainExactly(
mapOf(
"spanid" to it.context().spanId().toString(),
"traceid" to it.context().traceId().toString()
)
)
}
}
test("get context from map") {
val tracer = MockTracer()
tracer.extract(
mapOf(
"spanid" to "6",
"traceid" to "5"
)
).let {
it?.toSpanId() shouldBe "6"
it?.toTraceId() shouldBe "5"
}
}
test("trace failure") {
val tracer = MockTracer()
var span: Span? = null
assertThrows<Exception> {
tracer.trace(
operation = "mock",
component = "test"
) {
it.setTag("works", true)
span = it
throw Exception()
it.setTag("not_work", true)
}
}
(span as MockSpan).let {
it.tags() shouldContainAll mapOf<String, Any>(
"works" to true,
Tags.COMPONENT.key to "test",
Tags.ERROR.key to true
)
it.tags() shouldNotContainKey "not_work"
it.logEntries() shouldHave atLeastSize(1)
}
}
})
| mit | 200f600017153ef4a152565a6a9ea2b8 | 27.095238 | 66 | 0.533898 | 4.402985 | false | true | false | false |
SimpleTimeTracking/StandaloneClient | src/main/kotlin/org/stt/gui/UIMain.kt | 1 | 3749 | package org.stt.gui
import javafx.application.Application
import javafx.application.Platform
import javafx.scene.image.Image
import javafx.stage.Stage
import net.engio.mbassy.bus.MBassador
import net.engio.mbassy.listener.Handler
import org.controlsfx.dialog.ExceptionDialog
import org.stt.Service
import org.stt.StopWatch
import org.stt.event.ShuttingDown
import org.stt.event.TimePassedEvent
import org.stt.gui.jfx.MainWindowController
import java.util.*
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.ExecutorService
import java.util.logging.Level
import java.util.logging.Logger
class UIMain : Application() {
private val servicesToShutdown = CopyOnWriteArrayList<Service>()
private var eventBus: MBassador<Any>? = null
private lateinit var mainWindowController: MainWindowController
private lateinit var executorService: ExecutorService
override fun init() {
val rootLogger = Logger.getLogger("")
rootLogger.handlers[0].level = Level.FINEST
Logger.getLogger("org.stt").level = Level.FINEST
LOG.info("Starting STT in UI mode")
LOG.info("Starting injector")
val uiApplication = DaggerUIApplication.builder().build()
executorService = uiApplication.executorService()
startEventBus(uiApplication)
startService(uiApplication.configService())
startService(uiApplication.backupCreator())
startService(uiApplication.itemLogService())
LOG.info("init() done")
mainWindowController = uiApplication.mainWindow()
}
private fun startEventBus(uiApplication: UIApplication) {
LOG.info("Setting up event bus")
eventBus = uiApplication.eventBus()
eventBus!!.subscribe(this)
}
@Handler(priority = -999)
fun shutdown(request: ShuttingDown) {
LOG.info("Shutting down")
try {
servicesToShutdown.reverse()
for (service in servicesToShutdown) {
LOG.info("Stopping " + service.javaClass.simpleName)
service.stop()
}
executorService.shutdown()
} finally {
Platform.exit()
}
}
private fun startService(serviceInstance: Service) {
val stopWatch = StopWatch(serviceInstance.javaClass.simpleName)
LOG.info("Starting " + serviceInstance.javaClass.simpleName)
serviceInstance.start()
servicesToShutdown.add(serviceInstance)
stopWatch.stop()
}
override fun start(primaryStage: Stage) {
listOf("/Logo32.png", "/Logo64.png", "/Logo.png")
.map { javaClass.getResourceAsStream(it) }
.map { Image(it) }
.forEach { primaryStage.icons.add(it) }
Thread.currentThread().setUncaughtExceptionHandler { _, e ->
LOG.log(Level.SEVERE, "Uncaught exception", e)
eventBus!!.publish(e)
ExceptionDialog(e).show()
}
LOG.info("Showing window")
mainWindowController.show(primaryStage)
scheduleOneUpdatePerSecond()
LOG.fine("Window is now shown")
}
private fun scheduleOneUpdatePerSecond() {
Timer(true).schedule(object : TimerTask() {
override fun run() {
Platform.runLater { eventBus!!.publish(TimePassedEvent()) }
}
}, 0, 1000)
}
companion object {
/**
* Set to true to add debug graphics
*/
const val DEBUG_UI = false
private val LOG = Logger.getLogger(UIMain::class.java
.name)
@JvmStatic
fun main(args: Array<String>) {
LOG.info("START")
launch(UIMain::class.java, *args)
}
}
}
| gpl-3.0 | 2e62f7a603450c54f60300ee2c702dc0 | 31.318966 | 75 | 0.646572 | 4.571951 | false | false | false | false |
pabiagioli/gopro-showcase | app/src/main/java/com/aajtech/mobile/goproshowcase/MyGoProStatusDTORecyclerViewAdapter.kt | 1 | 1809 | package com.aajtech.mobile.goproshowcase
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.aajtech.mobile.goproshowcase.dto.GoProStatusDTO
/**
* [RecyclerView.Adapter] that can display a [GoProStatusDTO] and makes a call to the
* specified [OnListFragmentInteractionListener].
*/
class MyGoProStatusDTORecyclerViewAdapter(private val mValues: List<GoProStatusDTO>, private val mListener: GoProStatusDTOFragment.OnListFragmentInteractionListener?) : RecyclerView.Adapter<MyGoProStatusDTORecyclerViewAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.fragment_goprostatusdto, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.mItem = mValues[position]
holder.mIdView.text = mValues[position].propName
holder.mContentView.text = mValues[position].propValue.toString()
holder.mView.setOnClickListener {
mListener?.onListFragmentInteraction(holder.mItem!!)
}
}
override fun getItemCount(): Int {
return mValues.size
}
inner class ViewHolder(val mView: View) : RecyclerView.ViewHolder(mView) {
val mIdView: TextView
val mContentView: TextView
var mItem: GoProStatusDTO? = null
init {
mIdView = mView.findViewById(R.id.id) as TextView
mContentView = mView.findViewById(R.id.content) as TextView
}
override fun toString(): String {
return super.toString() + " '" + mContentView.text + "'"
}
}
}
| gpl-3.0 | ae12cab50a1d7bd7f433ffc74d0408d9 | 35.918367 | 241 | 0.71476 | 4.579747 | false | false | false | false |
cyrillrx/android_libraries | core/src/main/java/com/cyrillrx/android/utils/Views.kt | 1 | 941 | package com.cyrillrx.android.utils
import android.app.Activity
import android.content.ContextWrapper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
/**
* @author Cyril Leroux
* Created on 15/04/2018.
*/
fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View =
LayoutInflater
.from(this.context)
.inflate(layoutRes, this, attachToRoot)
fun View.getActivity(): Activity? {
val viewContext = this.context
if (viewContext is Activity) { // Android > 4
return viewContext
}
if (viewContext is ContextWrapper && viewContext.baseContext is Activity) {
return viewContext.baseContext as Activity
}
val rootContext = this.rootView.context
if (rootContext is Activity) { // Android >= 4
return rootContext
}
return null
} | mit | feb57a28fc6736503f989e499c9591ec | 24.459459 | 87 | 0.691817 | 4.41784 | false | false | false | false |
msebire/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GithubPullRequestsList.kt | 1 | 5811 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui
import com.intellij.ide.CopyProvider
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.util.Disposer
import com.intellij.ui.ListUtil
import com.intellij.ui.ScrollingUtil
import com.intellij.ui.components.JBList
import com.intellij.util.text.DateFormatUtil
import com.intellij.util.ui.*
import icons.GithubIcons
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.jetbrains.plugins.github.api.data.GithubIssueState
import org.jetbrains.plugins.github.api.data.GithubSearchedIssue
import org.jetbrains.plugins.github.pullrequest.avatars.CachingGithubAvatarIconsProvider
import org.jetbrains.plugins.github.util.GithubUIUtil
import java.awt.Component
import java.awt.FlowLayout
import java.awt.datatransfer.StringSelection
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.*
internal class GithubPullRequestsList(private val copyPasteManager: CopyPasteManager,
avatarIconsProviderFactory: CachingGithubAvatarIconsProvider.Factory,
model: ListModel<GithubSearchedIssue>)
: JBList<GithubSearchedIssue>(model), CopyProvider, DataProvider, Disposable {
private val avatarIconSize = JBValue.UIInteger("Github.PullRequests.List.Assignee.Avatar.Size", 20)
private val avatarIconsProvider = avatarIconsProviderFactory.create(avatarIconSize, this)
init {
selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION
addMouseListener(RightClickSelectionListener())
val renderer = PullRequestsListCellRenderer()
cellRenderer = renderer
UIUtil.putClientProperty(this, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, listOf(renderer))
ScrollingUtil.installActions(this)
Disposer.register(this, avatarIconsProvider)
}
override fun getToolTipText(event: MouseEvent): String? {
val childComponent = ListUtil.getDeepestRendererChildComponentAt(this, event.point)
if (childComponent !is JComponent) return null
return childComponent.toolTipText
}
override fun performCopy(dataContext: DataContext) {
if (selectedIndex < 0) return
val selection = model.getElementAt(selectedIndex)
copyPasteManager.setContents(StringSelection("#${selection.number} ${selection.title}"))
}
override fun isCopyEnabled(dataContext: DataContext) = !isSelectionEmpty
override fun isCopyVisible(dataContext: DataContext) = false
override fun getData(dataId: String) = if (PlatformDataKeys.COPY_PROVIDER.`is`(dataId)) this else null
override fun dispose() {}
private inner class PullRequestsListCellRenderer : ListCellRenderer<GithubSearchedIssue>, JPanel() {
private val stateIcon = JLabel()
private val title = JLabel()
private val info = JLabel()
private val labels = JPanel(FlowLayout(FlowLayout.LEFT, 4, 0))
private val assignees = JPanel().apply {
layout = BoxLayout(this, BoxLayout.X_AXIS)
}
init {
border = JBUI.Borders.empty(5, 8)
layout = MigLayout(LC().gridGap("0", "0")
.insets("0", "0", "0", "0")
.fillX())
add(stateIcon, CC()
.gapAfter("${JBUI.scale(5)}px"))
add(title, CC()
.minWidth("0px"))
add(labels, CC()
.growX()
.pushX())
add(assignees, CC()
.spanY(2)
.wrap())
add(info, CC()
.minWidth("0px")
.skip(1)
.spanX(2))
}
override fun getListCellRendererComponent(list: JList<out GithubSearchedIssue>,
value: GithubSearchedIssue,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean): Component {
UIUtil.setBackgroundRecursively(this, GithubUIUtil.List.WithTallRow.background(list, isSelected))
val primaryTextColor = GithubUIUtil.List.WithTallRow.foreground(list, isSelected)
val secondaryTextColor = GithubUIUtil.List.WithTallRow.secondaryForeground(list, isSelected)
stateIcon.apply {
icon = if (value.state == GithubIssueState.open) GithubIcons.PullRequestOpen else GithubIcons.PullRequestClosed
}
title.apply {
text = value.title
foreground = primaryTextColor
}
info.apply {
text = "#${value.number} ${value.user.login} on ${DateFormatUtil.formatDate(value.createdAt)}"
foreground = secondaryTextColor
}
labels.apply {
removeAll()
for (label in value.labels.orEmpty()) add(GithubUIUtil.createIssueLabelLabel(label))
}
assignees.apply {
removeAll()
for (assignee in value.assignees) {
if (componentCount != 0) {
add(Box.createRigidArea(JBDimension(UIUtil.DEFAULT_HGAP, 0)))
}
add(JLabel().apply {
icon = assignee.let { avatarIconsProvider.getIcon(it) }
toolTipText = assignee.login
})
}
}
return this
}
}
private inner class RightClickSelectionListener : MouseAdapter() {
override fun mousePressed(e: MouseEvent) {
if (JBSwingUtilities.isRightMouseButton(e)) {
val row = locationToIndex(e.point)
if (row != -1) selectionModel.setSelectionInterval(row, row)
}
}
}
} | apache-2.0 | b9150136f03f11ac1bb2ef2dcc7835b6 | 36.986928 | 140 | 0.68835 | 4.875 | false | false | false | false |
envoyproxy/envoy | mobile/library/kotlin/io/envoyproxy/envoymobile/stats/GaugeImpl.kt | 2 | 1252 | package io.envoyproxy.envoymobile
import io.envoyproxy.envoymobile.engine.EnvoyEngine
import java.lang.ref.WeakReference
/**
* Envoy implementation of a `Gauge`.
*/
internal class GaugeImpl : Gauge {
var envoyEngine: WeakReference<EnvoyEngine>
var series: String
var tags: Tags
internal constructor(engine: EnvoyEngine, elements: List<Element>, tags: Tags = TagsBuilder().build()) {
this.envoyEngine = WeakReference<EnvoyEngine>(engine)
this.series = elements.joinToString(separator = ".") { it.value }
this.tags = tags
}
override fun set(value: Int) {
envoyEngine.get()?.recordGaugeSet(series, this.tags.allTags(), value)
}
override fun set(tags: Tags, value: Int) {
envoyEngine.get()?.recordGaugeSet(series, tags.allTags(), value)
}
override fun add(amount: Int) {
envoyEngine.get()?.recordGaugeAdd(series, this.tags.allTags(), amount)
}
override fun add(tags: Tags, amount: Int) {
envoyEngine.get()?.recordGaugeAdd(series, tags.allTags(), amount)
}
override fun sub(amount: Int) {
envoyEngine.get()?.recordGaugeSub(series, this.tags.allTags(), amount)
}
override fun sub(tags: Tags, amount: Int) {
envoyEngine.get()?.recordGaugeSub(series, tags.allTags(), amount)
}
}
| apache-2.0 | bb8d798206b9e7a3876f92b8c4f37083 | 28.116279 | 106 | 0.704473 | 3.587393 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/DrawerActivity.kt | 1 | 6190 | package com.boardgamegeek.ui
import android.os.Bundle
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.viewModels
import androidx.appcompat.widget.Toolbar
import androidx.constraintlayout.widget.Group
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.core.view.isVisible
import androidx.drawerlayout.widget.DrawerLayout
import com.boardgamegeek.R
import com.boardgamegeek.auth.Authenticator
import com.boardgamegeek.databinding.ActivityDrawerBaseBinding
import com.boardgamegeek.entities.UserEntity
import com.boardgamegeek.extensions.*
import com.boardgamegeek.pref.SettingsActivity
import com.boardgamegeek.ui.viewmodel.SelfUserViewModel
import com.boardgamegeek.ui.viewmodel.SyncViewModel
import com.google.android.material.navigation.NavigationView
/**
* Activity that displays the navigation drawer and allows for content in the root_container FrameLayout.
*/
abstract class DrawerActivity : BaseActivity() {
private lateinit var binding: ActivityDrawerBaseBinding
lateinit var drawerLayout: DrawerLayout
private lateinit var navigationView: NavigationView
private lateinit var toolbar: Toolbar
var rootContainer: ViewGroup? = null
private val viewModel by viewModels<SelfUserViewModel>()
private val syncViewModel by viewModels<SyncViewModel>()
protected open val navigationItemId: Int
get() = 0
protected open fun bindLayout() {
binding = ActivityDrawerBaseBinding.inflate(layoutInflater)
setContentView(binding.root)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
bindLayout()
drawerLayout = findViewById(R.id.drawer_layout)
navigationView = findViewById(R.id.navigation)
toolbar = findViewById(R.id.toolbar)
rootContainer = findViewById(R.id.root_container)
setSupportActionBar(toolbar)
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START)
drawerLayout.setStatusBarBackgroundColor(ContextCompat.getColor(this, R.color.primary_dark))
navigationView.setNavigationItemSelectedListener { menuItem ->
selectItem(menuItem.itemId)
true
}
navigationView.getHeaderView(0).findViewById<Button>(R.id.signInButton)?.let {
it.setOnClickListener { startActivity<LoginActivity>() }
}
viewModel.user.observe(this) {
navigationView.menu.setGroupVisible(R.id.personal, Authenticator.isSignedIn(this))
refreshHeader(it?.data)
}
syncViewModel.currentSyncTimestamp.observe(this) {
invalidateOptionsMenu()
}
syncViewModel.username.observe(this) {
viewModel.setUsername(it)
}
}
override fun onStart() {
super.onStart()
if (preferences()[KEY_HAS_SEEN_NAV_DRAWER, false] != true) {
drawerLayout.openDrawer(GravityCompat.START)
preferences()[KEY_HAS_SEEN_NAV_DRAWER] = true
}
}
override fun onResume() {
super.onResume()
navigationView.setCheckedItem(navigationItemId)
}
override fun onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
private fun selectItem(menuItemId: Int) {
if (menuItemId != navigationItemId) {
when (menuItemId) {
R.id.collection -> startActivity<CollectionActivity>()
R.id.collection_details -> startActivity<CollectionDetailsActivity>()
R.id.search -> startActivity<SearchResultsActivity>()
R.id.hotness -> startActivity<HotnessActivity>()
R.id.top_games -> startActivity<TopGamesActivity>()
R.id.geeklists -> startActivity<GeekListsActivity>()
R.id.plays -> startActivity<PlaysSummaryActivity>()
R.id.geek_buddies -> startActivity<BuddiesActivity>()
R.id.forums -> startActivity<ForumsActivity>()
R.id.data -> startActivity<DataActivity>()
R.id.settings -> startActivity<SettingsActivity>()
}
}
drawerLayout.closeDrawer(navigationView)
}
private fun refreshHeader(user: UserEntity?) {
val view = navigationView.getHeaderView(0)
val primaryView = view.findViewById<TextView>(R.id.accountInfoPrimaryView)
val secondaryView = view.findViewById<TextView>(R.id.accountInfoSecondaryView)
val imageView = view.findViewById<ImageView>(R.id.accountImageView)
val signedInGroup = view.findViewById<Group>(R.id.signedInGroup)
val signInButton = view.findViewById<Button>(R.id.signInButton)
if (Authenticator.isSignedIn(this) && user != null) {
if (user.fullName.isNotBlank() && user.userName.isNotBlank()) {
primaryView.text = user.fullName
secondaryView.text = user.userName
primaryView.setOnClickListener { }
secondaryView.setOnClickListener { linkToBgg("user/${user.userName}") }
} else if (user.userName.isNotBlank()) {
primaryView.text = user.userName
secondaryView.text = ""
primaryView.setOnClickListener { linkToBgg("user/${user.userName}") }
secondaryView.setOnClickListener { }
} else {
Authenticator.getAccount(this)?.let { viewModel.setUsername(it.name) }
}
if (user.avatarUrl.isBlank()) {
imageView.isVisible = false
} else {
imageView.isVisible = true
imageView.loadThumbnail(user.avatarUrl, R.drawable.person_image_empty)
}
signedInGroup.isVisible = true
signInButton.isVisible = false
} else {
signedInGroup.isVisible = false
signInButton.isVisible = true
}
}
}
| gpl-3.0 | d8c24c231f9eaae581ef0e01e41dd3f4 | 38.426752 | 105 | 0.669467 | 5.069615 | false | false | false | false |
WindSekirun/RichUtilsKt | RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/utils/RUnReadCount.kt | 1 | 1339 | @file:JvmName("RichUtils")
@file:JvmMultifileClass
package pyxis.uzuki.live.richutilskt.utils
import android.content.Context
import android.content.Intent
/**
* apply count of UnRead
*
* @param[count] count of setting count
*/
fun Context.applyUnReadCount(count: Int) {
val launcherClassName = getLauncherClassName(this)
if (launcherClassName.isEmpty()) return
applyDefault(this, count, launcherClassName)
}
/**
* remove count of UnRead
*/
fun Context.removeUnReadCount() {
this.applyUnReadCount(0)
}
private fun applyDefault(context: Context, count: Int, launcherClassName: String) {
val intent = Intent("android.intent.action.BADGE_COUNT_UPDATE")
intent.putExtra("badge_count_package_name", context.packageName)
intent.putExtra("badge_count_class_name", launcherClassName)
intent.putExtra("badge_count", count)
intent.flags = 0x00000020
context.sendBroadcast(intent)
}
private fun getLauncherClassName(context: Context): String {
val intent = Intent(Intent.ACTION_MAIN)
intent.addCategory(Intent.CATEGORY_LAUNCHER)
intent.`package` = context.packageName
val resolveInfoList = context.packageManager.queryIntentActivities(intent, 0)
if (resolveInfoList != null && resolveInfoList.size > 0) {
return resolveInfoList[0].activityInfo.name
}
return ""
} | apache-2.0 | f4465e34b88d6e2aad3beebf7f4407e4 | 28.130435 | 83 | 0.740851 | 3.949853 | false | false | false | false |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/entitymapper/ShowCastMapper.kt | 1 | 1983 | /*
* Copyright (C) 2018 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.entitymapper
import android.database.Cursor
import net.simonvt.cathode.common.data.MappedCursorLiveData
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.common.database.getString
import net.simonvt.cathode.entity.CastMember
import net.simonvt.cathode.entity.Person
import net.simonvt.cathode.provider.DatabaseContract.PersonColumns
import net.simonvt.cathode.provider.DatabaseContract.ShowCastColumns
import net.simonvt.cathode.provider.DatabaseSchematic.Tables
object ShowCastMapper : MappedCursorLiveData.CursorMapper<List<CastMember>> {
override fun map(cursor: Cursor): List<CastMember> {
val castMembers = mutableListOf<CastMember>()
cursor.moveToPosition(-1)
while (cursor.moveToNext()) {
val personId = cursor.getLong(ShowCastColumns.PERSON_ID)
val personName = cursor.getString(PersonColumns.NAME)
val person =
Person(personId, personName, null, null, null, null, null)
val character = cursor.getString(ShowCastColumns.CHARACTER)
castMembers.add(CastMember(character, person))
}
return castMembers
}
val projection = arrayOf(
Tables.SHOW_CAST + "." + ShowCastColumns.ID,
Tables.SHOW_CAST + "." + ShowCastColumns.CHARACTER,
Tables.SHOW_CAST + "." + ShowCastColumns.PERSON_ID,
Tables.PEOPLE + "." + PersonColumns.NAME
)
}
| apache-2.0 | 28678b35a6be757105ac165774bcd8df | 35.722222 | 77 | 0.754917 | 4.122661 | false | false | false | false |
herolynx/elepantry-android | app/src/main/java/com/herolynx/elepantry/ext/google/firebase/db/TagRepository.kt | 1 | 1286 | package com.herolynx.elepantry.ext.google.firebase.db
import com.herolynx.elepantry.repository.Repository
import com.herolynx.elepantry.core.rx.DataEvent
import com.herolynx.elepantry.resources.core.model.Resource
import com.herolynx.elepantry.resources.core.model.Tag
import org.funktionale.option.Option
import org.funktionale.option.firstOption
import rx.Observable
internal class TagRepository(
private val resources: Repository<Resource>
) : Repository<Tag> {
override fun findAll(): Observable<List<Tag>> = resources.findAll()
.map { resources -> resources.flatMap(Resource::tags).toList() }
override fun find(id: String): Observable<Option<Tag>> = findAll()
.map { tags -> tags.filter { t -> t.equals(id, ignoreCase = true) } }
.map { tags -> tags.firstOption() }
override fun asObservable(): Observable<DataEvent<Tag>> = Observable.error(UnsupportedOperationException("Tags stream not supported globally on tags"))
override fun delete(t: Tag): Observable<DataEvent<Tag>> = Observable.error(UnsupportedOperationException("Delete not supported globally on tags"))
override fun save(t: Tag): Observable<DataEvent<Tag>> = Observable.error(UnsupportedOperationException("Save not supported globally on tags"))
} | gpl-3.0 | 9d2192e525a84d273098be4dad365e9d | 44.964286 | 155 | 0.748834 | 4.37415 | false | false | false | false |
dafi/photoshelf | tag-photo-browser/src/main/java/com/ternaryop/photoshelf/tagphotobrowser/activity/TagPhotoBrowserActivity.kt | 1 | 2610 | package com.ternaryop.photoshelf.tagphotobrowser.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.preference.PreferenceManager
import com.ternaryop.compat.os.getSerializableCompat
import com.ternaryop.photoshelf.activity.AbsPhotoShelfActivity
import com.ternaryop.photoshelf.activity.TagPhotoBrowserData
import com.ternaryop.photoshelf.core.prefs.selectedBlogName
import com.ternaryop.photoshelf.fragment.appFragmentFactory
import com.ternaryop.photoshelf.tagphotobrowser.R
import com.ternaryop.photoshelf.tagphotobrowser.fragment.TagPhotoBrowserFragment
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class TagPhotoBrowserActivity : AbsPhotoShelfActivity() {
private lateinit var blogName: String
override val contentViewLayoutId: Int = R.layout.activity_tag_photo_browser
override val contentFrameId: Int = R.id.content_frame
override fun onCreate(savedInstanceState: Bundle?) {
val data = tagPhotoBrowserData(intent.extras)
blogName = data?.blogName ?: checkNotNull(PreferenceManager.getDefaultSharedPreferences(this).selectedBlogName)
supportFragmentManager.fragmentFactory = appFragmentFactory
super.onCreate(savedInstanceState)
}
override fun createFragment(): Fragment =
supportFragmentManager.fragmentFactory.instantiate(
classLoader, TagPhotoBrowserFragment::class.java.name
)
companion object {
private const val EXTRA_TAG_PHOTO_BROWSER_DATA = "com.ternaryop.photoshelf.extra.TAG_PHOTO_BROWSER_DATA"
private const val EXTRA_RETURN_SELECTED_POST = "com.ternaryop.photoshelf.extra.EXTRA_RETURN_SELECTED_POST"
fun createIntent(
context: Context,
tagPhotoBrowserData: TagPhotoBrowserData,
returnSelectedPost: Boolean = false
): Intent {
val intent = Intent(context, TagPhotoBrowserActivity::class.java)
val bundle = Bundle()
bundle.putSerializable(EXTRA_TAG_PHOTO_BROWSER_DATA, tagPhotoBrowserData)
bundle.putBoolean(EXTRA_RETURN_SELECTED_POST, returnSelectedPost)
intent.putExtras(bundle)
return intent
}
fun tagPhotoBrowserData(bundle: Bundle?) =
bundle?.getSerializableCompat(EXTRA_TAG_PHOTO_BROWSER_DATA, TagPhotoBrowserData::class.java)
fun returnSelectedPost(bundle: Bundle?, defaultValue: Boolean = false) =
bundle?.getBoolean(EXTRA_RETURN_SELECTED_POST, defaultValue) ?: defaultValue
}
}
| mit | 6f9de7e81012432d27fade0496929e26 | 41.786885 | 119 | 0.753257 | 4.878505 | false | false | false | false |
dafi/photoshelf | tumblr-dialog/src/main/java/com/ternaryop/photoshelf/tumblr/dialog/editor/fragment/PostEditorFragment.kt | 1 | 10348 | package com.ternaryop.photoshelf.tumblr.dialog.editor.fragment
import android.content.SharedPreferences
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.Spinner
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.MenuProvider
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ternaryop.compat.os.getSerializableCompat
import com.ternaryop.photoshelf.lifecycle.EventObserver
import com.ternaryop.photoshelf.lifecycle.Status
import com.ternaryop.photoshelf.mru.adapter.MRUHolder
import com.ternaryop.photoshelf.tumblr.dialog.EditPostEditorData
import com.ternaryop.photoshelf.tumblr.dialog.NewPostEditorData
import com.ternaryop.photoshelf.tumblr.dialog.PostEditorData
import com.ternaryop.photoshelf.tumblr.dialog.PostViewModel
import com.ternaryop.photoshelf.tumblr.dialog.R
import com.ternaryop.photoshelf.tumblr.dialog.TumblrPostDialog.Companion.ARG_POST_DATA
import com.ternaryop.photoshelf.tumblr.dialog.TumblrPostDialog.Companion.EXTRA_MAX_HIGHLIGHTED_TAGS_MRU_ITEMS
import com.ternaryop.photoshelf.tumblr.dialog.TumblrPostDialog.Companion.EXTRA_MAX_TAGS_MRU_ITEMS
import com.ternaryop.photoshelf.tumblr.dialog.TumblrPostDialog.Companion.EXTRA_THUMBNAILS_ITEMS
import com.ternaryop.photoshelf.tumblr.dialog.TumblrPostDialog.Companion.EXTRA_THUMBNAILS_SIZE
import com.ternaryop.photoshelf.tumblr.dialog.TumblrPostModelResult
import com.ternaryop.photoshelf.tumblr.dialog.editor.AbsTumblrPostEditor
import com.ternaryop.photoshelf.tumblr.dialog.editor.EditTumblrPostEditor
import com.ternaryop.photoshelf.tumblr.dialog.editor.NewTumblrPostEditor
import com.ternaryop.photoshelf.tumblr.dialog.editor.adapter.ThumbnailAdapter
import com.ternaryop.photoshelf.tumblr.dialog.editor.finishActivity
import com.ternaryop.photoshelf.tumblr.dialog.editor.viewholder.TagsHolder
import com.ternaryop.photoshelf.tumblr.dialog.editor.viewholder.TitleHolder
import com.ternaryop.photoshelf.util.menu.enableAll
import dagger.hilt.android.AndroidEntryPoint
private const val BLOG_VISIBLE_PREF_NAME = "postEditorIsBlogVisible"
private const val THUMBNAIL_VISIBLE_PREF_NAME = "postEditorIsThumbnailListVisible"
private const val DEFAULT_THUMBNAIL_SIZE = 75
fun Map<String, Any>?.getInt(preferences: SharedPreferences, key: String, defaultValue: Int): Int {
return this?.get(key) as? Int ?: preferences.getInt(key, defaultValue)
}
@AndroidEntryPoint
class PostEditorFragment :
Fragment(),
MenuProvider {
private lateinit var tumblrPostAction: AbsTumblrPostEditor
private lateinit var preferences: SharedPreferences
private val viewModel: PostViewModel by viewModels()
private lateinit var blogSpinner: Spinner
private lateinit var refreshBlogButton: ImageButton
private lateinit var thumbnailsRecyclerView: RecyclerView
val supportActionBar: ActionBar?
get() = (activity as AppCompatActivity).supportActionBar
private var isOptionsMenuEnabled = false
set(value) {
field = value
requireActivity().invalidateOptionsMenu()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_tumblr_post, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
preferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
viewModel.result.observe(
requireActivity(),
EventObserver { result ->
when (result) {
is TumblrPostModelResult.TitleParsed -> onTitleParsed(result)
is TumblrPostModelResult.MisspelledInfo -> onMisspelledInfo(result)
}
}
)
blogSpinner = view.findViewById(R.id.blog)
refreshBlogButton = view.findViewById(R.id.refreshBlogList)
thumbnailsRecyclerView = view.findViewById(R.id.thumbnail)
val data = checkNotNull(arguments?.getSerializableCompat(ARG_POST_DATA, PostEditorData::class.java))
val tagsHolder = TagsHolder(requireContext(), view.findViewById(R.id.post_tags), data.blogName)
val titleHolder = TitleHolder(view.findViewById(R.id.post_title), data.sourceTitle, data.htmlSourceTitle)
val maxMruItems = data.extras.getInt(
preferences,
EXTRA_MAX_TAGS_MRU_ITEMS,
resources.getInteger(R.integer.post_editor_max_mru_items)
)
val maxHighlightedMruItems = data.extras.getInt(
preferences,
EXTRA_MAX_HIGHLIGHTED_TAGS_MRU_ITEMS,
resources.getInteger(R.integer.post_editor_max_highlighted_items)
)
val mruHolder = MRUHolder(
requireContext(),
view.findViewById(R.id.mru_list),
maxMruItems,
maxHighlightedMruItems,
tagsHolder
)
requireActivity().addMenuProvider(this, viewLifecycleOwner, Lifecycle.State.RESUMED)
tumblrPostAction = when (data) {
is EditPostEditorData -> EditTumblrPostEditor(data, titleHolder, tagsHolder, mruHolder)
is NewPostEditorData -> NewTumblrPostEditor(data, titleHolder, tagsHolder, mruHolder)
.apply { lifecycle.addObserver(this) }
else -> error("Unknown post data")
}
showBlogList()
showThumbnails()
setupThumbnails(data)
supportActionBar?.subtitle = data.blogName
tumblrPostAction.setupUI(supportActionBar, view)
isOptionsMenuEnabled = false
fillTags(data.tags)
}
private fun showThumbnails() {
thumbnailsRecyclerView.visibility = if (preferences.getBoolean(THUMBNAIL_VISIBLE_PREF_NAME, true)) {
View.VISIBLE
} else {
View.GONE
}
}
private fun showBlogList() {
val visibility = if (preferences.getBoolean(BLOG_VISIBLE_PREF_NAME, true)) {
View.VISIBLE
} else {
View.GONE
}
blogSpinner.visibility = visibility
refreshBlogButton.visibility = visibility
}
@Suppress("UNCHECKED_CAST")
private fun setupThumbnails(data: PostEditorData) {
(data.extras?.get(EXTRA_THUMBNAILS_ITEMS) as? List<String>)?.also { thumbnails ->
val context = thumbnailsRecyclerView.context
val size = (data.extras[EXTRA_THUMBNAILS_SIZE] as? Int) ?: DEFAULT_THUMBNAIL_SIZE
val adapter = ThumbnailAdapter(context, size)
adapter.addAll(thumbnails)
thumbnailsRecyclerView.adapter = adapter
thumbnailsRecyclerView.setHasFixedSize(true)
thumbnailsRecyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
}
}
override fun onCreateMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.tumblr_post_edit, menu)
}
override fun onPrepareMenu(menu: Menu) {
tumblrPostAction.onPrepareMenu(menu)
menu.findItem(R.id.toggle_blog_list).isChecked = preferences.getBoolean(BLOG_VISIBLE_PREF_NAME, true)
menu.findItem(R.id.toggle_thumbnails).isChecked = preferences.getBoolean(THUMBNAIL_VISIBLE_PREF_NAME, true)
menu.enableAll(isOptionsMenuEnabled)
}
override fun onMenuItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.parse_title -> {
viewModel.parse(tumblrPostAction.titleHolder.plainTitle, false)
true
}
R.id.parse_title_swap -> {
viewModel.parse(tumblrPostAction.titleHolder.plainTitle, true)
true
}
R.id.source_title -> {
tumblrPostAction.titleHolder.restoreSourceTitle()
true
}
R.id.toggle_blog_list -> {
item.isChecked = !item.isChecked
preferences.edit().putBoolean(BLOG_VISIBLE_PREF_NAME, item.isChecked).apply()
showBlogList()
true
}
R.id.toggle_thumbnails -> {
item.isChecked = !item.isChecked
preferences.edit().putBoolean(THUMBNAIL_VISIBLE_PREF_NAME, item.isChecked).apply()
showThumbnails()
true
}
else -> {
val result = tumblrPostAction.execute(item) ?: return false
result.finishActivity(requireActivity())
true
}
}
}
private fun onTitleParsed(result: TumblrPostModelResult.TitleParsed) {
when (result.command.status) {
Status.SUCCESS -> result.command.data?.also { data ->
tumblrPostAction.titleHolder.htmlTitle = data.html
fillTags(data.tags)
}
Status.ERROR -> result.command.error?.also { error ->
AlertDialog.Builder(requireContext())
.setTitle(R.string.parsing_error)
.setMessage(error.localizedMessage)
.show()
}
Status.PROGRESS -> {}
}
}
private fun onMisspelledInfo(result: TumblrPostModelResult.MisspelledInfo) {
isOptionsMenuEnabled = true
when (result.command.status) {
Status.SUCCESS -> result.command.data?.also { tumblrPostAction.tagsHolder.highlightTagName(it) }
Status.ERROR -> {}
Status.PROGRESS -> {}
}
}
private fun fillTags(tags: List<String>) {
isOptionsMenuEnabled = false
val firstTag = if (tags.isEmpty()) "" else tags[0]
tumblrPostAction.tagsHolder.tags = tags.joinToString(", ")
viewModel.searchMisspelledName(firstTag)
}
}
| mit | 466ecd78d273f529380059fd002a756c | 40.063492 | 118 | 0.688346 | 4.663362 | false | false | false | false |
cout970/Magneticraft | src/main/kotlin/com/cout970/magneticraft/api/internal/registries/generation/OreGenerationRegistry.kt | 2 | 880 | package com.cout970.magneticraft.api.internal.registries.generation
import com.cout970.magneticraft.api.registries.generation.IOreGenerationRegistry
import com.cout970.magneticraft.api.registries.generation.OreGeneration
/**
* Created by cout970 on 2017/07/12.
*/
object OreGenerationRegistry : IOreGenerationRegistry {
private val registered = mutableMapOf<String, OreGeneration>()
override fun isRegistered(oreDictName: String): Boolean = oreDictName in registered
override fun getOreGeneration(oreDictName: String): OreGeneration? = registered[oreDictName]
override fun getRegisteredOres(): MutableMap<String, OreGeneration> = registered.toMutableMap()
override fun registerOreGeneration(gen: OreGeneration): Boolean {
val override = gen.oreDictName in registered
registered += gen.oreDictName to gen
return override
}
} | gpl-2.0 | 72d5d4e3d314f4329934beb656d69e8c | 35.708333 | 99 | 0.778409 | 4.656085 | false | false | false | false |
Light-Team/ModPE-IDE-Source | editorkit/src/main/kotlin/com/brackeys/ui/editorkit/span/ErrorSpan.kt | 1 | 1895 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* 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.brackeys.ui.editorkit.span
import android.content.res.Resources
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.text.style.LineBackgroundSpan
class ErrorSpan(
private val lineWidth: Float = 1 * Resources.getSystem().displayMetrics.density + 0.5f,
private val waveSize: Float = 3 * Resources.getSystem().displayMetrics.density + 0.5f,
private val color: Int = Color.RED
) : LineBackgroundSpan {
override fun drawBackground(
canvas: Canvas,
paint: Paint,
left: Int,
right: Int,
top: Int,
baseline: Int,
bottom: Int,
text: CharSequence,
start: Int,
end: Int,
lineNumber: Int
) {
val width = paint.measureText(text, start, end)
val linePaint = Paint(paint)
linePaint.color = color
linePaint.strokeWidth = lineWidth
val doubleWaveSize = waveSize * 2
var i = left.toFloat()
while (i < left + width) {
canvas.drawLine(i, bottom.toFloat(), i + waveSize, bottom - waveSize, linePaint)
canvas.drawLine(i + waveSize, bottom - waveSize, i + doubleWaveSize, bottom.toFloat(), linePaint)
i += doubleWaveSize
}
}
} | apache-2.0 | d4708fc298ecd31b24bd75914f8386e3 | 32.857143 | 109 | 0.669657 | 4.201774 | false | false | false | false |
pedroSG94/rtmp-streamer-java | rtmp/src/main/java/com/pedro/rtmp/rtmp/message/data/DataAmf0.kt | 1 | 1145 | /*
* Copyright (C) 2021 pedroSG94.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pedro.rtmp.rtmp.message.data
import com.pedro.rtmp.rtmp.chunk.ChunkStreamId
import com.pedro.rtmp.rtmp.chunk.ChunkType
import com.pedro.rtmp.rtmp.message.BasicHeader
import com.pedro.rtmp.rtmp.message.MessageType
/**
* Created by pedro on 21/04/21.
*/
class DataAmf0(name: String = "", timeStamp: Int = 0, streamId: Int = 0, basicHeader: BasicHeader = BasicHeader(ChunkType.TYPE_0, ChunkStreamId.OVER_CONNECTION.mark)):
Data(name, timeStamp, streamId, basicHeader) {
override fun getType(): MessageType = MessageType.DATA_AMF0
} | apache-2.0 | 35f5d1aad6fa0205b720ddc7ddec993c | 37.2 | 167 | 0.751965 | 3.816667 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/recording/DefaultNotificationRecordingService.kt | 1 | 2731 | package net.nemerosa.ontrack.extension.notifications.recording
import net.nemerosa.ontrack.common.Time
import net.nemerosa.ontrack.json.asJson
import net.nemerosa.ontrack.model.pagination.PaginatedList
import net.nemerosa.ontrack.model.security.SecurityService
import net.nemerosa.ontrack.model.support.StorageService
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.Duration
import java.util.*
@Service
@Transactional
class DefaultNotificationRecordingService(
private val storageService: StorageService,
private val securityService: SecurityService,
) : NotificationRecordingService {
override fun clearAll() {
securityService.checkGlobalFunction(NotificationRecordingAccess::class.java)
storageService.deleteWithFilter(STORE)
}
override fun clear(retentionSeconds: Long) {
securityService.checkGlobalFunction(NotificationRecordingAccess::class.java)
val ref = Time.now() - Duration.ofSeconds(retentionSeconds)
storageService.deleteWithFilter(
store = STORE,
query = "data::jsonb->>'timestamp' <= :timestamp",
queryVariables = mapOf(
"timestamp" to Time.store(ref)
)
)
}
override fun filter(filter: NotificationRecordFilter): PaginatedList<NotificationRecord> {
securityService.checkGlobalFunction(NotificationRecordingAccess::class.java)
val queries = mutableListOf<String>()
val queryVariables = mutableMapOf<String, String>()
if (filter.resultType != null) {
queries += "data::jsonb->'result'->>'type' = :resultType"
queryVariables["resultType"] = filter.resultType.name
}
val query = queries.joinToString(" AND ") { "( $it )" }
val total = storageService.count(
store = STORE,
query = query,
queryVariables = queryVariables,
)
val records = storageService.filter(
store = STORE,
type = NotificationRecord::class,
query = query,
queryVariables = queryVariables,
offset = filter.offset,
size = filter.size,
orderQuery = "ORDER BY data::jsonb->>'timestamp' DESC"
)
return PaginatedList.create(records, filter.offset, filter.size, total)
}
override fun record(record: NotificationRecord): String {
val id = UUID.randomUUID().toString()
storageService.store(
STORE,
id,
record,
)
return id
}
companion object {
private val STORE = NotificationRecord::class.java.name
}
} | mit | 783d79b7f2e233bd1dd19863ff3ae6fb | 31.915663 | 94 | 0.661296 | 5.029466 | false | false | false | false |
neo4j-contrib/neo4j-apoc-procedures | extended/src/main/kotlin/apoc/nlp/aws/AWSVirtualEntitiesGraph.kt | 1 | 4326 | package apoc.nlp.aws
import apoc.graph.document.builder.DocumentToGraph
import apoc.nlp.NLPHelperFunctions.mergeRelationship
import apoc.nlp.NLPVirtualGraph
import apoc.result.VirtualGraph
import apoc.result.VirtualNode
import com.amazonaws.services.comprehend.model.BatchDetectEntitiesResult
import org.apache.commons.text.WordUtils
import org.neo4j.graphdb.Label
import org.neo4j.graphdb.Node
import org.neo4j.graphdb.Relationship
import org.neo4j.graphdb.RelationshipType
import org.neo4j.graphdb.Transaction
import java.util.ArrayList
import java.util.LinkedHashMap
data class AWSVirtualEntitiesGraph(private val detectEntitiesResult: BatchDetectEntitiesResult, private val sourceNodes: List<Node>, val relType: RelationshipType, val relProperty: String, val cutoff: Number): NLPVirtualGraph() {
override fun extractDocument(index: Int, sourceNode: Node) : ArrayList<Map<String, Any>> = AWSProcedures.transformResults(index, sourceNode, detectEntitiesResult).value["entities"] as ArrayList<Map<String, Any>>
companion object {
const val LABEL_KEY = "type"
const val SCORE_PROPERTY = "score"
val KEYS = listOf("text", "type")
val LABEL = Label { "Entity" }
val ID_KEYS = listOf("text")
}
override fun createVirtualGraph(transaction: Transaction?): VirtualGraph {
val storeGraph = transaction != null
val allNodes: MutableSet<Node> = mutableSetOf()
val nonSourceNodes: MutableSet<Node> = mutableSetOf()
val allRelationships: MutableSet<Relationship> = mutableSetOf()
sourceNodes.forEachIndexed { index, sourceNode ->
val document = extractDocument(index, sourceNode) as List<Map<String, Any>>
val virtualNodes = LinkedHashMap<MutableSet<String>, MutableSet<Node>>()
val virtualNode = VirtualNode(sourceNode, sourceNode.propertyKeys.toList())
val documentToNodes = DocumentToGraph.DocumentToNodes(nonSourceNodes, transaction)
val entityNodes = mutableSetOf<Node>()
val relationships = mutableSetOf<Relationship>()
for (item in document) {
val labels: Array<Label> = labels(item)
val idValues: Map<String, Any> = idValues(item)
val score = item[SCORE_PROPERTY] as Number
if(score.toDouble() >= cutoff.toDouble()) {
val node = if (storeGraph) {
val entityNode = documentToNodes.getOrCreateRealNode(labels, idValues)
setProperties(entityNode, item)
entityNodes.add(entityNode)
val nodeAndScore = Pair(entityNode, score)
relationships.add(mergeRelationship(sourceNode, nodeAndScore, relType, relProperty))
sourceNode
} else {
val entityNode = documentToNodes.getOrCreateVirtualNode(virtualNodes, labels, idValues)
setProperties(entityNode, item)
entityNodes.add(entityNode)
DocumentToGraph.getNodesWithSameLabels(virtualNodes, labels).add(entityNode)
val nodeAndScore = Pair(entityNode, score)
relationships.add(mergeRelationship(virtualNode, nodeAndScore, relType, relProperty))
virtualNode
}
allNodes.add(node)
}
}
nonSourceNodes.addAll(entityNodes)
allNodes.addAll(entityNodes)
allRelationships.addAll(relationships)
}
return VirtualGraph("Graph", allNodes, allRelationships, emptyMap())
}
private fun idValues(item: Map<String, Any>) = ID_KEYS.map { it to item[it].toString() }.toMap()
private fun labels(item: Map<String, Any>) = arrayOf(LABEL, Label { asLabel(item[LABEL_KEY].toString()) })
private fun asLabel(value: String) : String {
return WordUtils.capitalizeFully(value, '_', ' ')
.replace("_".toRegex(), "")
.replace(" ".toRegex(), "")
}
private fun setProperties(entityNode: Node, item: Map<String, Any>) {
for (key in KEYS) {
entityNode.setProperty(key, item[key].toString())
}
}
} | apache-2.0 | bfe24831240e2aadc7521097af7b912d | 42.27 | 229 | 0.642164 | 4.727869 | false | false | false | false |
oboehm/jfachwert | src/main/kotlin/de/jfachwert/post/PLZ.kt | 1 | 8919 | /*
* Copyright (c) 2017-2020 by Oliver Boehm
*
* 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.
*
* (c)reated 21.02.2017 by oboehm ([email protected])
*/
package de.jfachwert.post
import de.jfachwert.KSimpleValidator
import de.jfachwert.Text
import de.jfachwert.pruefung.LengthValidator
import de.jfachwert.pruefung.NullValidator
import de.jfachwert.pruefung.NumberValidator
import de.jfachwert.pruefung.exception.InvalidValueException
import org.apache.commons.lang3.Range
import org.apache.commons.lang3.StringUtils
import java.math.BigDecimal
import java.util.*
/**
* Eine Postleitzahl (PLZ) kennzeichnet den Zustellort auf Briefen, Paketten
* oder Paeckchen. In Deutschland ist es eine 5-stellige Zahl, wobei auch
* "0" als fuehrende Ziffer erlaubt ist.
*
* Vor der Postleitzahl kann auch noch eine Kennung (wie 'D' fuer Deutschland)
* stehen. Diese wird mit abgespeichert, wenn sie angegeben ist.
*
* @author oboehm
* @since 0.2.0 (10.04.2017)
*/
open class PLZ : Text {
/**
* Hierueber wird eine Postleitzahl angelegt.
*
* @param plz z.B. "70839" oder "D-70839"
*/
constructor(plz: String) : super(plz, VALIDATOR) {}
/**
* Hierueber wird eine Postleitzahl angelegt.
*
* @param plz z.B. "70839" oder "D-70839"
* @param validator fuer die Ueberpruefung
*/
constructor(plz: String, validator: KSimpleValidator<String>) : super(plz, validator) {}
/**
* Ueber diesen Konstruktor kann die Landeskennung als extra Parameter
* angegeben werden.
*
* @param landeskennung z.B. "D"
* @param plz z.B. "70839" (fuer Gerlingen)
*/
constructor(landeskennung: String, plz: String) : this(landeskennung + plz) {}
/**
* Ueber diesen Konstruktor kann die Landeskennung als extra Parameter
* angegeben werden.
*
* @param land z.B. "de_DE"
* @param plz z.B. "70839" (fuer Gerlingen)
*/
constructor(land: Locale, plz: String) : this(toLandeskennung(land) + plz) {}
/**
* Hierueber kann man abfragen, ob der Postleitzahl eine Landeskennung
* vorangestellt ist.
*
* @return true, falls PLZ eine Kennung besitzt
*/
fun hasLandeskennung(): Boolean {
return hasLandeskennung(code)
}
/**
* Liefert die Landeskennung als String. Wenn keine Landeskennung
* angegeben wurde, wird eine Exception geworfen.
*
* @return z.B. "D" fuer Deutschland
*/
val landeskennung: String
get() {
check(this.hasLandeskennung()) { "keine Landeskennung angegeben" }
return getLandeskennung(code)
}
/**
* Liefert das Land, die der Landeskennung entspricht.
*
* @return z.B. "de_CH" (fuer die Schweiz)
*/
val land: Locale
get() {
val kennung = landeskennung
return when (kennung) {
"D" -> Locale("de", "DE")
"A" -> Locale("de", "AT")
"CH" -> Locale("de", "CH")
else -> throw UnsupportedOperationException("unbekannte Landeskennung '$kennung'")
}
}
/**
* Liefert die eigentliche Postleitzahl ohne Landeskennung.
*
* @return z,B. "01001"
*/
val postleitZahl: String
get() = getPostleitZahl(code)
/**
* Liefert die PLZ in kompakter Schreibweise (ohne Trennzeichen zwischen
* Landeskennung und eigentlicher PLZ) zurueck.
*
* @return z.B. "D70839"
*/
fun toShortString(): String {
return code
}
/**
* Liefert die PLZ in mit Trennzeichen zwischen Landeskennung (falls
* vorhanden) und eigentlicher PLZ zurueck.
*
* @return z.B. "D-70839"
*/
fun toLongString(): String {
var plz = code
if (this.hasLandeskennung()) {
plz = toLongString(plz)
}
return plz
}
/**
* Aus Lesbarkeitsgruenden wird zwischen Landeskennung und eigentlicher PLZ
* ein Trennzeichen mit ausgegeben.
*
* @return z.B. "D-70839"
*/
override fun toString(): String {
return this.toLongString()
}
/**
* In dieser Klasse sind die Validierungsregeln der diversen
* PLZ-Validierungen zusammengefasst. Fuer Deutschland gilt z.B.:
*
* * Eine PLZ besteht aus 5 Ziffern.
* * Steht an erster Stelle eine 0, folgt darauf eine Zahl zwischen
* 1 und 9.
* * Steht an erster Stelle eine Zahl zwischen 1 und 9, folgt darauf
* eine Zahl zwischen 0 und 9.
* * An den letzten drei Stellen steht eine Zahl zwischen 0 und 9.
*
* Will man eine PLZ online fuer verschiedene Laender validieren, kann man
* auf [Zippotam](http://api.zippopotam.us/) zurueckgreifen.
*/
class Validator : KSimpleValidator<String> {
/**
* Eine Postleitahl muss zwischen 3 und 10 Ziffern lang sein. Eventuell
* kann noch die Laenderkennung vorangestellt werden. Dies wird hier
* ueberprueft.
*
* @param code die PLZ
* @return die validierte PLZ (zur Weiterverarbeitung)
*/
override fun validate(code: String): String {
var plz = normalize(code)
if (hasLandeskennung(plz)) {
validateNumberOf(plz)
} else {
plz = LengthValidator.validate(plz, 3, 10)
if (plz.length == 5) {
validateNumberDE(plz)
}
}
return plz
}
companion object {
private fun validateNumberOf(plz: String) {
val kennung = getLandeskennung(plz)
val zahl = getPostleitZahl(plz)
when (kennung) {
"D" -> {
validateNumberDE(zahl)
validateNumberWith(plz, 6, zahl)
}
"CH" -> validateNumberWith(plz, 6, zahl)
"A" -> validateNumberWith(plz, 5, zahl)
else -> LengthValidator.validate(zahl, 3, 10)
}
}
private fun validateNumberWith(plz: String, length: Int, zahl: String) {
LengthValidator.validate(plz, length)
NumberValidator(BigDecimal.ZERO, BigDecimal.TEN.pow(length)).validate(zahl)
}
private fun validateNumberDE(plz: String) {
val n = plz.toInt()
if (n < 1067 || n > 99998) {
throw InvalidValueException(plz, "postal_code", Range.between("01067", "99998"))
}
}
private fun normalize(plz: String): String {
return StringUtils.replaceChars(plz, " -", "").toUpperCase()
}
}
}
companion object {
private val VALIDATOR: KSimpleValidator<String> = Validator()
private val WEAK_CACHE = WeakHashMap<String, PLZ>()
/** Null-Wert fuer Initialisierung. */
@JvmField
val NULL = PLZ("00000", NullValidator())
private fun toLandeskennung(locale: Locale): String {
val country = locale.country.toUpperCase()
return when (country) {
"AT", "DE" -> country.substring(0, 1)
else -> country
}
}
/**
* Liefert eine PLZ zurueck.
*
* @param plz PLZ als String
* @return PLZ
*/
@JvmStatic
fun of(plz: String): PLZ {
return WEAK_CACHE.computeIfAbsent(plz) { s: String -> PLZ(s) }
}
private fun hasLandeskennung(plz: String): Boolean {
val kennung = plz[0]
return Character.isLetter(kennung)
}
private fun getLandeskennung(plz: String): String {
return StringUtils.substringBefore(toLongString(plz), "-")
}
private fun getPostleitZahl(plz: String): String {
return if (!hasLandeskennung(plz)) {
plz
} else StringUtils.substringAfter(toLongString(plz), "-")
}
private fun toLongString(plz: String): String {
val i = StringUtils.indexOfAny(plz, "0123456789")
if (i < 0) {
throw InvalidValueException(plz, "postal_code")
}
return plz.substring(0, i) + "-" + plz.substring(i)
}
}
} | apache-2.0 | 49c6182741c005f65a6d22674b7436c4 | 30.298246 | 100 | 0.583137 | 3.624137 | false | false | false | false |
dewarder/Android-Kotlin-Commons | akommons/src/main/java/com/dewarder/akommons/content/Context.kt | 1 | 8651 | /*
* Copyright (C) 2017 Artem Hluhovskyi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
@file:[Suppress("unused")]
package com.dewarder.akommons.content
import android.Manifest
import android.animation.Animator
import android.animation.AnimatorInflater
import android.app.Activity
import android.app.PendingIntent
import android.app.Service
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.ColorStateList
import android.content.res.Configuration
import android.content.res.TypedArray
import android.graphics.drawable.Drawable
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Build
import android.support.annotation.*
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.Toast
import com.dewarder.akommons.content.res.use
/**
* Creates intent for specified [T] component of Android.
*
* @param action - value passed to [Intent.setAction]
* @param flags - value passed to [Intent.setFlags]
*/
inline fun <reified T : Any> Context.intentFor(
action: String? = null,
flags: Int = -1
): Intent = Intent(this, T::class.java).apply {
this.action = action
this.flags = flags
}
/**
* Creates intent for specified [T] component of Android and
* initialize it with [init] block.
*/
inline fun <reified T : Any> Context.intentFor(
action: String? = null,
flags: Int = -1,
init: Intent.() -> Unit
): Intent = intentFor<T>(action, flags).apply(init)
/**
* Activities
*/
inline fun <reified T : Activity> Context.startActivity(
action: String? = null,
flags: Int = -1
) = startActivity(intentFor<T>(action, flags))
inline fun <reified T : Activity> Context.startActivity(
action: String? = null,
flags: Int = -1,
init: Intent.() -> Unit
) = startActivity(intentFor<T>(action, flags, init))
/**
* Services
*/
inline fun <reified T : Service> Context.startService(
action: String? = null
): ComponentName = startService(intentFor<T>(action = action))
inline fun <reified T : Service> Context.startService(
action: String? = null,
init: Intent.() -> Unit
): ComponentName = startService(intentFor<T>(action = action, init = init))
fun Context.browse(url: String) {
browse(Uri.parse(url))
}
fun Context.browse(uri: Uri) {
startActivity(Intent(Intent.ACTION_VIEW, uri))
}
/**
* PendingIntent
*/
inline fun <reified T : Any> Context.pendingIntentFor(
intent: Intent,
requestCode: Int = 0,
pendingIntentFlags: Int = 0
): PendingIntent = T::class.java.let { clazz ->
when {
Activity::class.java.isAssignableFrom(clazz) ->
PendingIntent.getActivity(this, requestCode, intent, pendingIntentFlags)
Service::class.java.isAssignableFrom(clazz) ->
PendingIntent.getService(this, requestCode, intent, pendingIntentFlags)
BroadcastReceiver::class.java.isAssignableFrom(clazz) ->
PendingIntent.getBroadcast(this, requestCode, intent, pendingIntentFlags)
else -> throw IllegalStateException("PendingIntent must be used only with Activity, Service or BroadcastReceiver")
}
}
inline fun <reified T : Any> Context.pendingIntentFor(
action: String? = null,
intentFlags: Int = -1,
requestCode: Int = 0,
pendingIntentFlags: Int = 0
): PendingIntent = pendingIntentFor<T>(
intent = intentFor<T>(action, intentFlags),
requestCode = requestCode,
pendingIntentFlags = pendingIntentFlags
)
inline fun <reified T : Any> Context.pendingIntentFor(
action: String? = null,
intentFlags: Int = -1,
requestCode: Int = 0,
pendingIntentFlags: Int = 0,
init: Intent.() -> Unit
): PendingIntent = pendingIntentFor<T>(
intent = intentFor<T>(action, intentFlags, init),
requestCode = requestCode,
pendingIntentFlags = pendingIntentFlags
)
/**
* Shows short [Toast] with specified string resource.
*/
fun Context.showShortToast(@StringRes resId: Int) {
Toast.makeText(this, resId, Toast.LENGTH_SHORT).show()
}
fun Context.showShortToast(text: String) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
fun Context.showLongToast(@StringRes resId: Int) {
Toast.makeText(this, resId, Toast.LENGTH_LONG).show()
}
fun Context.showLongToast(text: String) {
Toast.makeText(this, text, Toast.LENGTH_LONG).show()
}
/**
* Resources
*/
fun Context.getAnimation(@AnimRes id: Int): Animation =
AnimationUtils.loadAnimation(this, id)
fun Context.getAnimator(@AnimatorRes id: Int): Animator =
AnimatorInflater.loadAnimator(this, id)
/**
* ContextCompat
*/
fun Context.getThemedColor(@ColorRes resId: Int): Int =
ContextCompat.getColor(this, resId)
fun Context.getThemedColorStateList(@ColorRes resId: Int): ColorStateList =
ContextCompat.getColorStateList(this, resId)
fun Context.getThemedDrawable(@DrawableRes resId: Int): Drawable =
ContextCompat.getDrawable(this, resId)
/**
* Other
*/
val Context.isRtl: Boolean
get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL
} else {
false
}
val Context.isLtr: Boolean
get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_LTR
} else {
true
}
val Context.isLandscape: Boolean
get() = resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
val Context.isPortrait: Boolean
get() = resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
fun Context.convertToDp(pixels: Int): Int =
(pixels * resources.displayMetrics.density).toInt()
fun Context.convertToSp(pixels: Int): Int =
(pixels * resources.displayMetrics.scaledDensity).toInt()
fun Context.inflate(
@LayoutRes layoutId: Int,
root: ViewGroup? = null,
attachToRoot: Boolean = false
): View = LayoutInflater.from(this).inflate(layoutId, root, attachToRoot)
fun Context.isPackageInstalled(packageName: String): Boolean = try {
packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES)
true
} catch (e: PackageManager.NameNotFoundException) {
false
}
/**
* Connections
*/
@get:RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
val Context.hasConnection: Boolean
get() = connectivityManager.activeNetworkInfo?.isConnectedOrConnecting ?: false
@get:RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
val Context.isConnectedToWifi: Boolean
get() = connectivityManager.activeNetworkInfo?.type == ConnectivityManager.TYPE_WIFI
@get:RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
inline val Context.isConnectedToMobile: Boolean
get() = connectivityManager.activeNetworkInfo?.type == ConnectivityManager.TYPE_MOBILE
/**
* Use styled attributes [TypedArray] ensuring it's recycled afterwards
*/
inline fun <R> Context.useStyledAttributes(@StyleableRes attrs: IntArray,
block: (TypedArray) -> R): R
= obtainStyledAttributes(attrs).use(block)
inline fun <R> Context.useStyledAttributes(@StyleRes resId: Int,
@StyleableRes attrs: IntArray,
block: (TypedArray) -> R): R
= obtainStyledAttributes(resId, attrs).use(block)
inline fun <R> Context.useStyledAttributes(set: AttributeSet,
@StyleableRes attrs: IntArray,
@AttrRes defStyleAttr: Int = 0,
@StyleRes defStyleRes: Int = 0,
block: (TypedArray) -> R): R
= obtainStyledAttributes(set, attrs, defStyleAttr, defStyleRes).use(block) | apache-2.0 | 12d7562eed0f4c407fe25853b84f5234 | 30.926199 | 122 | 0.707548 | 4.280554 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.