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
songful/PocketHub
app/src/main/java/com/github/pockethub/android/ui/item/issue/IssueHeaderItem.kt
1
5462
package com.github.pockethub.android.ui.item.issue import android.content.Context import android.text.TextUtils import android.view.View.GONE import android.view.View.VISIBLE import android.widget.LinearLayout import androidx.text.bold import androidx.text.buildSpannedString import com.github.pockethub.android.R import com.github.pockethub.android.util.android.text.append import com.github.pockethub.android.core.issue.IssueUtils import com.github.pockethub.android.ui.issue.LabelDrawableSpan import com.github.pockethub.android.ui.view.OcticonTextView.ICON_COMMIT import com.github.pockethub.android.util.AvatarLoader import com.github.pockethub.android.util.HttpImageGetter import com.meisolsson.githubsdk.model.Issue import com.meisolsson.githubsdk.model.IssueState import com.xwray.groupie.kotlinandroidextensions.Item import com.xwray.groupie.kotlinandroidextensions.ViewHolder import kotlinx.android.synthetic.main.issue_header.* import kotlinx.android.synthetic.main.milestone.* class IssueHeaderItem( private val avatarLoader: AvatarLoader, private val imageGetter: HttpImageGetter, private val context: Context, private val actionListener: OnIssueHeaderActionListener, val issue: Issue ) : Item(issue.id()!!) { override fun getLayout() = R.layout.issue_header override fun bind(holder: ViewHolder, position: Int) { holder.tv_issue_title.text = issue.title() val body = issue.bodyHtml() if (!TextUtils.isEmpty(body)) { imageGetter.bind(holder.tv_issue_body, body, issue.id()) } else { holder.tv_issue_body.setText(R.string.no_description_given) } holder.tv_issue_author.text = issue.user()!!.login() holder.tv_issue_creation_date.text = buildSpannedString { append("${context.getString(R.string.prefix_opened)}${issue.createdAt()}") } avatarLoader.bind(holder.iv_avatar, issue.user()) if (IssueUtils.isPullRequest(issue) && issue.pullRequest()!!.commits() != null && issue.pullRequest()!!.commits()!! > 0 ) { holder.ll_issue_commits.visibility = VISIBLE holder.tv_commit_icon.text = ICON_COMMIT val commits = context.getString( R.string.pull_request_commits, issue.pullRequest()!!.commits() ) holder.tv_pull_request_commits.text = commits } else { holder.ll_issue_commits.visibility = GONE } val open = IssueState.Open == issue.state() if (!open) { holder.tv_state.text = buildSpannedString { bold { append(context.getString(R.string.closed)) } val closedAt = issue.closedAt() if (closedAt != null) { append(' ') append(closedAt) } } holder.tv_state.visibility = VISIBLE } else { holder.tv_state.visibility = GONE } val assignee = issue.assignee() if (assignee != null) { holder.tv_assignee_name.text = buildSpannedString { bold { append(assignee.login()) } append(" ${context.getString(R.string.assigned)}") } holder.iv_assignee_avatar.visibility = VISIBLE avatarLoader.bind(holder.iv_assignee_avatar, assignee) } else { holder.iv_assignee_avatar.visibility = GONE holder.tv_assignee_name.setText(R.string.unassigned) } val labels = issue.labels() if (labels != null && !labels.isEmpty()) { LabelDrawableSpan.setText(holder.tv_labels, labels) holder.tv_labels.visibility = VISIBLE } else { holder.tv_labels.visibility = GONE } if (issue.milestone() != null) { val milestone = issue.milestone() holder.tv_milestone.text = buildSpannedString { append("${context.getString(R.string.milestone_prefix)} ") bold { append(milestone!!.title()) } } val closed = milestone!!.closedIssues()!!.toFloat() val total = closed + milestone.openIssues()!! if (total > 0) { (holder.v_closed.layoutParams as LinearLayout.LayoutParams).weight = closed / total holder.v_closed.visibility = VISIBLE } else { holder.v_closed.visibility = GONE } holder.ll_milestone.visibility = VISIBLE } else { holder.ll_milestone.visibility = GONE } holder.ll_issue_commits.setOnClickListener { _ -> actionListener.onCommitsClicked() } holder.tv_state.setOnClickListener { _ -> actionListener.onStateClicked() } holder.ll_milestone.setOnClickListener { _ -> actionListener.onMilestonesClicked() } holder.ll_assignee.setOnClickListener { _ -> actionListener.onAssigneesClicked() } holder.tv_labels.setOnClickListener { _ -> actionListener.onLabelsClicked() } } interface OnIssueHeaderActionListener { fun onCommitsClicked() fun onStateClicked() fun onMilestonesClicked() fun onAssigneesClicked() fun onLabelsClicked() } }
apache-2.0
bb649580b8b60441098e98c58cbb0010
35.172185
99
0.612596
4.620981
false
false
false
false
spotify/heroic
heroic-component/src/main/java/com/spotify/heroic/metadata/WriteMetadata.kt
1
2314
/* * Copyright (c) 2019 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * 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.spotify.heroic.metadata import com.spotify.heroic.cluster.ClusterShard import com.spotify.heroic.common.DateRange import com.spotify.heroic.common.RequestTimer import com.spotify.heroic.common.Series import com.spotify.heroic.metric.RequestError import com.spotify.heroic.metric.ShardError import eu.toolchain.async.Collector import eu.toolchain.async.Transform data class WriteMetadata( val errors: List<RequestError> = listOf(), val times: List<Long> = listOf() ) { constructor(time: Long): this(times = listOf(time)) companion object { @JvmStatic fun shardError(shard: ClusterShard): Transform<Throwable, WriteMetadata> { return Transform { e: Throwable -> WriteMetadata(errors = listOf(ShardError.fromThrowable(shard, e))) } } @JvmStatic fun reduce(): Collector<WriteMetadata, WriteMetadata> { return Collector { requests: Collection<WriteMetadata> -> val errors = mutableListOf<RequestError>() val times = mutableListOf<Long>() requests.forEach { errors.addAll(it.errors) times.addAll(it.times) } WriteMetadata(errors.toList(), times.toList()) } } @JvmStatic fun timer(): RequestTimer<WriteMetadata> = RequestTimer(::WriteMetadata) } data class Request(val series: Series, val range: DateRange) }
apache-2.0
19fcf2ee5dab739709e08143434fa47e
35.746032
93
0.687986
4.475822
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/ide/browsers/impl/WebBrowserServiceImpl.kt
4
3325
// 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.ide.browsers.impl import com.intellij.ide.browsers.* import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.DumbService import com.intellij.psi.PsiElement import com.intellij.testFramework.LightVirtualFile import com.intellij.util.Url import com.intellij.util.Urls import com.intellij.util.containers.ContainerUtil import java.util.* import java.util.stream.Stream private val URL_PROVIDER_EP = ExtensionPointName<WebBrowserUrlProvider>("com.intellij.webBrowserUrlProvider") class WebBrowserServiceImpl : WebBrowserService() { companion object { fun getProviders(request: OpenInBrowserRequest): Stream<WebBrowserUrlProvider> { val dumbService = DumbService.getInstance(request.project) return URL_PROVIDER_EP.extensions().filter { (!dumbService.isDumb || DumbService.isDumbAware(it)) && it.canHandleElement(request) } } fun getDebuggableUrls(context: PsiElement?): Collection<Url> { try { val request = if (context == null) null else createOpenInBrowserRequest(context) if (request == null || WebBrowserXmlService.getInstance().isXmlLanguage(request.file.viewProvider.baseLanguage)) { return emptyList() } else { // it is client responsibility to set token request.isAppendAccessToken = false request.reloadMode = ReloadMode.DISABLED return getProviders(request) .map { getUrls(it, request) } .filter(Collection<*>::isNotEmpty).findFirst().orElse(Collections.emptyList()) } } catch (ignored: WebBrowserUrlProvider.BrowserException) { return emptyList() } } @JvmStatic fun getDebuggableUrl(context: PsiElement?): Url? = ContainerUtil.getFirstItem(getDebuggableUrls(context)) } override fun getUrlsToOpen(request: OpenInBrowserRequest, preferLocalUrl: Boolean): Collection<Url> { val isHtmlOrXml = WebBrowserXmlService.getInstance().isHtmlOrXmlFile(request.file) if (!preferLocalUrl || !isHtmlOrXml) { val dumbService = DumbService.getInstance(request.project) for (urlProvider in URL_PROVIDER_EP.extensionList) { if ((!dumbService.isDumb || DumbService.isDumbAware(urlProvider)) && urlProvider.canHandleElement(request)) { val urls = getUrls(urlProvider, request) if (!urls.isEmpty()) { return urls } } } if (!isHtmlOrXml && !request.isForceFileUrlIfNoUrlProvider) { return emptyList() } } val file = if (!request.file.viewProvider.isPhysical) null else request.virtualFile return if (file is LightVirtualFile || file == null) emptyList() else listOf(Urls.newFromVirtualFile(file)) } } private fun getUrls(provider: WebBrowserUrlProvider?, request: OpenInBrowserRequest): Collection<Url> { if (provider != null) { request.result?.let { return it } try { return provider.getUrls(request) } catch (e: WebBrowserUrlProvider.BrowserException) { if (!WebBrowserXmlService.getInstance().isHtmlFile(request.file)) { throw e } } } return emptyList() }
apache-2.0
9e23319ad12a3a51ffc899dd66c78549
37.229885
140
0.704361
4.605263
false
false
false
false
earizon/java-vertx-ledger
src/main/java/com/everis/everledger/impl/manager/SimpleTransferManagerMod.kt
1
10744
package com.everis.everledger.impl.manager import io.vertx.core.json.JsonObject import java.time.ZonedDateTime import java.util.HashMap import java.util.HashSet // import java.util.Map // import java.util.List import java.util.ArrayList // import java.util.Set import java.util.UUID import javax.money.MonetaryAmount import org.interledger.Condition import org.interledger.Fulfillment import org.interledger.ledger.model.TransferStatus //import org.javamoney.moneta.Money // import org.slf4j.Logger import org.slf4j.LoggerFactory import com.everis.everledger.handlers.TransferWSEventHandler import com.everis.everledger.ifaces.account.IfaceLocalAccount import com.everis.everledger.ifaces.transfer.IfaceTransfer import com.everis.everledger.ifaces.transfer.IfaceTransferManager import com.everis.everledger.util.ConversionUtil import com.everis.everledger.util.ILPExceptionSupport import com.everis.everledger.util.Config import com.everis.everledger.impl.SimpleTransfer import com.everis.everledger.impl.CC_NOT_PROVIDED import com.everis.everledger.ifaces.transfer.ILocalTransfer import com.everis.everledger.impl.ILPSpec2LocalTransferID import com.everis.everledger.impl.manager.SimpleAccountManager /** * Simple in-memory {@code SimpleLedgerTransferManager}. * * @author earizon * * FIXME: * All the @Override methods will be transactional in a real database * JEE / Hibernate / ... . Mark them "somehow" * REF: * - http://docs.oracle.com/cd/E23095_01/Platform.93/ATGProgGuide/html/s1205transactiondemarcation01.html * - http://docs.oracle.com/javaee/6/tutorial/doc/bncij.html * - ... */ private val log = LoggerFactory.getLogger(SimpleTransferManager::class.java) private val accountManager = SimpleAccountManager // fun getTransferManager() : IfaceTransferManager { // // TODO:(1) Move function to factory similar to LedgerAccountManagerFactory // return singleton // } private fun notifyUpdate(transfer : IfaceTransfer, fulfillment : Fulfillment, isExecution : Boolean){ try { val notification : JsonObject = (transfer as SimpleTransfer).toILPJSONStringifiedFormat() // Notify affected accounts: val eventType : TransferWSEventHandler.EventType = if (transfer.getTransferStatus() == TransferStatus.PROPOSED) TransferWSEventHandler.EventType.TRANSFER_CREATE else TransferWSEventHandler.EventType.TRANSFER_UPDATE val setAffectedAccounts = HashSet<String>() for (debit in transfer.debits ) setAffectedAccounts.add( debit.localAccount.localID) for (credit in transfer.credits) setAffectedAccounts.add(credit.localAccount.localID) val relatedResources = HashMap<String, Any>() val relatedResourceKey = if (isExecution) "execution_condition_fulfillment" else "cancellation_condition_fulfillment" val base64FF = ConversionUtil.fulfillmentToBase64(fulfillment) relatedResources.put( relatedResourceKey, base64FF) val jsonRelatedResources = JsonObject(relatedResources) TransferWSEventHandler.notifyListener(setAffectedAccounts, eventType, notification, jsonRelatedResources) } catch (e : Exception ) { log.warn("Fulfillment registrered correctly but ilp-connector couldn't be notified due to " + e.toString()) } } object SimpleTransferManager : IfaceTransferManager { private val log = LoggerFactory.getLogger(SimpleTransferManager::class.java) private val transferMap = HashMap<ILocalTransfer.LocalTransferID, IfaceTransfer>() // In-memory database of pending/executed/cancelled transfers fun developerTestingResetTransfers() { // TODO:(?) Make static? if (! Config.unitTestsActive) { throw RuntimeException("developer.unitTestsActive must be true @ application.conf " + "to be able to reset tests") } transferMap.clear() } // START IfaceLocalTransferManager implementation { override fun getTransferById(transferId : ILocalTransfer.LocalTransferID ) : IfaceTransfer { val result = transferMap[transferId] ?: throw ILPExceptionSupport.createILPNotFoundException("transfer '${transferId.uniqueID}' not found") if (result.transferStatus == TransferStatus.REJECTED) { throw ILPExceptionSupport.createILPUnprocessableEntityException( "This transfer has already been rejected") } return result } override fun executeLocalTransfer(transfer : IfaceTransfer ) : IfaceTransfer { // AccountUri sender, AccountUri recipient, MonetaryAmount amount) val debit_list : Array<ILocalTransfer.Debit> = transfer.debits // TODO:(0) This function is not simetrict between debits and credits!!! val debit0 = debit_list[0] if (debit_list.size > 1) { // STEP 1: Pass all debits to first account. for ( debit in debit_list) { val sender : IfaceLocalAccount = debit.localAccount val recipient : IfaceLocalAccount = debit0.localAccount val amount : MonetaryAmount = debit.amount __executeLocalTransfer(sender, recipient, amount) } } // STEP 2: Pay crediters from first account: val sender : IfaceLocalAccount = debit0.localAccount for (credit in transfer.credits) { __executeLocalTransfer(sender, credit.localAccount, credit.amount) } return (transfer as SimpleTransfer).copy( int_transferStatus=TransferStatus.EXECUTED, int_DTTM_prepared=ZonedDateTime.now(), int_DTTM_executed=ZonedDateTime.now() ) } override fun doesTransferExists(transferId : ILocalTransfer.LocalTransferID) :Boolean { return transferMap.containsKey(transferId) } // } END IfaceLocalTransferManager implementation // START IfaceILPSpecTransferManager implementation { override fun getTransfersByExecutionCondition(condition : Condition ) : MutableList<IfaceTransfer> { // For this simple implementation just run over existing transfers until val result = ArrayList<IfaceTransfer>() // = HashMap<LocalTransferID, IfaceTransfer>();// In-memory database of pending/executed/cancelled transfers for ( transferId : ILocalTransfer.LocalTransferID in transferMap.keys) { val transfer = transferMap.get(transferId) ?: throw RuntimeException("null found for transferId "+transferId) if (transfer.getExecutionCondition() == condition) { result.add(transfer) } } return result } override fun createNewRemoteILPTransfer(newTransfer : IfaceTransfer ) { log.debug("createNewRemoteILPTransfer") if (doesTransferExists(newTransfer.getTransferID())) { throw RuntimeException("trying to create new transfer " + "but transferID '"+newTransfer.getTransferID()+"'already registrered. " + "Check transfer with SimpleLedgerTransferManager.transferExists before invoquing this function") } log.debug("createNewRemoteILPTransfer newTransfer "+ newTransfer.getTransferID().uniqueID+", status: "+newTransfer.getTransferStatus().toString()) transferMap.put(newTransfer.getTransferID(), newTransfer) if (newTransfer.executionCondition == CC_NOT_PROVIDED) { // local transfer with no execution condition => execute and "forget" log.debug("createNewRemoteILPTransfer execute locally and forget") executeLocalTransfer(newTransfer) return } // PUT Money on-hold: for (debit in newTransfer.getDebits()) { __executeLocalTransfer(debit.localAccount, accountManager.holdAccountILP, debit.amount) } // TODO:(0) Next line commented to make tests pass, but looks to be sensible to do so. // newTransfer.setTransferStatus(TransferStatus.PROPOSED) } private fun executeOrCancelILPTransfer(transfer : IfaceTransfer , FF : Fulfillment , isExecution : Boolean /*false => isCancellation*/) : IfaceTransfer { if (isExecution /* => DisburseFunds */) { for (credit in transfer.getCredits()) { __executeLocalTransfer(sender = accountManager.holdAccountILP, recipient = credit.localAccount, amount = credit.amount) } return (transfer as SimpleTransfer).copy( int_transferStatus=TransferStatus.EXECUTED, int_DTTM_executed=ZonedDateTime.now(), executionFF=FF ) } else /* => Cancellation/Rollback */ { for (debit in transfer.getDebits()) { __executeLocalTransfer(sender = accountManager.holdAccountILP, recipient = debit.localAccount, amount = debit.amount) } return (transfer as SimpleTransfer).copy( int_transferStatus=TransferStatus.REJECTED, int_DTTM_executed=ZonedDateTime.now(), executionFF=FF ) } notifyUpdate(transfer = transfer, fulfillment = FF, isExecution = isExecution) } // TODO:(0) Update returned instance in ddbb if needed override fun executeILPTransfer(transfer : IfaceTransfer, executionFulfillment : Fulfillment ) : IfaceTransfer { return executeOrCancelILPTransfer(transfer, executionFulfillment, true) } // TODO:(0) Update returned instance in ddbb if needed override fun cancelILPTransfer (transfer : IfaceTransfer, cancellationFulfillment : Fulfillment ) : IfaceTransfer { return executeOrCancelILPTransfer(transfer, cancellationFulfillment, false) } override fun doesTransferExists(transferId : UUID ) : Boolean { return doesTransferExists(ILPSpec2LocalTransferID(transferId)) } // } END IfaceILPSpecTransferManager implementation private fun __executeLocalTransfer(sender : IfaceLocalAccount , recipient : IfaceLocalAccount , amount : MonetaryAmount ) { // TODO: LOG local transfer execution. log.info("executeLocalTransfer {") accountManager.getAccountByName(sender .getLocalID()).debit (amount) accountManager.getAccountByName(recipient.getLocalID()).credit(amount) log.info("} executeLocalTransfer") } // UnitTest / function test realated code fun unitTestsResetTransactionDDBB() { transferMap.clear() } fun unitTestsGetTotalTransactions() : String { return "${transferMap.keys.size}" } }
apache-2.0
87afaa43d12f0423ba55823af0d232b7
44.142857
158
0.692666
4.48414
false
false
false
false
google/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/VcsLogDiffPreview.kt
5
8058
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.vcs.log.ui.frame import com.intellij.diff.chains.DiffRequestChain import com.intellij.diff.chains.SimpleDiffRequestChain import com.intellij.diff.impl.DiffRequestProcessor import com.intellij.diff.tools.external.ExternalDiffTool import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionToolbar import com.intellij.openapi.application.invokeLater import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Splitter import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.changes.EditorTabPreviewBase.Companion.openPreview import com.intellij.openapi.vcs.changes.EditorTabPreviewBase.Companion.registerEscapeHandler import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager import com.intellij.openapi.vcs.changes.ui.VcsTreeModelData import com.intellij.openapi.wm.IdeFocusManager import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.OnePixelSplitter import com.intellij.util.ui.JBUI import com.intellij.vcs.log.VcsLogBundle import com.intellij.vcs.log.impl.CommonUiProperties import com.intellij.vcs.log.impl.MainVcsLogUiProperties import com.intellij.vcs.log.impl.VcsLogUiProperties import com.intellij.vcs.log.impl.VcsLogUiProperties.PropertiesChangeListener import com.intellij.vcs.log.impl.VcsLogUiProperties.VcsLogUiProperty import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import javax.swing.JComponent import kotlin.math.roundToInt private fun toggleDiffPreviewOnPropertyChange(uiProperties: VcsLogUiProperties, parent: Disposable, showDiffPreview: (Boolean) -> Unit) = onBooleanPropertyChange(uiProperties, CommonUiProperties.SHOW_DIFF_PREVIEW, parent, showDiffPreview) private fun toggleDiffPreviewOrientationOnPropertyChange(uiProperties: VcsLogUiProperties, parent: Disposable, changeShowDiffPreviewOrientation: (Boolean) -> Unit) = onBooleanPropertyChange(uiProperties, MainVcsLogUiProperties.DIFF_PREVIEW_VERTICAL_SPLIT, parent, changeShowDiffPreviewOrientation) private fun onBooleanPropertyChange(uiProperties: VcsLogUiProperties, property: VcsLogUiProperty<Boolean>, parent: Disposable, onPropertyChangeAction: (Boolean) -> Unit) { val propertiesChangeListener: PropertiesChangeListener = object : PropertiesChangeListener { override fun <T> onPropertyChanged(p: VcsLogUiProperty<T>) { if (property == p) { onPropertyChangeAction(uiProperties.get(property)) } } } uiProperties.addChangeListener(propertiesChangeListener) Disposer.register(parent, Disposable { uiProperties.removeChangeListener(propertiesChangeListener) }) } abstract class FrameDiffPreview<D : DiffRequestProcessor>(protected val previewDiff: D, uiProperties: VcsLogUiProperties, mainComponent: JComponent, @NonNls splitterProportionKey: String, vertical: Boolean = false, defaultProportion: Float = 0.7f) { private val previewDiffSplitter: Splitter = OnePixelSplitter(vertical, splitterProportionKey, defaultProportion) val mainComponent: JComponent get() = previewDiffSplitter init { previewDiffSplitter.firstComponent = mainComponent toggleDiffPreviewOnPropertyChange(uiProperties, previewDiff, ::showDiffPreview) toggleDiffPreviewOrientationOnPropertyChange(uiProperties, previewDiff, ::changeDiffPreviewOrientation) invokeLater { showDiffPreview(uiProperties.get(CommonUiProperties.SHOW_DIFF_PREVIEW)) } } abstract fun updatePreview(state: Boolean) private fun showDiffPreview(state: Boolean) { previewDiffSplitter.secondComponent = if (state) previewDiff.component else null previewDiffSplitter.secondComponent?.let { val defaultMinimumSize = it.minimumSize val actionButtonSize = ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE it.minimumSize = JBUI.size(defaultMinimumSize.width.coerceAtMost((actionButtonSize.width * 1.5f).roundToInt()), defaultMinimumSize.height.coerceAtMost((actionButtonSize.height * 1.5f).roundToInt())) } updatePreview(state) } private fun changeDiffPreviewOrientation(bottom: Boolean) { previewDiffSplitter.orientation = bottom } } abstract class EditorDiffPreview(protected val project: Project, private val owner: Disposable) : DiffPreviewProvider, DiffPreview { private val previewFileDelegate = lazy { PreviewDiffVirtualFile(this) } private val previewFile by previewFileDelegate protected fun init() { addSelectionListener { updatePreview(true) } } override fun openPreview(requestFocus: Boolean): Boolean { val currentFocusOwner = IdeFocusManager.getInstance(project).focusOwner val escapeHandler = Runnable { closePreview() val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID) toolWindow?.activate({ IdeFocusManager.getInstance(project).requestFocus(currentFocusOwner, true) }, false) } registerEscapeHandler(previewFile, escapeHandler) openPreview(project, previewFile, requestFocus) return true } override fun closePreview() { if (previewFileDelegate.isInitialized()) { FileEditorManager.getInstance(project).closeFile(previewFile) } } override fun getOwner(): Disposable = owner abstract fun getOwnerComponent(): JComponent abstract fun addSelectionListener(listener: () -> Unit) } class VcsLogEditorDiffPreview(project: Project, private val changesBrowser: VcsLogChangesBrowser) : EditorDiffPreview(project, changesBrowser), ChainBackedDiffPreviewProvider { init { init() } override fun createDiffRequestProcessor(): DiffRequestProcessor { val preview = changesBrowser.createChangeProcessor(true) preview.updatePreview(true) return preview } override fun getEditorTabName(processor: DiffRequestProcessor?): @Nls String { val filePath = (processor as? VcsLogChangeProcessor)?.currentChange?.filePath return if (filePath == null) VcsLogBundle.message("vcs.log.diff.preview.editor.empty.tab.name") else VcsLogBundle.message("vcs.log.diff.preview.editor.tab.name", filePath.name) } override fun getOwnerComponent(): JComponent = changesBrowser.preferredFocusedComponent override fun addSelectionListener(listener: () -> Unit) { changesBrowser.viewer.addSelectionListener(Runnable { if (changesBrowser.selectedChanges.isNotEmpty()) { listener() } }, owner) changesBrowser.addListener(VcsLogChangesBrowser.Listener { updatePreview(true) }, owner) } override fun createDiffRequestChain(): DiffRequestChain? { val producers = VcsTreeModelData.getListSelectionOrAll(changesBrowser.viewer).map { changesBrowser.getDiffRequestProducer(it, false) } return SimpleDiffRequestChain.fromProducers(producers) } override fun performDiffAction(): Boolean { if (ExternalDiffTool.isEnabled()) { val diffProducers = VcsTreeModelData.getListSelectionOrAll(changesBrowser.viewer) .map { change -> changesBrowser.getDiffRequestProducer(change, false) } if (EditorTabPreviewBase.showExternalToolIfNeeded(project, diffProducers)) { return true } } return super.performDiffAction() } }
apache-2.0
a0cab9df06187c40ced14855a94f6c44
42.556757
133
0.73033
5.364847
false
false
false
false
google/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/WinExeInstallerBuilder.kt
1
9526
// 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.intellij.build.impl import com.intellij.diagnostic.telemetry.useWithScope2 import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.io.NioFiles import com.intellij.util.io.Decompressor import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.BuildOptions import org.jetbrains.intellij.build.TraceManager.spanBuilder import org.jetbrains.intellij.build.WindowsDistributionCustomizer import org.jetbrains.intellij.build.executeStep import org.jetbrains.intellij.build.io.copyDir import org.jetbrains.intellij.build.io.deleteDir import org.jetbrains.intellij.build.io.runProcess import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption import java.nio.file.StandardOpenOption import java.util.concurrent.TimeUnit private fun generateInstallationConfigFileForSilentMode(customizer: WindowsDistributionCustomizer, context: BuildContext) { val targetFilePath = context.paths.artifactDir.resolve("silent.config") if (Files.exists(targetFilePath)) { return } val customConfigPath = customizer.silentInstallationConfig val silentConfigTemplate = if (customConfigPath != null) { check(Files.exists(customConfigPath)) { "WindowsDistributionCustomizer.silentInstallationConfig points to a file which doesn't exist: $customConfigPath" } customConfigPath } else { context.paths.communityHomeDir.communityRoot.resolve("platform/build-scripts/resources/win/nsis/silent.config") } Files.createDirectories(targetFilePath.parent) Files.copy(silentConfigTemplate, targetFilePath) val extensionsList = getFileAssociations(customizer) var associations = "\n\n; List of associations. To create an association change value to 1.\n" if (extensionsList.isEmpty()) { associations = "\n\n; There are no associations for the product.\n" } else { associations += extensionsList.joinToString(separator = "") { "$it=0\n" } } Files.writeString(targetFilePath, associations, StandardOpenOption.WRITE, StandardOpenOption.APPEND) } /** * Returns list of file extensions with leading dot added */ private fun getFileAssociations(customizer: WindowsDistributionCustomizer): List<String> { return customizer.fileAssociations.map { if (it.startsWith(".")) it else ".$it" } } @Suppress("SpellCheckingInspection") internal suspend fun buildNsisInstaller(winDistPath: Path, additionalDirectoryToInclude: Path, suffix: String, customizer: WindowsDistributionCustomizer, jreDir: Path, context: BuildContext): Path? { if (!SystemInfoRt.isWindows && !SystemInfoRt.isLinux) { context.messages.warning("Windows installer can be built only under Windows or Linux") return null } val communityHome = context.paths.communityHomeDir val outFileName = context.productProperties.getBaseArtifactName(context.applicationInfo, context.buildNumber) + suffix context.messages.progress("Building Windows installer $outFileName") val box = context.paths.tempDir.resolve("winInstaller") //noinspection SpellCheckingInspection val nsiConfDir = box.resolve("nsiconf") withContext(Dispatchers.IO) { Files.createDirectories(nsiConfDir) copyDir(context.paths.communityHomeDir.communityRoot.resolve("build/conf/nsis"), nsiConfDir) generateInstallationConfigFileForSilentMode(customizer, context) if (SystemInfoRt.isLinux) { val ideaNsiPath = nsiConfDir.resolve("idea.nsi") Files.writeString(ideaNsiPath, BuildUtils.replaceAll(text = Files.readString(ideaNsiPath), replacements = mapOf("\${IMAGES_LOCATION}\\" to "\${IMAGES_LOCATION}/"), marker = "")) } val generator = NsisFileListGenerator() generator.addDirectory(context.paths.distAllDir.toString()) generator.addDirectory(winDistPath.toString(), listOf("**/idea.properties", "**/*.vmoptions")) generator.addDirectory(additionalDirectoryToInclude.toString()) generator.addDirectory(jreDir.toString()) generator.generateInstallerFile(nsiConfDir.resolve("idea_win.nsh").toFile()) generator.generateUninstallerFile(nsiConfDir.resolve("unidea_win.nsh").toFile()) prepareConfigurationFiles(nsiConfDir = nsiConfDir, winDistPath = winDistPath, customizer = customizer, context = context) for (it in customizer.customNsiConfigurationFiles) { val file = Path.of(it) Files.copy(file, nsiConfDir.resolve(file.fileName), StandardCopyOption.REPLACE_EXISTING) } // Log final nsi directory to make debugging easier val logDir = Path.of(context.paths.buildOutputRoot, "log") val nsiLogDir = logDir.resolve("nsi") deleteDir(nsiLogDir) copyDir(nsiConfDir, nsiLogDir) Decompressor.Zip(communityHome.communityRoot.resolve("build/tools/NSIS.zip")).withZipExtensions().extract(box) spanBuilder("run NSIS tool to build .exe installer for Windows").useWithScope2 { val timeoutMs = TimeUnit.HOURS.toMillis(2) if (SystemInfoRt.isWindows) { runProcess( args = listOf( "${box}/NSIS/makensis.exe", "/V2", "/DCOMMUNITY_DIR=${communityHome.communityRoot}", "/DIPR=${customizer.associateIpr}", "/DOUT_DIR=${context.paths.artifacts}", "/DOUT_FILE=${outFileName}", "${box}/nsiconf/idea.nsi", ), workingDir = box, logger = context.messages, timeoutMillis = timeoutMs, ) } else { val makeNsis = "${box}/NSIS/Bin/makensis" NioFiles.setExecutable(Path.of(makeNsis)) runProcess( args = listOf( makeNsis, "-V2", "-DCOMMUNITY_DIR=${communityHome.communityRoot}", "-DIPR=${customizer.associateIpr}", "-DOUT_DIR=${context.paths.artifacts}", "-DOUT_FILE=${outFileName}", "${box}/nsiconf/idea.nsi", ), workingDir = box, logger = context.messages, timeoutMillis = timeoutMs, additionalEnvVariables = mapOf("NSISDIR" to "${box}/NSIS"), ) } } } val installerFile = context.paths.artifactDir.resolve("$outFileName.exe") check(Files.exists(installerFile)) { "Windows installer wasn't created." } context.executeStep(spanBuilder("sign").setAttribute("file", installerFile.toString()), BuildOptions.WIN_SIGN_STEP) { context.signFiles(listOf(installerFile)) } context.notifyArtifactWasBuilt(installerFile) return installerFile } private fun prepareConfigurationFiles(nsiConfDir: Path, winDistPath: Path, customizer: WindowsDistributionCustomizer, context: BuildContext) { val productProperties = context.productProperties Files.writeString(nsiConfDir.resolve("paths.nsi"), """ !define IMAGES_LOCATION "${FileUtilRt.toSystemDependentName(customizer.installerImagesPath!!)}" !define PRODUCT_PROPERTIES_FILE "${FileUtilRt.toSystemDependentName("$winDistPath/bin/idea.properties")}" !define PRODUCT_VM_OPTIONS_NAME ${productProperties.baseFileName}*.exe.vmoptions !define PRODUCT_VM_OPTIONS_FILE "${FileUtilRt.toSystemDependentName("${winDistPath}/bin/")}${'$'}{PRODUCT_VM_OPTIONS_NAME}" """) val extensionsList = getFileAssociations(customizer) val fileAssociations = if (extensionsList.isEmpty()) "NoAssociation" else extensionsList.joinToString(separator = ",") val appInfo = context.applicationInfo Files.writeString(nsiConfDir.resolve("strings.nsi"), """ !define MANUFACTURER "${appInfo.shortCompanyName}" !define MUI_PRODUCT "${customizer.getFullNameIncludingEdition(appInfo)}" !define PRODUCT_FULL_NAME "${customizer.getFullNameIncludingEditionAndVendor(appInfo)}" !define PRODUCT_EXE_FILE "${productProperties.baseFileName}64.exe" !define PRODUCT_ICON_FILE "install.ico" !define PRODUCT_UNINST_ICON_FILE "uninstall.ico" !define PRODUCT_LOGO_FILE "logo.bmp" !define PRODUCT_HEADER_FILE "headerlogo.bmp" !define ASSOCIATION "$fileAssociations" !define UNINSTALL_WEB_PAGE "${customizer.getUninstallFeedbackPageUrl(appInfo) ?: "feedback_web_page"}" ; if SHOULD_SET_DEFAULT_INSTDIR != 0 then default installation directory will be directory where highest-numbered IDE build has been installed ; set to 1 for release build !define SHOULD_SET_DEFAULT_INSTDIR "0" """) val versionString = if (appInfo.isEAP) "\${VER_BUILD}" else "\${MUI_VERSION_MAJOR}.\${MUI_VERSION_MINOR}" val installDirAndShortcutName = customizer.getNameForInstallDirAndDesktopShortcut(appInfo, context.buildNumber) Files.writeString(nsiConfDir.resolve("version.nsi"), """ !define MUI_VERSION_MAJOR "${appInfo.majorVersion}" !define MUI_VERSION_MINOR "${appInfo.minorVersion}" !define VER_BUILD ${context.buildNumber} !define INSTALL_DIR_AND_SHORTCUT_NAME "$installDirAndShortcutName" !define PRODUCT_WITH_VER "\$\{MUI_PRODUCT} $versionString" !define PRODUCT_PATHS_SELECTOR "${context.systemSelector}" """) }
apache-2.0
cf443b0216dacde14f93ac6780c3b225
44.361905
142
0.711631
4.463918
false
true
false
false
JetBrains/intellij-community
python/src/com/jetbrains/python/sdk/add/PyAddNewCondaEnvPanel.kt
1
6401
// 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.jetbrains.python.sdk.add import com.intellij.execution.ExecutionException import com.intellij.execution.target.readableFs.PathInfo import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.ui.DocumentAdapter import com.intellij.ui.components.JBCheckBox import com.intellij.util.PathUtil import com.intellij.util.SystemProperties import com.intellij.util.ui.FormBuilder import com.jetbrains.python.PyBundle import com.jetbrains.python.packaging.PyCondaPackageManagerImpl import com.jetbrains.python.packaging.PyCondaPackageService import com.jetbrains.python.sdk.* import com.jetbrains.python.sdk.add.target.conda.condaSupportedLanguages import com.jetbrains.python.sdk.conda.PyCondaSdkCustomizer import com.jetbrains.python.sdk.flavors.conda.CondaEnvSdkFlavor import icons.PythonIcons import org.jetbrains.annotations.SystemIndependent import java.awt.BorderLayout import javax.swing.Icon import javax.swing.JComboBox import javax.swing.event.DocumentEvent /** * @author vlan */ open class PyAddNewCondaEnvPanel( private val project: Project?, private val module: Module?, private val existingSdks: List<Sdk>, newProjectPath: String? ) : PyAddNewEnvPanel() { override val envName: String = "Conda" override val panelName: String get() = PyBundle.message("python.add.sdk.panel.name.new.environment") override val icon: Icon = PythonIcons.Python.Anaconda protected val languageLevelsField: JComboBox<String> protected val condaPathField = TextFieldWithBrowseButton().apply { val path = PyCondaPackageService.getCondaExecutable(null) path?.let { text = it } addBrowseFolderListener(PyBundle.message("python.sdk.select.conda.path.title"), null, project, FileChooserDescriptorFactory.createSingleFileOrExecutableAppDescriptor()) textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { updatePathField() } }) } protected val pathField = TextFieldWithBrowseButton().apply { addBrowseFolderListener(PyBundle.message("python.sdk.select.location.for.conda.title"), null, project, FileChooserDescriptorFactory.createSingleFolderDescriptor()) } private val makeSharedField = JBCheckBox(PyBundle.message("available.to.all.projects")) override var newProjectPath: String? = newProjectPath set(value) { field = value updatePathField() } init { layout = BorderLayout() val supportedLanguageLevels = condaSupportedLanguages .map { it.toPythonVersion() } languageLevelsField = ComboBox(supportedLanguageLevels.toTypedArray()).apply { selectedItem = if (itemCount > 0) getItemAt(0) else null } if (PyCondaSdkCustomizer.instance.sharedEnvironmentsByDefault) { makeSharedField.isSelected = true } updatePathField() @Suppress("LeakingThis") layoutComponents() } protected open fun layoutComponents() { layout = BorderLayout() val formPanel = FormBuilder.createFormBuilder() .addLabeledComponent(PyBundle.message("sdk.create.venv.conda.dialog.label.location"), pathField) .addLabeledComponent(PyBundle.message("sdk.create.venv.conda.dialog.label.python.version"), languageLevelsField) .addLabeledComponent(PyBundle.message("python.sdk.conda.path"), condaPathField) .addComponent(makeSharedField) .panel add(formPanel, BorderLayout.NORTH) } override fun validateAll(): List<ValidationInfo> = listOfNotNull(CondaEnvSdkFlavor.validateCondaPath(condaPathField.text), validateEnvironmentDirectoryLocation(pathField, PathInfo.localPathInfoProvider)) override fun getOrCreateSdk(): Sdk? { val condaPath = condaPathField.text val task = object : Task.WithResult<String, ExecutionException>(project, PyBundle.message("python.sdk.creating.conda.environment.title"), false) { override fun compute(indicator: ProgressIndicator): String { indicator.isIndeterminate = true return PyCondaPackageManagerImpl.createVirtualEnv(condaPath, pathField.text, selectedLanguageLevel) } } val shared = makeSharedField.isSelected val associatedPath = if (!shared) projectBasePath else null val sdk = createSdkByGenerateTask(task, existingSdks, null, associatedPath, null) ?: return null if (!shared) { sdk.associateWithModule(module, newProjectPath) } PyCondaPackageService.onCondaEnvCreated(condaPath) project.excludeInnerVirtualEnv(sdk) // Old conda created, convert to new fixPythonCondaSdk(sdk, sdk.getOrCreateAdditionalData(), condaPath) return sdk } override fun addChangeListener(listener: Runnable) { val documentListener = object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { listener.run() } } pathField.textField.document.addDocumentListener(documentListener) condaPathField.textField.document.addDocumentListener(documentListener) } private fun updatePathField() { val baseDir = defaultBaseDir ?: "${SystemProperties.getUserHome()}/.conda/envs" val dirName = PathUtil.getFileName(projectBasePath ?: "untitled") pathField.text = FileUtil.toSystemDependentName("$baseDir/$dirName") } private val defaultBaseDir: String? get() { val conda = condaPathField.text val condaFile = LocalFileSystem.getInstance().findFileByPath(conda) ?: return null return condaFile.parent?.parent?.findChild("envs")?.path } private val projectBasePath: @SystemIndependent String? get() = newProjectPath ?: module?.basePath ?: project?.basePath private val selectedLanguageLevel: String get() = languageLevelsField.getItemAt(languageLevelsField.selectedIndex) }
apache-2.0
4926b4e5a82d1308f43ee37dc3e93648
39.00625
156
0.765037
4.679094
false
false
false
false
dinosaurwithakatana/Google-I-O-Bingo
app/src/main/kotlin/io/dwak/googleiobingo/main/MainActivity.kt
1
2712
package io.dwak.googleiobingo.main import android.os.Bundle import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import butterknife.bindView import io.dwak.googleiobingo.R import io.dwak.googleiobingo.adapter import io.dwak.googleiobingo.layoutManager import io.dwak.googleiobingo.model.BingoEntry import io.dwak.googleiobingo.view.MainView import io.dwak.meh.base.MvpActivity import kotlinx.android.anko.AnkoLogger import kotlinx.android.anko.alert import java.util.ArrayList class MainActivity : MvpActivity<MainPresenterImpl>(), MainView, AnkoLogger { override val presenterClass: Class<MainPresenterImpl> = javaClass() val toolbar: Toolbar by bindView(R.id.toolbar) val recyclerView: RecyclerView by bindView(R.id.recycler_view) val layoutManager = GridLayoutManager(this, 5) var adapter = BingoAdapter(this) override fun setView() { presenter.view = this } override fun onCreate(savedInstanceState: Bundle?) { super<MvpActivity>.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) var onItemClickListener = object : BingoAdapter.Companion.BingoAdapterItemClickListener { override fun onItemClick(position: Int) { adapter.toggleItemClick(position) presenter.toggleItemClick(adapter.list.get(position)) } } adapter.itemClickListener = onItemClickListener recyclerView.layoutManager = layoutManager recyclerView.adapter = adapter recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST)) presenter.getBingo(getResources().getStringArray(R.array.bingo_entries)) } override fun displayBingo(bingoEntries: ArrayList<BingoEntry>) { debug(bingoEntries) adapter.setItems(bingoEntries) } override fun onCreateOptionsMenu(menu: Menu): Boolean { getMenuInflater().inflate(R.menu.menu_main, menu) return super<MvpActivity>.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.getItemId()){ R.id.action_regenerate_board -> { alert("This will clear your current board", null) { positiveButton("Ok") { presenter.getBingo(getResources().getStringArray(R.array.bingo_entries), true) } negativeButton("Nevermind") {} }.show() } } return super<MvpActivity>.onOptionsItemSelected(item) } }
mit
ee0944a05f849e4ecf5f8457a7c716be
35.648649
123
0.713864
4.659794
false
false
false
false
leafclick/intellij-community
platform/indexing-impl/src/com/intellij/psi/impl/search/InjectionAwareOccurrenceProcessor.kt
1
3442
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.impl.search import com.intellij.lang.Language import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.model.search.impl.LanguageInfo import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.Pair import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.component1 import com.intellij.openapi.util.component2 import com.intellij.psi.PsiElement import com.intellij.util.SmartList import com.intellij.util.text.StringSearcher import gnu.trove.THashSet internal class InjectionAwareOccurrenceProcessor( private val progress: ProgressIndicator, private val processors: RequestProcessors, private val manager: InjectedLanguageManager, private val searcher: StringSearcher ) : OccurrenceProcessor { private val processedInjections = THashSet<PsiElement>() override fun invoke(occurrence: LeafOccurrence): Boolean { if (processors.injectionProcessors.isEmpty()) { return processHost(occurrence) } // TODO find injections of needed languages only, needed languages are the key set of languageInjectionProcessors map val injected: PsiElement? = findInjectionAtOffset(occurrence) if (injected == null) { return processHost(occurrence) } if (!processedInjections.add(injected)) { // The same injection might contain several occurrences at different offsets, we don't know about them beforehand. // Since `LowLevelSearchUtil.getTextOccurrencesInScope` is used // its possible to end up in the situation when N occurrences in a single injection are processed N times each. return true } val injectionProcessors: Collection<OccurrenceProcessor> = getLanguageProcessors(injected.language) if (injectionProcessors.isEmpty()) { return true } val offsets = LowLevelSearchUtil.getTextOccurrencesInScope(injected, searcher) val patternLength = searcher.patternLength return processOffsets(injected, offsets, patternLength, progress, injectionProcessors.compound(progress)) } private fun getLanguageProcessors(injectionLanguage: Language): Collection<OccurrenceProcessor> { val injectionProcessors = processors.injectionProcessors val result = SmartList<OccurrenceProcessor>() for ((languageInfo, processors) in injectionProcessors) { if (languageInfo == LanguageInfo.NoLanguage || languageInfo is LanguageInfo.InLanguage && languageInfo.matcher.matchesLanguage(injectionLanguage)) { result += processors } } return result } private fun findInjectionAtOffset(occurrence: LeafOccurrence): PsiElement? { for ((currentElement, currentOffset) in occurrence.elementsUp()) { progress.checkCanceled() val injectedFiles: List<Pair<PsiElement, TextRange>> = manager.getInjectedPsiFiles(currentElement) ?: continue for ((injected, range) in injectedFiles) { if (range.containsRange(currentOffset, currentOffset + searcher.patternLength)) { return injected } } } return null } private fun processHost(occurrence: LeafOccurrence): Boolean { // Feed host element into the processors which doesn't want injections. return processors.hostProcessors.runProcessors(progress, occurrence) } }
apache-2.0
c019ee02859135fc33dd7792b036e919
42.025
140
0.764381
4.959654
false
false
false
false
exponent/exponent
packages/expo-dev-menu/android/src/main/java/expo/modules/devmenu/extensions/DevMenuExtension.kt
2
4511
package expo.modules.devmenu.extensions import android.util.Log import android.view.KeyEvent import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.devsupport.DevInternalSettings import expo.interfaces.devmenu.DevMenuExtensionInterface import expo.interfaces.devmenu.DevMenuExtensionSettingsInterface import expo.interfaces.devmenu.items.DevMenuDataSourceInterface import expo.interfaces.devmenu.items.DevMenuItemImportance import expo.interfaces.devmenu.items.DevMenuItemsContainer import expo.interfaces.devmenu.items.DevMenuScreen import expo.interfaces.devmenu.items.KeyCommand import expo.modules.devmenu.DEV_MENU_TAG import expo.modules.devmenu.DevMenuManager import expo.modules.devmenu.devtools.DevMenuDevToolsDelegate import kotlinx.coroutines.runBlocking class DevMenuExtension(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext), DevMenuExtensionInterface { override fun getName() = "ExpoDevMenuExtensions" override fun devMenuItems(settings: DevMenuExtensionSettingsInterface) = DevMenuItemsContainer.export { if (!settings.wasRunOnDevelopmentBridge()) { return@export } val reactInstanceManager = settings.manager.getSession()?.reactInstanceManager if (reactInstanceManager == null) { Log.w(DEV_MENU_TAG, "Couldn't export dev-menu items, because the react instance manager isn't present.") return@export } val devDelegate = DevMenuDevToolsDelegate(settings.manager, reactInstanceManager) val reactDevManager = devDelegate.reactDevManager val devSettings = devDelegate.devSettings if (reactDevManager == null || devSettings == null) { Log.w(DEV_MENU_TAG, "Couldn't export dev-menu items, because react-native bridge doesn't contain the dev support manager.") return@export } action("reload", devDelegate::reload) { label = { "Reload" } glyphName = { "reload" } keyCommand = KeyCommand(KeyEvent.KEYCODE_R) importance = DevMenuItemImportance.HIGHEST.value } action( "performance-monitor", { currentActivity?.let { devDelegate.togglePerformanceMonitor(it) } } ) { isEnabled = { devSettings.isFpsDebugEnabled } label = { if (isEnabled()) "Hide Performance Monitor" else "Show Performance Monitor" } glyphName = { "speedometer" } keyCommand = KeyCommand(KeyEvent.KEYCODE_P) importance = DevMenuItemImportance.HIGH.value } action("inspector", devDelegate::toggleElementInspector) { isEnabled = { devSettings.isElementInspectorEnabled } label = { if (isEnabled()) "Hide Element Inspector" else "Show Element Inspector" } glyphName = { "border-style" } keyCommand = KeyCommand(KeyEvent.KEYCODE_I) importance = DevMenuItemImportance.HIGH.value } action("remote-debug", devDelegate::toggleRemoteDebugging) { isEnabled = { devSettings.isRemoteJSDebugEnabled } label = { if (isEnabled()) "Stop Remote Debugging" else "Debug Remote JS" } glyphName = { "remote-desktop" } importance = DevMenuItemImportance.LOW.value } if (devSettings is DevInternalSettings) { action("js-inspector", devDelegate::openJsInspector) { isAvailable = { val metroHost = "http://${devSettings.packagerConnectionSettings.debugServerHost}" var result: Boolean runBlocking { result = DevMenuManager.metroClient .queryJSInspectorAvailability(metroHost, reactApplicationContext.packageName) } result } label = { "Open JavaScript Inspector" } glyphName = { "language-javascript" } importance = DevMenuItemImportance.LOW.value } val fastRefreshAction = { devSettings.isHotModuleReplacementEnabled = !devSettings.isHotModuleReplacementEnabled } action("fast-refresh", fastRefreshAction) { isEnabled = { devSettings.isHotModuleReplacementEnabled } label = { if (isEnabled()) "Disable Fast Refresh" else "Enable Fast Refresh" } glyphName = { "run-fast" } importance = DevMenuItemImportance.LOW.value } } } override fun devMenuScreens(settings: DevMenuExtensionSettingsInterface): List<DevMenuScreen>? = null override fun devMenuDataSources(settings: DevMenuExtensionSettingsInterface): List<DevMenuDataSourceInterface>? = null }
bsd-3-clause
f82ac131fb604233993397f393424a90
38.226087
129
0.724895
4.778602
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/gui/Gui.kt
1
1798
package com.cout970.modeler.gui import com.cout970.glutilities.structure.Timer import com.cout970.modeler.controller.Dispatcher import com.cout970.modeler.controller.binders.ButtonBinder import com.cout970.modeler.controller.binders.KeyboardBinder import com.cout970.modeler.core.project.IProgramState import com.cout970.modeler.core.project.IProjectPropertiesHolder import com.cout970.modeler.gui.canvas.CanvasContainer import com.cout970.modeler.gui.canvas.CanvasManager import com.cout970.modeler.gui.canvas.GridLines import com.cout970.modeler.gui.canvas.cursor.CursorManager import com.cout970.modeler.gui.event.NotificationHandler import com.cout970.modeler.gui.views.EditorView import com.cout970.modeler.input.event.IInput import com.cout970.modeler.input.window.WindowHandler import com.cout970.modeler.render.tool.Animator /** * Created by cout970 on 2017/05/26. */ data class Gui( val root: Root, val canvasContainer: CanvasContainer, val listeners: Listeners, val windowHandler: WindowHandler, val timer: Timer, val input: IInput, var editorView: EditorView, val resources: GuiResources, val state: GuiState, val programState: IProgramState, val dispatcher: Dispatcher, val buttonBinder: ButtonBinder, val keyboardBinder: KeyboardBinder, val canvasManager: CanvasManager, val cursorManager: CursorManager, val propertyHolder: IProjectPropertiesHolder, val notificationHandler: NotificationHandler, val gridLines: GridLines, val animator: Animator ) { init { canvasManager.gui = this editorView.gui = this notificationHandler.gui = this gridLines.gui = this animator.gui = this } }
gpl-3.0
7403236487fcde9858b0d1ace0b4b8fe
33.596154
64
0.741379
4.210773
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/errors.kt
2
3125
// 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.tools.projectWizard.core import com.intellij.openapi.util.NlsSafe import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle import java.io.IOException import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module abstract class Error { @get:Nls abstract val message: String } abstract class ExceptionError : Error() { abstract val exception: Exception override val message: String @NlsSafe get() = exception::class.simpleName!!.removeSuffix("Exception").splitByWords() + exception.message?.let { ": $it" }.orEmpty() companion object { private val wordRegex = "[A-Z][a-z0-9]+".toRegex() private fun String.splitByWords() = wordRegex.findAll(this).joinToString(separator = " ") { it.value } } } data class IOError(override val exception: IOException) : ExceptionError() data class ExceptionErrorImpl(override val exception: Exception) : ExceptionError() data class ParseError(@Nls override val message: String) : Error() data class TemplateNotFoundError(val id: String) : Error() { override val message: String get() = KotlinNewProjectWizardBundle.message("error.template.not.found", id) } data class RequiredSettingsIsNotPresentError(val settingNames: List<String>) : Error() { override val message: String @Nls get() = KotlinNewProjectWizardBundle.message( "error.required.settings.are.not.present.0", settingNames.joinToString(separator = "\n") { " $it" } ) } data class CircularTaskDependencyError(@NonNls val taskName: String) : Error() { @get:NonNls override val message: String get() = "$taskName task has circular dependencies" } data class BadSettingValueError(@Nls override val message: String) : Error() data class ConfiguratorNotFoundError(val id: String) : Error() { override val message: String get() = KotlinNewProjectWizardBundle.message("error.configurator.not.found", id) } data class ValidationError(@Nls val validationMessage: String) : Error() { override val message: String get() = validationMessage.capitalize() } data class ProjectImportingError(val kotlinVersion: String, @Nls val reason: String, val details: String) : Error() { override val message: String get() = KotlinNewProjectWizardBundle.message("error.text.project.importing.error.kotlin.version.0.reason.1", kotlinVersion, reason) } data class InvalidModuleDependencyError(val from: String, val to: String, @Nls val reason: String? = null) : Error() { constructor(from: Module, to: Module, @Nls reason: String? = null) : this(from.name, to.name, reason) override val message: String get() = KotlinNewProjectWizardBundle.message("error.invalid.module.dependency", from, to) + reason?.let { ": $it" }.orEmpty() }
apache-2.0
5c790c27bbd3f3dd212b5d5d4a2034e0
39.076923
158
0.71936
4.280822
false
false
false
false
MER-GROUP/intellij-community
platform/testFramework/test-framework-java8/path.kt
2
2984
package com.intellij.testFramework import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import java.io.File import java.io.IOException import java.io.OutputStream import java.nio.file.FileVisitResult import java.nio.file.Files import java.nio.file.Path import java.nio.file.SimpleFileVisitor import java.nio.file.attribute.BasicFileAttributes import java.nio.file.attribute.FileTime fun Path.exists() = Files.exists(this) fun Path.createDirectories() = Files.createDirectories(this) /** * Opposite to Java, parent directories will be created */ fun Path.outputStream(): OutputStream { parent?.createDirectories() return Files.newOutputStream(this) } /** * Opposite to Java, parent directories will be created */ fun Path.createSymbolicLink(target: Path): Path { parent?.createDirectories() Files.createSymbolicLink(this, target) return this } fun Path.deleteRecursively(): Path = if (exists()) Files.walkFileTree(this, object : SimpleFileVisitor<Path>() { override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { deleteFile(file) return FileVisitResult.CONTINUE } override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult { deleteFile(dir) return FileVisitResult.CONTINUE } private fun deleteFile(file: Path) { try { Files.delete(file) } catch (e: Exception) { FileUtil.delete(file.toFile()) } } }) else this fun Path.getLastModifiedTime(): FileTime? = Files.getLastModifiedTime(this) val Path.systemIndependentPath: String get() = toString().replace(File.separatorChar, '/') val Path.parentSystemIndependentPath: String get() = parent!!.toString().replace(File.separatorChar, '/') fun Path.readBytes() = Files.readAllBytes(this) fun Path.readText() = readBytes().toString(Charsets.UTF_8) fun VirtualFile.writeChild(relativePath: String, data: String) = VfsTestUtil.createFile(this, relativePath, data) fun Path.writeChild(relativePath: String, data: ByteArray) = resolve(relativePath).write(data) fun Path.writeChild(relativePath: String, data: String) = writeChild(relativePath, data.toByteArray()) fun Path.write(data: ByteArray): Path { parent?.createDirectories() return Files.write(this, data) } fun Path.isDirectory() = Files.isDirectory(this) fun Path.isFile() = Files.isRegularFile(this) /** * Opposite to Java, parent directories will be created */ fun Path.createFile() { parent?.createDirectories() Files.createFile(this) } fun Path.refreshVfs() { LocalFileSystem.getInstance()?.let { fs -> // If a temp directory is reused from some previous test run, there might be cached children in its VFS. Ensure they're removed. val virtualFile = fs.findFileByPath(systemIndependentPath) if (virtualFile != null) { VfsUtil.markDirtyAndRefresh(false, true, true, virtualFile) } } }
apache-2.0
2ec9e04edc1968545ff0a9e18d6ae51d
28.264706
132
0.752346
4.150209
false
false
false
false
lucasgomes-eti/KotlinAndroidProjects
TetesEspresso/app/src/main/java/com/lucasgomes/tetesespresso/SettingsActivity.kt
1
9948
package com.lucasgomes.tetesespresso import android.annotation.TargetApi import android.content.Context import android.content.Intent import android.content.res.Configuration import android.media.Ringtone import android.media.RingtoneManager import android.net.Uri import android.os.Build import android.os.Bundle import android.preference.ListPreference import android.preference.Preference import android.preference.PreferenceActivity import android.support.v7.app.ActionBar import android.preference.PreferenceFragment import android.preference.PreferenceManager import android.preference.RingtonePreference import android.text.TextUtils import android.view.MenuItem import android.support.v4.app.NavUtils /** * A [PreferenceActivity] that presents a set of application settings. On * handset devices, settings are presented as a single list. On tablets, * settings are split by category, with category headers shown to the left of * the list of settings. * * * See [ * Android Design: Settings](http://developer.android.com/design/patterns/settings.html) for design guidelines and the [Settings * API Guide](http://developer.android.com/guide/topics/ui/settings.html) for more information on developing a Settings UI. */ class SettingsActivity : AppCompatPreferenceActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setupActionBar() } /** * Set up the [android.app.ActionBar], if the API is available. */ private fun setupActionBar() { val actionBar = supportActionBar actionBar?.setDisplayHomeAsUpEnabled(true) } override fun onMenuItemSelected(featureId: Int, item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { if (!super.onMenuItemSelected(featureId, item)) { NavUtils.navigateUpFromSameTask(this) } return true } return super.onMenuItemSelected(featureId, item) } /** * {@inheritDoc} */ override fun onIsMultiPane(): Boolean { return isXLargeTablet(this) } /** * {@inheritDoc} */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) override fun onBuildHeaders(target: List<PreferenceActivity.Header>) { loadHeadersFromResource(R.xml.pref_headers, target) } /** * This method stops fragment injection in malicious applications. * Make sure to deny any unknown fragments here. */ override fun isValidFragment(fragmentName: String): Boolean { return PreferenceFragment::class.java.name == fragmentName || GeneralPreferenceFragment::class.java.name == fragmentName || DataSyncPreferenceFragment::class.java.name == fragmentName || NotificationPreferenceFragment::class.java.name == fragmentName } /** * This fragment shows general preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) class GeneralPreferenceFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.pref_general) setHasOptionsMenu(true) // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("example_text")) bindPreferenceSummaryToValue(findPreference("example_list")) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { startActivity(Intent(activity, SettingsActivity::class.java)) return true } return super.onOptionsItemSelected(item) } } /** * This fragment shows notification preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) class NotificationPreferenceFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.pref_notification) setHasOptionsMenu(true) // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone")) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { startActivity(Intent(activity, SettingsActivity::class.java)) return true } return super.onOptionsItemSelected(item) } } /** * This fragment shows data and sync preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) class DataSyncPreferenceFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.pref_data_sync) setHasOptionsMenu(true) // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("sync_frequency")) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { startActivity(Intent(activity, SettingsActivity::class.java)) return true } return super.onOptionsItemSelected(item) } } companion object { /** * Helper method to determine if the device has an extra-large screen. For * example, 10" tablets are extra-large. */ private fun isXLargeTablet(context: Context): Boolean { return context.resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK >= Configuration.SCREENLAYOUT_SIZE_XLARGE } /** * A preference value change listener that updates the preference's summary * to reflect its new value. */ private val sBindPreferenceSummaryToValueListener = Preference.OnPreferenceChangeListener { preference, value -> val stringValue = value.toString() if (preference is ListPreference) { // For list preferences, look up the correct display value in // the preference's 'entries' list. val index = preference.findIndexOfValue(stringValue) // Set the summary to reflect the new value. preference.setSummary( if (index >= 0) preference.entries[index] else null) } else if (preference is RingtonePreference) { // For ringtone preferences, look up the correct display value // using RingtoneManager. if (TextUtils.isEmpty(stringValue)) { // Empty values correspond to 'silent' (no ringtone). preference.setSummary(R.string.pref_ringtone_silent) } else { val ringtone = RingtoneManager.getRingtone( preference.getContext(), Uri.parse(stringValue)) if (ringtone == null) { // Clear the summary if there was a lookup error. preference.setSummary(null) } else { // Set the summary to reflect the new ringtone display // name. val name = ringtone.getTitle(preference.getContext()) preference.setSummary(name) } } } else { // For all other preferences, set the summary to the value's // simple string representation. preference.summary = stringValue } true } /** * Binds a preference's summary to its value. More specifically, when the * preference's value is changed, its summary (line of text below the * preference title) is updated to reflect the value. The summary is also * immediately updated upon calling this method. The exact display format is * dependent on the type of preference. * * @see .sBindPreferenceSummaryToValueListener */ private fun bindPreferenceSummaryToValue(preference: Preference) { // Set the listener to watch for value changes. preference.onPreferenceChangeListener = sBindPreferenceSummaryToValueListener // Trigger the listener immediately with the preference's // current value. sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.context) .getString(preference.key, "")) } } }
cc0-1.0
3ffef0d381afad36600c9290aa164ddf
38.47619
146
0.629473
5.595051
false
false
false
false
siosio/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/highlighter/visitors/VariableReferenceHighlightingVisitor.kt
1
3424
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.fir.highlighter.visitors import com.intellij.lang.annotation.AnnotationHolder import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.PsiModifier import com.intellij.psi.PsiVariable import com.intellij.psi.util.PsiUtilCore import com.intellij.psi.util.parentOfType import org.jetbrains.kotlin.idea.KotlinIdeaAnalysisBundle import org.jetbrains.kotlin.idea.fir.highlighter.textAttributesKeyForPropertyDeclaration import org.jetbrains.kotlin.idea.frontend.api.KtAnalysisSession import org.jetbrains.kotlin.idea.highlighter.NameHighlighter import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingColors as Colors internal class VariableReferenceHighlightingVisitor( analysisSession: KtAnalysisSession, holder: AnnotationHolder ) : FirAfterResolveHighlightingVisitor(analysisSession, holder) { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { if (!NameHighlighter.namesHighlightingEnabled) return if (expression.isAssignmentReference()) return if (expression.isByNameArgumentReference()) return if (expression.parent is KtInstanceExpressionWithLabel) return if (expression.isAutoCreatedItParameter()) { createInfoAnnotation( expression, KotlinIdeaAnalysisBundle.message("automatically.declared.based.on.the.expected.type"), Colors.FUNCTION_LITERAL_DEFAULT_PARAMETER ) return } val target = expression.mainReference.resolve() when { target != null && expression.isBackingField(target) -> Colors.BACKING_FIELD_VARIABLE target is PsiMethod -> Colors.SYNTHETIC_EXTENSION_PROPERTY target != null -> textAttributesKeyForPropertyDeclaration(target) else -> null }?.let { attribute -> highlightName(expression, attribute) if (target?.isMutableVariable() == true) { highlightName(expression, Colors.MUTABLE_VARIABLE) } } } private fun KtSimpleNameExpression.isByNameArgumentReference() = parent is KtValueArgumentName private fun KtSimpleNameExpression.isAutoCreatedItParameter(): Boolean { return getReferencedName() == "it" // todo } } private fun PsiElement.isMutableVariable() = when { this is KtValVarKeywordOwner && PsiUtilCore.getElementType(valOrVarKeyword) == KtTokens.VAR_KEYWORD -> true this is PsiVariable && !hasModifierProperty(PsiModifier.FINAL) -> true else -> false } private fun KtSimpleNameExpression.isAssignmentReference(): Boolean { if (this !is KtOperationReferenceExpression) return false return operationSignTokenType == KtTokens.EQ } private fun KtSimpleNameExpression.isBackingField(target: PsiElement): Boolean { if (getReferencedName() != "field") return false if (target !is KtProperty) return false val accessor = parentOfType<KtPropertyAccessor>() ?: return false return accessor.parent == target }
apache-2.0
59b1859aadd7dc4cae8834ef36556f96
40.253012
115
0.741238
5.156627
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/KotlinCallHierarchyNodeDescriptor.kt
1
8380
// 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.hierarchy.calls import com.intellij.icons.AllIcons import com.intellij.ide.IdeBundle import com.intellij.ide.hierarchy.HierarchyNodeDescriptor import com.intellij.ide.hierarchy.call.CallHierarchyNodeDescriptor import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.roots.ui.util.CompositeAppearance import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.Iconable import com.intellij.openapi.util.text.StringUtil import com.intellij.pom.Navigatable import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.ui.LayeredIcon import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import java.awt.Font class KotlinCallHierarchyNodeDescriptor( parentDescriptor: HierarchyNodeDescriptor?, element: KtElement, isBase: Boolean, navigateToReference: Boolean ) : HierarchyNodeDescriptor(element.project, parentDescriptor, element, isBase), Navigatable { private var usageCount = 1 private val references: MutableSet<PsiReference> = HashSet() private val javaDelegate: CallHierarchyNodeDescriptor fun incrementUsageCount() { usageCount++ javaDelegate.incrementUsageCount() } fun addReference(reference: PsiReference) { references.add(reference) javaDelegate.addReference(reference) } override fun isValid(): Boolean { val myElement = psiElement return myElement != null && myElement.isValid } override fun update(): Boolean { val oldText = myHighlightedText val oldIcon = icon val flags: Int = if (isMarkReadOnly) { Iconable.ICON_FLAG_VISIBILITY or Iconable.ICON_FLAG_READ_STATUS } else { Iconable.ICON_FLAG_VISIBILITY } var changes = super.update() val elementText = renderElement(psiElement) if (elementText == null) { val invalidPrefix = IdeBundle.message("node.hierarchy.invalid") if (!myHighlightedText.text.startsWith(invalidPrefix)) { myHighlightedText.beginning.addText(invalidPrefix, getInvalidPrefixAttributes()) } return true } val targetElement = psiElement val elementIcon = targetElement!!.getIcon(flags) icon = if (changes && myIsBase) { LayeredIcon(2).apply { setIcon(elementIcon, 0) setIcon(AllIcons.General.Modified, 1, -AllIcons.General.Modified.iconWidth / 2, 0) } } else { elementIcon } val mainTextAttributes: TextAttributes? = if (myColor != null) { TextAttributes(myColor, null, null, null, Font.PLAIN) } else { null } myHighlightedText = CompositeAppearance() myHighlightedText.ending.addText(elementText, mainTextAttributes) if (usageCount > 1) { myHighlightedText.ending.addText( IdeBundle.message("node.call.hierarchy.N.usages", usageCount), getUsageCountPrefixAttributes(), ) } val packageName = KtPsiUtil.getPackageName(targetElement as KtElement) ?: "" myHighlightedText.ending.addText(" ($packageName)", getPackageNameAttributes()) myName = myHighlightedText.text if (!(Comparing.equal(myHighlightedText, oldText) && Comparing.equal(icon, oldIcon))) { changes = true } return changes } override fun navigate(requestFocus: Boolean) { javaDelegate.navigate(requestFocus) } override fun canNavigate(): Boolean { return javaDelegate.canNavigate() } override fun canNavigateToSource(): Boolean { return javaDelegate.canNavigateToSource() } companion object { private fun renderElement(element: PsiElement?): String? { when (element) { is KtFile -> { return element.name } !is KtNamedDeclaration -> { return null } else -> { var descriptor: DeclarationDescriptor = element.resolveToDescriptorIfAny(BodyResolveMode.PARTIAL) ?: return null val elementText: String? when (element) { is KtClassOrObject -> { when { element is KtObjectDeclaration && element.isCompanion() -> { val containingDescriptor = descriptor.containingDeclaration if (containingDescriptor !is ClassDescriptor) return null descriptor = containingDescriptor elementText = renderClassOrObject(descriptor) } element is KtEnumEntry -> { elementText = element.name } else -> { elementText = if (element.name != null) { renderClassOrObject(descriptor as ClassDescriptor) } else { KotlinBundle.message("hierarchy.text.anonymous") } } } } is KtNamedFunction, is KtConstructor<*> -> { if (descriptor !is FunctionDescriptor) return null elementText = renderNamedFunction(descriptor) } is KtProperty -> { elementText = element.name } else -> return null } if (elementText == null) return null var containerText: String? = null var containerDescriptor = descriptor.containingDeclaration while (containerDescriptor != null) { if (containerDescriptor is PackageFragmentDescriptor || containerDescriptor is ModuleDescriptor) { break } val name = containerDescriptor.name if (!name.isSpecial) { val identifier = name.identifier containerText = if (containerText != null) "$identifier.$containerText" else identifier } containerDescriptor = containerDescriptor.containingDeclaration } return if (containerText != null) "$containerText.$elementText" else elementText } } } fun renderNamedFunction(descriptor: FunctionDescriptor): String { val descriptorForName: DeclarationDescriptor = (descriptor as? ConstructorDescriptor)?.containingDeclaration ?: descriptor val name = descriptorForName.name.asString() val paramTypes = StringUtil.join( descriptor.valueParameters, { descriptor1: ValueParameterDescriptor -> DescriptorRenderer .SHORT_NAMES_IN_TYPES .renderType(descriptor1.type) }, ", " ) return "$name($paramTypes)" } private fun renderClassOrObject(descriptor: ClassDescriptor): String { return descriptor.name.asString() } } init { javaDelegate = CallHierarchyNodeDescriptor(myProject, null, element, isBase, navigateToReference) } }
apache-2.0
0d52a6b7ba5b301b80b468739c34a596
38.909524
158
0.56957
6.189069
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/codeVision/CodeVisionProvider.kt
1
4213
// 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 com.intellij.codeInsight.codeVision import com.intellij.codeInsight.codeVision.settings.PlatformCodeVisionIds import com.intellij.codeInsight.codeVision.ui.model.CodeVisionPredefinedActionEntry import com.intellij.openapi.editor.Editor import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiFile import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls /** * @see CodeVisionProviderFactory * If invalidation and calculation should be bound to daemon, then use @see [com.intellij.codeInsight.hints.codeVision.DaemonBoundCodeVisionProvider] * Otherwise implement [CodeVisionProvider] directly * * If you want to implement multiple providers with same meaning (for example, for different languages) * and group them in settings window, then @see [com.intellij.codeInsight.codeVision.settings.CodeVisionGroupSettingProvider] * Also @see [PlatformCodeVisionIds] */ @ApiStatus.Experimental interface CodeVisionProvider<T> { companion object { val EP_NAME = "com.intellij.codeInsight.codeVisionProvider" val providersExtensionPoint = ExtensionPointName.create<CodeVisionProvider<*>>(EP_NAME) } /** * It affects whether the group will be shown in settings or not. * * @return true iff it could potentially provide any lenses for the project */ @JvmDefault fun isAvailableFor(project: Project) = true @JvmDefault fun preparePreview(editor: Editor, file: PsiFile) { } /** * Computes some data on UI thread, before the background thread invocation */ fun precomputeOnUiThread(editor: Editor): T /** * Called during code vision update process * Return true if [computeForEditor] should be called * false otherwise */ fun shouldRecomputeForEditor(editor: Editor, uiData: T) = true /** * Should return text ranges and applicable hints for them, invoked on background thread. * * Note that this method is not executed under read action. */ @Deprecated("Use computeCodeVision instead", ReplaceWith("computeCodeVision")) fun computeForEditor(editor: Editor, uiData: T): List<Pair<TextRange, CodeVisionEntry>> = emptyList() /** * Should return text ranges and applicable hints for them, invoked on background thread. * * Note that this method is not executed under read action. */ fun computeCodeVision(editor: Editor, uiData: T): CodeVisionState = CodeVisionState.Ready(computeForEditor(editor, uiData)) /** * Handle click on a lens at given range * [java.awt.event.MouseEvent] accessible with [codeVisionEntryMouseEventKey] data key from [CodeVisionEntry] */ fun handleClick(editor: Editor, textRange: TextRange, entry: CodeVisionEntry){ if (entry is CodeVisionPredefinedActionEntry) entry.onClick(editor) } /** * Handle click on an extra action on a lens at a given range */ fun handleExtraAction(editor: Editor, textRange: TextRange, actionId: String) = Unit /** * Calls on background BEFORE editor opening * Returns ranges where placeholders should be when editor opens */ @Deprecated("use getPlaceholderCollector") fun collectPlaceholders(editor: Editor): List<TextRange> = emptyList() fun getPlaceholderCollector(editor: Editor, psiFile: PsiFile?) : CodeVisionPlaceholderCollector? = null /** * User-visible name */ @get:Nls val name: String /** * Used for the default sorting of providers */ val relativeOrderings: List<CodeVisionRelativeOrdering> /** * Specifies default anchor for this provider */ val defaultAnchor: CodeVisionAnchorKind /** * Internal id */ val id: String /** * Uses to group provider in settings panel and to share same behavior (like position and ext.) and description * @see PlatformCodeVisionIds * To group different provider implement @see [com.intellij.codeInsight.codeVision.settings.CodeVisionGroupSettingProvider] */ val groupId: String get() = id }
apache-2.0
6fb5f509d6c09ef8ea1aa821e8979b7e
34.116667
158
0.751246
4.554595
false
false
false
false
androidx/androidx
fragment/fragment/src/androidTest/java/androidx/fragment/app/UserVisibleHintTest.kt
3
4228
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.fragment.app import androidx.fragment.app.test.FragmentTestActivity import androidx.test.annotation.UiThreadTest import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.testutils.runOnUiThreadRethrow import com.google.common.truth.Truth.assertWithMessage import leakcanary.DetectLeaksAfterTestSuccess import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain import org.junit.runner.RunWith @Suppress("DEPRECATION") @RunWith(AndroidJUnit4::class) @MediumTest class UserVisibleHintTest { @Suppress("DEPRECATION") var activityRule = androidx.test.rule.ActivityTestRule(FragmentTestActivity::class.java) // Detect leaks BEFORE and AFTER activity is destroyed @get:Rule val ruleChain: RuleChain = RuleChain.outerRule(DetectLeaksAfterTestSuccess()) .around(activityRule) @UiThreadTest @Test fun startOrdering() { var firstStartedFragment: Fragment? = null val callback: (fragment: Fragment) -> Unit = { if (firstStartedFragment == null) { firstStartedFragment = it } } val deferredFragment = ReportStartFragment(callback).apply { userVisibleHint = false } val fragment = ReportStartFragment(callback) val fm = activityRule.activity.supportFragmentManager fm.beginTransaction() .add(deferredFragment, "deferred") .commit() fm.beginTransaction() .add(fragment, "fragment") .commit() activityRule.executePendingTransactions() assertWithMessage("userVisibleHint=false Fragments should start after other Fragments") .that(firstStartedFragment) .isSameInstanceAs(fragment) } @UiThreadTest @Test fun startOrderingAfterSave() { var firstStartedFragment: Fragment? = null val callback: (fragment: Fragment) -> Unit = { if (firstStartedFragment == null) { firstStartedFragment = it } } val fm = activityRule.activity.supportFragmentManager // Add the fragment, save its state, then remove it. var deferredFragment = ReportStartFragment().apply { userVisibleHint = false } fm.beginTransaction().add(deferredFragment, "tag").commit() activityRule.executePendingTransactions() var state: Fragment.SavedState? = null activityRule.runOnUiThreadRethrow { state = fm.saveFragmentInstanceState(deferredFragment) } fm.beginTransaction().remove(deferredFragment).commit() activityRule.executePendingTransactions() // Create a new instance, calling setInitialSavedState deferredFragment = ReportStartFragment(callback) deferredFragment.setInitialSavedState(state) val fragment = ReportStartFragment(callback) fm.beginTransaction() .add(deferredFragment, "deferred") .commit() fm.beginTransaction() .add(fragment, "fragment") .commit() activityRule.executePendingTransactions() assertWithMessage("userVisibleHint=false Fragments should start after other Fragments") .that(firstStartedFragment) .isSameInstanceAs(fragment) } class ReportStartFragment( val callback: ((fragment: Fragment) -> Unit) = {} ) : StrictFragment() { override fun onStart() { super.onStart() callback.invoke(this) } } }
apache-2.0
d70f165f3462d90069fdf52e8ffaac46
33.942149
95
0.677389
5.081731
false
true
false
false
tginsberg/advent-2016-kotlin
src/main/kotlin/com/ginsberg/advent2016/Day09.kt
1
2144
/* * Copyright (c) 2016 by Todd Ginsberg */ package com.ginsberg.advent2016 /** * Advent of Code - Day 9: December 9, 2016 * * From http://adventofcode.com/2016/day/9 * */ class Day09(private val input: String) { private val digits = Regex("""^\((\d+)x(\d+)\).*""") /** * What is the decompressed length of the file (your puzzle input)? */ fun solvePart1(): Long = decodeV1Length(input.replace("""\s+""", "")) /** * What is the decompressed length of the file using this improved format? */ fun solvePart2(): Long = decodeV2Length(input.replace("""\s+""", "")) private tailrec fun decodeV1Length(rest: String, carry: Long = 0): Long = when { rest.isEmpty() -> carry !rest.startsWith("(") -> decodeV1Length(rest.substringAt("("), carry + rest.substringBefore("(").length) else -> { val digits = parseDigitsFromHead(rest) val headless = rest.substringAfter(")") decodeV1Length( headless.substring(digits.first), carry + (digits.first * digits.second) ) } } private tailrec fun decodeV2Length(rest: String, carry: Long = 0L): Long = when { rest.isEmpty() -> carry !rest.startsWith("(") -> decodeV2Length(rest.substringAt("("), carry + rest.substringBefore("(").length) else -> { val digits = parseDigitsFromHead(rest) val headless = rest.substringAfter(")") decodeV2Length( headless.substring(digits.first), carry + ((digits.second) * decodeV2Length(headless.substring(0, digits.first))) ) } } fun String.substringAt(str: String): String = if (this.contains(str)) str + this.substringAfter(str) else "" fun parseDigitsFromHead(line: String): Pair<Int, Int> = digits.matchEntire(line)?.destructured?.let { Pair(it.component1().toInt(), it.component2().toInt()) } ?: Pair(0, 0) }
mit
9191ef0446405d27c863fd69c6d1f54d
31.484848
116
0.545709
4.296593
false
false
false
false
GunoH/intellij-community
platform/vcs-tests/testSrc/com/intellij/openapi/vcs/roots/VcsIntegrationEnablerTest.kt
9
4520
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.roots import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.openapi.project.guessProjectDir import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.* import com.intellij.openapi.vcs.changes.committed.MockAbstractVcs import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.replaceService import com.intellij.util.containers.ContainerUtil import com.intellij.vcsUtil.VcsUtil import java.io.File class VcsIntegrationEnablerTest : VcsRootBaseTest() { private var myTestRoot: VirtualFile? = null @Throws(Exception::class) public override fun setUp() { super.setUp() myProject.replaceService(VcsNotifier::class.java, TestVcsNotifier(myProject), testRootDisposable) myTestRoot = projectRoot.parent } fun `test one root for the whole project then just add vcs root`() { doTest(given("."), null, null) } fun `test no mock roots then init and notify`() { doTest(given(), notification("Created mock repository in " + projectRoot.presentableUrl), ".", VcsTestUtil.toAbsolute(".", myProject)) } fun `test below mock no inside then notify`() { doTest(given(".."), notification("Added mock root: " + myTestRoot!!.presentableUrl)) } fun `test mock for project some inside then notify`() { doTest(given(".", "community"), notification("Added mock roots: " + projectRoot.presentableUrl + ", " + getPresentationForRoot("community"))) } fun `test below mock some inside then notify`() { doTest(given("..", "community"), notification("Added mock roots: " + myTestRoot!!.presentableUrl + ", " + getPresentationForRoot("community"))) } fun `test not under mock some inside then notify`() { doTest(given("community", "contrib"), notification( "Added mock roots: " + getPresentationForRoot("community") + ", " + getPresentationForRoot("contrib")) ) } private fun doTest(vcsRoots: Collection<VcsRoot>, notification: Notification? ) { doTest(vcsRoots, notification, null) } private fun doTest(vcsRoots: Collection<VcsRoot>, notification: Notification?, mock_init: String?, vararg vcs_roots: String) { for (vcsRoot in vcsRoots) { assertTrue(File(vcsRoot.path.path, DOT_MOCK).mkdirs()) } val vcsRootsList = mutableListOf(*vcs_roots) //default if (vcsRootsList.isEmpty()) { vcsRootsList.addAll(ContainerUtil.map(vcsRoots) { root -> root.path.path }) } TestIntegrationEnabler(vcs).enable(vcsRoots) assertVcsRoots(vcsRootsList) if (mock_init != null) { assertMockInit(mock_init) } VcsTestUtil.assertNotificationShown(myProject, notification) } private fun assertMockInit(root: String) { val rootFile = File(projectRoot.path, root) assertTrue(File(rootFile.path, DOT_MOCK).exists()) } private fun assertVcsRoots(expectedVcsRoots: Collection<String>) { val actualRoots = ProjectLevelVcsManager.getInstance(myProject).getRootsUnderVcsWithoutFiltering(vcs) VcsTestUtil.assertEqualCollections(actualRoots.map { it.path }, expectedVcsRoots) } private fun given(vararg roots: String): Collection<VcsRoot> { return ContainerUtil.map(roots) { s -> val path = VcsTestUtil.toAbsolute(s, myProject) LocalFileSystem.getInstance().refreshAndFindFileByPath(path) VcsRoot(vcs, VcsUtil.getVirtualFile(path)!!) } } @Suppress("UnresolvedPluginConfigReference") internal fun notification(content: String): Notification { return Notification("Test", "", content, NotificationType.INFORMATION) } private fun getPresentationForRoot(root: String): String { return FileUtil.toSystemDependentName(VcsTestUtil.toAbsolute(root, myProject)) } private class TestIntegrationEnabler(vcs: MockAbstractVcs) : VcsIntegrationEnabler(vcs, vcs.project.guessProjectDir()!!) { override fun initOrNotifyError(directory: VirtualFile): Boolean { val file = File(directory.path, DOT_MOCK) VcsNotifier.getInstance(myProject).notifySuccess(null, "", "Created mock repository in " + directory.presentableUrl) return file.mkdir() } } }
apache-2.0
be4eb493f4f5c0feab2ca7bc6655fc68
35.451613
140
0.708628
4.547284
false
true
false
false
krsnvijay/Black-Board-App
app/src/main/java/com/notadeveloper/app/blackboard/ui/adapters/ExpandableListAdapter.kt
1
2761
package com.notadeveloper.app.blackboard.ui.adapters /** * Created by Chirag on 10/12/2017. */ import android.content.Context import android.graphics.Typeface import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseExpandableListAdapter import android.widget.TextView import com.notadeveloper.app.blackboard.R import java.util.HashMap class ExpandableListAdapter(private val _context: Context, private val _listDataHeader: List<String> // header titles , // child data in format of header title, child title private val _listDataChild: HashMap<String, List<String>>) : BaseExpandableListAdapter() { override fun getChild(groupPosition: Int, childPosititon: Int): Any = this._listDataChild[this._listDataHeader[groupPosition]]?.get(childPosititon) ?: "No Data" override fun getChildId(groupPosition: Int, childPosition: Int): Long = childPosition.toLong() override fun getChildView(groupPosition: Int, childPosition: Int, isLastChild: Boolean, convertView: View?, parent: ViewGroup): View { var convertView = convertView val childText = getChild(groupPosition, childPosition) as String if (convertView == null) { val infalInflater = this._context .getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater convertView = infalInflater.inflate(R.layout.listt_item, null) } val txtListChild = convertView!! .findViewById<TextView>(R.id.lblListItem) txtListChild.text = (childPosition + 1).toString() + ". " + childText return convertView } override fun getChildrenCount(groupPosition: Int): Int = this._listDataChild[this._listDataHeader[groupPosition]]?.size ?: 0 override fun getGroup(groupPosition: Int): Any = this._listDataHeader[groupPosition] override fun getGroupCount(): Int = this._listDataHeader.size override fun getGroupId(groupPosition: Int): Long = groupPosition.toLong() override fun getGroupView(groupPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup): View { var convertView = convertView val headerTitle = getGroup(groupPosition) as String if (convertView == null) { val infalInflater = this._context .getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater convertView = infalInflater.inflate(R.layout.list_group, null) } val lblListHeader = convertView!! .findViewById<TextView>(R.id.lblListHeader) lblListHeader.setTypeface(null, Typeface.BOLD) lblListHeader.text = headerTitle return convertView } override fun hasStableIds(): Boolean = false override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean = true }
mit
b249f303e9b8c33f570be9be01547506
34.87013
96
0.742847
4.474878
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/KotlinDocumentationProvider.kt
1
37796
// 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 import com.google.common.html.HtmlEscapers import com.intellij.codeInsight.documentation.DocumentationManagerUtil import com.intellij.codeInsight.javadoc.JavaDocExternalFilter import com.intellij.codeInsight.javadoc.JavaDocInfoGeneratorFactory import com.intellij.lang.documentation.AbstractDocumentationProvider import com.intellij.lang.documentation.CompositeDocumentationProvider import com.intellij.lang.documentation.DocumentationMarkup.* import com.intellij.lang.documentation.DocumentationSettings import com.intellij.lang.documentation.ExternalDocumentationProvider import com.intellij.lang.java.JavaDocumentationProvider import com.intellij.openapi.application.runReadAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.editor.richcopy.HtmlSyntaxInfoUtil import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.psi.impl.compiled.ClsMethodImpl import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.io.HttpRequests import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration import org.jetbrains.kotlin.base.util.KotlinPlatformUtils import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject import org.jetbrains.kotlin.idea.decompiler.navigation.SourceNavigationHelper import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingColors import org.jetbrains.kotlin.idea.kdoc.* import org.jetbrains.kotlin.idea.kdoc.KDocRenderer.appendKDocContent import org.jetbrains.kotlin.idea.kdoc.KDocRenderer.appendKDocSections import org.jetbrains.kotlin.idea.kdoc.KDocTemplate.DescriptionBodyTemplate import org.jetbrains.kotlin.idea.parameterInfo.KotlinIdeDescriptorRenderer import org.jetbrains.kotlin.idea.parameterInfo.KotlinIdeDescriptorRendererHighlightingManager import org.jetbrains.kotlin.idea.parameterInfo.KotlinIdeDescriptorRendererHighlightingManager.Companion.eraseTypeParameter import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveToDescriptors import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi import org.jetbrains.kotlin.kdoc.psi.api.KDoc import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.NULLABILITY_ANNOTATIONS import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.renderer.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver import org.jetbrains.kotlin.resolve.deprecation.deprecatedByAnnotationReplaceWithExpression import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.utils.addToStdlib.constant import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.util.function.Consumer class HtmlClassifierNamePolicy(val base: ClassifierNamePolicy) : ClassifierNamePolicy { override fun renderClassifier(classifier: ClassifierDescriptor, renderer: DescriptorRenderer): String { if (DescriptorUtils.isAnonymousObject(classifier)) { val supertypes = classifier.typeConstructor.supertypes return buildString { append("&lt;anonymous object") if (supertypes.isNotEmpty()) { append(" : ") supertypes.joinTo(this) { val ref = it.constructor.declarationDescriptor if (ref != null) renderClassifier(ref, renderer) else "&lt;ERROR CLASS&gt;" } } append("&gt;") } } val name = base.renderClassifier(classifier, renderer) if (classifier.isBoringBuiltinClass()) return name return buildString { val ref = classifier.fqNameUnsafe.toString() DocumentationManagerUtil.createHyperlink(this, ref, name, true, false) } } } class WrapValueParameterHandler(val base: DescriptorRenderer.ValueParametersHandler) : DescriptorRenderer.ValueParametersHandler { override fun appendBeforeValueParameters(parameterCount: Int, builder: StringBuilder) { base.appendBeforeValueParameters(parameterCount, builder) } override fun appendBeforeValueParameter( parameter: ValueParameterDescriptor, parameterIndex: Int, parameterCount: Int, builder: StringBuilder ) { builder.append("\n ") base.appendBeforeValueParameter(parameter, parameterIndex, parameterCount, builder) } override fun appendAfterValueParameter( parameter: ValueParameterDescriptor, parameterIndex: Int, parameterCount: Int, builder: StringBuilder ) { if (parameterIndex != parameterCount - 1) { builder.append(",") } } override fun appendAfterValueParameters(parameterCount: Int, builder: StringBuilder) { if (parameterCount > 0) { builder.appendLine() } base.appendAfterValueParameters(parameterCount, builder) } } class KotlinDocumentationProvider : AbstractDocumentationProvider(), ExternalDocumentationProvider { override fun collectDocComments(file: PsiFile, sink: Consumer<in PsiDocCommentBase>) { if (file !is KtFile) return PsiTreeUtil.processElements(file) { val comment = (it as? KtDeclaration)?.docComment if (comment != null) sink.accept(comment) true } } @Nls override fun generateRenderedDoc(comment: PsiDocCommentBase): String? { val docComment = comment as? KDoc ?: return null val result = StringBuilder().also { it.renderKDoc(docComment.getDefaultSection(), docComment.getAllSections()) } @Suppress("HardCodedStringLiteral") return JavaDocExternalFilter.filterInternalDocInfo(result.toString()) } override fun getCustomDocumentationElement(editor: Editor, file: PsiFile, contextElement: PsiElement?, targetOffset: Int): PsiElement? { return if (contextElement.isModifier()) contextElement else null } @Nls override fun getQuickNavigateInfo(element: PsiElement?, originalElement: PsiElement?): String? { return if (element == null) null else getText(element, originalElement, true) } @Nls override fun generateDoc(element: PsiElement, originalElement: PsiElement?): String? { return getText(element, originalElement, false) } override fun getDocumentationElementForLink(psiManager: PsiManager, link: String, context: PsiElement?): PsiElement? { val navElement = context?.navigationElement as? KtElement ?: return null val resolutionFacade = navElement.getResolutionFacade() val bindingContext = navElement.safeAnalyzeNonSourceRootCode(resolutionFacade, BodyResolveMode.PARTIAL) val contextDescriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, navElement] ?: return null val descriptors = resolveKDocLink( bindingContext, resolutionFacade, contextDescriptor, null, link.split('.') ) val target = descriptors.firstOrNull() ?: return null return DescriptorToSourceUtilsIde.getAnyDeclaration(psiManager.project, target) } override fun getDocumentationElementForLookupItem(psiManager: PsiManager, `object`: Any?, element: PsiElement?): PsiElement? { if (`object` is DeclarationLookupObject) { `object`.psiElement?.let { return it } `object`.descriptor?.let { descriptor -> return DescriptorToSourceUtilsIde.getAnyDeclaration(psiManager.project, descriptor) } } return null } override fun getUrlFor(element: PsiElement?, originalElement: PsiElement?): List<String>? { return KotlinExternalDocUrlsProvider.getExternalJavaDocUrl(element) } override fun fetchExternalDocumentation( project: Project?, element: PsiElement?, docUrls: List<String>?, onHover: Boolean ): String? { if (docUrls == null || project == null || element == null || !runReadAction { element.language }.`is`(KotlinLanguage.INSTANCE) ) { return null } val docFilter = KotlinDocExtractorFromJavaDoc(project) for (docURL in docUrls) { try { val externalDoc = docFilter.getExternalDocInfoForElement(docURL, element) if (!StringUtil.isEmpty(externalDoc)) { return externalDoc } } catch (ignored: ProcessCanceledException) { break } catch (e: IndexNotReadyException) { throw e } catch (e: HttpRequests.HttpStatusException) { logger<KotlinDocumentationProvider>().info(e.url + ": " + e.statusCode) } catch (e: Exception) { logger<KotlinDocumentationProvider>().info(e) } } return null } @Deprecated("Deprecated in Java") override fun hasDocumentationFor(element: PsiElement?, originalElement: PsiElement?): Boolean { return CompositeDocumentationProvider.hasUrlsFor(this, element, originalElement) } override fun canPromptToConfigureDocumentation(element: PsiElement?): Boolean { return false } override fun promptToConfigureDocumentation(element: PsiElement?) { // do nothing } companion object { private val LOG = Logger.getInstance(KotlinDocumentationProvider::class.java) private val javaDocumentProvider = JavaDocumentationProvider() //private val DESCRIPTOR_RENDERER = DescriptorRenderer.HTML.withOptions { // classifierNamePolicy = HtmlClassifierNamePolicy(ClassifierNamePolicy.SHORT) // valueParametersHandler = WrapValueParameterHandler(valueParametersHandler) // annotationArgumentsRenderingPolicy = AnnotationArgumentsRenderingPolicy.UNLESS_EMPTY // renderCompanionObjectName = true // withDefinedIn = false // eachAnnotationOnNewLine = true // boldOnlyForNamesInHtml = true // excludedTypeAnnotationClasses = NULLABILITY_ANNOTATIONS // defaultParameterValueRenderer = { (it.source.getPsi() as? KtParameter)?.defaultValue?.text ?: "..." } //} private val DESCRIPTOR_RENDERER = KotlinIdeDescriptorRenderer.withOptions { textFormat = RenderingFormat.HTML modifiers = DescriptorRendererModifier.ALL classifierNamePolicy = HtmlClassifierNamePolicy(ClassifierNamePolicy.SHORT) valueParametersHandler = WrapValueParameterHandler(valueParametersHandler) annotationArgumentsRenderingPolicy = AnnotationArgumentsRenderingPolicy.UNLESS_EMPTY renderCompanionObjectName = true renderPrimaryConstructorParametersAsProperties = true withDefinedIn = false eachAnnotationOnNewLine = true excludedTypeAnnotationClasses = NULLABILITY_ANNOTATIONS defaultParameterValueRenderer = { (it.source.getPsi() as? KtParameter)?.defaultValue?.text ?: "..." } } private data class TextAttributesAdapter(val attributes: TextAttributes) : KotlinIdeDescriptorRendererHighlightingManager.Companion.Attributes private fun createHighlightingManager(project: Project?): KotlinIdeDescriptorRendererHighlightingManager<KotlinIdeDescriptorRendererHighlightingManager.Companion.Attributes> { if (!DocumentationSettings.isHighlightingOfQuickDocSignaturesEnabled()) { return KotlinIdeDescriptorRendererHighlightingManager.NO_HIGHLIGHTING } return object : KotlinIdeDescriptorRendererHighlightingManager<TextAttributesAdapter> { override fun StringBuilder.appendHighlighted(value: String, attributes: TextAttributesAdapter) { HtmlSyntaxInfoUtil.appendStyledSpan( this, attributes.attributes, value, DocumentationSettings.getHighlightingSaturation(false) ) } override fun StringBuilder.appendCodeSnippetHighlightedByLexer(codeSnippet: String) { HtmlSyntaxInfoUtil.appendHighlightedByLexerAndEncodedAsHtmlCodeSnippet( this, project!!, KotlinLanguage.INSTANCE, codeSnippet, DocumentationSettings.getHighlightingSaturation(false) ) } private fun resolveKey(key: TextAttributesKey): TextAttributesAdapter { return TextAttributesAdapter(EditorColorsManager.getInstance().globalScheme.getAttributes(key)!!) } override val asError get() = resolveKey(KotlinHighlightingColors.RESOLVED_TO_ERROR) override val asInfo get() = resolveKey(KotlinHighlightingColors.BLOCK_COMMENT) override val asDot get() = resolveKey(KotlinHighlightingColors.DOT) override val asComma get() = resolveKey(KotlinHighlightingColors.COMMA) override val asColon get() = resolveKey(KotlinHighlightingColors.COLON) override val asDoubleColon get() = resolveKey(KotlinHighlightingColors.DOUBLE_COLON) override val asParentheses get() = resolveKey(KotlinHighlightingColors.PARENTHESIS) override val asArrow get() = resolveKey(KotlinHighlightingColors.ARROW) override val asBrackets get() = resolveKey(KotlinHighlightingColors.BRACKETS) override val asBraces get() = resolveKey(KotlinHighlightingColors.BRACES) override val asOperationSign get() = resolveKey(KotlinHighlightingColors.OPERATOR_SIGN) override val asNonNullAssertion get() = resolveKey(KotlinHighlightingColors.EXCLEXCL) override val asNullityMarker get() = resolveKey(KotlinHighlightingColors.QUEST) override val asKeyword get() = resolveKey(KotlinHighlightingColors.KEYWORD) override val asVal get() = resolveKey(KotlinHighlightingColors.VAL_KEYWORD) override val asVar get() = resolveKey(KotlinHighlightingColors.VAR_KEYWORD) override val asAnnotationName get() = resolveKey(KotlinHighlightingColors.ANNOTATION) override val asAnnotationAttributeName get() = resolveKey(KotlinHighlightingColors.ANNOTATION_ATTRIBUTE_NAME_ATTRIBUTES) override val asClassName get() = resolveKey(KotlinHighlightingColors.CLASS) override val asPackageName get() = resolveKey(DefaultLanguageHighlighterColors.IDENTIFIER) override val asObjectName get() = resolveKey(KotlinHighlightingColors.OBJECT) override val asInstanceProperty get() = resolveKey(KotlinHighlightingColors.INSTANCE_PROPERTY) override val asTypeAlias get() = resolveKey(KotlinHighlightingColors.TYPE_ALIAS) override val asParameter get() = resolveKey(KotlinHighlightingColors.PARAMETER) override val asTypeParameterName get() = resolveKey(KotlinHighlightingColors.TYPE_PARAMETER) override val asLocalVarOrVal get() = resolveKey(KotlinHighlightingColors.LOCAL_VARIABLE) override val asFunDeclaration get() = resolveKey(KotlinHighlightingColors.FUNCTION_DECLARATION) override val asFunCall get() = resolveKey(KotlinHighlightingColors.FUNCTION_CALL) } .eraseTypeParameter() } private fun StringBuilder.appendHighlighted( value: String, attributesBuilder: KotlinIdeDescriptorRendererHighlightingManager<KotlinIdeDescriptorRendererHighlightingManager.Companion.Attributes>.() -> KotlinIdeDescriptorRendererHighlightingManager.Companion.Attributes ) { with(createHighlightingManager(project = null)) { [email protected](value, attributesBuilder()) } } private fun highlight( value: String, attributesBuilder: KotlinIdeDescriptorRendererHighlightingManager<KotlinIdeDescriptorRendererHighlightingManager.Companion.Attributes>.() -> KotlinIdeDescriptorRendererHighlightingManager.Companion.Attributes ): String { return StringBuilder().apply { appendHighlighted(value, attributesBuilder) }.toString() } private fun StringBuilder.appendCodeSnippetHighlightedByLexer(project: Project, codeSnippet: String) { with(createHighlightingManager(project)) { appendCodeSnippetHighlightedByLexer(codeSnippet) } } internal fun StringBuilder.renderKDoc( contentTag: KDocTag, sections: List<KDocSection> = if (contentTag is KDocSection) listOf(contentTag) else emptyList() ) { insert(DescriptionBodyTemplate.Kotlin()) { content { appendKDocContent(contentTag) } sections { appendKDocSections(sections) } } } private fun renderEnumSpecialFunction(element: KtClass, functionDescriptor: FunctionDescriptor, quickNavigation: Boolean): String { val kdoc = run { val declarationDescriptor = element.resolveToDescriptorIfAny() val enumDescriptor = declarationDescriptor?.getSuperClassNotAny() ?: return@run null val enumDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, enumDescriptor) as? KtDeclaration ?: return@run null val enumSource = SourceNavigationHelper.getNavigationElement(enumDeclaration) val functionName = functionDescriptor.fqNameSafe.shortName().asString() return@run enumSource.findDescendantOfType<KDoc> { doc -> doc.getChildrenOfType<KDocSection>().any { it.findTagByName(functionName) != null } } } return buildString { insert(KDocTemplate()) { definition { renderDefinition(functionDescriptor, DESCRIPTOR_RENDERER .withIdeOptions { highlightingManager = createHighlightingManager(element.project) } ) } if (!quickNavigation && kdoc != null) { description { renderKDoc(kdoc.getDefaultSection()) } } } } } @NlsSafe private fun renderEnum(element: KtClass, originalElement: PsiElement?, quickNavigation: Boolean): String { val referenceExpression = originalElement?.getNonStrictParentOfType<KtReferenceExpression>() if (referenceExpression != null) { // When caret on special enum function (e.g. SomeEnum.values<caret>()) // element is not an KtReferenceExpression, but KtClass of enum // so reference extracted from originalElement val context = referenceExpression.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) (context[BindingContext.REFERENCE_TARGET, referenceExpression] ?: context[BindingContext.REFERENCE_TARGET, referenceExpression.getChildOfType<KtReferenceExpression>()])?.let { if (it is FunctionDescriptor) // To protect from Some<caret>Enum.values() return renderEnumSpecialFunction(element, it, quickNavigation) } } return renderKotlinDeclaration(element, quickNavigation) } @Nls private fun getText(element: PsiElement, originalElement: PsiElement?, quickNavigation: Boolean) = getTextImpl(element, originalElement, quickNavigation) @Nls private fun getTextImpl(element: PsiElement, originalElement: PsiElement?, quickNavigation: Boolean): String? { if (element is PsiWhiteSpace) { val itElement = findElementWithText(originalElement, "it") val itReference = itElement?.getParentOfType<KtNameReferenceExpression>(false) if (itReference != null) { return getTextImpl(itReference, originalElement, quickNavigation) } } if (element is KtTypeReference) { val declaration = element.parent if (declaration is KtCallableDeclaration && declaration.receiverTypeReference == element) { val thisElement = findElementWithText(originalElement, "this") if (thisElement != null) { return getTextImpl(declaration, originalElement, quickNavigation) } } } if (element is KtClass && element.isEnum()) { // When caret on special enum function (e.g. SomeEnum.values<caret>()) // element is not an KtReferenceExpression, but KtClass of enum return renderEnum(element, originalElement, quickNavigation) } else if (element is KtEnumEntry && !quickNavigation) { val ordinal = element.containingClassOrObject?.body?.run { getChildrenOfType<KtEnumEntry>().indexOf(element) } @Suppress("HardCodedStringLiteral") return buildString { insert(buildKotlinDeclaration(element, quickNavigation)) { definition { it.inherit() ordinal?.let { append("<br>") appendHighlighted("// ") { asInfo } appendHighlighted(KotlinBundle.message("quick.doc.text.enum.ordinal", ordinal)) { asInfo } } } } } } else if (element is KtDeclaration) { return renderKotlinDeclaration(element, quickNavigation) } else if (element is KtNameReferenceExpression && element.getReferencedName() == "it") { return renderKotlinImplicitLambdaParameter(element, quickNavigation) } else if (element is KtLightDeclaration<*, *>) { val origin = element.kotlinOrigin ?: return null return renderKotlinDeclaration(origin, quickNavigation) } else if (element is KtValueArgumentList) { val referenceExpression = element.prevSibling as? KtSimpleNameExpression ?: return null val calledElement = referenceExpression.mainReference.resolve() if (calledElement is KtNamedFunction || calledElement is KtConstructor<*>) { // In case of Kotlin function or constructor return renderKotlinDeclaration(calledElement as KtExpression, quickNavigation) } else if (calledElement is ClsMethodImpl || calledElement is PsiMethod) { // In case of java function or constructor return javaDocumentProvider.generateDoc(calledElement, referenceExpression) } } else if (element is KtCallExpression) { val calledElement = element.referenceExpression()?.mainReference?.resolve() return calledElement?.let { getTextImpl(it, originalElement, quickNavigation) } } else if (element.isModifier()) { when (element.text) { KtTokens.LATEINIT_KEYWORD.value -> return KotlinBundle.message("quick.doc.text.lateinit") KtTokens.TAILREC_KEYWORD.value -> return KotlinBundle.message("quick.doc.text.tailrec") } } if (quickNavigation) { val referenceExpression = originalElement?.getNonStrictParentOfType<KtReferenceExpression>() if (referenceExpression != null) { val context = referenceExpression.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) val declarationDescriptor = context[BindingContext.REFERENCE_TARGET, referenceExpression] if (declarationDescriptor != null) { return mixKotlinToJava(declarationDescriptor, element, originalElement) } } } // This element was resolved to non-kotlin element, it will be rendered with own provider return null } @NlsSafe private fun renderKotlinDeclaration(declaration: KtExpression, quickNavigation: Boolean) = buildString { insert(buildKotlinDeclaration(declaration, quickNavigation)) {} } private fun buildKotlinDeclaration(declaration: KtExpression, quickNavigation: Boolean): KDocTemplate { val resolutionFacade = declaration.getResolutionFacade() val context = declaration.safeAnalyzeNonSourceRootCode(resolutionFacade, BodyResolveMode.PARTIAL) val declarationDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration] if (declarationDescriptor == null) { LOG.info("Failed to find descriptor for declaration " + declaration.getElementTextWithContext()) return KDocTemplate.NoDocTemplate().apply { error { append(KotlinBundle.message("quick.doc.no.documentation")) } } } return buildKotlin(context, declarationDescriptor, quickNavigation, declaration, resolutionFacade) } @NlsSafe private fun renderKotlinImplicitLambdaParameter(element: KtReferenceExpression, quickNavigation: Boolean): String? { val resolutionFacade = element.getResolutionFacade() val context = element.safeAnalyzeNonSourceRootCode(resolutionFacade, BodyResolveMode.PARTIAL) val target = element.mainReference.resolveToDescriptors(context).singleOrNull() as? ValueParameterDescriptor? ?: return null return renderKotlin(context, target, quickNavigation, element, resolutionFacade) } private fun renderKotlin( context: BindingContext, declarationDescriptor: DeclarationDescriptor, quickNavigation: Boolean, ktElement: KtElement, resolutionFacade: ResolutionFacade, ) = buildString { insert(buildKotlin(context, declarationDescriptor, quickNavigation, ktElement, resolutionFacade)) {} } private fun buildKotlin( context: BindingContext, declarationDescriptor: DeclarationDescriptor, quickNavigation: Boolean, ktElement: KtElement, resolutionFacade: ResolutionFacade, ): KDocTemplate { @Suppress("NAME_SHADOWING") var declarationDescriptor = declarationDescriptor if (declarationDescriptor is ValueParameterDescriptor) { val property = context[BindingContext.VALUE_PARAMETER_AS_PROPERTY, declarationDescriptor] if (property != null) { declarationDescriptor = property } } @OptIn(FrontendInternals::class) val deprecationProvider = resolutionFacade.frontendService<DeprecationResolver>() return KDocTemplate().apply { definition { renderDefinition(declarationDescriptor, DESCRIPTOR_RENDERER .withIdeOptions { highlightingManager = createHighlightingManager(ktElement.project) } ) } insertDeprecationInfo(declarationDescriptor, deprecationProvider, ktElement.project) if (!quickNavigation) { description { declarationDescriptor.findKDoc { DescriptorToSourceUtilsIde.getAnyDeclaration(ktElement.project, it) }?.let { renderKDoc(it.contentTag, it.sections) return@description } if (declarationDescriptor is ClassConstructorDescriptor && !declarationDescriptor.isPrimary) { declarationDescriptor.constructedClass.findKDoc { DescriptorToSourceUtilsIde.getAnyDeclaration( ktElement.project, it ) }?.let { renderKDoc(it.contentTag, it.sections) return@description } } if (declarationDescriptor is CallableDescriptor) { // If we couldn't find KDoc, try to find javadoc in one of super's insert(DescriptionBodyTemplate.FromJava()) { body = extractJavaDescription(declarationDescriptor) } } } } getContainerInfo(ktElement)?.toString()?.takeIf { it.isNotBlank() }?.let { info -> containerInfo { append(info) } } } } private fun StringBuilder.renderDefinition(descriptor: DeclarationDescriptor, renderer: DescriptorRenderer) { append(renderer.render(descriptor)) } private fun extractJavaDescription(declarationDescriptor: DeclarationDescriptor): String { val psi = declarationDescriptor.findPsi() as? KtFunction ?: return "" val lightElement = LightClassUtil.getLightClassMethod(psi) // Light method for super's scan in javadoc info gen val javaDocInfoGenerator = JavaDocInfoGeneratorFactory.create(psi.project, lightElement) val builder = StringBuilder() if (javaDocInfoGenerator.generateDocInfoCore(builder, false)) { val renderedJava = builder.toString() return renderedJava.removeRange( renderedJava.indexOf(DEFINITION_START), renderedJava.indexOf(DEFINITION_END) ) // Cut off light method signature } return "" } private fun KDocTemplate.insertDeprecationInfo( declarationDescriptor: DeclarationDescriptor, deprecationResolver: DeprecationResolver, project: Project ) { val deprecationInfo = deprecationResolver.getDeprecations(declarationDescriptor).firstOrNull() ?: return deprecation { deprecationInfo.message?.let { message -> append(SECTION_HEADER_START) append(KotlinBundle.message("quick.doc.section.deprecated")) append(SECTION_SEPARATOR) append(message.htmlEscape()) append(SECTION_END) } deprecationInfo.deprecatedByAnnotationReplaceWithExpression()?.let { replaceWith -> append(SECTION_HEADER_START) append(KotlinBundle.message("quick.doc.section.replace.with")) append(SECTION_SEPARATOR) wrapTag("code") { appendCodeSnippetHighlightedByLexer(project, replaceWith.htmlEscape()) } append(SECTION_END) } } } private fun getContainerInfo(element: PsiElement?): HtmlChunk? { if (element !is KtExpression) return null val resolutionFacade = element.getResolutionFacade() val context = element.safeAnalyzeNonSourceRootCode(resolutionFacade, BodyResolveMode.PARTIAL) val descriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, element] ?: return null if (DescriptorUtils.isLocal(descriptor)) return null val containingDeclaration = descriptor.containingDeclaration ?: return null val fqNameSection = containingDeclaration.fqNameSafe .takeUnless { it.isRoot } ?.let { @Nls val link = StringBuilder().apply { val highlighted = if (DocumentationSettings.isSemanticHighlightingOfLinksEnabled()) highlight(it.asString()) { asClassName } else it.asString() DocumentationManagerUtil.createHyperlink(this, it.asString(), highlighted, false, false) } HtmlChunk.fragment( HtmlChunk.tag("icon").attr("src", "/org/jetbrains/kotlin/idea/icons/classKotlin.svg"), HtmlChunk.nbsp(), HtmlChunk.raw(link.toString()), HtmlChunk.br() ) } ?: HtmlChunk.empty() val fileNameSection = descriptor .safeAs<DeclarationDescriptorWithSource>() ?.source ?.containingFile ?.name ?.takeIf { containingDeclaration is PackageFragmentDescriptor } ?.let { HtmlChunk.fragment( HtmlChunk.tag("icon").attr("src", "/org/jetbrains/kotlin/idea/icons/kotlin_file.svg"), HtmlChunk.nbsp(), HtmlChunk.text(it), HtmlChunk.br() ) } ?: HtmlChunk.empty() return HtmlChunk.fragment(fqNameSection, fileNameSection) } private fun String.htmlEscape(): String = HtmlEscapers.htmlEscaper().escape(this) private inline fun StringBuilder.wrap(prefix: String, postfix: String, crossinline body: () -> Unit) { this.append(prefix) body() this.append(postfix) } private inline fun StringBuilder.wrapTag(tag: String, crossinline body: () -> Unit) { wrap("<$tag>", "</$tag>", body) } @NlsSafe private fun mixKotlinToJava( declarationDescriptor: DeclarationDescriptor, element: PsiElement, originalElement: PsiElement? ): String? { if (KotlinPlatformUtils.isCidr) { // No Java support in CIDR return null } val originalInfo = JavaDocumentationProvider().getQuickNavigateInfo(element, originalElement) if (originalInfo != null) { val renderedDecl = constant { DESCRIPTOR_RENDERER.withIdeOptions { withDefinedIn = false } }.render(declarationDescriptor) return "$renderedDecl<br/>" + KotlinBundle.message("quick.doc.section.java.declaration") + "<br/>$originalInfo" } return null } private fun findElementWithText(element: PsiElement?, text: String): PsiElement? { return when { element == null -> null element.text == text -> element element.prevLeaf()?.text == text -> element.prevLeaf() else -> null } } private fun PsiElement?.isModifier() = this != null && parent is KtModifierList && KtTokens.MODIFIER_KEYWORDS_ARRAY.firstOrNull { it.value == text } != null } }
apache-2.0
c9d5f13916f4fc6b5a8ed9f1a04c701f
48.731579
183
0.642925
6.022307
false
false
false
false
appmattus/layercache
testutils/src/main/kotlin/com/appmattus/layercache/keystore/AndroidOpenSSLProvider.kt
1
2528
/* * Copyright 2020 Appmattus Limited * * 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.appmattus.layercache.keystore import android.annotation.SuppressLint import java.security.AlgorithmParameters import java.security.Key import java.security.Provider import java.security.SecureRandom import java.security.spec.AlgorithmParameterSpec import javax.crypto.Cipher import javax.crypto.CipherSpi class AndroidOpenSSLProvider : Provider("AndroidOpenSSL", 1.0, "") { init { put("Cipher.RSA/ECB/PKCS1Padding", RsaCipher::class.java.name) } @Suppress("TooManyFunctions") class RsaCipher : CipherSpi() { @SuppressLint("GetInstance") private val wrapped = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC") override fun engineSetMode(p0: String?) = Unit override fun engineInit(p0: Int, p1: Key?, p2: SecureRandom?) = wrapped.init(p0, p1, p2) override fun engineInit(p0: Int, p1: Key?, p2: AlgorithmParameterSpec?, p3: SecureRandom?) = wrapped.init(p0, p1, p2, p3) override fun engineInit(p0: Int, p1: Key?, p2: AlgorithmParameters?, p3: SecureRandom?) = wrapped.init(p0, p1, p2, p3) override fun engineGetIV(): ByteArray = wrapped.iv override fun engineDoFinal(p0: ByteArray?, p1: Int, p2: Int): ByteArray = wrapped.doFinal(p0, p1, p2) override fun engineDoFinal(p0: ByteArray?, p1: Int, p2: Int, p3: ByteArray?, p4: Int) = wrapped.doFinal(p0, p1, p2, p3, p4) override fun engineSetPadding(p0: String?) = Unit override fun engineGetParameters(): AlgorithmParameters = wrapped.parameters override fun engineUpdate(p0: ByteArray?, p1: Int, p2: Int): ByteArray = wrapped.update(p0, p1, p2) override fun engineUpdate(p0: ByteArray?, p1: Int, p2: Int, p3: ByteArray?, p4: Int): Int = wrapped.update(p0, p1, p2, p3, p4) override fun engineGetBlockSize(): Int = wrapped.blockSize override fun engineGetOutputSize(p0: Int): Int = wrapped.getOutputSize(p0) } }
apache-2.0
c1d622afadda421459ffc93752dc2d5e
38.5
134
0.709256
3.642651
false
false
false
false
BenWoodworth/FastCraft
fastcraft-bukkit/bukkit-1.7/src/main/kotlin/net/benwoodworth/fastcraft/bukkit/world/LegacyMaterialInfo_1_7.kt
1
2796
package net.benwoodworth.fastcraft.bukkit.world import net.benwoodworth.fastcraft.bukkit.text.createTranslate import net.benwoodworth.fastcraft.bukkit.util.BukkitVersion import net.benwoodworth.fastcraft.bukkit.util.getMap import net.benwoodworth.fastcraft.bukkit.util.toYamlConfiguration import net.benwoodworth.fastcraft.platform.text.FcText import org.apache.commons.lang.WordUtils import org.bukkit.Material import org.bukkit.material.MaterialData import org.bukkit.plugin.Plugin import javax.inject.Inject import javax.inject.Singleton @Singleton class LegacyMaterialInfo_1_7 @Inject constructor( plugin: Plugin, bukkitVersion: BukkitVersion, private val fcTextFactory: FcText.Factory, ) : LegacyMaterialInfo { private val itemIds: Map<Material, String> private val itemNames: Map<Material, String> private val itemVariantNames: Map<Material, List<String>> init { val version = bukkitVersion.run { "$major.$minor" } val yaml = plugin.getResource("bukkit/legacy-materials/$version.yml") ?.toYamlConfiguration() itemIds = yaml ?.getMap("item-ids") { getString(it) } ?.mapKeys { (key, _) -> enumValueOf(key) } ?: emptyMap() itemNames = yaml ?.getMap("item-names") { getString(it) } ?.mapKeys { (key, _) -> enumValueOf(key) } ?: emptyMap() itemVariantNames = yaml ?.getMap("item-variant-names") { getStringList(it) } ?.mapKeys { (key, _) -> enumValueOf(key) } ?: emptyMap() } @Suppress("DEPRECATION") override fun getItemName(materialData: MaterialData): FcText { return itemVariantNames[materialData.itemType] ?.getOrNull(materialData.data.toInt()) .let { it ?: itemNames[materialData.itemType] } ?.let { fcTextFactory.createTranslate("$it.name") } ?: run { var name = materialData.toString() // Trim data number from end val nameEnd = name.lastIndexOf('(') if (nameEnd != -1) { name = name.substring(0 until nameEnd) } name = name.replace('_', ' ') return fcTextFactory.create(WordUtils.capitalizeFully(name)) } } override fun getItemId(material: Material): String { return itemIds[material] ?.let { "minecraft:$it" } ?: material.name } @Suppress("DEPRECATION") override fun getItemId(materialData: MaterialData): String { return if (materialData.data == 0.toByte()) { getItemId(materialData.itemType) } else { "${getItemId(materialData.itemType)}:${materialData.data}" } } }
gpl-3.0
d11225c1c7318594b9965fdb4c506816
33.097561
77
0.621602
4.502415
false
false
false
false
Tolriq/yatse-customcommandsplugin-api
api/src/main/java/tv/yatse/plugin/customcommands/api/CustomCommandsPluginReceiver.kt
1
3212
/* * Copyright 2015 Tolriq / Genimee. * 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 tv.yatse.plugin.customcommands.api import android.content.BroadcastReceiver import android.content.Context import android.content.Intent /** * The CustomCommandsPluginService service that any plugin must extend * */ abstract class CustomCommandsPluginReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (context != null && intent != null) { if (intent.hasExtra(EXTRA_CUSTOM_COMMAND)) { executeCustomCommand( context, intent.getParcelableExtra(EXTRA_CUSTOM_COMMAND), intent.getStringExtra(EXTRA_STRING_MEDIA_CENTER_UNIQUE_ID), intent.getStringExtra(EXTRA_STRING_MEDIA_CENTER_NAME), intent.getStringExtra(EXTRA_STRING_MEDIA_CENTER_IP) ) } } } /** * Execute a custom command. * This is called from an BroadcastReceiver so on main thread. * * @param pluginCustomCommand the plugin custom command * @param hostId the host id currently connected to * @param hostName the host name currently connected to * @param hostIP the host iP currently connected to */ protected abstract fun executeCustomCommand(context: Context, pluginCustomCommand: PluginCustomCommand?, hostId: String?, hostName: String?, hostIP: String?) companion object { /** * String extra that will contains the associated media center unique id when Yatse connect to the service or start the settings activity. * This extra should always be filled, empty values should be checked and indicate a problem. */ const val EXTRA_STRING_MEDIA_CENTER_UNIQUE_ID = "tv.yatse.plugin.customcommands.EXTRA_STRING_MEDIA_CENTER_UNIQUE_ID" /** * String extra that will contains the associated media center name when Yatse connect to the service or start the settings activity. */ const val EXTRA_STRING_MEDIA_CENTER_NAME = "tv.yatse.plugin.customcommands.EXTRA_STRING_MEDIA_CENTER_NAME" /** * String extra that will contains the associated media center IP when Yatse connect to the service or start the settings activity. */ const val EXTRA_STRING_MEDIA_CENTER_IP = "tv.yatse.plugin.customcommands.EXTRA_STRING_MEDIA_CENTER_IP" /** * Parcelable extra that will contains the custom command. */ const val EXTRA_CUSTOM_COMMAND = "tv.yatse.plugin.customcommands.EXTRA_CUSTOM_COMMAND" } }
apache-2.0
a5dba9299c2695a3194d1b464be4265b
41.84
161
0.675592
4.601719
false
false
false
false
ademar111190/bitkointlin
samples/kotlin/src/main/kotlin/se/simbio/sample/kotlin/Main.kt
1
3470
package se.simbio.sample.kotlin import se.simbio.bitkointlin.Bitkointlin import se.simbio.bitkointlin.http.fuel.HttpClientImplFuel import java.awt.GridLayout import javax.swing.* /** * You need to setup your bitcoin environment and set below the correct data * more info: https://bitcoin.org/en/developer-guide */ val bitkointlin = Bitkointlin( user = "your_user", password = "your_password", httpAddress = "http://127.0.0.1:8332/", httpClient = HttpClientImplFuel()) val frame = JFrame("Bitkointlin") var dialog = JDialog() fun main(args: Array<String>) { frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE frame.layout = GridLayout(0, 1) addButton("Get Balance") { getBalance() } addButton("Get BestBlockHash") { getBestBlockHash() } addButton("Get Difficulty") { getDifficulty() } addButton("Get GetInfo") { getInfo() } frame.pack() frame.setLocationRelativeTo(null) frame.isVisible = true } fun addButton(method: String, callback: () -> Unit) { val button = JButton(method) button.addActionListener { callback() } frame.add(button) } fun showDialog(method: String) { dialog = JDialog(frame, method, false) dialog.setLocationRelativeTo(frame) dialog.add(JTextField("$method called, waiting...")) dialog.pack() dialog.isVisible = true } fun showSuccess(method: String, message: String) { dialog.dispose() JOptionPane.showMessageDialog(frame, message, "$method success", JOptionPane.INFORMATION_MESSAGE) } fun showError(method: String, message: String) { dialog.dispose() JOptionPane.showMessageDialog(frame, message, "$method error", JOptionPane.ERROR_MESSAGE) } fun getBalance() { val method = "getBalance" showDialog(method) bitkointlin.getBalance({ balance -> showSuccess(method, "Balance: $balance") }, { error -> showError(method, "$error") }) } fun getBestBlockHash() { val method = "getBestBlockHash" showDialog(method) bitkointlin.getBestBlockHash({ bestBlockHash -> showSuccess(method, "Best Block Hash: $bestBlockHash") }, { error -> showError(method, "$error") }) } fun getDifficulty() { val method = "getDifficulty" showDialog(method) bitkointlin.getDifficulty({ difficulty -> showSuccess(method, "Difficulty: $difficulty") }, { error -> showError(method, "$error") }) } fun getInfo() { val method = "getInfo" showDialog(method) bitkointlin.getInfo({ info -> showSuccess(method, "Info:\n\t" + "- Version: ${info.version}\n\t" + "- Protocol Version: ${info.protocolVersion}\n\t" + "- Wallet Version: ${info.walletVersion}\n\t" + "- Balance: ${info.balance}\n\t" + "- Blocks: ${info.blocks}\n\t" + "- Time Offset: ${info.timeOffset}\n\t" + "- Connections: ${info.connections}\n\t" + "- Proxy: ${info.proxy}\n\t" + "- Difficulty: ${info.difficulty}\n\t" + "- Test Net: ${info.testNet}\n\t" + "- Key Pool Oldest: ${info.keyPoolOldest}\n\t" + "- Key Pool Size: ${info.keyPoolSize}\n\t" + "- Pay Tx Fee: ${info.payTxFee}\n\t" + "- Relay Fee: ${info.relayFee}\n\t" + "- Errors: ${info.errors}\n\t") }, { error -> showError(method, "$error") }) }
mit
7568f9c8aa869150ab8de713217b5223
29.982143
101
0.610951
3.78821
false
false
false
false
dinosaurwithakatana/freight
freight-processor/src/main/kotlin/io/dwak/freight/processor/binding/FreightTrainBindingClass.kt
1
3817
package io.dwak.freight.processor.binding import com.squareup.javapoet.AnnotationSpec import com.squareup.javapoet.ClassName import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.ParameterSpec import com.squareup.javapoet.ParameterizedTypeName import com.squareup.javapoet.TypeName.VOID import com.squareup.javapoet.TypeSpec import com.squareup.javapoet.TypeVariableName import io.dwak.freight.processor.model.FieldBinding import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.element.Modifier.FINAL import javax.lang.model.element.Modifier.PUBLIC class FreightTrainBindingClass(classPackage: String, className: String, targetClass: String, processingEnvironment: ProcessingEnvironment) : AbstractBindingClass(classPackage, className, targetClass, processingEnvironment) { companion object { val CLASS_SUFFIX = "$\$FreightTrain" val METHOD_NAME = "ship" } override fun createAndAddBinding(element: Element) { val binding = FieldBinding(element) bindings.put(binding.name, binding) } override fun generate(): TypeSpec { val classBuilder = TypeSpec.classBuilder(className) .addModifiers(PUBLIC) .addAnnotation(AnnotationSpec.builder(SuppressWarnings::class.java) .addMember("value", "\$S", "unused") .build()) .addTypeVariable(TypeVariableName.get("T", ClassName.get(classPackage, targetClass))) .addSuperinterface(ParameterizedTypeName.get(ClassName.get("io.dwak.freight.internal", "IFreightTrain"), TypeVariableName.get("T"))) val shipBuilder = MethodSpec.methodBuilder(METHOD_NAME) .addModifiers(PUBLIC) .returns(VOID) .addParameter(ParameterSpec.builder(TypeVariableName.get("T"), "target", FINAL).build()) .addAnnotation(AnnotationSpec.builder(Override::class.java).build()) .addAnnotation(AnnotationSpec.builder(SuppressWarnings::class.java) .addMember("value", "\$S", "unused") .build()) .addStatement("final \$T bundle = target.getArgs()", bundle) bindings.values .map { it as FieldBinding } .forEach { val (typeHandled, statement) = getBundleStatement(it) when (it.kind) { ElementKind.FIELD -> when (typeHandled) { true -> shipBuilder.addStatement("target.\$L = \$L", it.name, statement) false -> { shipBuilder.addStatement("target.\$L = (\$L) bundle.getSerializable(\"${it.key}\")", it.name, it.type) } } else -> when (typeHandled) { true -> shipBuilder.addStatement("target.\$L(\$L)", it.name, statement) false -> { shipBuilder.addStatement("target.\$L((\$L) bundle.getSerializable(\"${it.key}\"))", it.name, it.type) } } } } return classBuilder.addMethod(shipBuilder.build()) .build() } private fun getBundleStatement(fieldBinding: FieldBinding): Pair<Boolean, String> { return handleType(fieldBinding, { var statement = "" if (!fieldBinding.isRequired) { statement += "bundle.containsKey(\"${fieldBinding.key}\") ? " } statement += "bundle.get$it(\"${fieldBinding.key}\")" if (!fieldBinding.isRequired) { statement += ": null" } statement }) } }
apache-2.0
81faac9e55cb4dc4cc670877aae492e9
39.606383
100
0.606759
4.881074
false
false
false
false
Duke1/UnrealMedia
UnrealMedia/app/src/main/java/com/qfleng/um/bean/ArtistMedia.kt
1
512
package com.qfleng.um.bean import android.os.Parcelable import kotlinx.parcelize.Parcelize /** * Created by Duke */ @Parcelize class ArtistMedia(var artistName: String = "", var artistCover: String = "", var medias: ArrayList<MediaInfo> = ArrayList()) : Parcelable { override fun equals(other: Any?): Boolean { if (other is ArtistMedia) { return artistName.trim() == other.artistName.trim() } return super.equals(other) } }
mit
36888b96b367258eb597092b276de79a
20.375
80
0.613281
4.338983
false
false
false
false
seventhroot/elysium
bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/command/profession/experience/ProfessionExperienceRemoveCommand.kt
1
5037
/* * Copyright 2019 Ren Binden * * 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.rpkit.professions.bukkit.command.profession.experience import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import com.rpkit.professions.bukkit.RPKProfessionsBukkit import com.rpkit.professions.bukkit.profession.RPKProfessionProvider import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class ProfessionExperienceRemoveCommand(val plugin: RPKProfessionsBukkit): CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (!sender.hasPermission("rpkit.professions.command.profession.experience.remove")) { sender.sendMessage(plugin.messages["no-permission-profession-experience-remove"]) return true } var argsOffset = 0 val target = if (sender.hasPermission("rpkit.professions.command.profession.experience.remove.other")) { when { args.size > 2 -> { val player = plugin.server.getPlayer(args[0]) if (player == null) { sender.sendMessage(plugin.messages["profession-experience-remove-invalid-player-not-online"]) return true } else { argsOffset = 1 player } } sender is Player -> sender else -> { sender.sendMessage(plugin.messages["profession-experience-remove-invalid-player-please-specify-from-console"]) return true } } } else { if (sender is Player) { sender } else { sender.sendMessage(plugin.messages["profession-experience-remove-invalid-player-please-specify-from-console"]) return true } } val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(target) if (minecraftProfile == null) { if (sender == target) { sender.sendMessage(plugin.messages["no-minecraft-profile-self"]) } else { sender.sendMessage(plugin.messages["no-minecraft-profile-other"]) } return true } val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val character = characterProvider.getActiveCharacter(minecraftProfile) if (character == null) { if (sender == target) { sender.sendMessage(plugin.messages["no-character-self"]) } else { sender.sendMessage(plugin.messages["no-character-other"]) } return true } val professionProvider = plugin.core.serviceManager.getServiceProvider(RPKProfessionProvider::class) if (args.size < 2) { sender.sendMessage(plugin.messages["profession-experience-remove-usage"]) return true } val exp = try { args[argsOffset + 1].toInt() } catch (exception: NumberFormatException) { sender.sendMessage(plugin.messages["profession-experience-remove-invalid-exp-not-a-number"]) return true } val profession = professionProvider.getProfession(args[argsOffset]) if (profession == null) { sender.sendMessage(plugin.messages["profession-experience-remove-invalid-profession"]) return true } professionProvider.setProfessionExperience(character, profession, professionProvider.getProfessionExperience(character, profession) - exp) sender.sendMessage(plugin.messages["profession-experience-remove-valid", mapOf( "player" to minecraftProfile.minecraftUsername, "character" to if (!character.isNameHidden) character.name else "[HIDDEN]", "profession" to profession.name, "total-experience" to professionProvider.getProfessionExperience(character, profession).toString(), "removed-experience" to exp.toString() )]) return true } }
apache-2.0
b1f9afc88626cd5224bb0793af5a7481
45.211009
146
0.64324
5.176773
false
false
false
false
Goyatuzo/LurkerBot
entry/discord-bot/src/main/kotlin/command/RemoveMe.kt
1
1016
package com.lurkerbot.command import com.lurkerbot.discordUser.UserTracker import dev.kord.core.behavior.interaction.respondEphemeral import dev.kord.core.entity.interaction.ApplicationCommandInteraction import mu.KotlinLogging class RemoveMe(private val userTracker: UserTracker) : BotCommand { private val logger = KotlinLogging.logger {} override val name: String = "remove-me" override val description: String = "Stop tracking future game sessions. Will not delete game sessions in the past." override suspend fun invoke(interaction: ApplicationCommandInteraction) { val user = interaction.user.asUserOrNull() userTracker.removeUser(user) interaction.respondEphemeral { content = "Future game sessions will not be recorded. Existing records can be deleted with a separate command." } logger.info { "${interaction.invokedCommandName} was run for ${user.username}#${user.discriminator}" } } }
apache-2.0
df562ff0442975aad00d744f9950db34
36.62963
117
0.71752
4.861244
false
false
false
false
hazuki0x0/YuzuBrowser
module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/repository/original/AdBlockManager.kt
1
14435
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.adblock.repository.original import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteConstraintException import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import jp.hazuki.yuzubrowser.adblock.filter.fastmatch.AdBlockDecoder import jp.hazuki.yuzubrowser.adblock.filter.fastmatch.LegacyDecoder import jp.hazuki.yuzubrowser.adblock.filter.unified.UnifiedFilter import jp.hazuki.yuzubrowser.adblock.filter.unified.getFilterDir import jp.hazuki.yuzubrowser.adblock.filter.unified.io.FilterReader import jp.hazuki.yuzubrowser.adblock.filter.unified.io.FilterWriter import jp.hazuki.yuzubrowser.adblock.filter.unified.writeFilter import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import java.io.BufferedInputStream import java.io.File import java.io.IOException import java.util.* class AdBlockManager internal constructor(private val context: Context) { private val mOpenHelper = MyOpenHelper(context) private val appContext = context.applicationContext private val updating = mutableMapOf<String, Boolean>() init { if (!context.getDatabasePath(DB_NAME).exists()) { initList(appContext) } } private fun update(table: String, adBlock: AdBlock): Boolean { val result = if (adBlock.id > -1) { updateInternal(table, adBlock) } else { insert(table, adBlock) } updateListTime(table) return result } private fun insert(table: String, adBlock: AdBlock): Boolean { val db = mOpenHelper.writableDatabase val values = ContentValues() values.put(COLUMN_MATCH, adBlock.match) values.put(COLUMN_ENABLE, if (adBlock.isEnable) 1 else 0) return try { val id = db.insert(table, null, values) adBlock.id = id.toInt() true } catch (e: SQLiteConstraintException) { false } } private fun updateInternal(table: String, adBlock: AdBlock): Boolean { val db = mOpenHelper.writableDatabase val values = ContentValues() values.put(COLUMN_MATCH, adBlock.match) values.put(COLUMN_ENABLE, if (adBlock.isEnable) 1 else 0) return try { db.update(table, values, "$COLUMN_ID = ?", arrayOf(Integer.toString(adBlock.id))) true } catch (e: SQLiteConstraintException) { false } } private fun delete(table: String, id: Int) { val db = mOpenHelper.writableDatabase db.delete(table, "$COLUMN_ID = ?", arrayOf(Integer.toString(id))) updateListTime(table) } private fun addAll(table: String, adBlocks: List<AdBlock>) { val db = mOpenHelper.writableDatabase db.beginTransaction() try { for (adBlock in adBlocks) { val values = ContentValues() values.put(COLUMN_MATCH, adBlock.match) values.put(COLUMN_ENABLE, if (adBlock.isEnable) 1 else 0) try { db.insert(table, null, values) } catch (e: SQLiteConstraintException) { e.printStackTrace() } } db.setTransactionSuccessful() } finally { db.endTransaction() } updateListTime(table) } private fun getAllItems(table: String): ArrayList<AdBlock> { val db = mOpenHelper.readableDatabase db.query(table, null, null, null, null, null, null).use { c -> val id = c.getColumnIndex(COLUMN_ID) val match = c.getColumnIndex(COLUMN_MATCH) val enable = c.getColumnIndex(COLUMN_ENABLE) val adBlocks = ArrayList<AdBlock>() while (c.moveToNext()) { adBlocks.add(AdBlock(c.getInt(id), c.getString(match), c.getInt(enable) != 0)) } return adBlocks } } private fun getEnableItems(table: String): ArrayList<AdBlock> { val db = mOpenHelper.readableDatabase db.query(table, null, "$COLUMN_ENABLE = 1", null, null, null, null).use { c -> val id = c.getColumnIndex(COLUMN_ID) val match = c.getColumnIndex(COLUMN_MATCH) val enable = c.getColumnIndex(COLUMN_ENABLE) val adBlocks = ArrayList<AdBlock>() while (c.moveToNext()) { adBlocks.add(AdBlock(c.getInt(id), c.getString(match), c.getInt(enable) != 0)) } return adBlocks } } private fun deleteAll(table: String) { val db = mOpenHelper.writableDatabase db.delete(table, null, null) } fun getCachedMatcherList(table: String): Sequence<UnifiedFilter> { val listTime = getListUpdateTime(table) val cacheTime = getCacheUpdateTime(table) if (listTime <= cacheTime) { try { getFilterFile(table).inputStream().use { val reader = FilterReader(it) if (reader.checkHeader()) { return reader.readAll() } } } catch (e: IOException) { e.printStackTrace() } } val list = getMatcherList(table) GlobalScope.launch(Dispatchers.IO) { writeFilter(getFilterFile(table), list) updateCacheTime(table) } return list.asSequence() } private fun getMatcherList(table: String): List<UnifiedFilter> { val list = arrayListOf<UnifiedFilter>() val decoder = LegacyDecoder() val db = mOpenHelper.readableDatabase db.query(table, null, "$COLUMN_ENABLE = 1", null, null, null, null).use { c -> val match = c.getColumnIndex(COLUMN_MATCH) while (c.moveToNext()) { val matcher = decoder.singleDecode(c.getString(match)) if (matcher != null) { list += matcher } } return list } } private fun getListUpdateTime(table: String): Long { val db = mOpenHelper.readableDatabase db.query(INFO_TABLE_NAME, null, "$INFO_COLUMN_NAME = ?", arrayOf(table), null, null, null, "1").use { c -> var time: Long = -1 if (c.moveToFirst()) time = c.getLong(c.getColumnIndex(INFO_COLUMN_LAST_TIME)) return time } } private fun updateListTime(table: String) { val db = mOpenHelper.writableDatabase val values = ContentValues() values.put(INFO_COLUMN_LAST_TIME, System.currentTimeMillis()) db.update(INFO_TABLE_NAME, values, "$INFO_COLUMN_NAME = ?", arrayOf(table)) } private fun getCacheUpdateTime(table: String): Long { val db = mOpenHelper.readableDatabase db.query(INFO_TABLE_NAME, null, "$INFO_COLUMN_NAME = ?", arrayOf("${table}_cache"), null, null, null, "1").use { c -> var time: Long = -1 if (c.moveToFirst()) time = c.getLong(c.getColumnIndex(INFO_COLUMN_LAST_TIME)) return time } } private fun updateCacheTime(table: String) { val db = mOpenHelper.writableDatabase val values = ContentValues() values.put(INFO_COLUMN_LAST_TIME, System.currentTimeMillis()) db.update(INFO_TABLE_NAME, values, "$INFO_COLUMN_NAME = ?", arrayOf("${table}_cache")) } private fun initList(context: Context) { try { BufferedInputStream(context.assets.open("adblock/whitelist.txt")).use { val adBlocks = AdBlockDecoder.decode(Scanner(it), false) addAll(ALLOW_TABLE_NAME, adBlocks) } GlobalScope.launch(Dispatchers.IO) { createCache(ALLOW_TABLE_NAME) } } catch (e: IOException) { e.printStackTrace() } try { BufferedInputStream(context.assets.open("adblock/whitepagelist.txt")).use { val adBlocks = AdBlockDecoder.decode(Scanner(it), false) addAll(ALLOW_PAGE_TABLE_NAME, adBlocks) } GlobalScope.launch(Dispatchers.IO) { createCache(ALLOW_PAGE_TABLE_NAME) } } catch (e: IOException) { e.printStackTrace() } } private fun createCache(table: String) { if (isUpdating(table)) return updating[table] = true try { getFilterFile(table).outputStream().use { val writer = FilterWriter() writer.write(it, getMatcherList(table)) } updateCacheTime(table) } catch (e: IOException) { e.printStackTrace() } finally { updating[table] = false } } fun isUpdating(table: String): Boolean { return updating[table] ?: false } private fun getFilterFile(table: String): File { return File(context.getFilterDir(), "cache_$table") } class AdBlockItemProvider constructor(context: Context, private val table: String) { private val manager: AdBlockManager = AdBlockManager(context) val allItems: ArrayList<AdBlock> get() = manager.getAllItems(table) val enableItems: ArrayList<AdBlock> get() = manager.getEnableItems(table) fun update(adBlock: AdBlock): Boolean = manager.update(table, adBlock) fun delete(id: Int) { manager.delete(table, id) } fun addAll(adBlocks: List<AdBlock>) { manager.addAll(table, adBlocks) } fun deleteAll() { manager.deleteAll(table) } fun updateCache() { manager.createCache(table) } } private class MyOpenHelper private constructor(context: Context) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) { override fun onCreate(db: SQLiteDatabase) { db.beginTransaction() try { db.execSQL("CREATE TABLE " + INFO_TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY" + ", " + INFO_COLUMN_NAME + " TEXT NOT NULL" + ", " + INFO_COLUMN_LAST_TIME + " INTEGER DEFAULT 0" + ")") db.execSQL("CREATE TABLE " + DENY_TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY" + ", " + COLUMN_MATCH + " TEXT NOT NULL UNIQUE" + ", " + COLUMN_ENABLE + " INTEGER DEFAULT 0" + ")") db.execSQL("CREATE TABLE " + ALLOW_TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY" + ", " + COLUMN_MATCH + " TEXT NOT NULL UNIQUE" + ", " + COLUMN_ENABLE + " INTEGER DEFAULT 0" + ")") db.execSQL("CREATE TABLE " + ALLOW_PAGE_TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY" + ", " + COLUMN_MATCH + " TEXT NOT NULL UNIQUE" + ", " + COLUMN_ENABLE + " INTEGER DEFAULT 0" + ")") // init info table val values = ContentValues() values.put(INFO_COLUMN_LAST_TIME, System.currentTimeMillis()) values.put(INFO_COLUMN_NAME, DENY_TABLE_NAME) db.insert(INFO_TABLE_NAME, null, values) values.put(INFO_COLUMN_NAME, ALLOW_TABLE_NAME) db.insert(INFO_TABLE_NAME, null, values) values.put(INFO_COLUMN_NAME, ALLOW_PAGE_TABLE_NAME) db.insert(INFO_TABLE_NAME, null, values) db.setTransactionSuccessful() } finally { db.endTransaction() } } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { db.execSQL("DROP TABLE IF EXISTS $DENY_TABLE_NAME") db.execSQL("DROP TABLE IF EXISTS $ALLOW_TABLE_NAME") db.execSQL("DROP TABLE IF EXISTS $ALLOW_PAGE_TABLE_NAME") db.execSQL("DROP TABLE IF EXISTS $INFO_TABLE_NAME") onCreate(db) } companion object { private var instance: MyOpenHelper? = null operator fun invoke(context: Context): MyOpenHelper { if (instance == null) instance = MyOpenHelper(context) return instance!! } } } companion object { private const val DB_NAME = "adblock.db" private const val DB_VERSION = 1 internal const val DENY_TABLE_NAME = "black" internal const val ALLOW_TABLE_NAME = "white" internal const val ALLOW_PAGE_TABLE_NAME = "white_page" const val TYPE_DENY_TABLE = 1 const val TYPE_ALLOW_TABLE = 2 const val TYPE_ALLOW_PAGE_TABLE = 3 private const val INFO_TABLE_NAME = "info" private const val COLUMN_ID = "_id" private const val COLUMN_MATCH = "match" private const val COLUMN_ENABLE = "enable" private const val INFO_COLUMN_NAME = "name" private const val INFO_COLUMN_LAST_TIME = "time" @JvmStatic fun getProvider(context: Context, type: Int): AdBlockItemProvider = when (type) { TYPE_DENY_TABLE -> AdBlockItemProvider(context, DENY_TABLE_NAME) TYPE_ALLOW_TABLE -> AdBlockItemProvider(context, ALLOW_TABLE_NAME) TYPE_ALLOW_PAGE_TABLE -> AdBlockItemProvider(context, ALLOW_PAGE_TABLE_NAME) else -> throw IllegalArgumentException("unknown type") } } }
apache-2.0
f17927b550ef40fe5d09509d445978b3
35.268844
125
0.582404
4.522243
false
false
false
false
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/kpspemu/hle/modules/ThreadManForUser_EventFlags.kt
1
3847
package com.soywiz.kpspemu.hle.modules import com.soywiz.kpspemu.cpu.* import com.soywiz.kpspemu.hle.* import com.soywiz.kpspemu.hle.error.* import com.soywiz.kpspemu.hle.manager.* import com.soywiz.kpspemu.mem.* import com.soywiz.kpspemu.util.* class ThreadManForUser_EventFlags(val tmodule: ThreadManForUser) : SceSubmodule<ThreadManForUser>(tmodule) { val eventFlags = ResourceList("EventFlag") { PspEventFlag(it) } fun sceKernelCreateEventFlag(name: String?, attributes: Int, bitPattern: Int, optionsPtr: Ptr): Int { return eventFlags.alloc().apply { this.name = name ?: "eventFlag" this.attributes = attributes this.currentPattern = bitPattern this.optionsPtr = optionsPtr }.id } private fun getEventFlag(id: Int): PspEventFlag = eventFlags.tryGetById(id) ?: sceKernelException(SceKernelErrors.ERROR_KERNEL_NOT_FOUND_EVENT_FLAG) fun sceKernelPollEventFlag(id: Int, bits: Int, waitType: Int, outBits: Ptr): Int { val eventFlag = getEventFlag(id) if ((waitType and EventFlagWaitTypeSet.MaskValidBits.inv()) != 0) return SceKernelErrors.ERROR_KERNEL_ILLEGAL_MODE if ((waitType and (EventFlagWaitTypeSet.Clear or EventFlagWaitTypeSet.ClearAll)) == (EventFlagWaitTypeSet.Clear or EventFlagWaitTypeSet.ClearAll)) { return SceKernelErrors.ERROR_KERNEL_ILLEGAL_MODE } if (bits == 0) return SceKernelErrors.ERROR_KERNEL_EVENT_FLAG_ILLEGAL_WAIT_PATTERN //if (EventFlag == null) return SceKernelErrors.ERROR_KERNEL_NOT_FOUND_EVENT_FLAG; val matched = eventFlag.poll(bits, waitType, outBits) return if (matched) 0 else SceKernelErrors.ERROR_KERNEL_EVENT_FLAG_POLL_FAILED } fun sceKernelSetEventFlag(id: Int, bitPattern: Int): Int { val eventFlag = getEventFlag(id) eventFlag.setBits(bitPattern) return 0 } fun sceKernelDeleteEventFlag(id: Int): Int { getEventFlag(id) // To throw exceptions if not exists eventFlags.freeById(id) return 0 } fun sceKernelCancelEventFlag(cpu: CpuState): Unit = UNIMPLEMENTED(0xCD203292) fun sceKernelReferEventFlagStatus(cpu: CpuState): Unit = UNIMPLEMENTED(0xA66B0120) fun sceKernelWaitEventFlagCB(cpu: CpuState): Unit = UNIMPLEMENTED(0x328C546A) fun sceKernelWaitEventFlag(cpu: CpuState): Unit = UNIMPLEMENTED(0x402FCF22) fun sceKernelClearEventFlag(cpu: CpuState): Unit = UNIMPLEMENTED(0x812346E4) fun registerSubmodule() = tmodule.apply { registerFunctionInt("sceKernelCreateEventFlag", 0x55C20A00, since = 150) { sceKernelCreateEventFlag( str, int, int, ptr ) } registerFunctionInt("sceKernelPollEventFlag", 0x30FD48F0, since = 150) { sceKernelPollEventFlag( int, int, int, ptr ) } registerFunctionInt("sceKernelSetEventFlag", 0x1FB15A32, since = 150) { sceKernelSetEventFlag(int, int) } registerFunctionInt("sceKernelDeleteEventFlag", 0xEF9E4C70, since = 150) { sceKernelDeleteEventFlag(int) } registerFunctionRaw("sceKernelCancelEventFlag", 0xCD203292, since = 150) { sceKernelCancelEventFlag(it) } registerFunctionRaw( "sceKernelReferEventFlagStatus", 0xA66B0120, since = 150 ) { sceKernelReferEventFlagStatus(it) } registerFunctionRaw("sceKernelWaitEventFlagCB", 0x328C546A, since = 150) { sceKernelWaitEventFlagCB(it) } registerFunctionRaw("sceKernelWaitEventFlag", 0x402FCF22, since = 150) { sceKernelWaitEventFlag(it) } registerFunctionRaw("sceKernelClearEventFlag", 0x812346E4, since = 150) { sceKernelClearEventFlag(it) } } }
mit
39429c35d529a3643e0eeedcc4d92d15
43.229885
156
0.679491
4.070899
false
false
false
false
erubit-open/platform
erubit.platform/src/main/java/t/FuriganaViewMultiline.kt
1
13316
package t import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.text.TextPaint import android.util.AttributeSet import android.view.View import android.widget.TextView import java.util.* import java.util.regex.Pattern import kotlin.math.ceil import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt class FuriganaViewMultiline : TextView { private val mLines: Vector<Line> = Vector(0) private val mAllTexts: Vector<PairText> = Vector(0) private lateinit var mNormalTextPaint: TextPaint private lateinit var mFuriganaTextPaint: TextPaint private lateinit var mBoldTextPaint: TextPaint private lateinit var mItalicTextPaint: TextPaint private lateinit var mBoldItalicTextPaint: TextPaint private var mLineHeight = 0f private var mMaxLineWidth = 0f constructor(context: Context?) : super(context) { initialize() } constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) { initialize() } constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { initialize() } override fun setText(text: CharSequence, type: BufferType) { super.setText(text, type) if (text.isNotEmpty()) { setJText() onMeasure(MeasureSpec.EXACTLY, MeasureSpec.EXACTLY) } } private fun initialize() { val textPaint = paint mNormalTextPaint = TextPaint(textPaint) mFuriganaTextPaint = TextPaint(textPaint) mFuriganaTextPaint.textSize = textPaint.textSize / 2 mBoldTextPaint = TextPaint(textPaint) mBoldTextPaint.isFakeBoldText = true mItalicTextPaint = TextPaint(textPaint) mItalicTextPaint.textSkewX = -0.35f mBoldItalicTextPaint = TextPaint(textPaint) mBoldItalicTextPaint.textSkewX = -0.35f mBoldItalicTextPaint.isFakeBoldText = true // Calculate the height of one line. mLineHeight = mFuriganaTextPaint.fontSpacing + 8 + maxOf( mNormalTextPaint.fontSpacing, max(mBoldTextPaint.fontSpacing, mItalicTextPaint.fontSpacing), mBoldItalicTextPaint.fontSpacing ) setJText() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val widthMode = MeasureSpec.getMode(widthMeasureSpec) val heightMode = MeasureSpec.getMode(heightMeasureSpec) val widthSize = MeasureSpec.getSize(widthMeasureSpec) val heightSize = MeasureSpec.getSize(heightMeasureSpec) measureText(widthSize) var height = ceil(mLineHeight * mLines.size).roundToInt() + 15 var width = widthSize if (widthMode != MeasureSpec.EXACTLY && mLines.size <= 1) width = ceil(mMaxLineWidth.toDouble()).roundToInt() if (heightMode != MeasureSpec.UNSPECIFIED && height > heightSize) height = height or View.MEASURED_STATE_TOO_SMALL if (widthMode == MeasureSpec.EXACTLY) width = min(widthSize, width) if (heightMode == MeasureSpec.EXACTLY) height = min(heightSize, height) setMeasuredDimension(width, height) } /*** * Measure view with max width. * @param width if width < 0 → the view has one line, which has width unlimited. */ private fun measureText(width: Int) { mLines.clear() mMaxLineWidth = 0f if (width <= 0) { val line = Line() line.mPairTexts = mAllTexts for (t in mAllTexts) mMaxLineWidth += t.mWidth } else { var tmpW = 0f var pairTexts = Vector<PairText>() for (pairText in mAllTexts) { // Break to new line if {@PairText} contain break character. if (pairText.isBreak) { val line = Line() line.mPairTexts = pairTexts mLines.add(line) mMaxLineWidth = if (mMaxLineWidth > tmpW) mMaxLineWidth else tmpW // Reset for new line pairTexts = Vector() tmpW = 0f continue } tmpW += pairText.mWidth if (tmpW < width) { pairTexts.add(pairText) } else { var line = Line() tmpW -= pairText.mWidth // If kanji -> break to new line if (pairText.mFuriganaText != null) { line.mPairTexts = pairTexts mLines.add(line) mMaxLineWidth = if (mMaxLineWidth > tmpW) mMaxLineWidth else tmpW // Reset for new line pairTexts = Vector() pairTexts.add(pairText) tmpW = pairText.mWidth } else { var splitPairText = pairText.split(tmpW, width.toFloat(), pairTexts) // Add new line line.mPairTexts = pairTexts mLines.add(line) mMaxLineWidth = if (mMaxLineWidth > tmpW) mMaxLineWidth else tmpW if (splitPairText == null) { pairTexts = Vector() continue } // Reset for new line tmpW = splitPairText.mWidth //split for long text while (tmpW > width) { tmpW = 0f pairTexts = Vector() splitPairText = splitPairText!!.split(tmpW, width.toFloat(), pairTexts) line = Line() line.mPairTexts = pairTexts mLines.add(line) mMaxLineWidth = if (mMaxLineWidth > tmpW) mMaxLineWidth else tmpW tmpW = splitPairText?.mWidth ?: 0f } pairTexts = Vector() if (splitPairText != null) { pairTexts.add(splitPairText) } } } // Make the rest of text before quit loop. if (pairText == mAllTexts.lastElement() && pairTexts.size > 0) { val line = Line() line.mPairTexts = pairTexts mLines.add(line) mMaxLineWidth = if (mMaxLineWidth > tmpW) mMaxLineWidth else tmpW } } } } override fun onDraw(canvas: Canvas) { if (mLines.size > 0) { var y = mLineHeight for (line in mLines) { line.mLineRect.set(0, (y - mLineHeight).toInt(), mMaxLineWidth.toInt(), y.toInt()) var x = 0f for (pairText in line.mPairTexts) { pairText.mPairRect.set(x.toInt(), (y - mLineHeight).toInt(), (x + pairText.mWidth).toInt(), y.toInt()) pairText.onDraw(canvas, x, y) x += pairText.mWidth } y += mLineHeight if (y > height) break } } else super.onDraw(canvas) } /** * Set text without invalidate */ private fun setJText() { val t = text.toString() if (t.isEmpty()) return mAllTexts.clear() parseBoldText(t.replace(BREAK_REGEX.toRegex(), BREAK_CHARACTER)) } /** * Parse text with struct **...** * @param text text to parse */ private fun parseBoldText(text: String) { val pattern = Pattern.compile(BOLD_TEXT_REGEX) val matcher = pattern.matcher(text) var start = 0 var end: Int while (matcher.find()) { val fullText = matcher.group(1) ?: "" val boldText = matcher.group(3) ?: "" end = text.indexOf(fullText, start) if (end < 0) continue if (end > start) parseItalicText(text.substring(start, end), TYPE_NORMAL) parseItalicText(boldText, TYPE_BOLDER) start = end + fullText.length } end = text.length if (end > start) parseItalicText(text.substring(start, end), TYPE_NORMAL) } /** * Parse text with struct *...* * @param text text to parse * @param type 2 type for this function. bold and normal. */ private fun parseItalicText(text: String, type: Int) { val pattern = Pattern.compile(ITALIC_TEXT_REGEX) val matcher = pattern.matcher(text) var start = 0 var end: Int while (matcher.find()) { val fullText = matcher.group(1) ?: "" val italicText = matcher.group(3) ?: "" end = text.indexOf(fullText, start) if (end < 0) continue if (end > start) parseFuriganaText(text.substring(start, end), type) parseFuriganaText(italicText, if (type == TYPE_BOLDER) TYPE_BOLDER or TYPE_ITALIC else TYPE_ITALIC) start = end + fullText.length } end = text.length if (end > start) parseFuriganaText(text.substring(start, end), type) } /** * Parse text with struct {kanji:furigana} * @param text text to parse * @param type 4 type for display. bold, italic, bold-italic and normal. */ private fun parseFuriganaText(text: String, type: Int) { val pattern = Pattern.compile(KANJI_REGEX) val matcher = pattern.matcher(text) var start = 0 var end: Int while (matcher.find()) { val fullText = matcher.group(1) ?: "" val kanji = matcher.group(3) ?: "" val furigana = matcher.group(5) ?: "" end = text.indexOf(fullText, start) if (end < 0) continue if (end > start) parseBreakLineText(text.substring(start, end), type) val kanjiText = JText(kanji, type) val furiganaText = FuriganaText(furigana) val pairText = PairText(kanjiText, furiganaText) mAllTexts.add(pairText) start = end + fullText.length } end = text.length if (end > start) parseBreakLineText(text.substring(start, end), type) } /** * Parse text with struct \n \r <br></br> <br></br> <br></br> * @param text text to parse * @param type 4 type for display. bold, italic, bold-italic and normal. */ private fun parseBreakLineText(text: String, type: Int) { if (text.contains(BREAK_CHARACTER)) { val breakIndex = text.indexOf(BREAK_CHARACTER) val jText = JText(text.substring(0, breakIndex), type) mAllTexts.add(PairText(jText)) mAllTexts.add(PairText()) val secondText = text.substring(breakIndex + BREAK_CHARACTER.length) parseBreakLineText(secondText, type) } else mAllTexts.add(PairText(JText(text, type))) } private inner class Line { var mPairTexts: Vector<PairText> = Vector(0) val mLineRect: Rect = Rect() } private inner class PairText { var mPairRect: Rect = Rect() lateinit var mJText: JText var mFuriganaText: FuriganaText? = null var isBreak = false var mWidth = 0f constructor() { isBreak = true } constructor(jText: JText) { mJText = jText measureWidth() } constructor(jText: JText, furiganaText: FuriganaText?) { mJText = jText mFuriganaText = furiganaText measureWidth() } private fun measureWidth() { mWidth = when (mFuriganaText) { null -> mJText.mWidth else -> max(mJText.mWidth, mFuriganaText!!.mWidth) } } fun split(width: Float, maxWidth: Float, pairTexts: Vector<PairText>): PairText? { return if (mFuriganaText != null) null else mJText.split(width, maxWidth, pairTexts) } fun onDraw(canvas: Canvas, x: Float, y: Float) { if (mFuriganaText == null) mJText.onDraw(canvas, x, y) else { val nx = x + (mWidth - mJText.mWidth) / 2 mJText.onDraw(canvas, nx, y) val fx = x + (mWidth - mFuriganaText!!.mWidth) / 2 val fy = y - mJText.mHeight mFuriganaText!!.onDraw(canvas, fx, fy) } } } private open inner class JText(var text: String, var type: Int) { var mWidth: Float var mHeight = 0f var mWidthCharArray: FloatArray = FloatArray(text.length) lateinit var mTextPaint: TextPaint fun onDraw(canvas: Canvas, x: Float, y: Float) { mTextPaint.color = currentTextColor canvas.drawText(text, 0, text.length, x, y, mTextPaint) } fun split(width: Float, maxWidth: Float, pairTexts: Vector<PairText>): PairText? { var w = width var i = 0 while (i < mWidthCharArray.size) { w += mWidthCharArray[i] if (w < maxWidth) { i++ continue } else { w -= mWidthCharArray[i] i-- break } } return when { i <= 0 -> PairText(JText(text, type)) else -> { val newText = text.substring(0, i) val pairText = PairText(JText(newText, type)) pairTexts.add(pairText) when (i) { text.length -> null else -> PairText(JText(text.substring(i), type)) } } } } init { when { type and TYPE_FURIGANA == TYPE_FURIGANA -> { mFuriganaTextPaint.getTextWidths(text, mWidthCharArray) mHeight = mFuriganaTextPaint.descent() - mFuriganaTextPaint.ascent() mTextPaint = mFuriganaTextPaint } type and TYPE_BOLDER == TYPE_BOLDER && type and TYPE_ITALIC == TYPE_ITALIC -> { mBoldItalicTextPaint.getTextWidths(text, mWidthCharArray) mHeight = mBoldItalicTextPaint.descent() - mBoldItalicTextPaint.ascent() mTextPaint = mBoldItalicTextPaint } type and TYPE_BOLDER == TYPE_BOLDER -> { mBoldTextPaint.getTextWidths(text, mWidthCharArray) mHeight = mBoldTextPaint.descent() - mBoldTextPaint.ascent() mTextPaint = mBoldTextPaint } type and TYPE_ITALIC == TYPE_ITALIC -> { mItalicTextPaint.getTextWidths(text, mWidthCharArray) mHeight = mItalicTextPaint.descent() - mItalicTextPaint.ascent() mTextPaint = mItalicTextPaint } type and TYPE_NORMAL == TYPE_NORMAL -> { mNormalTextPaint.getTextWidths(text, mWidthCharArray) mHeight = mNormalTextPaint.descent() - mNormalTextPaint.ascent() mTextPaint = mNormalTextPaint } } mWidth = 0f for (w in mWidthCharArray) mWidth += w } } private inner class FuriganaText(text: String) : JText(text, TYPE_FURIGANA) companion object { private const val TYPE_NORMAL = 1 private const val TYPE_BOLDER = 2 private const val TYPE_ITALIC = 4 private const val TYPE_FURIGANA = 8 /* regex for kanji with struct {kanji:furigana} */ private const val KANJI_REGEX = "(([{])([ぁ-ゔゞァ-・ヽヾ゛゜ー一-龯0-90-9]*)([:])([\\u3040-\\u30FFー[0-9]]*)([}]))" private const val BOLD_TEXT_REGEX = "(?m)(?d)(?s)(([<][b][>])(.*?)([<][\\/][b][>]))" private const val ITALIC_TEXT_REGEX = "(?m)(?d)(?s)(([<][i][>])(.*?)([<][\\/][i][>]))" private const val BREAK_REGEX = "(<br ?\\/?>)" private const val BREAK_CHARACTER = "\n" } }
gpl-3.0
059f6a181aa0669b462f86a9dc82a338
24.894737
112
0.667871
3.195574
false
false
false
false
eurofurence/ef-app_android
app/src/main/kotlin/org/eurofurence/connavigator/ui/fragments/EventItemFragment.kt
1
12828
package org.eurofurence.connavigator.ui.fragments import android.content.res.ColorStateList import android.os.Bundle import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.ScrollView import android.widget.TextView import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.github.chrisbanes.photoview.PhotoView import com.google.android.material.floatingactionbutton.FloatingActionButton import com.pawegio.kandroid.IntentFor import com.pawegio.kandroid.runDelayed import io.reactivex.disposables.Disposables import io.swagger.client.model.EventRecord import org.eurofurence.connavigator.BuildConfig import org.eurofurence.connavigator.R import org.eurofurence.connavigator.database.HasDb import org.eurofurence.connavigator.database.descriptionFor import org.eurofurence.connavigator.database.lazyLocateDb import org.eurofurence.connavigator.events.EventFavoriteBroadcast import org.eurofurence.connavigator.preferences.AppPreferences import org.eurofurence.connavigator.services.AnalyticsService import org.eurofurence.connavigator.services.AnalyticsService.Action import org.eurofurence.connavigator.services.AnalyticsService.Category import org.eurofurence.connavigator.services.ImageService import org.eurofurence.connavigator.ui.LayoutConstants import org.eurofurence.connavigator.ui.dialogs.eventDialog import org.eurofurence.connavigator.ui.filters.start import org.eurofurence.connavigator.util.extensions.* import org.eurofurence.connavigator.util.v2.compatAppearance import org.eurofurence.connavigator.util.v2.get import org.eurofurence.connavigator.util.v2.plus import org.jetbrains.anko.* import org.jetbrains.anko.custom.ankoView import org.jetbrains.anko.design.coordinatorLayout import org.jetbrains.anko.support.v4.UI import org.jetbrains.anko.support.v4.alert import us.feras.mdv.MarkdownView import java.util.* /** * Created by David on 4/9/2016. */ class EventItemFragment : DisposingFragment(), HasDb, AnkoLogger { override val db by lazyLocateDb() val args: EventItemFragmentArgs by navArgs() val eventId by lazy { UUID.fromString(args.eventId) } val ui by lazy { EventUi() } var mapIsSet = false 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) if (args.CID != null && !args.CID.equals(BuildConfig.CONVENTION_IDENTIFIER, true)) { alert("This item is not for this convention", "Wrong convention!").show() findNavController().popBackStack() } db.subscribe { fillUi(savedInstanceState) }.collectOnDestroyView() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) ui.scrollview?.also { sv -> outState.putInt("sv_key_x", sv.scrollX) outState.putInt("sv_key_y", sv.scrollY) } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) runDelayed(200) { ui.scrollview?.also { sv -> savedInstanceState?.getInt("sv_key_x")?.let(sv::setScrollX) savedInstanceState?.getInt("sv_key_y")?.let(sv::setScrollY) } } } private fun fillUi(savedInstanceState: Bundle?) { if (eventId != null) { val event: EventRecord = db.events[eventId] ?: return AnalyticsService.event(Category.EVENT, Action.OPENED, event.title) val conferenceRoom = event[toRoom] ui.title.text = event.fullTitle() (event.description.markdownLinks() ?: "").let { if (it != ui.description.tag) { ui.description.tag = it ui.description.loadMarkdown(it) } } ui.time.text = getString(R.string.event_weekday_from_to, event.start.dayOfWeek().asText, event.startTimeString(), event.endTimeString()) ui.organizers.text = event.ownerString() ui.room.text = getString(R.string.misc_room_number, conferenceRoom?.name ?: getString(R.string.event_unable_to_locate_room)) (event.posterImageId ?: event.bannerImageId).let { if (it != ui.image.tag) { ui.image.tag = it if (it != null) { ui.image.visibility = View.VISIBLE ImageService.load(db.images[it], ui.image) } else ui.image.visibility = View.GONE } } val description = descriptionFor(event).joinToString("\r\n\r\n") description.let { if (it != ui.extrasContent.tag) { ui.extrasContent.tag = it ui.extrasContent.text = it ui.extras.visibility = if (it == "") View.GONE else View.VISIBLE } } setFabIconState(db.faves.contains(eventId)) ui.favoriteButton.setOnClickListener { if (AppPreferences.dialogOnEventPress) { showDialog(event) } else { favoriteEvent(event) } } ui.favoriteButton.setOnLongClickListener { if (AppPreferences.dialogOnEventPress) { favoriteEvent(event) } else { showDialog(event) } true } ui.feedbackButton.apply { visibility = if (event.isAcceptingFeedback) View.VISIBLE else View.GONE setImageDrawable(context.createFADrawable(R.string.fa_comment)) setOnClickListener { val action = EventItemFragmentDirections.actionFragmentViewEventToEventFeedbackFragment(args.eventId) findNavController().navigate(action) } } childFragmentManager.beginTransaction() .replace(R.id.event_map, MapDetailFragment().withArguments(conferenceRoom?.id, true), "mapDetails") .commit() } } private fun showDialog(event: EventRecord) { context?.let { eventDialog(it, event, db) { isFavorite -> setFabIconState(isFavorite) } } } private fun favoriteEvent(event: EventRecord) { // TODO: Handle state change in a reactive instead of proactive way! // Due to the receiver for EventFavoriteBroadcast events, which actually modifies the DB // being the EventFavoriteBroadcast itself with its own instance of RootDb, onNext() calls // from there will not propagate to this fragment, keeping us from being reactive instead of // proactively predicting the expected state in this case. setFabIconState(!db.faves.contains(eventId)) context?.let { it.sendBroadcast(IntentFor<EventFavoriteBroadcast>(it).apply { jsonObjects["event"] = event }) } } /** * Changes the FAB based on if the current event is liked or not */ private fun setFabIconState(isFavorite: Boolean) { info("Updating icon of FAB for $eventId") if (isFavorite) { ui.favoriteButton.setImageDrawable(context?.createFADrawable(R.string.fa_heart, true)) ui.favoriteButton.backgroundTintList = ColorStateList.valueOf(resources.getColor(R.color.accent)) } else { ui.favoriteButton.setImageDrawable(context?.createFADrawable(R.string.fa_heart, false)) ui.favoriteButton.backgroundTintList = ColorStateList.valueOf(resources.getColor(R.color.primaryLight)) } } } class EventUi : AnkoComponent<Fragment> { var scrollview: ScrollView? = null lateinit var splitter: LinearLayout lateinit var extras: LinearLayout lateinit var extrasContent: TextView lateinit var image: PhotoView lateinit var title: TextView lateinit var time: TextView lateinit var room: TextView lateinit var organizers: TextView lateinit var description: MarkdownView lateinit var favoriteButton: FloatingActionButton lateinit var feedbackButton: FloatingActionButton override fun createView(ui: AnkoContext<Fragment>) = with(ui) { coordinatorLayout { backgroundResource = R.color.backgroundGrey isClickable = true scrollview = scrollView { verticalLayout { image = ankoView(::PhotoView, 0) { contentDescription = "Event" imageResource = R.drawable.placeholder_event backgroundResource = R.drawable.image_fade scaleType = ImageView.ScaleType.FIT_CENTER visibility = View.GONE adjustViewBounds = true }.lparams(matchParent, wrapContent) verticalLayout { id = R.id.event_splitter backgroundResource = R.color.primaryDarker padding = dip(15) title = textView { textResource = R.string.event compatAppearance = android.R.style.TextAppearance_Large_Inverse setPadding(0, dip(15), 0, dip(15)) gravity = Gravity.CENTER_HORIZONTAL }.lparams(matchParent, wrapContent) time = textView { compatAppearance = android.R.style.TextAppearance_Medium_Inverse setPadding(0, 0, 0, dip(10)) }.lparams(matchParent, wrapContent, weight = 5F) room = textView { compatAppearance = android.R.style.TextAppearance_Medium_Inverse setPadding(0, 0, 0, dip(10)) }.lparams(matchParent, wrapContent, weight = 5F) organizers = textView { textResource = R.string.event_run_by compatAppearance = android.R.style.TextAppearance_Medium_Inverse setPadding(0, 0, 0, dip(10)) }.lparams(matchParent, wrapContent, weight = 5F) }.lparams(matchParent, wrapContent) { setMargins(0, 0, 0, dip(10)) } extras = verticalLayout { backgroundResource = R.color.lightBackground padding = dip(15) extrasContent = fontAwesomeView { text = "{fa-home} Glyphs" singleLine = false maxLines = 6 }.lparams(matchParent, wrapContent, weight = 5F) }.lparams(matchParent, wrapContent) { setMargins(0, 0, 0, dip(10)) } verticalLayout { backgroundResource = R.color.lightBackground padding = dip(25) description = ankoView(::MarkdownView, 0) { }.lparams(matchParent, wrapContent) }.lparams(matchParent, wrapContent) verticalLayout { id = R.id.event_map } }.lparams(matchParent, wrapContent) }.lparams(matchParent, matchParent) // Icon Layout linearLayout { feedbackButton = floatingActionButton { imageResource = R.drawable.icon_menu backgroundColorResource = R.color.accent }.lparams { margin = dip(LayoutConstants.MARGIN_SMALL) } favoriteButton = floatingActionButton { }.lparams { margin = dip(LayoutConstants.MARGIN_SMALL) } }.lparams(wrapContent, wrapContent) { anchorGravity = Gravity.BOTTOM or Gravity.END anchorId = R.id.event_splitter margin = dip(LayoutConstants.MARGIN_LARGE) } } } }
mit
561bf0ee0e46ade33a76a6da21579b98
38.352761
148
0.597989
5.197731
false
false
false
false
fluidsonic/jetpack-kotlin
Sources/Measurement/Angle.kt
1
1372
package com.github.fluidsonic.jetpack import java.util.Locale public class Angle : Measurement<Angle, Angle.Unit> { private constructor(rawValue: Double) : super(rawValue) public constructor(angle: Angle) : super(angle.rawValue) public fun degrees() = rawValue protected override val description: Description<Angle, Unit> get() = Angle.description public fun radians() = degrees() * radiansPerDegree public override fun valueInUnit(unit: Unit) = when (unit) { Angle.Unit.degrees -> degrees() Angle.Unit.radians -> radians() } public enum class Unit private constructor(key: String) : _StandardUnitType<Unit, Angle> { degrees("degree"), radians("radian"); public override val _descriptor = _StandardUnitType.Descriptor(key) public override fun toString() = pluralName(Locale.getDefault()) public override fun value(value: Double) = when (this) { degrees -> degrees(value) radians -> radians(value) } } public companion object { private val description = Measurement.Description("Angle", Unit.degrees) private val degreesPerRadian = 180.0 / Math.PI private val radiansPerDegree = 1 / degreesPerRadian public fun degrees(degrees: Double) = Angle(rawValue = validatedValue(degrees)) public fun radians(radians: Double) = degrees(validatedValue(radians) * degreesPerRadian) } }
mit
ba909aaf59f1f30df470c8b4760ff9b7
19.176471
91
0.71793
3.779614
false
false
false
false
viniciussoares/esl-pod-client
app/src/main/java/br/com/wakim/eslpodclient/data/interactor/rx/DownloadSyncOnSubscribe.kt
2
5033
package br.com.wakim.eslpodclient.data.interactor.rx import br.com.wakim.eslpodclient.data.interactor.DownloadDbInteractor import br.com.wakim.eslpodclient.data.interactor.StorageInteractor import br.com.wakim.eslpodclient.data.model.DownloadStatus import br.com.wakim.eslpodclient.data.model.PodcastItem import br.com.wakim.eslpodclient.data.model.PodcastItemDetail import br.com.wakim.eslpodclient.data.model.SeekPos import br.com.wakim.eslpodclient.util.extensions.getFileName import br.com.wakim.eslpodclient.util.extensions.onNextIfSubscribed import br.com.wakim.eslpodclient.util.extensions.secondsFromHourMinute import org.jsoup.Jsoup import org.jsoup.nodes.Element import org.threeten.bp.LocalDate import org.threeten.bp.format.DateTimeFormatter import rx.Observable import rx.Subscriber class DownloadSyncOnSubscribe(private val storageInteractor: StorageInteractor, private val downloadDbInteractor: DownloadDbInteractor, private val url: String): Observable.OnSubscribe<Pair<PodcastItem, PodcastItemDetail>> { companion object { const val RESULTS_SELECTOR = "#res" const val RESULT_SELECTOR = "li div.g" const val LINK_SELECTOR = "a.l" const val PODCAST_TITLE_SELECTOR = "title" const val PODCAST_DATE_SELECTOR = ".date-header" const val PODCAST_BODIES_SELECTOR = ".pod_body" const val PODCAST_TAGS_SELECTOR = "a:gt(4)" } override fun call(subscriber: Subscriber<in Pair<PodcastItem, PodcastItemDetail>>) { val baseDir = storageInteractor.getBaseDir() downloadDbInteractor.clearDatabase() baseDir.listFiles().asSequence() .map { file -> file.nameWithoutExtension } .filter { filename -> downloadDbInteractor.getDownloadByFilename(filename) == null } .filter { filename -> filename.startsWith("EC") || filename.startsWith("ESLPod") } .map { filename -> filename.replace("EC", "English Cafe ").replace("ESLPod", "ESLPod ") } .map { searchQuery -> searchAndUpdate(searchQuery, if (searchQuery.startsWith("English Cafe")) PodcastItem.ENGLISH_CAFE else PodcastItem.PODCAST) } .filterNotNull() .forEach { pair -> subscriber.onNextIfSubscribed(pair) } subscriber.onCompleted() } fun searchAndUpdate(searchQuery: String, type: Long): Pair<PodcastItem, PodcastItemDetail>? { val document = Jsoup.connect(url + searchQuery).get() val body = document.select(RESULTS_SELECTOR) val first = body.select(RESULT_SELECTOR).firstOrNull() return first?.let { val link = first.select(LINK_SELECTOR).first() savePodcastInfo(link.absUrl("href"), type) } ?: null } fun savePodcastInfo(url: String, type: Long): Pair<PodcastItem, PodcastItemDetail> { val remoteId = url.substring(url.indexOf("?issue_id=") + 10).toLong() val document = Jsoup.connect(url).get() val titleEl = document.select(PODCAST_TITLE_SELECTOR).first() val body = titleEl.parent() val dateEl = body.select(PODCAST_DATE_SELECTOR).first() val podBodies = body.select(PODCAST_BODIES_SELECTOR) val title = titleEl.text().trim() val date = LocalDate.parse(dateEl.text(), DateTimeFormatter.ofPattern("yyyy-MM-dd")) val seekPos = getSeekPositions(podBodies[2]) val script = getScript(podBodies[3], podBodies[4]) val mp3Url = podBodies[0].select("a")[2].attr("href") val tags = podBodies[0].select(PODCAST_TAGS_SELECTOR).joinToString(", ") { it.text() } val podcastDetail = PodcastItemDetail(remoteId = remoteId, type = type, script = script, seekPos = seekPos, title = title) val podcastItem = PodcastItem(remoteId = remoteId, title = title, date = date, mp3Url = mp3Url, tags = tags, type = type) downloadDbInteractor.insertDownload(filename = podcastItem.mp3Url.getFileName(), remoteId = remoteId, status = DownloadStatus.DOWNLOADED, downloadId = 0L) return podcastItem to podcastDetail } fun getSeekPositions(indexBody : Element) : SeekPos? { val textNodes = indexBody.textNodes() if (textNodes.size < 4) return null val slow = textNodes[1].text().trim() val explanation = textNodes[2].text().trim() val normal = textNodes[3].text().trim() return SeekPos(extractSeekInSeconds(slow), extractSeekInSeconds(explanation), extractSeekInSeconds(normal)) } fun extractSeekInSeconds(label : String) : Int { val indexOfFirstDoubleDot = label.indexOf(":") val time = label.substring(indexOfFirstDoubleDot + 1).trim() return time.secondsFromHourMinute() } fun getScript(body1 : Element, body2 : Element) : String { val body2Text = body2.text() return body1.html() + if (!body2Text.isBlank()) ("\n\n" + body2Text) else "" } }
apache-2.0
052c284a18fd22501552b686d34bc689
43.946429
163
0.675541
4.312768
false
false
false
false
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/endpoints/lists/Ownerships.kt
1
5913
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ @file:Suppress("UNUSED", "PublicApiImplicitType") package jp.nephy.penicillin.endpoints.lists import jp.nephy.penicillin.core.request.action.CursorJsonObjectApiAction import jp.nephy.penicillin.core.request.parameters import jp.nephy.penicillin.core.session.get import jp.nephy.penicillin.endpoints.Lists import jp.nephy.penicillin.endpoints.Option import jp.nephy.penicillin.models.cursor.CursorLists /** * Returns the lists owned by the specified Twitter user. Private lists will only be shown if the authenticated user is also the owner of the lists. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships) * * @param count The amount of results to return per page. Defaults to 20. No more than 1000 results will ever be returned in a single page. * @param cursor Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned in the response body's next_cursor and previous_cursor attributes to page back and forth in the list. It is recommended to always use cursors when the method supports them. See [Cursoring](https://developer.twitter.com/en/docs/basics/cursoring) for more information. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [CursorJsonObjectApiAction] for [CursorLists] model. */ fun Lists.ownerships( count: Int? = null, cursor: Long? = null, vararg options: Option ) = ownershipsInternal(null, null, count, cursor, *options) /** * Returns the lists owned by the specified Twitter user. Private lists will only be shown if the authenticated user is also the owner of the lists. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships) * * @param userId The ID of the user for whom to return results. Helpful for disambiguating when a valid user ID is also a valid screen name. * @param count The amount of results to return per page. Defaults to 20. No more than 1000 results will ever be returned in a single page. * @param cursor Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned in the response body's next_cursor and previous_cursor attributes to page back and forth in the list. It is recommended to always use cursors when the method supports them. See [Cursoring](https://developer.twitter.com/en/docs/basics/cursoring) for more information. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [CursorJsonObjectApiAction] for [CursorLists] model. */ fun Lists.ownershipsByUserId( userId: Long, count: Int? = null, cursor: Long? = null, vararg options: Option ) = ownershipsInternal(userId, null, count, cursor, *options) /** * Returns the lists owned by the specified Twitter user. Private lists will only be shown if the authenticated user is also the owner of the lists. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships) * * @param screenName The screen name of the user for whom to return results. Helpful for disambiguating when a valid screen name is also a user ID. * @param count The amount of results to return per page. Defaults to 20. No more than 1000 results will ever be returned in a single page. * @param cursor Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned in the response body's next_cursor and previous_cursor attributes to page back and forth in the list. It is recommended to always use cursors when the method supports them. See [Cursoring](https://developer.twitter.com/en/docs/basics/cursoring) for more information. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [CursorJsonObjectApiAction] for [CursorLists] model. */ fun Lists.ownerships( screenName: String, count: Int? = null, cursor: Long? = null, vararg options: Option ) = ownershipsInternal(null, screenName, count, cursor, *options) private fun Lists.ownershipsInternal( userId: Long? = null, screenName: String? = null, count: Int? = null, cursor: Long? = null, vararg options: Option ) = client.session.get("/1.1/lists/ownerships.json") { parameters( "user_id" to userId, "screen_name" to screenName, "count" to count, "cursor" to cursor, *options ) }.cursorJsonObject<CursorLists>() /** * Shorthand property to [Lists.ownerships]. * @see Lists.ownerships */ val Lists.ownerships get() = ownerships()
mit
8ae40014709e2e8df0a5eda7c09a6d1c
51.794643
380
0.752579
4.137859
false
false
false
false
VerifAPS/verifaps-lib
run/src/main/kotlin/edu/kit/iti/formal/automation/run/State.kt
1
2058
package edu.kit.iti.formal.automation.run import edu.kit.iti.formal.automation.datatypes.AnyDt import edu.kit.iti.formal.automation.datatypes.RecordType import edu.kit.iti.formal.automation.datatypes.values.RecordValue import edu.kit.iti.formal.automation.datatypes.values.Value import java.util.* typealias EValue = Value<*, *> class State(private val impl: MutableMap<String, EValue> = HashMap()/*val parent: State?*/) : MutableMap<String, EValue> by impl { fun declare(key: String, dataType: AnyDt) = declare(key, ExecutionFacade.getDefaultValue(dataType)) fun <T : AnyDt, S : Any> declare(key: String, value: Value<T, S>) = impl.put(key, value) //operator fun get(name: String) = impl[name] operator fun contains(key: String) = key in impl operator fun get(name: List<String>): EValue? { if (name.isEmpty()) return null if (name.size == 1) return this[name[0]] try { val o = impl[name[0]] as Value<RecordType, RecordValue> val state = State(o.value.fieldValues) val r = 1..(name.size - 1) return state[name.slice(r)] } catch (e: ClassCastException) { return null } } operator fun contains(key: List<String>) = get(key) != null operator fun plusAssign(values: Map<String, EValue>) { impl += values } operator fun set(name: List<String>, value: EValue) { if (name.isEmpty()) return if (name.size == 1) this[name[0]] = value try { val o = impl[name[0]] as Value<RecordType, RecordValue> val state = State(o.value.fieldValues) val r = 1..(name.size-1) state[name.slice(r)] = value } catch (e: ClassCastException) { return } } operator fun set(name: String, value: EValue) { impl[name] = value } fun clone(): State { //TODO copy val s = State(HashMap(impl)) return s } override fun toString(): String = map { (k, v) -> k to v }.toString() }
gpl-3.0
d51a96579db30a75642fca580662906f
32.737705
103
0.607872
3.681574
false
false
false
false
VerifAPS/verifaps-lib
lang/src/main/kotlin/edu/kit/iti/formal/automation/analysis/RegisterDataTypes.kt
1
3707
package edu.kit.iti.formal.automation.analysis import edu.kit.iti.formal.automation.scope.Scope import edu.kit.iti.formal.automation.st.ast.* import edu.kit.iti.formal.automation.st.util.AstVisitorWithScope /** * @author Alexander Weigl, Augusto Modanese * @version 1 (25.06.17) */ class RegisterDataTypes(val globalScope: Scope) : AstVisitorWithScope<Unit>() { init { scope = globalScope } override fun defaultVisit(obj: Any) {} override fun visit(elements: PouElements) { super.visit(elements) } override fun visit(pd: ProgramDeclaration) { scope.registerProgram(pd) goIntoScope(pd) pd.actions.forEach { a -> pd.scope.registerAction(a) } goOutoScope() } override fun visit(fbd: FunctionBlockDeclaration) { scope.registerFunctionBlock(fbd) goIntoScope(fbd) fbd.actions.forEach { scope.registerAction(it) } fbd.methods.forEach { scope.registerMethod(it); it.scope.parent = scope } goOutoScope() } override fun visit(functionDeclaration: FunctionDeclaration) { scope.registerFunction(functionDeclaration) goIntoScope(functionDeclaration) goOutoScope() } override fun visit(subRangeTypeDeclaration: SubRangeTypeDeclaration) { scope.registerType(subRangeTypeDeclaration) } override fun visit(variableDeclaration: VariableDeclaration) { //weigl: do not register anonymous datatype, or references to data types. /* if (variableDeclaration.getTypeDeclaration() instanceof ArrayTypeDeclaration) variableDeclaration.getTypeDeclaration().accept(this); return super.visit(variableDeclaration); */ } override fun visit(simpleTypeDeclaration: SimpleTypeDeclaration) { scope.registerType(simpleTypeDeclaration) //super.visit(simpleTypeDeclaration) } override fun visit(ptd: PointerTypeDeclaration) { scope.registerType(ptd) return super.visit(ptd) } override fun visit(clazz: ClassDeclaration) { scope.registerClass(clazz) goIntoScope(clazz) clazz.methods.forEach { scope.registerMethod(it); it.scope.parent = scope } goOutoScope() } override fun visit(interfaceDeclaration: InterfaceDeclaration) { //goIntoScope(interfaceDeclaration) scope.registerInterface(interfaceDeclaration) //super.visit(interfaceDeclaration) } override fun visit(arrayTypeDeclaration: ArrayTypeDeclaration) { scope.registerType(arrayTypeDeclaration) } /** * {@inheritDoc} */ override fun visit(enumerationTypeDeclaration: EnumerationTypeDeclaration) { scope.registerType(enumerationTypeDeclaration) } /** * {@inheritDoc} */ override fun visit(stringTypeDeclaration: StringTypeDeclaration) { scope.registerType(stringTypeDeclaration) } override fun visit(typeDeclarations: TypeDeclarations) { for (td in typeDeclarations) td.accept(this) } override fun visit(structureTypeDeclaration: StructureTypeDeclaration) { scope.registerType(structureTypeDeclaration) } override fun visit(gvl: GlobalVariableListDeclaration) { scope.addVariables(gvl.scope) gvl.scope = scope // global variables does not open an own scope. //return super.visit(gvl) } private fun goIntoScope(hasScope: HasScope) { if (scope != null) hasScope.scope.parent = scope scope = hasScope.scope } private fun goOutoScope() { scope = if (scope.parent != null) scope.parent!! else globalScope } }
gpl-3.0
97885f933a309b1b2aedcbd28815bb7c
27.960938
85
0.679525
4.515225
false
false
false
false
android/android-dev-challenge-compose
app/src/main/java/com/google/ads22/speedchallenge/ui/theme/Color.kt
1
4166
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.ads22.speedchallenge.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF0058CA) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFD9E2FF) val md_theme_light_onPrimaryContainer = Color(0xFF001945) val md_theme_light_secondary = Color(0xFF355CA8) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFD9E2FF) val md_theme_light_onSecondaryContainer = Color(0xFF001944) val md_theme_light_tertiary = Color(0xFF85468C) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFFFD6FD) val md_theme_light_onTertiaryContainer = Color(0xFF36003E) val md_theme_light_error = Color(0xFFBA1A1A) val md_theme_light_errorContainer = Color(0xFFFFDAD6) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_onErrorContainer = Color(0xFF410002) val md_theme_light_background = Color(0xFFFEFBFF) val md_theme_light_onBackground = Color(0xFF001945) val md_theme_light_surface = Color(0xFFFEFBFF) val md_theme_light_onSurface = Color(0xFF001945) val md_theme_light_surfaceVariant = Color(0xFF2B2B2B) val md_theme_light_onSurfaceVariant = Color(0xFF44464F) val md_theme_light_outline = Color(0xFF757780) val md_theme_light_inverseOnSurface = Color(0xFFEEF0FF) val md_theme_light_inverseSurface = Color(0xFF002C6F) val md_theme_light_inversePrimary = Color(0xFFB0C6FF) val md_theme_light_shadow = Color(0xFF000000) val md_theme_light_surfaceTint = Color(0xFF0058CA) val md_theme_light_surfaceTintColor = Color(0xFF0058CA) val md_theme_dark_primary = Color(0xFFB0C6FF) val md_theme_dark_onPrimary = Color(0xFF002D6E) val md_theme_dark_primaryContainer = Color(0xFF00429B) val md_theme_dark_onPrimaryContainer = Color(0xFFD9E2FF) val md_theme_dark_secondary = Color(0xFFAFC6FF) val md_theme_dark_onSecondary = Color(0xFF002D6D) val md_theme_dark_secondaryContainer = Color(0xFF17448F) val md_theme_dark_onSecondaryContainer = Color(0xFFD9E2FF) val md_theme_dark_tertiary = Color(0xFFF8ADFB) val md_theme_dark_onTertiary = Color(0xFF51145A) val md_theme_dark_tertiaryContainer = Color(0xFF6B2D72) val md_theme_dark_onTertiaryContainer = Color(0xFFFFD6FD) val md_theme_dark_error = Color(0xFFFFB4AB) val md_theme_dark_errorContainer = Color(0xFF93000A) val md_theme_dark_onError = Color(0xFF690005) val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6) val md_theme_dark_background = Color(0xFF001945) val md_theme_dark_onBackground = Color(0xFFD9E2FF) val md_theme_dark_surface = Color(0xFF001945) val md_theme_dark_onSurface = Color(0xFFD9E2FF) val md_theme_dark_surfaceVariant = Color(0xFF44464F) val md_theme_dark_onSurfaceVariant = Color(0xFFC5C6D0) val md_theme_dark_outline = Color(0xFF8F9099) val md_theme_dark_inverseOnSurface = Color(0xFF001945) val md_theme_dark_inverseSurface = Color(0xFFD9E2FF) val md_theme_dark_inversePrimary = Color(0xFF0058CA) val md_theme_dark_shadow = Color(0xFF000000) val md_theme_dark_surfaceTint = Color(0xFFB0C6FF) val md_theme_dark_surfaceTintColor = Color(0xFFB0C6FF) val seed = Color(0xFF0058CA) val CustomColor1 = Color(0xFF22252A) val light_CustomColor1 = Color(0xFF1260A4) val light_onCustomColor1 = Color(0xFFFFFFFF) val light_CustomColor1Container = Color(0xFFD3E4FF) val light_onCustomColor1Container = Color(0xFF001C38) val dark_CustomColor1 = Color(0xFFA2C9FF) val dark_onCustomColor1 = Color(0xFF00315B) val dark_CustomColor1Container = Color(0xFF004880) val dark_onCustomColor1Container = Color(0xFFD3E4FF)
apache-2.0
a2e567ade64495585a44e330136a2fb1
45.288889
75
0.799328
2.917367
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-crafting-skill-bukkit/src/main/kotlin/com/rpkit/craftingskill/bukkit/listener/BlockBreakListener.kt
1
4633
/* * Copyright 2022 Ren Binden * * 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.rpkit.craftingskill.bukkit.listener import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.bukkit.extension.addLore import com.rpkit.core.service.Services import com.rpkit.craftingskill.bukkit.RPKCraftingSkillBukkit import com.rpkit.craftingskill.bukkit.craftingskill.RPKCraftingAction import com.rpkit.craftingskill.bukkit.craftingskill.RPKCraftingSkillService import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import org.bukkit.GameMode import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.block.BlockBreakEvent import kotlin.math.min import kotlin.math.roundToInt import kotlin.random.Random class BlockBreakListener(private val plugin: RPKCraftingSkillBukkit) : Listener { @EventHandler fun onBlockBreak(event: BlockBreakEvent) { val bukkitPlayer = event.player if (bukkitPlayer.gameMode == GameMode.CREATIVE || bukkitPlayer.gameMode == GameMode.SPECTATOR) return val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return val characterService = Services[RPKCharacterService::class.java] ?: return val craftingSkillService = Services[RPKCraftingSkillService::class.java] ?: return val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(bukkitPlayer) ?: return val character = characterService.getPreloadedActiveCharacter(minecraftProfile) ?: return event.isDropItems = false for (item in event.block.getDrops(event.player.inventory.itemInMainHand)) { val material = item.type craftingSkillService.getCraftingExperience(character, RPKCraftingAction.MINE, material) .thenAccept { craftingSkill -> val quality = craftingSkillService.getQualityFor(RPKCraftingAction.MINE, material, craftingSkill) val amount = craftingSkillService.getAmountFor(RPKCraftingAction.MINE, material, craftingSkill) if (quality != null) { item.addLore(quality.lore) } var dropItem = false if (amount > 1) { item.amount = amount.roundToInt() dropItem = true } else if (amount < 1) { val random = Random.nextDouble() if (random <= amount) { item.amount = 1 dropItem = true } } else { dropItem = true } val maxExperience = plugin.config.getConfigurationSection("mining.$material") ?.getKeys(false) ?.maxOfOrNull(String::toInt) ?: 0 if (maxExperience != 0 && craftingSkill < maxExperience) { val totalExperience = min(craftingSkill + item.amount, maxExperience) craftingSkillService.setCraftingExperience( character, RPKCraftingAction.MINE, material, totalExperience ).thenRun { event.player.sendMessage( plugin.messages["mine-experience", mapOf( "total_experience" to totalExperience.toString(), "received_experience" to item.amount.toString() )] ) } } if (dropItem) { plugin.server.scheduler.runTask(plugin, Runnable { event.block.world.dropItemNaturally(event.block.location, item) }) } } } } }
apache-2.0
05aa1d25f959fd12e0620f62eff9c358
46.285714
117
0.593784
5.588661
false
false
false
false
chaseberry/KJson
src/main/kotlin/edu/csh/chase/kjson/JsonObject.kt
1
23829
package edu.csh.chase.kjson import java.io.IOException import java.io.StringWriter import java.io.Writer import java.util.* class JsonObject() : JsonBase(), Iterable<Map.Entry<String, Any?>> { private val map = LinkedHashMap<String, Any?>() /** * The number of key, value pairs this JsonObject currently holds */ override val size: Int get() { return map.size } /** * An iterator over the set of keys this JsonObject currently holds */ val keys: Iterator<String> get() { return map.keys.iterator() } /** * A set of the keys this JsonObject currently holds */ val keySet: Set<String> get() { return map.keys } /** * Creates an instance of a JsonObject with a JsonTokener * Parses the tokens to create a JsonObject * An invalid JsonTokener will cause a JsonException to be thrown */ constructor(tokener: JsonTokener) : this() { if (tokener.nextClean() != '{') { throw tokener.syntaxError("A JsonObject must begin with '{'") } var key: String while (true) { when (tokener.nextClean()) { 0.toChar() -> throw tokener.syntaxError("A JsonObject must end with '}'")//EOF '}' -> return else -> { tokener.back() key = tokener.nextValue().toString() } } // The key is followed by ':'. if (tokener.nextClean() != ':') { throw tokener.syntaxError("Expected a ':' after a key") } this.putOnce(key, tokener.nextValue()) // Pairs are separated by ','. when (tokener.nextClean()) { ',' -> { if (tokener.nextClean() == '}') { return } tokener.back() } '}' -> return else -> throw tokener.syntaxError("Expected a ',' or '}'") } } } /** * Constructs a JsonObject from a string * An invalid JsonString will cause a JsonException to be thrown */ constructor(stringJson: String) : this(JsonTokener(stringJson)) /** * Constructs a clone of the provided JsonObject with only the specified keys */ constructor(obj: JsonObject, vararg names: String) : this() { for (name in names) { putOnce(name, obj[name]) } } /** * Constructs a JsonObject from a map of <String, Any?> */ constructor(map: Map<String, Any?>) : this() { for ((key, value) in map) { putOnce(key, value) } } /** * Constructs a JsonObject from a list of key, value Pairs * Any key,value with a value that is not a valid json type will be ignored */ constructor(vararg elementList: Pair<String, Any?>) : this() { elementList.filter { it.second.isValidJsonType() }.forEach { putOnce(it) } } private fun addKeyToValue(key: String, value: Any?) { if (!value.isValidJsonType()) { throw JsonException("$value is not a valid type for Json.") } if (value is Double && (value.isInfinite() || value.isNaN())) { throw JsonException("Doubles must be finite and real") } map[key] = value } /** * Adds the key and value to this JsonObject only if key is not already present * @param key The key for the value * @param value The value assigned to the specified key * @return This JsonObject the key, value were placed into */ fun putOnce(key: String, value: Any?): JsonObject { if (key in map) { return this//Throw an error? } addKeyToValue(key, value) return this } /** * Adds the key and value to this JsonObject only if key is not already present * @param keyValuePair A key, value pair to add to this JsonObject * @return This JsonObject the pair was placed into */ fun putOnce(keyValuePair: Pair<String, Any?>): JsonObject { return putOnce(keyValuePair.first, keyValuePair.second) } //Setters /** * A key, value set function, in Kotlin this can be invoked as jsonObject["key"] = "value" * * @param key String a key for this JsonObject. Will overwrite any data previously stored in this key * @param value Any? a value to be stored at this key. This must be a valid Json type or an exception will be thrown * * @throws JsonException an unchecked exception will be thrown if the passed value is not a valid Json value type */ operator fun set(key: String, value: Any?) { addKeyToValue(key, value) } //Putters /** * Puts a mapping of key to value in the given object * This function is used to chain calls together for simplicity * * @param key A String key * @param value A valid json value * * @return JsonObject the JsonObject the key,value pair was put into */ fun put(key: String, value: Any?): JsonObject { addKeyToValue(key, value) return this } /** * Puts a mapping of a key to value in the given object * This function can be used to chain calls together for simplicity * * @param keyValuePair A Pair<String,Any?> of a key to value * * @return JsonObject the JsonObject the pair was put into */ fun put(keyValuePair: Pair<String, Any?>): JsonObject { return put(keyValuePair.first, keyValuePair.second) } /** * Puts from a map of key, value Pairs in the given object * This function can be used to chain calls together for simplicity * * @param map A map of key, value - <String, Any?> * * @return JsonObject the JsonObject the list of pairs was put into */ fun put(map: Map<String, Any?>): JsonObject { map.forEach { (key, value) -> put(key, value) } return this } /** * Puts from a list of key, value Pairs in the given object * This function can be used to chain calls together for simplicity * * @param elementList A list of key, value Pair<String,Any?> * * @return JsonObject the JsonObject the list of pairs was put into */ fun put(vararg elementList: Pair<String, Any?>): JsonObject { elementList.filter { it.second.isValidJsonType() }.forEach { put(it) } return this } /** * Takes a Any? and only adds it to the given key if the value is not null * This function can be used to chain calls together for simplicity * * @param key A String key * @param value A valid json value * * @return JsonObject the JsonObject the key,value pair was put into */ fun putNotNull(key: String, value: Any?): JsonObject { if (value == null) { return this } addKeyToValue(key, value) return this } /** * Takes a Pair of <String, Any?> and only adds it to the given key if the value is not null * This function can be used to chain calls together for simplicity * * @param keyValuePair A Pair<String,Any?> of a key to value * * @return JsonObject the JsonObject the pair was put into */ fun putNotNull(keyValuePair: Pair<String, Any?>): JsonObject { return putNotNull(keyValuePair.first, keyValuePair.second) } /** * Puts from a map of key, value Pairs in the given object only if the value is not null * This function can be used to chain calls together for simplicity * * @param map A map of key, value - <String, Any?> * * @return JsonObject the JsonObject the list of pairs was put into */ fun putNotNull(map: Map<String, Any?>): JsonObject { map.forEach { (key, value) -> putNotNull(key, value) } return this } /** * Puts from a list of key, value Pairs in the given object only if the value is not null * This function can be used to chain calls together for simplicity * * @param elementList A list of key, value Pair<String,Any?> * * @return JsonObject the JsonObject the list of pairs was put into */ fun putNotNull(vararg elementList: Pair<String, Any?>): JsonObject { elementList.filter { it.second.isValidJsonType() }.forEach { putNotNull(it) } return this } //Getters /** * Gets the value from a given key * * @param key The key to pull the value from * @return The value corresponding to the given key, null if no value was found */ operator fun get(key: String): Any? { return map[key] } /** * Gets the value from a given key * * @param key The key to pull the value from * @param default The default value to return if null is found * @return The value corresponding to the given key, default if no value was found */ operator fun get(key: String, default: Any): Any { if (map[key] != null) { return map[key]!! } return default } /** * Gets a Boolean? from a given key * * @param key The key to pull the value from * @return The Boolean corresponding to the given key, null if no value was found */ fun getBoolean(key: String): Boolean? = get(key) as? Boolean /** * Gets the value for the given key and attempts to coerce it into a Boolean. * * @param key The key to coerce the value from * @return The Boolean corresponding to the given key, null if there was no value, or it couldn't be coerced */ fun coerceBoolean(key: String): Boolean? = Coercers.toBoolean(get(key)) /** * Gets the value from a given key * * @param key The key to pull the value from * @param default The default value to return if null is found * @return The value corresponding to the given key, default if no value was found */ fun getBoolean(key: String, default: Boolean): Boolean = getBoolean(key) ?: default /** * Gets the value from a given key and attempts to coerce it to a Boolean * If no value can be found, or coercion fails it will return the default provided * * @param key The key to pull the value from * @param default The default value to return if no value is found, or the coercion fails * @return The coerced value, or default */ fun coerceBoolean(key: String, default: Boolean): Boolean = coerceBoolean(key) ?: default /** * Gets the value from a given key * * @param key The key to pull the value from * @return The value corresponding to the given key, null if no value was found */ fun getInt(key: String): Int? = get(key) as? Int /** * Gets the value for the given key and attempts to coerce it into an Int. * * @param key The key to coerce the value from * @return The Int corresponding to the given key, null if there was no value, or it couldn't be coerced */ fun coerceInt(key: String): Int? = Coercers.toInt(get(key)) /** * Gets the value from a given key * * @param key The key to pull the value from * @param default The default value to return if null is found * @return The value corresponding to the given key, default if no value was found */ fun getInt(key: String, default: Int): Int = getInt(key) ?: default /** * Gets the value from a given key and attempts to coerce it to an Int * If no value can be found, or coercion fails it will return the default provided * * @param key The key to pull the value from * @param default The default value to return if no value is found, or the coercion fails * @return The coerced value, or default */ fun coerceInt(key: String, default: Int): Int = coerceInt(key) ?: default /** * Gets the value from a given key * * @param key The key to pull the value from * @return The value corresponding to the given key, null if no value was found */ fun getString(key: String): String? = get(key) as? String /** * Gets the value for the given key and attempts to coerce it into a String. * Coercing to a String will only return null if the value is null/not present. All other values are .toString() * * @param key The key to coerce the value from * @return The String corresponding to the given key, null if there was no value, or it couldn't be coerced */ fun coerceString(key: String): String? = Coercers.toString(get(key)) /** * Gets the value from a given key * * @param key The key to pull the value from * @param default The default value to return if null is found * @return The value corresponding to the given key, default if no value was found */ fun getString(key: String, default: String): String = getString(key) ?: default /** * Gets the value for the given key and attempts to coerce it into a String. * Coercing to a String will only return null if the value is null/not present. All other values are .toString() * If no value can be found, or coercion fails it will return the default provided * * @param key The key to pull the value from * @param default The default value to return if no value is found, or the coercion fails * @return The coerced value, or default */ fun coerceString(key: String, default: String): String = coerceString(key) ?: default /** * Gets the value from a given key * * @param key The key to pull the value from * @return The value corresponding to the given key, null if no value was found */ fun getDouble(key: String): Double? = get(key) as? Double /** * Gets the value for the given key and attempts to coerce it into a Double. * * @param key The key to coerce the value from * @return The Int corresponding to the given key, null if there was no value, or it couldn't be coerced */ fun coerceDouble(key: String): Double? = Coercers.toDouble(get(key)) /** * Gets the value from a given key * * @param key The key to pull the value from * @param default The default value to return if null is found * @return The value corresponding to the given key, default if no value was found */ fun getDouble(key: String, default: Double): Double = getDouble(key) ?: default /** * Gets the value from a given key and attempts to coerce it to a Double * If no value can be found, or coercion fails it will return the default provided * * @param key The key to pull the value from * @param default The default value to return if no value is found, or the coercion fails * @return The coerced value, or default */ fun coerceDouble(key: String, default: Double): Double = coerceDouble(key) ?: default /** * Gets the value from a given key * * @param key The key to pull the value from * @return The value corresponding to the given key, null if no value was found */ fun getJsonObject(key: String): JsonObject? = get(key) as? JsonObject /** * Gets the value from a given key * * @param key The key to pull the value from * @param default The default value to return if null is found * @return The value corresponding to the given key, default if no value was found */ fun getJsonObject(key: String, default: JsonObject): JsonObject = getJsonObject(key) ?: default /** * Gets the value from a given key * * @param key The key to pull the value from * @return The value corresponding to the given key, null if no value was found */ fun getJsonArray(key: String): JsonArray? = get(key) as? JsonArray /** * Gets the value from a given key * * @param key The key to pull the value from * @param default The default value to return if null is found * @return The value corresponding to the given key, default if no value was found */ fun getJsonArray(key: String, default: JsonArray): JsonArray = getJsonArray(key) ?: default /** * Gets the value from a given key if the value is a number * * @param key The key to pull the value from * @return The Float from the given key, null if no value or not a number */ @Deprecated(message = "Not parsed", replaceWith = ReplaceWith("coerceFloat(key)")) fun getFloat(key: String): Float? = coerceFloat(key) /** * Gets the value for the given key and attempts to coerce it into a Float. * * @param key The key to coerce the value from * @return The Float corresponding to the given key, null if there was no value, or it couldn't be coerced */ fun coerceFloat(key: String): Float? = Coercers.toFloat(get(key)) /** * Gets the value from the given key if the value is a number * * @param key The key to pull a value from * @param default The default value is no value is found * @return The Float from the given key, default if no value or not a number */ @Deprecated(message = "Not parsed", replaceWith = ReplaceWith("coerceFloat(key, default)")) fun getFloat(key: String, default: Float): Float = coerceFloat(key, default) /** * Gets the value from a given key and attempts to coerce it to a Float * If no value can be found, or coercion fails it will return the default provided * * @param key The key to pull the value from * @param default The default value to return if no value is found, or the coercion fails * @return The coerced value, or default */ fun coerceFloat(key: String, default: Float): Float = coerceFloat(key) ?: default /** * Gets the value from a given key if the value is a number * * @param key The key to pull the value from * @return The Long from the given key, null if no value or not a number */ @Deprecated(message = "Not the default parsed number type", replaceWith = ReplaceWith("coerceLong(key)")) fun getLong(key: String): Long? = coerceLong(key) /** * Gets the value for the given key and attempts to coerce it into a Long. * * @param key The key to coerce the value from * @return The Long corresponding to the given key, null if there was no value, or it couldn't be coerced */ fun coerceLong(key: String): Long? = Coercers.toLong(get(key)) /** * Gets the value from the given key if the value is a number * * @param key The key to pull a value from * @param default The default value is no value is found * @return The Long from the given key, default if no value or not a number */ @Deprecated(message = "Not the default parsed number type", replaceWith = ReplaceWith("coerceLong(key, default)")) fun getLong(key: String, default: Long): Long = coerceLong(key, default) /** * Gets the value from a given key and attempts to coerce it to a Long * If no value can be found, or coercion fails it will return the default provided * * @param key The key to pull the value from * @param default The default value to return if no value is found, or the coercion fails * @return The coerced value, or default */ fun coerceLong(key: String, default: Long): Long = coerceLong(key) ?: default //Other functions /** * Returns an immutable map of this JsonObject * This is ReadOnly and modifying will cause an exception to be thrown * * @return An immutable map */ fun getInternalMap(): Map<String, Any?> = Collections.unmodifiableMap(map.mapValues { it.value?.let { when (it) { is JsonObject -> it.getInternalMap() is JsonArray -> it.getInternalArray() else -> it } } }) /** * Removes a given (key, value) pair from this JsonObject * * @param key The key to remove * * @return The value removed, or null if none were removed */ fun remove(key: String): Any? = map.remove(key) /** * Removes all values from this JsonObject * No data is saved and the size is reset to 0 * * @return Map<String, Any?> a copy of the key,value pairs that were housed in this JsonObject */ fun clear(): HashMap<String, Any?> { val mapClone = HashMap<String, Any?>(map) map.clear() return mapClone } /** * Check to see if a given key exists in the map * This function does not care about the value if found * * @return Boolean true if a key exists in this JsonObject, false otherwise */ operator fun contains(key: String): Boolean { return key in map } /** * Check to see if a given key exists and it's value is null * * @return Boolean true if the key exists and value of key is null, false otherwise */ fun isNull(key: String): Boolean { return key in this && get(key) == null } override fun equals(other: Any?): Boolean { return other is JsonObject && other.map == map } override fun jsonSerialize(): String { return this.toString(false) } /** * Gets an iterator of key, Value pairs * This can be used in a foreach loop to loop over all pairs in this JsonObject * * @return an iterator of key, Value pairs */ override fun iterator(): Iterator<Map.Entry<String, Any?>> { return map.iterator() } override fun toString(): String { return toString(false) } override fun toString(shouldIndent: Boolean, depth: Int): String { val writer = StringWriter() synchronized(writer.buffer) { return this.write(writer, shouldIndent, depth).toString() } } /** * Write the contents of the JSONObject as JSON text to a writer. For * compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return The writer. */ fun write(writer: Writer): Writer { return this.write(writer, false) } /** * Write the contents of the JSONObject as JSON text to a writer. For * compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return The writer. */ fun write(writer: Writer, shouldIndent: Boolean, depth: Int = 1): Writer { try { var addComa = false writer.write("{") for ((key, value) in map) { if (addComa) { writer.write(",") } if (shouldIndent) { writer.write("\n") writer.indent(depth) } writer.write(quote(key)) writer.write(":") if (shouldIndent) { writer.write(" ") } writer.write(JsonValues.toString(value, shouldIndent, depth + 1)) addComa = true } if (shouldIndent) { writer.write("\n") writer.indent(depth - 1) } writer.write("}") return writer } catch (exception: IOException) { throw JsonException(exception) } } }
apache-2.0
28d13ee1428af1c7cb5cf2e9e9840147
33.286331
120
0.608376
4.361091
false
false
false
false
snxamdf/study-android-login
app/src/androidTest/java/RSAUtils.kt
1
7091
import android.mutil.Base64 import java.security.KeyFactory import java.security.KeyPair import java.security.KeyPairGenerator import java.security.NoSuchAlgorithmException import java.security.PrivateKey import java.security.PublicKey import java.security.interfaces.RSAPrivateKey import java.security.interfaces.RSAPublicKey import java.security.spec.PKCS8EncodedKeySpec import java.security.spec.X509EncodedKeySpec import javax.crypto.Cipher /** * Created by hongyanyang1 on 2017/6/13. */ class RSAUtils { fun test() { val encodedString = Base64.encodeToString("whoislcj".toByteArray(), Base64.DEFAULT) val decodedString = String(Base64.decode(encodedString, Base64.DEFAULT)) } companion object { fun base64EncodedString(key: ByteArray): String { return Base64.encodeToString(key, Base64.DEFAULT) } fun base64DecodedString(key: ByteArray): ByteArray { return Base64.decode(key, Base64.DEFAULT) } fun generateRSAKeyPair(keyLength: Int): KeyPair? { try { val kpg = KeyPairGenerator.getInstance(RSA) kpg.initialize(keyLength) return kpg.genKeyPair() } catch (e: NoSuchAlgorithmException) { e.printStackTrace() return null } } /** * 用公钥对字符串进行加密 * @param data 原文 */ @Throws(Exception::class) fun encryptByPublicKey(data: ByteArray, publicKey: ByteArray): ByteArray { // 得到公钥 val keySpec = X509EncodedKeySpec(publicKey) val kf = KeyFactory.getInstance(RSA) val keyPublic = kf.generatePublic(keySpec) // 加密数据 val cp = Cipher.getInstance(ECB_PKCS1_PADDING) cp.init(Cipher.ENCRYPT_MODE, keyPublic) return cp.doFinal(data) } /** * 使用私钥进行解密 */ @Throws(Exception::class) fun decryptByPrivateKey(encrypted: ByteArray, privateKey: ByteArray): ByteArray { // 得到私钥 val keySpec = PKCS8EncodedKeySpec(privateKey) val kf = KeyFactory.getInstance(RSA) val keyPrivate = kf.generatePrivate(keySpec) // 解密数据 val cp = Cipher.getInstance(ECB_PKCS1_PADDING) cp.init(Cipher.DECRYPT_MODE, keyPrivate) val arr = cp.doFinal(encrypted) return arr } val RSA = "RSA"// 非对称加密密钥算法 val ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding"//加密填充方式 val DEFAULT_KEY_SIZE = 2048//秘钥默认长度 @JvmStatic fun main(args: Array<String>) { val keyPair = RSAUtils.generateRSAKeyPair(RSAUtils.DEFAULT_KEY_SIZE) // 生成公钥 val publicKey = keyPair!!.public as RSAPublicKey println(base64EncodedString(publicKey.encoded)) // 生成私钥 val privateKey = keyPair.private as RSAPrivateKey println(base64EncodedString(privateKey.encoded)) try { //测试 val o = "aaaaaaaaaaaa" val enr = encryptAndBase64Encode(o.toByteArray())//加密后转base64 val dec = decryptAndBase64Decode(enr!!.toByteArray())//解base64后解密 val o2 = String(dec!!) println(o2) } catch (e: Exception) { e.printStackTrace() } } //加密 字符串先rsa encrypt 后 Base64Decode internal fun encryptAndBase64Encode(src: ByteArray): String? { try { return RSAUtils.base64EncodedString(RSAUtils.encryptByPublicKey(src, RSAUtils.base64DecodedString(pubKey.toByteArray()))) } catch (e: Exception) { e.printStackTrace() } return null } //解密 字符串先Base64Decode 后 rsa decrypt internal fun decryptAndBase64Decode(src: ByteArray): ByteArray? { try { return RSAUtils.decryptByPrivateKey(RSAUtils.base64DecodedString(src), RSAUtils.base64DecodedString(priKey.toByteArray())) } catch (e: Exception) { e.printStackTrace() } return null } private val pubKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlaSVahwldva5mvxY9I2uImKO5TZA/cnc\n" + "6MFEZnBW1NbUlq85M7sjHI8Lm/NXKtvy8yF114jUvZhU91DrfC1PfndMbJCl9YW+qFVz42r4E6Oa\n" + "T5+fAJAUWV5tXR2SWYvjaL7TZUuCNK/0DZbfyTqgPasTD1XlO6uEHRBuPyfoC0QuW/xbvrBFWjoh\n" + "RINUnozGaiEnS2eij17X6Pll3g+h9hx81Owvpnx1EhyUP4rrs53xILbWGpxtnEI2n2B/Vs0ffpnD\n" + "hUDmIdwfiWSX9OSxoHn1NRDunRJfl0T3OkYr3gAzrudkTBddLF4Ebzye3g83H05uj8C2T2GkaY+l\n" + "+1vzKwIDAQAB" private val priKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCVpJVqHCV29rma/Fj0ja4iYo7l\n" + "NkD9ydzowURmcFbU1tSWrzkzuyMcjwub81cq2/LzIXXXiNS9mFT3UOt8LU9+d0xskKX1hb6oVXPj\n" + "avgTo5pPn58AkBRZXm1dHZJZi+NovtNlS4I0r/QNlt/JOqA9qxMPVeU7q4QdEG4/J+gLRC5b/Fu+\n" + "sEVaOiFEg1SejMZqISdLZ6KPXtfo+WXeD6H2HHzU7C+mfHUSHJQ/iuuznfEgttYanG2cQjafYH9W\n" + "zR9+mcOFQOYh3B+JZJf05LGgefU1EO6dEl+XRPc6RiveADOu52RMF10sXgRvPJ7eDzcfTm6PwLZP\n" + "YaRpj6X7W/MrAgMBAAECggEBAISo0niuGRx8n5BhU68BhzUecJWM4lLayMdixnOV9bRb+zzWe/x7\n" + "UyY3PdB0CnuJX7jgmeqIeCjYScKybwC33ng75Hl+RlIBzkLG9qTOqLwoVl1uIXRLRm7vwj5BQAO4\n" + "etLaEOgE55ozvkTp0tw+592jspLuz/h1Ffr6HPJKO3D4DN1MdYHvGMJFOQFzdpyJO68YcB2uYc1t\n" + "mwogzV6Hk5r45iFZBERcEA/mcx/XrCO8IpWV3iMBZ4EiGQQfzJfYKR0/JrOB58ruItBYZPyIn6Iw\n" + "Z8zC6XIJgG4HduuYAf+MDqXBsbC9OxlEOG3meKFyEcVmBvsyH3RE3rmiPq60UPECgYEA+Aq7Dp60\n" + "+3Jo92zOjw+EgPuqAtGTSHReY3ti6lfKcdIksEPCGTRFNKGZgq0CwrQTajDbfZdkNYuOgQ04f8+7\n" + "OP3NWdQ4JpbZ+g8oSNQMx7uQzqDipq4TeQJAjpwwNk3EFPYMBB2g5Gn7F9lfeKBpFXmeqfvptw7U\n" + "kWrEp5Dx1PMCgYEAmnGpav0pG0E1COg7ZFETjyI+w2e7EjEJJpVpk3U4/svxD7sTgvrTkReRsoX+\n" + "FdVillVsfnW/S6GRmYLEFTC/a2mAWP0mXIfHZhEgoJ9jjDRWiVTa6LSYX567x8Hq+3ThZf6O6WUy\n" + "pY0hfOquPgWW2ptzo2JSWio/3zcHw4NK1ukCgYBLV98YAsdQtaECvy9DL2B9WXR75LMLSCW/rCQQ\n" + "sNgSmNWCISLdSw5WfVvG4My83bwj/nE9hfXvedOwiZaG5E+ncRimV5syxZGyrlX7QUYciXHkAeS2\n" + "4puRn0iCyRiv9hFAmLhvq5xKpZKa3PFuD7O7zTSPx7BnZX7WKQtRJur+VwKBgHEP7k+1fydFqDaa\n" + "FAiPVfs9vaa9RHS/0wwc60oY0Z2t3Q6ADHuhdcpM78s6TlTbfq3BYYh+WIlcgUNZOISuyCMw+9Wp\n" + "lTC98ZplxXXw2SZllkg5B3y94KJ3iM5mxshIu004epSgEeCiHbbd8qrS2qm0jYY5T0JUlaeqGJPn\n" + "hJ0pAoGAH/D5UbgBkq2BGa8WY7IlzSadTB/hWXzdUBkxMqeUNPBhIo6EQ31keLV1G4LCbkd9lnnp\n" + "8OWwFOp7uo38YTythKGDqv6DYnQsxwkxRtXpFn5A+6Z++F1uk+2hUVqCIKXK7ZSrmReDWy2W396J\n" + "2tTZM0iOHU2kGOGIUfis1DX15NQ=" } }
apache-2.0
6948ab49a2e5666016b90c68bd61e024
41.925466
138
0.6562
2.763295
false
false
false
false
chillcoding-at-the-beach/my-cute-heart
MyCuteHeart/fablibrary/src/main/java/com/chillcoding/fablibrary/GameFab.kt
1
3055
package com.chillcoding.fablibrary import android.content.Context import android.graphics.drawable.Animatable import android.graphics.drawable.Drawable import android.support.annotation.DrawableRes import android.support.design.widget.FloatingActionButton import android.support.v4.content.ContextCompat import android.support.v7.content.res.AppCompatResources import android.util.AttributeSet import android.view.View import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.channels.actor import kotlinx.coroutines.experimental.channels.consumeEach import kotlinx.coroutines.experimental.delay class GameFab : FloatingActionButton { private val maximumAnimationDuration by lazy { context.resources.getInteger(R.integer.play_button_animation_duration).toLong() } private var listener: OnGameFabClickListener? = null private var currentMode: Mode = Mode.PLAYPAUSE set(value) { field = value setImageDrawable(field) } constructor(context: Context, attrs: AttributeSet) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { val typedArray = context.theme.obtainStyledAttributes( attrs, R.styleable.FloatingGameActionButton, 0, 0) try { currentMode = getMode(typedArray.getInteger(R.styleable.FloatingGameActionButton_mode, Mode.PLAYPAUSE.styleableInt)) } finally { typedArray.recycle() } this.setOnClickListener { eventActor.offer(it) listener?.onClick(it) } } private fun getMode(styleableInt: Int): Mode = listOf(Mode.PLAYPAUSE, Mode.PAUSEPLAY).first { it.styleableInt == styleableInt } private val eventActor = actor<View>(UI) { channel.consumeEach { val oppositeMode = currentMode.getOppositeMode() [email protected]() delay(maximumAnimationDuration) currentMode = oppositeMode } } sealed class Mode(val styleableInt: Int, @DrawableRes val drawableRes: Int) { object PLAYPAUSE : Mode(0, R.drawable.play_to_pause_animation) object PAUSEPLAY : Mode(1, R.drawable.pause_to_play_animation) } private val opposites = mapOf( Mode.PLAYPAUSE to Mode.PAUSEPLAY, Mode.PAUSEPLAY to Mode.PLAYPAUSE) private fun Mode.getOppositeMode() = opposites[this]!! fun setOnGameFabClickListener(listener: OnGameFabClickListener) { this.listener = listener } private fun Drawable.startAsAnimatable() = (this as Animatable).start() private fun setImageDrawable(mode: Mode) { val animatedVector = AppCompatResources.getDrawable(context, mode.drawableRes) this.setImageDrawable(animatedVector) } fun playAnimation(view: View) { eventActor.offer(view) } interface OnGameFabClickListener { fun onClick(view: View) } }
gpl-3.0
e3d8344c997b1501ef8864f2c029b912
32.582418
132
0.7018
4.593985
false
false
false
false
proxer/ProxerAndroid
src/main/kotlin/me/proxer/app/settings/status/ServerStatusFragment.kt
1
2747
package me.proxer.app.settings.status import android.os.Bundle import android.view.View import android.widget.TextView import androidx.core.os.bundleOf import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial import com.mikepenz.iconics.utils.colorRes import com.mikepenz.iconics.utils.paddingDp import com.mikepenz.iconics.utils.sizeDp import kotterknife.bindView import me.proxer.app.R import me.proxer.app.base.BaseContentFragment import me.proxer.app.util.DeviceUtils import me.proxer.app.util.extension.enableFastScroll import me.proxer.app.util.extension.unsafeLazy import org.koin.androidx.viewmodel.ext.android.viewModel /** * @author Ruben Gees */ class ServerStatusFragment : BaseContentFragment<List<ServerStatus>>(R.layout.fragment_server_status) { companion object { fun newInstance() = ServerStatusFragment().apply { arguments = bundleOf() } } override val isSwipeToRefreshEnabled = true override val viewModel by viewModel<ServerStatusViewModel>() private val layoutManger by unsafeLazy { GridLayoutManager(requireContext(), DeviceUtils.calculateSpanAmount(requireActivity())) } private val adapter = ServerStatusAdapter() private val overallStatus: TextView by bindView(R.id.overallStatus) private val recyclerView: RecyclerView by bindView(R.id.recyclerView) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recyclerView.setHasFixedSize(true) recyclerView.enableFastScroll() recyclerView.layoutManager = layoutManger recyclerView.adapter = adapter } override fun showData(data: List<ServerStatus>) { super.showData(data) val allServersOnline = data.all { it.online } val overallStatusText = when (allServersOnline) { true -> getString(R.string.fragment_server_status_overall_online) false -> getString(R.string.fragment_server_status_overall_offline) } val overallStatusIcon = IconicsDrawable(requireContext()).apply { icon = if (allServersOnline) CommunityMaterial.Icon.cmd_earth else CommunityMaterial.Icon.cmd_earth_off colorRes = if (allServersOnline) R.color.green_500 else R.color.red_500 paddingDp = 12 sizeDp = 48 } overallStatus.text = overallStatusText overallStatus.setCompoundDrawablesWithIntrinsicBounds(overallStatusIcon, null, null, null) adapter.swapDataAndNotifyWithDiffing(data) } }
gpl-3.0
ac7dbff0cddd295c9d238c91ff271b1a
34.675325
115
0.744448
4.752595
false
false
false
false
jitsi/jibri
src/test/kotlin/org/jitsi/jibri/util/XmppUtilsTest.kt
1
3662
/* * Copyright @ 2018 Atlassian Pty Ltd * * 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.jitsi.jibri.util import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.shouldBe import org.jitsi.jibri.CallUrlInfo import org.jxmpp.jid.impl.JidCreate class XmppUtilsTest : ShouldSpec() { private val baseDomain = "brian.jitsi.net" private val baseUrl = "http://brian.jitsi.net" init { context("getCallUrlInfoFromJid") { context("a basic room jid with no baseUrl set") { val expected = CallUrlInfo("https://$baseDomain", "roomName") val jid = JidCreate.entityBareFrom("${expected.callName}@$baseDomain") should("convert to a call url correctly") { getCallUrlInfoFromJid(jid, "", baseDomain, null) shouldBe expected } } context("a basic room jid with the baseUrl set") { val expected = CallUrlInfo(baseUrl, "roomName") val jid = JidCreate.entityBareFrom("${expected.callName}@$baseDomain") should("convert to a call url correctly") { getCallUrlInfoFromJid(jid, "", baseDomain, baseUrl) shouldBe expected } } context("a basic room jid with empty baseUrl") { val expected = CallUrlInfo("https://$baseDomain", "roomName") val jid = JidCreate.entityBareFrom("${expected.callName}@$baseDomain") should("convert to a call url correctly") { getCallUrlInfoFromJid(jid, "", baseDomain, "") shouldBe expected } } context("a roomjid with a subdomain that should be stripped") { val expected = CallUrlInfo("https://$baseDomain", "roomName") val jid = JidCreate.entityBareFrom("${expected.callName}@mucdomain.$baseDomain") should("convert to a call url correctly") { getCallUrlInfoFromJid(jid, "mucdomain.", baseDomain, "") shouldBe expected } } context("a roomjid with a call subdomain") { val expected = CallUrlInfo("https://$baseDomain/subdomain", "roomName") val jid = JidCreate.entityBareFrom("${expected.callName}@mucdomain.subdomain.$baseDomain") getCallUrlInfoFromJid(jid, "mucdomain.", baseDomain, "") shouldBe expected } context("a basic muc room jid, domain contains part to be stripped") { // domain contains 'conference' val conferenceBaseDomain = "conference.$baseDomain" val expected = CallUrlInfo("https://$conferenceBaseDomain", "roomName") val jid = JidCreate.entityBareFrom("${expected.callName}@conference.$conferenceBaseDomain") should("convert to a call url correctly") { // we want to strip the first conference from the jid getCallUrlInfoFromJid(jid, "conference", conferenceBaseDomain, "") shouldBe expected } } } } }
apache-2.0
16e1848fc52e3818d6dd5e571b2f6190
47.184211
107
0.611961
4.682864
false
false
false
false
LorittaBot/Loritta
common/src/commonMain/kotlin/net/perfectdreams/loritta/common/utils/LorittaColors.kt
1
331
package net.perfectdreams.loritta.common.utils object LorittaColors { val LorittaAqua = Color(26, 160, 254) val LorittaRed = Color(255, 96, 71) val DiscordBlurple = Color(88, 101, 242) val DiscordOldBlurple = Color(110, 133, 211) val CorreiosYellow = Color(253, 220, 1) val RobloxRed = Color(226, 34, 26) }
agpl-3.0
cad8044b0696cc214a5898e1ccb4ee65
32.2
48
0.691843
3.277228
false
false
false
false
owntracks/android
project/app/src/main/java/org/owntracks/android/location/geofencing/Geofence.kt
1
644
package org.owntracks.android.location.geofencing data class Geofence( val requestId: String? = null, val transitionTypes: Int? = null, val notificationResponsiveness: Int? = null, val circularLatitude: Double? = null, val circularLongitude: Double? = null, val circularRadius: Float? = null, val expirationDuration: Long? = null, val loiteringDelay: Int? = null, ) { companion object { const val GEOFENCE_TRANSITION_ENTER: Int = 1 const val GEOFENCE_TRANSITION_EXIT: Int = 2 const val GEOFENCE_TRANSITION_DWELL: Int = 4 const val NEVER_EXPIRE: Long = Long.MAX_VALUE } }
epl-1.0
61061a88847f14a858b3108ec3bea839
32.894737
53
0.677019
3.879518
false
false
false
false
Lennoard/HEBF
app/src/main/java/com/androidvip/hebf/ui/main/tune/cpu/CpuTunableAdapter.kt
1
2824
package com.androidvip.hebf.ui.main.tune.cpu import android.app.Activity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.Toast import androidx.recyclerview.widget.RecyclerView import com.androidvip.hebf.R import com.androidvip.hebf.utils.* import java.util.* class CpuTunableAdapter(private val activity: Activity, private val mDataSet: ArrayList<CpuManager.GovernorTunable>?) : RecyclerView.Adapter<CpuTunableAdapter.ViewHolder>() { class ViewHolder(v: View) : RecyclerView.ViewHolder(v) { var name: TextView = v.findViewById(R.id.paramNameLarge) var value: TextView = v.findViewById(R.id.cpu_tunable_value) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val v = LayoutInflater.from(activity).inflate(R.layout.list_item_generic_param_large, parent, false) return ViewHolder(v) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val (name, value, path) = mDataSet!![position] holder.name.text = name holder.value.text = value holder.itemView.setOnClickListener { if (value.isNullOrEmpty() || path.isNullOrEmpty() || value.contains("error")) Toast.makeText(activity, R.string.unsafe_operation, Toast.LENGTH_SHORT).show() else { EditDialog(activity).buildApplying { title = name!! inputText = value inputHint = value guessInputType = true onConfirmListener = object : EditDialog.OnConfirmListener { override fun onOkButtonClicked(newData: String) { if (newData.isEmpty()) Utils.showEmptyInputFieldSnackbar(holder.name) else { RootUtils.executeAsync("echo '${newData.trim()}' > $path") holder.value.text = newData.trim() val achievementsSet = UserPrefs(activity).getStringSet(K.PREF.ACHIEVEMENT_SET, HashSet()) if (!achievementsSet.contains("tunable")) { Utils.addAchievement(activity.applicationContext, "tunable") Toast.makeText(activity, activity.getString(R.string.achievement_unlocked, activity.getString(R.string.achievement_tunable)), Toast.LENGTH_LONG).show() } } } } }.show() } } } override fun getItemCount(): Int { return mDataSet?.size ?: 0 } }
apache-2.0
093c11d913c7b24d6eb4faa149a8cc77
41.787879
187
0.586756
4.989399
false
false
false
false
MeilCli/KLinq
src/main/kotlin/net/meilcli/klinq/Enumerable.kt
1
2854
package net.meilcli.klinq open class Enumerable<T> : IEnumerable<T> { private val enumerator: IEnumerator<T> constructor(func: () -> Iterator<T>) { enumerator = object : IEnumerator<T> { private var iterator: Iterator<T> = func() private var _current: T? = null override var current: T get() = _current!! set(value) { _current = value } override fun moveNext(): Boolean { if (iterator.hasNext() == false) return false _current = iterator.next() return true } override fun reset() { iterator = func() } } } constructor(iterable: Iterable<T>) : this({ iterable.iterator() }) { } constructor(enumerator: IEnumerator<T>) { this.enumerator = enumerator; } companion object { fun range(start: Int, count: Int): IEnumerable<Int> { var enumerator = object : IEnumerator<Int> { private var n: Int = 0 override var current: Int = start - 1 override fun moveNext(): Boolean { if (n < count) { n++ current++ return true } return false } override fun reset() { n = 0 current = start - 1 } } return Enumerable<Int>(enumerator) } fun <TResult> repeat(element: TResult, count: Int): IEnumerable<TResult> { var enumerator = object : IEnumerator<TResult> { private var n: Int = 0 override var current: TResult = element override fun moveNext(): Boolean { if (n < count) { n++ return true } return false } override fun reset() { n = 0 } } return Enumerable<TResult>(enumerator) } fun <TResult> empty(): IEnumerable<TResult> { var enumerator = object : IEnumerator<TResult> { override var current: TResult get() = throw UnsupportedOperationException() set(value) { } override fun moveNext(): Boolean { return false } override fun reset() { } } return Enumerable<TResult>(enumerator) } } override fun getEnumerator(): IEnumerator<T> { return enumerator } }
mit
4752e86721473b5f077d84d029b79bf8
26.990196
82
0.433427
5.477927
false
false
false
false
chRyNaN/GuitarChords
core/src/jsMain/kotlin/com/chrynan/chords/util/ChordViewModelUtils.kt
1
1457
package com.chrynan.chords.util import com.chrynan.chords.model.ChordViewModel import com.chrynan.chords.model.StringLabelState import com.chrynan.chords.view.ChordView import com.chrynan.colors.Color @Suppress("unused", "FunctionName") fun ChordViewModel( fitToHeight: Boolean = ChordView.DEFAULT_FIT_TO_HEIGHT, showFretNumbers: Boolean = ChordView.DEFAULT_SHOW_FRET_NUMBERS, showFingerNumbers: Boolean = ChordView.DEFAULT_SHOW_FINGER_NUMBERS, stringLabelState: StringLabelState = ChordView.DEFAULT_STRING_LABEL_STATE, mutedStringText: String = ChordView.DEFAULT_MUTED_TEXT, openStringText: String = ChordView.DEFAULT_OPEN_TEXT, fretColor: Color, fretLabelTextColor: Color, stringColor: Color, stringLabelTextColor: Color, noteColor: Color, noteLabelTextColor: Color ): ChordViewModel = ChordViewModel( fitToHeight = fitToHeight, showFretNumbers = showFretNumbers, showFingerNumbers = showFingerNumbers, stringLabelState = stringLabelState, mutedStringText = mutedStringText, openStringText = openStringText, fretColor = fretColor.colorInt, fretLabelTextColor = fretLabelTextColor.colorInt, stringColor = stringColor.colorInt, stringLabelTextColor = stringLabelTextColor.colorInt, noteColor = noteColor.colorInt, noteLabelTextColor = noteLabelTextColor.colorInt)
apache-2.0
eef33b0eacd135e62415881436bea56f
41.882353
82
0.728895
4.808581
false
false
false
false
ejeinc/Meganekko
library/src/main/java/org/meganekkovr/GeometryComponent.kt
1
4937
package org.meganekkovr import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.view.View /** * This gives geometry to [Entity] for rendering. */ class GeometryComponent : Component() { private val _nativePointer = NativePointer.getInstance(newInstance()) val nativePointer: Long get() { return _nativePointer.get() } private external fun setEntityGeometry(entityPtr: Long, nativePtr: Long) private external fun build(nativePtr: Long, positions: FloatArray, colors: FloatArray, uvs: FloatArray, triangles: IntArray) private external fun buildGlobe(nativePtr: Long) private external fun buildDome(nativePtr: Long, latRads: Float) private external fun buildSpherePatch(nativePtr: Long, fov: Float) private external fun newInstance(): Long override fun onAttach(entity: Entity) { super.onAttach(entity) setEntityGeometry(entity.nativePointer, nativePointer) } /** * Build big sphere with inverted normals. * This is often used for a projecting equirectangular photo or video. */ fun buildGlobe() { buildGlobe(nativePointer) } fun buildDome(latRads: Float) { buildDome(nativePointer, latRads) } /** * Make a square patch on a sphere that can rotate with the viewer so it always covers the screen. * * @param fov */ fun buildSpherePatch(fov: Float) { buildSpherePatch(nativePointer, fov) } fun build(positions: FloatArray, colors: FloatArray, uvs: FloatArray, triangles: IntArray) { require(positions.size % 3 == 0) { "positions element count must be multiple of 3." } require(colors.size % 4 == 0) { "positions element count must be multiple of 4." } require(uvs.size % 2 == 0) { "positions element count must be multiple of 2." } require(triangles.size % 3 == 0) { "triangles element count must be multiple of 3." } val positionSize = positions.size / 3 val colorSize = colors.size / 4 val uvSize = uvs.size / 2 require(positionSize == colorSize) { "position elements are $positionSize but color elements are $colorSize." } require(colorSize == uvSize) { "color elements are $colorSize but uv elements are $uvSize." } build(nativePointer, positions, colors, uvs, triangles) } /** * Build quad plane mesh geometry. * * @param width Plane's width * @param height Plane's height */ fun buildQuad(width: Float, height: Float) { /* * 0 2 * *----* * | / | * | / | * *----* * 1 3 */ val positions = floatArrayOf( width * -0.5f, height * 0.5f, 0.0f, // Left Top width * -0.5f, height * -0.5f, 0.0f, // Left Bottom width * 0.5f, height * 0.5f, 0.0f, // Right Top width * 0.5f, height * -0.5f, 0.0f // Right Bottom ) val colors = floatArrayOf( 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f) val uvs = floatArrayOf( 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f) val triangles = intArrayOf( 0, 1, 2, 1, 3, 2) build(positions, colors, uvs, triangles) } companion object { /** * Build plane geometry from [View]. * * @param view View * @return new instance */ @JvmStatic fun from(view: View): GeometryComponent { view.measure(0, 0) val width = view.measuredWidth val height = view.measuredHeight view.layout(0, 0, width, height) val geometryComponent = GeometryComponent() geometryComponent.buildQuad(width * 0.01f, height * 0.01f) return geometryComponent } /** * Build plane geometry from [Drawable]. * * @param drawable Drawable * @return new instance */ @JvmStatic fun from(drawable: Drawable): GeometryComponent { val geometryComponent = GeometryComponent() geometryComponent.buildQuad(drawable.intrinsicWidth * 0.01f, drawable.intrinsicHeight * 0.01f) return geometryComponent } /** * Build plane geometry from [Bitmap]. * * @param bitmap Bitmap * @return new instance */ @JvmStatic fun from(bitmap: Bitmap): GeometryComponent { val geometryComponent = GeometryComponent() geometryComponent.buildQuad(bitmap.width * 0.01f, bitmap.height * 0.01f) return geometryComponent } } }
apache-2.0
f968045df383f13d0399125cc1a2a08c
28.213018
128
0.570589
4.090307
false
false
false
false
J-rooft/Telesam
app/src/main/java/space/naboo/telesam/model/Sms.kt
1
539
package space.naboo.telesam.model import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey import space.naboo.telesam.model.Sms.Companion.TABLE_NAME @Entity(tableName = TABLE_NAME) data class Sms( @PrimaryKey(autoGenerate = true) var id: Long = 0, @ColumnInfo(name = "from") var from: String = "", @ColumnInfo(name = "message") var message: String = "") { companion object { const val TABLE_NAME = "messages" } }
apache-2.0
ea6384ae2dab3b00b3d9b5154e73b47c
29
65
0.705009
3.641892
false
false
false
false
wireapp/wire-android
storage/src/androidTest/kotlin/com/waz/zclient/storage/userdatabase/history/EditHistoryTableTestHelper.kt
1
1074
package com.waz.zclient.storage.userdatabase.history import android.content.ContentValues import com.waz.zclient.storage.DbSQLiteOpenHelper class EditHistoryTableTestHelper private constructor() { companion object { private const val EDIT_HISTORY_TABLE_NAME = "EditHistory" private const val EDIT_HISTORY_ORIGINAL_ID_COL = "original_id" private const val EDIT_HISTORY_UPDATED_ID_COL = "updated_id" private const val EDIT_HISTORY_TIMESTAMP_COL = "timestamp" fun insertHistory(originalId: String, updatedId: String, timestamp: Int, openHelper: DbSQLiteOpenHelper) { val contentValues = ContentValues().also { it.put(EDIT_HISTORY_ORIGINAL_ID_COL, originalId) it.put(EDIT_HISTORY_UPDATED_ID_COL, updatedId) it.put(EDIT_HISTORY_TIMESTAMP_COL, timestamp) } openHelper.insertWithOnConflict( tableName = EDIT_HISTORY_TABLE_NAME, contentValues = contentValues ) } } }
gpl-3.0
48845d2b4182cc111ae5f9d8f62afc47
37.357143
80
0.646182
4.710526
false
false
false
false
GyrosWorkshop/WukongAndroid
wukong/src/main/java/com/senorsen/wukong/media/AlbumArtCache.kt
1
10500
package com.senorsen.wukong.media /* * Copyright (C) 2014 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. */ import android.content.Context import android.content.SharedPreferences import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.AsyncTask import android.os.Environment import android.os.Environment.isExternalStorageRemovable import android.preference.PreferenceManager import android.util.Base64 import android.util.Log import android.util.LruCache import com.senorsen.wukong.model.Song import com.senorsen.wukong.utils.BitmapHelper import java.io.* import java.io.File.separator import java.lang.ref.WeakReference /** * Implements a basic cache of album arts, with async loading support. */ class AlbumArtCache(private val context: WeakReference<Context>) { private val TAG = javaClass.simpleName private val KEY_PREF_USE_CDN = "pref_useCdn" private var useCdn: Boolean = false private lateinit var mDiskLruCache: DiskLruCache private var mDiskCacheStarting = false private val mDiskCacheLock = Object() private val mMemoryCache: LruCache<String, Array<Bitmap>> private val sharedPref: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.get()) init { val cacheDir = getDiskCacheDir(DISK_CACHE_SUBDIR) initDiskCache(cacheDir) Log.i(TAG, "cacheDir: $cacheDir") val memCacheSize = 10 * 1024 // 10 MiB Log.i(TAG, "memCacheSize: $memCacheSize kb") mMemoryCache = object : LruCache<String, Array<Bitmap>>(memCacheSize) { override fun sizeOf(key: String, bitmaps: Array<Bitmap>): Int { return bitmaps.map { it.byteCount }.reduce { a, b -> a + b } / 1024 } } } private fun pullSettings() { useCdn = sharedPref.getBoolean(KEY_PREF_USE_CDN, useCdn) } // Creates a unique subdirectory of the designated app cache directory. Tries to use external // but if not mounted, falls back on internal storage. fun getDiskCacheDir(uniqueName: String): File { // Check if media is mounted or storage is built-in, if so, try and use external cache dir // otherwise use internal cache dir val cachePath = if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState() || !isExternalStorageRemovable()) context.get()?.externalCacheDir?.path else context.get()?.cacheDir?.path return File(cachePath + separator + uniqueName) } private fun initDiskCache(cacheDir: File) { mDiskLruCache = DiskLruCache.open(cacheDir, 1, 2, MAX_ALBUM_ART_CACHE_SIZE) mDiskCacheStarting = false // Finished initialization } private fun getBitmapFromDiskCache(key: String): Array<Bitmap>? { synchronized(mDiskCacheLock) { // Wait while disk cache is started from background thread while (mDiskCacheStarting) { try { mDiskCacheLock.wait() } catch (e: InterruptedException) { e.printStackTrace() } } Log.i(TAG, "read from disk $key") val snapshot = mDiskLruCache.get(key) ?: return null Log.d(TAG, "disk cache hit $key") return arrayOf(BIG_BITMAP_INDEX, ICON_BITMAP_INDEX).map { val inputStream = snapshot.getInputStream(it) readInputStreamToBitmap(inputStream) }.toTypedArray() } } private fun readInputStreamToBitmap(inputStream: InputStream): Bitmap { val fd = (inputStream as FileInputStream).fd return ImageResizer.decodeSampledBitmapFromDescriptor( fd, Integer.MAX_VALUE, Integer.MAX_VALUE) } fun addBitmapToCache(key: String, bitmaps: Array<Bitmap>) { // Add to memory cache as before addBitmapToMemoryCache(key, bitmaps) // Also add to disk cache val editor = mDiskLruCache.edit(key) val outs = arrayOf(BIG_BITMAP_INDEX, ICON_BITMAP_INDEX).map { val out = editor.newOutputStream(it) writeOutputStreamFromBitmap(bitmaps[it], out) out } editor.commit() mDiskLruCache.flush() outs.forEach { it.close() } Log.d(TAG, "write to disk cache $key") } private fun writeOutputStreamFromBitmap(bitmap: Bitmap, out: OutputStream) { bitmap.compress(Bitmap.CompressFormat.WEBP, 100, out) } private fun getBitmapFromCache(key: String): Array<Bitmap>? { return getBitmapFromMemCache(key) ?: getBitmapFromDiskCache(key) } private fun addBitmapToMemoryCache(key: String, bitmaps: Array<Bitmap>) { Log.d(TAG, "put memory cache $key , prev size: ${mMemoryCache.size()} / ${mMemoryCache.maxSize()}") mMemoryCache.put(key, bitmaps) } private fun getBitmapFromMemCache(key: String): Array<Bitmap>? { Log.d(TAG, "memory cache size: ${mMemoryCache.size()}") return mMemoryCache.get(key) } fun getBigImage(artUrl: String, key: String = artUrl): Bitmap? { return getBitmapFromCache(key)?.get(BIG_BITMAP_INDEX) } fun getBigImage(song: Song): Bitmap? { return getBitmapFromCache(song.songKey)?.get(BIG_BITMAP_INDEX) } fun getIconImage(artUrl: String, key: String = artUrl): Bitmap? { return getBitmapFromCache(key)?.get(ICON_BITMAP_INDEX) } fun fetch(song: Song, listener: FetchListener?) { pullSettings() val key = song.songKey val artUrl = if (useCdn) song.artwork?.fileViaCdn else song.artwork?.file if (artUrl != null) fetch(artUrl, listener, key) } class FetchAsyncTask(private val weakContext: WeakReference<AlbumArtCache>, private val artUrl: String, private val listener: FetchListener?, private val key: String) : AsyncTask<Void, Void, Array<Bitmap>>() { override fun doInBackground(objects: Array<Void>): Array<Bitmap>? { val bitmaps: Array<Bitmap> try { val bitmap = BitmapHelper.fetchAndRescaleBitmap(artUrl, MAX_ART_WIDTH, MAX_ART_HEIGHT) val icon = BitmapHelper.scaleBitmap(bitmap, MAX_ART_WIDTH_ICON, MAX_ART_HEIGHT_ICON) bitmaps = arrayOf<Bitmap>(bitmap, icon) Log.d(AlbumArtCache::class.simpleName, "doInBackground: putting bitmap in cache") weakContext.get()?.addBitmapToCache(key, bitmaps) } catch (e: Exception) { e.printStackTrace() return null } return bitmaps } override fun onPostExecute(bitmaps: Array<Bitmap>?) { if (bitmaps == null) { listener?.onError(artUrl, IllegalArgumentException("got null bitmaps")) } else { listener?.onFetched(artUrl, bitmaps[BIG_BITMAP_INDEX], bitmaps[ICON_BITMAP_INDEX]) } } } fun fetch(artUrl: String, listener: FetchListener?, key: String = artUrl.hashCode().toString()) { // WARNING: for the sake of simplicity, simultaneous multi-workThread fetch requests // are not handled properly: they may cause redundant costly operations, like HTTP // requests and bitmap rescales. For production-level apps, we recommend you use // a proper image loading library, like Glide. val bitmap = getBitmapFromCache(key) if (bitmap != null) { Log.d(TAG, "getOrFetch: album art $key is in cache, using it $artUrl") listener?.onFetched(artUrl, bitmap[BIG_BITMAP_INDEX], bitmap[ICON_BITMAP_INDEX]) return } Log.d(TAG, "getOrFetch: starting asynctask to fetch " + artUrl) FetchAsyncTask(WeakReference(this), artUrl, listener, key).execute() } abstract class FetchListener { private val TAG = javaClass.simpleName abstract fun onFetched(artUrl: String, bigImage: Bitmap, iconImage: Bitmap) fun onError(artUrl: String, e: Exception) { Log.e(TAG, "AlbumArtFetchListener: error while downloading " + artUrl) e.printStackTrace() } } companion object { private val DISK_CACHE_SUBDIR = "music_artwork" private val MAX_ALBUM_ART_CACHE_SIZE: Long = 100 * 1024 * 1024 // 50 MB private val MAX_ART_WIDTH = 1000 // pixels private val MAX_ART_HEIGHT = 1000 // pixels // Resolution reasonable for carrying around as an icon (generally in // MediaDescription.getIconBitmap). This should not be bigger than necessary, because // the MediaDescription object should be lightweight. If you set it too high and try to // serialize the MediaDescription, you may get FAILED BINDER TRANSACTION errors. private val MAX_ART_WIDTH_ICON = 128 // pixels private val MAX_ART_HEIGHT_ICON = 128 // pixels private val BIG_BITMAP_INDEX = 0 private val ICON_BITMAP_INDEX = 1 fun stringToBitMap(encodedString: String): Bitmap? { try { val encodeByte = Base64.decode(encodedString, Base64.DEFAULT) val bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.size) return bitmap } catch (e: Exception) { e.printStackTrace() return null } } fun bitMapToString(bitmap: Bitmap?): String { if (bitmap == null) return "" val baos = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos) val b = baos.toByteArray() val temp = Base64.encodeToString(b, Base64.DEFAULT) return temp } } }
agpl-3.0
309137994400f9e27ae561c9f0816086
38.329588
128
0.636381
4.557292
false
false
false
false
google/horologist
compose-layout/src/main/java/com/google/android/horologist/compose/rotaryinput/RotaryInputAccumulator.kt
1
2508
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.compose.rotaryinput import kotlin.math.abs /** Accumulator to trigger callbacks based on rotary input event. */ internal class RotaryInputAccumulator( private val eventAccumulationThresholdMs: Long = DEFAULT_EVENT_ACCUMULATION_THRESHOLD_MS, private val minValueChangeDistancePx: Float = DEFAULT_MIN_VALUE_CHANGE_DISTANCE_PX, private val rateLimitCoolDownMs: Long = DEFAULT_RATE_LIMIT_COOL_DOWN_MS, private val onValueChange: ((change: Float) -> Unit) ) { private var accumulatedDistance = 0f private var lastAccumulatedEventTimeMs: Long = 0 private var lastUpdateTimeMs: Long = 0 /** * Process a rotary input event. * * @param scrollPixels the amount to scroll in pixels of the event. * @param eventTimeMillis the time in milliseconds at which this even occurred */ public fun onRotaryScroll(scrollPixels: Float, eventTimeMillis: Long) { val timeSinceLastAccumulatedMs = eventTimeMillis - lastAccumulatedEventTimeMs lastAccumulatedEventTimeMs = eventTimeMillis if (timeSinceLastAccumulatedMs > eventAccumulationThresholdMs) { accumulatedDistance = scrollPixels } else { accumulatedDistance += scrollPixels } onEventAccumulated(eventTimeMillis) } private fun onEventAccumulated(eventTimeMs: Long) { if (abs(accumulatedDistance) < minValueChangeDistancePx || eventTimeMs - lastUpdateTimeMs < rateLimitCoolDownMs ) { return } onValueChange(accumulatedDistance) lastUpdateTimeMs = eventTimeMs accumulatedDistance = 0f } companion object { const val DEFAULT_EVENT_ACCUMULATION_THRESHOLD_MS = 200L const val DEFAULT_MIN_VALUE_CHANGE_DISTANCE_PX = 48f const val DEFAULT_RATE_LIMIT_COOL_DOWN_MS = 300L } }
apache-2.0
07d7f07ca627b24a0a881cb2d8a4d5cc
37.584615
93
0.714115
4.518919
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/icons/IconPack.kt
1
2471
package app.lawnchair.icons import android.content.ComponentName import android.content.Context import android.graphics.drawable.Drawable import com.android.launcher3.compat.AlphabeticIndexCompat import kotlinx.coroutines.* import kotlinx.coroutines.flow.Flow import java.util.concurrent.Semaphore abstract class IconPack( protected val context: Context, val packPackageName: String, ) { private var waiter: Semaphore? = Semaphore(0) private lateinit var deferredLoad: Deferred<Unit> abstract val label: String private val alphabeticIndexCompat by lazy { AlphabeticIndexCompat(context) } protected fun startLoad() { deferredLoad = scope.async(Dispatchers.IO) { loadInternal() waiter?.release() waiter = null } } suspend fun load() { return deferredLoad.await() } fun loadBlocking() { waiter?.run { acquireUninterruptibly() release() } } abstract fun getIcon(componentName: ComponentName): IconEntry? abstract fun getCalendar(componentName: ComponentName): IconEntry? abstract fun getClock(entry: IconEntry): ClockMetadata? abstract fun getCalendars(): MutableSet<ComponentName> abstract fun getClocks(): MutableSet<ComponentName> abstract fun getIcon(iconEntry: IconEntry, iconDpi: Int): Drawable? abstract fun getAllIcons(): Flow<List<IconPickerCategory>> @Suppress("BlockingMethodInNonBlockingContext") protected abstract fun loadInternal() protected fun removeDuplicates(items: List<IconPickerItem>): List<IconPickerItem> { var previous = "" val filtered = ArrayList<IconPickerItem>() items.sortedBy { it.drawableName }.forEach { if (it.drawableName != previous) { previous = it.drawableName filtered.add(it) } } return filtered } protected fun categorize(allItems: List<IconPickerItem>): List<IconPickerCategory> { return allItems .groupBy { alphabeticIndexCompat.computeSectionName(it.label) } .map { (sectionName, items) -> IconPickerCategory( title = sectionName, items = items ) } .sortedBy { it.title } } companion object { private val scope = CoroutineScope(Dispatchers.IO) + CoroutineName("IconPack") } }
gpl-3.0
30e7e7bab35c92d34d7b8ce288f0724c
29.134146
88
0.651963
4.981855
false
false
false
false
EyeBody/EyeBody
EyeBody2/app/src/main/java/com/example/android/eyebody/management/BasePageFragment.kt
1
1917
package com.example.android.eyebody.management import android.content.Context import android.net.Uri import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup /** * Created by YOON on 2017-11-11. * 정석대로 해보려고 기본으로 제공하는 Fragment를 생성해보았음. */ open class BasePageFragment : Fragment(){ protected var pageNumber: Int? = null private var mFragmentInteractionListener: OnFragmentInteractionListener? = null fun onButtonPressed(uri: Uri) { if (mFragmentInteractionListener != null) { mFragmentInteractionListener!!.onFragmentInteraction(uri) } } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { throw RuntimeException("fragment must override onCreateView return not null") } override fun onAttach(context: Context?) { super.onAttach(context) if (context is OnFragmentInteractionListener) { mFragmentInteractionListener = context } else { throw RuntimeException(context!!.toString() + " must implement OnFragmentInteractionListener") } } override fun onDetach() { super.onDetach() mFragmentInteractionListener = null } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * * * See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information. */ interface OnFragmentInteractionListener { fun onFragmentInteraction(uri: Uri) } }
mit
380be7272483d8e13ab1a0935a7802d5
31.824561
172
0.712453
4.85974
false
false
false
false
emufog/emufog
src/test/kotlin/emufog/reader/brite/BriteFormatReaderTest.kt
1
5704
/* * MIT License * * Copyright (c) 2020 emufog contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package emufog.reader.brite import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.TestInstance.Lifecycle import org.junit.jupiter.api.assertThrows import java.nio.file.Paths import kotlin.math.abs @TestInstance(Lifecycle.PER_CLASS) internal class BriteFormatReaderTest { private val resourcePath = Paths.get("src", "test", "resources", "brite") private val defaultBaseAddress = "1.2.3.4" @Test fun `empty list of files should fail`() { assertThrows<IllegalArgumentException> { BriteFormatReader.readGraph(emptyList(), defaultBaseAddress) } } @Test fun `multiple files should fail`() { assertThrows<IllegalArgumentException> { BriteFormatReader.readGraph(listOf(Paths.get("file1"), Paths.get("file2")), defaultBaseAddress) } } private inline fun <reified T : Exception> assertExceptionForFile(file: String) { assertThrows<T> { BriteFormatReader.readGraph(listOf(resourcePath.resolve(file)), defaultBaseAddress) } } private fun assertBriteExceptionFor(file: String) = assertExceptionForFile<BriteFormatException>(file) private fun assertStateExceptionFor(file: String) = assertExceptionForFile<IllegalStateException>(file) @Test fun `too few node columns should fail`() { assertBriteExceptionFor("topo_nodes_column_few.brite") } @Test fun `too few edge columns should fail`() { assertBriteExceptionFor("topo_edges_column_few.brite") } @Test fun `wrong format for node id should fail`() { assertBriteExceptionFor("topo_nodes_id_format.brite") } @Test fun `wrong format for node as id should fail`() { assertBriteExceptionFor("topo_nodes_as_id_format.brite") } @Test fun `wrong format for edge id should fail`() { assertBriteExceptionFor("topo_edges_id_format.brite") } @Test fun `wrong format for edge from id should fail`() { assertBriteExceptionFor("topo_edges_from_id_format.brite") } @Test fun `wrong format for edge to id should fail`() { assertBriteExceptionFor("topo_edges_to_id_format.brite") } @Test fun `wrong format for latency should fail`() { assertBriteExceptionFor("topo_edges_latency_format.brite") } @Test fun `wrong format for bandwidth should fail`() { assertBriteExceptionFor("topo_edges_bandwidth_format.brite") } @Test fun `missing from node id should fail`() { assertStateExceptionFor("topo_edges_missing_from.brite") } @Test fun `missing to node id should fail`() { assertStateExceptionFor("topo_edges_missing_to.brite") } @Test fun `read a sample topology in`() { val file = resourcePath.resolve("topo.brite") val graph = BriteFormatReader.readGraph(listOf(file), defaultBaseAddress) assertEquals(20, graph.edgeNodes.size) assertEquals(0, graph.backboneNodes.size) assertEquals(0, graph.hostDevices.size) assertEquals(37, graph.edges.size) // test sample node val node11 = graph.getEdgeNode(11) requireNotNull(node11) assertEquals(11, node11.id) assertEquals(-1, node11.system.id) // test sample edge val edge23 = graph.edges.firstOrNull { it.id == 23 } requireNotNull(edge23) assertEquals(13, edge23.source.id) assertEquals(2, edge23.destination.id) assertTrue(floatEquals(0.8399260491500409F, edge23.latency)) assertTrue(floatEquals(10F, edge23.bandwidth)) } @Test fun `separate autonomous systems should contain their resp nodes`() { val file = resourcePath.resolve("topo2.brite") val graph = BriteFormatReader.readGraph(listOf(file), defaultBaseAddress) assertEquals(500, graph.edgeNodes.size) assertEquals(0, graph.backboneNodes.size) assertEquals(0, graph.hostDevices.size) assertEquals(1000, graph.edges.size) val system1 = graph.getAutonomousSystem(-1) requireNotNull(system1) assertEquals(380, system1.edgeNodes.size) val system2 = graph.getAutonomousSystem(42) requireNotNull(system2) assertEquals(120, system2.edgeNodes.size) } private fun floatEquals(x: Float, y: Float): Boolean { return abs(x - y) < 0.00001F } }
mit
e812560c2ab230c2fa411b0b2454b9f7
33.36747
107
0.691971
4.247208
false
true
false
false
vase4kin/TeamCityApp
app/src/main/java/com/github/vase4kin/teamcityapp/runbuild/view/BranchesComponentViewImpl.kt
1
6505
/* * Copyright 2019 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.runbuild.view import android.content.Context import android.view.View import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputMethodManager import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import android.widget.Filter import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import butterknife.BindView import butterknife.ButterKnife import butterknife.Unbinder import com.github.vase4kin.teamcityapp.R import java.util.ArrayList /** * Impl of [BranchesComponentView] */ class BranchesComponentViewImpl(private val activity: AppCompatActivity) : BranchesComponentView { @BindView(R.id.autocomplete_branches) lateinit var branchAutocomplete: AutoCompleteTextView @BindView(R.id.text_no_branches_available) lateinit var noBranchesAvailable: TextView @BindView(R.id.text_no_branches_available_to_filter) lateinit var noBranchesAvailableToFilter: TextView @BindView(R.id.progress_branches_loading) lateinit var branchesLoadingProgress: View lateinit var unbinder: Unbinder /** * {@inheritDoc} */ override val branchName: String get() = branchAutocomplete.text.toString() /** * {@inheritDoc} */ override fun initViews() { unbinder = ButterKnife.bind(this, activity) } /** * {@inheritDoc} */ override fun unbindViews() { unbinder.unbind() } /** * {@inheritDoc} */ override fun hideBranchesLoadingProgress() { branchesLoadingProgress.visibility = View.GONE } /** * {@inheritDoc} */ override fun setupAutoComplete(branches: List<String>) { val adapter = BranchArrayAdapter(activity, android.R.layout.simple_dropdown_item_1line, branches) branchAutocomplete.setAdapter(adapter) branchAutocomplete.setOnItemClickListener { _, _, _, _ -> hideKeyboard() } branchAutocomplete.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { hideKeyboard() } true } } /** * {@inheritDoc} */ override fun setupAutoCompleteForSingleBranch(branches: List<String>) { branchAutocomplete.setAdapter( ArrayAdapter( activity, android.R.layout.simple_dropdown_item_1line, branches ) ) branchAutocomplete.setText(branches[0], false) branchAutocomplete.isEnabled = false } private fun hideKeyboard() { val view = activity.currentFocus if (view != null) { val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view.windowToken, 0) } } /** * {@inheritDoc} */ override fun showNoBranchesAvailable() { noBranchesAvailable.visibility = View.VISIBLE } /** * {@inheritDoc} */ override fun showNoBranchesAvailableToFilter() { noBranchesAvailableToFilter.visibility = View.VISIBLE } /** * {@inheritDoc} */ override fun showBranchesAutoComplete() { branchAutocomplete.visibility = View.VISIBLE } /** * {@inheritDoc} */ override fun setAutocompleteHintForFilter() { branchAutocomplete.setHint(R.string.hint_default_filter_branch) } /** * Branches adapter with custom branch filtering */ private class BranchArrayAdapter /** * Constructor * * @param context The current context. * @param resource The resource ID for a layout file containing a TextView to use when * instantiating views. * @param objects The objects to represent in the ListView. */ internal constructor( context: Context, resource: Int, objects: List<String> ) : ArrayAdapter<String>(context, resource, objects) { /** * Branches to show and filter */ private val branches: List<String> /** * Branch filter */ private var filter: BranchFilter? = null init { this.branches = ArrayList(objects) } /** * {@inheritDoc} */ override fun getFilter(): Filter { val filter = this.filter ?: BranchFilter() this.filter = filter return filter } /** * Branch filter */ private inner class BranchFilter : Filter() { /** * {@inheritDoc} */ override fun performFiltering(constraint: CharSequence?): FilterResults { val results = FilterResults() if (constraint.isNullOrEmpty()) { results.values = branches results.count = branches.size } else { val newValues = ArrayList<String>() for (branch in branches) { if (branch.toLowerCase().contains(constraint.toString().toLowerCase())) { newValues.add(branch) } } results.values = newValues results.count = newValues.size } return results } /** * {@inheritDoc} */ override fun publishResults(constraint: CharSequence?, results: FilterResults) { if (results.count > 0) { clear() addAll(results.values as List<String>) notifyDataSetChanged() } else { notifyDataSetInvalidated() } } } } }
apache-2.0
9fdc7089aee413737bc296942f0e386e
28.170404
99
0.597694
5.118017
false
false
false
false
edvin/tornadofx-idea-plugin
src/main/kotlin/no/tornado/tornadofx/idea/dialog/ExtractStringToResourceDialog.kt
1
1904
package no.tornado.tornadofx.idea.dialog import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogWrapper import com.intellij.psi.PsiFile import com.intellij.ui.components.JBTextField import java.awt.GridBagConstraints import java.awt.GridBagLayout import java.awt.Insets import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel class ExtractStringToResourceDialog( project: Project, defaultKey: String, defaultValue: String, private val resourcePaths: List<PsiFile>, resourcePathStrings: Array<String>, private val okAction: (String, String, PsiFile) -> Unit ) : DialogWrapper(project) { private val resourcePathComboBox = ComboBox(resourcePathStrings).apply { resourcePathStrings.maxByOrNull { it.length }?.let { prototypeDisplayValue = it } } private val keyTextField = JBTextField(defaultKey) private val valueTextField = JBTextField(defaultValue) private val c = GridBagConstraints().apply { fill = GridBagConstraints.HORIZONTAL } init { title = "Extract String resource" init() } override fun createCenterPanel(): JComponent = JPanel(GridBagLayout()).apply { addGrid(0, 0, JLabel("resource:")) addGrid(1, 0, resourcePathComboBox) addGrid(0, 1, JLabel("key")) addGrid(1, 1, keyTextField) addGrid(0, 2, JLabel("value")) addGrid(1, 2, valueTextField) } override fun doOKAction() { okAction(keyTextField.text, valueTextField.text, resourcePaths[resourcePathComboBox.selectedIndex]) super.doOKAction() } private fun JComponent.addGrid(x: Int, y: Int, component: JComponent) { c.gridx = x c.gridy = y c.insets = Insets(1, 5, 1, 5) add(component, c) } }
apache-2.0
f85618d742c0dc1c9c72dbc4a8cc18ce
29.222222
107
0.682773
4.377011
false
false
false
false
androidthings/endtoend-base
companionApp/src/main/java/com/example/androidthings/endtoend/companion/auth/AuthViewModel.kt
1
4328
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.androidthings.endtoend.companion.auth import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import androidx.lifecycle.ViewModel import com.example.androidthings.endtoend.companion.data.GizmoDao import com.example.androidthings.endtoend.companion.util.Event import com.google.firebase.auth.UserInfo class AuthViewModel( private val authProvider: AuthProvider, private val gizmoDao: GizmoDao ) : ViewModel(), AuthProvider by authProvider { // We don't want clients to be able to set what is stored in our MutableLiveData, so we expose // it as a regular LiveData instead. private val _authStateModelLiveData = MutableLiveData<Event<AuthStateModel>>() val authStateModelLiveData: LiveData<Event<AuthStateModel>> get() = _authStateModelLiveData private val _authUiModelLiveData = MutableLiveData<AuthUiModel>() val authUiModelLiveData: LiveData<AuthUiModel> get() = _authUiModelLiveData private var userInfo: UserInfo? = null private var authUiModel = AuthUiModel(true, false, null) // Initializing private val userObserver = Observer<UserInfo?> { user -> resolveAuthStateModel(user) setAuthUiModel(authUiModel.copy(initializing = false, user = user)) gizmoDao.setUser(user?.uid) } init { // Show initializing state setAuthUiModel(authUiModel) // Watch for changes to signed in user userLiveData.observeForever(userObserver) } override fun onCleared() { super.onCleared() userLiveData.removeObserver(userObserver) } private fun setAuthUiModel(model: AuthUiModel) { authUiModel = model _authUiModelLiveData.value = authUiModel } // Compare new UserInfo with the previous the determine if (and what kind of) change occurred. private fun resolveAuthStateModel(newInfo: UserInfo?) { val oldUid = userInfo?.uid val newUid = newInfo?.uid userInfo = newInfo if (oldUid != newUid) { val stateChange = when { oldUid == null -> AuthStateChange.SIGNED_IN newUid == null -> AuthStateChange.SIGNED_OUT else -> AuthStateChange.USER_CHANGED } _authStateModelLiveData.value = Event(AuthStateModel(stateChange, newInfo)) } } /** Initiates sign in action with the AuthProvider. */ override fun performSignIn() { // TODO maybe skip if we're initializing or already have a user setAuthUiModel(authUiModel.copy(authInProgress = true)) authProvider.performSignIn() } /** Initiates sign out action with the AuthProvider. */ override fun performSignOut() { setAuthUiModel(authUiModel.copy(authInProgress = true)) authProvider.performSignOut() } /** To be called by the AuthProvider with the result of an auth action. */ fun onAuthResult(result: AuthActionResult) { setAuthUiModel(authUiModel.copy(authInProgress = false)) // TODO maybe show a snackbar if result is FAIL } enum class AuthActionResult { SUCCESS, FAIL, CANCEL } /** Model describing the current authentication state and the change that resulted in it. */ data class AuthStateModel( val authStateChange: AuthStateChange, val user: UserInfo? ) enum class AuthStateChange { SIGNED_IN, SIGNED_OUT, USER_CHANGED } /** Model containing data for showing a UI around authentication state and actions. */ data class AuthUiModel( val initializing: Boolean, val authInProgress: Boolean, val user: UserInfo? ) }
apache-2.0
31216426a457b8e079d28f6e50d3716b
34.186992
98
0.694085
4.724891
false
false
false
false
tkiapril/Weisseliste
src/main/kotlin/kotlin/sql/InsertQuery.kt
1
2206
package kotlin.sql import java.util.* /** * isIgnore is supported for mysql only */ class InsertQuery(val table: Table, val isIgnore: Boolean = false, val isReplace: Boolean = false) { val values = LinkedHashMap<Column<*>, Any?>() var generatedKey: Int? = null operator fun <T> set(column: Column<T>, value: T) { if (values containsKey column) { error("$column is already initialized") } values.put(column, column.columnType.valueToDB(value)) } infix operator fun get(column: Column<Int>): Int { return generatedKey ?: error("No key generated") } /* fun get(column: Column<EntityID>): EntityID { return EntityID(generatedKey ?: error("No key generated"), null) } */ fun execute(session: Session): Int { val builder = QueryBuilder(true) val ignore = if (isIgnore && Session.get().vendor == DatabaseVendor.MySql) " IGNORE " else "" val insert = if (isReplace && Session.get().vendor == DatabaseVendor.MySql) "REPLACE" else "INSERT" var sql = StringBuilder("$insert ${ignore}INTO ${session.identity(table)}") sql.append(" (") sql.append((values map { session.identity(it.key) }).joinToString(", ")) sql.append(") ") sql.append("VALUES (") sql.append((values map { builder.registerArgument(it.value, it.key.columnType) }).joinToString(", ")) sql.append(") ") if (isReplace && Session.get().vendor == DatabaseVendor.H2 && Session.get().vendorCompatibleWith() == DatabaseVendor.MySql) { sql.append("ON DUPLICATE KEY UPDATE ") sql.append(values.map { "${session.identity(it.key)}=${it.key.columnType.valueToString(it.value)}"}.joinToString(", ")) } try { val autoincs: List<String> = table.columns.filter { it.columnType.autoinc } map {session.identity(it)} return builder.executeUpdate(session, sql.toString(), autoincs) { rs -> if (rs.next()) { generatedKey = rs.getInt(1) } } } catch (e: Exception) { println("BAD SQL: $sql") throw e } } }
agpl-3.0
e702dd1b57eba266d9b38120100af90f
34.015873
133
0.589302
4.154426
false
false
false
false
FarbodSalamat-Zadeh/TimetableApp
app/src/main/java/co/timetableapp/data/handler/ClassTimeHandler.kt
1
5393
/* * Copyright 2017 Farbod Salamat-Zadeh * * 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 co.timetableapp.data.handler import android.app.Activity import android.app.Application import android.content.ContentValues import android.content.Context import android.database.Cursor import co.timetableapp.TimetableApplication import co.timetableapp.data.query.Filters import co.timetableapp.data.query.Query import co.timetableapp.data.schema.ClassTimesSchema import co.timetableapp.model.ClassTime import co.timetableapp.receiver.AlarmReceiver import co.timetableapp.util.DateUtils import co.timetableapp.util.PrefUtils import org.threeten.bp.LocalDate import org.threeten.bp.LocalDateTime import org.threeten.bp.LocalTime import org.threeten.bp.temporal.TemporalAdjusters import java.util.* class ClassTimeHandler(context: Context) : TimetableItemHandler<ClassTime>(context) { override val tableName = ClassTimesSchema.TABLE_NAME override val itemIdCol = ClassTimesSchema._ID override val timetableIdCol = ClassTimesSchema.COL_TIMETABLE_ID override fun createFromCursor(cursor: Cursor) = ClassTime.from(cursor) override fun createFromId(id: Int) = ClassTime.create(context, id) override fun propertiesAsContentValues(item: ClassTime): ContentValues { val values = ContentValues() with(values) { put(ClassTimesSchema._ID, item.id) put(ClassTimesSchema.COL_TIMETABLE_ID, item.timetableId) put(ClassTimesSchema.COL_CLASS_DETAIL_ID, item.classDetailId) put(ClassTimesSchema.COL_DAY, item.day.value) put(ClassTimesSchema.COL_WEEK_NUMBER, item.weekNumber) put(ClassTimesSchema.COL_START_TIME_HRS, item.startTime.hour) put(ClassTimesSchema.COL_START_TIME_MINS, item.startTime.minute) put(ClassTimesSchema.COL_END_TIME_HRS, item.endTime.hour) put(ClassTimesSchema.COL_END_TIME_MINS, item.endTime.minute) } return values } override fun deleteItem(itemId: Int) { super.deleteItem(itemId) AlarmReceiver().cancelAlarm(context, AlarmReceiver.Type.CLASS, itemId) } companion object { private const val WEEK_AS_MILLISECONDS = 604800000L @JvmStatic fun addAlarmsForClassTime(activity: Activity, classTime: ClassTime) = addAlarmsForClassTime(activity, activity.application, classTime) @JvmStatic fun addAlarmsForClassTime(context: Context, application: Application, classTime: ClassTime) { // Don't add an alarm if the user has disabled them if (!PrefUtils.getClassNotificationsEnabled(context)) { return } // First, try to find a suitable start date for the alarms var possibleDate = if (classTime.day != LocalDate.now().dayOfWeek || classTime.startTime.minusMinutes(5).isBefore(LocalTime.now())) { // Class is on a different day of the week OR the 5 minute start notice has passed val adjuster = TemporalAdjusters.next(classTime.day) LocalDate.now().with(adjuster) } else { // Class is on the same day of the week (AND it has not yet begun) LocalDate.now() } while (DateUtils.findWeekNumber(application, possibleDate) != classTime.weekNumber) { // Find a week with the correct week number possibleDate = possibleDate.plusWeeks(1) } // Make a LocalDateTime using the calculated start date and ClassTime val minsBefore = PrefUtils.getClassNotificationTime(context).toLong() val startDateTime = LocalDateTime.of(possibleDate, classTime.startTime.minusMinutes(minsBefore)) // remind X mins before start // Find the repeat interval in milliseconds (for the alarm to repeat) val timetable = (application as TimetableApplication).currentTimetable!! val repeatInterval = timetable.weekRotations * WEEK_AS_MILLISECONDS // Set repeating alarm AlarmReceiver().setRepeatingAlarm(context, AlarmReceiver.Type.CLASS, DateUtils.asCalendar(startDateTime), classTime.id, repeatInterval) } @JvmStatic fun getClassTimesForDetail(context: Context, classDetailId: Int): ArrayList<ClassTime> { val classTimesQuery = Query.Builder() .addFilter(Filters.equal( ClassTimesSchema.COL_CLASS_DETAIL_ID, classDetailId.toString())) .build() return ClassTimeHandler(context).getAllItems(classTimesQuery) } } }
apache-2.0
87dd0a17c2bbaa65ba31bb295391225a
38.654412
98
0.670128
4.681424
false
false
false
false
rock3r/detekt
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/empty/EmptyClassBlockSpec.kt
2
2127
package io.gitlab.arturbosch.detekt.rules.empty import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.test.assertThat import io.gitlab.arturbosch.detekt.test.compileAndLint import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class EmptyClassBlockSpec : Spek({ val subject by memoized { EmptyClassBlock(Config.empty) } describe("EmptyClassBlock rule") { it("reports the empty class body") { val code = "class SomeClass {}" assertThat(subject.compileAndLint(code)).hasSize(1) } it("does not report class with comments in the body") { val code = """ class SomeClass { // Some comment to explain what this class is supposed to do } """ assertThat(subject.compileAndLint(code)).isEmpty() } it("does not report class with multiline comments in the body") { val code = """ class SomeClass { /* Some comment to explain what this class is supposed to do */ } """ assertThat(subject.compileAndLint(code)).isEmpty() } it("reports the empty nested class body") { val code = """ class SomeClass { class EmptyClass {} } """ assertThat(subject.compileAndLint(code)).hasSize(1) } it("reports the empty object body") { val code = "object SomeObject {}" val findings = subject.compileAndLint(code) assertThat(findings).hasSize(1) assertThat(findings).hasTextLocations(18 to 20) } it("does not report the object if it is of an anonymous class") { val code = """ open class Open fun f() { object : Open() {} } """ assertThat(subject.compileAndLint(code)).isEmpty() } } })
apache-2.0
53b0e9efb69bdb870de7f64976c35d81
30.746269
80
0.538317
5.226044
false
false
false
false
tipsy/javalin
javalin/src/main/java/io/javalin/http/HttpResponseExceptionMapper.kt
1
2708
/* * Javalin - https://javalin.io * Copyright 2017 David Åse * Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE */ package io.javalin.http import io.javalin.core.util.Header import io.javalin.http.util.JsonEscapeUtil import java.util.* import java.util.concurrent.CompletionException object HttpResponseExceptionMapper { fun canHandle(t: Throwable) = HttpResponseException::class.java.isAssignableFrom(t::class.java) // is HttpResponseException or subclass fun handle(exception: Exception, ctx: Context) { val e = unwrap(exception) if (ctx.header(Header.ACCEPT)?.contains(ContentType.JSON) == true || ctx.res.contentType == ContentType.JSON) { ctx.status(e.status).result("""{ | "title": "${e.message?.jsonEscape()}", | "status": ${e.status}, | "type": "${getTypeUrl(e).lowercase(Locale.ROOT)}", | "details": {${e.details.map { """"${it.key}":"${it.value.jsonEscape()}"""" }.joinToString(",")}} |}""".trimMargin() ).contentType(ContentType.APPLICATION_JSON) } else { val result = if (e.details.isEmpty()) "${e.message}" else """ |${e.message} |${ e.details.map { """ |${it.key}: |${it.value} |""" }.joinToString("") }""".trimMargin() ctx.status(e.status).result(result) } } private const val docsUrl = "https://javalin.io/documentation#" private fun classUrl(e: HttpResponseException) = docsUrl + e.javaClass.simpleName private fun unwrap(e: Exception) = (if (e is CompletionException) e.cause else e) as HttpResponseException // this could be removed by introducing a "DefaultResponse", but I would // rather keep this ugly snippet than introduced another abstraction layer private fun getTypeUrl(e: HttpResponseException) = when (e) { is RedirectResponse -> classUrl(e) is BadRequestResponse -> classUrl(e) is UnauthorizedResponse -> classUrl(e) is ForbiddenResponse -> classUrl(e) is NotFoundResponse -> classUrl(e) is MethodNotAllowedResponse -> classUrl(e) is ConflictResponse -> classUrl(e) is GoneResponse -> classUrl(e) is InternalServerErrorResponse -> classUrl(e) is ServiceUnavailableResponse -> classUrl(e) is BadGatewayResponse -> classUrl(e) is GatewayTimeoutResponse -> classUrl(e) else -> docsUrl + "error-responses" } private fun String.jsonEscape() = JsonEscapeUtil.escape(this) }
apache-2.0
e864645c4c5ae54b4f8055b30736978c
39.402985
139
0.609161
4.359098
false
false
false
false
NaikSoftware/EVGen
src/rest/Google.kt
1
1961
package rest import model.Location import model.LocationDetails import java.util.* /** * Created by naik on 20.02.16. */ class Google(val myLatitude: Float, val myLongitude: Float, val radius: Int) { val googleClient = GoogleClient() val locationTypes = "bar,cafe,library,hospital,bank,casino,church,electrician,hair_care,hardware_store,police,school,university" val random = Random() fun getRandomLocationDeatils() : LocationDetails? { val location = getRandomLocation() ?: return null val response = googleClient.mapsRepository.getPlaceDetails( location.placeId, Main.GOOGLE_API_KEY).execute() if (response.isSuccessful) { val googleResponse = response.body() println(response.raw().message()) if (googleResponse.status.compareTo("OK", true) == 0) { return googleResponse.result } else { println("Get google place error: ${googleResponse.status}") return null } } else { println("Get google place error: ${response.raw().message()}") return null } } fun getRandomLocation() : Location? { val response = googleClient.mapsRepository.getPlaceNear( "%f,%f".format(Locale.US, myLatitude, myLongitude), radius, locationTypes, "", Main.GOOGLE_API_KEY).execute() if (response.isSuccessful) { val googleResponse = response.body() if (googleResponse.status.compareTo("OK", true) == 0) { val results = googleResponse.results return results[random.nextInt(results.size)] } else { println("Get google place error: ${googleResponse.status}") return null } } else { println("Get google place error: ${response.raw().message()}") return null } } }
apache-2.0
47333e013b4aae7d7a7a6f9b30c61e14
32.827586
132
0.591535
4.528868
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/model/leaderboards/WCProductLeaderboardsMapper.kt
1
3422
package org.wordpress.android.fluxc.model.leaderboards import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.WCProductModel import org.wordpress.android.fluxc.network.rest.wpcom.wc.leaderboards.LeaderboardProductItem import org.wordpress.android.fluxc.network.rest.wpcom.wc.leaderboards.LeaderboardsApiResponse import org.wordpress.android.fluxc.persistence.ProductSqlUtils import org.wordpress.android.fluxc.persistence.ProductSqlUtils.geProductExistsByRemoteId import org.wordpress.android.fluxc.persistence.entity.TopPerformerProductEntity import org.wordpress.android.fluxc.store.WCProductStore import org.wordpress.android.fluxc.store.WCStatsStore.StatsGranularity import javax.inject.Inject class WCProductLeaderboardsMapper @Inject constructor() { suspend fun mapTopPerformerProductsEntity( response: LeaderboardsApiResponse, site: SiteModel, productStore: WCProductStore, granularity: StatsGranularity ): List<TopPerformerProductEntity> = response.products ?.takeIf { it.isNotEmpty() } ?.mapNotNull { it.productId } ?.asProductList(site, productStore) ?.mapNotNull { product -> response.products ?.find { it.productId == product.remoteProductId } ?.let { product.toTopPerformerProductEntity(it, site, granularity) } }.orEmpty() /** * This method fetch and request all Products from the IDs described by the * List<Long>, but it only requests to the site products who doesn't exist * inside the database to avoid unnecessary data traffic. * * Please note that we must request first the local products and second the * remote products, if we invert this order the remotely fetched products will * be inserted inside the database by the [WCProductStore] natural behavior, and * when we fetch the local products after that we will end up unnecessarily duplicating * data, since they will be both fetched remotely and locally. */ private suspend fun List<Long>.asProductList( site: SiteModel, productStore: WCProductStore ): List<WCProductModel> { val locallyFetchedProducts = this .filter { geProductExistsByRemoteId(site, it) } .mapNotNull { ProductSqlUtils.getProductByRemoteId(site, it) } val remotelyFetchedProducts = this .filter { geProductExistsByRemoteId(site, it).not() } .takeIf { it.isNotEmpty() } ?.let { productStore.fetchProductListSynced(site, it) } .orEmpty() return mutableListOf<WCProductModel>().apply { addAll(remotelyFetchedProducts) addAll(locallyFetchedProducts) }.toList() } private fun WCProductModel.toTopPerformerProductEntity( productItem: LeaderboardProductItem, site: SiteModel, granularity: StatsGranularity ) = TopPerformerProductEntity( siteId = site.siteId, granularity = granularity.toString(), productId = remoteProductId, name = name, imageUrl = getFirstImageUrl(), quantity = productItem.quantity?.toIntOrNull() ?: 0, currency = productItem.currency.toString(), total = productItem.total?.toDoubleOrNull() ?: 0.0, millisSinceLastUpdated = System.currentTimeMillis() ) }
gpl-2.0
71599f079a11154efd4e464bb47a7cc5
44.026316
93
0.702805
5.047198
false
false
false
false
android/topeka
quiz/src/main/java/com/google/samples/apps/topeka/widget/quiz/PickerQuizView.kt
1
3192
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.topeka.widget.quiz import android.annotation.SuppressLint import android.content.Context import android.os.Bundle import android.view.View import android.widget.SeekBar import android.widget.TextView import com.google.samples.apps.topeka.quiz.R import com.google.samples.apps.topeka.model.Category import com.google.samples.apps.topeka.model.quiz.PickerQuiz import com.google.samples.apps.topeka.widget.SeekBarListener @SuppressLint("ViewConstructor") class PickerQuizView( context: Context, category: Category, quiz: PickerQuiz ) : AbsQuizView<PickerQuiz>(context, category, quiz) { private val KEY_ANSWER = "ANSWER" private var currentSelection: TextView? = null private var seekBar: SeekBar? = null private var step = 0 private var min = quiz.min private var progress = 0 override fun createQuizContentView(): View { initStep() min = quiz.min val layout = inflate<View>(R.layout.quiz_layout_picker) currentSelection = (layout.findViewById<TextView>(R.id.seekbar_progress)).apply { text = min.toString() } seekBar = (layout.findViewById<SeekBar>(R.id.seekbar)).apply { max = seekBarMax setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener by SeekBarListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { setCurrentSelectionText([email protected] + progress) allowAnswer() } }) } return layout } private fun setCurrentSelectionText(progress: Int) { this.progress = progress / step * step currentSelection?.text = this.progress.toString() } override val isAnswerCorrect get() = quiz.isAnswerCorrect(progress) private fun initStep() { val tmpStep = quiz.step //make sure steps are never 0 step = if (0 == tmpStep) 1 else tmpStep } override var userInput: Bundle get() = Bundle().apply { putInt(KEY_ANSWER, progress) } set(value) { seekBar?.progress = value.getInt(KEY_ANSWER) - min } /** * Calculates the actual max value of the SeekBar */ private val seekBarMax: Int get() { val absMin = Math.abs(quiz.min) val absMax = Math.abs(quiz.max) val realMin = Math.min(absMin, absMax) val realMax = Math.max(absMin, absMax) return realMax - realMin } }
apache-2.0
8614f840187b8559d24364839b99b44c
32.6
100
0.660401
4.372603
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/api/item/inventory/ExtendedCarriedInventory.kt
1
2033
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ @file:Suppress("NOTHING_TO_INLINE") package org.lanternpowered.api.item.inventory import java.util.Optional import kotlin.contracts.contract typealias Carrier = org.spongepowered.api.item.inventory.Carrier typealias SpongeCarriedInventory<C> = org.spongepowered.api.item.inventory.type.CarriedInventory<C> /** * Gets the normal carried inventory as an extended carried inventory. */ inline fun <C : Carrier> SpongeCarriedInventory<C>.fix(): ExtendedSpongeCarriedInventory<C> { contract { returns() implies (this@fix is ExtendedSpongeCarriedInventory) } return this as ExtendedSpongeCarriedInventory } /** * Gets the normal carried inventory as an extended carried inventory. */ @Deprecated(message = "Redundant call.", replaceWith = ReplaceWith("")) inline fun <C : Carrier> ExtendedSpongeCarriedInventory<C>.fix(): ExtendedSpongeCarriedInventory<C> = this /** * Gets the carrier of this inventory. */ inline fun <C : Carrier> SpongeCarriedInventory<C>.carrierOrNull(): C? { contract { returns() implies (this@carrierOrNull is ExtendedSpongeCarriedInventory) } return (this as ExtendedSpongeCarriedInventory).carrierOrNull() } /** * Represents an inventory carried by a carrier of type [C]. */ interface CarriedInventory<C : Any> : ExtendedInventory { /** * Gets the carrier of this inventory. Returns * `null` if there is no carrier. */ fun carrierOrNull(): C? } /** * An extended version of [SpongeCarriedInventory]. */ interface ExtendedSpongeCarriedInventory<C : Carrier> : ExtendedInventory, CarriedInventory<C>, SpongeCarriedInventory<C> { @Deprecated(message = "Prefer to use carrierOrNull()") override fun getCarrier(): Optional<C> }
mit
a083f0bdbfc8eb4956b66ec450b41e28
31.790323
123
0.739793
4.03373
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/api/item/inventory/ExtendedItemStack.kt
1
2644
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ @file:Suppress("NOTHING_TO_INLINE") package org.lanternpowered.api.item.inventory import org.lanternpowered.api.item.inventory.stack.fix typealias ItemStack = org.spongepowered.api.item.inventory.ItemStack /** * Gets an empty [ItemStack]. */ inline fun emptyItemStack(): ExtendedItemStack = ItemStack.empty().fix() /** * An extended version of [ItemStack]. */ interface ExtendedItemStack : ItemStack { /** * Gets whether this item stack is similar to the other one. * * Stacks are similar if all the data matches, excluding * the quantity. * * @param other The other stack to match with * @return Whether the stacks are similar */ infix fun isSimilarTo(other: ItemStack): Boolean /** * Gets whether this item stack is similar to the other one. * * Stacks are similar if all the data matches, excluding * the quantity. * * @param other The other stack to match with * @return Whether the stacks are similar */ infix fun isSimilarTo(other: ItemStackSnapshot): Boolean /** * Gets whether this item stack is similar to the other one. * * Stacks are equal if all the data matches, including * the quantity. * * @param other The other stack to match with * @return Whether the stacks are similar */ infix fun isEqualTo(other: ItemStack): Boolean /** * Gets whether this item stack is similar to the other one. * * Stacks are equal if all the data matches, including * the quantity. * * @param other The other stack to match with * @return Whether the stacks are similar */ infix fun isEqualTo(other: ItemStackSnapshot): Boolean @Deprecated(message = "Prefer to use isEqualTo", replaceWith = ReplaceWith("this.isEqualTo(other)")) override fun equalTo(other: ItemStack): Boolean = this.isEqualTo(other) /** * Creates a *view* of this [ItemStack] as an [ItemStackSnapshot], changes * to the item stack will reflect to the snapshot. * * This should only be used if you know what you're doing, one use case can * be reducing the amount of copies that are being created by conversions. */ @UnsafeInventoryApi fun asSnapshot(): ExtendedItemStackSnapshot }
mit
d0ece8d2718bc0aa63e838e51429f442
29.390805
104
0.670575
4.377483
false
false
false
false
zaviyalov/dialog
backend/src/main/kotlin/com/github/zaviyalov/dialog/controller/DiaryEntryController.kt
1
4127
package com.github.zaviyalov.dialog.controller import com.github.zaviyalov.dialog.common.Paths import com.github.zaviyalov.dialog.exception.UnknownUserException import com.github.zaviyalov.dialog.model.DiaryEntry import com.github.zaviyalov.dialog.service.AppUserManagementService import com.github.zaviyalov.dialog.service.DiaryEntryService import org.springframework.beans.factory.annotation.Autowired import org.springframework.data.domain.Pageable import org.springframework.data.domain.Sort import org.springframework.data.web.PageableDefault import org.springframework.http.ResponseEntity import org.springframework.security.core.Authentication import org.springframework.web.bind.annotation.* @RestController @RequestMapping(Paths.DIARY_ENTRY_CONTROLLER) class DiaryEntryController @Autowired constructor( private val diaryEntryService: DiaryEntryService, userService: AppUserManagementService ) : AbstractController(userService) { @GetMapping("/{id}") @Throws(UnknownUserException::class) fun findById(@PathVariable id: String, auth: Authentication): ResponseEntity<DiaryEntry> { val entry = diaryEntryService.findByIdAndUser(id, getUser(auth)) return entry?.let { ResponseEntity.ok(it) } ?: ResponseEntity.notFound().build() } @GetMapping @Throws(UnknownUserException::class) fun findAll( @PageableDefault(sort = arrayOf("dateTime"), direction = Sort.Direction.DESC) pageable: Pageable?, auth: Authentication ): ResponseEntity<List<DiaryEntry>> { val list = diaryEntryService.findAllByUser(getUser(auth), pageable) return ResponseEntity.ok(list) } @PostMapping @Throws(UnknownUserException::class) fun insert(@RequestBody diaryEntry: DiaryEntry, auth: Authentication): ResponseEntity<DiaryEntry> { val authUser = getUser(auth) if (diaryEntry.user == null || diaryEntry.user == authUser) { diaryEntry.user = authUser val result = diaryEntryService.insert(diaryEntry) return ResponseEntity.ok(result) } return ResponseEntity.notFound().build() } @PutMapping @Throws(UnknownUserException::class) fun update(@RequestBody diaryEntry: DiaryEntry, auth: Authentication): ResponseEntity<DiaryEntry> { diaryEntry.id?.let { val authUser = getUser(auth) val entryUser = diaryEntryService.findByIdAndUser(it, authUser)?.user if (entryUser != null && entryUser == authUser) { diaryEntry.user = entryUser val result = diaryEntryService.save(diaryEntry) return ResponseEntity.ok(result) } else { return ResponseEntity.notFound().build() } } return ResponseEntity.badRequest().build() } @DeleteMapping @Throws(UnknownUserException::class) fun delete(@RequestBody diaryEntry: DiaryEntry, auth: Authentication): ResponseEntity<Void> { diaryEntry.id?.let { val authUser = getUser(auth) val entryUser = diaryEntryService.findByIdAndUser(it, authUser)?.user if (entryUser != null && entryUser == authUser) { diaryEntry.user = entryUser diaryEntryService.delete(diaryEntry) return ResponseEntity.ok().build() } else { return ResponseEntity.notFound().build() } } return ResponseEntity.badRequest().build() } @DeleteMapping("/{id}") @Throws(UnknownUserException::class) fun deleteById(@PathVariable id: String, auth: Authentication): ResponseEntity<Void> { val entry = diaryEntryService.findByIdAndUser(id, getUser(auth)) ?: return ResponseEntity.notFound().build() diaryEntryService.delete(entry) return ResponseEntity.ok().build() } @GetMapping("/pagesCount") fun getPagesCount(@RequestParam pageSize: Int, auth: Authentication): ResponseEntity<Long> { val count = diaryEntryService.getPagesCount(getUser(auth), pageSize) return ResponseEntity.ok(count) } }
bsd-3-clause
a13095d54ea7e5b194f307721916185d
40.686869
116
0.694693
4.530187
false
false
false
false
ursjoss/scipamato
core/core-web/src/main/java/ch/difty/scipamato/core/logic/exporting/RisAdapter.kt
1
8502
@file:Suppress("SpellCheckingInspection") package ch.difty.scipamato.core.logic.exporting import ch.difty.kris.KRis import ch.difty.kris.domain.RisRecord import ch.difty.kris.domain.RisType import ch.difty.scipamato.core.entity.Paper import java.io.Serializable private val defaultSort: List<String> = listOf( "AU", "PY", "TI", "JO", "SP", "EP", "VL", "IS", "ID", "DO", "M1", "M2", "AB", "DB", "L1", "L2" ) private val defaultDistillerSort: List<String> = listOf( "AU", "PY", "TI", "JO", "SP", "EP", "M2", "VL", "IS", "ID", "DO", "M1", "C1", "AB", "DB", "L1", "L2" ) private const val LOCATION_PARTS = 6 /** * The implementation of the [RisAdapterFactory] provides a configured [RisAdapter] able export to * different flavours of RIS files. */ interface RisAdapterFactory { /** * Creates an implementation of a [RisAdapter] depending on the provided `risExporter string`. */ fun createRisAdapter(brand: String, internalUrl: String?, publicUrl: String?): RisAdapter companion object { fun create(risExporterStrategy: RisExporterStrategy) = object : RisAdapterFactory { override fun createRisAdapter(brand: String, internalUrl: String?, publicUrl: String?): RisAdapter = when (risExporterStrategy) { RisExporterStrategy.DEFAULT -> DefaultRisAdapter(brand, internalUrl, publicUrl) RisExporterStrategy.DISTILLERSR -> DistillerSrRisAdapter(brand, internalUrl, publicUrl) } } } } interface RisAdapter : Serializable { fun build(papers: List<Paper>) = build(papers, defaultSort) fun build(papers: List<Paper>, sort: List<String>): String } /** * Adapter working as a kind of bridge between [Paper]s and the JRis world. */ sealed class JRisAdapter( protected val dbName: String, protected val internalUrl: String?, protected val publicUrl: String? ) : RisAdapter { @Suppress("EXPERIMENTAL_API_USAGE") override fun build(papers: List<Paper>, sort: List<String>): String = KRis.buildFromList( risRecords = papers.map(::toRisRecords).toList(), sort = sort ).joinToString(separator = "") @Suppress("DestructuringDeclarationWithTooManyEntries") private fun toRisRecords(p: Paper): RisRecord { val (periodical, volume, issue, startPage, endPage) = p.locationComponents() return newRisRecord(p, startPage, endPage, periodical, volume, issue) } @Suppress("LongParameterList") protected abstract fun newRisRecord( p: Paper, startPage: Int?, endPage: Int?, periodical: String, volume: String?, issue: String? ): RisRecord protected fun Paper.formattedAuthors(): List<String> { val formattedAuthors = authors .removeSuffix(AUTHOR_SUFFIX) .split(AUTHOR_DELIM) .map { it.trim() } .map(::toRisAuthor) .toList() check(formattedAuthors.isNotEmpty()) { throw IllegalStateException("paper must have at least one author") } return formattedAuthors } private fun toRisAuthor(scipamatoAuthor: String): String { val matchResult = authorRegex.matchEntire(scipamatoAuthor) matchResult?.let { val groups = matchResult.groupValues.drop(1).map { it.trim() }.filter { it.isNotEmpty() } val lastNames = groups.first() val firstAndStuff = groups.drop(1).joinToString("$AUTHOR_SUFFIX$AUTHOR_DELIM").plus(AUTHOR_SUFFIX) return "$lastNames,$firstAndStuff" } return "$scipamatoAuthor$AUTHOR_SUFFIX" } private fun Paper.locationComponents(): LocationComponents { val matchResult = locationRegex.matchEntire(location) matchResult?.let { result -> val groups = result.groupValues check(groups.size == LOCATION_PARTS) { throw IllegalStateException("Unable to parse '$location' - should have been LOCATION_PARTS parts") } var i = 1 return LocationComponents( periodical = groups[i++], volume = groups[i++], issue = groups[i++].takeUnless { it.trim().isBlank() }, startPage = groups[i++].run { if (isNotEmpty()) toInt() else null }, endPage = groups[i].run { if (isNotEmpty()) toInt() else null } ) } return LocationComponents(location) } private data class LocationComponents( val periodical: String, val volume: String? = null, val issue: String? = null, val startPage: Int? = null, val endPage: Int? = null ) companion object { private const val AUTHOR_DELIM = "," private const val AUTHOR_SUFFIX = "." private const val RE_W = """\w\u00C0-\u024f""" private const val RW_WW = """[$RE_W-']+""" private val authorRegex = """^((?:$RW_WW ?)+) ([A-Z]+)(?: (Sr))?$""".toRegex() private val locationRegex = """^([^.]+)\. \d+; (\d+(?:-\d+)?)(?: \(([\d-]+)\))?: (\d+)?(?:-(\d+))?(?:\.? ?e\d+)?\.$""".toRegex() } } /** * Default mapping of SciPaMaTo fields to the RIS tag that seem most appropriate. */ class DefaultRisAdapter( dbName: String, internalUrl: String?, publicUrl: String? ) : JRisAdapter(dbName, internalUrl, publicUrl) { override fun newRisRecord( p: Paper, startPage: Int?, endPage: Int?, periodical: String, volume: String?, issue: String? ): RisRecord = RisRecord( type = RisType.JOUR, referenceId = p.pmId?.toString(), title = p.title, authors = p.formattedAuthors().toMutableList(), publicationYear = p.publicationYear?.toString(), startPage = startPage?.toString(), endPage = endPage?.toString(), periodicalNameFullFormatJO = periodical, volumeNumber = volume, issue = issue, abstr = p.originalAbstract, pdfLinks = publicUrl?.run { mutableListOf("${this}paper/number/${p.number}") } ?: mutableListOf(), number = p.number?.toLong(), fullTextLinks = internalUrl?.run { mutableListOf("$this${p.pmId}") } ?: mutableListOf(), miscellaneous2 = p.goals?.takeUnless { it.trim().isBlank() }, doi = p.doi?.takeUnless { it.trim().isBlank() }, databaseName = dbName ) } /** * Mapping of SciPaMaTo-fields to the RIS tags expected to be imported into DistillerSR. Apparently * the folks at Evidence Partners had to adapt the import into their tool to be able to handle * importing from some other exporters: * * * `M2` is mapped to `Start Page` (instead of `SP`) * * `SP` is mapped to `Pages` */ class DistillerSrRisAdapter( dbName: String, internalUrl: String?, publicUrl: String? ) : JRisAdapter(dbName, internalUrl, publicUrl) { override fun build(papers: List<Paper>) = build(papers, defaultDistillerSort) override fun newRisRecord( p: Paper, startPage: Int?, endPage: Int?, periodical: String, volume: String?, issue: String? ): RisRecord = RisRecord( type = RisType.JOUR, referenceId = p.pmId?.toString(), title = p.title, authors = p.formattedAuthors().toMutableList(), publicationYear = p.publicationYear?.toString(), miscellaneous2 = startPage?.toString(), startPage = getPages(startPage, endPage), endPage = endPage?.toString(), periodicalNameFullFormatJO = periodical, volumeNumber = volume, issue = issue, abstr = p.originalAbstract, pdfLinks = publicUrl?.run { mutableListOf("${this}paper/number/${p.number}") } ?: mutableListOf(), number = p.number?.toLong(), fullTextLinks = internalUrl?.run { mutableListOf("$this${p.pmId}") } ?: mutableListOf(), custom1 = p.goals?.takeUnless { it.trim().isBlank() }, doi = p.doi?.takeUnless { it.trim().isBlank() }, databaseName = dbName ) private fun getPages(sp: Int?, ep: Int?) = when { sp == null && ep == null -> null ep == null -> sp.toString() sp == null -> ep.toString() else -> "$sp-$ep" } }
bsd-3-clause
3dcc2f0cdb852cd27408cfc831ac96c2
35.805195
115
0.595977
4.206828
false
false
false
false
debop/debop4k
debop4k-examples/src/test/kotlin/debop4k/examples/operators/DelegateExample.kt
1
6072
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.examples.operators import debop4k.examples.AbstractExampleTest import org.assertj.core.api.Assertions.assertThat import org.jetbrains.exposed.dao.* import org.jetbrains.exposed.sql.Column import org.junit.Test import java.beans.PropertyChangeListener import java.beans.PropertyChangeSupport import kotlin.reflect.KProperty /** * Delegated Properties : 속성 접근 로직을 재사용하기 */ class DelegateExample : AbstractExampleTest() { @Test fun `Lazy Initialization and by backed field`() { val p = Person("debop") assertThat(p.emails).isNotNull() assertThat(p.emails).isNotNull() assertThat(p.emails).isNotNull() } @Test fun `Lazy Initialization and by lazy()`() { val p2 = Person2("debop") assertThat(p2.emails).isNotNull() assertThat(p2.emails).isNotNull() assertThat(p2.emails).isNotNull() } @Test fun `Person 3 - Delegate with PropertyChangeSupport`() { val p = Person3("Debop", 49, 1200) p.addPropertyChangeListener(PropertyChangeListener { event -> log.debug("Property ${event.propertyName} changed from ${event.oldValue} to ${event.newValue}") }) p.age = 50 p.salary = 1500 } @Test fun `Person 4 - Delegate with ObservableProperty`() { val p = Person4("Debop", 49, 1200) p.addPropertyChangeListener(PropertyChangeListener { event -> log.debug("Property with Observable ${event.propertyName} changed from ${event.oldValue} to ${event.newValue}") }) p.age = 50 p.salary = 1500 } @Test fun `Person5 - with Reflect`() { val p = Person5("debop", 55, 5500) p.addPropertyChangeListener(PropertyChangeListener { event -> log.debug("Property with Reflect ${event.propertyName} changed from ${event.oldValue} to ${event.newValue}") }) p.age = 555 p.salary = 323423432 } @Test fun `Store Property Values in a map`() { class Person { private val _attrs = hashMapOf<String, String>() fun setAttribute(name: String, value: String) { _attrs[name] = value } fun setAttribute(map: Map<String, String>) { _attrs.putAll(map) } val name: String get() = _attrs["name"]!! } val p = Person() p.setAttribute(mapOf("name" to "Debop", "company" to "KESTI")) assertThat(p.name).isEqualTo("Debop") } } data class Email(val address: String) open class Person(val name: String) { @Volatile private var _emails: List<Email>? = null val emails: List<Email> get() { if (_emails == null) { _emails = loadEmails(this) } return _emails!! } } fun loadEmails(person: Person): List<Email> { println("Load emails for ${person.name}") return listOf(Email("a"), Email("b")) } class Person2(val name: String) { // lazy delegate val emails: List<Email> by lazy { loadEmails2(this) } } fun loadEmails2(person: Person2): List<Email> { println("Load emails for ${person.name}") return listOf(Email("a"), Email("b")) } open class PropertyChangeAware { protected val changeSupport = PropertyChangeSupport(this) fun addPropertyChangeListener(listener: PropertyChangeListener) { changeSupport.addPropertyChangeListener(listener) } fun removePropertyChangeListener(listener: PropertyChangeListener) { changeSupport.removePropertyChangeListener(listener) } } class Person3(val name: String, age: Int, salary: Int) : PropertyChangeAware() { var age: Int = age set(newValue) { val oldValue = field field = newValue changeSupport.firePropertyChange("age", oldValue, newValue) } var salary: Int = salary set(newValue) { val oldValue = field field = newValue changeSupport.firePropertyChange("salary", oldValue, newValue) } } class ObservableProperty(val propName: String, var propValue: Int, val changeSupport: PropertyChangeSupport) { fun getValue(): Int = propValue fun setValue(newValue: Int) { val oldValue = propValue propValue = newValue changeSupport.firePropertyChange(propName, oldValue, newValue) } } class Person4(val name: String, age: Int, salary: Int) : PropertyChangeAware() { val _age = ObservableProperty("age", age, changeSupport) val _salary = ObservableProperty("salary", salary, changeSupport) var age: Int get() = _age.propValue set(value) { _age.setValue(value) } var salary: Int get() = _salary.propValue set(value) { _salary.setValue(value) } } class ObservableProperty2(var propValue: Int, val changeSupport: PropertyChangeSupport) { operator fun getValue(p: Person5, prop: KProperty<*>): Int = propValue operator fun setValue(p: Person5, prop: KProperty<*>, newValue: Int) { val oldValue = propValue propValue = newValue changeSupport.firePropertyChange(prop.name, oldValue, newValue) } } class Person5(val name: String, age: Int, salary: Int) : PropertyChangeAware() { var age: Int by ObservableProperty2(age, changeSupport) var salary: Int by ObservableProperty2(salary, changeSupport) } class User(id: EntityID<Int>) : Entity<Int>(id) { var name: String by Users.name var age: Int by Users.age } object Users : IdTable<Int>("Users") { override val id: Column<EntityID<Int>> get() = integer("id").entityId() val name: Column<String> = varchar("name", 50).index() val age: Column<Int> = integer("age") }
apache-2.0
677f12f5b1a167aaf2b4f3a515ccf48d
26.371041
117
0.681713
3.976331
false
false
false
false
jeffersonvenancio/BarzingaNow
android/app/src/main/java/com/barzinga/view/ProductsActivity.kt
1
8623
package com.barzinga.view import android.app.Activity import android.app.SearchManager import android.arch.lifecycle.ViewModelProviders import android.content.Context import android.content.Intent import android.databinding.DataBindingUtil import android.graphics.Color import android.graphics.PorterDuff import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.SearchView import android.support.v7.widget.Toolbar import android.view.Menu import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.view.inputmethod.InputMethodManager import android.widget.ImageView import com.barzinga.R import com.barzinga.databinding.ActivityProductsBinding import com.barzinga.model.Item import com.barzinga.model.Product import com.barzinga.model.User import com.barzinga.restClient.parameter.TransactionParameter import com.barzinga.util.ConvertObjectsUtil.Companion.getStringFromObject import com.barzinga.util.loadUrl import com.barzinga.view.adapter.ProductsAdapter import com.barzinga.viewmodel.Constants import com.barzinga.viewmodel.Constants.CHECKOUT_REQUEST import com.barzinga.viewmodel.ProductListViewModel import com.barzinga.viewmodel.UserViewModel import kotlinx.android.synthetic.main.activity_products.* import kotlinx.android.synthetic.main.view_bottom_bar.* import kotlinx.android.synthetic.main.view_user_info.* class ProductsActivity : AppCompatActivity(), ItemsListFragment.OnItemSelectedListener, ProductListViewModel.ProductsListener { private var user: User? = null lateinit var viewModel: ProductListViewModel lateinit var searchView: SearchView lateinit var binding: ActivityProductsBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_products) val mToolbar = findViewById<Toolbar>(R.id.toolbar) mToolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.white)) setSupportActionBar(mToolbar) supportActionBar?.setDisplayShowTitleEnabled(false) viewModel = ViewModelProviders.of(this).get(ProductListViewModel::class.java) viewModel.listProducts(this) getUser() llFinishOrder.setOnClickListener({ openCheckout() }) } override fun onCreateOptionsMenu(menu: Menu):Boolean { menuInflater.inflate(R.menu.product_menus, menu) setSearch(menu) return true } private fun setSearch(menu: Menu) { val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager searchView = menu.findItem(R.id.action_search) .actionView as SearchView searchView.setSearchableInfo(searchManager .getSearchableInfo(componentName)) searchView.maxWidth = 5000 searchView.findViewById<ImageView>(android.support.v7.appcompat.R.id.search_button).setColorFilter(Color.BLACK) searchView.findViewById<ImageView>(android.support.v7.appcompat.R.id.search_close_btn).setColorFilter(Color.BLACK) searchView.findViewById<View>(android.support.v7.appcompat.R.id.search_plate).background.setColorFilter(Color.BLACK, PorterDuff.Mode.MULTIPLY) val searchAutoComplete = searchView.findViewById<SearchView.SearchAutoComplete>(android.support.v7.appcompat.R.id.search_src_text) searchAutoComplete?.setHintTextColor(Color.BLACK) searchAutoComplete?.setTextColor(Color.BLACK) searchAutoComplete?.setHint(R.string.search_product_hint) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { (products_list.adapter as ProductsAdapter).filter.filter(query) return false } override fun onQueryTextChange(query: String): Boolean { (products_list.adapter as ProductsAdapter).filter.filter(query) return false } }) } private fun getUser() { if (intent?.hasExtra(Constants.USER_EXTRA) == true) { user = intent.getSerializableExtra(Constants.USER_EXTRA) as User? mUserPhoto.loadUrl(user?.photoUrl) binding.viewmodel = user?.let { UserViewModel(it) } } } private fun openCheckout() { val products = (products_list.adapter as ProductsAdapter).getChosenProducts() val transactionProducts = ArrayList<Product>() for (product in products) { if((product.quantityOrdered ?: 0) > 0) { product.quantity = product.quantityOrdered transactionProducts.add(product) } } val transactionParameter = TransactionParameter(user, "", transactionProducts) val transactionJson = getStringFromObject(transactionParameter) startActivityForResult(CheckoutActivity.startIntent(this, transactionJson), CHECKOUT_REQUEST) } private fun setupRecyclerView(products: ArrayList<Product>) { val productsAdapter = ProductsAdapter(this, products, this) products_list.apply { adapter = productsAdapter setHasFixedSize(true) val gridLayout = GridLayoutManager(context, 2) layoutManager = gridLayout } products_list.visibility = VISIBLE mLoadingProgress.visibility = GONE determinePaneLayout(setCategories(products)) } override fun onProductsQuantityChanged() { val currentOrderPrice: Double? = (products_list.adapter as ProductsAdapter).getCurrentOrderPrice() if ((currentOrderPrice ?: 0.0) > 0.0) { mOrderPrice.text = String.format("%.2f", currentOrderPrice) mBottomBar.visibility = VISIBLE } else { mBottomBar.visibility = GONE } } private fun setCategories(productsList: List<Product>?): ArrayList<Item> { val products = productsList?.sortedBy { it.category } val categories = ArrayList<Item>() var categoryName = "" for (product in products.orEmpty()) { if (categoryName.isEmpty()) { categoryName = product.category.toString() } if (categoryName != product.category) { categories.add(Item(categoryName, "")) categoryName = product.category.toString() } } categories.add(Item(categoryName, "")) return categories } private fun determinePaneLayout(items: ArrayList<Item>) { val fragmentItem = ItemsListFragment.newInstance(items) val ft = supportFragmentManager.beginTransaction() ft.replace(R.id.fragmentItemsList, fragmentItem) ft.commit() (products_list.adapter as ProductsAdapter).setCategory(items.get(0).title) } override fun onItemSelected(i: Item) { (products_list.adapter as ProductsAdapter).setCategory(i.title) products_list.scrollToPosition(0) invalidateOptionsMenu() hideKeyboard() } fun hideKeyboard() { val imm = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager //Find the currently focused view, so we can grab the correct window token from it. var view = currentFocus //If no view currently has focus, create a new one, just so we can grab a window token from it if (view == null) { view = View(this) } imm.hideSoftInputFromWindow(view.windowToken, 0) } override fun onProductsListGotten(products: ArrayList<Product>) { setupRecyclerView(products) } override fun onProductsListError() { } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == CHECKOUT_REQUEST) { if(resultCode == Activity.RESULT_OK) { finish() } else { mLoadingProgress.visibility = VISIBLE products_list.visibility = GONE mBottomBar.visibility = GONE viewModel.listProducts(this) } } } override fun onBackPressed() { if (!searchView.isIconified) { searchView.isIconified = true return } super.onBackPressed() } }
apache-2.0
9d382731912f93da9e6fefe38747068f
34.632231
150
0.688507
4.958597
false
false
false
false
android/animation-samples
Motion/app/src/main/java/com/example/android/motion/demo/reorder/ReorderActivity.kt
1
4851
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.motion.demo.reorder import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.core.view.ViewCompat import androidx.core.view.WindowCompat import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.example.android.motion.R import com.example.android.motion.ui.EdgeToEdge import com.example.android.motion.widget.SpaceDecoration class ReorderActivity : AppCompatActivity() { private val viewModel: ReorderViewModel by viewModels() private var pickUpElevation: Float = 0f override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.reorder_activity) val toolbar: Toolbar = findViewById(R.id.toolbar) val list: RecyclerView = findViewById(R.id.list) setSupportActionBar(toolbar) WindowCompat.setDecorFitsSystemWindows(window, false) EdgeToEdge.setUpAppBar(findViewById(R.id.app_bar), toolbar) EdgeToEdge.setUpScrollingContent(list) pickUpElevation = resources.getDimensionPixelSize(R.dimen.pick_up_elevation).toFloat() list.addItemDecoration( SpaceDecoration(resources.getDimensionPixelSize(R.dimen.spacing_small)) ) // The ItemTouchHelper handles view drag inside the RecyclerView. val itemTouchHelper = ItemTouchHelper(touchHelperCallback) itemTouchHelper.attachToRecyclerView(list) val adapter = CheeseGridAdapter(onItemLongClick = { holder -> // Start dragging the item when it is long-pressed. itemTouchHelper.startDrag(holder) }) list.adapter = adapter viewModel.cheeses.observe(this) { cheeses -> // Every time the items are reordered on the screen, we receive a new list here. // The adapter takes a diff between the old and the new lists, and animates any moving // items by ItemAnimator. adapter.submitList(cheeses) } } private val touchHelperCallback = object : ItemTouchHelper.Callback() { override fun getMovementFlags( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder ): Int { return makeMovementFlags( // We allow items to be dragged in any direction. ItemTouchHelper.UP or ItemTouchHelper.DOWN or ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT, // But not swiped away. 0 ) } override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { // Reorder the items in the ViewModel. The ViewModel will then notify the UI through the // LiveData. viewModel.move(viewHolder.bindingAdapterPosition, target.bindingAdapterPosition) return true } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { // Do nothing } override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) { super.onSelectedChanged(viewHolder, actionState) val view = viewHolder?.itemView ?: return when (actionState) { ItemTouchHelper.ACTION_STATE_DRAG -> { ViewCompat.animate(view).setDuration(150L).translationZ(pickUpElevation) } } } override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) { super.clearView(recyclerView, viewHolder) ViewCompat.animate(viewHolder.itemView).setDuration(150L).translationZ(0f) } override fun isLongPressDragEnabled(): Boolean { // We handle the long press on our side for better touch feedback. return false } override fun isItemViewSwipeEnabled(): Boolean { return false } } }
apache-2.0
36d1247008fd6f843953675d0830ff4c
37.5
100
0.667491
5.301639
false
false
false
false
SpineEventEngine/core-java
server/src/test/kotlin/io/spine/server/CommandServiceUnpublishedLanguageTest.kt
1
3037
/* * 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. */ package io.spine.server import com.google.common.truth.Truth.assertThat import io.spine.core.Ack import io.spine.core.Command import io.spine.core.Status import io.spine.grpc.MemoizingObserver import io.spine.grpc.StreamObservers.memoizingObserver import io.spine.protobuf.Messages.isNotDefault import io.spine.test.unpublished.command.Halt import io.spine.testing.client.TestActorRequestFactory import io.spine.testing.logging.mute.MuteLogging import io.spine.type.UnpublishedLanguageException import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test @MuteLogging internal class `'CommandService' should prohibit using 'internal_type' commands` { private lateinit var service: CommandService private lateinit var observer: MemoizingObserver<Ack> @BeforeEach fun initServiceAndObserver() { service = CommandService.newBuilder().build() observer = memoizingObserver() } @Test fun `returning 'Error' when such a command posted`() { val command = createCommand() service.post(command, observer) assertThat(observer.error).isNull() assertThat(observer.isCompleted).isTrue() val response = observer.firstResponse() assertThat(isNotDefault(response)).isTrue() val status = response.status assertThat(status.statusCase).isEqualTo(Status.StatusCase.ERROR) val error = status.error assertThat(error.type) .isEqualTo(UnpublishedLanguageException::class.java.canonicalName) } private fun createCommand(): Command { val factory = TestActorRequestFactory(javaClass) val commandMessage = Halt.newBuilder().setValue(true).build() val command = factory.createCommand(commandMessage) return command } }
apache-2.0
bf953af5a979b4cefd81524cc2b81152
36.493827
82
0.745802
4.401449
false
true
false
false
rsiebert/TVHClient
data/src/main/java/org/tvheadend/data/source/RecordingDataSource.kt
1
4414
package org.tvheadend.data.source import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.tvheadend.data.db.AppRoomDatabase import org.tvheadend.data.entity.Recording import org.tvheadend.data.entity.RecordingEntity import java.util.* class RecordingDataSource(private val db: AppRoomDatabase) : DataSourceInterface<Recording> { private val scope = CoroutineScope(Dispatchers.IO) override fun addItem(item: Recording) { scope.launch { db.recordingDao.insert(RecordingEntity.from(item)) } } fun addItems(items: List<Recording>) { scope.launch { db.recordingDao.insert(ArrayList(items.map { RecordingEntity.from(it) })) } } override fun updateItem(item: Recording) { scope.launch { db.recordingDao.update(RecordingEntity.from(item)) } } override fun removeItem(item: Recording) { scope.launch { db.recordingDao.delete(RecordingEntity.from(item)) } } override fun getLiveDataItemCount(): LiveData<Int> { return MutableLiveData() } override fun getLiveDataItems(): LiveData<List<Recording>> { return Transformations.map(db.recordingDao.loadRecordings()) { entities -> entities.map { it.toRecording() } } } override fun getLiveDataItemById(id: Any): LiveData<Recording> { return Transformations.map(db.recordingDao.loadRecordingById(id as Int)) { entity -> entity.toRecording() } } fun getLiveDataItemsByChannelId(channelId: Int): LiveData<List<Recording>> { return Transformations.map(db.recordingDao.loadRecordingsByChannelId(channelId)) { entities -> entities.map { it.toRecording() } } } fun getCompletedRecordings(sortOrder: Int): LiveData<List<Recording>> { return Transformations.map(db.recordingDao.loadCompletedRecordings(sortOrder)) { entities -> entities.map { it.toRecording() } } } fun getScheduledRecordings(hideDuplicates: Boolean): LiveData<List<Recording>> { return if (hideDuplicates) { Transformations.map(db.recordingDao.loadUniqueScheduledRecordings()) { entities -> entities.map { it.toRecording() } } } else { Transformations.map(db.recordingDao.loadScheduledRecordings()) { entities -> entities.map { it.toRecording() } } } } fun getFailedRecordings(): LiveData<List<Recording>> { return Transformations.map(db.recordingDao.loadFailedRecordings()) { entities -> entities.map { it.toRecording() } } } fun getRemovedRecordings(): LiveData<List<Recording>> { return Transformations.map(db.recordingDao.loadRemovedRecordings()) { entities -> entities.map { it.toRecording() } } } fun getLiveDataCountByType(type: String): LiveData<Int> { return when (type) { "completed" -> db.recordingDao.completedRecordingCount "scheduled" -> db.recordingDao.scheduledRecordingCount "running" -> db.recordingDao.runningRecordingCount "failed" -> db.recordingDao.failedRecordingCount "removed" -> db.recordingDao.removedRecordingCount else -> MutableLiveData() } } override fun getItemById(id: Any): Recording? { var recording: Recording? = null if ((id as Int) > 0) { runBlocking(Dispatchers.IO) { recording = db.recordingDao.loadRecordingByIdSync(id)?.toRecording() } } return recording } override fun getItems(): List<Recording> { return ArrayList() } fun getItemByEventId(id: Int): Recording? { var recording: Recording? = null if (id > 0) { runBlocking(Dispatchers.IO) { recording = db.recordingDao.loadRecordingByEventIdSync(id)?.toRecording() } } return recording } fun removeAndAddItems(items: ArrayList<Recording>) { scope.launch { db.recordingDao.deleteAll() db.recordingDao.insert(items.map { RecordingEntity.from(it) }) } } }
gpl-3.0
225a71415aa8c99afbdd0a3ff3b96327
33.484375
102
0.652923
4.675847
false
false
false
false
wiltonlazary/kotlin-native
samples/zephyr/src/main.kt
1
678
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ import platform.zephyr.stm32f4_disco.* import kotlinx.cinterop.* fun blinky(value: Int) { val port = LED0_GPIO_CONTROLLER val led = LED0_GPIO_PIN var toggler = false val dev = device_get_binding(port) gpio_pin_configure(dev, led.convert(), GPIO_DIR_OUT) while (true) { /* Set pin to HIGH/LOW every 1 second */ gpio_pin_write(dev, led.convert(), if (toggler) 1U else 0U); toggler = !toggler k_sleep(1000 * value); } } fun main() { blinky(1) }
apache-2.0
100cb6ddfbc274329851b5089d7837a6
23.214286
101
0.635693
2.986784
false
false
false
false
liceoArzignano/app_bold
app/src/main/kotlin/it/liceoarzignano/bold/ui/recyclerview/RecyclerTouchListener.kt
1
1124
package it.liceoarzignano.bold.ui.recyclerview import android.content.Context import android.view.GestureDetector import android.view.MotionEvent class RecyclerTouchListener(context: Context, private val mListener: RecyclerClickListener?) : androidx.recyclerview.widget.RecyclerView.OnItemTouchListener { private val mDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() { override fun onSingleTapUp(event: MotionEvent): Boolean = true }) override fun onInterceptTouchEvent(view: androidx.recyclerview.widget.RecyclerView, event: MotionEvent): Boolean { val child = view.findChildViewUnder(event.x, event.y) if (child != null && mListener != null && mDetector.onTouchEvent(event)) { mListener.onClick(child, view.getChildAdapterPosition(child)) return true } return false } override fun onTouchEvent(view: androidx.recyclerview.widget.RecyclerView, event: MotionEvent) = Unit override fun onRequestDisallowInterceptTouchEvent(shouldDisallow: Boolean) = Unit }
lgpl-3.0
df87d98274e488a0253ca4153eeb124a
40.62963
118
0.730427
5.301887
false
false
false
false
goodwinnk/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/ComponentFixtureUtils.kt
1
21514
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testGuiFramework.impl import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.ui.ComponentWithBrowseButton import com.intellij.testGuiFramework.cellReader.ExtendedJComboboxCellReader import com.intellij.testGuiFramework.cellReader.ExtendedJListCellReader import com.intellij.testGuiFramework.fixtures.* import com.intellij.testGuiFramework.fixtures.extended.ExtendedButtonFixture import com.intellij.testGuiFramework.fixtures.extended.ExtendedJTreePathFixture import com.intellij.testGuiFramework.fixtures.extended.ExtendedTableFixture import com.intellij.testGuiFramework.framework.GuiTestUtil import com.intellij.testGuiFramework.framework.Timeouts.defaultTimeout import com.intellij.testGuiFramework.framework.toPrintable import com.intellij.testGuiFramework.impl.GuiTestUtilKt.typeMatcher import com.intellij.testGuiFramework.util.FinderPredicate import com.intellij.testGuiFramework.util.Predicate import com.intellij.ui.CheckboxTree import com.intellij.ui.HyperlinkLabel import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBList import com.intellij.ui.components.JBTabbedPane import com.intellij.ui.components.labels.ActionLink import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.treeStructure.treetable.TreeTable import com.intellij.util.ui.AsyncProcessIcon import org.fest.swing.core.GenericTypeMatcher import org.fest.swing.core.Robot import org.fest.swing.exception.ActionFailedException import org.fest.swing.exception.ComponentLookupException import org.fest.swing.exception.WaitTimedOutError import org.fest.swing.fixture.* import org.fest.swing.timing.Timeout import org.junit.Assert import java.awt.Component import java.awt.Container import javax.swing.* //*********FIXTURES METHODS WITHOUT ROBOT and TARGET; KOTLIN ONLY /** * Finds a JList component in hierarchy of context component with a containingItem and returns JListFixture. * * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.jList(containingItem: String? = null, timeout: Timeout = defaultTimeout): JListFixture { val extCellReader = ExtendedJListCellReader() val myJList: JList<*> = findComponentWithTimeout(timeout) { jList: JList<*> -> if (containingItem == null) true //if were searching for any jList() else { val elements = (0 until jList.model.size).map { it: Int -> extCellReader.valueAt(jList as JList<Any?>, it) } elements.any { it.toString() == containingItem } && jList.isShowing } } val jListFixture = JListFixture(robot(), myJList) jListFixture.replaceCellReader(extCellReader) return jListFixture } /** * Finds a JButton component in hierarchy of context component with a name and returns ExtendedButtonFixture. * * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.button(name: String, timeout: Timeout = defaultTimeout): ExtendedButtonFixture { val jButton: JButton = findComponentWithTimeout(timeout) { it.isShowing && it.isVisible && it.text == name } return ExtendedButtonFixture(robot(), jButton) } /** * Finds a list of JButton component in hierarchy of context component with a name and returns ExtendedButtonFixture. * There can be cases when there are several the same named components and it's OK * * @throws ComponentLookupException if no component has not been found or timeout exceeded * @return list of JButton components sorted by locationOnScreen (left to right, top to down) */ fun <C : Container> ContainerFixture<C>.buttons(name: String, timeout: Timeout = defaultTimeout): List<ExtendedButtonFixture> { val jButtons = waitUntilFoundList(target() as Container, JButton::class.java, timeout) { it.isShowing && it.isVisible && it.text == name } return jButtons .map { ExtendedButtonFixture(GuiRobotHolder.robot, it) } .sortedBy { it.target().locationOnScreen.x } .sortedBy { it.target().locationOnScreen.y } } fun <C : Container> ContainerFixture<C>.componentWithBrowseButton(boundedLabelText: String, timeout: Timeout = defaultTimeout): ComponentWithBrowseButtonFixture { val boundedLabel: JLabel = findComponentWithTimeout(timeout) { it.text == boundedLabelText && it.isShowing } val component = boundedLabel.labelFor if (component is ComponentWithBrowseButton<*>) { return ComponentWithBrowseButtonFixture(component, robot()) } else throw unableToFindComponent("ComponentWithBrowseButton", timeout) } fun <C : Container> ContainerFixture<C>.treeTable(timeout: Timeout = defaultTimeout): TreeTableFixture { val table: TreeTable = findComponentWithTimeout(timeout) return TreeTableFixture(robot(), table) } fun <C : Container> ContainerFixture<C>.spinner(boundedLabelText: String, timeout: Timeout = defaultTimeout): JSpinnerFixture { val boundedLabel: JLabel = findComponentWithTimeout(timeout) { it.text == boundedLabelText } val component = boundedLabel.labelFor if (component is JSpinner) return JSpinnerFixture(robot(), component) else throw unableToFindComponent("JSpinner", timeout) } fun <C : Container> ContainerFixture<C>?.unableToFindComponent(componentName: String, timeout: Timeout): Throwable { if (this == null) throw ComponentLookupException("Unable to find $componentName component without parent container (null) in $timeout") else throw ComponentLookupException( "Unable to find $componentName component without parent container ${this.target()::javaClass.name} in $timeout") } /** * Finds a JComboBox component in hierarchy of context component by text of label and returns ComboBoxFixture. * * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.combobox(labelText: String, timeout: Timeout = defaultTimeout): ComboBoxFixture { //todo: cut all waits in fixtures val comboBox = GuiTestUtilKt.findBoundedComponentByText(robot(), target() as Container, labelText, JComboBox::class.java, timeout) val comboboxFixture = ComboBoxFixture(robot(), comboBox) comboboxFixture.replaceCellReader(ExtendedJComboboxCellReader()) return comboboxFixture } /** * Finds a JCheckBox component in hierarchy of context component by text of label and returns CheckBoxFixture. * * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.checkbox(labelText: String, timeout: Timeout = defaultTimeout): CheckBoxFixture { val jCheckBox: JCheckBox = findComponentWithTimeout(timeout) { it.isShowing && it.isVisible && it.text == labelText } return CheckBoxFixture(robot(), jCheckBox) } /** * Finds a ActionLink component in hierarchy of context component by name and returns ActionLinkFixture. * * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.actionLink(name: String, timeout: Timeout = defaultTimeout): ActionLinkFixture { val actionLink: ActionLink = findComponentWithTimeout(timeout) { it.isVisible && it.isShowing && it.text == name } return ActionLinkFixture(robot(), actionLink) } /** * Finds a ActionButton component in hierarchy of context component by action name and returns ActionButtonFixture. * * @actionName text or action id of an action button (@see com.intellij.openapi.actionSystem.ActionManager#getId()) * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.actionButton(actionName: String, timeout: Timeout = defaultTimeout): ActionButtonFixture { val actionButton: ActionButton = try { findComponentWithTimeout(timeout, ActionButtonFixture.textMatcher(actionName)) } catch (componentLookupException: ComponentLookupException) { findComponentWithTimeout(timeout, ActionButtonFixture.actionIdMatcher(actionName)) } return ActionButtonFixture(robot(), actionButton) } fun <C : Container> ContainerFixture<C>.actionButton(actionName: String, filter: (ActionButton) -> Boolean, timeout: Timeout = defaultTimeout): ActionButtonFixture { val actionButton: ActionButton = try { findComponentWithTimeout(timeout) { ActionButtonFixture.textMatcher(actionName).invoke(it).and(filter.invoke(it)) } } catch (componentLookupException: ComponentLookupException) { findComponentWithTimeout(timeout) { ActionButtonFixture.actionIdMatcher(actionName).invoke(it).and(filter.invoke(it)) } } return ActionButtonFixture(robot(), actionButton) } /** * Finds a InplaceButton component in hierarchy of context component by icon and returns InplaceButtonFixture. * * @icon of InplaceButton component. * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.inplaceButton(icon: Icon, timeout: Timeout = defaultTimeout): InplaceButtonFixture { val target = target() return InplaceButtonFixture.findInplaceButtonFixture(target, robot(), icon, timeout) } /** * Finds a ActionButton component in hierarchy of context component by action class name and returns ActionButtonFixture. * * @actionClassName qualified name of class for action * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.actionButtonByClass(actionClassName: String, timeout: Timeout = defaultTimeout): ActionButtonFixture { val actionButton: ActionButton = findComponentWithTimeout(timeout, ActionButtonFixture.actionClassNameMatcher(actionClassName)) return ActionButtonFixture(robot(), actionButton) } fun <C : Container> ContainerFixture<C>.tab(textLabel: String, timeout: Timeout = defaultTimeout): JBTabbedPaneFixture { val jbTabbedPane: JBTabbedPane = findComponentWithTimeout(timeout) { it.indexOfTab(textLabel) != -1 } return JBTabbedPaneFixture(textLabel, jbTabbedPane, robot()) } /** * Finds a JRadioButton component in hierarchy of context component by label text and returns JRadioButtonFixture. * * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.radioButton(textLabel: String, timeout: Timeout = defaultTimeout): RadioButtonFixture = GuiTestUtil.findRadioButton(target() as Container, textLabel, timeout) /** * Finds a JTextComponent component (JTextField) in hierarchy of context component by text of label and returns JTextComponentFixture. * * @textLabel could be a null if label is absent * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.textfield(textLabel: String?, timeout: Timeout = defaultTimeout): JTextComponentFixture { return GuiTestUtil.textfield(textLabel, target(), timeout) } /** * Finds a JTree component in hierarchy of context component by a path and returns ExtendedTreeFixture. * * @pathStrings comma separated array of Strings, representing path items: jTree("myProject", "src", "Main.java") * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.jTree(vararg pathStrings: String, timeout: Timeout = defaultTimeout, predicate: FinderPredicate = Predicate.equality): ExtendedJTreePathFixture = ExtendedJTreePathFixture(GuiTestUtil.jTreeComponent( container = target() as Container, timeout = timeout, pathStrings = *pathStrings, predicate = predicate ), pathStrings.toList(), predicate) /** * Finds a CheckboxTree component in hierarchy of context component by a path and returns CheckboxTreeFixture. * * @pathStrings comma separated array of Strings, representing path items: checkboxTree("JBoss", "JBoss Drools") * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.checkboxTree( vararg pathStrings: String, timeout: Timeout = defaultTimeout, predicate: FinderPredicate = Predicate.equality ): CheckboxTreeFixture { val tree = GuiTestUtil.jTreeComponent( container = target() as Container, timeout = timeout, predicate = predicate, pathStrings = *pathStrings ) as? CheckboxTree ?: throw ComponentLookupException("Found JTree but not a CheckboxTree") return CheckboxTreeFixture(tree, pathStrings.toList(), predicate, robot()) } /** * Finds a JTable component in hierarchy of context component by a cellText and returns JTableFixture. * * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.table(cellText: String, timeout: Timeout = defaultTimeout): ExtendedTableFixture { var tableFixture: ExtendedTableFixture? = null val jTable: JTable = findComponentWithTimeout(timeout) { tableFixture = ExtendedTableFixture(robot(), it) try { tableFixture?.cell(cellText) tableFixture != null } catch (e: ActionFailedException) { false } } return tableFixture ?: throw unableToFindComponent("""JTable with cell text "$cellText"""", timeout) } fun popupMenu( item: String, robot: Robot, root: Container? = null, timeout: Timeout = defaultTimeout, predicate: FinderPredicate = Predicate.equality ): JBListPopupFixture { val jbList = GuiTestUtil.waitUntilFound( robot, root, object : GenericTypeMatcher<JBList<*>>(JBList::class.java) { override fun isMatching(component: JBList<*>): Boolean { return JBListPopupFixture(component, item, predicate, robot).isSearchedItemPresent() } }, timeout) return JBListPopupFixture(jbList, item, predicate, robot) } fun <C : Container> ContainerFixture<C>.popupMenu(item: String, timeout: Timeout = defaultTimeout, predicate: FinderPredicate = Predicate.equality): JBListPopupFixture { val root: Container? = GuiTestUtil.getRootContainer(target()) Assert.assertNotNull(root) return popupMenu(item, robot(), root, timeout, predicate) } /** * Finds a LinkLabel component in hierarchy of context component by a link name and returns fixture for it. * * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.linkLabel(linkName: String, timeout: Timeout = defaultTimeout): ComponentFixture<ComponentFixture<*, *>, LinkLabel<*>> { val myLinkLabel = GuiTestUtil.waitUntilFound( robot(), target() as Container, GuiTestUtilKt.typeMatcher(LinkLabel::class.java) { it.isShowing && (it.text == linkName) }, timeout) return ComponentFixture(ComponentFixture::class.java, robot(), myLinkLabel) } fun <C : Container> ContainerFixture<C>.hyperlinkLabel(labelText: String, timeout: Timeout = defaultTimeout): HyperlinkLabelFixture { val hyperlinkLabel = GuiTestUtil.waitUntilFound(robot(), target() as Container, GuiTestUtilKt.typeMatcher(HyperlinkLabel::class.java) { it.isShowing && (it.text == labelText) }, timeout) return HyperlinkLabelFixture(robot(), hyperlinkLabel) } /** * Finds a table of plugins component in hierarchy of context component by a link name and returns fixture for it. * * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.pluginTable(timeout: Timeout = defaultTimeout) = PluginTableFixture.find(robot(), target() as Container, timeout) /** * Finds a Message component in hierarchy of context component by a title MessageFixture. * * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.message(title: String, timeout: Timeout = defaultTimeout): MessagesFixture<*> = MessagesFixture.findByTitle(robot(), target() as Container, title, timeout) fun <C : Container> ContainerFixture<C>.message(title: String, timeout: Timeout = defaultTimeout, func: MessagesFixture<*>.() -> Unit) { func(MessagesFixture.findByTitle(robot(), target() as Container, title, timeout)) } /** * Finds a JBLabel component in hierarchy of context component by a label name and returns fixture for it. * * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <C : Container> ContainerFixture<C>.label(labelName: String, timeout: Timeout = defaultTimeout): JLabelFixture { val jbLabel = GuiTestUtil.waitUntilFound( robot(), target() as Container, GuiTestUtilKt.typeMatcher(JBLabel::class.java) { it.isShowing && (it.text == labelName || labelName in it.text) }, timeout) return JLabelFixture(robot(), jbLabel) } /** * Find an AsyncProcessIcon component in a current context (gets by receiver) and returns a fixture for it. * Indexing processIcon is excluded from this search */ fun <C : Container> ContainerFixture<C>.asyncProcessIcon(timeout: Timeout = defaultTimeout): AsyncProcessIconFixture { val indexingProcessIconTooltipText = ActionsBundle.message("action.ShowProcessWindow.double.click") val asyncProcessIcon = GuiTestUtil.waitUntilFound( robot(), target(), GuiTestUtilKt.typeMatcher(AsyncProcessIcon::class.java) { it.isShowing && it.isVisible && it.toolTipText != indexingProcessIconTooltipText }, timeout) return AsyncProcessIconFixture(robot(), asyncProcessIcon) } fun <ComponentType : Component> waitUntilFound(container: Container?, componentClass: Class<ComponentType>, timeout: Timeout, matcher: (ComponentType) -> Boolean): ComponentType { return GuiTestUtil.waitUntilFound(GuiRobotHolder.robot, container, GuiTestUtilKt.typeMatcher(componentClass) { matcher(it) }, timeout) } fun <ComponentType : Component> waitUntilFoundList(container: Container?, componentClass: Class<ComponentType>, timeout: Timeout, matcher: (ComponentType) -> Boolean): List<ComponentType> { return GuiTestUtil.waitUntilFoundList(container, timeout, GuiTestUtilKt.typeMatcher(componentClass) { matcher(it) }) } /** * function to find component of returning type inside a container (gets from receiver). * * @throws ComponentLookupException if desired component haven't been found under the container (gets from receiver) in specified timeout */ inline fun <reified ComponentType : Component, ContainerComponentType : Container> ContainerFixture<ContainerComponentType>?.findComponentWithTimeout( timeout: Timeout = defaultTimeout, crossinline finderFunction: (ComponentType) -> Boolean = { _ -> true }): ComponentType { try { return GuiTestUtil.waitUntilFound(GuiRobotHolder.robot, this?.target() as Container?, GuiTestUtilKt.typeMatcher(ComponentType::class.java) { finderFunction(it) }, timeout) } catch (e: WaitTimedOutError) { throw ComponentLookupException( "Unable to find ${ComponentType::class.java.name} ${if (this?.target() != null) "in container ${this.target()}" else ""} in ${timeout.toPrintable()} seconds") } } fun <ComponentType : Component> findComponentWithTimeout(container: Container?, componentClass: Class<ComponentType>, timeout: Timeout = defaultTimeout, finderFunction: (ComponentType) -> Boolean = { _ -> true }): ComponentType { try { return GuiTestUtil.waitUntilFound(GuiRobotHolder.robot, container, GuiTestUtilKt.typeMatcher(componentClass) { finderFunction(it) }, timeout) } catch (e: WaitTimedOutError) { throw ComponentLookupException( "Unable to find ${componentClass.simpleName} ${if (container != null) "in container $container" else ""} in $timeout seconds") } } fun <ComponentType : Component> Robot.findComponent(container: Container?, componentClass: Class<ComponentType>, finderFunction: (ComponentType) -> Boolean = { _ -> true }): ComponentType { return if (container == null) this.finder().find(typeMatcher(componentClass, finderFunction)) else this.finder().find(container, typeMatcher(componentClass, finderFunction)) }
apache-2.0
610afe4e35527a89d6da558d7d75e4fd
46.915367
165
0.723389
5.083648
false
true
false
false
ohmae/mmupnp
mmupnp/src/main/java/net/mm2d/upnp/internal/impl/ActionImpl.kt
1
2793
/* * Copyright (c) 2019 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.upnp.internal.impl import net.mm2d.upnp.Action import net.mm2d.upnp.Argument /** * Implements for [Action]. * * @author [大前良介(OHMAE Ryosuke)](mailto:[email protected]) */ internal class ActionImpl( override val service: ServiceImpl, override val name: String, internal val argumentMap: Map<String, Argument> ) : Action { // VisibleForTesting internal val invokeDelegate: ActionInvokeDelegate by lazy { createInvokeDelegate(this) } override val argumentList: List<Argument> by lazy { argumentMap.values.toList() } override fun findArgument(name: String): Argument? = argumentMap[name] override suspend fun invoke( argumentValues: Map<String, String?>, returnErrorResponse: Boolean ): Map<String, String> = invokeCustom(argumentValues, emptyMap(), emptyMap(), returnErrorResponse) override suspend fun invokeCustom( argumentValues: Map<String, String?>, customNamespace: Map<String, String>, customArguments: Map<String, String>, returnErrorResponse: Boolean ): Map<String, String> = invokeDelegate.invoke(argumentValues, customNamespace, customArguments, returnErrorResponse) class Builder { private var service: ServiceImpl? = null private var name: String? = null private val argumentList: MutableList<ArgumentImpl.Builder> = mutableListOf() @Throws(IllegalStateException::class) fun build(): ActionImpl { val service = service ?: throw IllegalStateException("service must be set.") val name = name ?: throw IllegalStateException("name must be set.") return ActionImpl( service = service, name = name, argumentMap = argumentList .map { it.build() } .map { it.name to it } .toMap() ) } fun getArgumentBuilderList(): List<ArgumentImpl.Builder> = argumentList fun setService(service: ServiceImpl): Builder = apply { this.service = service } fun setName(name: String): Builder = apply { this.name = name } // Actionのインスタンス作成後にArgumentを登録することはできない fun addArgumentBuilder(argument: ArgumentImpl.Builder): Builder = apply { argumentList.add(argument) } } companion object { // VisibleForTesting internal fun createInvokeDelegate(action: ActionImpl) = ActionInvokeDelegate(action) } }
mit
010cebef4d79271e7237106f70106d6d
30.755814
102
0.6342
4.724913
false
false
false
false
KyuBlade/kotlin-discord-bot
src/main/kotlin/com/omega/discord/bot/database/DatabaseFactory.kt
1
1622
package com.omega.discord.bot.database import com.mongodb.MongoClient import com.omega.discord.bot.database.impl.MorphiaGroupDAO import com.omega.discord.bot.database.impl.MorphiaGuildPropertiesDAO import com.omega.discord.bot.database.impl.MorphiaUserDAO import com.omega.discord.bot.database.impl.converter.ChannelTypeConverter import com.omega.discord.bot.database.impl.converter.GuildTypeConverter import com.omega.discord.bot.database.impl.converter.RoleTypeConverter import com.omega.discord.bot.database.impl.converter.UserTypeConverter import com.omega.discord.bot.permission.Group import com.omega.discord.bot.permission.User import com.omega.discord.bot.property.GuildProperties import org.mongodb.morphia.Morphia object DatabaseFactory { private val morphia = Morphia() private val datastore = morphia.createDatastore(MongoClient(), "kotlin_bot") init { morphia.map(setOf( User::class.java, Group::class.java, GuildProperties::class.java )) with(morphia.mapper.converters) { addConverter(GuildTypeConverter()) addConverter(ChannelTypeConverter()) addConverter(UserTypeConverter()) addConverter(RoleTypeConverter()) } datastore.ensureIndexes() } val userDAO: UserDAO = MorphiaUserDAO(datastore) val groupDAO: GroupDAO = MorphiaGroupDAO(datastore) val guildPropertiesDAO: GuildPropertiesDAO = MorphiaGuildPropertiesDAO(datastore) fun close() { userDAO.clean() groupDAO.clean() guildPropertiesDAO.clean() } }
gpl-3.0
ec3973fae4fa3de106b8ed71a5f94907
32.122449
85
0.73058
4.202073
false
false
false
false
absurdhero/parsekt
src/main/kotlin/net/raboof/parsekt/CharParsers.kt
1
3270
package net.raboof.parsekt import kotlin.collections.arrayListOf import kotlin.collections.joinToString import kotlin.collections.plus import kotlin.text.Regex /** Extends the basic combinators with many character-specific parsers */ abstract class CharParsers<TInput> : Parsers<TInput>() { // implement anyChar to read a character from a sequence abstract val anyChar: Parser<TInput, Char> fun char(ch: Char): Parser<TInput, Char> { return anyChar.filter { c -> c == ch }.withErrorLabel("char($ch)") } fun char(predicate: (Char) -> Boolean): Parser<TInput, Char> { return anyChar.filter(predicate).withErrorLabel("char(predicate)") } fun char(regex: Regex): Parser<TInput, Char> { return anyChar.filter { ch: Char -> regex.matches(ch.toString()) }.withErrorLabel("char(/$regex/)") } //public val whitespace: Parser<TInput, List<Char>> = repeat(char(' ') or char('\t') or char('\n') or char('\r')); val whitespace = repeat(char(Regex("""\s"""))).withErrorLabel("whitespace") val wordChar = char(Regex("""\w""")) fun wsChar(ch: Char) = whitespace and char(ch) val token = repeat1(wordChar).between(whitespace) fun concat(p1: Parser<TInput, Char>, p2: Parser<TInput, List<Char>>): Parser<TInput, List<Char>> { return p1.project({v: Char, l: List<Char> -> arrayListOf(v) + l })({p2}) } fun concat(vararg charParsers: Parser<TInput, Char>): Parser<TInput, List<Char>> { var parser : Parser<TInput, List<Char>> = succeed(emptyList()) for (p in charParsers) { parser = parser.project({l: List<Char>, v: Char -> l + v })({p}) } return parser } fun charPrefix(prefix: Char, parser: Parser<TInput, List<Char>>): Parser<TInput, List<Char>> { return concat(char(prefix), parser) or parser } /** greedy regex matcher */ fun substring(regex: Regex): Parser<TInput, List<Char>> { return Parser { input -> var result = anyChar(input) when (result) { is Result.ParseError -> Result.ParseError(result) is Result.Value -> { val temp = StringBuilder() var lastRest: TInput = result.rest var everMatched = false while (result !is Result.ParseError) { result as Result.Value temp.append(result.value) if (regex.matches(temp)) { everMatched = true } else if (everMatched) { temp.deleteCharAt(temp.length-1) break } lastRest = result.rest result = anyChar(result.rest) } if (everMatched) { Result.Value(temp.toList(), lastRest) } else { Result.ParseError("/$regex/", lastRest) } } } } } } fun <TInput> Parser<TInput, List<Char>>.string(): Parser<TInput, String> { return this.mapResult { Result.Value(it.value.joinToString(""), it.rest) } }
apache-2.0
a2586e6eef143d17989f061802105db7
36.170455
118
0.551376
4.246753
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/adapter/SelectableUsersAdapter.kt
1
8213
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.adapter import android.content.Context import android.support.v4.util.ArrayMap import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.bumptech.glide.RequestManager import de.vanita5.twittnuker.R import de.vanita5.twittnuker.adapter.iface.IItemCountsAdapter import de.vanita5.twittnuker.adapter.iface.ILoadMoreSupportAdapter import de.vanita5.twittnuker.adapter.iface.ILoadMoreSupportAdapter.Companion.ITEM_VIEW_TYPE_LOAD_INDICATOR import de.vanita5.twittnuker.exception.UnsupportedCountIndexException import de.vanita5.twittnuker.model.ItemCounts import de.vanita5.twittnuker.model.ParcelableUser import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.view.holder.LoadIndicatorViewHolder import de.vanita5.twittnuker.view.holder.SelectableUserViewHolder class SelectableUsersAdapter( context: Context, requestManager: RequestManager ) : LoadMoreSupportAdapter<RecyclerView.ViewHolder>(context, requestManager), IItemCountsAdapter { val ITEM_VIEW_TYPE_USER = 2 override val itemCounts: ItemCounts = ItemCounts(3) private val inflater: LayoutInflater = LayoutInflater.from(context) private val checkedState: MutableMap<UserKey, Boolean> = ArrayMap() private val lockedState: MutableMap<UserKey, Boolean> = ArrayMap() var itemCheckedListener: ((Int, Boolean) -> Boolean)? = null var data: List<ParcelableUser>? = null set(value) { field = value updateItemCounts() notifyDataSetChanged() } init { setHasStableIds(true) } override fun getItemCount(): Int { return itemCounts.itemCount } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { when (viewType) { ITEM_VIEW_TYPE_USER -> { val view = inflater.inflate(R.layout.list_item_simple_user, parent, false) val holder = SelectableUserViewHolder(view, this) return holder } ITEM_VIEW_TYPE_LOAD_INDICATOR -> { val view = inflater.inflate(R.layout.list_item_load_indicator, parent, false) return LoadIndicatorViewHolder(view) } } throw IllegalStateException("Unknown view type " + viewType) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder.itemViewType) { ITEM_VIEW_TYPE_USER -> { bindUser(holder as SelectableUserViewHolder, position) } } } override fun getItemViewType(position: Int): Int { val countIndex = itemCounts.getItemCountIndex(position) when (countIndex) { ITEM_TYPE_START_INDICATOR, ITEM_TYPE_END_INDICATOR -> return ITEM_VIEW_TYPE_LOAD_INDICATOR ITEM_TYPE_USER -> return ITEM_VIEW_TYPE_USER else -> throw UnsupportedCountIndexException(countIndex, position) } } override fun getItemId(position: Int): Long { val countIndex = itemCounts.getItemCountIndex(position) return when (countIndex) { ITEM_TYPE_START_INDICATOR, ITEM_TYPE_END_INDICATOR -> (countIndex.toLong() shl 32) ITEM_TYPE_USER -> (countIndex.toLong() shl 32) or getUser(position).hashCode().toLong() else -> throw UnsupportedCountIndexException(countIndex, position) } } private fun bindUser(holder: SelectableUserViewHolder, position: Int) { holder.displayUser(getUser(position)) } private fun updateItemCounts() { val position = loadMoreIndicatorPosition itemCounts[ITEM_TYPE_START_INDICATOR] = if (position and ILoadMoreSupportAdapter.START != 0L) 1 else 0 itemCounts[ITEM_TYPE_USER] = userCount itemCounts[ITEM_TYPE_END_INDICATOR] = if (position and ILoadMoreSupportAdapter.END != 0L) 1 else 0 } fun getUser(position: Int): ParcelableUser { return data!![position - itemCounts.getItemStartPosition(1)] } val userStartIndex: Int get() { val position = loadMoreIndicatorPosition var start = 0 if (position and ILoadMoreSupportAdapter.START != 0L) { start += 1 } return start } fun getUserKey(position: Int): UserKey { return getUser(position).key } val userCount: Int get() = data?.size ?: 0 fun removeUserAt(position: Int): Boolean { val data = this.data as? MutableList ?: return false val dataPosition = position - userStartIndex if (dataPosition < 0 || dataPosition >= userCount) return false data.removeAt(dataPosition) notifyItemRemoved(position) return true } fun setUserAt(position: Int, user: ParcelableUser): Boolean { val data = this.data as? MutableList ?: return false val dataPosition = position - userStartIndex if (dataPosition < 0 || dataPosition >= userCount) return false data[dataPosition] = user notifyItemChanged(position) return true } fun findPosition(accountKey: UserKey, userKey: UserKey): Int { if (data == null) return RecyclerView.NO_POSITION for (i in userStartIndex until userStartIndex + userCount) { val user = data!![i] if (accountKey == user.account_key && userKey == user.key) { return i } } return RecyclerView.NO_POSITION } val checkedCount: Int get() { return data?.count { it.key !in lockedState && checkedState[it.key] ?: false } ?: 0 } fun setItemChecked(position: Int, value: Boolean) { val userKey = getUserKey(position) setCheckState(userKey, value) if (!(itemCheckedListener?.invoke(position, value) ?: true)) { setCheckState(userKey, !value) notifyItemChanged(position) } } fun clearCheckState() { checkedState.clear() } fun setCheckState(userKey: UserKey, value: Boolean) { checkedState[userKey] = value } fun clearLockedState() { lockedState.clear() } fun setLockedState(userKey: UserKey, locked: Boolean) { lockedState[userKey] = locked } fun removeLockedState(userKey: UserKey) { lockedState.remove(userKey) } fun isItemChecked(position: Int): Boolean { return checkedState[getUserKey(position)] ?: false } fun isItemChecked(userKey: UserKey): Boolean { return checkedState[userKey] ?: false } fun getLockedState(position: Int): Boolean { return lockedState[getUserKey(position)] ?: false } fun getLockedState(userKey: UserKey): Boolean { return lockedState[userKey] ?: false } fun isItemLocked(position: Int): Boolean { return getUserKey(position) in lockedState } fun isItemLocked(userKey: UserKey): Boolean { return userKey in lockedState } fun clearSelection() { checkedState.clear() } companion object { const val ITEM_TYPE_START_INDICATOR = 0 const val ITEM_TYPE_USER = 1 const val ITEM_TYPE_END_INDICATOR = 2 } }
gpl-3.0
25c3f2ebba5b3186b1c5277229db393a
32.942149
110
0.664191
4.557714
false
false
false
false
06needhamt/LINQ-For-Java
src/linq/sql/parser/Parser.kt
1
2481
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package linq.sql.parser import linq.collections.LinqListFunctions import linq.sql.parser.ast.Statement import linq.sql.parser.ast.WhereStatement import linq.sql.tokens.KeywordToken import linq.sql.tokens.Token import linq.sql.tokens.TokenType import java.util.* /** * Created by Tom Needham on 10/03/2016. */ class Parser { val lexical : Lexer val statements : ArrayList<Statement?> = ArrayList<Statement?>() constructor(lexical: Lexer){ this.lexical = lexical } fun CreateStatements() : ArrayList<Statement?>{ val statementList = ArrayList<Statement?>() var i : Int = 0 while(i < lexical.tokens.size - 1){ val tok : Token? = lexical.tokens.get(i) if(tok is KeywordToken){ when (tok.type){ TokenType.EnumKeywordToken.WHERE -> { val tokens : ArrayList<Token?> = ArrayList(LinqListFunctions.Take(lexical.tokens,3)) val smt : WhereStatement = WhereStatement(tokens,3) i += 2 } } } } return statementList } fun ReturnsValue() : Boolean{ val tok = LinqListFunctions.First(lexical.tokens) if(tok is KeywordToken) return tok.type == TokenType.EnumKeywordToken.SELECT else return false } }
mit
7aa002ac3f2927951b7a60c846ec988a
33.957746
108
0.682789
4.42246
false
false
false
false
alexcustos/linkasanote
app/src/main/java/com/bytesforge/linkasanote/sync/SyncNotifications.kt
1
5253
/* * LaaNo Android application * * @author Aleksandr Borisenko <[email protected]> * Copyright (C) 2017 Aleksandr Borisenko * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.bytesforge.linkasanote.sync import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.drawable.BitmapDrawable import android.os.Build import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat import com.bytesforge.linkasanote.BuildConfig import com.bytesforge.linkasanote.R import com.bytesforge.linkasanote.sync.SyncNotifications import com.google.common.base.Preconditions class SyncNotifications(private val context: Context?) { private val notificationManager: NotificationManagerCompat = NotificationManagerCompat.from(context!!) private var accountName: String? = null @JvmOverloads fun sendSyncBroadcast(action: String?, status: Int, id: String? = null, count: Int = -1) { Preconditions.checkNotNull(accountName) val intent = Intent(action) intent.putExtra(EXTRA_ACCOUNT_NAME, accountName) if (status >= 0) intent.putExtra(EXTRA_STATUS, status) if (id != null) intent.putExtra(EXTRA_ID, id) if (count >= 0) intent.putExtra(EXTRA_COUNT, count) context!!.sendBroadcast(intent) } fun notifyFailedSynchronization(text: String) { Preconditions.checkNotNull(text) notifyFailedSynchronization(null, text) } private fun initChannels(context: Context?) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return val notificationManager = context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (notificationManager == null) { Log.e(TAG, "Error while retrieving Notification Service") return } val channel = NotificationChannel( CHANNEL_NAME_SYNC, context.getString(R.string.sync_adapter_sync_channel_name), NotificationManager.IMPORTANCE_DEFAULT ) channel.description = context.getString(R.string.sync_adapter_sync_channel_description) notificationManager.createNotificationChannel(channel) } fun notifyFailedSynchronization(title: String?, text: String) { Preconditions.checkNotNull(text) //notificationManager.cancel(NOTIFICATION_SYNC); val defaultTitle = context!!.getString(R.string.sync_adapter_title_failed_default) val notificationTitle = if (title == null) defaultTitle else "$defaultTitle: $title" val color = ContextCompat.getColor(context, R.color.color_primary) val notification = NotificationCompat.Builder(context, CHANNEL_NAME_SYNC) .setSmallIcon(R.drawable.ic_error_white) .setLargeIcon(launcherBitmap) .setColor(color) .setTicker(notificationTitle) .setContentTitle(notificationTitle) .setContentText(text) .build() notificationManager.notify(NOTIFICATION_SYNC, notification) } private val launcherBitmap: Bitmap? get() { val logo = ContextCompat.getDrawable(context!!, R.mipmap.ic_launcher) return if (logo is BitmapDrawable) { logo.bitmap } else null } fun setAccountName(accountName: String?) { this.accountName = accountName } companion object { private val TAG = SyncNotifications::class.java.simpleName private const val CHANNEL_NAME_SYNC = "sync_channel" const val ACTION_SYNC = BuildConfig.APPLICATION_ID + ".ACTION_SYNC" const val ACTION_SYNC_LINKS = BuildConfig.APPLICATION_ID + ".ACTION_SYNC_LINKS" const val ACTION_SYNC_FAVORITES = BuildConfig.APPLICATION_ID + ".ACTION_SYNC_FAVORITES" const val ACTION_SYNC_NOTES = BuildConfig.APPLICATION_ID + ".ACTION_SYNC_NOTES" const val EXTRA_ACCOUNT_NAME = "ACCOUNT_NAME" const val EXTRA_STATUS = "STATUS" const val EXTRA_ID = "ID" const val EXTRA_COUNT = "COUNT" const val STATUS_SYNC_START = 10 const val STATUS_SYNC_STOP = 11 const val STATUS_CREATED = 20 const val STATUS_UPDATED = 21 const val STATUS_DELETED = 22 const val STATUS_UPLOADED = 30 const val STATUS_DOWNLOADED = 31 private const val NOTIFICATION_SYNC = 0 } init { initChannels(context) } }
gpl-3.0
3d3b2235b9de1641238d28b37c3c28b2
39.415385
95
0.695983
4.620053
false
false
false
false
slartus/4pdaClient-plus
qms/qms-impl/src/main/java/org/softeg/slartus/forpdaplus/qms/impl/screens/contacts/fingerprints/QmsContactFingerprint.kt
1
3526
package org.softeg.slartus.forpdaplus.qms.impl.screens.contacts.fingerprints import android.os.Build import android.os.Build.VERSION.SDK_INT import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.recyclerview.widget.DiffUtil import coil.ImageLoader import coil.decode.GifDecoder import coil.decode.ImageDecoderDecoder import coil.load import coil.transform.CircleCropTransformation import coil.transform.Transformation import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.BaseViewHolder import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.Item import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.ItemFingerprint import org.softeg.slartus.forpdaplus.qms.impl.R import org.softeg.slartus.forpdaplus.qms.impl.databinding.LayoutQmsContactItemBinding class QmsContactFingerprint( private val squareAvatars: Boolean, private val showAvatars: Boolean, private val onClickListener: (view: View?, item: QmsContactItem) -> Unit ) : ItemFingerprint<LayoutQmsContactItemBinding, QmsContactItem> { private val diffUtil = object : DiffUtil.ItemCallback<QmsContactItem>() { override fun areItemsTheSame( oldItem: QmsContactItem, newItem: QmsContactItem ) = oldItem.id == newItem.id override fun areContentsTheSame( oldItem: QmsContactItem, newItem: QmsContactItem ) = oldItem == newItem } override fun getLayoutId() = R.layout.layout_qms_contact_item override fun isRelativeItem(item: Item) = item is QmsContactItem && item.newMessagesCount == 0 override fun getViewHolder( layoutInflater: LayoutInflater, parent: ViewGroup ): BaseViewHolder<LayoutQmsContactItemBinding, QmsContactItem> { val binding = LayoutQmsContactItemBinding.inflate(layoutInflater, parent, false) return QmsContactViewHolder( binding = binding, squareAvatars = squareAvatars, showAvatars = showAvatars, onClickListener = onClickListener ) } override fun getDiffUtil() = diffUtil } class QmsContactViewHolder( binding: LayoutQmsContactItemBinding, squareAvatars: Boolean, private val showAvatars: Boolean, private val onClickListener: (view: View?, item: QmsContactItem) -> Unit ) : BaseViewHolder<LayoutQmsContactItemBinding, QmsContactItem>(binding) { private val avatarTransformations: List<Transformation> = if (squareAvatars) emptyList() else listOf(CircleCropTransformation()) val imageLoader = ImageLoader.Builder(itemView.context) .componentRegistry { if (SDK_INT >= Build.VERSION_CODES.P) { add(ImageDecoderDecoder(itemView.context)) } else { add(GifDecoder()) } } .build() init { itemView.setOnClickListener { v -> onClickListener(v, item) } binding.avatarImageView.isVisible = showAvatars } override fun onBind(item: QmsContactItem) { super.onBind(item) with(binding) { if (showAvatars) { avatarImageView.load(item.avatarUrl, imageLoader) { transformations(avatarTransformations) } } nickTextView.text = item.nick } } } data class QmsContactItem( val id: String, val nick: String, val avatarUrl: String?, val newMessagesCount: Int ) : Item
apache-2.0
94e950ba00a1c5c88cbeed5718c4ea8b
32.590476
98
0.698242
4.81694
false
false
false
false
AndroidX/androidx
compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/collection/MutableVector.kt
3
34940
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE", "UNCHECKED_CAST") package androidx.compose.runtime.collection import kotlin.contracts.ExperimentalContracts import kotlin.contracts.contract import kotlin.math.max /** * A [MutableList]-like structure with a simplified interface that offers faster access than * [ArrayList]. */ @OptIn(ExperimentalContracts::class) class MutableVector<T> @PublishedApi internal constructor( @PublishedApi internal var content: Array<T?>, size: Int ) : RandomAccess { /** * Stores allocated [MutableList] representation of this vector. */ private var list: MutableList<T>? = null /** * The number of elements in the [MutableVector]. */ var size: Int = size private set /** * Returns the last valid index in the [MutableVector]. */ inline val lastIndex: Int get() = size - 1 /** * Returns an [IntRange] of the valid indices for this [MutableVector]. */ inline val indices: IntRange get() = 0..size - 1 /** * Adds [element] to the [MutableVector] and returns `true`. */ fun add(element: T): Boolean { ensureCapacity(size + 1) content[size] = element size++ return true } /** * Adds [element] to the [MutableVector] at the given [index], shifting over any elements * that are in the way. */ fun add(index: Int, element: T) { ensureCapacity(size + 1) val content = content if (index != size) { content.copyInto( destination = content, destinationOffset = index + 1, startIndex = index, endIndex = size ) } content[index] = element size++ } /** * Adds all [elements] to the [MutableVector] at the given [index], shifting over any * elements that are in the way. */ fun addAll(index: Int, elements: List<T>): Boolean { if (elements.isEmpty()) return false ensureCapacity(size + elements.size) val content = content if (index != size) { content.copyInto( destination = content, destinationOffset = index + elements.size, startIndex = index, endIndex = size ) } for (i in elements.indices) { content[index + i] = elements[i] } size += elements.size return true } /** * Adds all [elements] to the [MutableVector] at the given [index], shifting over any * elements that are in the way. */ fun addAll(index: Int, elements: MutableVector<T>): Boolean { if (elements.isEmpty()) return false ensureCapacity(size + elements.size) val content = content if (index != size) { content.copyInto( destination = content, destinationOffset = index + elements.size, startIndex = index, endIndex = size ) } elements.content.copyInto( destination = content, destinationOffset = index, startIndex = 0, endIndex = elements.size ) size += elements.size return true } /** * Adds all [elements] to the end of the [MutableVector] and returns `true` if the * [MutableVector] was changed. */ inline fun addAll(elements: List<T>): Boolean { return addAll(size, elements) } /** * Adds all [elements] to the end of the [MutableVector] and returns `true` if the * [MutableVector] was changed. */ inline fun addAll(elements: MutableVector<T>): Boolean { return addAll(size, elements) } /** * Adds all [elements] to the end of the [MutableVector] and returns `true` if the * [MutableVector] was changed. */ fun addAll( @Suppress("ArrayReturn") elements: Array<T> ): Boolean { if (elements.isEmpty()) { return false } ensureCapacity(size + elements.size) elements.copyInto( destination = content, destinationOffset = size ) size += elements.size return true } /** * Adds all [elements] to the [MutableVector] at the given [index], shifting over any * elements that are in the way. */ fun addAll(index: Int, elements: Collection<T>): Boolean { if (elements.isEmpty()) return false ensureCapacity(size + elements.size) val content = content if (index != size) { content.copyInto( destination = content, destinationOffset = index + elements.size, startIndex = index, endIndex = size ) } elements.forEachIndexed { i, item -> content[index + i] = item } size += elements.size return true } /** * Adds all [elements] to the end of the [MutableVector] and returns `true` if the * [MutableVector] was changed. */ fun addAll(elements: Collection<T>): Boolean { return addAll(size, elements) } /** * Returns `true` if any of the elements give a `true` return value for [predicate]. */ inline fun any(predicate: (T) -> Boolean): Boolean { contract { callsInPlace(predicate) } val size = size if (size > 0) { var i = 0 val content = content as Array<T> do { if (predicate(content[i])) return true i++ } while (i < size) } return false } /** * Returns `true` if any of the elements give a `true` return value for [predicate] while * iterating in the reverse order. */ inline fun reversedAny(predicate: (T) -> Boolean): Boolean { contract { callsInPlace(predicate) } val size = size if (size > 0) { var i = size - 1 val content = content as Array<T> do { if (predicate(content[i])) return true i-- } while (i >= 0) } return false } /** * Returns [MutableList] interface access to the [MutableVector]. */ fun asMutableList(): MutableList<T> { return list ?: MutableVectorList(this).also { list = it } } /** * Removes all elements in the [MutableVector]. */ fun clear() { val content = content for (i in lastIndex downTo 0) { content[i] = null } size = 0 } /** * Returns `true` if the [MutableVector] contains [element] or `false` otherwise. */ operator fun contains(element: T): Boolean { for (i in 0..lastIndex) { if (get(i) == element) return true } return false } /** * Returns `true` if the [MutableVector] contains all elements in [elements] or `false` if * one or more are missing. */ fun containsAll(elements: List<T>): Boolean { for (i in elements.indices) { if (!contains(elements[i])) return false } return true } /** * Returns `true` if the [MutableVector] contains all elements in [elements] or `false` if * one or more are missing. */ fun containsAll(elements: Collection<T>): Boolean { elements.forEach { if (!contains(it)) return false } return true } /** * Returns `true` if the [MutableVector] contains all elements in [elements] or `false` if * one or more are missing. */ fun containsAll(elements: MutableVector<T>): Boolean { for (i in elements.indices) { if (!contains(elements[i])) return false } return true } /** * Returns `true` if the contents of the [MutableVector] are the same or `false` if there * is any difference. This uses equality comparisons on each element rather than reference * equality. */ fun contentEquals(other: MutableVector<T>): Boolean { if (other.size != size) { return false } for (i in 0..lastIndex) { if (other[i] != this[i]) { return false } } return true } /** * Ensures that there is enough space to store [capacity] elements in the [MutableVector]. */ fun ensureCapacity(capacity: Int) { val oldContent = content if (oldContent.size < capacity) { val newSize = max(capacity, oldContent.size * 2) content = oldContent.copyOf(newSize) } } /** * Returns the first element in the [MutableVector] or throws a [NoSuchElementException] if * it [isEmpty]. */ fun first(): T { if (isEmpty()) { throw NoSuchElementException("MutableVector is empty.") } return get(0) } /** * Returns the first element in the [MutableVector] for which [predicate] returns `true` or * throws [NoSuchElementException] if nothing matches. */ inline fun first(predicate: (T) -> Boolean): T { contract { callsInPlace(predicate) } val size = size if (size > 0) { var i = 0 val content = content as Array<T> do { val item = content[i] if (predicate(item)) return item i++ } while (i < size) } throwNoSuchElementException() } /** * Returns the first element in the [MutableVector] or `null` if it [isEmpty]. */ inline fun firstOrNull() = if (isEmpty()) null else get(0) /** * Returns the first element in the [MutableVector] for which [predicate] returns `true` or * returns `null` if nothing matches. */ inline fun firstOrNull(predicate: (T) -> Boolean): T? { contract { callsInPlace(predicate) } val size = size if (size > 0) { var i = 0 val content = content as Array<T> do { val item = content[i] if (predicate(item)) return item i++ } while (i < size) } return null } /** * Accumulates values, starting with [initial], and applying [operation] to each element * in the [MutableVector] in order. */ inline fun <R> fold(initial: R, operation: (acc: R, T) -> R): R { contract { callsInPlace(operation) } var acc = initial val size = size if (size > 0) { var i = 0 val content = content as Array<T> do { acc = operation(acc, content[i]) i++ } while (i < size) } return acc } /** * Accumulates values, starting with [initial], and applying [operation] to each element * in the [MutableVector] in order. */ inline fun <R> foldIndexed(initial: R, operation: (index: Int, acc: R, T) -> R): R { contract { callsInPlace(operation) } var acc = initial val size = size if (size > 0) { var i = 0 val content = content as Array<T> do { acc = operation(i, acc, content[i]) i++ } while (i < size) } return acc } /** * Accumulates values, starting with [initial], and applying [operation] to each element * in the [MutableVector] in reverse order. */ inline fun <R> foldRight(initial: R, operation: (T, acc: R) -> R): R { contract { callsInPlace(operation) } var acc = initial val size = size if (size > 0) { var i = size - 1 val content = content as Array<T> do { acc = operation(content[i], acc) i-- } while (i >= 0) } return acc } /** * Accumulates values, starting with [initial], and applying [operation] to each element * in the [MutableVector] in reverse order. */ inline fun <R> foldRightIndexed(initial: R, operation: (index: Int, T, acc: R) -> R): R { contract { callsInPlace(operation) } var acc = initial val size = size if (size > 0) { var i = size - 1 val content = content as Array<T> do { acc = operation(i, content[i], acc) i-- } while (i >= 0) } return acc } /** * Calls [block] for each element in the [MutableVector], in order. */ inline fun forEach(block: (T) -> Unit) { contract { callsInPlace(block) } val size = size if (size > 0) { var i = 0 val content = content as Array<T> do { block(content[i]) i++ } while (i < size) } } /** * Calls [block] for each element in the [MutableVector] along with its index, in order. */ inline fun forEachIndexed(block: (Int, T) -> Unit) { contract { callsInPlace(block) } val size = size if (size > 0) { var i = 0 val content = content as Array<T> do { block(i, content[i]) i++ } while (i < size) } } /** * Calls [block] for each element in the [MutableVector] in reverse order. */ inline fun forEachReversed(block: (T) -> Unit) { contract { callsInPlace(block) } val size = size if (size > 0) { var i = size - 1 val content = content as Array<T> do { block(content[i]) i-- } while (i >= 0) } } /** * Calls [block] for each element in the [MutableVector] along with its index, in reverse * order. */ inline fun forEachReversedIndexed(block: (Int, T) -> Unit) { contract { callsInPlace(block) } if (size > 0) { var i = size - 1 val content = content as Array<T> do { block(i, content[i]) i-- } while (i >= 0) } } /** * Returns the element at the given [index]. */ inline operator fun get(index: Int): T = content[index] as T /** * Returns the index of [element] in the [MutableVector] or `-1` if [element] is not there. */ fun indexOf(element: T): Int { val size = size if (size > 0) { var i = 0 val content = content as Array<T> do { if (element == content[i]) return i i++ } while (i < size) } return -1 } /** * Returns the index if the first element in the [MutableVector] for which [predicate] * returns `true`. */ inline fun indexOfFirst(predicate: (T) -> Boolean): Int { contract { callsInPlace(predicate) } val size = size if (size > 0) { var i = 0 val content = content as Array<T> do { if (predicate(content[i])) return i i++ } while (i < size) } return -1 } /** * Returns the index if the last element in the [MutableVector] for which [predicate] * returns `true`. */ inline fun indexOfLast(predicate: (T) -> Boolean): Int { contract { callsInPlace(predicate) } val size = size if (size > 0) { var i = size - 1 val content = content as Array<T> do { if (predicate(content[i])) return i i-- } while (i >= 0) } return -1 } /** * Returns `true` if the [MutableVector] has no elements in it or `false` otherwise. */ fun isEmpty(): Boolean = size == 0 /** * Returns `true` if there are elements in the [MutableVector] or `false` if it is empty. */ fun isNotEmpty(): Boolean = size != 0 /** * Returns the last element in the [MutableVector] or throws a [NoSuchElementException] if * it [isEmpty]. */ fun last(): T { if (isEmpty()) { throw NoSuchElementException("MutableVector is empty.") } return get(lastIndex) } /** * Returns the last element in the [MutableVector] for which [predicate] returns `true` or * throws [NoSuchElementException] if nothing matches. */ inline fun last(predicate: (T) -> Boolean): T { contract { callsInPlace(predicate) } val size = size if (size > 0) { var i = size - 1 val content = content as Array<T> do { val item = content[i] if (predicate(item)) return item i-- } while (i >= 0) } throwNoSuchElementException() } /** * Returns the index of the last element in the [MutableVector] that is the same as * [element] or `-1` if no elements match. */ fun lastIndexOf(element: T): Int { val size = size if (size > 0) { var i = size - 1 val content = content as Array<T> do { if (element == content[i]) return i i-- } while (i >= 0) } return -1 } /** * Returns the last element in the [MutableVector] or `null` if it [isEmpty]. */ inline fun lastOrNull() = if (isEmpty()) null else get(lastIndex) /** * Returns the last element in the [MutableVector] for which [predicate] returns `true` or * returns `null` if nothing matches. */ inline fun lastOrNull(predicate: (T) -> Boolean): T? { contract { callsInPlace(predicate) } val size = size if (size > 0) { var i = size - 1 val content = content as Array<T> do { val item = content[i] if (predicate(item)) return item i-- } while (i >= 0) } return null } /** * Returns an [Array] of results of transforming each element in the [MutableVector]. The * Array will be the same size as this. */ @Suppress("ArrayReturn") inline fun <reified R> map(transform: (T) -> R): Array<R> { contract { callsInPlace(transform) } return Array(size) { transform(get(it)) } } /** * Returns an [Array] of results of transforming each element in the [MutableVector]. The * Array will be the same size as this. */ @Suppress("ArrayReturn") inline fun <reified R> mapIndexed(transform: (index: Int, T) -> R): Array<R> { contract { callsInPlace(transform) } return Array(size) { transform(it, get(it)) } } /** * Returns an [MutableVector] of results of transforming each element in the [MutableVector], * excluding those transformed values that are `null`. */ inline fun <reified R> mapIndexedNotNull(transform: (index: Int, T) -> R?): MutableVector<R> { contract { callsInPlace(transform) } val size = size val arr = arrayOfNulls<R>(size) var targetSize = 0 if (size > 0) { val content = content as Array<T> var i = 0 do { val target = transform(i, content[i]) if (target != null) { arr[targetSize++] = target } i++ } while (i < size) } return MutableVector(arr, targetSize) } /** * Returns an [MutableVector] of results of transforming each element in the [MutableVector], * excluding those transformed values that are `null`. */ inline fun <reified R> mapNotNull(transform: (T) -> R?): MutableVector<R> { contract { callsInPlace(transform) } val size = size val arr = arrayOfNulls<R>(size) var targetSize = 0 if (size > 0) { val content = content as Array<T> var i = 0 do { val target = transform(content[i]) if (target != null) { arr[targetSize++] = target } i++ } while (i < size) } return MutableVector(arr, targetSize) } /** * [add] [element] to the [MutableVector]. */ inline operator fun plusAssign(element: T) { add(element) } /** * [remove] [element] from the [MutableVector] */ inline operator fun minusAssign(element: T) { remove(element) } /** * Removes [element] from the [MutableVector]. If [element] was in the [MutableVector] * and was removed, `true` will be returned, or `false` will be returned if the element * was not found. */ fun remove(element: T): Boolean { val index = indexOf(element) if (index >= 0) { removeAt(index) return true } return false } /** * Removes all [elements] from the [MutableVector] and returns `true` if anything was removed. */ fun removeAll(elements: List<T>): Boolean { val initialSize = size for (i in elements.indices) { remove(elements[i]) } return initialSize != size } /** * Removes all [elements] from the [MutableVector] and returns `true` if anything was removed. */ fun removeAll(elements: MutableVector<T>): Boolean { val initialSize = size for (i in 0..elements.lastIndex) { remove(elements.get(i)) } return initialSize != size } /** * Removes all [elements] from the [MutableVector] and returns `true` if anything was removed. */ fun removeAll(elements: Collection<T>): Boolean { if (elements.isEmpty()) { return false } val initialSize = size elements.forEach { remove(it) } return initialSize != size } /** * Removes the element at the given [index] and returns it. */ fun removeAt(index: Int): T { val content = content val item = content[index] as T if (index != lastIndex) { content.copyInto( destination = content, destinationOffset = index, startIndex = index + 1, endIndex = size ) } size-- content[size] = null return item } /** * Removes items from index [start] (inclusive) to [end] (exclusive). */ fun removeRange(start: Int, end: Int) { if (end > start) { if (end < size) { content.copyInto( destination = content, destinationOffset = start, startIndex = end, endIndex = size ) } val newSize = size - (end - start) for (i in newSize..lastIndex) { content[i] = null // clean up the removed items } size = newSize } } /** * Keeps only [elements] in the [MutableVector] and removes all other values. */ fun retainAll(elements: Collection<T>): Boolean { val initialSize = size for (i in lastIndex downTo 0) { val item = get(i) if (item !in elements) { removeAt(i) } } return initialSize != size } /** * Sets the value at [index] to [element]. */ operator fun set(index: Int, element: T): T { val content = content val old = content[index] as T content[index] = element return old } /** * Sorts the [MutableVector] using [comparator] to order the items. */ fun sortWith(comparator: Comparator<T>) { (content as Array<T>).sortWith(comparator = comparator, fromIndex = 0, toIndex = size) } /** * Returns the sum of all values produced by [selector] for each element in the * [MutableVector]. */ inline fun sumBy(selector: (T) -> Int): Int { contract { callsInPlace(selector) } var sum = 0 val size = size if (size > 0) { val content = content as Array<T> var i = 0 do { sum += selector(content[i]) i++ } while (i < size) } return sum } @PublishedApi internal fun throwNoSuchElementException(): Nothing { throw NoSuchElementException("MutableVector contains no element matching the predicate.") } private class VectorListIterator<T>( private val list: MutableList<T>, private var index: Int ) : MutableListIterator<T> { override fun hasNext(): Boolean { return index < list.size } override fun next(): T { return list[index++] } override fun remove() { index-- list.removeAt(index) } override fun hasPrevious(): Boolean { return index > 0 } override fun nextIndex(): Int { return index } override fun previous(): T { index-- return list[index] } override fun previousIndex(): Int { return index - 1 } override fun add(element: T) { list.add(index, element) index++ } override fun set(element: T) { list[index] = element } } /** * [MutableList] implementation for a [MutableVector], used in [asMutableList]. */ private class MutableVectorList<T>(private val vector: MutableVector<T>) : MutableList<T> { override val size: Int get() = vector.size override fun contains(element: T): Boolean = vector.contains(element) override fun containsAll(elements: Collection<T>): Boolean = vector.containsAll(elements) override fun get(index: Int): T { checkIndex(index) return vector[index] } override fun indexOf(element: T): Int = vector.indexOf(element) override fun isEmpty(): Boolean = vector.isEmpty() override fun iterator(): MutableIterator<T> = VectorListIterator(this, 0) override fun lastIndexOf(element: T): Int = vector.lastIndexOf(element) override fun add(element: T): Boolean = vector.add(element) override fun add(index: Int, element: T) = vector.add(index, element) override fun addAll(index: Int, elements: Collection<T>): Boolean = vector.addAll(index, elements) override fun addAll(elements: Collection<T>): Boolean = vector.addAll(elements) override fun clear() = vector.clear() override fun listIterator(): MutableListIterator<T> = VectorListIterator(this, 0) override fun listIterator(index: Int): MutableListIterator<T> = VectorListIterator(this, index) override fun remove(element: T): Boolean = vector.remove(element) override fun removeAll(elements: Collection<T>): Boolean = vector.removeAll(elements) override fun removeAt(index: Int): T { checkIndex(index) return vector.removeAt(index) } override fun retainAll(elements: Collection<T>): Boolean = vector.retainAll(elements) override fun set(index: Int, element: T): T { checkIndex(index) return vector.set(index, element) } override fun subList(fromIndex: Int, toIndex: Int): MutableList<T> { checkSubIndex(fromIndex, toIndex) return SubList(this, fromIndex, toIndex) } } /** * A view into an underlying [MutableList] that directly accesses the underlying [MutableList]. * This is important for the implementation of [List.subList]. A change to the [SubList] * also changes the referenced [MutableList]. */ private class SubList<T>( private val list: MutableList<T>, private val start: Int, private var end: Int ) : MutableList<T> { override val size: Int get() = end - start override fun contains(element: T): Boolean { for (i in start until end) { if (list[i] == element) { return true } } return false } override fun containsAll(elements: Collection<T>): Boolean { elements.forEach { if (!contains(it)) { return false } } return true } override fun get(index: Int): T { checkIndex(index) return list[index + start] } override fun indexOf(element: T): Int { for (i in start until end) { if (list[i] == element) { return i - start } } return -1 } override fun isEmpty(): Boolean = end == start override fun iterator(): MutableIterator<T> = VectorListIterator(this, 0) override fun lastIndexOf(element: T): Int { for (i in end - 1 downTo start) { if (list[i] == element) { return i - start } } return -1 } override fun add(element: T): Boolean { list.add(end++, element) return true } override fun add(index: Int, element: T) { list.add(index + start, element) end++ } override fun addAll(index: Int, elements: Collection<T>): Boolean { list.addAll(index + start, elements) end += elements.size return elements.size > 0 } override fun addAll(elements: Collection<T>): Boolean { list.addAll(end, elements) end += elements.size return elements.size > 0 } override fun clear() { for (i in end - 1 downTo start) { list.removeAt(i) } end = start } override fun listIterator(): MutableListIterator<T> = VectorListIterator(this, 0) override fun listIterator(index: Int): MutableListIterator<T> = VectorListIterator(this, index) override fun remove(element: T): Boolean { for (i in start until end) { if (list[i] == element) { list.removeAt(i) end-- return true } } return false } override fun removeAll(elements: Collection<T>): Boolean { val originalEnd = end elements.forEach { remove(it) } return originalEnd != end } override fun removeAt(index: Int): T { checkIndex(index) val item = list.removeAt(index + start) end-- return item } override fun retainAll(elements: Collection<T>): Boolean { val originalEnd = end for (i in end - 1 downTo start) { val item = list[i] if (item !in elements) { list.removeAt(i) end-- } } return originalEnd != end } override fun set(index: Int, element: T): T { checkIndex(index) return list.set(index + start, element) } override fun subList(fromIndex: Int, toIndex: Int): MutableList<T> { checkSubIndex(fromIndex, toIndex) return SubList(this, fromIndex, toIndex) } } } private fun List<*>.checkIndex(index: Int) { val size = size if (index < 0 || index >= size) { throw IndexOutOfBoundsException("Index $index is out of bounds. " + "The list has $size elements.") } } private fun List<*>.checkSubIndex(fromIndex: Int, toIndex: Int) { val size = size if (fromIndex > toIndex) { throw IllegalArgumentException("Indices are out of order. fromIndex ($fromIndex) is " + "greater than toIndex ($toIndex).") } if (fromIndex < 0) { throw IndexOutOfBoundsException("fromIndex ($fromIndex) is less than 0.") } if (toIndex > size) { throw IndexOutOfBoundsException( "toIndex ($toIndex) is more than than the list size ($size)" ) } } /** * Create a [MutableVector] with a given initial [capacity]. * * @see MutableVector.ensureCapacity */ inline fun <reified T> MutableVector(capacity: Int = 16) = MutableVector<T>(arrayOfNulls<T>(capacity), 0) /** * Create a [MutableVector] with a given [size], initializing each element using the [init] * function. * * [init] is called for each element in the [MutableVector], starting from the first one and should * return the value to be assigned to the element at its given index. */ @OptIn(ExperimentalContracts::class) inline fun <reified T> MutableVector(size: Int, noinline init: (Int) -> T): MutableVector<T> { contract { callsInPlace(init) } val arr = Array(size, init) return MutableVector(arr as Array<T?>, size) } /** * Creates an empty [MutableVector] with a [capacity][MutableVector.ensureCapacity] of 16. */ inline fun <reified T> mutableVectorOf() = MutableVector<T>() /** * Creates a [MutableVector] with the given values. This will use the passed vararg [elements] * storage. */ inline fun <reified T> mutableVectorOf(vararg elements: T): MutableVector<T> { return MutableVector( elements as Array<T?>, elements.size ) }
apache-2.0
fef26b5d1198ea0d19190c286dc8e3cc
28.28751
99
0.53194
4.52708
false
false
false
false
Nunnery/MythicDrops
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/settings/language/MythicRepairingMessages.kt
1
2187
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2019 Richard Harrah * * Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.tealcube.minecraft.bukkit.mythicdrops.settings.language import com.squareup.moshi.JsonClass import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.language.RepairingMessages import com.tealcube.minecraft.bukkit.mythicdrops.getNonNullString import org.bukkit.configuration.ConfigurationSection @JsonClass(generateAdapter = true) data class MythicRepairingMessages internal constructor( override val cannotUse: String = "", override val doNotHave: String = "", override val success: String = "", override val instructions: String = "" ) : RepairingMessages { companion object { fun fromConfigurationSection(configurationSection: ConfigurationSection) = MythicRepairingMessages( configurationSection.getNonNullString("cannot-use"), configurationSection.getNonNullString("do-not-have"), configurationSection.getNonNullString("success"), configurationSection.getNonNullString("instructions") ) } }
mit
3af82241470de0d8ae5b2e21d470237c
48.704545
107
0.763603
4.936795
false
true
false
false
MeilCli/Twitter4HK
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/data/Entity.kt
1
990
package com.twitter.meil_mitu.twitter4hk.data import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException import com.twitter.meil_mitu.twitter4hk.util.JsonUtils.getInt import com.twitter.meil_mitu.twitter4hk.util.JsonUtils.getJSONArray import org.json.JSONObject open class Entity { val start: Int val end: Int @Throws(Twitter4HKException::class) constructor(obj: JSONObject) { val ar = getJSONArray(obj, "indices") start = getInt(ar, 0) end = getInt(ar, 1) } override fun toString(): String { return "Entity{Start=$start, End=$end}" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Entity) return false if (end != other.end) return false if (start != other.start) return false return true } override fun hashCode(): Int { var result = start result = 31 * result + end return result } }
mit
c198e3a1a2e13dff2aab9af2ba7f6e18
23.75
69
0.643434
3.928571
false
false
false
false
McGars/basekitk
basekitk/src/main/kotlin/com/mcgars/basekitk/tools/ViewExtention.kt
1
1510
package com.mcgars.basekitk.tools import androidx.annotation.LayoutRes import android.view.LayoutInflater import android.view.View import android.view.ViewGroup fun View.paddingFast( left: Int = paddingLeft, top: Int = paddingTop, right: Int = paddingRight, bottom: Int = paddingBottom ) { setPadding( left, top, right, bottom ) } /** * Inflate view */ fun <T : View> View.inflate(layout: Int, parent: ViewGroup? = null) = context.inflate<T>(layout, parent) fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View { return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot) } fun View.offsetForStatusBarByMargin() { val offset = context.getStatusBarHeight() if (offset == 0) return val params = layoutParams as ViewGroup.MarginLayoutParams params.topMargin = offset } fun <T : View> Array<out T>.offsetForStatusBarByMargin() { if (!this.iterator().hasNext()) return val offset = first().context.getStatusBarHeight() if (offset == 0) return forEach { val params = it.layoutParams as ViewGroup.MarginLayoutParams params.topMargin = offset } } fun <T : View> Array<out T>.offsetForStatusBarByPadding() { if (!this.iterator().hasNext()) return val offset = first().context.getStatusBarHeight() if (offset == 0) return forEach { it.paddingFast(top = offset + it.paddingTop) } }
apache-2.0
d4b8c7f1580ecc70a204cba60cadb0ce
22.246154
104
0.662914
4.206128
false
false
false
false
nimakro/tornadofx
src/main/java/tornadofx/Binding.kt
1
8215
@file:Suppress("UNCHECKED_CAST", "CAST_NEVER_SUCCEEDS") package tornadofx import javafx.beans.binding.Bindings import javafx.beans.binding.BooleanBinding import javafx.beans.binding.BooleanExpression import javafx.beans.property.Property import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleObjectProperty import javafx.beans.property.StringProperty import javafx.beans.value.ChangeListener import javafx.beans.value.ObservableValue import javafx.beans.value.WritableValue import javafx.collections.FXCollections import javafx.collections.ObservableList import javafx.scene.control.* import javafx.scene.text.Text import javafx.util.StringConverter import javafx.util.converter.* import java.math.BigDecimal import java.math.BigInteger import java.text.Format import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.util.* import java.util.concurrent.Callable private fun <T> Property<T>.internalBind(property: ObservableValue<T>, readonly: Boolean) { ViewModel.register(this, property) if (readonly || (property !is Property<*>)) bind(property) else bindBidirectional(property as Property<T>) } fun <T> ComboBoxBase<T>.bind(property: ObservableValue<T>, readonly: Boolean = false) = valueProperty().internalBind(property, readonly) fun DatePicker.bind(property: ObservableValue<LocalDate>, readonly: Boolean = false) = valueProperty().internalBind(property, readonly) fun ProgressIndicator.bind(property: ObservableValue<Number>, readonly: Boolean = false) = progressProperty().internalBind(property, readonly) fun <T> ChoiceBox<T>.bind(property: ObservableValue<T>, readonly: Boolean = false) = valueProperty().internalBind(property, readonly) fun CheckBox.bind(property: ObservableValue<Boolean>, readonly: Boolean = false) = selectedProperty().internalBind(property, readonly) fun CheckMenuItem.bind(property: ObservableValue<Boolean>, readonly: Boolean = false) = selectedProperty().internalBind(property, readonly) fun Slider.bind(property: ObservableValue<Number>, readonly: Boolean = false) = valueProperty().internalBind(property, readonly) fun <T> Spinner<T>.bind(property: ObservableValue<T>, readonly: Boolean = false) = valueFactory.valueProperty().internalBind(property, readonly) inline fun <reified S : T, reified T : Any> Labeled.bind( property: ObservableValue<S>, readonly: Boolean = false, converter: StringConverter<T>? = null, format: Format? = null ) { bindStringProperty(textProperty(), converter, format, property, readonly) } inline fun <reified S : T, reified T : Any> TitledPane.bind( property: ObservableValue<S>, readonly: Boolean = false, converter: StringConverter<T>? = null, format: Format? = null ) = bindStringProperty(textProperty(), converter, format, property, readonly) inline fun <reified S : T, reified T : Any> Text.bind( property: ObservableValue<S>, readonly: Boolean = false, converter: StringConverter<T>? = null, format: Format? = null ) = bindStringProperty(textProperty(), converter, format, property, readonly) inline fun <reified S : T, reified T : Any> TextInputControl.bind( property: ObservableValue<S>, readonly: Boolean = false, converter: StringConverter<T>? = null, format: Format? = null ) = bindStringProperty(textProperty(), converter, format, property, readonly) inline fun <reified S : T, reified T : Any> bindStringProperty( stringProperty: StringProperty, converter: StringConverter<T>?, format: Format?, property: ObservableValue<S>, readonly: Boolean ) { if (stringProperty.isBound) stringProperty.unbind() val effectiveReadonly = readonly || property !is Property<S> || S::class != T::class ViewModel.register(stringProperty, property) if (S::class == String::class) when { effectiveReadonly -> stringProperty.bind(property as ObservableValue<String>) else -> stringProperty.bindBidirectional(property as Property<String>) } else { val effectiveConverter = if (format != null) null else converter ?: getDefaultConverter<S>() if (effectiveReadonly) { val toStringConverter = Callable { when { converter != null -> converter.toString(property.value) format != null -> format.format(property.value) else -> property.value?.toString() } } val stringBinding = Bindings.createStringBinding(toStringConverter, property) stringProperty.bind(stringBinding) } else when { effectiveConverter != null -> stringProperty.bindBidirectional(property as Property<S>, effectiveConverter as StringConverter<S>) format != null -> stringProperty.bindBidirectional(property as Property<S>, format) else -> throw IllegalArgumentException("Cannot convert from ${S::class} to String without an explicit converter or format") } } } inline fun <reified T : Any> getDefaultConverter() = when (T::class.javaPrimitiveType ?: T::class) { Int::class.javaPrimitiveType -> IntegerStringConverter() Long::class.javaPrimitiveType -> LongStringConverter() Double::class.javaPrimitiveType -> DoubleStringConverter() Float::class.javaPrimitiveType -> FloatStringConverter() Date::class -> DateStringConverter() BigDecimal::class -> BigDecimalStringConverter() BigInteger::class -> BigIntegerStringConverter() Number::class -> NumberStringConverter() LocalDate::class -> LocalDateStringConverter() LocalTime::class -> LocalTimeStringConverter() LocalDateTime::class -> LocalDateTimeStringConverter() Boolean::class.javaPrimitiveType -> BooleanStringConverter() else -> null } as StringConverter<T>? fun ObservableValue<Boolean>.toBinding() = object : BooleanBinding() { init { super.bind(this@toBinding) } override fun dispose() { super.unbind(this@toBinding) } override fun computeValue() = [email protected] override fun getDependencies(): ObservableList<*> = FXCollections.singletonObservableList(this@toBinding) } fun <T, N> ObservableValue<T>.select(nested: (T) -> ObservableValue<N>): Property<N> { fun extractNested(): ObservableValue<N>? = value?.let(nested) var currentNested: ObservableValue<N>? = extractNested() return object : SimpleObjectProperty<N>() { val changeListener = ChangeListener<Any?> { _, _, _ -> invalidated() fireValueChangedEvent() } init { currentNested?.addListener(changeListener) [email protected](changeListener) } override fun invalidated() { currentNested?.removeListener(changeListener) currentNested = extractNested() currentNested?.addListener(changeListener) } override fun get() = currentNested?.value override fun set(v: N?) { (currentNested as? WritableValue<N>)?.value = v super.set(v) } } } fun <T> ObservableValue<T>.selectBoolean(nested: (T) -> BooleanExpression): BooleanExpression { fun extractNested() = nested(value) val dis = this var currentNested = extractNested() return object : SimpleBooleanProperty() { val changeListener = ChangeListener<Boolean> { _, _, _ -> currentNested = extractNested() fireValueChangedEvent() } init { dis.onChange { fireValueChangedEvent() invalidated() } } override fun invalidated() { currentNested.removeListener(changeListener) currentNested = extractNested() currentNested.addListener(changeListener) } override fun getValue() = currentNested.value override fun setValue(v: Boolean?) { (currentNested as? WritableValue<*>)?.value = v super.setValue(v) } } }
apache-2.0
7cb673f10ab0dd24213759567ff98ace
35.511111
141
0.683628
4.818182
false
false
false
false
stoyicker/dinger
data/src/main/kotlin/data/tinder/recommendation/RecommendationUserSpotifyThemeTrackEntity.kt
1
808
package data.tinder.recommendation import android.arch.persistence.room.Entity import android.arch.persistence.room.ForeignKey import android.arch.persistence.room.Index import android.arch.persistence.room.PrimaryKey @Entity(indices = [Index("id"), Index("album")], foreignKeys = [ForeignKey( entity = RecommendationUserSpotifyThemeTrackAlbumEntity::class, parentColumns = ["id"], childColumns = ["album"])]) internal class RecommendationUserSpotifyThemeTrackEntity( var album: String, var previewUrl: String?, var name: String, @PrimaryKey var id: String, var uri: String) { companion object { val NONE = RecommendationUserSpotifyThemeTrackEntity(album = "", previewUrl = null, name = "", id = "", uri = "") } }
mit
91607990b9262070dbd7573037d50215
28.925926
71
0.685644
4.464088
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/util/MagnetUri.kt
1
2573
package org.andstatus.app.util import android.net.Uri import io.vavr.control.Try import java.net.URL /** * Magnet URI scheme: https://en.wikipedia.org/wiki/Magnet_URI_scheme * * Feature discussion: https://github.com/andstatus/andstatus/issues/535 * Related discussion: https://socialhub.activitypub.rocks/t/content-addressing-and-urn-resolution/1674 */ data class MagnetUri(val dn: String, val xt: List<Uri>, val xs: Uri) { companion object { fun Uri.getDownloadableUrl(): URL? = takeIf { UriUtils.isDownloadable(it) } ?.let { uri -> uri.toString().tryMargetUri().map(MagnetUri::xs).getOrElse(uri) } ?.let { URL(it.toString()) } fun String?.tryMargetUri(): Try<MagnetUri> = this?.trim() ?.split("magnet:?") ?.takeIf { it.size == 2 && it.get(0).isEmpty() } ?.get(1) ?.let { Try.success(it) } ?.flatMap(::parseData) ?: TryUtils.notFound() private fun parseData(data: String): Try<MagnetUri> { val params = data.split("&") .fold(HashMap<String, List<String>>()) { acc, param -> val parts = param.split('=', ignoreCase = false, limit = 2) if (parts.size == 2) { val name = parts[0].let { nn -> val nameParts = nn.split('.', ignoreCase = false, limit = 2) if (nameParts.size == 2 && nameParts[0].isNotEmpty()) nameParts[0] else nn } val value = parts[1] if (value.isNotEmpty()) { acc.compute(name) { k, v -> v?.let { v + value } ?: listOf(value) } } } acc } return params["xs"] ?.mapNotNull { it -> UriUtils.toDownloadableOptional(it).orElseGet { -> null } } ?.firstOrNull() ?.let { xs -> val dn = params["dn"]?.firstOrNull() ?: "" val xt = params["xt"] ?.mapNotNull { it -> UriUtils.toOptional(it).orElseGet { -> null } } ?: emptyList() Try.success(MagnetUri(dn, xt, xs)) } ?: TryUtils.failure("Failed to parse Magnet URI data: '$data'") } } }
apache-2.0
fa6462dd3f8a91f57c5c08665b450068
38.584615
103
0.456277
4.451557
false
false
false
false
Ribesg/Purpur
src/main/kotlin/fr/ribesg/minecraft/purpur/Log.kt
1
2169
package fr.ribesg.minecraft.purpur import java.util.logging.ConsoleHandler import java.util.logging.Handler import java.util.logging.Level import java.util.logging.Logger /** * @author Ribesg */ internal object Log { private val logger: Logger init { logger = Logger.getLogger("Purpur") System.setProperty( "java.util.logging.SimpleFormatter.format", "%n%5\$s %6\$s" ) for (h in logger.handlers) { logger.removeHandler(h); } logger.addHandler(object : ConsoleHandler() { init { this.setOutputStream(System.out); this.level = Level.ALL; } }); Runtime.getRuntime().addShutdownHook(Thread { Log.info("") }) } fun isDebugEnabled(): Boolean = logger.isLoggable(Level.FINEST) fun setDebugEnabled(value: Boolean) { logger.level = if (value) Level.FINEST else Level.INFO } fun isServerLogEnabled(): Boolean = logger.isLoggable(Level.FINE) fun setServerLogEnabled(value: Boolean) { logger.level = if (value) Level.FINE else Level.INFO } fun debug(message: Any) { logger.log(Level.FINEST, "[PURPUR] " + message.toString()) } fun debug(message: Any, t: Throwable) { logger.log(Level.FINEST, "[PURPUR] " + message.toString(), t) } fun info(message: Any? = null) { if (message == null || "".equals(message.toString())) { logger.log(Level.INFO, "") } else { logger.log(Level.INFO, "[PURPUR] " + message.toString()) } } fun server(serverLogLine: String) { logger.log(Level.FINE, "[SERVER] " + serverLogLine) } fun error(message: Any) { logger.log(Level.SEVERE, "[PURPUR] " + message.toString()) flush() } fun error(message: Any, t: Throwable) { logger.log(Level.SEVERE, "[PURPUR] " + message.toString(), t) flush() } fun error(t: Throwable) { logger.log(Level.SEVERE, "[PURPUR] Error caught", t) flush() } fun flush() { logger.handlers.forEach(Handler::flush) } }
agpl-3.0
6354655ed0b80f5e08de2423599d3504
24.517647
69
0.57953
3.873214
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/widgets/dialog/LanguageBottomSheetDialog.kt
2
2542
package ru.fantlab.android.ui.widgets.dialog import android.content.Context import android.os.Bundle import android.view.Gravity import android.view.View import android.view.ViewGroup import android.widget.RadioButton import android.widget.RadioGroup import kotlinx.android.synthetic.main.picker_dialog.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.AppLanguageModel import ru.fantlab.android.helper.PrefGetter import ru.fantlab.android.ui.base.BaseBottomSheetDialog import kotlin.reflect.KFunction0 class LanguageBottomSheetDialog : BaseBottomSheetDialog() { private var callback: LanguageDialogViewActionCallback? = null interface LanguageDialogViewActionCallback { fun onLanguageChanged() } override fun onAttach(context: Context) { super.onAttach(context) if (parentFragment != null && parentFragment is LanguageDialogViewActionCallback) { callback = parentFragment as LanguageDialogViewActionCallback } else if (context is LanguageDialogViewActionCallback) { callback = context } } override fun onDetach() { super.onDetach() callback = null } override fun layoutRes(): Int { return R.layout.picker_dialog } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val language = PrefGetter.getAppLanguage() val values = resources.getStringArray(R.array.languages_array_values) val padding = resources.getDimensionPixelSize(R.dimen.spacing_xs_large) resources.getStringArray(R.array.languages_array) .mapIndexed { index, string -> AppLanguageModel(values[index], string) } .sortedBy { it.label } .forEachIndexed { index, appLanguageModel -> val radioButtonView = RadioButton(context) val params = RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) radioButtonView.layoutParams = params radioButtonView.text = appLanguageModel.label radioButtonView.id = index radioButtonView.tag = appLanguageModel.value radioButtonView.gravity = Gravity.CENTER_VERTICAL radioButtonView.setPadding(padding, padding, padding, padding) picker.addView(radioButtonView) if (appLanguageModel.value.equals(language, ignoreCase = true)) picker.check(index) } picker.setOnCheckedChangeListener { group, checkedId -> val tag = picker.getChildAt(checkedId).tag as String if (!tag.equals(language, ignoreCase = true)) { PrefGetter.setAppLanguage(tag) dismiss() callback?.onLanguageChanged() } } } }
gpl-3.0
7f61c0f9d12802af2392f78c65407f19
33.364865
115
0.776554
4.174056
false
false
false
false
inorichi/tachiyomi-extensions
src/fr/furyosquad/src/eu/kanade/tachiyomi/extension/fr/furyosquad/FuryoSquad.kt
1
9205
package eu.kanade.tachiyomi.extension.fr.furyosquad import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import rx.Observable import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale import java.util.concurrent.TimeUnit class FuryoSquad : ParsedHttpSource() { override val name = "FuryoSquad" override val baseUrl = "https://www.furyosquad.com/" override val lang = "fr" override val supportsLatest = true private val rateLimitInterceptor = RateLimitInterceptor(1) override val client: OkHttpClient = network.cloudflareClient.newBuilder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .addNetworkInterceptor(rateLimitInterceptor) .build() // Popular override fun popularMangaRequest(page: Int): Request { return GET("$baseUrl/mangas", headers) } override fun popularMangaSelector() = "div#fs-tous div.fs-card-body" override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() with(element) { manga.url = select("div.fs-card-img-container a").attr("href") manga.title = select("span.fs-comic-title a").text() manga.thumbnail_url = select("div.fs-card-img-container img").attr("abs:src") } return manga } override fun popularMangaNextPageSelector() = "Not needed" // Latest override fun latestUpdatesRequest(page: Int): Request { return GET(baseUrl, headers) } override fun latestUpdatesParse(response: Response): MangasPage { val document = response.asJsoup() val mangas = mutableListOf<SManga>() document.select(latestUpdatesSelector()).map { mangas.add(latestUpdatesFromElement(it)) } return MangasPage(mangas.distinctBy { it.url }, false) } override fun latestUpdatesSelector() = "table.table-striped tr" override fun latestUpdatesFromElement(element: Element): SManga { val manga = SManga.create() with(element) { manga.url = select("span.fs-comic-title a").attr("href") manga.title = select("span.fs-comic-title a").text() manga.thumbnail_url = select("img.fs-chap-img").attr("abs:src") } return manga } override fun latestUpdatesNextPageSelector() = "not needed" // Search override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> { return client.newCall(searchMangaRequest(page, query, filters)) .asObservableSuccess() .map { response -> searchMangaParse(response, query) } } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = popularMangaRequest(1) private fun searchMangaParse(response: Response, query: String): MangasPage { return MangasPage(popularMangaParse(response).mangas.filter { it.title.contains(query, ignoreCase = true) }, false) } override fun searchMangaSelector() = throw UnsupportedOperationException("Not used") override fun searchMangaFromElement(element: Element): SManga = throw UnsupportedOperationException("Not used") override fun searchMangaNextPageSelector() = throw UnsupportedOperationException("Not used") // Details override fun mangaDetailsParse(document: Document): SManga { val manga = SManga.create() document.select("div.comic-info").let { it.select("p.fs-comic-label").forEach { el -> when (el.text().toLowerCase(Locale.ROOT)) { "scénario" -> manga.author = el.nextElementSibling().text() "dessins" -> manga.artist = el.nextElementSibling().text() "genre" -> manga.genre = el.nextElementSibling().text() } } manga.description = it.select("div.fs-comic-description").text() manga.thumbnail_url = it.select("img.comic-cover").attr("abs:src") } return manga } // Chapters override fun chapterListSelector() = "div.fs-chapter-list div.element" override fun chapterFromElement(element: Element): SChapter { val chapter = SChapter.create() chapter.url = element.select("div.title a").attr("href") chapter.name = element.select("div.title a").attr("title") chapter.date_upload = parseChapterDate(element.select("div.meta_r").text()) return chapter } private fun parseChapterDate(date: String): Long { val lcDate = date.toLowerCase(Locale.ROOT) if (lcDate.startsWith("il y a")) parseRelativeDate(lcDate).let { return it } // Handle 'day before yesterday', yesterday' and 'today', using midnight var relativeDate: Calendar? = null // Result parsed but no year, copy current year over when { lcDate.startsWith("avant-hier") -> { relativeDate = Calendar.getInstance() relativeDate.add(Calendar.DAY_OF_MONTH, -2) // day before yesterday relativeDate.set(Calendar.HOUR_OF_DAY, 0) relativeDate.set(Calendar.MINUTE, 0) relativeDate.set(Calendar.SECOND, 0) relativeDate.set(Calendar.MILLISECOND, 0) } lcDate.startsWith("hier") -> { relativeDate = Calendar.getInstance() relativeDate.add(Calendar.DAY_OF_MONTH, -1) // yesterday relativeDate.set(Calendar.HOUR_OF_DAY, 0) relativeDate.set(Calendar.MINUTE, 0) relativeDate.set(Calendar.SECOND, 0) relativeDate.set(Calendar.MILLISECOND, 0) } lcDate.startsWith("aujourd'hui") -> { relativeDate = Calendar.getInstance() relativeDate.set(Calendar.HOUR_OF_DAY, 0) // today relativeDate.set(Calendar.MINUTE, 0) relativeDate.set(Calendar.SECOND, 0) relativeDate.set(Calendar.MILLISECOND, 0) } } return relativeDate?.timeInMillis ?: 0L } private fun parseRelativeDate(date: String): Long { val value = date.split(" ")[3].toIntOrNull() return if (value != null) { when (date.split(" ")[4]) { "minute", "minutes" -> Calendar.getInstance().apply { add(Calendar.MINUTE, value * -1) set(Calendar.SECOND, 0) set(Calendar.MILLISECOND, 0) }.timeInMillis "heure", "heures" -> Calendar.getInstance().apply { add(Calendar.HOUR_OF_DAY, value * -1) set(Calendar.SECOND, 0) set(Calendar.MILLISECOND, 0) }.timeInMillis "jour", "jours" -> Calendar.getInstance().apply { add(Calendar.DATE, value * -1) set(Calendar.SECOND, 0) set(Calendar.MILLISECOND, 0) }.timeInMillis "semaine", "semaines" -> Calendar.getInstance().apply { add(Calendar.DATE, value * 7 * -1) set(Calendar.SECOND, 0) set(Calendar.MILLISECOND, 0) }.timeInMillis "mois" -> Calendar.getInstance().apply { add(Calendar.MONTH, value * -1) set(Calendar.SECOND, 0) set(Calendar.MILLISECOND, 0) }.timeInMillis "an", "ans", "année", "années" -> Calendar.getInstance().apply { add(Calendar.YEAR, value * -1) set(Calendar.SECOND, 0) set(Calendar.MILLISECOND, 0) }.timeInMillis else -> { return 0L } } } else { try { SimpleDateFormat("dd MMM yyyy", Locale.FRENCH).parse(date.substringAfter("le "))?.time ?: 0 } catch (_: Exception) { 0L } } } // Pages override fun pageListParse(document: Document): List<Page> { val pages = mutableListOf<Page>() document.select("div.fs-read img[id]").forEachIndexed { i, img -> pages.add(Page(i, "", img.attr("abs:src"))) } return pages } override fun imageUrlParse(document: Document) = throw UnsupportedOperationException("Not used") override fun getFilterList() = FilterList() }
apache-2.0
2478b5ded9d1e3f0b21323524f21c139
35.228346
123
0.604869
4.656883
false
false
false
false
inorichi/tachiyomi-extensions
multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/wpmangastream/WPMangaStream.kt
1
19328
package eu.kanade.tachiyomi.multisrc.wpmangastream import android.app.Application import android.content.SharedPreferences import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.ConfigurableSource import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import kotlinx.serialization.json.Json import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonPrimitive import okhttp3.Headers import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import org.jsoup.select.Elements import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import uy.kohesive.injekt.injectLazy import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale import java.util.concurrent.TimeUnit abstract class WPMangaStream( override val name: String, override val baseUrl: String, override val lang: String, private val dateFormat: SimpleDateFormat = SimpleDateFormat("MMM d, yyyy", Locale.US) ) : ConfigurableSource, ParsedHttpSource() { override val supportsLatest = true companion object { private const val MID_QUALITY = 1 private const val LOW_QUALITY = 2 private const val SHOW_THUMBNAIL_PREF_Title = "Default thumbnail quality" private const val SHOW_THUMBNAIL_PREF = "showThumbnailDefault" } private val preferences: SharedPreferences by lazy { Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000) } override fun setupPreferenceScreen(screen: androidx.preference.PreferenceScreen) { val thumbsPref = androidx.preference.ListPreference(screen.context).apply { key = SHOW_THUMBNAIL_PREF_Title title = SHOW_THUMBNAIL_PREF_Title entries = arrayOf("Show high quality", "Show mid quality", "Show low quality") entryValues = arrayOf("0", "1", "2") summary = "%s" setOnPreferenceChangeListener { _, newValue -> val selected = newValue as String val index = this.findIndexOfValue(selected) preferences.edit().putInt(SHOW_THUMBNAIL_PREF, index).commit() } } screen.addPreference(thumbsPref) } private fun getShowThumbnail(): Int = preferences.getInt(SHOW_THUMBNAIL_PREF, 0) override val client: OkHttpClient = network.cloudflareClient.newBuilder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build() protected fun Element.imgAttr(): String = if (this.hasAttr("data-src")) this.attr("abs:data-src") else this.attr("abs:src") protected fun Elements.imgAttr(): String = this.first().imgAttr() private val json: Json by injectLazy() override fun popularMangaRequest(page: Int): Request { return GET("$baseUrl/manga/?page=$page&order=popular", headers) } override fun latestUpdatesRequest(page: Int): Request { return GET("$baseUrl/manga/?page=$page&order=update", headers) } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { var url = "$baseUrl/manga/".toHttpUrlOrNull()!!.newBuilder() url.addQueryParameter("title", query) url.addQueryParameter("page", page.toString()) filters.forEach { filter -> when (filter) { is AuthorFilter -> { url.addQueryParameter("author", filter.state) } is YearFilter -> { url.addQueryParameter("yearx", filter.state) } is StatusFilter -> { val status = when (filter.state) { Filter.TriState.STATE_INCLUDE -> "completed" Filter.TriState.STATE_EXCLUDE -> "ongoing" else -> "" } url.addQueryParameter("status", status) } is TypeFilter -> { url.addQueryParameter("type", filter.toUriPart()) } is SortByFilter -> { url.addQueryParameter("order", filter.toUriPart()) } is GenreListFilter -> { filter.state .filter { it.state != Filter.TriState.STATE_IGNORE } .forEach { url.addQueryParameter("genre[]", it.id) } } // if site has project page, default value "hasProjectPage" = false is ProjectFilter -> { if (filter.toUriPart() == "project-filter-on") { url = "$baseUrl$projectPageString/page/$page".toHttpUrlOrNull()!!.newBuilder() } } } } return GET(url.build().toString(), headers) } open val projectPageString = "/project" override fun popularMangaSelector() = "div.bs" override fun latestUpdatesSelector() = popularMangaSelector() override fun searchMangaSelector() = popularMangaSelector() override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.thumbnail_url = element.select("div.limit img").imgAttr() element.select("div.bsx > a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.attr("title") } return manga } override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element) override fun latestUpdatesFromElement(element: Element): SManga = popularMangaFromElement(element) override fun popularMangaNextPageSelector(): String? = "a.next.page-numbers, a.r" override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector() override fun searchMangaNextPageSelector() = popularMangaNextPageSelector() override fun mangaDetailsParse(document: Document): SManga { return SManga.create().apply { document.select("div.bigcontent, div.animefull, div.main-info").firstOrNull()?.let { infoElement -> status = parseStatus(infoElement.select("span:contains(Status:), .imptdt:contains(Status) i").firstOrNull()?.ownText()) author = infoElement.select("span:contains(Author:), span:contains(Pengarang:), .fmed b:contains(Author)+span, .imptdt:contains(Author) i").firstOrNull()?.ownText() artist = infoElement.select(".fmed b:contains(Artist)+span, .imptdt:contains(Artist) i").firstOrNull()?.ownText() description = infoElement.select("div.desc p, div.entry-content p").joinToString("\n") { it.text() } thumbnail_url = infoElement.select("div.thumb img").imgAttr() val genres = infoElement.select("span:contains(Genre) a, .mgen a") .map { element -> element.text().toLowerCase() } .toMutableSet() // add series type(manga/manhwa/manhua/other) thinggy to genre document.select(seriesTypeSelector).firstOrNull()?.ownText()?.let { if (it.isEmpty().not() && genres.contains(it).not()) { genres.add(it.toLowerCase()) } } genre = genres.toList().map { it.capitalize() }.joinToString(", ") // add alternative name to manga description document.select(altNameSelector).firstOrNull()?.ownText()?.let { if (it.isEmpty().not() && it != "N/A" && it != "-") { description += when { description!!.isEmpty() -> altName + it else -> "\n\n$altName" + it } } } } } } open val seriesTypeSelector = "span:contains(Type) a, .imptdt:contains(Type) a, a[href*=type\\=], .infotable tr:contains(Type) td:last-child" open val altNameSelector = ".alternative, .wd-full:contains(Alt) span, .alter, .seriestualt" open val altName = "Alternative Name" + ": " protected open fun parseStatus(element: String?): Int = when { element == null -> SManga.UNKNOWN listOf("ongoing", "publishing").any { it.contains(element, ignoreCase = true) } -> SManga.ONGOING listOf("completed").any { it.contains(element, ignoreCase = true) } -> SManga.COMPLETED else -> SManga.UNKNOWN } override fun chapterListSelector() = "div.bxcl ul li, div.cl ul li, ul li:has(div.chbox):has(div.eph-num)" override fun chapterListParse(response: Response): List<SChapter> { val document = response.asJsoup() val chapters = document.select(chapterListSelector()).map { chapterFromElement(it) } // Add timestamp to latest chapter, taken from "Updated On". so source which not provide chapter timestamp will have atleast one val date = document.select(".fmed:contains(update) time ,span:contains(update) time").attr("datetime") val checkChapter = document.select(chapterListSelector()).firstOrNull() if (date != "" && checkChapter != null) chapters[0].date_upload = parseDate(date) return chapters } private fun parseDate(date: String): Long { return SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(date)?.time ?: 0L } override fun chapterFromElement(element: Element): SChapter { val urlElement = element.select(".lchx > a, span.leftoff a, div.eph-num > a").first() val chapter = SChapter.create() chapter.setUrlWithoutDomain(urlElement.attr("href")) chapter.name = if (urlElement.select("span.chapternum").isNotEmpty()) urlElement.select("span.chapternum").text() else urlElement.text() chapter.date_upload = element.select("span.rightoff, time, span.chapterdate").firstOrNull()?.text()?.let { parseChapterDate(it) } ?: 0 return chapter } fun parseChapterDate(date: String): Long { return if (date.contains("ago")) { val value = date.split(' ')[0].toInt() when { "min" in date -> Calendar.getInstance().apply { add(Calendar.MINUTE, value * -1) }.timeInMillis "hour" in date -> Calendar.getInstance().apply { add(Calendar.HOUR_OF_DAY, value * -1) }.timeInMillis "day" in date -> Calendar.getInstance().apply { add(Calendar.DATE, value * -1) }.timeInMillis "week" in date -> Calendar.getInstance().apply { add(Calendar.DATE, value * 7 * -1) }.timeInMillis "month" in date -> Calendar.getInstance().apply { add(Calendar.MONTH, value * -1) }.timeInMillis "year" in date -> Calendar.getInstance().apply { add(Calendar.YEAR, value * -1) }.timeInMillis else -> { 0L } } } else { try { dateFormat.parse(date)?.time ?: 0 } catch (_: Exception) { 0L } } } override fun prepareNewChapter(chapter: SChapter, manga: SManga) { val basic = Regex("""Chapter\s([0-9]+)""") when { basic.containsMatchIn(chapter.name) -> { basic.find(chapter.name)?.let { chapter.chapter_number = it.groups[1]?.value!!.toFloat() } } } } open val pageSelector = "div#readerarea img" override fun pageListParse(document: Document): List<Page> { val htmlPages = document.select(pageSelector) .filterNot { it.attr("abs:src").isNullOrEmpty() } .mapIndexed { i, img -> Page(i, "", img.attr("abs:src")) } .toMutableList() val docString = document.toString() val imageListRegex = Regex("\\\"images.*?:.*?(\\[.*?\\])") val imageListJson = imageListRegex.find(docString)!!.destructured.toList()[0] val imageList = json.parseToJsonElement(imageListJson).jsonArray val scriptPages = imageList.mapIndexed { i, jsonEl -> Page(i, "", jsonEl.jsonPrimitive.content) } if (htmlPages.size < scriptPages.size) { htmlPages += scriptPages } return htmlPages.distinctBy { it.imageUrl } } override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not used") override fun imageRequest(page: Page): Request { val headers = Headers.Builder() headers.apply { add("Accept", "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8") add("Referer", baseUrl) add("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/76.0.3809.100 Mobile Safari/537.36") } if (page.imageUrl!!.contains(".wp.com")) { headers.apply { set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3") } } return GET(getImageUrl(page.imageUrl!!, getShowThumbnail()), headers.build()) } private fun getImageUrl(originalUrl: String, quality: Int): String { val url = originalUrl.substringAfter("//") return when (quality) { LOW_QUALITY -> "https://images.weserv.nl/?w=300&q=70&url=$url" MID_QUALITY -> "https://images.weserv.nl/?w=600&q=70&url=$url" else -> originalUrl } } private class AuthorFilter : Filter.Text("Author") private class YearFilter : Filter.Text("Year") protected class TypeFilter : UriPartFilter( "Type", arrayOf( Pair("Default", ""), Pair("Manga", "Manga"), Pair("Manhwa", "Manhwa"), Pair("Manhua", "Manhua"), Pair("Comic", "Comic") ) ) protected class SortByFilter : UriPartFilter( "Sort By", arrayOf( Pair("Default", ""), Pair("A-Z", "title"), Pair("Z-A", "titlereverse"), Pair("Latest Update", "update"), Pair("Latest Added", "latest"), Pair("Popular", "popular") ) ) protected class StatusFilter : UriPartFilter( "Status", arrayOf( Pair("All", ""), Pair("Ongoing", "ongoing"), Pair("Completed", "completed") ) ) protected class ProjectFilter : UriPartFilter( "Filter Project", arrayOf( Pair("Show all manga", ""), Pair("Show only project manga", "project-filter-on") ) ) protected class Genre(name: String, val id: String = name) : Filter.TriState(name) protected class GenreListFilter(genres: List<Genre>) : Filter.Group<Genre>("Genre", genres) open val hasProjectPage = false override fun getFilterList(): FilterList { val filters = mutableListOf<Filter<*>>( Filter.Header("NOTE: Ignored if using text search!"), Filter.Header("Genre exclusion not available for all sources"), Filter.Separator(), AuthorFilter(), YearFilter(), StatusFilter(), TypeFilter(), SortByFilter(), GenreListFilter(getGenreList()), ) if (hasProjectPage) { filters.addAll( mutableListOf<Filter<*>>( Filter.Separator(), Filter.Header("NOTE: cant be used with other filter!"), Filter.Header("$name Project List page"), ProjectFilter(), ) ) } return FilterList(filters) } protected open fun getGenreList(): List<Genre> = listOf( Genre("4 Koma", "4-koma"), Genre("Action", "action"), Genre("Adult", "adult"), Genre("Adventure", "adventure"), Genre("Comedy", "comedy"), Genre("Completed", "completed"), Genre("Cooking", "cooking"), Genre("Crime", "crime"), Genre("Demon", "demon"), Genre("Demons", "demons"), Genre("Doujinshi", "doujinshi"), Genre("Drama", "drama"), Genre("Ecchi", "ecchi"), Genre("Fantasy", "fantasy"), Genre("Game", "game"), Genre("Games", "games"), Genre("Gender Bender", "gender-bender"), Genre("Gore", "gore"), Genre("Harem", "harem"), Genre("Historical", "historical"), Genre("Horror", "horror"), Genre("Isekai", "isekai"), Genre("Josei", "josei"), Genre("Magic", "magic"), Genre("Manga", "manga"), Genre("Manhua", "manhua"), Genre("Manhwa", "manhwa"), Genre("Martial Art", "martial-art"), Genre("Martial Arts", "martial-arts"), Genre("Mature", "mature"), Genre("Mecha", "mecha"), Genre("Military", "military"), Genre("Monster", "monster"), Genre("Monster Girls", "monster-girls"), Genre("Monsters", "monsters"), Genre("Music", "music"), Genre("Mystery", "mystery"), Genre("One-shot", "one-shot"), Genre("Oneshot", "oneshot"), Genre("Police", "police"), Genre("Pshycological", "pshycological"), Genre("Psychological", "psychological"), Genre("Reincarnation", "reincarnation"), Genre("Reverse Harem", "reverse-harem"), Genre("Romancce", "romancce"), Genre("Romance", "romance"), Genre("Samurai", "samurai"), Genre("School", "school"), Genre("School Life", "school-life"), Genre("Sci-fi", "sci-fi"), Genre("Seinen", "seinen"), Genre("Shoujo", "shoujo"), Genre("Shoujo Ai", "shoujo-ai"), Genre("Shounen", "shounen"), Genre("Shounen Ai", "shounen-ai"), Genre("Slice of Life", "slice-of-life"), Genre("Sports", "sports"), Genre("Super Power", "super-power"), Genre("Supernatural", "supernatural"), Genre("Thriller", "thriller"), Genre("Time Travel", "time-travel"), Genre("Tragedy", "tragedy"), Genre("Vampire", "vampire"), Genre("Webtoon", "webtoon"), Genre("Webtoons", "webtoons"), Genre("Yaoi", "yaoi"), Genre("Yuri", "yuri"), Genre("Zombies", "zombies") ) open class UriPartFilter(displayName: String, private val vals: Array<Pair<String, String>>) : Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) { fun toUriPart() = vals[state].second } }
apache-2.0
3ceb7d603b954011b7a12abb40724afb
39.605042
201
0.582316
4.550977
false
false
false
false
jussijartamo/rgadmin
src/test/kotlin/org/rgadmin/embedded/EmbeddedPostgreSQL.kt
1
2770
package org.rgadmin.embedded import org.dalesbred.Database import org.postgresql.ds.PGSimpleDataSource import ru.yandex.qatools.embed.postgresql.PostgresProcess import ru.yandex.qatools.embed.postgresql.PostgresStarter import ru.yandex.qatools.embed.postgresql.config.AbstractPostgresConfig import ru.yandex.qatools.embed.postgresql.config.PostgresConfig import ru.yandex.qatools.embed.postgresql.distribution.Version import java.sql.DriverManager import java.util.* class EmbeddedPostgreSQL(val port: Int) { val username = "test" val password = "test" val config = PostgresConfig(Version.Main.PRODUCTION, AbstractPostgresConfig.Net("127.0.0.1", port), AbstractPostgresConfig.Storage("test"), AbstractPostgresConfig.Timeout(), AbstractPostgresConfig.Credentials(username, password)) val url = "jdbc:postgresql://${config.net().host()}:${config.net().port()}/${config.storage().dbName()}?user=$username&password=$password" init { val runtime = PostgresStarter.getDefaultInstance(); val exec = runtime.prepare(config); val mainThread = Thread.currentThread(); var process: PostgresProcess? = null val runnable: Runnable = Runnable { process!!.stop(); mainThread.join(); }; Runtime.getRuntime().addShutdownHook(Thread(runnable)); process = exec.start(); } } fun main(args: Array<String>) { val port = Integer.parseInt(System.getProperty("port") ?: "5432"); val postgre = EmbeddedPostgreSQL(port) val datasource = PGSimpleDataSource() datasource.url = postgre.url datasource.user = postgre.username datasource.password = postgre.password val db = Database.forDataSource(datasource); db.update( """ CREATE sequence serial; CREATE TABLE films ( code char(5) CONSTRAINT firstkey PRIMARY KEY, title varchar(40) NOT NULL, did integer NOT NULL, date_prod date, kind varchar(10) ); CREATE TABLE distributors ( did integer PRIMARY KEY DEFAULT nextval('serial'), name varchar(40) NOT NULL CHECK (name <> '') ); """ ); for (i in 1..100) { val distributorName = "distributor_name_$i" val did = db.update("insert into distributors (name) values (?)", distributorName); val code = "cd$i" val title = "title_$i"; val kind = "kind_$i"; db.update("insert into films (code,title,did,date_prod,kind) values (?, ?, ?, ?, ?)", code, title, did, Date(), kind); } Thread.currentThread().join() }
apache-2.0
29b2b568281d98b0057c454cace05608
35.447368
142
0.623827
4.375987
false
true
false
false