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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dkrivoruchko/ScreenStream | app/src/main/kotlin/info/dvkr/screenstream/ui/fragment/AboutFragment.kt | 1 | 3501 | package info.dvkr.screenstream.ui.fragment
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.elvishew.xlog.XLog
import info.dvkr.screenstream.BaseApp
import info.dvkr.screenstream.R
import info.dvkr.screenstream.common.getLog
import info.dvkr.screenstream.common.settings.AppSettings
import info.dvkr.screenstream.databinding.FragmentAboutBinding
import info.dvkr.screenstream.ui.viewBinding
import kotlinx.coroutines.flow.first
import org.koin.android.ext.android.inject
class AboutFragment : Fragment(R.layout.fragment_about) {
private val appSettings: AppSettings by inject()
private var settingsLoggingVisibleCounter: Int = 0
private var version: String = ""
private val binding by viewBinding { fragment -> FragmentAboutBinding.bind(fragment.requireView()) }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val packageName = requireContext().packageName
runCatching {
version = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requireContext().packageManager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0)).versionName
} else {
@Suppress("DEPRECATION")
requireContext().packageManager.getPackageInfo(packageName, 0).versionName
}
binding.tvFragmentAboutVersion.text = getString(R.string.about_fragment_app_version, version)
}.onFailure {
XLog.e(getLog("onViewCreated", "getPackageInfo"), it)
}
binding.tvFragmentAboutVersion.setOnClickListener {
viewLifecycleOwner.lifecycleScope.launchWhenCreated {
if (appSettings.loggingVisibleFlow.first()) return@launchWhenCreated
settingsLoggingVisibleCounter++
if (settingsLoggingVisibleCounter >= 5) {
(requireActivity().application as BaseApp).isLoggingOn = true
appSettings.setLoggingVisible(true)
Toast.makeText(requireContext(), "Logging option enabled", Toast.LENGTH_LONG).show()
binding.tvFragmentAboutVersion.setOnClickListener(null)
}
}
}
binding.bFragmentAboutRate.setOnClickListener {
openStringUrl("market://details?id=$packageName") {
openStringUrl("https://play.google.com/store/apps/details?id=$packageName")
}
}
binding.bFragmentAboutSources.setOnClickListener {
openStringUrl("https://github.com/dkrivoruchko/ScreenStream")
}
binding.bFragmentPrivacyPolicy.setOnClickListener {
openStringUrl("https://github.com/dkrivoruchko/ScreenStream/blob/master/PrivacyPolicy.md")
}
binding.bFragmentLicense.setOnClickListener {
openStringUrl("https://github.com/dkrivoruchko/ScreenStream/blob/master/LICENSE")
}
}
private fun openStringUrl(url: String, onFailure: () -> Unit = {}) {
runCatching {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}.onFailure {
runCatching { onFailure.invoke() }
}
}
} | mit | b658fc5fe7596ea0d22d7c37b527df91 | 39.252874 | 126 | 0.688946 | 4.8625 | false | false | false | false |
GunoH/intellij-community | plugins/search-everywhere-ml/test/com/intellij/ide/actions/searcheverywhere/ml/SearchEverywhereFileRankingModelTest.kt | 8 | 1555 | package com.intellij.ide.actions.searcheverywhere.ml
import com.intellij.ide.actions.GotoFileItemProvider
import com.intellij.ide.actions.searcheverywhere.FoundItemDescriptor
import com.intellij.ide.util.gotoByName.GotoFileModel
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFileSystemItem
internal class SearchEverywhereFileRankingModelTest : SearchEverywhereRankingModelTest() {
override val tab = SearchEverywhereTabWithMl.FILES
private val gotoFileModel by lazy { GotoFileModel(project) }
private val gotoFileModelProvider: GotoFileItemProvider by lazy { gotoFileModel.getItemProvider(null) as GotoFileItemProvider }
private val viewModel by lazy { StubChooseByNameViewModel(gotoFileModel) }
fun `test exact match appears at the top`() {
var expectedFile: VirtualFile? = null
module {
source {
createPackage("psi.codeStyle") {
file("MinusculeMatcher.java") { expectedFile = it }
file("MinusculeMatcherImpl.java")
file("OtherMinusculeMatcher.java")
}
}
}
performSearchFor("codeStyle/MinusculeMatcher.java")
.findElementAndAssert { (it.item as PsiFileSystemItem).virtualFile == expectedFile }
.isAtIndex(0)
}
override fun filterElements(searchQuery: String): List<FoundItemDescriptor<*>> {
val elements = mutableListOf<FoundItemDescriptor<*>>()
gotoFileModelProvider.filterElementsWithWeights(viewModel, searchQuery, false, mockProgressIndicator) {
elements.add(it)
true
}
return elements
}
} | apache-2.0 | 1741538d29604f2d54d62f87a8b99f88 | 36.95122 | 129 | 0.754341 | 4.936508 | false | true | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/refactoring/rename/ui/renameUi.kt | 8 | 2891 | // 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 com.intellij.refactoring.rename.ui
import com.intellij.model.Pointer
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.application.readAction
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts.Command
import com.intellij.openapi.util.NlsContexts.ProgressTitle
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.rename.api.RenameTarget
import kotlinx.coroutines.*
import java.util.concurrent.locks.LockSupport
import kotlin.coroutines.ContinuationInterceptor
internal val uiDispatcher: ContinuationInterceptor = AppUIExecutor.onUiThread(ModalityState.NON_MODAL).coroutineDispatchingContext()
/**
* Shows a background progress indicator in the UI,
* the indicator cancels the coroutine when cancelled from the UI.
*/
internal suspend fun <T> withBackgroundIndicator(
project: Project,
@ProgressTitle progressTitle: String,
action: suspend CoroutineScope.() -> T
): T = coroutineScope {
if (ApplicationManager.getApplication().isUnitTestMode) {
return@coroutineScope action()
}
val deferred = async(block = action)
launch(Dispatchers.IO) { // block some thread while [action] is not completed
CoroutineBackgroundTask(project, progressTitle, deferred).queue()
}
deferred.await()
}
/**
* - stays in progress while the [job] is running;
* - cancels the [job] then user cancels the progress in the UI.
*/
private class CoroutineBackgroundTask(
project: Project,
@ProgressTitle progressTitle: String,
private val job: Job
) : Task.Backgroundable(project, progressTitle) {
override fun run(indicator: ProgressIndicator) {
while (job.isActive) {
if (indicator.isCanceled) {
job.cancel()
return
}
LockSupport.parkNanos(10_000_000)
}
}
}
private suspend fun Pointer<out RenameTarget>.presentableText(): String? {
return readAction {
dereference()?.presentation?.presentableText
}
}
@ProgressTitle
internal suspend fun Pointer<out RenameTarget>.progressTitle(): String? {
val presentableText = presentableText() ?: return null
return RefactoringBundle.message("rename.progress.title.0", presentableText)
}
@Command
internal suspend fun Pointer<out RenameTarget>.commandName(newName: String): String? {
val presentableText = presentableText() ?: return null
return RefactoringBundle.message("rename.command.name.0.1", presentableText, newName)
}
| apache-2.0 | bd6fa1b255ef563cc7abf524762ec5b3 | 35.594937 | 158 | 0.782774 | 4.574367 | false | false | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/ide/customize/WelcomeWizardHelper.kt | 3 | 2439 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.customize
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.ide.ApplicationInitializedListener
import com.intellij.ide.WelcomeWizardUtil
import com.intellij.ide.projectView.impl.ProjectViewSharedSettings
import com.intellij.ide.ui.UISettings
import com.intellij.lang.Language
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.util.registry.Registry
private class WelcomeWizardHelper : ApplicationInitializedListener {
init {
if (ApplicationManager.getApplication().isHeadlessEnvironment) {
throw ExtensionNotApplicableException.create()
}
}
override fun componentsInitialized() {
// project View settings
WelcomeWizardUtil.getAutoScrollToSource()?.let {
ProjectViewSharedSettings.instance.autoscrollToSource = it
}
WelcomeWizardUtil.getManualOrder()?.let {
ProjectViewSharedSettings.instance.manualOrder = it
}
// debugger settings
WelcomeWizardUtil.getDisableBreakpointsOnClick()?.let{
Registry.get("debugger.click.disable.breakpoints").setValue(it)
}
// code insight settings
WelcomeWizardUtil.getCompletionCaseSensitive()?.let {
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = it
}
// code style settings
WelcomeWizardUtil.getContinuationIndent()?.let {
Language.getRegisteredLanguages()
.asSequence()
.map { CodeStyle.getDefaultSettings().getIndentOptions(it.associatedFileType) }
.filter { it.CONTINUATION_INDENT_SIZE > WelcomeWizardUtil.getContinuationIndent() }
.forEach { it.CONTINUATION_INDENT_SIZE = WelcomeWizardUtil.getContinuationIndent() }
}
// UI settings
WelcomeWizardUtil.getTabsPlacement()?.let {
UISettings.getInstance().editorTabPlacement = it
}
WelcomeWizardUtil.getAppearanceFontSize()?.let {
val settings = UISettings.getInstance()
settings.overrideLafFonts = true
UISettings.getInstance().fontSize = it
}
WelcomeWizardUtil.getAppearanceFontFace()?.let {
val settings = UISettings.getInstance()
settings.overrideLafFonts = true
settings.fontFace = it
}
}
}
| apache-2.0 | 69be85e6fe68dcab294284540a19618e | 35.402985 | 120 | 0.756868 | 5.245161 | false | false | false | false |
jaycarey/montior | montior-web/src/main/java/com/jay/montior/core/StatusCache.kt | 1 | 2579 | package com.jay.montior.core
import com.jay.montior.ci.*
import com.jay.montior.common.Util.callLogFailure
import jersey.repackaged.com.google.common.util.concurrent.FutureCallback
import jersey.repackaged.com.google.common.util.concurrent.Futures
import jersey.repackaged.com.google.common.util.concurrent.ListenableFuture
import jersey.repackaged.com.google.common.util.concurrent.MoreExecutors.listeningDecorator
import org.slf4j.LoggerFactory
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors.newFixedThreadPool
import java.util.concurrent.TimeUnit
import kotlin.concurrent.scheduleAtFixedRate
open class StatusCache(vararg val cis: Ci) {
private val logger = LoggerFactory.getLogger(javaClass)
private val pool by lazy { listeningDecorator(newFixedThreadPool(10)) }
private val timer = Timer("check-timer", true)
@Volatile private var checkFuture: ListenableFuture<Map<String, BuildTypeStatus>> = Futures.immediateFuture(mapOf())
private val builds: ConcurrentHashMap<String, BuildTypeStatus> = ConcurrentHashMap()
fun init() {
timer.scheduleAtFixedRate(0, 3000, {
if (checkFuture.isDone) {
checkFuture = pool.submit(callLogFailure { checkBuilds() })
}
})
}
private fun checkBuilds(): Map<String, BuildTypeStatus> {
val checks = cis.flatMap { ci ->
ci.buildTypes.map { buildType ->
val future: ListenableFuture<BuildTypeStatus?> = pool.submit(callLogFailure { ci.checkOrUnknown(buildType.value) })
Futures.addCallback(future, object : FutureCallback<BuildTypeStatus?> {
override fun onSuccess(result: BuildTypeStatus?) {
if(result != null) builds.put (result.buildType.id, result)
}
override fun onFailure(t: Throwable?) {
}
})
future
}
}
Futures.allAsList(checks).get(10, TimeUnit.MINUTES)
return builds
}
private fun Ci.checkOrUnknown(buildType: BuildType): BuildTypeStatus? {
try {
return status(buildType)
} catch (e: Exception) {
logger.error("Unable to retrieve build's status $buildType, message: ${e.message}", e)
return BuildTypeStatus(buildType, null, null, listOf())
}
}
fun close() {
timer.cancel()
pool.shutdownNow()
}
open fun builds(): List<BuildTypeStatus> = builds.values.toList()
} | apache-2.0 | d22324cace07ab684dabe6f1d5df851b | 37.507463 | 131 | 0.664986 | 4.461938 | false | false | false | false |
smmribeiro/intellij-community | platform/testFramework/src/com/intellij/testFramework/fixtures/InjectionTestFixture.kt | 2 | 6632 | // 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.testFramework.fixtures
import com.intellij.codeInsight.intention.impl.QuickEditAction
import com.intellij.codeInsight.intention.impl.QuickEditHandler
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiLanguageInjectionHost
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.testFramework.UsefulTestCase
import junit.framework.TestCase
import org.junit.Assert
import org.junit.Assert.*
import java.util.*
class InjectionTestFixture(private val javaFixture: CodeInsightTestFixture) {
val injectedLanguageManager: InjectedLanguageManager
get() = InjectedLanguageManager.getInstance(javaFixture.project)
val injectedElement: PsiElement?
get() {
return injectedLanguageManager.findInjectedElementAt(topLevelFile ?: return null, topLevelCaretPosition)
}
fun assertInjectedLangAtCaret(lang: String?) {
val injectedElement = injectedElement
if (lang != null) {
TestCase.assertNotNull("injection of '$lang' expected", injectedElement)
TestCase.assertEquals(lang, injectedElement!!.language.id)
}
else {
TestCase.assertNull(injectedElement)
}
}
fun getAllInjections(): List<Pair<PsiElement, PsiFile>> {
val injected = mutableListOf<Pair<PsiElement, PsiFile>>()
val hosts = PsiTreeUtil.collectElementsOfType(topLevelFile, PsiLanguageInjectionHost::class.java)
for (host in hosts) {
injectedLanguageManager.enumerate(host, PsiLanguageInjectionHost.InjectedPsiVisitor { injectedPsi, _ ->
injected.add(host to injectedPsi)
})
}
return injected
}
fun assertInjectedContent(vararg expectedInjectFileTexts: String) {
assertInjectedContent("injected content expected", expectedInjectFileTexts.toList())
}
fun assertInjectedContent(message: String, expectedFilesTexts: List<String>) {
UsefulTestCase.assertSameElements(message,
getAllInjections().mapTo(HashSet()) { it.second }.map { it.text },
expectedFilesTexts)
}
fun assertInjected(vararg expectedInjections: InjectionAssertionData) {
val expected = expectedInjections.toCollection(LinkedList())
val foundInjections = getAllInjections().toCollection(LinkedList())
while (expected.isNotEmpty()) {
val (text, injectedLanguage) = expected.pop()
val found = (foundInjections.find { (psi, file) -> psi.text == text && file.language.id == injectedLanguage }
?: Assert.fail(
"no injection '$text' -> '$injectedLanguage' were found, remains: ${foundInjections.joinToString { (psi, file) -> "'${psi.text}' -> '${file.language}'" }} "))
foundInjections.remove(found)
}
}
fun openInFragmentEditor(): EditorTestFixture {
val quickEditHandler = QuickEditAction().invokeImpl(javaFixture.project, topLevelEditor, topLevelFile)
return openInFragmentEditor(quickEditHandler)
}
fun openInFragmentEditor(quickEditHandler: QuickEditHandler): EditorTestFixture {
val injectedFile = quickEditHandler.newFile
val project = javaFixture.project
val documentWindow = InjectedLanguageUtil.getDocumentWindow(injectedElement?.containingFile!!)
val offset = topLevelEditor.caretModel.offset
val unEscapedOffset = InjectedLanguageUtil.hostToInjectedUnescaped(documentWindow, offset)
val fragmentEditor = FileEditorManagerEx.getInstanceEx(project).openTextEditor(
OpenFileDescriptor(project, injectedFile.virtualFile, unEscapedOffset), true
)
return EditorTestFixture(project, fragmentEditor!!, injectedFile.virtualFile)
}
val topLevelFile: PsiFile
get() = javaFixture.file!!.let { injectedLanguageManager.getTopLevelFile(it) }
val topLevelCaretPosition
get() = topLevelEditor.caretModel.offset
val topLevelEditor: Editor
get() = (FileEditorManager.getInstance(javaFixture.project).getSelectedEditor(topLevelFile!!.virtualFile) as TextEditor).editor
}
data class InjectionAssertionData(val text: String, val injectedLanguage: String? = null) {
fun hasLanguage(lang: String): InjectionAssertionData = this.copy(injectedLanguage = lang)
}
fun injectionForHost(text: String) = InjectionAssertionData(text)
fun CodeInsightTestFixture.assertInjectedLanguage(langId: String?, vararg fragmentTexts: String) {
runReadAction {
val injectedLanguageManager = InjectedLanguageManager.getInstance(project)
val doc = editor.document
for (text in fragmentTexts) {
val index = doc.text.indexOf(text)
if (index < 0) fail("No such text in document: $text")
val pos = index + text.length / 2
val injectedElement = injectedLanguageManager.findInjectedElementAt(file, pos)
if (langId != null) {
assertNotNull("There should be injected element at $pos with text '$text'", injectedElement)
assertEquals("Injected Language don't match", langId, injectedElement!!.language.id)
}
else {
assertNull("There should be no injected element at $pos with text '$text'", injectedElement)
}
}
}
}
fun CodeInsightTestFixture.assertInjectedReference(referenceClass: Class<*>, vararg fragmentTexts: String) {
runReadAction {
val doc = editor.document
val provider = file.viewProvider
for (text in fragmentTexts) {
val pos = doc.text.indexOf(text) + text.length / 2
val element = provider.findElementAt(pos)
assertNotNull("There should be element at $pos", element)
val host = element as? PsiLanguageInjectionHost ?: element!!.parent as? PsiLanguageInjectionHost
assertNotNull("There should injection host at $pos", host)
val reference = host!!.references.firstOrNull()
assertNotNull("There should be reference in element", reference)
assertEquals(referenceClass, reference!!.javaClass)
}
}
}
inline fun <reified T> CodeInsightTestFixture.assertInjectedReference(vararg fragmentTexts: String) {
this.assertInjectedReference(T::class.java, *fragmentTexts)
} | apache-2.0 | 05f671edab26e9079c53c4138dbfd074 | 40.716981 | 181 | 0.747889 | 4.844412 | false | true | false | false |
smmribeiro/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesTable.kt | 1 | 16006 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages
import com.intellij.ide.CopyProvider
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.project.Project
import com.intellij.ui.SpeedSearchComparator
import com.intellij.ui.TableSpeedSearch
import com.intellij.ui.TableUtil
import com.intellij.ui.table.JBTable
import com.intellij.util.ui.UIUtil
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.OperationExecutor
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperationFactory
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.ActionsColumn
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.NameColumn
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.ScopeColumn
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.VersionColumn
import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint
import com.jetbrains.packagesearch.intellij.plugin.ui.util.onMouseMotion
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.flow.MutableStateFlow
import java.awt.Cursor
import java.awt.Dimension
import java.awt.KeyboardFocusManager
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.awt.event.FocusAdapter
import java.awt.event.FocusEvent
import javax.swing.ListSelectionModel
import javax.swing.event.ListSelectionListener
import javax.swing.table.DefaultTableCellRenderer
import javax.swing.table.TableCellEditor
import javax.swing.table.TableCellRenderer
import javax.swing.table.TableColumn
import kotlin.math.roundToInt
internal typealias SearchResultStateChangeListener =
(PackageModel.SearchResult, NormalizedPackageVersion<*>?, PackageScope?) -> Unit
@Suppress("MagicNumber") // Swing dimension constants
internal class PackagesTable(
private val project: Project,
private val operationExecutor: OperationExecutor,
private val onSearchResultStateChanged: SearchResultStateChangeListener
) : JBTable(), CopyProvider, DataProvider {
private val operationFactory = PackageSearchOperationFactory()
private val tableModel: PackagesTableModel
get() = model as PackagesTableModel
var transferFocusUp: () -> Unit = { transferFocusBackward() }
private val columnWeights = listOf(
.5f, // Name column
.2f, // Scope column
.2f, // Version column
.1f // Actions column
)
private val nameColumn = NameColumn()
private val scopeColumn = ScopeColumn { packageModel, newScope -> updatePackageScope(packageModel, newScope) }
private val versionColumn = VersionColumn { packageModel, newVersion ->
updatePackageVersion(packageModel, newVersion)
}
private val actionsColumn = ActionsColumn(project, operationExecutor = ::executeActionColumnOperations)
private val actionsColumnIndex: Int
private val autosizingColumnsIndices: List<Int>
private var targetModules: TargetModules = TargetModules.None
private var knownRepositoriesInTargetModules = KnownRepositories.InTargetModules.EMPTY
val selectedPackageStateFlow = MutableStateFlow<UiPackageModel<*>?>(null)
private val listSelectionListener = ListSelectionListener {
val item = getSelectedTableItem()
if (selectedIndex >= 0 && item != null) {
TableUtil.scrollSelectionToVisible(this)
updateAndRepaint()
selectedPackageStateFlow.tryEmit(item.uiPackageModel)
} else {
selectedPackageStateFlow.tryEmit(null)
}
}
val hasInstalledItems: Boolean
get() = tableModel.items.any { it is PackagesTableItem.InstalledPackage }
val firstPackageIndex: Int
get() = tableModel.items.indexOfFirst { it is PackagesTableItem.InstalledPackage }
var selectedIndex: Int
get() = selectedRow
set(value) {
if (tableModel.items.isNotEmpty() && (0 until tableModel.items.count()).contains(value)) {
setRowSelectionInterval(value, value)
} else {
clearSelection()
}
}
init {
require(columnWeights.sum() == 1.0f) { "The column weights must sum to 1.0" }
model = PackagesTableModel(
nameColumn = nameColumn,
scopeColumn = scopeColumn,
versionColumn = versionColumn,
actionsColumn = actionsColumn
)
val columnInfos = tableModel.columnInfos
actionsColumnIndex = columnInfos.indexOf(actionsColumn)
autosizingColumnsIndices = listOf(
columnInfos.indexOf(scopeColumn),
columnInfos.indexOf(versionColumn),
actionsColumnIndex
)
setTableHeader(InvisibleResizableHeader())
getTableHeader().apply {
reorderingAllowed = false
resizingAllowed = true
}
columnSelectionAllowed = false
setShowGrid(false)
rowHeight = 20.scaled()
background = UIUtil.getTableBackground()
foreground = UIUtil.getTableForeground()
selectionBackground = UIUtil.getTableSelectionBackground(true)
selectionForeground = UIUtil.getTableSelectionForeground(true)
setExpandableItemsEnabled(false)
selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION
putClientProperty("terminateEditOnFocusLost", true)
intercellSpacing = Dimension(0, 2)
// By default, JTable uses Tab/Shift-Tab for navigation between cells; Ctrl-Tab/Ctrl-Shift-Tab allows to break out of the JTable.
// In this table, we don't want to navigate between cells - so override the traversal keys by default values.
setFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS)
)
setFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS)
)
addFocusListener(object : FocusAdapter() {
override fun focusGained(e: FocusEvent?) {
if (tableModel.rowCount > 0 && selectedRows.isEmpty()) {
setRowSelectionInterval(0, 0)
}
}
})
PackageSearchUI.overrideKeyStroke(this, "jtable:RIGHT", "RIGHT") { transferFocus() }
PackageSearchUI.overrideKeyStroke(this, "jtable:ENTER", "ENTER") { transferFocus() }
PackageSearchUI.overrideKeyStroke(this, "shift ENTER") {
clearSelection()
transferFocusUp()
}
selectionModel.addListSelectionListener(listSelectionListener)
addFocusListener(object : FocusAdapter() {
override fun focusGained(e: FocusEvent?) {
if (selectedIndex == -1) {
selectedIndex = firstPackageIndex
}
}
})
TableSpeedSearch(this) { item, _ ->
if (item is PackagesTableItem<*>) {
val rawIdentifier = item.packageModel.identifier.rawValue
val name = item.packageModel.remoteInfo?.name?.takeIf { !it.equals(rawIdentifier, ignoreCase = true) }
if (name != null) rawIdentifier + name else rawIdentifier
} else {
""
}
}.apply {
comparator = SpeedSearchComparator(false)
}
addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
applyColumnSizes(columnModel.totalColumnWidth, columnModel.columns.toList(), columnWeights)
removeComponentListener(this)
}
})
onMouseMotion(
onMouseMoved = { mouseEvent ->
val point = mouseEvent.point
val hoverColumn = columnAtPoint(point)
val hoverRow = rowAtPoint(point)
if (tableModel.items.isEmpty() || hoverRow < 0) {
cursor = Cursor.getDefaultCursor()
return@onMouseMotion
}
val isHoveringActionsColumn = hoverColumn == actionsColumnIndex
cursor = if (isHoveringActionsColumn) Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) else Cursor.getDefaultCursor()
}
)
}
override fun getCellRenderer(row: Int, column: Int): TableCellRenderer =
tableModel.columns.getOrNull(column)?.getRenderer(tableModel.items[row]) ?: DefaultTableCellRenderer()
override fun getCellEditor(row: Int, column: Int): TableCellEditor? =
tableModel.columns.getOrNull(column)?.getEditor(tableModel.items[row])
internal data class ViewModel(
val items: TableItems,
val onlyStable: Boolean,
val targetModules: TargetModules,
val knownRepositoriesInTargetModules: KnownRepositories.InTargetModules,
) {
data class TableItems(
val items: List<PackagesTableItem<*>>,
) : List<PackagesTableItem<*>> by items {
companion object {
val EMPTY = TableItems(items = emptyList())
}
}
}
fun display(viewModel: ViewModel) {
knownRepositoriesInTargetModules = viewModel.knownRepositoriesInTargetModules
targetModules = viewModel.targetModules
// We need to update those immediately before setting the items, on EDT, to avoid timing issues
// where the target modules or only stable flags get updated after the items data change, thus
// causing issues when Swing tries to render things (e.g., targetModules doesn't match packages' usages)
versionColumn.updateData(viewModel.onlyStable, viewModel.targetModules)
actionsColumn.updateData(
viewModel.onlyStable,
viewModel.targetModules,
viewModel.knownRepositoriesInTargetModules
)
selectionModel.removeListSelectionListener(listSelectionListener)
tableModel.items = viewModel.items
// TODO size columns
selectionModel.addListSelectionListener(listSelectionListener)
updateAndRepaint()
}
override fun getData(dataId: String): Any? = when {
PlatformDataKeys.COPY_PROVIDER.`is`(dataId) -> this
else -> null
}
override fun performCopy(dataContext: DataContext) {
getSelectedTableItem()?.performCopy(dataContext)
}
override fun isCopyEnabled(dataContext: DataContext) = getSelectedTableItem()?.isCopyEnabled(dataContext) ?: false
override fun isCopyVisible(dataContext: DataContext) = getSelectedTableItem()?.isCopyVisible(dataContext) ?: false
private fun getSelectedTableItem(): PackagesTableItem<*>? {
if (selectedIndex == -1) {
return null
}
return tableModel.getValueAt(selectedIndex, 0) as? PackagesTableItem<*>
}
private fun updatePackageScope(uiPackageModel: UiPackageModel<*>, newScope: PackageScope) {
when (uiPackageModel) {
is UiPackageModel.Installed -> {
val operations = operationFactory.createChangePackageScopeOperations(
packageModel = uiPackageModel.packageModel,
newScope = newScope,
targetModules = targetModules,
repoToInstall = null
)
logDebug("PackagesTable#updatePackageScope()") {
"The user has selected a new scope for ${uiPackageModel.identifier}: '$newScope'. This resulted in ${operations.size} operation(s)."
}
operationExecutor.executeOperations(operations)
}
is UiPackageModel.SearchResult -> {
val selectedVersion = uiPackageModel.selectedVersion
onSearchResultStateChanged(uiPackageModel.packageModel, selectedVersion, newScope)
logDebug("PackagesTable#updatePackageScope()") {
"The user has selected a new scope for search result ${uiPackageModel.identifier}: '$newScope'."
}
updateAndRepaint()
}
}
}
private fun updatePackageVersion(uiPackageModel: UiPackageModel<*>, newVersion: NormalizedPackageVersion<*>) {
when (uiPackageModel) {
is UiPackageModel.Installed -> {
val operations = uiPackageModel.packageModel.usageInfo.flatMap {
val repoToInstall = knownRepositoriesInTargetModules.repositoryToAddWhenInstallingOrUpgrading(
project = project,
packageModel = uiPackageModel.packageModel,
selectedVersion = newVersion.originalVersion
)
operationFactory.createChangePackageVersionOperations(
packageModel = uiPackageModel.packageModel,
newVersion = newVersion.originalVersion,
targetModules = targetModules,
repoToInstall = repoToInstall
)
}
logDebug("PackagesTable#updatePackageVersion()") {
"The user has selected a new version for ${uiPackageModel.identifier}: '$newVersion'. " +
"This resulted in ${operations.size} operation(s)."
}
operationExecutor.executeOperations(operations)
}
is UiPackageModel.SearchResult -> {
onSearchResultStateChanged(uiPackageModel.packageModel, newVersion, uiPackageModel.selectedScope)
logDebug("PackagesTable#updatePackageVersion()") {
"The user has selected a new version for search result ${uiPackageModel.identifier}: '$newVersion'."
}
updateAndRepaint()
}
}
}
private fun executeActionColumnOperations(operations: Deferred<List<PackageSearchOperation<*>>>) {
logDebug("PackagesTable#executeActionColumnOperations()") {
"The user has clicked the action for a package. This resulted in many operation(s)."
}
operationExecutor.executeOperations(operations)
}
private fun applyColumnSizes(tW: Int, columns: List<TableColumn>, weights: List<Float>) {
require(columnWeights.size == columns.size) {
"Column weights count != columns count! We have ${columns.size} columns, ${columnWeights.size} weights"
}
for (column in columns) {
column.preferredWidth = (weights[column.modelIndex] * tW).roundToInt()
}
}
}
| apache-2.0 | b9d745e7435817baa98e296a0d4d0a8b | 41.456233 | 152 | 0.68037 | 5.807692 | false | false | false | false |
tlaukkan/kotlin-web-vr | client/src/vr/webvr/tools/SelectTool.kt | 1 | 1047 | package vr.webvr.tools
import lib.threejs.*
import vr.webvr.devices.InputButton
import vr.webvr.devices.InputDevice
/**
* Created by tlaukkan on 11/1/2016.
*/
class SelectTool(inputDevice: InputDevice) : Tool("Select", inputDevice) {
override fun active() {
inputDevice.display("Select tool.\nUse menu key to change tool.")
inputDevice.showSelectLine(0xffffff)
}
override fun render() {
}
override fun deactivate() {
inputDevice.hideSelectLine()
gripped = false
}
override fun onPressed(button: InputButton) {
if (button == InputButton.GRIP) {
gripped = true
}
if (!gripped) {
inputDevice.unselectNodes()
}
inputDevice.selectNodes()
}
override fun onReleased(button: InputButton) {
if (button == InputButton.GRIP) {
gripped = false
}
}
override fun onSqueezed(button: InputButton, value: Double) {
}
override fun onPadTouched(x: Double, y: Double) {
}
} | mit | 12a0eabbd1155ff5e93f682db793cee4 | 20.387755 | 74 | 0.613181 | 3.835165 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/history/src/main/java/jp/hazuki/yuzubrowser/history/presenter/BrowserHistoryActivity.kt | 1 | 2761 | /*
* 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.history.presenter
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.MenuItem
import android.view.WindowInsets
import android.view.WindowManager
import dagger.hilt.android.AndroidEntryPoint
import jp.hazuki.yuzubrowser.core.utility.extensions.convertDpToFloatPx
import jp.hazuki.yuzubrowser.historyModel.R
import jp.hazuki.yuzubrowser.ui.INTENT_EXTRA_MODE_FULLSCREEN
import jp.hazuki.yuzubrowser.ui.INTENT_EXTRA_MODE_ORIENTATION
import jp.hazuki.yuzubrowser.ui.app.ThemeActivity
import jp.hazuki.yuzubrowser.ui.settings.AppPrefs
@AndroidEntryPoint
class BrowserHistoryActivity : ThemeActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.fragment_base)
supportActionBar?.run {
elevation = convertDpToFloatPx(1)
setDisplayHomeAsUpEnabled(true)
}
var pickMode = false
var fullscreen = AppPrefs.fullscreen.get()
var orientation = AppPrefs.oritentation.get()
intent?.run {
if (Intent.ACTION_PICK == action)
pickMode = true
fullscreen = getBooleanExtra(INTENT_EXTRA_MODE_FULLSCREEN, fullscreen)
orientation = getIntExtra(INTENT_EXTRA_MODE_ORIENTATION, orientation)
}
if (fullscreen) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.insetsController?.hide(WindowInsets.Type.statusBars())
} else {
@Suppress("DEPRECATION")
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
}
}
requestedOrientation = orientation
supportFragmentManager.beginTransaction()
.replace(R.id.container, BrowserHistoryFragment(pickMode))
.commit()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
}
| apache-2.0 | 60a0e1da7f0d769a4befa55e2e8cfd77 | 33.08642 | 82 | 0.684535 | 4.663851 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/speeddial/view/SpeedDialSettingActivityEditFragment.kt | 1 | 6487 | /*
* Copyright (C) 2017-2021 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.legacy.speeddial.view
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import jp.hazuki.yuzubrowser.core.utility.utils.ImageUtils
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.legacy.databinding.FragmentEditSpeeddialBinding
import jp.hazuki.yuzubrowser.legacy.speeddial.SpeedDial
import jp.hazuki.yuzubrowser.legacy.speeddial.WebIcon
import jp.hazuki.yuzubrowser.ui.BrowserApplication
import java.io.File
class SpeedDialSettingActivityEditFragment : Fragment() {
private lateinit var speedDial: SpeedDial
private var mCallBack: SpeedDialEditCallBack? = null
private var goBack: GoBackController? = null
private var viewBinding: FragmentEditSpeeddialBinding? = null
private val binding: FragmentEditSpeeddialBinding
get() = viewBinding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
viewBinding = FragmentEditSpeeddialBinding.inflate(layoutInflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val arguments = arguments ?: throw IllegalArgumentException()
speedDial = arguments.getSerializable(DATA) as? SpeedDial ?: SpeedDial()
binding.apply {
superFrameLayout.setOnImeShownListener { visible -> bottomBar.visibility = if (visible) View.GONE else View.VISIBLE }
name.setText(speedDial.title)
url.setText(speedDial.url)
val iconBitmap = speedDial.icon
?: WebIcon.createIcon(ImageUtils.getBitmapFromVectorDrawable(activity, R.drawable.ic_public_white_24dp))
icon.setImageBitmap(iconBitmap.bitmap)
useFavicon.isChecked = speedDial.isFavicon
setIconEnable(!speedDial.isFavicon)
useFavicon.setOnCheckedChangeListener { _, isChecked ->
speedDial.isFavicon = isChecked
setIconEnable(!isChecked)
}
icon.setOnClickListener {
val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
intent.type = "image/*"
startActivityForResult(intent, REQUEST_PICK_IMAGE)
}
okButton.setOnClickListener {
mCallBack?.run {
speedDial.title = name.text.toString()
speedDial.url = url.text.toString()
onEdited(speedDial)
}
}
cancelButton.setOnClickListener {
goBack?.run {
goBack()
}
}
}
}
private fun setIconEnable(enable: Boolean) {
binding.icon.apply {
isEnabled = enable
alpha = if (enable) 1.0f else 0.6f
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
REQUEST_PICK_IMAGE -> if (resultCode == Activity.RESULT_OK && data != null) {
try {
var uri = data.data ?: return
val activity = activity ?: return
if ("file" == uri.scheme) {
val provider = (activity.applicationContext as BrowserApplication).providerManager.downloadFileProvider
uri = provider.getUriForFile(File(uri.path!!))
}
val intent = Intent("com.android.camera.action.CROP").apply {
this.data = uri
putExtra("outputX", 200)
putExtra("outputY", 200)
putExtra("aspectX", 1)
putExtra("aspectY", 1)
putExtra("scale", true)
putExtra("return-data", true)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
startActivityForResult(intent, REQUEST_CROP_IMAGE)
} catch (e: ActivityNotFoundException) {
Toast.makeText(activity, "Activity not found", Toast.LENGTH_SHORT).show()
}
}
REQUEST_CROP_IMAGE -> if (resultCode == Activity.RESULT_OK && data != null && data.extras != null) {
val bitmap = data.extras!!.getParcelable<Bitmap>("data")
speedDial.icon = WebIcon.createIconOrNull(bitmap)
binding.icon.setImageBitmap(bitmap)
}
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
try {
mCallBack = activity as SpeedDialEditCallBack
goBack = activity as GoBackController
} catch (e: ClassCastException) {
throw IllegalStateException(e)
}
}
override fun onDetach() {
super.onDetach()
mCallBack = null
goBack = null
}
internal interface GoBackController {
fun goBack(): Boolean
}
companion object {
private const val DATA = "dat"
private const val REQUEST_PICK_IMAGE = 100
private const val REQUEST_CROP_IMAGE = 101
fun newInstance(speedDial: SpeedDial): androidx.fragment.app.Fragment {
val fragment = SpeedDialSettingActivityEditFragment()
val bundle = Bundle()
bundle.putSerializable(DATA, speedDial)
fragment.arguments = bundle
return fragment
}
}
}
| apache-2.0 | 85f06ecb1095421ca51353cffe645a3f | 36.068571 | 129 | 0.621705 | 4.993841 | false | false | false | false |
spinnaker/kork | kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/update/release/provider/AggregatePluginInfoReleaseProvider.kt | 3 | 2478 | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.spinnaker.kork.plugins.update.release.provider
import com.netflix.spinnaker.kork.plugins.SpringStrictPluginLoaderStatusProvider
import com.netflix.spinnaker.kork.plugins.update.internal.SpinnakerPluginInfo
import com.netflix.spinnaker.kork.plugins.update.release.PluginInfoRelease
import com.netflix.spinnaker.kork.plugins.update.release.source.PluginInfoReleaseSource
import org.pf4j.update.PluginInfo
/**
* A composite [PluginInfoReleaseSource], that processes releases as defined by their order.
*/
class AggregatePluginInfoReleaseProvider(
private val pluginInfoReleaseSources: List<PluginInfoReleaseSource>,
private val strictPluginLoaderStatusProvider: SpringStrictPluginLoaderStatusProvider
) : PluginInfoReleaseProvider {
override fun getReleases(pluginInfo: List<SpinnakerPluginInfo>): Set<PluginInfoRelease> {
val pluginInfoReleases: MutableSet<PluginInfoRelease> = mutableSetOf()
pluginInfoReleaseSources.forEach { source ->
source.getReleases(pluginInfo).forEach { release ->
val hit = pluginInfoReleases.find { it.pluginId == release.pluginId }
if (hit != null) {
pluginInfoReleases.remove(hit)
pluginInfoReleases.add(release)
} else {
pluginInfoReleases.add(release)
}
}
source.processReleases(pluginInfoReleases)
}
pluginInfo.forEach { plugin ->
if (missingPluginWithStrictLoading(pluginInfoReleases, plugin)) {
throw PluginReleaseNotFoundException(plugin.id, pluginInfoReleaseSources)
}
}
return pluginInfoReleases
}
private fun missingPluginWithStrictLoading(
pluginInfoReleases: Set<PluginInfoRelease>,
pluginInfo: PluginInfo
): Boolean {
return pluginInfoReleases.find { it.pluginId == pluginInfo.id } == null &&
strictPluginLoaderStatusProvider.isStrictPluginLoading()
}
}
| apache-2.0 | b60a000c008b80eb9bf1843d67492c4c | 35.985075 | 92 | 0.757062 | 4.614525 | false | false | false | false |
ferranponsscmspain/android-cast-remote-display-sample | app/src/main/java/com/schibsted/remotedisplaysample/PresentationService.kt | 1 | 2555 | package com.schibsted.remotedisplaysample
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.Display
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.android.gms.cast.CastPresentation
import com.google.android.gms.cast.CastRemoteDisplayLocalService
class PresentationService : CastRemoteDisplayLocalService() {
private var castPresentation: DetailPresentation? = null
private var adViewModel: AdViewModel? = null
override fun onCreatePresentation(display: Display) {
dismissPresentation()
castPresentation = DetailPresentation(this, display)
try {
castPresentation?.show()
} catch (ex: Throwable) {
dismissPresentation()
}
}
override fun onDismissPresentation() {
dismissPresentation()
adViewModel = null
}
private fun dismissPresentation() {
castPresentation?.let {
it.dismiss()
castPresentation = null
}
}
fun setAdViewModel(ad: AdViewModel) {
adViewModel = ad
castPresentation?.updateAdDetail(ad)
}
inner class DetailPresentation(context: Context, display: Display) : CastPresentation(context, display) {
private lateinit var title: TextView
private lateinit var price: TextView
private lateinit var image: ImageView
override fun onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setContentView(R.layout.presentation_detail)
title = findViewById(R.id.ad_title)
price = findViewById(R.id.ad_price)
image = findViewById(R.id.ad_image)
updateAdDetail(adViewModel)
}
@SuppressLint("CheckResult")
fun updateAdDetail(adViewModel: AdViewModel?) {
adViewModel?.let {
title.text = it.title
price.text = it.price
it.image?.let { imageUrl ->
if (imageUrl.isNotEmpty()) {
val options = RequestOptions()
options.centerCrop()
Glide.with(context)
.load(it.image)
.apply(options)
.into(image)
}
}
}
}
}
} | apache-2.0 | bd10c7474f56485463c9f9ca7f8d889b | 30.170732 | 109 | 0.610176 | 5.278926 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/main/kotlin/me/proxer/library/api/list/MediaSearchEndpoint.kt | 2 | 5003 | package me.proxer.library.api.list
import me.proxer.library.ProxerCall
import me.proxer.library.api.PagingLimitEndpoint
import me.proxer.library.entity.list.MediaListEntry
import me.proxer.library.enums.FskConstraint
import me.proxer.library.enums.Language
import me.proxer.library.enums.LengthBound
import me.proxer.library.enums.MediaSearchSortCriteria
import me.proxer.library.enums.MediaType
import me.proxer.library.enums.TagRateFilter
import me.proxer.library.enums.TagSpoilerFilter
import me.proxer.library.internal.util.toIntOrNull
import me.proxer.library.util.ProxerUtils
/**
* Search for all available media. Features various filter and sort options and uses paging.
*
* @author Desnoo
*/
class MediaSearchEndpoint internal constructor(
private val internalApi: InternalApi
) : PagingLimitEndpoint<List<MediaListEntry>> {
private companion object {
private const val DELIMITER = "+"
}
private var page: Int? = null
private var limit: Int? = null
private var name: String? = null
private var language: Language? = null
private var type: MediaType? = null
private var sort: MediaSearchSortCriteria? = null
private var length: Int? = null
private var lengthBound: LengthBound? = null
private var tagRateFilter: TagRateFilter? = null
private var tagSpoilerFilter: TagSpoilerFilter? = null
private var fskConstraints: Set<FskConstraint>? = null
private var hideFinished: Boolean? = null
private var tags: Set<String>? = null
private var excludedTags: Set<String>? = null
private var genres: Set<String>? = null
private var excludedGenres: Set<String>? = null
override fun page(page: Int?) = this.apply { this.page = page }
override fun limit(limit: Int?) = this.apply { this.limit = limit }
/**
* Sets the name to search for.
*/
fun name(name: String?) = this.apply { this.name = name }
/**
* Sets the language to filter by.
*/
fun language(language: Language?) = this.apply { this.language = language }
/**
* Sets the type to load.
*/
fun type(type: MediaType?) = this.apply { this.type = type }
/**
* Sets the criteria the list should be sorted by.
*/
fun sort(sort: MediaSearchSortCriteria?) = this.apply { this.sort = sort }
/**
* Sets the minimum/maximum episode count a entry must have to be included in the result.
* You can specify if the count must be greater or smaller with the [lengthBound] method.
*/
fun length(length: Int?) = this.apply { this.length = length }
/**
* To be used in conjunction with [length]. Sets if the episode count must
* be greater or smaller than the specified value.
*/
fun lengthBound(lengthBound: LengthBound?) = this.apply { this.lengthBound = lengthBound }
/**
* Sets the filter for the tags.
*/
fun tagRateFilter(tagRateFilter: TagRateFilter?) = this.apply { this.tagRateFilter = tagRateFilter }
/**
* Sets the spoiler filter for the tags.
*/
fun tagSpoilerFilter(tagSpoilerFilter: TagSpoilerFilter?) = this.apply { this.tagSpoilerFilter = tagSpoilerFilter }
/**
* Sets the required fsk ratings.
*/
fun fskConstraints(fskConstraints: Set<FskConstraint>?) = this.apply { this.fskConstraints = fskConstraints }
/**
* Sets if already finished media of the current user should be hidden from the result.
*/
fun hideFinished(hideFinished: Boolean? = true) = this.apply { this.hideFinished = hideFinished }
/**
* Sets the tag ids a entry must have to be included in the result.
*/
fun tags(ids: Set<String>?) = this.apply { this.tags = ids }
/**
* Sets the tag ids a entry must not have to be included in the result.
*/
fun excludedTags(excludedIds: Set<String>?) = this.apply { this.excludedTags = excludedIds }
/**
* Sets the genre tag ids a entry must have to be included in the result.
*/
fun genres(ids: Set<String>?) = this.apply { this.genres = ids }
/**
* Sets the genre tag ids a entry must not have to be included in the result.
*/
fun excludedGenres(excludedIds: Set<String>?) = this.apply { this.excludedGenres = excludedIds }
override fun build(): ProxerCall<List<MediaListEntry>> {
val joinedFskConstraints = fskConstraints?.joinToString(DELIMITER) { ProxerUtils.getSafeApiEnumName(it) }
val joinedTags = tags?.joinToString(DELIMITER)
val joinedExcludedTags = excludedTags?.joinToString(DELIMITER)
val joinedGenres = genres?.joinToString(DELIMITER)
val joinedExcludedGenres = excludedGenres?.joinToString(DELIMITER)
return internalApi.mediaSearch(
name, language, type, joinedFskConstraints, sort, length, lengthBound,
joinedTags, joinedExcludedTags, joinedGenres, joinedExcludedGenres,
tagRateFilter, tagSpoilerFilter, hideFinished.toIntOrNull(), page, limit
)
}
}
| gpl-3.0 | 66c1bc2110e7f3c36c127de8c9dfad60 | 36.059259 | 119 | 0.690386 | 4.200672 | false | false | false | false |
firebase/quickstart-android | database/app/src/main/java/com/google/firebase/quickstart/database/kotlin/NewPostFragment.kt | 1 | 4710 | package com.google.firebase.quickstart.database.kotlin
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.navigation.fragment.findNavController
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.ValueEventListener
import com.google.firebase.database.ktx.database
import com.google.firebase.database.ktx.getValue
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.database.R
import com.google.firebase.quickstart.database.databinding.FragmentNewPostBinding
import com.google.firebase.quickstart.database.kotlin.models.Post
import com.google.firebase.quickstart.database.kotlin.models.User
class NewPostFragment : BaseFragment() {
private var _binding: FragmentNewPostBinding? = null
private val binding get() = _binding!!
private lateinit var database: DatabaseReference
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentNewPostBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
database = Firebase.database.reference
binding.fabSubmitPost.setOnClickListener { submitPost() }
}
private fun submitPost() {
val title = binding.fieldTitle.text.toString()
val body = binding.fieldBody.text.toString()
// Title is required
if (TextUtils.isEmpty(title)) {
binding.fieldTitle.error = REQUIRED
return
}
// Body is required
if (TextUtils.isEmpty(body)) {
binding.fieldBody.error = REQUIRED
return
}
// Disable button so there are no multi-posts
setEditingEnabled(false)
Toast.makeText(context, "Posting...", Toast.LENGTH_SHORT).show()
val userId = uid
database.child("users").child(userId).addListenerForSingleValueEvent(
object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
// Get user value
val user = dataSnapshot.getValue<User>()
if (user == null) {
// User is null, error out
Log.e(TAG, "User $userId is unexpectedly null")
Toast.makeText(context,
"Error: could not fetch user.",
Toast.LENGTH_SHORT).show()
} else {
// Write new post
writeNewPost(userId, user.username.toString(), title, body)
}
setEditingEnabled(true)
findNavController().navigate(R.id.action_NewPostFragment_to_MainFragment)
}
override fun onCancelled(databaseError: DatabaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException())
setEditingEnabled(true)
}
})
}
private fun setEditingEnabled(enabled: Boolean) {
with(binding) {
fieldTitle.isEnabled = enabled
fieldBody.isEnabled = enabled
if (enabled) {
fabSubmitPost.show()
} else {
fabSubmitPost.hide()
}
}
}
private fun writeNewPost(userId: String, username: String, title: String, body: String) {
// Create new post at /user-posts/$userid/$postid and at
// /posts/$postid simultaneously
val key = database.child("posts").push().key
if (key == null) {
Log.w(TAG, "Couldn't get push key for posts")
return
}
val post = Post(userId, username, title, body)
val postValues = post.toMap()
val childUpdates = hashMapOf<String, Any>(
"/posts/$key" to postValues,
"/user-posts/$userId/$key" to postValues
)
database.updateChildren(childUpdates)
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
companion object {
private const val TAG = "NewPostFragment"
private const val REQUIRED = "Required"
}
} | apache-2.0 | 8800ad245f6dd57d7ed00f218cce105f | 34.689394 | 116 | 0.607643 | 5.053648 | false | false | false | false |
sunghwanJo/workshop-jb | src/i_introduction/_4_Lambdas/Lambdas.kt | 1 | 815 | package i_introduction._4_Lambdas
import util.*
fun example() {
val sum = { x: Int, y: Int -> x + y }
val square: (Int) -> Int = { x -> x * x }
sum(1, square(2)) == 5
}
fun todoTask4(collection: Collection<Int>): Nothing = TODO(
"""
Task 4.
Rewrite 'JavaCode4.task4()' in Kotlin using lambdas.
You can find the appropriate function to call on 'collection' through IntelliJ's code completion feature.
(Don't use the class 'Iterables').
""",
documentation = doc4(),
references = { JavaCode4().task4(collection) })
<<<<<<< HEAD
fun task3(collection: Collection<Int>): Boolean {
return collection.any { it%42==0 }
}
=======
fun task4(collection: Collection<Int>): Boolean = todoTask4(collection)
>>>>>>> 350fc69a6a89148f21ace7bb429e7d3d60987881
| mit | 338807df6541db4b842991b252aeacc1 | 23.69697 | 113 | 0.626994 | 3.482906 | false | false | false | false |
antoniolg/Kotlin-for-Android-Developers | app/src/main/java/com/antonioleiva/weatherapp/data/server/ServerDataMapper.kt | 1 | 1091 | package com.antonioleiva.weatherapp.data.server
import com.antonioleiva.weatherapp.domain.model.ForecastList
import java.util.*
import java.util.concurrent.TimeUnit
import com.antonioleiva.weatherapp.domain.model.Forecast as ModelForecast
class ServerDataMapper {
fun convertToDomain(zipCode: Long, forecast: ForecastResult) = with(forecast) {
ForecastList(zipCode, city.name, city.country, convertForecastListToDomain(list))
}
private fun convertForecastListToDomain(list: List<Forecast>): List<ModelForecast> {
return list.mapIndexed { i, forecast ->
val dt = Calendar.getInstance().timeInMillis + TimeUnit.DAYS.toMillis(i.toLong())
convertForecastItemToDomain(forecast.copy(dt = dt))
}
}
private fun convertForecastItemToDomain(forecast: Forecast) = with(forecast) {
ModelForecast(-1, dt, weather[0].description, temp.max.toInt(), temp.min.toInt(),
generateIconUrl(weather[0].icon))
}
private fun generateIconUrl(iconCode: String) = "http://openweathermap.org/img/w/$iconCode.png"
} | apache-2.0 | 0763c65b849a850a98f158e9e7dbf14a | 39.444444 | 99 | 0.725023 | 4.164122 | false | false | false | false |
FutureioLab/FastPeak | app/src/main/java/com/binlly/fastpeak/base/glide/DisplayUtil.kt | 1 | 2326 | package com.binlly.fastpeak.base.glide
import android.content.Context
import android.util.DisplayMetrics
import android.view.WindowManager
import com.binlly.fastpeak.service.Services
object DisplayUtil {
private val windowManager: WindowManager by lazy {
Services.app.getSystemService(Context.WINDOW_SERVICE) as WindowManager
}
// 根据手机的分辨率将dp的单位转成px(像素)
fun dip2px(context: Context, dpValue: Float): Int {
val scale = context.resources.displayMetrics.density
return (dpValue * scale + 0.5f).toInt()
}
// 根据手机的分辨率将px(像素)的单位转成dp
fun px2dip(context: Context, pxValue: Float): Int {
val scale = context.resources.displayMetrics.density
return (pxValue / scale + 0.5f).toInt()
}
// 将px值转换为sp值
fun px2sp(context: Context, pxValue: Float): Int {
val fontScale = context.resources.displayMetrics.scaledDensity
return (pxValue / fontScale + 0.5f).toInt()
}
// 将sp值转换为px值
fun sp2px(context: Context, spValue: Float): Int {
val fontScale = context.resources.displayMetrics.scaledDensity
return (spValue * fontScale + 0.5f).toInt()
}
// 屏幕宽度(像素)
fun getScreenWidth(context: Context): Int {
val metric = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(metric)
return metric.widthPixels
}
// 屏幕高度(像素)
fun getScreenHeight(context: Context): Int {
val metric = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(metric)
return metric.heightPixels
}
fun getScreenDensity(context: Context): Float {
return try {
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
displayMetrics.density
} catch (e: Throwable) {
e.printStackTrace()
1.0f
}
}
fun getDensityDpi(context: Context): Int {
return try {
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
displayMetrics.densityDpi
} catch (e: Throwable) {
e.printStackTrace()
320
}
}
}
| mit | 61ee1c976d5f0ed5d70131d198be3eb1 | 29.219178 | 78 | 0.647325 | 4.300195 | false | false | false | false |
j-selby/kotgb | desktop/src/net/jselby/kotgb/desktop/DesktopLauncher.kt | 1 | 5594 | package net.jselby.kotgb.desktop
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration
import com.badlogic.gdx.files.FileHandle
import javafx.application.Application
import mu.KotlinLogging
import net.jselby.kotgb.EmulationEnvironment
import net.jselby.kotgb.KotGB
import net.jselby.kotgb.cpu.CPU
import net.jselby.kotgb.desktop.debugger.DebuggingApplication
import net.jselby.kotgb.desktop.jit.JITExecutor
import net.jselby.kotgb.desktop.jit.JITTest
import net.jselby.kotgb.lwjgl.io.FileDialog
import net.sourceforge.argparse4j.ArgumentParsers
import net.sourceforge.argparse4j.impl.Arguments
import net.sourceforge.argparse4j.inf.ArgumentParserException
import net.sourceforge.argparse4j.inf.Namespace
import org.apache.logging.log4j.Level
import org.apache.logging.log4j.core.Filter
import org.apache.logging.log4j.core.appender.ConsoleAppender
import org.apache.logging.log4j.core.config.Configurator
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory
import java.io.File
import java.util.*
import kotlin.concurrent.thread
object DesktopLauncher {
@JvmStatic fun main(args: Array<String>) {
// Set up logging via Log4j
val builder = ConfigurationBuilderFactory.newConfigurationBuilder()
builder.setStatusLevel(Level.ERROR)
builder.setConfigurationName("KotGB on Desktop")
builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL)
.addAttribute("level", Level.DEBUG))
val appenderBuilder = builder.newAppender("Stdout", "CONSOLE").addAttribute("target",
ConsoleAppender.Target.SYSTEM_OUT)
appenderBuilder.add(builder.newLayout("PatternLayout")
.addAttribute("pattern", "[%d{HH:mm:ss.SSS}] [%t] [%level] %C{1}: %msg%n"))
appenderBuilder.add(builder.newFilter("MarkerFilter", Filter.Result.DENY, Filter.Result.NEUTRAL)
.addAttribute("marker", "FLOW"))
builder.add(appenderBuilder)
builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG)
.add(builder.newAppenderRef("Stdout")).addAttribute("additivity", false))
builder.add(builder.newRootLogger(Level.DEBUG).add(builder.newAppenderRef("Stdout")).addAttribute("additivity", false))
Configurator.initialize(builder.build())
val logger = KotlinLogging.logger {}
val parser = ArgumentParsers.newArgumentParser("KotGB", true)
.description("A Gameboy Emulator, written in Kotlin")
parser.addArgument("--file")
.dest("file")
.help("The path of a file to load immediately")
.required(false)
.nargs(1)
.type(String::class.java)
parser.addArgument("--breakAt")
.dest("breakpoints")
.help("Adds a breakpoint")
.required(false)
.nargs("+")
.setDefault(ArrayList<String>())
.type(String::class.java)
parser.addArgument("--debug")
.dest("debug")
.action(Arguments.storeTrue())
.help("Enables debugging by default")
.setDefault(false)
.required(false)
parser.addArgument("--jit")
.dest("jit")
.action(Arguments.storeTrue())
.help("Uses the experimental JIT recompiler")
.setDefault(false)
.required(false)
var namespace: Namespace? = null
try {
namespace = parser.parseArgs(args)
} catch (e: ArgumentParserException) {
parser.handleError(e)
System.exit(1)
}
val parsedArgs = namespace!!.attrs
val useJit = parsedArgs.containsKey("jit")
&& parsedArgs["jit"] != null && parsedArgs["jit"] as Boolean
var jitWorks = false
if (useJit) {
try {
JITTest().test()
jitWorks = true
} catch (e: Exception) {
logger.error(e, { "JIT is unavailable" })
} catch (e: Error) {
logger.error(e, { "JIT is unavailable" })
}
}
val env = EmulationEnvironment(
cpuFactory = {
if (useJit && jitWorks)
CPU(it, JITExecutor())
else
CPU(it)
},
cpuState = {
if (useJit && jitWorks) {
"Cached blocks: ${(it.executor as JITExecutor).manager.getCount()}," +
" errors: ${(it.executor as JITExecutor).manager.errorCount}"
} else {
null
}
},
openFile = {
callback ->
val dialog = FileDialog()
dialog.addFilter(".gb", ".gbc")
val path = dialog.openSingle()
if (path != null) {
callback(FileHandle(path))
}
}
)
thread {
Thread.sleep(10000)
Application.launch(DebuggingApplication::class.java)
}
val config = Lwjgl3ApplicationConfiguration()
config.setWindowedMode(800, 600)
config.useVsync(true)
Lwjgl3Application(KotGB(parsedArgs, env), config)
}
}
| mit | 8bb49fb51c222fb888a699d8355475e8 | 39.244604 | 127 | 0.585091 | 4.540584 | false | true | false | false |
RP-Kit/RPKit | bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/speaker/RPKChatChannelSpeakerService.kt | 1 | 3669 | /*
* 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.chat.bukkit.speaker
import com.rpkit.chat.bukkit.RPKChatBukkit
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannel
import com.rpkit.chat.bukkit.database.table.RPKChatChannelSpeakerTable
import com.rpkit.core.service.Service
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile
import java.util.concurrent.CompletableFuture
import java.util.logging.Level
/**
* Provides chat channel speaker related operations.
*/
class RPKChatChannelSpeakerService(override val plugin: RPKChatBukkit) : Service {
/**
* Gets which channel a Minecraft profile is speaking in.
* If the Minecraft profile is not currently speaking in a channel, null is returned
*
* @param minecraftProfile The Minecraft profile
* @return The chat channel, or null if the Minecraft profile is not currently speaking
*/
fun getMinecraftProfileChannel(minecraftProfile: RPKMinecraftProfile): CompletableFuture<RPKChatChannel?> {
return plugin.database.getTable(RPKChatChannelSpeakerTable::class.java).get(minecraftProfile)
.thenApply { speaker -> speaker?.chatChannel }
}
/**
* Sets which channel a Minecraft profile is speaking in.
*
* @param minecraftProfile The Minecraft profile
* @param chatChannel The chat channel to set
*/
fun setMinecraftProfileChannel(minecraftProfile: RPKMinecraftProfile, chatChannel: RPKChatChannel?): CompletableFuture<Void> {
val table = plugin.database.getTable(RPKChatChannelSpeakerTable::class.java)
return table.get(minecraftProfile).thenAcceptAsync { chatChannelSpeaker ->
if (chatChannelSpeaker == null) {
if (chatChannel != null) {
table.insert(RPKChatChannelSpeaker(minecraftProfile = minecraftProfile, chatChannel = chatChannel)).join()
}
} else {
if (chatChannel == null) {
table.delete(chatChannelSpeaker).join()
} else {
chatChannelSpeaker.chatChannel = chatChannel
table.update(chatChannelSpeaker).join()
}
}
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to set minecraft profile channel", exception)
throw exception
}
}
/**
* Stops a Minecraft profile speaking in any channels.
*
* @param minecraftProfile The Minecraft profile to stop speaking
*/
fun removeMinecraftProfileChannel(minecraftProfile: RPKMinecraftProfile): CompletableFuture<Void> {
val table = plugin.database.getTable(RPKChatChannelSpeakerTable::class.java)
return table.get(minecraftProfile).thenAcceptAsync { chatChannelSpeaker ->
if (chatChannelSpeaker != null) {
table.delete(chatChannelSpeaker).join()
}
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to remove minecraft profile channel", exception)
throw exception
}
}
} | apache-2.0 | 1e684764a8f3f52fe931703eb2031696 | 40.704545 | 130 | 0.689016 | 5.145863 | false | false | false | false |
MichaelEvans/kotlin-koans | src/v_collections/C_AllAnyAndOtherPredicates.kt | 8 | 1018 | package v_collections
fun example2(list: List<Int>) {
val isZero: (Int) -> Boolean = { it == 0 }
val hasZero: Boolean = list.any(isZero)
val allZeros: Boolean = list.all(isZero)
val numberOfZeros: Int = list.count(isZero)
val firstPositiveNumber: Int? = list.firstOrNull { it > 0 }
}
fun Customer.isFrom(city: City): Boolean {
// Return true if the customer is from the given city
todoCollectionTask()
}
fun Shop.checkAllCustomersAreFrom(city: City): Boolean {
// Return true if all customers are from the given city
todoCollectionTask()
}
fun Shop.hasCustomerFrom(city: City): Boolean {
// Check there is at least one customer from the given city
todoCollectionTask()
}
fun Shop.countCustomersFrom(city: City): Int {
// Returns the number of customers from the given city
todoCollectionTask()
}
fun Shop.findAnyCustomerFrom(city: City): Customer? {
// Return a customer who lives in the given city or null if there is none
todoCollectionTask()
}
| mit | bad7b247df22453c37d82a1103320dcc | 25.102564 | 77 | 0.700393 | 4.039683 | false | false | false | false |
Burning-Man-Earth/iBurn-Android | iBurn/src/main/java/com/gaiagps/iburn/database/PlayaItem.kt | 1 | 1608 | package com.gaiagps.iburn.database
/**
* Created by dbro on 6/6/17.
*/
/*
Kotlin models on ice pending release of https://youtrack.jetbrains.com/issue/KT-18048
abstract class PlayaItem(
@PrimaryKey @ColumnInfo(name = ColId) val id: Int = 0,
@ColumnInfo(name = ColName) val name: String,
@ColumnInfo(name = ColDesc) val description: String,
@ColumnInfo(name = ColUrl) val url: String,
@ColumnInfo(name = ColContact) val contact: String,
@ColumnInfo(name = ColPlayaAddress) val playaAddress: String?,
@ColumnInfo(name = ColPlayaId) val playaId: String,
@Embedded val location: Location,
@ColumnInfo(name = ColFavorite) val isFavorite: Boolean) : Serializable {
companion object {
const val ColId = "id"
const val ColName = "name"
const val ColDesc = "description"
const val ColUrl = "url"
const val ColContact = "contact"
const val ColPlayaAddress = "playa_address"
const val ColPlayaId = "playa_id"
const val ColFavorite = "favorite"
}
}
class Location(@ColumnInfo(name = ColLatitude) val latitude: Float,
@ColumnInfo(name = ColLongitude) val longitude: Float) {
companion object {
const val ColLatitude = "latitude"
const val ColLongitude = "longitude"
}
}
*/ | mpl-2.0 | 023c15625f348cce61b53104670ee444 | 40.25641 | 105 | 0.542289 | 4.647399 | false | false | false | false |
signed/intellij-community | plugins/git4idea/tests/git4idea/rebase/GitRebaseBaseTest.kt | 1 | 7773 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.rebase
import com.intellij.dvcs.repo.Repository
import com.intellij.notification.Notification
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.Executor
import git4idea.GitUtil
import git4idea.branch.GitRebaseParams
import git4idea.repo.GitRepository
import git4idea.test.*
abstract class GitRebaseBaseTest : GitPlatformTest() {
protected val LOCAL_CHANGES_WARNING : String = "Note that some local changes were <a>stashed</a> before rebase."
override fun createRepository(rootDir: String) = createRepository(myProject, rootDir, false)
override fun getDebugLogCategories() = super.getDebugLogCategories().plus("#git4idea.rebase")
protected fun GitRepository.`diverge feature and master`() {
build(this) {
master {
0()
1()
}
feature(0) {
2()
}
}
}
protected fun GitRepository.`place feature above master`() {
build(this) {
master {
0()
1()
}
feature {
2()
}
}
}
protected fun GitRepository.`place feature below master`() {
build(this) {
master {
0()
1()
}
feature(0) {
}
}
}
protected fun GitRepository.`place feature on master`() {
build(this) {
master {
0()
1()
}
feature {}
}
}
protected fun GitRepository.`prepare simple conflict`() {
build(this) {
master {
0("c.txt")
1("c.txt")
}
feature(0) {
2("c.txt")
}
}
}
protected fun GitRepository.`make rebase fail on 2nd commit`() {
build(this) {
master {
0()
1("m.txt")
}
feature(0) {
2()
3("m.txt")
}
}
`make rebase fail after resolving conflicts`()
}
protected fun GitRepository.`make rebase fail after resolving conflicts`() {
vcsHelper.onMerge {
resolveConflicts(this)
myGit.setShouldRebaseFail { true }
}
}
protected fun resolveConflicts(repository: GitRepository) {
cd(repository)
git("add -u .")
}
protected fun assertSuccessfulRebaseNotification(message: String) : Notification {
return assertSuccessfulNotification("Rebase Successful", message)
}
protected fun GitRepository.`assert feature rebased on master`() {
assertRebased(this, "feature", "master")
}
protected fun GitRepository.`assert feature not rebased on master`() {
assertNotRebased("feature", "master", this)
}
protected fun assertRebased(repository: GitRepository, feature: String, master: String) {
cd(repository)
assertEquals("$feature is not rebased on $master!", git("rev-parse " + master), git("merge-base $feature $master"))
}
protected fun assertNotRebased(feature: String, master: String, repository: GitRepository) {
cd(repository)
assertFalse("$feature is unexpectedly rebased on $master" + GitUtil.mention(repository),
git("rev-parse " + master) == git("merge-base $feature $master"))
}
protected fun assertNoRebaseInProgress(repository: GitRepository) {
assertEquals(Repository.State.NORMAL, repository.state)
}
protected fun assertNoRebaseInProgress(repositories: Collection<GitRepository>) {
for (repository in repositories) {
assertNoRebaseInProgress(repository)
}
}
protected fun GitRepository.assertRebaseInProgress() {
assertEquals(Repository.State.REBASING, this.state)
}
protected fun GitRepository.assertNoLocalChanges() {
assertEquals("There should be no local changes!", "", gitStatus())
}
protected fun GitRepository.hasConflict(file: String) : Boolean {
return ("UU " + file).equals(git(this, "status --porcelain"));
}
protected fun GitRepository.assertConflict(file: String) {
assertTrue("Conflict was expected for " + file + ", but git status doesn't show it: \n${git(this, "status --porcelain")}",
hasConflict(file))
}
protected fun `assert conflict not resolved notification`() {
assertWarningNotification("Rebase Suspended",
"""
You have to <a>resolve</a> the conflicts and <a>continue</a> rebase.<br/>
If you want to start from the beginning, you can <a>abort</a> rebase.
""")
}
protected fun `assert conflict not resolved notification with link to stash`() {
assertWarningNotification("Rebase Suspended",
"""
You have to <a>resolve</a> the conflicts and <a>continue</a> rebase.<br/>
If you want to start from the beginning, you can <a>abort</a> rebase.<br/>
$LOCAL_CHANGES_WARNING
""")
}
protected fun `assert unknown error notification`() {
assertErrorNotification("Rebase Failed",
"""
$UNKNOWN_ERROR_TEXT<br/>
<a>Retry.</a>
""")
}
protected fun `assert unknown error notification with link to abort`(afterContinue : Boolean = false) {
val expectedTitle = if (afterContinue) "Continue Rebase Failed" else "Rebase Failed";
assertErrorNotification(expectedTitle,
"""
$UNKNOWN_ERROR_TEXT<br/>
You can <a>retry</a> or <a>abort</a> rebase.
""")
}
protected fun `assert unknown error notification with link to stash`() {
assertErrorNotification("Rebase Failed",
"""
$UNKNOWN_ERROR_TEXT<br/>
<a>Retry.</a><br/>
$LOCAL_CHANGES_WARNING
""")
}
protected fun `assert error about unstaged file before continue rebase`(file : String) {
assertErrorNotification("Continue Rebase Failed",
"""
$file: needs update
You must edit all merge conflicts
and then mark them as resolved using git add
You can <a>retry</a> or <a>abort</a> rebase.
""")
}
class LocalChange(val repository: GitRepository, val filePath: String, val content: String = "Some content") {
fun generate() : LocalChange {
cd(repository)
file(filePath).create(content).add()
return this
}
fun verify() {
assertNewFile(repository, filePath, content)
}
fun assertNewFile(repository: GitRepository, file: String, content: String) {
cd(repository)
assertEquals("Incorrect git status output", "A " + file, git("status --porcelain"))
assertEquals("Incorrect content of the file [$file]", content, Executor.cat(file))
}
}
protected open class GitTestingRebaseProcess(project: Project, params: GitRebaseParams, val repositories: Collection<GitRepository>) :
GitRebaseProcess(project, GitRebaseSpec.forNewRebase(project, params, repositories, EmptyProgressIndicator()), null) {
constructor(project: Project, params: GitRebaseParams, repository: GitRepository) : this(project, params, listOf(repository))
override fun getDirtyRoots(repositories: Collection<GitRepository>): Collection<GitRepository> {
return repositories.filter { it.isDirty() }
}
protected fun GitRepository.isDirty(): Boolean {
return !gitStatus().isEmpty();
}
}
}
private fun GitRepository.gitStatus() = git(this, "status --porcelain").trim()
| apache-2.0 | 1d5ef790312e322c8bdca7366a63c5f8 | 29.245136 | 136 | 0.661006 | 4.490468 | false | false | false | false |
ericberman/MyFlightbookAndroid | app/src/main/java/com/myflightbook/android/webservices/CommitFlightSvc.kt | 1 | 4274 | /*
MyFlightbook for Android - provides native access to MyFlightbook
pilot's logbook
Copyright (C) 2017-2022 MyFlightbook, LLC
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.myflightbook.android.webservices
import android.content.Context
import android.util.Log
import com.myflightbook.android.R
import com.myflightbook.android.marshal.MarshalDate
import com.myflightbook.android.marshal.MarshalDouble
import model.*
import org.ksoap2.serialization.PropertyInfo
import org.ksoap2.serialization.SoapObject
import org.ksoap2.serialization.SoapSerializationEnvelope
class CommitFlightSvc : MFBSoap() {
override fun addMappings(e: SoapSerializationEnvelope) {
e.addMapping(NAMESPACE, "CommitFlightWithOptionsResult", LogbookEntry::class.java)
e.addMapping(NAMESPACE, "le", LogbookEntry::class.java)
e.addMapping(NAMESPACE, "LogbookEntry", LogbookEntry::class.java)
e.addMapping(NAMESPACE, "CustomFlightProperty", FlightProperty::class.java)
e.addMapping(NAMESPACE, "MFBImageInfo", MFBImageInfo::class.java)
e.addMapping(NAMESPACE, "LatLong", LatLong::class.java)
val mdt = MarshalDate()
val md = MarshalDouble()
mdt.register(e)
md.register(e)
}
fun fCommitFlightForUser(szAuthToken: String?, le: LogbookEntry, c: Context): Boolean {
val request = setMethod("CommitFlightWithOptions")
request.addProperty("szAuthUserToken", szAuthToken)
val piLe = PropertyInfo()
val pipo = PropertyInfo()
piLe.name = "le"
piLe.type = "LogbookEntry"
piLe.value = le
piLe.namespace = NAMESPACE
pipo.name = "po"
pipo.type = "PostingOptions"
pipo.value = null
pipo.namespace = NAMESPACE
request.addProperty(piLe)
request.addProperty(pipo)
// The date of flight is done in local time; need to convert it to
// a UTC time that looks like the correct local time so that it records
// correctly over the wire (same as in iPhone version.
// save the date, since we're making a live copy
val dtSave = le.dtFlight
le.dtFlight = MFBUtil.getUTCDateFromLocalDate(le.dtFlight)
if (le.rgFlightImages == null) le.imagesForFlight
val rgmfbii = le.rgFlightImages
?: throw NullPointerException("le.rgFlightImages is null")
le.rgFlightImages = arrayOf()
val result = invoke(c) as SoapObject? ?: return false
try {
val leReturn = LogbookEntry()
leReturn.fromProperties(result)
le.szError = leReturn.szError
le.idFlight = leReturn.idFlight
var iImg = 1
for (mfbii in rgmfbii) {
val szFmtUploadProgress = c.getString(R.string.prgUploadingImages)
val szStatus = String.format(szFmtUploadProgress, iImg, rgmfbii.size)
mProgress?.notifyProgress(
iImg * 100 / rgmfbii.size,
szStatus
)
// skip anything that is already on the server.
if (!mfbii.isOnServer()) {
mfbii.setKey(leReturn.idFlight)
if (!mfbii.uploadPendingImage(mfbii.id, c)) Log.w(
MFBConstants.LOG_TAG,
"Image Upload failed"
)
}
iImg++
}
le.deletePendingImagesForFlight()
} catch (e: Exception) {
lastError += e.message
}
le.dtFlight = dtSave
le.szError = lastError
return lastError.isEmpty()
}
} | gpl-3.0 | 949ca2ef7d7c5447336a26d24b4185b6 | 40.105769 | 91 | 0.644361 | 4.339086 | false | false | false | false |
Biacode/escommons | escommons-persistence/src/test/kotlin/org/biacode/escommons/persistence/repository/EsRepositoryIntegrationTest.kt | 1 | 4922 | package org.biacode.escommons.persistence.repository
import org.assertj.core.api.Assertions.assertThat
import org.biacode.escommons.core.test.AbstractEsCommonsIntegrationTest
import org.biacode.escommons.toolkit.component.EsCommonsClientWrapper
import org.elasticsearch.client.RequestOptions
import org.elasticsearch.client.RestHighLevelClient
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.ComponentScan
import java.util.*
/**
* Created by Arthur Asatryan.
* Date: 3/30/18
* Time: 5:05 PM
*/
@ComponentScan("org.biacode.escommons.persistence.repository")
class EsRepositoryIntegrationTest : AbstractEsCommonsIntegrationTest() {
override fun mappings(): String = "escommons_test_person"
//region Dependencies
@Autowired
private lateinit var esClient: RestHighLevelClient
@Autowired
private lateinit var personTestRepository: PersonTestRepository
@Autowired
private lateinit var esCommonsClientWrapper: EsCommonsClientWrapper
//endregion
//region Test methods
@Test
fun `test is alive`() {
esClient.ping(RequestOptions.DEFAULT)
}
@Test
fun `test save single document`() {
// given
val indexName = prepareIndex()
val person = Person(UUID.randomUUID().toString())
person.id = UUID.randomUUID().toString()
assertThat(personTestRepository.save(person, indexName)).isTrue()
}
@Test
fun `test save multiple documents`() {
// given
val indexName = prepareIndex()
(1..100).map {
val person = Person(UUID.randomUUID().toString())
person.id = UUID.randomUUID().toString()
person
}.toList().let { persons ->
// when
personTestRepository.save(persons, indexName).let {
// then
refreshIndex(indexName)
assertThat(it).isTrue()
}
}
}
@Test
fun `test delete single document`() {
// given
persistPerson().let { (indexName, person) ->
// when
val delete = personTestRepository.delete(person.id, indexName)
refreshIndex(indexName)
// then
assertThat(delete).isTrue()
// then
assertThat(personTestRepository.findById(person.id, indexName).isPresent).isFalse()
}
}
@Test
fun `test delete multiple documents`() {
// given
val indexName = prepareIndex()
val otherPerson = persistPerson(indexName = indexName).second.id
val persons = listOf<String>(persistPerson(indexName = indexName).second.id, persistPerson(indexName = indexName).second.id)
refreshIndex(indexName)
// when
personTestRepository.delete(persons, indexName).let {
refreshIndex(indexName)
// then
assertThat(it).isFalse()
// then
assertThat(personTestRepository.findByIds(persons, indexName).size).isEqualTo(0)
// then
assertThat(personTestRepository.findById(otherPerson, indexName).isPresent).isTrue()
}
}
@Test
fun `test get single document`() {
// given
val indexName = prepareIndex()
// other person
persistPerson(indexName = indexName).second
val person = persistPerson(indexName = indexName).second
refreshIndex(indexName)
// when
personTestRepository.findById(person.id, indexName).let {
// then
assertThat(it.isPresent).isTrue()
// then
assertThat(it.get()).isEqualTo(person)
}
}
@Test
fun `test get multiple documents`() {
// given
val indexName = prepareIndex()
// other person
persistPerson(indexName = indexName).second
val persons = listOf(persistPerson(indexName = indexName).second, persistPerson(indexName = indexName).second)
val personIds = persons.map { person -> person.id }
refreshIndex(indexName)
// when
personTestRepository.findByIds(personIds, indexName).let {
// then
assertThat(it).isEqualTo(persons)
}
}
//endregion
//region Utility methods
private fun prepareIndex(): String {
val indexName = UUID.randomUUID().toString()
esCommonsClientWrapper.createIndex(indexName, mappings())
return indexName
}
private fun persistPerson(
id: String = UUID.randomUUID().toString(),
firstName: String = UUID.randomUUID().toString(),
indexName: String = prepareIndex()
): Pair<String, Person> {
val person = Person(firstName)
person.id = id
personTestRepository.save(person, indexName)
return indexName to person
}
//endregion
} | mit | 54ddafb5044a323313729844f957f2a0 | 31.388158 | 132 | 0.632466 | 4.917083 | false | true | false | false |
danrien/projectBlue | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/shared/policies/ratelimiting/RateLimiter.kt | 1 | 1650 | package com.lasthopesoftware.bluewater.shared.policies.ratelimiting
import com.namehillsoftware.handoff.promises.Promise
import com.namehillsoftware.handoff.promises.propagation.PromiseProxy
import com.namehillsoftware.handoff.promises.response.ImmediateResponse
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.Executor
import java.util.concurrent.Semaphore
import java.util.concurrent.atomic.AtomicReference
class RateLimiter<T>(private val executor: Executor, rate: Int): RateLimitPromises<T>, Runnable {
private val queueProcessorReference = AtomicReference<RateLimiter<T>>()
private val semaphore = Semaphore(rate)
private val queuedPromises = ConcurrentLinkedQueue<() -> Promise<Unit>>()
private val semaphoreReleasingResolveHandler = ImmediateResponse<T, Unit> { semaphore.release() }
private val semaphoreReleasingRejectionHandler = ImmediateResponse<Throwable, Unit> { semaphore.release() }
override fun limit(factory: () -> Promise<T>): Promise<T> {
return Promise<T> { m ->
val promiseProxy = PromiseProxy(m)
// Use resolve/rejection handler over `must` so that errors don't propagate as unhandled
queuedPromises.offer { factory().also(promiseProxy::proxy).then(semaphoreReleasingResolveHandler, semaphoreReleasingRejectionHandler) }
if (queueProcessorReference.compareAndSet(null, this)) executor.execute(this)
}
}
override fun run() {
try {
var promiseFactory: (() -> Promise<Unit>)?
while (queuedPromises.poll().also { promiseFactory = it } != null) {
semaphore.acquire()
promiseFactory?.invoke()
}
} finally {
queueProcessorReference.set(null)
}
}
}
| lgpl-3.0 | 5c6ff785e4d9b90a19794b6d74bb80b3 | 41.307692 | 138 | 0.778182 | 4.125 | false | false | false | false |
cypressious/learning-spaces | app/src/main/java/de/maxvogler/learningspaces/services/MarkerFactory.kt | 1 | 1948 | package de.maxvogler.learningspaces.services
import android.content.Context
import android.graphics.*
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.MarkerOptions
import de.maxvogler.learningspaces.R
import de.maxvogler.learningspaces.models.Location
public class MarkerFactory(private val context: Context) {
public fun createMarker(location: Location): MarkerOptions {
if (location.coordinates == null) {
throw IllegalArgumentException("Cannot create marker without position for " + location)
}
return MarkerOptions()
.position(location.coordinates)
.icon(BitmapDescriptorFactory.fromBitmap(createIcon(location)))
.flat(true)
.anchor(0.5f, 0.5f)
}
public fun createSelectedMarker(location: Location): MarkerOptions {
return MarkerOptions().position(location.coordinates)
}
public fun createIcon(location: Location): Bitmap {
val o = BitmapFactory.Options()
o.inMutable = true
val bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.ic_local_library_black_24dp, o)
val color = if (location.openingHours.isClosed()) {
context.resources.getColor(R.color.location_unavailable)
} else {
getColor(location.freeSeatsPercentage)
}
val paint = Paint()
paint.setColorFilter(LightingColorFilter(0, color))
Canvas(bitmap).drawBitmap(bitmap, 0f, 0f, paint)
return bitmap
}
private fun getColor(percentage: Float): Int {
if (percentage > 0.4) {
return context.resources.getColor(R.color.location_good)
} else if (percentage > 0.2) {
return context.resources.getColor(R.color.location_okay)
} else {
return context.resources.getColor(R.color.location_bad)
}
}
}
| gpl-2.0 | 527f24568112026b7ba7f9230af42201 | 33.175439 | 111 | 0.667864 | 4.562061 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/twitter/joauth/Signature.kt | 1 | 3876 | package com.baulsupp.okurl.services.twitter.joauth
import com.baulsupp.okurl.services.twitter.TwitterAuthInterceptor
import com.baulsupp.okurl.services.twitter.TwitterCredentials
import okhttp3.FormBody
import okhttp3.Request
import okhttp3.RequestBody
import okio.Buffer
import java.nio.charset.Charset
import java.security.SecureRandom
import java.time.Clock
import java.util.logging.Level
import java.util.logging.Logger
class Signature(
private val clock: Clock = Clock.systemDefaultZone(),
private val random: () -> Long = { SecureRandom().nextLong() }
) {
private fun quoted(str: String): String {
return "\"" + str + "\""
}
private fun generateTimestamp(): Long {
val timestamp = clock.millis()
return timestamp / 1000
}
private fun generateNonce(): String {
return java.lang.Long.toString(Math.abs(random())) + clock.millis()
}
fun generateAuthorization(request: Request, credentials: TwitterCredentials): String {
val timestampSecs = generateTimestamp()
val nonce = generateNonce()
val oAuth1Params = OAuthParams.OAuth1Params(
credentials.token, credentials.consumerKey!!, nonce, timestampSecs,
java.lang.Long.toString(timestampSecs), "", OAuthParams.HMAC_SHA1,
OAuthParams.ONE_DOT_OH
)
val javaParams = mutableListOf<Pair<String, String>>()
val queryParamNames = request.url.queryParameterNames
for (queryParam in queryParamNames) {
val values = request.url.queryParameterValues(queryParam)
values.mapTo(javaParams) {
Pair(UrlCodec.encode(queryParam)!!, UrlCodec.encode(it)!!)
}
}
if (request.method == "POST") {
val body: RequestBody = request.body!!
if (body is FormBody) {
(0 until body.size).mapTo(javaParams) {
Pair(body.encodedName(it), body.encodedValue(it))
}
} else if (isFormContentType(request)) {
val buffer = Buffer()
body.writeTo(buffer)
val encodedBody = buffer.readString(Charset.forName("UTF-8"))
val handler = KeyValueHandler.DuplicateKeyValueHandler()
val bodyParser = StandardKeyValueParser("&", "=")
bodyParser.parse(encodedBody, listOf<KeyValueHandler>(handler))
javaParams.addAll(handler.toList())
}
}
val normalized = StandardNormalizer.normalize(
if (request.isHttps) "https" else "http", request.url.host, request.url.port,
request.method, request.url.encodedPath, javaParams, oAuth1Params
)
log.log(Level.FINE, "normalised $normalized")
log.log(Level.FINE, "secret " + credentials.secret)
log.log(Level.FINE, "consumerSecret " + credentials.consumerSecret)
val signature =
StandardSigner.getString(normalized, OAuthParams.HMAC_SHA1, credentials.secret!!, credentials.consumerSecret!!)
val oauthHeaders = linkedMapOf<String, String>()
if (credentials.consumerKey != null) {
oauthHeaders[OAuthParams.OAUTH_CONSUMER_KEY] = quoted(credentials.consumerKey!!)
}
oauthHeaders[OAuthParams.OAUTH_NONCE] = quoted(nonce)
oauthHeaders[OAuthParams.OAUTH_SIGNATURE] = quoted(signature)
oauthHeaders[OAuthParams.OAUTH_SIGNATURE_METHOD] = quoted(OAuthParams.HMAC_SHA1)
oauthHeaders[OAuthParams.OAUTH_TIMESTAMP] = quoted(java.lang.Long.toString(timestampSecs))
if (credentials.token != null) {
oauthHeaders[OAuthParams.OAUTH_TOKEN] = quoted(credentials.token!!)
}
oauthHeaders[OAuthParams.OAUTH_VERSION] = quoted(OAuthParams.ONE_DOT_OH)
return "OAuth " + oauthHeaders.entries.joinToString(", ") { it.key + "=" + it.value }
}
private fun isFormContentType(request: Request): Boolean {
return request.body!!.contentType()!!.toString().startsWith(
"application/x-www-form-urlencoded"
)
}
companion object {
private val log = Logger.getLogger(TwitterAuthInterceptor::class.java.name)
}
}
| apache-2.0 | b0e2545db3df98a6a5c1dca5e84b4949 | 33.607143 | 117 | 0.707172 | 4.123404 | false | false | false | false |
mplatvoet/kovenant | projects/rx/src/main/kotlin/observables.kt | 1 | 7988 | /*
* Copyright (c) 2016 Mark Platvoet<[email protected]>
*
* 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,
* THE SOFTWARE.
*/
package nl.komponents.kovenant.rx
import nl.komponents.kovenant.*
import rx.Observable
import rx.Subscriber
import java.util.*
enum class EmitStrategy {
FIRST, LAST
}
/**
* Turn an `Observable<V>` into a `Promise<V, Exception>`
*
* @param context the context of the new promise, `Kovenant.context` by default
* @param strategy the `EmitStrategy` to be used, `EmitStrategy.FIRST` by default
* @param emptyFactory the value to be calculated and used if the `Observable` hasn't emitted any values
*/
fun <V> Observable<V>.toPromise(context: Context = Kovenant.context,
strategy: EmitStrategy = EmitStrategy.FIRST,
emptyFactory: () -> V)
: Promise<V, Exception> = toPromise(context, strategy, EmptyPolicy.resolve(emptyFactory))
/**
* Turn an `Observable<V>` into a `Promise<V, Exception>`
*
* @param context the context of the new promise, `Kovenant.context` by default
* @param strategy the `EmitStrategy` to be used, `EmitStrategy.FIRST` by default
* @param emptyPolicy to policy to be used when the `Observable` hasn't emitted any values, rejection by default
*/
fun <V> Observable<V>.toPromise(context: Context = Kovenant.context,
strategy: EmitStrategy = EmitStrategy.FIRST,
emptyPolicy: EmptyPolicy<V, Exception> = EmptyPolicy.default()): Promise<V, Exception> {
val subscriber: PromiseSubscriber<V> = when (strategy) {
EmitStrategy.FIRST -> FirstValueSubscriber(context, emptyPolicy)
EmitStrategy.LAST -> LastValueSubscriber(context, emptyPolicy)
}
subscribe(subscriber)
return subscriber.promise
}
/**
* Turn an `Observable<V>` into a `Promise<V, Exception>`
*
* @param context the context of the new promise, `Kovenant.context` by default
* @param strategy the `EmitStrategy` to be used, `EmitStrategy.FIRST` by default
* @param defaultValue the value to be used when the `Observable` hasn't emitted any values
*/
fun <V> Observable<V>.toPromise(defaultValue: V, context: Context = Kovenant.context,
strategy: EmitStrategy = EmitStrategy.FIRST)
: Promise<V, Exception> = toPromise(context, strategy, EmptyPolicy.resolve(defaultValue))
/**
* Turn an `Observable<V>` into a `Promise<List<V>, Exception>`
*
* @param context the context of the new promise, `Kovenant.context` by default
*/
fun <V> Observable<V>.toListPromise(context: Context = Kovenant.context): Promise<List<V>, Exception> {
val observer = ListValuesSubscriber<V>(context)
subscribe(observer)
return observer.promise
}
private abstract class PromiseSubscriber<V> : Subscriber<V>() {
abstract val promise: Promise<V, Exception>
}
private class FirstValueSubscriber<V>(context: Context,
private val emptyPolicy: EmptyPolicy<V, Exception>) : PromiseSubscriber<V>() {
private val deferred = deferred<V, Exception>(context)
override val promise: Promise<V, Exception> = deferred.promise
override fun onNext(value: V) {
deferred.resolve(value)
unsubscribe()
}
override fun onError(error: Throwable?) = deferred.reject(error.asException())
override fun onCompleted() = emptyPolicy.apply(deferred)
}
private class LastValueSubscriber<V>(context: Context,
private val emptyPolicy: EmptyPolicy<V, Exception>) : PromiseSubscriber<V>() {
//Rx always executes on same thread/worker, no need to sync
private var value: V? = null
private var hasValue = false
private val deferred = deferred<V, Exception>(context)
override val promise: Promise<V, Exception> = deferred.promise
override fun onNext(value: V) {
this.value = value
hasValue = true
}
override fun onError(error: Throwable?) = deferred.reject(error.asException())
override fun onCompleted() {
if (hasValue) {
@Suppress("UNCHECKED_CAST")
deferred.resolve(value as V)
} else {
emptyPolicy.apply(deferred)
}
}
}
/**
* EmptyPolicy describes a strategy to apply when Observables are completed but without
* emitting any values
*/
interface EmptyPolicy<V, E> {
companion object {
private val default = FactoryRejectPolicy<Any>() {
EmptyException("completed without elements")
}
@Suppress("UNCHECKED_CAST")
fun <V> default(): EmptyPolicy<V, Exception> = default as EmptyPolicy<V, Exception>
/**
* Creates an `EmptyPolicy` that resolves as successful with the value
* generated by the `factory`
*/
fun <V> resolve(factory: () -> V): EmptyPolicy<V, Exception> = FactoryResolvePolicy(factory)
/**
* Creates an `EmptyPolicy` that resolves as successful with the provided value
*/
fun <V> resolve(value: V): EmptyPolicy<V, Exception> = ValueResolvePolicy(value)
/**
* Creates an `EmptyPolicy` that resolves as failed with the error
* generated by the `factory`
*/
fun <V> reject(factory: () -> Exception): EmptyPolicy<V, Exception> = FactoryRejectPolicy(factory)
/**
* Creates an `EmptyPolicy` that resolves as failed with the provided error
*/
fun <V> reject(error: Exception): EmptyPolicy<V, Exception> = ValueRejectPolicy(error)
}
fun apply(deferred: Deferred<V, E>)
}
private class FactoryRejectPolicy<V>(private val factory: () -> Exception) : EmptyPolicy<V, Exception> {
override fun apply(deferred: Deferred<V, Exception>) {
deferred.reject(factory())
}
}
private class FactoryResolvePolicy<V>(private val factory: () -> V) : EmptyPolicy<V, Exception> {
override fun apply(deferred: Deferred<V, Exception>) {
deferred.resolve(factory())
}
}
private class ValueResolvePolicy<V>(private val value: V) : EmptyPolicy<V, Exception> {
override fun apply(deferred: Deferred<V, Exception>) {
deferred.resolve(value)
}
}
private class ValueRejectPolicy<V>(private val error: Exception) : EmptyPolicy<V, Exception> {
override fun apply(deferred: Deferred<V, Exception>) {
deferred.reject(error)
}
}
private class ListValuesSubscriber<V>(context: Context) : Subscriber<V>() {
//Rx always executes on same thread/worker, no need to sync
private var values: MutableList<V> = ArrayList()
private val deferred = deferred<List<V>, Exception>(context)
val promise: Promise<List<V>, Exception> = deferred.promise
override fun onNext(value: V) {
values.add(value)
}
override fun onError(error: Throwable?) = deferred.reject(error.asException())
override fun onCompleted() = deferred.resolve(values)
}
fun Throwable?.asException(): Exception = if (this is Exception) this else RuntimeException(this)
| mit | 67d194c65f4d3241ef9eb03899648784 | 36.679245 | 120 | 0.67977 | 4.273943 | false | false | false | false |
halawata13/ArtichForAndroid | app/src/main/java/net/halawata/artich/model/ApiUrlString.kt | 2 | 1179 | package net.halawata.artich.model
import java.net.URLEncoder
object ApiUrlString {
object Hatena {
const val newEntry = "http://b.hatena.ne.jp/entrylist/it.rss"
const val hotEntry = "http://b.hatena.ne.jp/hotentry/it.rss"
fun get(keyword: String): String {
val escaped = escape(keyword)
return "http://b.hatena.ne.jp/keyword/$escaped?mode=rss&sort=count"
}
}
object Qiita {
const val newEntry = "https://qiita.com/api/v2/items"
const val tagList = "https://qiita.com/api/v2/tags?sort=count&per_page=100"
fun get(keyword: String): String {
val escaped = escape(keyword)
return "https://qiita.com/api/v2/tags/$escaped/items"
}
}
object GNews {
const val newEntry = "https://news.google.com/news?hl=ja&ned=us&ie=UTF-8&oe=UTF-8&output=rss&topic=t"
fun get(keyword: String): String {
val escaped = escape(keyword)
return "https://news.google.com/news?hl=ja&ned=us&ie=UTF-8&oe=UTF-8&output=rss&q=" + escaped
}
}
fun escape(keyword: String): String = URLEncoder.encode(keyword, "UTF-8")
}
| mit | ba59a4e1e59183761b5867938d40cea3 | 30.864865 | 109 | 0.608991 | 3.349432 | false | false | false | false |
Ph1b/MaterialAudiobookPlayer | app/src/main/kotlin/de/ph1b/audiobook/features/bookPlaying/selectchapter/SelectChapterViewModel.kt | 1 | 1896 | package de.ph1b.audiobook.features.bookPlaying.selectchapter
import de.ph1b.audiobook.data.Book2
import de.ph1b.audiobook.data.repo.BookRepo2
import de.ph1b.audiobook.playback.PlayerController
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import timber.log.Timber
import javax.inject.Inject
class SelectChapterViewModel
@Inject constructor(
private val bookRepository: BookRepo2,
private val player: PlayerController
) {
private val scope = MainScope()
private val _viewEffects = MutableSharedFlow<SelectChapterViewEffect>(extraBufferCapacity = 1)
val viewEffects: Flow<SelectChapterViewEffect> get() = _viewEffects
lateinit var bookId: Book2.Id
fun viewState(): SelectChapterViewState {
val book = runBlocking { bookRepository.flow(bookId).first() }
if (book == null) {
Timber.d("no book found for $bookId. CloseScreen")
_viewEffects.tryEmit(SelectChapterViewEffect.CloseScreen)
return SelectChapterViewState(emptyList(), null)
}
val chapterMarks = book.chapters.flatMap {
it.chapterMarks
}
val selectedIndex = chapterMarks.indexOf(book.currentMark)
return SelectChapterViewState(chapterMarks, selectedIndex.takeUnless { it == -1 })
}
fun chapterClicked(index: Int) {
scope.launch {
val book = bookRepository.flow(bookId).first() ?: return@launch
var currentIndex = -1
book.chapters.forEach { chapter ->
chapter.chapterMarks.forEach { mark ->
currentIndex++
if (currentIndex == index) {
player.setPosition(mark.startMs, chapter.id)
_viewEffects.tryEmit(SelectChapterViewEffect.CloseScreen)
return@launch
}
}
}
}
}
}
| lgpl-3.0 | 83522ce0da74aca98fa0f91b245993c5 | 30.081967 | 96 | 0.727848 | 4.27991 | false | false | false | false |
macrat/RuuMusic | app/src/main/java/jp/blanktar/ruumusic/util/Preference.kt | 1 | 10461 | package jp.blanktar.ruumusic.util
import android.preference.PreferenceManager
import android.content.SharedPreferences
import android.content.Context
class Preference(val context: Context) {
@JvmField val AudioPrefix = "audio_"
@JvmField val RootDirectory = RuuDirectoryPreferenceHandler("root_directory", defaultPath = "/")
@JvmField val BassBoostEnabled = BooleanPreferenceHandler(AudioPrefix + "bassboost_enabled")
@JvmField val BassBoostLevel = ShortPreferenceHandler(AudioPrefix + "bassboost_level", default = 500)
@JvmField val ReverbEnabled = BooleanPreferenceHandler(AudioPrefix + "reverb_enabled")
@JvmField val ReverbType = ShortPreferenceHandler(AudioPrefix + "reverb_type")
@JvmField val LoudnessEnabled = BooleanPreferenceHandler(AudioPrefix + "loudness_enabled")
@JvmField val LoudnessLevel = IntPreferenceHandler(AudioPrefix + "loudness_level", default = 1000)
@JvmField val EqualizerEnabled = BooleanPreferenceHandler(AudioPrefix + "equalizer_enabled")
@JvmField val EqualizerPreset = ShortPreferenceHandler(AudioPrefix + "equalizer_preset", default = -1)
@JvmField val EqualizerLevel = IntListPreferenceHandler(AudioPrefix + "equalizer_level")
@JvmField val VirtualizerEnabled = BooleanPreferenceHandler(AudioPrefix + "virtualizer_enabled")
@JvmField val VirtualizerMode = IntPreferenceHandler(AudioPrefix + "virtualizer_mode", default = 1)
@JvmField val VirtualizerStrength = ShortPreferenceHandler(AudioPrefix + "virtualizer_strength", default = 500)
// player preference
@JvmField val PlayerAutoShrinkEnabled = BooleanPreferenceHandler("player_auto_shrink_enabled", default = true)
@JvmField val PlayerMusicPathSize = IntPreferenceHandler("player_music_path_size", default = 20)
@JvmField val PlayerMusicNameSize = IntPreferenceHandler("player_music_name_size", default = 40)
// widget preference
@JvmField val UnifiedWidgetMusicPathSize = IntPreferenceHandler("widget_unified_music_path_size", default = 14)
@JvmField val UnifiedWidgetMusicNameSize = IntPreferenceHandler("widget_unified_music_name_size", default = 18)
@JvmField val MusicNameWidgetNameSize = IntPreferenceHandler("widget_musicname_music_name_size", default = 20)
// client state
@JvmField val LastViewPage = IntPreferenceHandler("last_view_page", default = 1)
// player state
@JvmField val RepeatMode = EnumPreferenceHandler("repeat_mode", RepeatModeType.OFF, { x -> RepeatModeType.valueOf(x)})
@JvmField val ShuffleMode = BooleanPreferenceHandler("shuffle_mode")
@JvmField val RecursivePath = RuuDirectoryPreferenceHandler("recursive_path")
@JvmField val SearchQuery = StringPreferenceHandler("search_query")
@JvmField val SearchPath = RuuDirectoryPreferenceHandler("search_path")
@JvmField val LastPlayMusic = RuuFilePreferenceHandler("last_play_music")
@JvmField val LastPlayPosition = IntPreferenceHandler("last_play_position")
// playlist state
@JvmField val CurrentViewPath = RuuDirectoryPreferenceHandler("current_view_path")
@JvmField val LastSearchQuery = StringPreferenceHandler("last_search_query")
// shortcuts
@JvmField val ListedDynamicShortcuts = DirectoriesPreferenceHandler("listed_dynamic_shortcuts")
val listeners = mutableSetOf<PreferenceHandler<*>>()
fun unsetAllListeners() {
while (!listeners.isEmpty()) {
try {
val x = listeners.first()
x.unsetOnChangeListener()
listeners.remove(x)
} catch(e: NoSuchElementException) {
break
}
}
}
abstract inner class PreferenceHandler<T>(val key: String, val default: T) : SharedPreferences.OnSharedPreferenceChangeListener {
var receiver: (() -> Unit)? = null
val sharedPreferences: SharedPreferences
get() = PreferenceManager.getDefaultSharedPreferences(context)
abstract fun get(): T
abstract fun set(value: T)
fun areSet() = sharedPreferences.contains(key)
open fun remove() {
sharedPreferences.edit().remove(key).apply()
}
open override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (receiver != null && key == this.key) {
receiver!!()
}
}
fun setOnChangeListener(listener: () -> Unit) {
if (receiver != null) {
unsetOnChangeListener()
}
receiver = listener
listeners.add(this)
sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
fun setOnChangeListener(listener: OnChangeListener) {
setOnChangeListener {
listener.onChange()
}
}
fun unsetOnChangeListener() {
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
listeners.remove(this)
receiver = null
}
}
abstract class OnChangeListener {
abstract fun onChange()
}
inner class IntPreferenceHandler(key: String, default: Int = 0) : PreferenceHandler<Int>(key, default) {
override fun get() = sharedPreferences.getInt(key, default)
override fun set(value: Int) {
sharedPreferences.edit().putInt(key, value).apply()
}
}
inner class ShortPreferenceHandler(key: String, default: Short = 0) : PreferenceHandler<Short>(key, default) {
override fun get() = sharedPreferences.getInt(key, default.toInt()).toShort()
override fun set(value: Short) {
sharedPreferences.edit().putInt(key, value.toInt()).apply()
}
}
inner class IntListPreferenceHandler(key: String, val defaultInt: Int = 0) : PreferenceHandler<List<Int>>(key, listOf()) {
private fun keyOf(index: Int) = "${key}_${index}"
fun get(index: Int) = sharedPreferences.getInt(keyOf(index), defaultInt)
override fun get(): List<Int> {
val result = mutableListOf<Int>()
var index = 0
while (sharedPreferences.contains(keyOf(index))) {
result.add(get(index))
index++
}
return result
}
fun set(index: Int, value: Int) {
sharedPreferences.edit().putInt(keyOf(index), value).apply()
}
override fun set(value: List<Int>) {
for ((i, x) in value.withIndex()) {
set(i, x)
}
}
override fun remove() {
var index = 0
while (sharedPreferences.contains(keyOf(index))) {
sharedPreferences.edit().remove(keyOf(index)).apply()
index++
}
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (receiver != null && key.startsWith("${this.key}_")) {
receiver!!()
}
}
}
inner class BooleanPreferenceHandler(key: String, default: Boolean = false) : PreferenceHandler<Boolean>(key, default) {
override fun get() = sharedPreferences.getBoolean(key, default)
override fun set(value: Boolean) {
sharedPreferences.edit().putBoolean(key, value).apply()
}
}
inner class StringPreferenceHandler(key: String, default: String? = null) : PreferenceHandler<String?>(key, default) {
override fun get(): String? = sharedPreferences.getString(key, default)
override fun set(value: String?) {
sharedPreferences.edit().putString(key, value).apply()
}
}
inner class RuuFilePreferenceHandler(key: String) : PreferenceHandler<RuuFile?>(key, null) {
override fun get(): RuuFile? {
try {
return RuuFile.getInstance(context, sharedPreferences.getString(key, null) ?: return null)
} catch (e: RuuFileBase.NotFound) {
return default
} catch (e: SecurityException) {
return null
}
}
override fun set(value: RuuFile?) {
if (value == null) {
remove()
} else {
sharedPreferences.edit().putString(key, value.fullPath).apply()
}
}
}
inner class RuuDirectoryPreferenceHandler(key: String, val defaultPath: String? = null) : PreferenceHandler<RuuDirectory?>(key, null) {
override fun get(): RuuDirectory? {
try {
val path = sharedPreferences.getString(key, null)
?: return if (defaultPath == null) null else RuuDirectory.getInstance(context, defaultPath)
return RuuDirectory.getInstance(context, path)
} catch (e: RuuFileBase.NotFound) {
return null
} catch (e: SecurityException) {
return null
}
}
override fun set(value: RuuDirectory?) {
if (value == null) {
remove()
} else {
sharedPreferences.edit().putString(key, value.fullPath).apply()
}
}
}
inner class DirectoriesPreferenceHandler(key: String) : PreferenceHandler<List<RuuDirectory>>(key, listOf()) {
override fun get() = sharedPreferences.getString(key, "")!!.lines().mapNotNull(fun (it): RuuDirectory? {
if (it == "") {
return null
}
try {
return RuuDirectory.getInstance(context, it)
} catch (e: RuuFileBase.NotFound) {
return null
} catch (e: SecurityException) {
return null
}
})
override fun set(value: List<RuuDirectory>) {
return sharedPreferences.edit().putString(key, value.joinToString("\n") { it.fullPath }).apply()
}
}
inner class EnumPreferenceHandler<T: Enum<T>>(key: String, default: T, val asEnum: (String) -> T) : PreferenceHandler<T>(key, default) {
override fun get(): T {
try {
return asEnum(sharedPreferences.getString(key, "")!!)
} catch(e: IllegalArgumentException) {
return default
}
}
override fun set(value: T) {
sharedPreferences.edit().putString(key, value.name).apply()
}
}
}
| mit | 237f0054f58625c40753d704413c2cee | 36.765343 | 140 | 0.625275 | 4.87238 | false | false | false | false |
7hens/KDroid | core/src/main/java/cn/thens/kdroid/core/log/ChunkPrinter.kt | 1 | 822 | package cn.thens.kdroid.core.log
class ChunkPrinter(private val printer: LinePrinter) : StoryPrinter {
override fun print(message: String) {
if (message.isEmpty()) return
val bytes = message.toByteArray()
val length = bytes.size
val pageSize = (length - 1) / CHUNK_SIZE + 1
for (i in 0 until pageSize) {
val offset = i * CHUNK_SIZE
val count = Math.min(length - offset, CHUNK_SIZE)
printChunk(String(bytes, offset, count, Charsets.UTF_8))
}
}
private fun printChunk(chunk: String) {
val lines = chunk.split('\n').dropLastWhile { it.isEmpty() }.toTypedArray()
for (line in lines) {
printer.print(line)
}
}
companion object {
private const val CHUNK_SIZE = 4 * 1024
}
} | apache-2.0 | 900d870f8cdd51ba771770ebaf839a7c | 30.653846 | 83 | 0.588808 | 4.11 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/RsCodeFragmentFactory.kt | 2 | 1755 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi
import com.intellij.openapi.project.Project
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.lang.core.macros.setContext
import org.rust.lang.core.psi.ext.CARGO_WORKSPACE
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.RsMod
import org.rust.lang.core.psi.ext.cargoWorkspace
import org.rust.openapiext.toPsiFile
class RsCodeFragmentFactory(val project: Project) {
private val psiFactory = RsPsiFactory(project)
fun createCrateRelativePath(pathText: String, target: CargoWorkspace.Target): RsPath? {
check(pathText.startsWith("::"))
val vFile = target.crateRoot ?: return null
val crateRoot = vFile.toPsiFile(project) as? RsFile ?: return null
return psiFactory.tryCreatePath(pathText)
?.apply { setContext(crateRoot) }
}
fun createPath(path: String, context: RsElement): RsPath? =
psiFactory.tryCreatePath(path)?.apply {
setContext(context)
containingFile?.putUserData(CARGO_WORKSPACE, context.cargoWorkspace)
}
fun createPathInTmpMod(context: RsMod, importingPath: RsPath, usePath: String, crateName: String?): RsPath? {
val (externCrateItem, useItem) = if (crateName != null) {
"extern crate $crateName;" to "use self::$usePath;"
} else {
"" to "use $usePath;"
}
val mod = psiFactory.createModItem("__tmp__", """
$externCrateItem
use super::*;
$useItem
""")
mod.setContext(context)
return createPath(importingPath.text, mod)
}
}
| mit | 33f60b495d036b929eb168aa2c71c707 | 34.816327 | 113 | 0.670085 | 4.228916 | false | false | false | false |
google/horologist | auth-ui/src/main/java/com/google/android/horologist/auth/ui/googlesignin/GoogleSignInScreen.kt | 1 | 5285 | /*
* 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.auth.ui.googlesignin
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContract
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.wear.compose.material.CircularProgressIndicator
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.auth.api.signin.GoogleSignInStatusCodes
import com.google.android.gms.common.api.ApiException
import com.google.android.horologist.auth.ui.ExperimentalHorologistAuthUiApi
@ExperimentalHorologistAuthUiApi
@Composable
public fun GoogleSignInScreen(
viewModel: GoogleSignInViewModel = viewModel()
) {
var executedOnce by rememberSaveable { mutableStateOf(false) }
val state by viewModel.uiState.collectAsStateWithLifecycle()
when (state) {
AuthGoogleSignInScreenState.Idle -> {
SideEffect {
if (!executedOnce) {
executedOnce = true
viewModel.startAuthFlow()
}
}
}
AuthGoogleSignInScreenState.SelectAccount -> {
val context = LocalContext.current
var googleSignInAccount by remember {
mutableStateOf(GoogleSignIn.getLastSignedInAccount(context))
}
googleSignInAccount?.let { account ->
SideEffect {
viewModel.onAccountSelected(account)
}
} ?: run {
val googleSignInClient = GoogleSignIn.getClient(
context,
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build()
)
val signInRequestLauncher = rememberLauncherForActivityResult(
contract = GoogleSignInContract(googleSignInClient) { viewModel.onAccountSelectionFailed() }
) { account ->
googleSignInAccount = account
googleSignInAccount?.let {
viewModel.onAccountSelected(it)
}
}
SideEffect {
signInRequestLauncher.launch(Unit)
}
}
}
AuthGoogleSignInScreenState.Failed,
is AuthGoogleSignInScreenState.Success -> {
// do nothing
}
}
Box(
modifier = Modifier
.fillMaxSize(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
}
/**
* An [ActivityResultContract] for signing in with the given [GoogleSignInClient].
*/
private class GoogleSignInContract(
private val googleSignInClient: GoogleSignInClient,
private val onTaskFailed: () -> Unit
) : ActivityResultContract<Unit, GoogleSignInAccount?>() {
override fun createIntent(context: Context, input: Unit): Intent =
googleSignInClient.signInIntent
override fun parseResult(resultCode: Int, intent: Intent?): GoogleSignInAccount? {
val task = GoogleSignIn.getSignedInAccountFromIntent(intent)
// As documented, this task must be complete
check(task.isComplete)
return if (task.isSuccessful) {
task.result
} else {
val exception = task.exception
check(exception is ApiException)
val message = GoogleSignInStatusCodes.getStatusCodeString(exception.statusCode)
Log.w(TAG, "Sign in failed: code=${exception.statusCode}, message=$message")
onTaskFailed()
null
}
}
private companion object {
private val TAG = GoogleSignInContract::class.java.simpleName
}
}
| apache-2.0 | 1dacbe5c35054b3606903f981497d7de | 34.952381 | 112 | 0.681552 | 5.285 | false | false | false | false |
google/horologist | media-data/src/test/java/com/google/android/horologist/media/data/mapper/MediaDownloadStatusMapperTest.kt | 1 | 2955 | /*
* 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.
*/
@file:OptIn(ExperimentalHorologistMediaDataApi::class)
package com.google.android.horologist.media.data.mapper
import com.google.android.horologist.media.data.ExperimentalHorologistMediaDataApi
import com.google.android.horologist.media.data.database.model.MediaDownloadEntity
import com.google.android.horologist.media.data.database.model.MediaDownloadEntityStatus
import com.google.android.horologist.media.model.MediaDownload
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@RunWith(Parameterized::class)
class MediaDownloadStatusMapperTest(
private val mediaDownloadEntity: MediaDownloadEntity,
private val expectedStatus: MediaDownload.Status
) {
@Test
fun mapsCorrectly() {
// when
val result = MediaDownloadStatusMapper.map(mediaDownloadEntity)
// then
assertThat(result).isEqualTo(expectedStatus)
}
companion object {
@JvmStatic
@Parameterized.Parameters
fun params() = listOf(
arrayOf(
MediaDownloadEntity(
mediaId = "mediaId",
status = MediaDownloadEntityStatus.NotDownloaded,
progress = 0F,
size = 0L
),
MediaDownload.Status.Idle
),
arrayOf(
MediaDownloadEntity(
mediaId = "mediaId",
status = MediaDownloadEntityStatus.Downloading,
progress = 75F,
size = 12345L
),
MediaDownload.Status.InProgress(75F)
),
arrayOf(
MediaDownloadEntity(
mediaId = "mediaId",
status = MediaDownloadEntityStatus.Downloaded,
progress = 100F,
size = 12345L
),
MediaDownload.Status.Completed
),
arrayOf(
MediaDownloadEntity(
mediaId = "mediaId",
status = MediaDownloadEntityStatus.Failed,
progress = 0F,
size = 0L
),
MediaDownload.Status.Idle
)
)
}
}
| apache-2.0 | ec0ce548423190f82aef70925f601f4e | 32.965517 | 88 | 0.607445 | 5.258007 | false | false | false | false |
googlemaps/android-samples | ApiDemos/kotlin/app/src/v3/java/com/example/kotlindemos/polyline/PolylineJointControlFragment.kt | 1 | 2813 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.kotlindemos.polyline
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RadioGroup
import android.widget.RadioGroup.OnCheckedChangeListener
import com.example.kotlindemos.R
import com.google.android.libraries.maps.model.JointType
/**
* Fragment with "joint" UI controls for Polylines, to be used in ViewPager.
*/
class PolylineJointControlFragment : PolylineControlFragment(), OnCheckedChangeListener {
private val radioIdToJointType = mutableMapOf<Int, Int>()
private lateinit var jointRadioGroup: RadioGroup
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, bundle: Bundle?): View {
val view = inflater.inflate(R.layout.polyline_joint_control_fragment, container, false)
jointRadioGroup = view.findViewById(R.id.joint_radio)
jointRadioGroup.setOnCheckedChangeListener(this)
return view
}
override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {
if (polyline == null) {
return
}
val jointType = radioIdToJointType[checkedId]
if (jointType != null) {
polyline?.jointType = jointType
}
}
override fun refresh() {
if (polyline == null) {
jointRadioGroup.clearCheck()
for (i in 0 until jointRadioGroup.childCount) {
jointRadioGroup.getChildAt(i).isEnabled = false
}
return
}
for (i in 0 until jointRadioGroup.childCount) {
jointRadioGroup.getChildAt(i).isEnabled = true
}
when (polyline?.jointType) {
JointType.DEFAULT -> jointRadioGroup.check(R.id.joint_radio_default)
JointType.BEVEL -> jointRadioGroup.check(R.id.joint_radio_bevel)
JointType.ROUND -> jointRadioGroup.check(R.id.joint_radio_round)
else -> jointRadioGroup.clearCheck()
}
}
init {
radioIdToJointType[R.id.joint_radio_default] = JointType.DEFAULT
radioIdToJointType[R.id.joint_radio_bevel] = JointType.BEVEL
radioIdToJointType[R.id.joint_radio_round] = JointType.ROUND
}
} | apache-2.0 | b1eaf78a4dd3d080c2fe858962129cce | 36.52 | 103 | 0.691433 | 4.341049 | false | false | false | false |
zensum/franz | src/main/kotlin/Producer.kt | 1 | 1002 | package franz
import franz.producer.Producer
import franz.producer.ProducerFactory
import franz.producer.kafka_one.KProducerFactory
private val stringSer = "org.apache.kafka.common.serialization.StringSerializer"
private val byteArraySer = "org.apache.kafka.common.serialization.ByteArraySerializer"
private val valueSerKey = "value.serializer"
data class ProducerBuilder<T> private constructor(
private val opts: Map<String, Any> = emptyMap(),
private val producer: ProducerFactory<String, T> = KProducerFactory()
) {
fun option(k: String, v: Any) = options(mapOf(k to v))
fun options(newOpts: Map<String, Any>) = ProducerBuilder<T>(opts + newOpts)
fun setProducer(p: ProducerFactory<String, T>) = copy(producer = p)
fun create(): Producer<String, T> = producer.create(opts)
companion object {
val ofByteArray = ProducerBuilder<ByteArray>().option(valueSerKey, byteArraySer)
val ofString = ProducerBuilder<String>().option(valueSerKey, stringSer)
}
} | mit | 8fa25de171d2acb1252147f83f38b20f | 42.608696 | 88 | 0.749501 | 3.883721 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | example/src/main/java/org/wordpress/android/fluxc/example/ui/products/WooProductsFragment.kt | 1 | 36538 | package org.wordpress.android.fluxc.example.ui.products
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_woo_products.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.action.WCProductAction.ADDED_PRODUCT_CATEGORY
import org.wordpress.android.fluxc.action.WCProductAction.ADDED_PRODUCT_TAGS
import org.wordpress.android.fluxc.action.WCProductAction.DELETED_PRODUCT
import org.wordpress.android.fluxc.action.WCProductAction.FETCH_PRODUCTS
import org.wordpress.android.fluxc.action.WCProductAction.FETCH_PRODUCT_CATEGORIES
import org.wordpress.android.fluxc.action.WCProductAction.FETCH_PRODUCT_TAGS
import org.wordpress.android.fluxc.action.WCProductAction.FETCH_SINGLE_PRODUCT_SHIPPING_CLASS
import org.wordpress.android.fluxc.example.R.layout
import org.wordpress.android.fluxc.example.prependToLog
import org.wordpress.android.fluxc.example.replaceFragment
import org.wordpress.android.fluxc.example.ui.StoreSelectingFragment
import org.wordpress.android.fluxc.example.utils.showSingleLineDialog
import org.wordpress.android.fluxc.generated.WCProductActionBuilder
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.WCProductCategoryModel
import org.wordpress.android.fluxc.model.WCProductImageModel
import org.wordpress.android.fluxc.store.MediaStore
import org.wordpress.android.fluxc.store.WCAddonsStore
import org.wordpress.android.fluxc.store.WCProductStore
import org.wordpress.android.fluxc.store.WCProductStore.AddProductCategoryPayload
import org.wordpress.android.fluxc.store.WCProductStore.AddProductTagsPayload
import org.wordpress.android.fluxc.store.WCProductStore.DeleteProductPayload
import org.wordpress.android.fluxc.store.WCProductStore.FetchProductCategoriesPayload
import org.wordpress.android.fluxc.store.WCProductStore.FetchProductReviewsPayload
import org.wordpress.android.fluxc.store.WCProductStore.FetchProductShippingClassListPayload
import org.wordpress.android.fluxc.store.WCProductStore.FetchProductSkuAvailabilityPayload
import org.wordpress.android.fluxc.store.WCProductStore.FetchProductTagsPayload
import org.wordpress.android.fluxc.store.WCProductStore.FetchProductVariationsPayload
import org.wordpress.android.fluxc.store.WCProductStore.FetchProductsPayload
import org.wordpress.android.fluxc.store.WCProductStore.FetchSingleProductPayload
import org.wordpress.android.fluxc.store.WCProductStore.FetchSingleProductReviewPayload
import org.wordpress.android.fluxc.store.WCProductStore.FetchSingleProductShippingClassPayload
import org.wordpress.android.fluxc.store.WCProductStore.OnProductCategoryChanged
import org.wordpress.android.fluxc.store.WCProductStore.OnProductChanged
import org.wordpress.android.fluxc.store.WCProductStore.OnProductImagesChanged
import org.wordpress.android.fluxc.store.WCProductStore.OnProductShippingClassesChanged
import org.wordpress.android.fluxc.store.WCProductStore.OnProductSkuAvailabilityChanged
import org.wordpress.android.fluxc.store.WCProductStore.OnProductTagChanged
import org.wordpress.android.fluxc.store.WCProductStore.OnProductsSearched
import org.wordpress.android.fluxc.store.WCProductStore.SearchProductsPayload
import org.wordpress.android.fluxc.store.WCProductStore.UpdateProductImagesPayload
import org.wordpress.android.fluxc.store.WooCommerceStore
import javax.inject.Inject
@Suppress("LargeClass")
class WooProductsFragment : StoreSelectingFragment() {
@Inject internal lateinit var dispatcher: Dispatcher
@Inject internal lateinit var wcProductStore: WCProductStore
@Inject lateinit var addonsStore: WCAddonsStore
@Inject internal lateinit var wooCommerceStore: WooCommerceStore
@Inject internal lateinit var mediaStore: MediaStore
private var pendingFetchSingleProductShippingClassRemoteId: Long? = null
private var pendingFetchProductVariationsProductRemoteId: Long? = null
private var pendingFetchSingleProductVariationOffset: Int = 0
private var pendingFetchProductShippingClassListOffset: Int = 0
private var pendingFetchProductCategoriesOffset: Int = 0
private var pendingFetchProductTagsOffset: Int = 0
private var enteredCategoryName: String? = null
private val enteredTagNames: MutableList<String> = mutableListOf()
private val coroutineScope = CoroutineScope(Dispatchers.Main)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(layout.fragment_woo_products, container, false)
@Suppress("LongMethod", "ComplexMethod")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fetch_single_product.setOnClickListener {
selectedSite?.let { site ->
showSingleLineDialog(activity, "Enter the remoteProductId of product to fetch:") { editText ->
editText.text.toString().toLongOrNull()?.let { remoteProductId ->
prependToLog("Submitting request to fetch product by remoteProductID $remoteProductId")
coroutineScope.launch {
val result = wcProductStore.fetchSingleProduct(
FetchSingleProductPayload(
site,
remoteProductId
)
)
val product = wcProductStore.getProductByRemoteId(site, result.remoteProductId)
product?.let {
val numVariations = it.getVariationIdList().size
if (numVariations > 0) {
prependToLog("Single product with $numVariations variations fetched! ${it.name}")
} else {
prependToLog("Single product fetched! ${it.name}")
}
} ?: prependToLog("WARNING: Fetched product not found in the local database!")
}
} ?: prependToLog("No valid remoteOrderId defined...doing nothing")
}
}
}
fetch_single_variation.setOnClickListener {
selectedSite?.let { site ->
showSingleLineDialog(
activity,
"Enter the remoteProductId of variation to fetch:"
) { productIdText ->
val productRemoteId = productIdText.text.toString().toLongOrNull()
productRemoteId?.let { productId ->
showSingleLineDialog(
activity,
"Enter the remoteVariationId of variation to fetch:"
) { variationIdText ->
variationIdText.text.toString().toLongOrNull()?.let { variationId ->
coroutineScope.launch {
prependToLog(
"Submitting request to fetch product by " +
"remoteProductId $productRemoteId, " +
"remoteVariationProductID $variationId"
)
val result = wcProductStore.fetchSingleVariation(site, productId, variationId)
prependToLog("Fetching single variation " +
"${result.error?.let { "failed" } ?: "was successful"}"
)
val variation = wcProductStore.getVariationByRemoteId(
site,
result.remoteProductId,
result.remoteVariationId
)
variation?.let {
prependToLog("Variation with id! ${it.remoteVariationId} found in local db")
} ?: prependToLog("WARNING: Fetched product not found in the local database!")
}
} ?: prependToLog("No valid remoteVariationId defined...doing nothing")
}
} ?: prependToLog("No valid remoteProductId defined...doing nothing")
}
}
}
fetch_product_sku_availability.setOnClickListener {
selectedSite?.let { site ->
showSingleLineDialog(
activity,
"Enter a product SKU:"
) { editText ->
val payload = FetchProductSkuAvailabilityPayload(site, editText.text.toString())
dispatcher.dispatch(WCProductActionBuilder.newFetchProductSkuAvailabilityAction(payload))
}
}
}
fetch_products.setOnClickListener {
selectedSite?.let { site ->
val payload = FetchProductsPayload(site)
dispatcher.dispatch(WCProductActionBuilder.newFetchProductsAction(payload))
}
}
fetch_products_with_filters.setOnClickListener {
replaceFragment(WooProductFiltersFragment.newInstance(selectedPos))
}
fetch_specific_products.setOnClickListener {
selectedSite?.let { site ->
showSingleLineDialog(activity, "Enter remote product IDs, separated by comma:") { editText ->
val ids = editText.text.toString().replace(" ", "").split(",").mapNotNull {
val id = it.toLongOrNull()
if (id == null) {
prependToLog("$it is not a valid remote product ID, ignoring...")
}
id
}
if (ids.isNotEmpty()) {
coroutineScope.launch {
val result = wcProductStore.fetchProducts(
site,
includedProductIds = ids
)
if (result.isError) {
prependToLog("Fetching products failed: ${result.error.message}")
} else {
val products = wcProductStore.getProductsByRemoteIds(site, ids)
prependToLog("${products.size} were fetched")
prependToLog("$products")
}
}
} else {
prependToLog("No valid product IDs...doing nothing")
}
}
}
}
search_products.setOnClickListener {
selectedSite?.let { site ->
showSingleLineDialog(
activity,
"Enter a search query:"
) { editText ->
val payload = SearchProductsPayload(
site = site,
searchQuery = editText.text.toString()
)
dispatcher.dispatch(WCProductActionBuilder.newSearchProductsAction(payload))
}
}
}
search_products_sku.setOnClickListener {
selectedSite?.let { site ->
showSingleLineDialog(
activity,
"Enter a SKU to search for:"
) { editText ->
val payload = SearchProductsPayload(
site = site,
searchQuery = editText.text.toString(),
isSkuSearch = true
)
dispatcher.dispatch(WCProductActionBuilder.newSearchProductsAction(payload))
}
}
}
fetch_product_variations.setOnClickListener {
selectedSite?.let { site ->
showSingleLineDialog(
activity,
"Enter the remoteProductId of product to fetch variations:"
) { editText ->
editText.text.toString().toLongOrNull()?.let { id ->
coroutineScope.launch {
pendingFetchProductVariationsProductRemoteId = id
prependToLog("Submitting request to fetch product variations by remoteProductID $id")
val result = wcProductStore.fetchProductVariations(FetchProductVariationsPayload(site, id))
prependToLog(
"Fetched ${result.rowsAffected} product variants. " +
"More variants available ${result.canLoadMore}"
)
if (result.canLoadMore) {
pendingFetchSingleProductVariationOffset += result.rowsAffected
load_more_product_variations.visibility = View.VISIBLE
load_more_product_variations.isEnabled = true
} else {
pendingFetchSingleProductVariationOffset = 0
load_more_product_variations.isEnabled = false
}
}
} ?: prependToLog("No valid remoteProductId defined...doing nothing")
}
}
}
load_more_product_variations.setOnClickListener {
selectedSite?.let { site ->
pendingFetchProductVariationsProductRemoteId?.let { id ->
coroutineScope.launch {
prependToLog("Submitting offset request to fetch product variations by remoteProductID $id")
val payload = FetchProductVariationsPayload(
site, id, offset = pendingFetchSingleProductVariationOffset
)
val result = wcProductStore.fetchProductVariations(payload)
prependToLog(
"Fetched ${result.rowsAffected} product variants. " +
"More variants available ${result.canLoadMore}"
)
if (result.canLoadMore) {
pendingFetchSingleProductVariationOffset += result.rowsAffected
load_more_product_variations.visibility = View.VISIBLE
load_more_product_variations.isEnabled = true
} else {
pendingFetchSingleProductVariationOffset = 0
load_more_product_variations.isEnabled = false
}
}
} ?: prependToLog("No valid remoteProductId defined...doing nothing")
}
}
fetch_reviews_for_product.setOnClickListener {
selectedSite?.let { site ->
showSingleLineDialog(
activity,
"Enter the remoteProductId of product to fetch reviews:"
) { editText ->
val remoteProductId = editText.text.toString().toLongOrNull()
remoteProductId?.let { id ->
coroutineScope.launch {
prependToLog("Submitting request to fetch product reviews for remoteProductID $id")
val result = wcProductStore.fetchProductReviews(
FetchProductReviewsPayload(
site,
productIds = listOf(remoteProductId)
)
)
prependToLog("Fetched ${result.rowsAffected} product reviews")
}
} ?: prependToLog("No valid remoteProductId defined...doing nothing")
}
}
}
fetch_all_reviews.setOnClickListener {
selectedSite?.let { site ->
coroutineScope.launch {
prependToLog("Submitting request to fetch product reviews for site ${site.id}")
val payload = FetchProductReviewsPayload(site)
val result = wcProductStore.fetchProductReviews(payload)
prependToLog("Fetched ${result.rowsAffected} product reviews")
}
}
}
fetch_review_by_id.setOnClickListener {
selectedSite?.let { site ->
showSingleLineDialog(
activity,
"Enter the remoteReviewId of the review to fetch:"
) { editText ->
val reviewId = editText.text.toString().toLongOrNull()
reviewId?.let { id ->
coroutineScope.launch {
prependToLog("Submitting request to fetch product review for ID $id")
val payload = FetchSingleProductReviewPayload(site, id)
val result = wcProductStore.fetchSingleProductReview(payload)
if (!result.isError) {
prependToLog("Fetched ${result.rowsAffected} single product review")
} else {
prependToLog("Fetching single product review FAILED")
}
}
} ?: prependToLog("No valid remoteReviewId defined...doing nothing")
}
}
}
update_review_status.setOnClickListener {
selectedSite?.let { site ->
coroutineScope.launch {
val id = showSingleLineDialog(
activity = requireActivity(),
message = "Enter the remoteReviewId of the review",
isNumeric = true
)?.toLongOrNull()
if (id == null) {
prependToLog("Please enter a valid id")
return@launch
}
val newStatus = showSingleLineDialog(
activity = requireActivity(),
message = "Enter the new status: (approved|hold|spam|trash)"
)
if (newStatus == null) {
prependToLog("Please enter a valid status")
return@launch
}
val result = wcProductStore.updateProductReviewStatus(
site = site, reviewId = id, newStatus = newStatus
)
if (!result.isError) {
prependToLog("Product Review status updated successfully")
} else {
prependToLog(
"Product Review status update failed, " +
"${result.error.type} ${result.error.message}"
)
}
}
}
}
fetch_product_shipping_class.setOnClickListener {
selectedSite?.let { site ->
showSingleLineDialog(
activity,
"Enter the remoteShippingClassId of the site to fetch:"
) { editText ->
pendingFetchSingleProductShippingClassRemoteId = editText.text.toString().toLongOrNull()
pendingFetchSingleProductShippingClassRemoteId?.let { id ->
prependToLog("Submitting request to fetch product shipping class for ID $id")
val payload = FetchSingleProductShippingClassPayload(site, id)
dispatcher.dispatch(WCProductActionBuilder.newFetchSingleProductShippingClassAction(payload))
} ?: prependToLog("No valid remoteShippingClassId defined...doing nothing")
}
}
}
fetch_product_shipping_classes.setOnClickListener {
selectedSite?.let { site ->
prependToLog("Submitting request to fetch product shipping classes for site ${site.id}")
val payload = FetchProductShippingClassListPayload(site)
dispatcher.dispatch(WCProductActionBuilder.newFetchProductShippingClassListAction(payload))
}
}
load_more_product_shipping_classes.setOnClickListener {
selectedSite?.let { site ->
prependToLog("Submitting offset request to fetch product shipping classes for site ${site.id}")
val payload = FetchProductShippingClassListPayload(
site, offset = pendingFetchProductShippingClassListOffset
)
dispatcher.dispatch(WCProductActionBuilder.newFetchProductShippingClassListAction(payload))
}
}
fetch_product_categories.setOnClickListener {
selectedSite?.let { site ->
prependToLog("Submitting request to fetch product categories for site ${site.id}")
val payload = FetchProductCategoriesPayload(site)
dispatcher.dispatch(WCProductActionBuilder.newFetchProductCategoriesAction(payload))
}
}
observe_product_categories.setOnClickListener {
selectedSite?.let { site ->
coroutineScope.launch {
val categories = wcProductStore.observeCategories(site).first()
prependToLog("Categories: $categories")
}
}
}
load_more_product_categories.setOnClickListener {
selectedSite?.let { site ->
prependToLog("Submitting offset request to fetch product categories for site ${site.id}")
val payload = FetchProductCategoriesPayload(
site, offset = pendingFetchProductCategoriesOffset
)
dispatcher.dispatch(WCProductActionBuilder.newFetchProductCategoriesAction(payload))
}
}
add_product_category.setOnClickListener {
selectedSite?.let { site ->
showSingleLineDialog(
activity,
"Enter a category name:"
) { editText ->
enteredCategoryName = editText.text.toString()
if (enteredCategoryName != null && enteredCategoryName?.isNotEmpty() == true) {
prependToLog("Submitting request to add product category")
val wcProductCategoryModel = WCProductCategoryModel().apply {
name = enteredCategoryName!!
}
val payload = AddProductCategoryPayload(site, wcProductCategoryModel)
dispatcher.dispatch(WCProductActionBuilder.newAddProductCategoryAction(payload))
} else {
prependToLog("No category name entered...doing nothing")
}
}
}
}
fetch_product_tags.setOnClickListener {
showSingleLineDialog(
activity,
"Enter a search query, leave blank for none:"
) { editText ->
val searchQuery = editText.text.toString()
selectedSite?.let { site ->
prependToLog("Submitting request to fetch product tags for site ${site.id}")
val payload = FetchProductTagsPayload(site, searchQuery = searchQuery)
dispatcher.dispatch(WCProductActionBuilder.newFetchProductTagsAction(payload))
}
}
}
load_more_product_tags.setOnClickListener {
selectedSite?.let { site ->
prependToLog("Submitting offset request to fetch product tags for site ${site.id}")
val payload = FetchProductTagsPayload(site, offset = pendingFetchProductTagsOffset)
dispatcher.dispatch(WCProductActionBuilder.newFetchProductTagsAction(payload))
}
}
add_product_tags.setOnClickListener {
selectedSite?.let { site ->
showSingleLineDialog(
activity,
"Enter tag name:"
) { editTextTagName1 ->
showSingleLineDialog(
activity,
"Enter another tag name:"
) { editTextTagName2 ->
val tagName1 = editTextTagName1.text.toString()
val tagName2 = editTextTagName2.text.toString()
if (tagName1.isNotEmpty() && tagName2.isNotEmpty()) {
enteredTagNames.add(tagName1)
enteredTagNames.add(tagName2)
prependToLog("Submitting request to add product tags for site ${site.id}")
val payload = AddProductTagsPayload(site, enteredTagNames)
dispatcher.dispatch(WCProductActionBuilder.newAddProductTagsAction(payload))
} else {
prependToLog("Tag name is empty. Doing nothing..")
}
}
}
}
}
test_add_ons.setOnClickListener {
selectedSite?.let { site ->
WooAddonsTestFragment.show(childFragmentManager, site.siteId)
}
}
update_product_images.setOnClickListener {
showSingleLineDialog(
activity,
"Enter the remoteProductId of the product to update images:"
) { editTextProduct ->
editTextProduct.text.toString().toLongOrNull()?.let { productId ->
showSingleLineDialog(
activity,
"Enter the mediaId of the image to assign to the product:"
) { editTextMedia ->
editTextMedia.text.toString().toLongOrNull()?.let { mediaId ->
updateProductImages(productId, mediaId)
}
}
}
}
}
update_product.setOnClickListener {
replaceFragment(WooUpdateProductFragment.newInstance(selectedPos))
}
update_variation.setOnClickListener {
replaceFragment(WooUpdateVariationFragment.newInstance(selectedPos))
}
add_new_product.setOnClickListener {
replaceFragment(WooUpdateProductFragment.newInstance(selectedPos, isAddNewProduct = true))
}
delete_product.setOnClickListener {
showSingleLineDialog(
activity,
"Enter the remoteProductId of the product to delete:"
) { editTextProduct ->
editTextProduct.text.toString().toLongOrNull()?.let { productId ->
selectedSite?.let { site ->
val payload = DeleteProductPayload(site, productId)
dispatcher.dispatch(WCProductActionBuilder.newDeleteProductAction(payload))
}
}
}
}
batch_update_variations.setOnClickListener {
replaceFragment(WooBatchUpdateVariationsFragment.newInstance(selectedPos))
}
batch_generate_variations.setOnClickListener{
replaceFragment(WooBatchGenerateVariationsFragment.newInstance(selectedPos))
}
}
/**
* Note that this will replace all this product's images with a single image, as defined by mediaId. Also note
* that the media must already be cached for this to work (ie: you may need to go to the first screen in the
* example app, tap Media, then ensure the media is fetched)
*/
private fun updateProductImages(productId: Long, mediaId: Long) {
selectedSite?.let { site ->
mediaStore.getSiteMediaWithId(site, mediaId)?.let { media ->
prependToLog("Submitting request to update product images")
val imageList = ArrayList<WCProductImageModel>().also {
it.add(WCProductImageModel.fromMediaModel(media))
}
val payload = UpdateProductImagesPayload(site, productId, imageList)
dispatcher.dispatch(WCProductActionBuilder.newUpdateProductImagesAction(payload))
} ?: prependToLog(("Not a valid media id"))
} ?: prependToLog(("No site selected"))
}
override fun onStart() {
super.onStart()
dispatcher.register(this)
}
override fun onStop() {
super.onStop()
dispatcher.unregister(this)
}
@Suppress("unused")
@Subscribe(threadMode = ThreadMode.MAIN)
fun onProductChanged(event: OnProductChanged) {
if (event.isError) {
prependToLog("Error from " + event.causeOfChange + " - error: " + event.error.type)
return
}
selectedSite?.let { site ->
when (event.causeOfChange) {
FETCH_PRODUCTS -> {
prependToLog("Fetched ${event.rowsAffected} products")
}
DELETED_PRODUCT -> {
prependToLog("${event.rowsAffected} product deleted")
}
else -> prependToLog("Product store was updated from a " + event.causeOfChange)
}
}
}
@Suppress("unused")
@Subscribe(threadMode = ThreadMode.MAIN)
fun onProductsSearched(event: OnProductsSearched) {
if (event.isError) {
prependToLog("Error searching products - error: " + event.error.type)
} else {
prependToLog("Found ${event.searchResults.size} products matching ${event.searchQuery}")
}
}
@Suppress("unused")
@Subscribe(threadMode = ThreadMode.MAIN)
fun onProductSkuAvailabilityChanged(event: OnProductSkuAvailabilityChanged) {
if (event.isError) {
prependToLog("Error searching product sku availability - error: " + event.error.type)
} else {
prependToLog("Sku ${event.sku} available for site ${selectedSite?.name}: ${event.available}")
}
}
@Suppress("unused")
@Subscribe(threadMode = ThreadMode.MAIN)
fun onProductImagesChanged(event: OnProductImagesChanged) {
if (event.isError) {
prependToLog("Error updating product images - error: " + event.error.type)
} else {
prependToLog("Product images updated")
}
}
@Suppress("unused")
@Subscribe(threadMode = ThreadMode.MAIN)
fun onProductCategoriesChanged(event: OnProductCategoryChanged) {
if (event.isError) {
prependToLog("Error from " + event.causeOfChange + " - error: " + event.error.type)
return
}
selectedSite?.let { site ->
when (event.causeOfChange) {
FETCH_PRODUCT_CATEGORIES -> {
prependToLog("Fetched ${event.rowsAffected} product categories. " +
"More categories available ${event.canLoadMore}")
if (event.canLoadMore) {
pendingFetchProductCategoriesOffset += event.rowsAffected
load_more_product_categories.visibility = View.VISIBLE
load_more_product_categories.isEnabled = true
} else {
pendingFetchProductCategoriesOffset = 0
load_more_product_categories.isEnabled = false
}
}
ADDED_PRODUCT_CATEGORY -> {
val category = enteredCategoryName?.let {
wcProductStore.getProductCategoryByNameAndParentId(site, it)
}
prependToLog("${event.rowsAffected} product category added with name: ${category?.name}")
} else -> { }
}
}
}
@Suppress("unused")
@Subscribe(threadMode = ThreadMode.MAIN)
fun onProductShippingClassesChanged(event: OnProductShippingClassesChanged) {
if (event.isError) {
prependToLog("Error from " + event.causeOfChange + " - error: " + event.error.type)
return
}
selectedSite?.let { site ->
when (event.causeOfChange) {
FETCH_SINGLE_PRODUCT_SHIPPING_CLASS -> logFetchSingleProductShippingClass(site)
else -> checkProductShippingClassesAndLoadMore(event)
}
}
}
private fun logFetchSingleProductShippingClass(site: SiteModel) {
pendingFetchSingleProductShippingClassRemoteId?.let { remoteId ->
pendingFetchSingleProductShippingClassRemoteId = null
val productShippingClass = wcProductStore.getShippingClassByRemoteId(site, remoteId)
productShippingClass?.let {
prependToLog("Single product shipping class fetched! ${it.name}")
} ?: prependToLog("WARNING: Fetched shipping class not found in the local database!")
}
}
private fun checkProductShippingClassesAndLoadMore(event: OnProductShippingClassesChanged) {
prependToLog(
"Fetched ${event.rowsAffected} product shipping classes. " +
"More shipping classes available ${event.canLoadMore}"
)
if (event.canLoadMore) {
pendingFetchProductShippingClassListOffset += event.rowsAffected
load_more_product_shipping_classes.visibility = View.VISIBLE
load_more_product_shipping_classes.isEnabled = true
} else {
pendingFetchProductShippingClassListOffset = 0
load_more_product_shipping_classes.isEnabled = false
}
}
@Suppress("unused")
@Subscribe(threadMode = ThreadMode.MAIN)
fun onProductTagChanged(event: OnProductTagChanged) {
if (event.isError) {
prependToLog("Error from " + event.causeOfChange + " - error: " + event.error.type)
return
}
selectedSite?.let { site ->
when (event.causeOfChange) {
FETCH_PRODUCT_TAGS -> {
prependToLog("Fetched ${event.rowsAffected} product tags. More tags available ${event.canLoadMore}")
if (event.canLoadMore) {
pendingFetchProductTagsOffset += event.rowsAffected
load_more_product_tags.visibility = View.VISIBLE
load_more_product_tags.isEnabled = true
} else {
pendingFetchProductTagsOffset = 0
load_more_product_tags.isEnabled = false
}
}
ADDED_PRODUCT_TAGS -> {
val tags = wcProductStore.getProductTagsByNames(site, enteredTagNames)
val tagNames = tags.map { it.name }.joinToString(",")
prependToLog("${event.rowsAffected} product tags added for $tagNames")
if (enteredTagNames.size > event.rowsAffected) {
prependToLog("Error occurred when trying to add some product tags")
}
}
else -> { }
}
}
}
}
| gpl-2.0 | 5f71124c29ea3c5a8a6979fdb087ffee | 46.637549 | 120 | 0.559253 | 6.533977 | false | false | false | false |
googlemaps/android-samples | ApiDemos/kotlin/app/src/gms/java/com/example/kotlindemos/MainActivity.kt | 1 | 5290 | /*
* 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.kotlindemos
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.*
import android.widget.AdapterView.OnItemSelectedListener
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.maps.MapsInitializer
import com.google.android.gms.maps.MapsInitializer.Renderer;
import com.google.android.gms.maps.OnMapsSdkInitializedCallback;
/**
* The main activity of the API library demo gallery.
* The main layout lists the demonstrated features, with buttons to launch them.
*/
class MainActivity : AppCompatActivity(), AdapterView.OnItemClickListener, OnMapsSdkInitializedCallback {
private val TAG = MainActivity::class.java.simpleName
override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val demo: DemoDetails = parent?.adapter?.getItem(position) as DemoDetails
startActivity(Intent(this, demo.activityClass))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val listAdapter: ListAdapter = CustomArrayAdapter(this, DemoDetailsList.DEMOS)
// Find the view that will show empty message if there is no demo in DemoDetailsList.DEMOS
val emptyMessage = findViewById<View>(R.id.empty)
with(findViewById<ListView>(R.id.list)) {
adapter = listAdapter
onItemClickListener = this@MainActivity
emptyView = emptyMessage
}
if (BuildConfig.MAPS_API_KEY.isEmpty()) {
Toast.makeText(this, "Add your own API key in local.properties as MAPS_API_KEY=YOUR_API_KEY", Toast.LENGTH_LONG).show()
}
val spinner = findViewById<Spinner>(R.id.map_renderer_spinner)
val spinnerAdapter = ArrayAdapter.createFromResource(
this, R.array.map_renderer_spinner_array, android.R.layout.simple_spinner_item
)
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = spinnerAdapter
spinner.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View,
position: Int,
id: Long
) {
val preferredRendererName = spinner.selectedItem as String
val preferredRenderer: Renderer?
preferredRenderer = if (preferredRendererName == getString(R.string.latest)) {
Renderer.LATEST
} else if (preferredRendererName == getString(R.string.legacy)) {
Renderer.LEGACY
} else if (preferredRendererName == getString(R.string.default_renderer)) {
null
} else {
Log.i(
TAG,
"Error setting renderer with name $preferredRendererName"
)
return
}
MapsInitializer.initialize(applicationContext, preferredRenderer, this@MainActivity)
// Disable spinner since renderer cannot be changed once map is intitialized.
spinner.isEnabled = false
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
}
override fun onMapsSdkInitialized(renderer: Renderer) {
Toast.makeText(
this,
"All demo activities will use the $renderer renderer.",
Toast.LENGTH_LONG
).show()
}
/**
* A custom array adapter that shows a {@link FeatureView} containing details about the demo.
*
* @property context current activity
* @property demos An array containing the details of the demos to be displayed.
*/
@SuppressLint("ResourceType")
class CustomArrayAdapter(context: Context, demos: List<DemoDetails>) :
ArrayAdapter<DemoDetails>(context, R.layout.feature, demos) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val demo: DemoDetails? = getItem(position)
return (convertView as? FeatureView ?: FeatureView(context)).apply {
if (demo != null) {
setTitleId(demo.titleId)
setDescriptionId(demo.descriptionId)
contentDescription = resources.getString(demo.titleId)
}
}
}
}
}
| apache-2.0 | 2df043dc9e4b76fe996d51736ed1c397 | 39.692308 | 131 | 0.651607 | 4.957826 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/actions/styling/ShowTextHexAction.kt | 1 | 2603 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.actions.styling
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.project.DumbAware
import com.vladsch.md.nav.actions.styling.util.MdActionUtil
import com.vladsch.md.nav.settings.MdApplicationSettings
import com.vladsch.plugin.util.maxLimit
class ShowTextHexAction : AnAction(), DumbAware {
override fun isDumbAware(): Boolean {
return true
}
override fun update(e: AnActionEvent) {
val debugSettings = MdApplicationSettings.instance.debugSettings
if (debugSettings.showTextHexDialog) {
MdActionUtil.getConditionBuilder(e, this).done()
} else {
e.presentation.isVisible = false
}
}
override fun actionPerformed(e: AnActionEvent) {
MdActionUtil.getProjectEditorPsiFile(e)?.let { (project, editor, _) ->
// load all markdown files one by one and wait for them to render before loading the next one
val primaryCaret = editor.caretModel.primaryCaret
val document = editor.document
val hadSelection = primaryCaret.hasSelection()
val caretOffset = primaryCaret.offset
if (!hadSelection) {
// select the current line
val line = document.getLineNumber(caretOffset)
val start = document.getLineStartOffset(line)
val end = document.getLineEndOffset(line)
primaryCaret.setSelection(start, end)
}
val replacementText = TextHexDialog.showDialog(editor.component, primaryCaret.selectedText ?: "")
if (replacementText != null) {
val selectionStart = primaryCaret.selectionStart
val selectionEnd = primaryCaret.selectionEnd
WriteCommandAction.runWriteCommandAction(project, Runnable {
document.replaceString(selectionStart, selectionEnd, replacementText)
if (!hadSelection) {
val offset = caretOffset.maxLimit(document.textLength)
primaryCaret.setSelection(offset, offset)
}
})
} else if (!hadSelection) {
primaryCaret.setSelection(caretOffset, caretOffset)
}
}
}
}
| apache-2.0 | 879fd12ef002d4de7335c31c0c4bd69a | 43.87931 | 177 | 0.653861 | 5.36701 | false | false | false | false |
JoosungPark/Leaning-Kotlin-Android | app/src/main/java/ma/sdop/weatherapp/ui/activities/MainActivity.kt | 1 | 1675 | package ma.sdop.weatherapp.ui.activities
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.Toolbar
import kotlinx.android.synthetic.main.activity_main.*
import ma.sdop.weatherapp.R
import ma.sdop.weatherapp.domain.commands.RequestForecastCommand
import ma.sdop.weatherapp.extensions.DelegatesExt
import ma.sdop.weatherapp.ui.adapters.ForecastListAdapter
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.find
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.uiThread
class MainActivity : AppCompatActivity(), ToolbarManager {
override val toolBar: Toolbar by lazy { find<Toolbar>(R.id.toolbar) }
val zipCode: Long by DelegatesExt.preference(this, SettingsActivity.ZIP_CODE, SettingsActivity.DEFAULT_ZIP)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initToolbar()
forecastList.layoutManager = LinearLayoutManager(this)
attachToScroll(forecastList)
}
override fun onResume() {
super.onResume()
loadForecast()
}
private fun loadForecast() = doAsync {
val result = RequestForecastCommand(zipCode).execute()
uiThread {
val adapter = ForecastListAdapter(result) {
startActivity<DetailActivity>(DetailActivity.ID to it.id,
DetailActivity.CITY_NAME to result.city)
}
forecastList.adapter = adapter
toolbarTitle = "${result.city} (${result.country})"
}
}
}
| apache-2.0 | 2bc18672a98f39cf177ff18b2b2cbe2c | 33.183673 | 111 | 0.721791 | 4.576503 | false | false | false | false |
wuseal/JsonToKotlinClass | src/main/kotlin/wu/seal/jsontokotlin/GenerateKotlinFileAction.kt | 1 | 4304 | package wu.seal.jsontokotlin
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.ui.Messages
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.PsiManager
import com.intellij.psi.impl.file.PsiDirectoryFactory
import wu.seal.jsontokotlin.feedback.dealWithException
import wu.seal.jsontokotlin.interceptor.InterceptorManager
import wu.seal.jsontokotlin.model.ConfigManager
import wu.seal.jsontokotlin.model.UnSupportJsonException
import wu.seal.jsontokotlin.ui.JsonInputDialog
import wu.seal.jsontokotlin.utils.KotlinClassFileGenerator
import wu.seal.jsontokotlin.utils.KotlinClassMaker
import wu.seal.jsontokotlin.utils.isJSONSchema
/**
* Created by Seal.Wu on 2018/4/18.
*/
class GenerateKotlinFileAction : AnAction("Kotlin data class File from JSON") {
override fun actionPerformed(event: AnActionEvent) {
var jsonString = ""
try {
val project = event.getData(PlatformDataKeys.PROJECT) ?: return
val dataContext = event.dataContext
val module = LangDataKeys.MODULE.getData(dataContext) ?: return
val directory = when (val navigatable = LangDataKeys.NAVIGATABLE.getData(dataContext)) {
is PsiDirectory -> navigatable
is PsiFile -> navigatable.containingDirectory
else -> {
val root = ModuleRootManager.getInstance(module)
root.sourceRoots
.asSequence()
.mapNotNull {
PsiManager.getInstance(project).findDirectory(it)
}.firstOrNull()
}
} ?: return
val directoryFactory = PsiDirectoryFactory.getInstance(directory.project)
val packageName = directoryFactory.getQualifiedName(directory, false)
val psiFileFactory = PsiFileFactory.getInstance(project)
val packageDeclare = if (packageName.isNotEmpty()) "package $packageName" else ""
val inputDialog = JsonInputDialog("", project)
inputDialog.show()
val className = inputDialog.getClassName()
val inputString = inputDialog.inputString.takeIf { it.isNotEmpty() } ?: return
jsonString = inputString
doGenerateKotlinDataClassFileAction(
className,
inputString,
packageDeclare,
project,
psiFileFactory,
directory
)
} catch (e: UnSupportJsonException) {
val advice = e.advice
Messages.showInfoMessage(dealWithHtmlConvert(advice), "Tip")
} catch (e: Throwable) {
dealWithException(jsonString, e)
throw e
}
}
private fun dealWithHtmlConvert(advice: String) = advice.replace("<", "<").replace(">", ">")
private fun doGenerateKotlinDataClassFileAction(
className: String,
json: String,
packageDeclare: String,
project: Project?,
psiFileFactory: PsiFileFactory,
directory: PsiDirectory
) {
val kotlinClass = KotlinClassMaker(className, json).makeKotlinClass()
val dataClassAfterApplyInterceptor =
kotlinClass.applyInterceptors(InterceptorManager.getEnabledKotlinDataClassInterceptors())
if (ConfigManager.isInnerClassModel) {
KotlinClassFileGenerator().generateSingleKotlinClassFile(
packageDeclare,
dataClassAfterApplyInterceptor,
project,
psiFileFactory,
directory
)
} else {
KotlinClassFileGenerator().generateMultipleKotlinClassFiles(
dataClassAfterApplyInterceptor,
packageDeclare,
project,
psiFileFactory,
directory,
json.isJSONSchema()
)
}
}
}
| gpl-3.0 | ee740c407503a842bbd5af98c3facbe0 | 37.774775 | 102 | 0.646608 | 5.546392 | false | false | false | false |
openMF/android-client | mifosng-android/src/main/java/com/mifos/mifosxdroid/online/createnewgroup/CreateNewGroupFragment.kt | 1 | 9836 | /*
* This project is licensed under the open source MPL V2.
* See https://github.com/openMF/android-client/blob/master/LICENSE.md
*/
package com.mifos.mifosxdroid.online.createnewgroup
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import android.widget.AdapterView.OnItemSelectedListener
import androidx.fragment.app.DialogFragment
import butterknife.BindView
import butterknife.ButterKnife
import com.mifos.exceptions.InvalidTextInputException
import com.mifos.exceptions.RequiredFieldException
import com.mifos.exceptions.ShortOfLengthException
import com.mifos.mifosxdroid.R
import com.mifos.mifosxdroid.core.MifosBaseActivity
import com.mifos.mifosxdroid.core.ProgressableFragment
import com.mifos.mifosxdroid.core.util.Toaster
import com.mifos.mifosxdroid.online.GroupsActivity
import com.mifos.mifosxdroid.uihelpers.MFDatePicker
import com.mifos.mifosxdroid.uihelpers.MFDatePicker.OnDatePickListener
import com.mifos.objects.group.GroupPayload
import com.mifos.objects.organisation.Office
import com.mifos.objects.response.SaveResponse
import com.mifos.utils.*
import java.util.*
import javax.inject.Inject
/**
* Created by nellyk on 1/22/2016.
*/ //TODO Show Image and Text after successful or Failed during creation of Group and
//TODO A button to Continue or Finish the GroupCreation.
class CreateNewGroupFragment : ProgressableFragment(), OnDatePickListener, CreateNewGroupMvpView, OnItemSelectedListener {
private val LOG_TAG = javaClass.simpleName
@JvmField
@BindView(R.id.et_group_name)
var et_groupName: EditText? = null
@JvmField
@BindView(R.id.et_group_external_id)
var et_groupexternalId: EditText? = null
@JvmField
@BindView(R.id.cb_group_active_status)
var cb_groupActiveStatus: CheckBox? = null
@JvmField
@BindView(R.id.tv_group_submission_date)
var tv_submissionDate: TextView? = null
@JvmField
@BindView(R.id.tv_group_activationDate)
var tv_activationDate: TextView? = null
@JvmField
@BindView(R.id.sp_group_offices)
var sp_offices: Spinner? = null
@JvmField
@BindView(R.id.btn_submit)
var bt_submit: Button? = null
@JvmField
@BindView(R.id.layout_submission)
var layout_submission: LinearLayout? = null
@JvmField
@Inject
var mCreateNewGroupPresenter: CreateNewGroupPresenter? = null
var activationdateString: String? = null
var officeId = 0
var result = true
lateinit var rootView: View
var dateofsubmissionstring: String? = null
private var mfDatePicker: DialogFragment? = null
private var newDatePicker: DialogFragment? = null
private val mListOffices: MutableList<String> = ArrayList()
private var officeList: List<Office>? = null
private var mOfficesAdapter: ArrayAdapter<String>? = null
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
if (parent.id == R.id.sp_group_offices) {
officeId = officeList!![position].id
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(activity as MifosBaseActivity?)!!.activityComponent.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = inflater.inflate(R.layout.fragment_create_new_group, null)
ButterKnife.bind(this, rootView)
mCreateNewGroupPresenter!!.attachView(this)
inflateOfficesSpinner()
inflateSubmissionDate()
inflateActivationDate()
mCreateNewGroupPresenter!!.loadOffices()
//client active checkbox onCheckedListener
cb_groupActiveStatus!!.setOnCheckedChangeListener { compoundButton, isChecked ->
if (isChecked) {
layout_submission!!.visibility = View.VISIBLE
} else {
layout_submission!!.visibility = View.GONE
}
}
activationdateString = tv_activationDate!!.text.toString()
activationdateString = DateHelper.getDateAsStringUsedForCollectionSheetPayload(activationdateString).replace("-", " ")
dateofsubmissionstring = tv_submissionDate!!.text.toString()
dateofsubmissionstring = DateHelper.getDateAsStringUsedForDateofBirth(dateofsubmissionstring).replace("-", " ")
bt_submit!!.setOnClickListener {
if (Network.isOnline(context)) {
val groupPayload = GroupPayload()
groupPayload.name = et_groupName!!.editableText.toString()
groupPayload.externalId = et_groupexternalId!!.editableText.toString()
groupPayload.isActive = cb_groupActiveStatus!!.isChecked
groupPayload.activationDate = activationdateString
groupPayload.setSubmissionDate(dateofsubmissionstring)
groupPayload.officeId = officeId
groupPayload.dateFormat = "dd MMMM yyyy"
groupPayload.locale = "en"
initiateGroupCreation(groupPayload)
} else {
Toaster.show(rootView, R.string.error_network_not_available, Toaster.LONG)
}
}
return rootView
}
private fun initiateGroupCreation(groupPayload: GroupPayload) {
//TextField validations
if (!isGroupNameValid) {
return
}
mCreateNewGroupPresenter!!.createGroup(groupPayload)
}
private fun inflateOfficesSpinner() {
mOfficesAdapter = ArrayAdapter(requireActivity(), android.R.layout.simple_spinner_item,
mListOffices)
mOfficesAdapter!!.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
sp_offices!!.adapter = mOfficesAdapter
sp_offices!!.onItemSelectedListener = this
}
fun inflateSubmissionDate() {
mfDatePicker = MFDatePicker.newInsance(this)
tv_submissionDate!!.text = MFDatePicker.getDatePickedAsString()
tv_submissionDate!!.setOnClickListener { (mfDatePicker as MFDatePicker?)?.show(requireActivity().supportFragmentManager, FragmentConstants.DFRAG_DATE_PICKER) }
}
fun inflateActivationDate() {
newDatePicker = MFDatePicker.newInsance(this)
tv_activationDate!!.text = MFDatePicker.getDatePickedAsString()
tv_activationDate!!.setOnClickListener { (newDatePicker as MFDatePicker?)?.show(requireActivity().supportFragmentManager, FragmentConstants.DFRAG_DATE_PICKER) }
}
override fun onDatePicked(date: String) {
tv_submissionDate!!.text = date
tv_activationDate!!.text = date
}
val isGroupNameValid: Boolean
get() {
result = true
try {
if (TextUtils.isEmpty(et_groupName!!.editableText.toString())) {
throw RequiredFieldException(resources.getString(R.string.group_name),
resources.getString(R.string.error_cannot_be_empty))
}
if (et_groupName!!.editableText.toString().trim { it <= ' ' }.length < 4 && et_groupName!!
.getEditableText().toString().trim { it <= ' ' }.length > 0) {
throw ShortOfLengthException(resources.getString(R.string.group_name), 4)
}
if (!ValidationUtil.isNameValid(et_groupName!!.editableText.toString())) {
throw InvalidTextInputException(resources.getString(R.string.group_name)
, resources.getString(R.string.error_should_contain_only),
InvalidTextInputException.TYPE_ALPHABETS)
}
} catch (e: InvalidTextInputException) {
e.notifyUserWithToast(activity)
result = false
} catch (e: ShortOfLengthException) {
e.notifyUserWithToast(activity)
result = false
} catch (e: RequiredFieldException) {
e.notifyUserWithToast(activity)
result = false
}
return result
}
override fun showOffices(offices: List<Office?>?) {
officeList = offices as List<Office>?
if (offices != null) {
for (office in offices) {
mListOffices.add(office.name)
}
}
Collections.sort(mListOffices)
mOfficesAdapter!!.notifyDataSetChanged()
}
override fun showGroupCreatedSuccessfully(group: SaveResponse?) {
Toast.makeText(activity, "Group " + MifosResponseHandler.getResponse(),
Toast.LENGTH_LONG).show()
requireActivity().supportFragmentManager.popBackStack()
if (PrefManager.getUserStatus() == Constants.USER_ONLINE) {
val groupActivityIntent = Intent(activity, GroupsActivity::class.java)
groupActivityIntent.putExtra(Constants.GROUP_ID, group?.groupId)
startActivity(groupActivityIntent)
}
}
override fun showFetchingError(s: String?) {
Toast.makeText(activity, s, Toast.LENGTH_SHORT).show()
}
override fun showProgressbar(b: Boolean) {
showProgress(b)
}
override fun onAttach(activity: Activity) {
super.onAttach(activity)
}
override fun onDestroyView() {
super.onDestroyView()
mCreateNewGroupPresenter!!.detachView()
}
override fun onDetach() {
super.onDetach()
}
companion object {
@JvmStatic
fun newInstance(): CreateNewGroupFragment {
return CreateNewGroupFragment()
}
}
} | mpl-2.0 | 5fae362690c90b0dd842b59ba4d12ec5 | 38.035714 | 168 | 0.671004 | 4.742527 | false | false | false | false |
sksamuel/elasticsearch-river-neo4j | streamops-datastore/src/main/kotlin/com/octaldata/datastore/metric/MetricDatastore.kt | 1 | 2985 | package com.octaldata.datastore.metric
import com.octaldata.datastore.JdbcCoroutineTemplate
import com.octaldata.domain.DeploymentId
import com.octaldata.domain.integrations.IntegrationId
import com.octaldata.domain.metrics.Metric
import com.octaldata.domain.metrics.MetricId
import com.octaldata.domain.metrics.MetricKey
import com.octaldata.domain.metrics.MetricStatus
import com.octaldata.domain.metrics.MetricType
import com.octaldata.domain.metrics.toTags
import org.springframework.jdbc.core.RowMapper
import javax.sql.DataSource
class MetricDatastore(ds: DataSource) {
private val template = JdbcCoroutineTemplate(ds)
private val mapper = RowMapper { rs, _ ->
Metric(
id = MetricId(rs.getString("id")),
deploymentId = DeploymentId(rs.getString("deployment_id")),
status = MetricStatus.valueOf(rs.getString("status")),
key = MetricKey(rs.getString("keyname")),
type = MetricType.valueOf(rs.getString("type")),
query = rs.getString("query"),
tags = rs.getString("tags")?.toTags() ?: emptyMap(),
integrationIds = rs.getString("integration_ids")
.split(',')
.filter { it.isNotBlank() }
.map { IntegrationId(it) },
)
}
suspend fun findAll(): Result<List<Metric>> {
return template.queryForList("SELECT * FROM `metric` ORDER BY `keyname`", mapper)
}
suspend fun insert(metric: Metric): Result<Int> {
return template.update(
"""INSERT INTO `metric`
(id, deployment_id, status, keyname, type, `query`, tags, integration_ids)
VALUES (?,?,?,?,?,?,?,?)""",
listOf(
metric.id.value,
metric.deploymentId.value,
metric.status.name,
metric.key.value,
metric.type.name,
metric.query,
metric.tags.map { "${it.key}=${it.value}" }.joinToString(","),
metric.integrationIds.joinToString(",") { it.value },
)
)
}
suspend fun update(metric: Metric): Result<Int> {
return template.update(
"""UPDATE `metric` SET status=?, keyname=?, integration_ids=? WHERE id=?""",
listOf(
metric.status.name,
metric.key.value,
metric.integrationIds.joinToString(",") { it.value },
metric.id.value,
)
)
}
suspend fun delete(metricId: MetricId): Result<Int> {
return template.update(
"DELETE FROM `metric` WHERE id=?",
listOf(metricId.value)
)
}
suspend fun getById(metricId: MetricId): Result<Metric?> {
return template.query(
"SELECT * FROM `metric` WHERE id=?",
mapper,
listOf(metricId.value)
)
}
suspend fun setStatus(metricId: MetricId, status: MetricStatus): Result<Int> {
return template.update(
"UPDATE `metric` SET status=? WHERE id=?",
listOf(status.name, metricId.value)
)
}
} | apache-2.0 | 1d2457980ababbdcd451c6f6076595d2 | 32.177778 | 89 | 0.615075 | 4.270386 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/api/item/inventory/builder/InventoryBuilder.kt | 1 | 10018 | /*
* 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>.
*/
package org.lanternpowered.api.item.inventory.builder
import org.lanternpowered.api.item.inventory.ExtendedInventory
import org.lanternpowered.api.item.inventory.ExtendedInventoryColumn
import org.lanternpowered.api.item.inventory.ExtendedInventoryRow
import org.lanternpowered.api.item.inventory.Inventory
import org.lanternpowered.api.item.inventory.InventoryColumn
import org.lanternpowered.api.item.inventory.InventoryRow
import org.lanternpowered.api.item.inventory.ItemStackSnapshot
import org.lanternpowered.api.item.inventory.ViewableInventory
import org.lanternpowered.api.item.inventory.archetype.ColumnArchetype
import org.lanternpowered.api.item.inventory.archetype.InventoryArchetype
import org.lanternpowered.api.item.inventory.archetype.RowArchetype
import org.lanternpowered.api.item.inventory.archetype.SlotArchetype
import org.lanternpowered.api.item.inventory.entity.ExtendedPlayerInventory
import org.lanternpowered.api.item.inventory.hotbar.ExtendedHotbar
import org.lanternpowered.api.item.inventory.slot.EquipmentSlot
import org.lanternpowered.api.item.inventory.slot.ExtendedSlot
import org.lanternpowered.api.item.inventory.slot.FilteringSlot
import org.lanternpowered.api.item.inventory.slot.FuelSlot
import org.lanternpowered.api.item.inventory.slot.InputSlot
import org.lanternpowered.api.item.inventory.slot.OutputSlot
import org.lanternpowered.api.item.inventory.slot.Slot
import org.spongepowered.api.item.inventory.ContainerType
import org.spongepowered.api.item.inventory.equipment.EquipmentGroup
import org.spongepowered.api.item.inventory.equipment.EquipmentType
import org.spongepowered.api.item.inventory.equipment.EquipmentTypes
import java.util.UUID
import java.util.function.Supplier
fun inventoryArchetype(
fn: InventoryBuilder<InventoryArchetype<*>, SlotArchetype<*>, RowArchetype<*>, ColumnArchetype<*>>.() -> Unit
): InventoryArchetype<ExtendedInventory> = TODO()
fun slotArchetype(fn: SlotBuilder<SlotArchetype<*>>.() -> Unit): SlotArchetype<ExtendedSlot> = TODO()
fun inventory(fn: InventoryBuilder<Inventory, Slot, InventoryRow, InventoryColumn>.() -> Unit): Inventory = TODO()
object InventoryTypes {
val Hotbar: InventoryType<ExtendedHotbar> = InventoryType()
val PlayerInventory: InventoryType<ExtendedPlayerInventory> = InventoryType()
}
class InventoryType<I : Inventory>
interface InventoryBaseBuilder {
/**
* Applies the container type of this inventory, applying a container
* type converts this inventory into a [ViewableInventory] which will
* use the given container type.
*/
fun containerType(containerType: ContainerType)
/**
* Applies a "tag" to the inventory, which can be queried for later.
*/
fun tag(tag: String)
/**
* Applies a "unique id" to the inventory, which can be queried for later.
*/
fun uniqueId(uniqueId: UUID)
}
interface InventoryBuilder<I, S, R, C> : InventoryBaseBuilder {
/**
* Adds the given child inventory.
*/
fun inventory(inventory: I)
fun group(fn: InventoryBuilder<I, S, R, C>.() -> Unit)
fun slot(fn: SlotBuilder<I>.() -> Unit)
fun slot()
fun column(height: Int, fn: ColumnBuilder<I, S, C>.(y: Int) -> Unit)
fun column(fn: ColumnBuilder<I, S, C>.(y: Int) -> Unit)
fun row(width: Int, fn: RowBuilder<I, S, R>.(x: Int) -> Unit)
fun row(fn: RowBuilder<I, S, R>.(x: Int) -> Unit)
fun grid(width: Int, height: Int, fn: GridBuilder<I, S, R, C>.() -> Unit)
fun grid(width: Int, height: Int)
fun grid(fn: GridBuilder<I, S, R, C>.() -> Unit)
}
interface GridBuilder<T, S, R, C> : InventoryBaseBuilder {
fun slot(slot: S)
fun slotAt(x: Int, y: Int, slot: S)
fun slots(fn: SlotBuilder<S>.(x: Int, y: Int) -> Unit)
fun slots(fn: SlotBuilder<S>.() -> Unit) = this.slots { _, _ -> fn() }
fun slotAt(x: Int, y: Int, fn: SlotBuilder<S>.() -> Unit)
fun columnAt(x: Int, width: Int, fn: ColumnBuilder<T, S, C>.(y: Int) -> Unit)
fun <C : ExtendedInventoryColumn> GridBuilder<T, S, R, out ColumnArchetype<*>>.columnAt(
x: Int, width: Int, type: InventoryType<out InventoryColumn>, fn: ColumnBuilder<T, S, ColumnArchetype<C>>.(y: Int) -> Unit)
fun columnAt(x: Int, fn: ColumnBuilder<T, S, C>.(y: Int) -> Unit)
fun <C : ExtendedInventoryColumn> GridBuilder<T, S, R, out ColumnArchetype<*>>.columnAt(
x: Int, type: InventoryType<out InventoryColumn>, fn: ColumnBuilder<T, S, ColumnArchetype<C>>.(y: Int) -> Unit)
fun column(height: Int, fn: ColumnBuilder<T, S, C>.(y: Int) -> Unit)
fun <C : ExtendedInventoryColumn> GridBuilder<T, S, R, out ColumnArchetype<*>>.column(
height: Int, type: InventoryType<out InventoryColumn>, fn: ColumnBuilder<T, S, ColumnArchetype<C>>.(y: Int) -> Unit)
fun column(height: Int)
fun <C : ExtendedInventoryColumn> GridBuilder<T, S, R, out ColumnArchetype<C>>.column(
height: Int, type: InventoryType<C>)
fun rowAt(y: Int, width: Int, fn: RowBuilder<T, S, R>.(x: Int) -> Unit)
fun <R : ExtendedInventoryRow> GridBuilder<T, S, out RowArchetype<*>, C>.rowAt(
y: Int, width: Int, type: InventoryType<R>, fn: RowBuilder<T, S, RowArchetype<R>>.(x: Int) -> Unit)
fun rowAt(y: Int, fn: RowBuilder<T, S, R>.(x: Int) -> Unit)
fun <R : ExtendedInventoryRow> GridBuilder<T, S, out RowArchetype<*>, C>.rowAt(
y: Int, type: InventoryType<R>, fn: RowBuilder<T, S, RowArchetype<R>>.(x: Int) -> Unit)
fun row(width: Int, fn: RowBuilder<T, S, R>.(x: Int) -> Unit)
fun <R : ExtendedInventoryRow> GridBuilder<T, S, out RowArchetype<*>, C>.row(
width: Int, type: InventoryType<R>, fn: RowBuilder<T, S, RowArchetype<R>>.(x: Int) -> Unit)
fun row(width: Int)
fun <R : ExtendedInventoryRow> row(width: Int, type: InventoryType<R>)
fun grid(width: Int, height: Int, fn: GridBuilder<T, S, R, C>.() -> Unit)
fun grid(width: Int, height: Int)
fun grid(fn: GridBuilder<T, S, R, C>.() -> Unit)
}
interface ColumnBuilder<T, S, C> : InventoryBaseBuilder {
fun slot(slot: S)
fun slotAt(y: Int, slot: S)
fun slots(fn: SlotBuilder<S>.(y: Int) -> Unit)
fun slots(fn: SlotBuilder<S>.() -> Unit) = this.slots { _ -> fn() }
fun slotsAt(yRange: IntRange, fn: SlotBuilder<S>.(y: Int) -> Unit)
fun slotsAt(yRange: IntRange, fn: SlotBuilder<S>.() -> Unit) = this.slotsAt(yRange) { _ -> fn() }
fun slotAt(y: Int, fn: SlotBuilder<S>.() -> Unit)
fun slot(fn: SlotBuilder<S>.() -> Unit)
}
interface RowBuilder<T, S, R> : InventoryBaseBuilder {
fun row(row: R)
fun rowAt(x: Int, row: R)
fun slot(slot: S)
fun slotAt(x: Int, slot: S)
fun slots(fn: SlotBuilder<S>.(x: Int) -> Unit)
fun slots(fn: SlotBuilder<S>.() -> Unit) = this.slots { _ -> fn() }
fun slotsAt(xRange: IntRange, fn: SlotBuilder<S>.(x: Int) -> Unit)
fun slotsAt(xRange: IntRange, fn: SlotBuilder<S>.() -> Unit) = this.slotsAt(xRange) { _ -> fn() }
fun slotAt(x: Int, fn: SlotBuilder<S>.() -> Unit)
fun slot(fn: SlotBuilder<S>.() -> Unit)
}
/**
* This applies an equipment filter to the slot, this means that only
* certain items will be accepted by the slot. This will turn the slot
* in an [EquipmentSlot].
*/
fun SlotBuilder<*>.equipment(type: Supplier<out EquipmentType>) =
this.equipment(type.get())
/**
* This applies an equipment filter to the slot, this means that only
* certain items will be accepted by the slot. This will turn the slot
* in an [EquipmentSlot].
*/
@JvmName("equipmentGroup")
fun SlotBuilder<*>.equipment(type: Supplier<out EquipmentGroup>) =
this.equipment(type.get())
interface SlotBuilder<T> : InventoryBaseBuilder {
/**
* This applies a filter to the slot, this means that only certain
* items will be accepted by the slot. This will turn the slot in
* a [FilteringSlot].
*/
fun filter(fn: (ItemStackSnapshot) -> Boolean)
/**
* This applies an equipment filter to the slot, this means that only
* certain items will be accepted by the slot. This will turn the slot
* in an [EquipmentSlot].
*/
fun equipment()
/**
* This applies an equipment filter to the slot, this means that only
* certain items will be accepted by the slot. This will turn the slot
* in an [EquipmentSlot].
*/
fun equipment(type: EquipmentType)
/**
* This applies an equipment filter to the slot, this means that only
* certain items will be accepted by the slot. This will turn the slot
* in an [EquipmentSlot].
*/
fun equipment(type: EquipmentGroup)
/**
* Marks the slot as a [FuelSlot]. This does not apply any filters.
*/
fun fuel()
/**
* Marks the slot as an [InputSlot]. This does not apply any filters.
*/
fun input()
/**
* Marks the slot as an [OutputSlot]. This does not apply any filters.
*/
fun output()
}
fun test() {
inventoryArchetype {
// Equipment
column {
slot {
equipment(EquipmentTypes.HEAD)
}
slot {
equipment(EquipmentTypes.CHEST)
}
slot {
equipment(EquipmentTypes.LEGS)
}
slot {
equipment(EquipmentTypes.FEET)
}
}
// Primary inventory
grid {
// Storage
grid(width = 9, height = 3)
// Hotbar
row(width = 9, type = InventoryTypes.Hotbar)
}
// Off hand
slot {
equipment(EquipmentTypes.OFF_HAND)
}
}
}
| mit | d67fd724f93d1bcad769801f8ed24967 | 32.61745 | 135 | 0.661509 | 3.71037 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/permission/ProxySubject.kt | 1 | 5394 | /*
* 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>.
*/
package org.lanternpowered.server.permission
import org.lanternpowered.api.service.serviceOf
import org.lanternpowered.api.util.optional.emptyOptional
import org.lanternpowered.server.service.permission.LanternPermissionService
import org.spongepowered.api.service.context.Context
import org.spongepowered.api.service.permission.PermissionService
import org.spongepowered.api.service.permission.Subject
import org.spongepowered.api.service.permission.SubjectCollection
import org.spongepowered.api.service.permission.SubjectData
import org.spongepowered.api.service.permission.SubjectReference
import org.spongepowered.api.util.Tristate
import java.util.Optional
interface ProxySubject : Subject {
/**
* The internal [SubjectReference].
*
* @return The internal subject reference
*/
var internalSubject: SubjectReference?
/**
* Gets the identifier of the subject collection.
*
* @return The subject collection identifier
*/
val subjectCollectionIdentifier: String
/**
* Gets the default [Tristate] result
* for the given permission.
*
* @param permission The permission
* @return The result
*/
fun getPermissionDefault(permission: String): Tristate
@JvmDefault
fun resolveNullableSubject(): Subject? {
var reference = this.internalSubject
if (reference == null) {
val service = serviceOf<PermissionService>()
if (service != null) {
// Try to update the internal subject
// check if we're using the native Lantern impl
// we can skip some unnecessary instance creation this way.
reference = if (service is LanternPermissionService) {
service[this.subjectCollectionIdentifier][this.identifier].asSubjectReference()
} else {
// build a new subject reference using the permission service
// this doesn't actually load the subject, so it will be lazily initialized when needed.
service.newSubjectReference(this.subjectCollectionIdentifier, this.identifier)
}
this.internalSubject = reference
}
}
return reference?.resolve()?.join()
}
@JvmDefault
fun resolveSubject(): Subject = this.resolveNullableSubject() ?: throw IllegalStateException("No subject present for $identifier")
// Delegated methods
@JvmDefault override fun asSubjectReference() = checkNotNull(this.internalSubject) { "No internal subject reference is set" }
@JvmDefault override fun getContainingCollection(): SubjectCollection = this.resolveSubject().containingCollection
@JvmDefault override fun getSubjectData(): SubjectData = this.resolveSubject().subjectData
@JvmDefault override fun getTransientSubjectData(): SubjectData = this.resolveSubject().transientSubjectData
@JvmDefault override fun isSubjectDataPersisted(): Boolean = this.resolveNullableSubject()?.isSubjectDataPersisted ?: false
@JvmDefault override fun getFriendlyIdentifier(): Optional<String> = this.resolveNullableSubject()?.friendlyIdentifier ?: emptyOptional()
@JvmDefault
override fun hasPermission(contexts: Set<Context>, permission: String): Boolean {
val subject = this.resolveNullableSubject()
return if (subject == null) {
this.getPermissionDefault(permission).asBoolean()
} else {
when (val tristate = this.getPermissionValue(contexts, permission)) {
Tristate.UNDEFINED -> this.getPermissionDefault(permission).asBoolean()
else -> tristate.asBoolean()
}
}
}
@JvmDefault
override fun getPermissionValue(contexts: Set<Context>, permission: String): Tristate =
this.resolveNullableSubject()?.getPermissionValue(contexts, permission) ?: getPermissionDefault(permission)
@JvmDefault
override fun isChildOf(parent: SubjectReference) =
this.resolveNullableSubject()?.isChildOf(parent) ?: false
@JvmDefault
override fun isChildOf(contexts: Set<Context>, parent: SubjectReference) =
this.resolveNullableSubject()?.isChildOf(contexts, parent) ?: false
@JvmDefault
override fun getParents(): List<SubjectReference> =
this.resolveNullableSubject()?.parents ?: emptyList()
@JvmDefault
override fun getParents(contexts: Set<Context>): List<SubjectReference> =
this.resolveNullableSubject()?.getParents(contexts) ?: emptyList()
@JvmDefault
override fun getActiveContexts(): Set<Context> =
this.resolveNullableSubject()?.activeContexts ?: emptySet()
@JvmDefault
override fun getOption(key: String): Optional<String> =
this.resolveNullableSubject()?.getOption(key) ?: emptyOptional()
@JvmDefault
override fun getOption(contexts: Set<Context>, key: String): Optional<String> =
this.resolveNullableSubject()?.getOption(contexts, key) ?: emptyOptional()
}
| mit | 4328f6a307365a2895191aba685ac2b9 | 41.140625 | 141 | 0.697627 | 5.060038 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/common/identity/AuthorityKeyServerInterceptor.kt | 1 | 3114 | // Copyright 2021 The Cross-Media Measurement Authors
//
// 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.wfanet.measurement.common.identity
import com.google.protobuf.ByteString
import io.grpc.Context
import io.grpc.Contexts
import io.grpc.Grpc
import io.grpc.Metadata
import io.grpc.ServerCall
import io.grpc.ServerCallHandler
import io.grpc.ServerInterceptor
import io.grpc.Status
import java.security.cert.X509Certificate
import javax.net.ssl.SSLSession
import org.wfanet.measurement.api.v2alpha.ContextKeys
import org.wfanet.measurement.common.crypto.authorityKeyIdentifier
import org.wfanet.measurement.common.grpc.failGrpc
/** Returns an [X509Certificate] installed in the current [io.grpc.Context]. */
val authorityKeyIdentifiersFromCurrentContext: List<ByteString>
get() =
AuthorityKeyServerInterceptor.AUTHORITY_KEY_IDENTIFIERS_CONTEXT_KEY.get()
?: failGrpc(Status.UNAUTHENTICATED) { "No authority keys available" }
/**
* gRPC [ServerInterceptor] that extracts Authority Key Identifiers from X509 certificates.
*
* The Authority Key Identifiers can be accessed by using
* [authorityKeyIdentifiersFromCurrentContext].
*/
class AuthorityKeyServerInterceptor : ServerInterceptor {
override fun <ReqT, RespT> interceptCall(
call: ServerCall<ReqT, RespT>,
headers: Metadata,
next: ServerCallHandler<ReqT, RespT>
): ServerCall.Listener<ReqT> {
if (ContextKeys.PRINCIPAL_CONTEXT_KEY.get() != null) {
return Contexts.interceptCall(Context.current(), call, headers, next)
}
val sslSession: SSLSession? = call.attributes[Grpc.TRANSPORT_ATTR_SSL_SESSION]
if (sslSession == null) {
call.close(Status.UNAUTHENTICATED.withDescription("No SSL session found"), Metadata())
return object : ServerCall.Listener<ReqT>() {}
}
val x509Certificates = sslSession.peerCertificates.filterIsInstance<X509Certificate>()
val authorityKeys: List<ByteString> = x509Certificates.mapNotNull { it.authorityKeyIdentifier }
if (authorityKeys.size != x509Certificates.size) {
call.close(
Status.UNAUTHENTICATED.withDescription(
"X509 certificate is missing an authority key identifier"
),
Metadata()
)
return object : ServerCall.Listener<ReqT>() {}
}
val context = Context.current().withValue(AUTHORITY_KEY_IDENTIFIERS_CONTEXT_KEY, authorityKeys)
return Contexts.interceptCall(context, call, headers, next)
}
companion object {
val AUTHORITY_KEY_IDENTIFIERS_CONTEXT_KEY: Context.Key<List<ByteString>> =
Context.key("authority-key-identifiers")
}
}
| apache-2.0 | 05cb529707025b36bf3ac02144321fd9 | 36.97561 | 99 | 0.751766 | 4.289256 | false | false | false | false |
natanieljr/droidmate | project/pcComponents/core/src/main/kotlin/org/droidmate/command/InlineCommand.kt | 1 | 2840 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// 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/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.command
import org.droidmate.device.android_sdk.AaptWrapper
import org.droidmate.monitor.ApkInliner
import org.droidmate.configuration.ConfigurationWrapper
import org.droidmate.device.android_sdk.Apk
import org.droidmate.misc.FailableExploration
import org.droidmate.misc.SysCmdExecutor
import org.droidmate.tools.ApksProvider
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.nio.file.Files
import java.nio.file.Path
class InlineCommand @JvmOverloads constructor(cfg: ConfigurationWrapper,
private val inliner: ApkInliner = ApkInliner(cfg.resourceDir)) {
companion object {
@JvmStatic
private val log: Logger by lazy { LoggerFactory.getLogger(this::class.java) }
@JvmStatic
private fun moveOriginal(apk: Apk, originalsDir: Path) {
val original = originalsDir.resolve(apk.fileName)
if (!Files.exists(original)) {
Files.move(apk.path, original)
log.info("Moved ${original.fileName} to '${originalsDir.fileName}' sub dir.")
} else {
log.info("Skipped moving ${original.fileName} to '${originalsDir.fileName}' sub dir: it already exists there.")
}
}
}
fun execute(cfg: ConfigurationWrapper): Map<Apk, FailableExploration> {
val apksProvider = ApksProvider(AaptWrapper())
val apks = apksProvider.getApks(cfg.apksDirPath, 0, ArrayList(), false)
if (apks.all { it.inlined }) {
log.warn("No non-inlined apks found. Aborting.")
return emptyMap()
}
val originalsDir = cfg.apksDirPath.resolve("originals").toAbsolutePath()
Files.createDirectories(originalsDir)
apks.filter { !it.inlined }.forEach { apk ->
inliner.instrumentApk(apk.path, apk.path.parent)
log.info("Inlined ${apk.fileName}")
moveOriginal(apk, originalsDir)
}
return emptyMap()
}
}
| gpl-3.0 | 13e13ed0028d0f14fe7636c4898f57e7 | 34.949367 | 115 | 0.738732 | 3.761589 | false | true | false | false |
rcgroot/open-gpstracker-ng | studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/map/TrackMapViewModel.kt | 1 | 2224 | /*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) 2016 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker 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.
*
* OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.ng.features.map
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import android.net.Uri
import com.google.android.gms.maps.model.LatLngBounds
import nl.sogeti.android.gpstracker.ng.base.location.LatLng
class TrackMapViewModel {
val trackUri: ObservableField<Uri?> = ObservableField()
val name: ObservableField<String> = ObservableField("")
val waypoints = ObservableField<List<List<LatLng>>?>()
val completeBounds = ObservableField<LatLngBounds?>()
val trackHead = ObservableField<LatLng?>()
val showSatellite = ObservableBoolean(false)
val willLock = ObservableBoolean(false)
val isLocked = ObservableBoolean(false)
}
| gpl-3.0 | 7070526eacb57fc97ff01050f5daddc2 | 47.347826 | 81 | 0.641637 | 4.953229 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-general/src/main/java/net/nemerosa/ontrack/extension/general/BuildLinkSearchExtension.kt | 1 | 4431 | package net.nemerosa.ontrack.extension.general
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.common.asMap
import net.nemerosa.ontrack.extension.support.AbstractExtension
import net.nemerosa.ontrack.job.Schedule
import net.nemerosa.ontrack.json.parseOrNull
import net.nemerosa.ontrack.model.events.BuildLinkListener
import net.nemerosa.ontrack.model.structure.*
import net.nemerosa.ontrack.ui.controller.EntityURIBuilder
import org.springframework.stereotype.Component
/**
* Searching on the build links.
*/
@Component
class BuildLinkSearchExtension(
extensionFeature: GeneralExtensionFeature,
private val uriBuilder: EntityURIBuilder,
private val structureService: StructureService,
private val buildDisplayNameService: BuildDisplayNameService,
private val searchIndexService: SearchIndexService
) : AbstractExtension(extensionFeature), SearchIndexer<BuildLinkSearchItem>, BuildLinkListener {
override val indexerName: String = "Build links"
override val indexName: String = BUILD_LINK_SEARCH_INDEX
override val indexerSchedule: Schedule = Schedule.EVERY_DAY
override val searchResultType = SearchResultType(
feature = extensionFeature.featureDescription,
id = "build-link",
name = "Linked Build",
description = "Reference to a linked project and build, using format project:[build] where the target build is optional"
)
override val indexMapping: SearchIndexMapping? = indexMappings<BuildLinkSearchItem> {
+BuildLinkSearchItem::fromBuildId to id { index = false }
+BuildLinkSearchItem::targetBuildId to id { index = false }
+BuildLinkSearchItem::targetProject to keyword()
+BuildLinkSearchItem::targetBuild to keyword()
+BuildLinkSearchItem::targetKey to text { scoreBoost = 3.0 }
}
override fun indexAll(processor: (BuildLinkSearchItem) -> Unit) {
structureService.forEachBuildLink { from, to ->
process(from, to, processor)
}
}
override fun toSearchResult(id: String, score: Double, source: JsonNode): SearchResult? {
// Parsing
val item = source.parseOrNull<BuildLinkSearchItem>()
// Loading
return item?.run {
// Loads the source build
structureService.findBuildByID(ID.of(item.fromBuildId))
}?.takeIf {
// The target build must still exist
structureService.findBuildByID(ID.of(item.targetBuildId)) != null
}?.run {
SearchResult(
entityDisplayName,
"Linked to ${item.targetProject}:${item.targetBuild}",
uriBuilder.getEntityURI(this),
uriBuilder.getEntityPage(this),
score,
searchResultType
)
}
}
override fun onBuildLinkAdded(from: Build, to: Build) {
process(from, to) { item ->
searchIndexService.createSearchIndex(this, item)
}
}
override fun onBuildLinkDeleted(from: Build, to: Build) {
process(from, to) { item ->
searchIndexService.deleteSearchIndex(this, item.id)
}
}
private fun process(from: Build, to: Build, processor: (BuildLinkSearchItem) -> Unit) {
processor(BuildLinkSearchItem(from, to))
// Alternative name
val otherName = buildDisplayNameService.getBuildDisplayName(to)
if (otherName != to.name) {
processor(BuildLinkSearchItem(from, to, otherName))
}
}
}
/**
* Index name for the build links
*/
const val BUILD_LINK_SEARCH_INDEX = "build-links"
class BuildLinkSearchItem(
val fromBuildId: Int,
val targetBuildId: Int,
val targetProject: String,
val targetBuild: String
) : SearchItem {
constructor(from: Build, to: Build, targetBuildName: String = to.name) : this(
fromBuildId = from.id(),
targetBuildId = to.id(),
targetProject = to.project.name,
targetBuild = targetBuildName
)
override val id: String = "$fromBuildId::$targetBuildId"
val targetKey = "$targetProject:$targetBuild"
override val fields: Map<String, Any?> = asMap(
this::fromBuildId,
this::targetBuildId,
this::targetProject,
this::targetBuild,
this::targetKey
)
} | mit | e0d5f84006b5371a7b3550f312402c20 | 33.897638 | 132 | 0.660348 | 4.610822 | false | false | false | false |
scana/ok-gradle | plugin/src/main/java/me/scana/okgradle/data/repository/BintrayRepository.kt | 1 | 1674 | package me.scana.okgradle.data.repository
import com.google.gson.Gson
import io.reactivex.Single
import me.scana.okgradle.util.fromJson
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Request
class BintrayRepository(private val networkClient: NetworkClient, private val gson: Gson) : ArtifactRepository {
companion object {
val BINTRAY_URL: HttpUrl = "https://api.bintray.com/search/packages/maven".toHttpUrl()
}
override fun search(query: String): Single<SearchResult> {
return Single.create {
val result = when {
query.isEmpty() -> SearchResult.Success()
else -> findArtifacts(query)
}
it.onSuccess(result)
}
}
private fun findArtifacts(query: String): SearchResult {
val url = BINTRAY_URL.newBuilder()
.addQueryParameter("a", "*$query*")
.addQueryParameter("repo", "jcenter")
.addQueryParameter("repo", "bintray")
.build()
val request = Request.Builder()
.url(url)
.build()
val response = networkClient.execute(request) {
val result = gson.fromJson<List<BintrayResult>>(this.charStream())
result.map {
val (groupId, artifactId) = it.name.split(":".toRegex(), 2)
Artifact(groupId, artifactId, it.versions.first())
}
}
return when(response) {
is NetworkResult.Success -> SearchResult.Success(response.data)
is NetworkResult.Failure -> SearchResult.Error(response.throwable)
}
}
} | apache-2.0 | 882b5b6fa896f69bb3d2989e399de93c | 31.843137 | 112 | 0.603943 | 4.61157 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/mixin/folding/MixinFoldingOptionsProvider.kt | 1 | 1543 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.folding
import com.intellij.application.options.editor.CodeFoldingOptionsProvider
import com.intellij.openapi.options.BeanConfigurable
class MixinFoldingOptionsProvider :
BeanConfigurable<MixinFoldingSettings.State>(MixinFoldingSettings.instance.state), CodeFoldingOptionsProvider {
init {
title = "Mixin"
val settings = MixinFoldingSettings.instance
checkBox(
"Target descriptors",
{ settings.state.foldTargetDescriptors },
{ b -> settings.state.foldTargetDescriptors = b }
)
checkBox("Object casts", { settings.state.foldObjectCasts }, { b -> settings.state.foldObjectCasts = b })
checkBox(
"Invoker casts",
{ settings.state.foldInvokerCasts },
{ b -> settings.state.foldInvokerCasts = b }
)
checkBox(
"Invoker method calls",
{ settings.state.foldInvokerMethodCalls },
{ b -> settings.state.foldInvokerMethodCalls = b }
)
checkBox(
"Accessor casts",
{ settings.state.foldAccessorCasts },
{ b -> settings.state.foldAccessorCasts = b }
)
checkBox(
"Accessor method calls",
{ settings.state.foldAccessorMethodCalls },
{ b -> settings.state.foldAccessorMethodCalls = b }
)
}
}
| mit | 7f596c7f4e72e9896d41ba7e105822d6 | 29.86 | 115 | 0.618924 | 4.747692 | false | false | false | false |
synyx/calenope | modules/organizer/src/main/kotlin/de/synyx/calenope/organizer/component/WeekviewEditor.kt | 1 | 7467 | package de.synyx.calenope.organizer.component
import android.app.TimePickerDialog
import android.content.Context
import android.view.Gravity
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.TimePicker
import com.encodeering.conflate.experimental.api.Storage
import de.synyx.calenope.organizer.Interact
import de.synyx.calenope.organizer.Interaction
import de.synyx.calenope.organizer.R
import de.synyx.calenope.organizer.State
import de.synyx.calenope.organizer.component.Widgets.Button
import de.synyx.calenope.organizer.component.Widgets.Speechinput
import de.synyx.calenope.organizer.speech.Speech
import trikita.anvil.BaseDSL.layoutGravity
import trikita.anvil.DSL.MATCH
import trikita.anvil.DSL.WRAP
import trikita.anvil.DSL.dip
import trikita.anvil.DSL.linearLayout
import trikita.anvil.DSL.margin
import trikita.anvil.DSL.onClick
import trikita.anvil.DSL.onEditorAction
import trikita.anvil.DSL.orientation
import trikita.anvil.DSL.sip
import trikita.anvil.DSL.size
import trikita.anvil.DSL.text
import trikita.anvil.DSL.textSize
import trikita.anvil.DSL.textView
/**
* @author clausen - [email protected]
*/
class WeekviewEditor (
private val context : Context,
private val speech : Speech,
private val store : Storage<State>
) : Component () {
override fun view () {
linearLayout {
size (MATCH, dip (210))
orientation (LinearLayout.VERTICAL)
val interaction = store.state.events.interaction
when (interaction) {
is Interaction.Inspect -> {
textView {
text (interaction.event.description ().run { take (197) + if (length > 197) "..." else "" })
textSize (sip (16.0f))
size (MATCH, WRAP)
margin (dip (20), dip (20), dip (20), 0)
}
}
is Interaction.Create -> {
fun editorwatch (action : TextView. () -> Unit) = { view : TextView, code : Int, _ : KeyEvent? ->
when (code) {
EditorInfo.IME_ACTION_PREVIOUS,
EditorInfo.IME_ACTION_NEXT,
EditorInfo.IME_ACTION_DONE -> action (view)
}
false
}
show {
Speechinput (interaction.title, context.getString (R.string.weekview_editor_title),
input = {
always += {
onEditorAction (editorwatch {
store.state.events.interaction.apply {
when (this) {
is Interaction.Create -> store.dispatcher.dispatch (Interact (copy (title = text.toString ()), visualize = true))
}
}
})
}
},
button = {
always += {
onClick {
speech.ask (context.getString (R.string.weekview_editor_title)) {
store.state.events.interaction.apply {
when (this) {
is Interaction.Create -> store.dispatcher.dispatch (Interact (copy (title = it), visualize = true))
}
}
}
}
}
})
}
show {
Speechinput (interaction.description, context.getString (R.string.weekview_editor_description),
input = {
always += {
onEditorAction (editorwatch {
store.state.events.interaction.apply {
when (this) {
is Interaction.Create -> store.dispatcher.dispatch (Interact (copy (description = text.toString ()), visualize = true))
}
}
})
}
},
button = {
always += {
onClick {
speech.ask (context.getString (R.string.weekview_editor_description)) {
store.state.events.interaction.apply {
when (this) {
is Interaction.Create -> store.dispatcher.dispatch (Interact (copy (description = it), visualize = true))
}
}
}
}
}
})
}
show {
Button (R.drawable.ic_timelapse) {
always += {
margin (0, dip (20), dip (20), 0)
layoutGravity (Gravity.RIGHT)
onClick {
store.state.events.interaction.apply {
when (this) {
is Interaction.Create -> start.plusMinutes (15).let {
val listener : (TimePicker, Int, Int) -> Unit = { _, hour, minute ->
val to = it.withMinuteOfHour (minute)
.withHourOfDay (hour)
if (to.isAfter (it)) {
store.dispatcher.dispatch (Interact (copy (end = to), visualize = true))
}
}
TimePickerDialog (context, listener, it.hourOfDay, it.minuteOfHour, true).run {
setCancelable (true)
setTitle (context.getString (R.string.weekview_editor_date))
show ()
}
}
}
}
}
}
}
}
}
}
}
}
} | apache-2.0 | 02de00ca1be971c2c45d110f1c5f5cb1 | 45.968553 | 167 | 0.388376 | 6.590468 | false | false | false | false |
apixandru/intellij-community | java/java-impl/src/com/intellij/lang/java/actions/CreateEnumConstantAction.kt | 2 | 4254 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.lang.java.actions
import com.intellij.codeInsight.CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement
import com.intellij.codeInsight.ExpectedTypeUtil
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.positionCursor
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.startTemplate
import com.intellij.codeInsight.daemon.impl.quickfix.EmptyExpression
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.lang.jvm.actions.CreateFieldRequest
import com.intellij.lang.jvm.actions.ExpectedTypes
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiEnumConstant
import com.intellij.psi.PsiFile
class CreateEnumConstantAction(targetClass: PsiClass, request: CreateFieldRequest) : CreateFieldActionBase(targetClass, request) {
private val myData: EnumConstantData?
get() {
val targetClass = myTargetClass.element
if (targetClass == null || !myRequest.isValid) return null
return extractRenderData(targetClass, myRequest)
}
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
val data = myData ?: return false
text = QuickFixBundle.message("create.enum.constant.from.usage.text", data.constantName)
return true
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
val data = myData ?: return
val name = data.constantName
val targetClass = data.targetClass
val elementFactory = JavaPsiFacade.getElementFactory(project)!!
// add constant
var enumConstant: PsiEnumConstant
enumConstant = elementFactory.createEnumConstantFromText(name, null)
enumConstant = targetClass.add(enumConstant) as PsiEnumConstant
// start template
val constructor = targetClass.constructors.firstOrNull() ?: return
val parameters = constructor.parameterList.parameters
if (parameters.isEmpty()) return
val paramString = parameters.joinToString(",") { it.name ?: "" }
enumConstant = enumConstant.replace(elementFactory.createEnumConstantFromText("$name($paramString)", null)) as PsiEnumConstant
val builder = TemplateBuilderImpl(enumConstant)
val argumentList = enumConstant.argumentList!!
for (expression in argumentList.expressions) {
builder.replaceElement(expression, EmptyExpression())
}
enumConstant = forcePsiPostprocessAndRestoreElement(enumConstant)
val template = builder.buildTemplate()
val newEditor = positionCursor(project, targetClass.containingFile, enumConstant) ?: return
val range = enumConstant.textRange
newEditor.document.deleteString(range.startOffset, range.endOffset)
startTemplate(newEditor, template, project)
}
}
private class EnumConstantData(
val targetClass: PsiClass,
val constantName: String
)
private fun extractRenderData(targetClass: PsiClass, request: CreateFieldRequest): EnumConstantData? {
if (!targetClass.isEnum) return null
if (!checkExpectedTypes(request.fieldType, targetClass, targetClass.project)) return null
return EnumConstantData(targetClass, request.fieldName)
}
private fun checkExpectedTypes(types: ExpectedTypes, targetClass: PsiClass, project: Project): Boolean {
val typeInfos = extractExpectedTypes(project, types)
if (typeInfos.isEmpty()) return true
val enumType = JavaPsiFacade.getElementFactory(project).createType(targetClass)
return typeInfos.any {
ExpectedTypeUtil.matches(enumType, it)
}
}
| apache-2.0 | 302d7d810c4295ec013b7ba7c6d3426f | 41.118812 | 130 | 0.782558 | 4.823129 | false | false | false | false |
karollewandowski/aem-intellij-plugin | src/main/kotlin/co/nums/intellij/aem/htl/inspections/HtlWrongStringQuotes.kt | 1 | 3946 | package co.nums.intellij.aem.htl.inspections
import co.nums.intellij.aem.extensions.canBeEdited
import co.nums.intellij.aem.htl.extensions.*
import co.nums.intellij.aem.htl.psi.HtlStringLiteral
import co.nums.intellij.aem.messages.HtlInspectionsBundle.message
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.annotation.*
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
/**
* Annotates HTL string literals with the same quotes as outer HTML attribute.
*/
class HtlWrongStringQuotesAnnotator : Annotator {
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
if (element is HtlStringLiteral && element.hasWrongQuotes()) {
holder.createErrorAnnotation(element.getTextRange(), message("inspections.htl.wrong.string.quotes.annotation"))
.registerFix(stringQuotesFixFor(element))
}
}
private fun PsiElement.hasWrongQuotes(): Boolean {
val htlStringQuote = this.text[0]
val outerHtmlAttributeQuote = this.getOuterHtmlAttributeQuote()
return htlStringQuote == outerHtmlAttributeQuote
}
private fun stringQuotesFixFor(htlStringLiteral: HtlStringLiteral): HtlStringQuotesFix {
val htlStringQuote = htlStringLiteral.text[0]
return when (htlStringQuote) {
'\'' -> HtlStringSingleQuotesFix
'"' -> HtlStringDoubleQuotesFix
else -> throw IllegalStateException("Found invalid string quote character: $htlStringQuote")
}
}
}
private const val SINGLE_QUOTE = '\''
private const val DOUBLE_QUOTE = '"'
object HtlStringSingleQuotesFix : HtlStringQuotesFix(SINGLE_QUOTE)
object HtlStringDoubleQuotesFix : HtlStringQuotesFix(DOUBLE_QUOTE)
open class HtlStringQuotesFix(private val quoteToFix: Char) : IntentionAction {
private val quoteToInsert: Char
get() = if (quoteToFix == DOUBLE_QUOTE) SINGLE_QUOTE else DOUBLE_QUOTE
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val currentElement = file.findElementAt(editor.caretModel.offset) ?: return
val stringLiteralToFix = getStringLiteralToFix(currentElement)
if (stringLiteralToFix?.canBeEdited() == true) {
fixQuotes(project, file, stringLiteralToFix)
}
}
private fun getStringLiteralToFix(currentElement: PsiElement): PsiElement? {
if (currentElement.isPartOfHtlString()) return currentElement.parent
val prevVisibleLeaf = PsiTreeUtil.prevVisibleLeaf(currentElement) ?: return null
if (prevVisibleLeaf.isPartOfHtlString()) return prevVisibleLeaf.parent
return null
}
private fun fixQuotes(project: Project, file: PsiFile, htlStringLiteral: PsiElement) {
val document = PsiDocumentManager.getInstance(project).getDocument(file)
if (document != null) {
val currentText = htlStringLiteral.text
var replacement = quoteToInsert + currentText.substring(1)
if (endsWithUnescapedQuote(currentText, replacement)) {
replacement = replacement.substring(0, replacement.length - 1) + quoteToInsert
}
val textRange = htlStringLiteral.textRange
document.replaceString(textRange.startOffset, textRange.endOffset, replacement)
}
}
private fun endsWithUnescapedQuote(currentText: String, replacement: String) =
currentText.length > 1
&& currentText.endsWith(Character.toString(quoteToFix)) && !replacement.endsWith("\\" + quoteToFix)
override fun getText() = message("inspections.htl.wrong.string.quotes.fix")
override fun getFamilyName() = message("inspection.htl.family")
override fun startInWriteAction() = true
override fun isAvailable(project: Project, editor: Editor, file: PsiFile) = true
}
| gpl-3.0 | a9f145cbe6f2f33e70aee09a94c64f59 | 40.104167 | 123 | 0.718702 | 4.731415 | false | false | false | false |
wbrawner/SimpleMarkdown | app/src/main/java/com/wbrawner/simplemarkdown/utility/Extensions.kt | 1 | 2107 | package com.wbrawner.simplemarkdown.utility
import android.content.Context
import android.content.res.AssetManager
import android.net.Uri
import android.provider.OpenableColumns
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.commonsware.cwac.anddown.AndDown
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.Reader
fun View.showKeyboard() {
(context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
requestFocus()
}
fun View.hideKeyboard() =
(context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
.hideSoftInputFromWindow(windowToken, 0)
suspend fun AssetManager.readAssetToString(asset: String): String? {
return withContext(Dispatchers.IO) {
open(asset).reader().use(Reader::readText)
}
}
const val HOEDOWN_FLAGS = AndDown.HOEDOWN_EXT_STRIKETHROUGH or AndDown.HOEDOWN_EXT_TABLES or
AndDown.HOEDOWN_EXT_UNDERLINE or AndDown.HOEDOWN_EXT_SUPERSCRIPT or
AndDown.HOEDOWN_EXT_FENCED_CODE
suspend fun String.toHtml(): String {
return withContext(Dispatchers.IO) {
AndDown().markdownToHtml(this@toHtml, HOEDOWN_FLAGS, 0)
}
}
suspend fun Uri.getName(context: Context): String {
var fileName: String? = null
try {
if ("content" == scheme) {
withContext(Dispatchers.IO) {
context.contentResolver.query(
this@getName,
null,
null,
null,
null
)?.use {
val nameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
it.moveToFirst()
fileName = it.getString(nameIndex)
}
}
} else if ("file" == scheme) {
fileName = lastPathSegment
}
} catch (ignored: Exception) {
ignored.printStackTrace()
}
return fileName ?: "Untitled.md"
}
| apache-2.0 | c3cd263900ad548339a27a2aff3b9402 | 31.921875 | 92 | 0.643094 | 4.445148 | false | false | false | false |
mctoyama/PixelClient | src/main/kotlin/org/pixelndice/table/pixelclient/connection/main/state06joingamebyuuid/State07SendingQueryGameByUUID.kt | 1 | 863 | package org.pixelndice.table.pixelclient.connection.main.state06joingamebyuuid
import org.apache.logging.log4j.LogManager
import org.pixelndice.table.pixelclient.connection.main.Context
import org.pixelndice.table.pixelclient.connection.main.State
import org.pixelndice.table.pixelclient.gameTag
import org.pixelndice.table.pixelprotocol.Protobuf
private val logger = LogManager.getLogger(State07SendingQueryGameByUUID::class.java)
class State07SendingQueryGameByUUID: State {
override fun process(ctx: Context): Unit {
val queryGame = Protobuf.QueryGame.newBuilder()
val resp = Protobuf.Packet.newBuilder()
queryGame.setUuid(gameTag)
resp.setQueryGame(queryGame.build())
ctx.packet = resp.build()
ctx.state = State08WaitingQueryGameByUUID()
logger.debug("Sending query game $gameTag")
}
} | bsd-2-clause | 7e676691d8bf97adb9d91f7a9fbc4751 | 29.857143 | 84 | 0.765933 | 4.051643 | false | false | false | false |
pennlabs/penn-mobile-android | PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/HomeAdapter.kt | 1 | 20592 | package com.pennapps.labs.pennmobile.adapters
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Build
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.browser.customtabs.CustomTabsClient
import androidx.browser.customtabs.CustomTabsIntent
import androidx.browser.customtabs.CustomTabsServiceConnection
import androidx.browser.customtabs.CustomTabsSession
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat.getColor
import androidx.core.content.ContextCompat.startActivity
import androidx.core.graphics.ColorUtils
import androidx.core.graphics.drawable.DrawableCompat
import androidx.palette.graphics.Palette
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.pennapps.labs.pennmobile.*
import com.pennapps.labs.pennmobile.DiningFragment.Companion.getMenus
import com.pennapps.labs.pennmobile.api.StudentLife
import com.pennapps.labs.pennmobile.classes.CalendarEvent
import com.pennapps.labs.pennmobile.classes.DiningHall
import com.pennapps.labs.pennmobile.classes.HomeCell
import com.pennapps.labs.pennmobile.components.sneaker.Utils.convertToDp
import com.squareup.picasso.Picasso
import eightbitlab.com.blurview.RenderScriptBlur
import kotlinx.android.synthetic.main.home_base_card.view.*
import kotlinx.android.synthetic.main.home_news_card.view.*
import kotlinx.android.synthetic.main.home_post_card.view.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import rx.Observable
class HomeAdapter(private var cells: ArrayList<HomeCell>) :
RecyclerView.Adapter<HomeAdapter.ViewHolder>() {
private lateinit var mContext: Context
private lateinit var mActivity: MainActivity
private lateinit var mStudentLife: StudentLife
private var mCustomTabsClient: CustomTabsClient? = null
private var customTabsIntent: CustomTabsIntent? = null
private var share: Intent? = null
private var session: CustomTabsSession? = null
private var builder: CustomTabsIntent.Builder? = null
companion object {
// Types of Home Cells
private const val NOT_SUPPORTED = -1
private const val RESERVATIONS = 0
private const val DINING = 1
private const val CALENDAR = 2
private const val NEWS = 3
private const val LAUNDRY = 5
private const val GSR_BOOKING = 6
private const val POST = 7
private const val FEATURE = 8
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
mContext = parent.context
mStudentLife = MainActivity.studentLifeInstance
mActivity = mContext as MainActivity
return when (viewType) {
NEWS -> {
ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.home_news_card, parent, false))
}
POST -> {
ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.home_post_card, parent, false))
}
FEATURE -> {
ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.home_post_card, parent, false))
}
NOT_SUPPORTED -> {
ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.empty_view, parent, false))
}
else -> {
ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.home_base_card, parent, false))
}
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val cell = cells[position]
when (cell.type) {
"reservations" -> bindHomeReservationsCell(holder, cell)
"dining" -> bindDiningCell(holder, cell)
"calendar" -> bindCalendarCell(holder, cell)
"news" -> bindNewsCell(holder, cell)
"laundry" -> bindLaundryCell(holder, cell)
"gsr_booking" -> bindGsrBookingCell(holder, cell)
"post" -> bindPostCell(holder, cell)
"feature" -> bindFeatureCell(holder, cell)
else -> Log.i("HomeAdapter", "Unsupported type of data at position $position")
}
}
override fun getItemCount(): Int {
return cells.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val view = itemView
}
override fun getItemViewType(position: Int): Int {
val cell = cells[position]
if (cell.info?.isTest == true) {
Log.i("HomeAdapter", "Test Portal post")
return NOT_SUPPORTED
}
return when (cell.type) {
"reservations" -> RESERVATIONS
"dining" -> DINING
"calendar" -> CALENDAR
"news" -> NEWS
"laundry" -> LAUNDRY
"gsr_booking" -> GSR_BOOKING
"post" -> POST
"feature" -> FEATURE
else -> NOT_SUPPORTED
}
}
private fun bindHomeReservationsCell(holder: ViewHolder, cell: HomeCell) {
val reservations = cell.reservations ?: ArrayList()
holder.itemView.home_card_title.text = "Upcoming Reservations"
holder.itemView.home_card_subtitle.text = "GSR RESERVATIONS"
holder.itemView.home_card_rv.layoutManager = LinearLayoutManager(mContext,
LinearLayoutManager.VERTICAL, false)
holder.itemView.home_card_rv.adapter = GsrReservationsAdapter(ArrayList(reservations))
}
@RequiresApi(Build.VERSION_CODES.O)
private fun bindDiningCell(holder: ViewHolder, cell: HomeCell) {
holder.itemView.home_card_title.text = "Favorites"
holder.itemView.home_card_subtitle.text = "DINING HALLS"
holder.itemView.dining_prefs_btn.visibility = View.VISIBLE
holder.itemView.dining_prefs_btn.setOnClickListener {
mActivity.fragmentTransact(DiningSettingsFragment(), false)
}
mStudentLife.venues()
.flatMap { venues -> Observable.from(venues) }
.flatMap { venue ->
val hall = DiningFragment.createHall(venue)
Observable.just(hall)
}
.toList()
.subscribe { diningHalls ->
mActivity.runOnUiThread {
val favorites: ArrayList<DiningHall> = arrayListOf()
val favoritesIdList: List<Int>? = cell.info?.venues
diningHalls.forEach {
if (favoritesIdList?.contains(it.id) == true) {
favorites.add(it)
}
}
getMenus(favorites)
holder.itemView.home_card_rv.layoutManager = LinearLayoutManager(mContext,
LinearLayoutManager.VERTICAL, false)
holder.itemView.home_card_rv.adapter = DiningCardAdapter(favorites)
}
}
}
private fun bindNewsCell(holder: ViewHolder, cell: HomeCell) {
val article = cell.info?.article
holder.itemView.home_news_title.text = article?.title
holder.itemView.home_news_subtitle.text = article?.subtitle
holder.itemView.home_news_timestamp.text = article?.timestamp?.trim()
Picasso.get()
.load(article?.imageUrl)
.fit()
.centerCrop()
.into(holder.itemView.home_news_iv)
/** Adds dynamically generated accent color from the fetched image to the news card */
var accentColor: Int = getColor(mContext, R.color.black)
GlobalScope.launch(Dispatchers.Default) {
val bitmap = Picasso.get().load(article?.imageUrl).get()
// Create palette from bitmap
fun createPaletteSync(bitmap: Bitmap): Palette = Palette.from(bitmap).generate()
val vibrantSwatch: Palette.Swatch? = createPaletteSync(bitmap).darkVibrantSwatch
vibrantSwatch?.rgb?.let { accentColor = it }
mActivity.runOnUiThread {
// Change all the components to match the accent color palette
vibrantSwatch?.titleTextColor?.let {
DrawableCompat.setTint(DrawableCompat.wrap(holder.itemView.news_card_logo.drawable),
ColorUtils.setAlphaComponent(it, 150))
DrawableCompat.setTint(DrawableCompat.wrap(holder.itemView.news_info_icon.drawable), it)
DrawableCompat.setTint(DrawableCompat.wrap(holder.itemView.dot_divider.drawable), it)
holder.itemView.button.setTextColor(ColorUtils.setAlphaComponent(it, 150))
DrawableCompat.setTint(DrawableCompat.wrap(holder.itemView.button.background), it)
holder.itemView.home_news_title.setTextColor(ColorUtils.setAlphaComponent(it, 150))
holder.itemView.home_news_subtitle.setTextColor(it)
holder.itemView.home_news_timestamp.setTextColor(it)
}
holder.itemView.news_card_container.background = BitmapDrawable(
holder.view.resources,
bitmap)
holder.itemView.blurView
.setOverlayColor(ColorUtils.setAlphaComponent(accentColor, 150))
}
}
/** Logic for the more info button on the news card */
holder.itemView.news_info_icon.setOnClickListener {
when (holder.itemView.home_news_subtitle.visibility) {
View.GONE -> {
holder.itemView.home_news_subtitle.visibility = View.VISIBLE
holder.itemView.home_news_title.setPadding(0, 0, 0, 0)
holder.itemView.blurView
.setOverlayColor(ColorUtils.setAlphaComponent(accentColor, 250))
}
View.VISIBLE -> {
holder.itemView.home_news_subtitle.visibility = View.GONE
holder.itemView.home_news_title.setPadding(0, 0, 0, convertToDp(mContext, 8f))
holder.itemView.blurView
.setOverlayColor(ColorUtils.setAlphaComponent(accentColor, 150))
}
}
}
/** Sets up blur view on news card */
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
holder.itemView.blurView.setupWith(holder.itemView.news_card_container)
.setFrameClearDrawable(ColorDrawable(getColor(mContext, R.color.white)))
.setBlurAlgorithm(RenderScriptBlur(mContext))
.setBlurRadius(25f)
.setHasFixedTransformationMatrix(true)
} else {
holder.itemView.blurView.setBackgroundColor(ColorUtils
.setAlphaComponent(getColor(mContext, R.color.black), 225))
}
holder.itemView.button.setOnClickListener {
val url = article?.articleUrl
val connection = NewsCustomTabsServiceConnection()
builder = CustomTabsIntent.Builder()
share = Intent(Intent.ACTION_SEND)
share?.type = "text/plain"
builder?.setToolbarColor(0x3E50B4)
builder?.setStartAnimations(
mContext,
R.anim.abc_popup_enter,
R.anim.abc_popup_exit)
CustomTabsClient.bindCustomTabsService(
mContext,
NewsFragment.CUSTOM_TAB_PACKAGE_NAME, connection)
if (mContext.isChromeCustomTabsSupported()) {
share?.putExtra(Intent.EXTRA_TEXT, url)
builder?.addMenuItem(
"Share", PendingIntent.getActivity(
mContext, 0,
share, PendingIntent.FLAG_CANCEL_CURRENT))
customTabsIntent = builder?.build()
customTabsIntent?.launchUrl(mActivity, Uri.parse(url))
} else {
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(mContext, browserIntent, null)
}
}
}
private fun bindCalendarCell(holder: ViewHolder, cell: HomeCell) {
val events = cell.events ?: ArrayList()
var i = events.size - 1
val eventList: ArrayList<CalendarEvent> = ArrayList()
while (i >= 0) {
if (!events[i].name.isNullOrEmpty()) {
eventList.add(events[i])
}
i--
}
eventList.reverse()
holder.itemView.home_card_title.text = "Upcoming Events"
holder.itemView.home_card_subtitle.text = "UNIVERSITY NOTIFICATIONS"
holder.itemView.home_card_rv.layoutManager = LinearLayoutManager(mContext,
LinearLayoutManager.VERTICAL, false)
holder.itemView.home_card_rv.adapter = UniversityEventAdapter(eventList)
}
private fun bindCoursesCell(holder: ViewHolder, cell: HomeCell) {
holder.itemView.home_card_title.text = "Today's schedule"
holder.itemView.home_card_subtitle.text = "COURSE SCHEDULE"
}
private fun bindLaundryCell(holder: ViewHolder, cell: HomeCell) {
val roomID = cell.info?.roomId ?: 0
holder.itemView.home_card_subtitle.text = "LAUNDRY"
holder.itemView.home_card_rv.layoutManager = LinearLayoutManager(mContext,
LinearLayoutManager.VERTICAL, false)
val params : ConstraintLayout.LayoutParams =
holder.itemView.home_card_rv.layoutParams as ConstraintLayout.LayoutParams
params.setMargins(0, 0, 0, 0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
params.marginStart = 0
}
holder.itemView.home_card_rv.layoutParams = params
mStudentLife.room(roomID).subscribe({ room ->
mActivity.runOnUiThread {
holder.itemView.home_card_title.text = room.name
val rooms = arrayListOf(room)
holder.itemView.home_card_rv.adapter = LaundryRoomAdapter(mContext, rooms, null, true)
}
}, { throwable -> mActivity.runOnUiThread { throwable.printStackTrace() } })
}
private fun bindGsrBookingCell(holder: ViewHolder, cell: HomeCell) {
val buildings = cell.buildings ?: ArrayList()
holder.itemView.home_card_title.text = "Book a GSR"
holder.itemView.home_card_subtitle.text = "GROUP STUDY ROOMS"
holder.itemView.home_card_rv.layoutManager = LinearLayoutManager(mContext,
LinearLayoutManager.VERTICAL, false)
holder.itemView.home_card_rv.adapter = HomeGsrBuildingAdapter(ArrayList(buildings))
}
private fun bindPostCell(holder: ViewHolder, cell: HomeCell) {
val info = cell.info
val post = cell.info?.post
holder.itemView.home_post_title.text = post?.title
holder.itemView.home_post_subtitle.text = post?.subtitle
holder.itemView.home_post_source.text = "Penn Labs" //post?.clubCode?.capitalize()
val time = post?.startDate?.substring(5, 7) + " / " +
post?.startDate?.substring(8, 10) + " - " +
post?.expireDate?.substring(5, 7) + " / " +
post?.expireDate?.substring(8, 10)
holder.itemView.home_post_timestamp.text = time
Picasso.get()
.load(post?.imageUrl)
.fit()
.centerCrop()
.into(holder.itemView.home_post_iv)
/** Adds dynamically generated accent color from the fetched image to the news card */
var accentColor: Int = getColor(mContext, R.color.black)
GlobalScope.launch(Dispatchers.Default) {
val bitmap = Picasso.get().load(post?.imageUrl).get()
// Create palette from bitmap
fun createPaletteSync(bitmap: Bitmap): Palette = Palette.from(bitmap).generate()
val vibrantSwatch: Palette.Swatch? = createPaletteSync(bitmap).darkVibrantSwatch
vibrantSwatch?.rgb?.let { accentColor = it }
mActivity.runOnUiThread {
// Change all the components to match the accent color palette
vibrantSwatch?.titleTextColor?.let {
holder.itemView.home_post_title.setTextColor(ColorUtils.setAlphaComponent(it, 150))
holder.itemView.home_post_subtitle.setTextColor(it)
holder.itemView.home_post_timestamp.setTextColor(it)
holder.itemView.home_post_source.setTextColor(it)
}
val bitmapDrawable = BitmapDrawable(
holder.view.resources,
bitmap)
holder.itemView.post_card_container.background = bitmapDrawable
holder.itemView.postBlurView
.setOverlayColor(ColorUtils.setAlphaComponent(accentColor, 150))
}
}
/** Sets up blur view on post card */
holder.itemView.postBlurView.setupWith(holder.itemView.post_card_container)
.setFrameClearDrawable(ColorDrawable(getColor(mContext, R.color.white)))
.setBlurAlgorithm(RenderScriptBlur(mContext))
.setBlurRadius(25f)
.setHasFixedTransformationMatrix(true)
/** Post clicking logic if there exists a URL **/
val url = post?.postUrl ?: return
holder.itemView.home_post_card.setOnClickListener {
val connection = NewsCustomTabsServiceConnection()
builder = CustomTabsIntent.Builder()
share = Intent(Intent.ACTION_SEND)
share?.type = "text/plain"
builder?.setToolbarColor(0x3E50B4)
builder?.setStartAnimations(mContext,
R.anim.abc_popup_enter,
R.anim.abc_popup_exit)
CustomTabsClient.bindCustomTabsService(mContext,
NewsFragment.CUSTOM_TAB_PACKAGE_NAME, connection)
if (mContext.isChromeCustomTabsSupported()) {
share?.putExtra(Intent.EXTRA_TEXT, url)
builder?.addMenuItem("Share", PendingIntent.getActivity(mContext, 0,
share, PendingIntent.FLAG_CANCEL_CURRENT))
customTabsIntent = builder?.build()
customTabsIntent?.launchUrl(mActivity, Uri.parse(url))
} else {
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(mContext, browserIntent, null)
}
}
}
// Returns an announcement for a Penn Mobile feature, such as Spring Fling
private fun bindFeatureCell(holder: ViewHolder, cell: HomeCell) {
val info = cell.info
holder.itemView.home_post_title?.text = info?.title
holder.itemView.home_post_subtitle?.text = info?.description
holder.itemView.home_post_source?.text = info?.source
holder.itemView.home_post_timestamp?.text = info?.timestamp
if (info?.imageUrl != null) {
Picasso.get().load(info.imageUrl).fit().centerCrop().into(holder.itemView.home_post_iv)
}
// For now, we only use Feature cards for Spring Fling so we show the Fling Fragment
holder.itemView.home_post_card.setOnClickListener {
mActivity.fragmentTransact(FlingFragment(), false)
}
}
// Chrome custom tabs to launch news site
internal inner class NewsCustomTabsServiceConnection : CustomTabsServiceConnection() {
override fun onCustomTabsServiceConnected(name: ComponentName, client: CustomTabsClient) {
mCustomTabsClient = client
mCustomTabsClient?.warmup(0)
session = mCustomTabsClient?.newSession(null)
}
override fun onServiceDisconnected(name: ComponentName) {
mCustomTabsClient = null
session = null
customTabsIntent = null
}
}
/** Checks if the chrome tab is supported on the current device. */
private fun Context.isChromeCustomTabsSupported(): Boolean {
val serviceIntent = Intent("android.support.customtabs.action.CustomTabsService")
serviceIntent.setPackage("com.android.chrome")
val resolveInfos = this.packageManager.queryIntentServices(serviceIntent, 0)
return resolveInfos.isNotEmpty()
}
} | mit | e7a1610d6cea745b6e79e8b68f4fd5b9 | 43.286022 | 108 | 0.635052 | 4.768874 | false | false | false | false |
exponent/exponent | packages/expo-image-picker/android/src/main/java/expo/modules/imagepicker/ImagePickerModule.kt | 2 | 16563 | package expo.modules.imagepicker
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import com.theartofdev.edmodo.cropper.CropImage
import expo.modules.core.ExportedModule
import expo.modules.core.ModuleRegistry
import expo.modules.core.ModuleRegistryDelegate
import expo.modules.core.Promise
import expo.modules.core.errors.ModuleDestroyedException
import expo.modules.core.interfaces.ActivityEventListener
import expo.modules.core.interfaces.ActivityProvider
import expo.modules.core.interfaces.ExpoMethod
import expo.modules.core.interfaces.LifecycleEventListener
import expo.modules.core.interfaces.services.UIManager
import expo.modules.core.utilities.FileUtilities.generateOutputPath
import expo.modules.core.utilities.ifNull
import expo.modules.imagepicker.ImagePickerOptions.Companion.optionsFromMap
import expo.modules.imagepicker.exporters.CompressionImageExporter
import expo.modules.imagepicker.exporters.CropImageExporter
import expo.modules.imagepicker.exporters.ImageExporter
import expo.modules.imagepicker.exporters.RawImageExporter
import expo.modules.imagepicker.fileproviders.CacheFileProvider
import expo.modules.imagepicker.fileproviders.CropFileProvider
import expo.modules.imagepicker.tasks.ImageResultTask
import expo.modules.imagepicker.tasks.VideoResultTask
import expo.modules.interfaces.imageloader.ImageLoaderInterface
import expo.modules.interfaces.permissions.Permissions
import expo.modules.interfaces.permissions.PermissionsResponse
import expo.modules.interfaces.permissions.PermissionsResponseListener
import expo.modules.interfaces.permissions.PermissionsStatus
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import java.io.IOException
import java.lang.ref.WeakReference
class ImagePickerModule(
private val mContext: Context,
private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate(),
private val pickerResultStore: PickerResultsStore = PickerResultsStore(mContext)
) : ExportedModule(mContext), ActivityEventListener, LifecycleEventListener {
private var mCameraCaptureURI: Uri? = null
private var mPromise: Promise? = null
private var mPickerOptions: ImagePickerOptions? = null
private val moduleCoroutineScope = CoroutineScope(Dispatchers.IO)
private var exifDataHandler: ExifDataHandler? = null
override fun onDestroy() {
try {
mUIManager.unregisterLifecycleEventListener(this)
moduleCoroutineScope.cancel(ModuleDestroyedException(ImagePickerConstants.PROMISES_CANCELED))
} catch (e: IllegalStateException) {
Log.e(ImagePickerConstants.TAG, "The scope does not have a job in it")
}
}
/**
* Android system sometimes kills the `MainActivity` after the `ImagePicker` finishes.
* Moreover, the react context will be reloaded again in such a case. We need to handle this situation.
* To do it we track if the current activity was destroyed.
*/
private var mWasHostDestroyed = false
private val mImageLoader: ImageLoaderInterface by moduleRegistry()
private val mUIManager: UIManager by moduleRegistry()
private val mPermissions: Permissions by moduleRegistry()
private val mActivityProvider: ActivityProvider by moduleRegistry()
private lateinit var _experienceActivity: WeakReference<Activity>
private val experienceActivity: Activity?
get() {
if (!this::_experienceActivity.isInitialized) {
_experienceActivity = WeakReference(mActivityProvider.currentActivity)
}
return _experienceActivity.get()
}
private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>()
override fun onCreate(moduleRegistry: ModuleRegistry) {
moduleRegistryDelegate.onCreate(moduleRegistry)
mUIManager.registerLifecycleEventListener(this)
}
override fun getName() = "ExponentImagePicker"
//region expo methods
@ExpoMethod
fun requestMediaLibraryPermissionsAsync(writeOnly: Boolean, promise: Promise) {
Permissions.askForPermissionsWithPermissionsManager(mPermissions, promise, *getMediaLibraryPermissions(writeOnly))
}
@ExpoMethod
fun getMediaLibraryPermissionsAsync(writeOnly: Boolean, promise: Promise) {
Permissions.getPermissionsWithPermissionsManager(mPermissions, promise, *getMediaLibraryPermissions(writeOnly))
}
@ExpoMethod
fun requestCameraPermissionsAsync(promise: Promise) {
Permissions.askForPermissionsWithPermissionsManager(mPermissions, promise, Manifest.permission.CAMERA)
}
@ExpoMethod
fun getCameraPermissionsAsync(promise: Promise) {
Permissions.getPermissionsWithPermissionsManager(mPermissions, promise, Manifest.permission.CAMERA)
}
@ExpoMethod
fun getPendingResultAsync(promise: Promise) {
promise.resolve(pickerResultStore.getAllPendingResults())
}
// NOTE: Currently not reentrant / doesn't support concurrent requests
@ExpoMethod
fun launchCameraAsync(options: Map<String, Any?>, promise: Promise) {
val pickerOptions = optionsFromMap(options, promise) ?: return
val activity = experienceActivity.ifNull {
promise.reject(ImagePickerConstants.ERR_MISSING_ACTIVITY, ImagePickerConstants.MISSING_ACTIVITY_MESSAGE)
return
}
val intentType = if (pickerOptions.mediaTypes == MediaTypes.VIDEOS) MediaStore.ACTION_VIDEO_CAPTURE else MediaStore.ACTION_IMAGE_CAPTURE
val cameraIntent = Intent(intentType)
cameraIntent.resolveActivity(activity.application.packageManager).ifNull {
promise.reject(IllegalStateException("Error resolving activity"))
return
}
val permissionsResponseHandler = PermissionsResponseListener { permissionsResponse: Map<String, PermissionsResponse> ->
if (permissionsResponse[Manifest.permission.WRITE_EXTERNAL_STORAGE]?.status == PermissionsStatus.GRANTED &&
permissionsResponse[Manifest.permission.CAMERA]?.status == PermissionsStatus.GRANTED
) {
launchCameraWithPermissionsGranted(promise, cameraIntent, pickerOptions)
} else {
promise.reject(SecurityException("User rejected permissions"))
}
}
mPermissions.askForPermissions(permissionsResponseHandler, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
}
// NOTE: Currently not reentrant / doesn't support concurrent requests
@ExpoMethod
fun launchImageLibraryAsync(options: Map<String, Any?>, promise: Promise) {
val pickerOptions = optionsFromMap(options, promise) ?: return
val libraryIntent = Intent().apply {
when (pickerOptions.mediaTypes) {
MediaTypes.IMAGES -> type = "image/*"
MediaTypes.VIDEOS -> type = "video/*"
MediaTypes.ALL -> {
type = "*/*"
putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("image/*", "video/*"))
}
}
action = Intent.ACTION_GET_CONTENT
}
startActivityOnResult(libraryIntent, ImagePickerConstants.REQUEST_LAUNCH_IMAGE_LIBRARY, promise, pickerOptions)
}
//endregion
//region helpers
private fun getMediaLibraryPermissions(writeOnly: Boolean): Array<String> {
return if (writeOnly) {
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)
} else {
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
}
}
private fun launchCameraWithPermissionsGranted(promise: Promise, cameraIntent: Intent, pickerOptions: ImagePickerOptions) {
val imageFile = createOutputFile(
mContext.cacheDir,
if (pickerOptions.mediaTypes == MediaTypes.VIDEOS) ".mp4" else ".jpg"
).ifNull {
promise.reject(IOException("Could not create image file."))
return
}
mCameraCaptureURI = uriFromFile(imageFile)
val activity = experienceActivity.ifNull {
promise.reject(ImagePickerConstants.ERR_MISSING_ACTIVITY, ImagePickerConstants.MISSING_ACTIVITY_MESSAGE)
return
}
mPromise = promise
mPickerOptions = pickerOptions
if (pickerOptions.videoMaxDuration > 0) {
cameraIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, pickerOptions.videoMaxDuration)
}
// camera intent needs a content URI but we need a file one
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, contentUriFromFile(imageFile, activity.application))
startActivityOnResult(cameraIntent, ImagePickerConstants.REQUEST_LAUNCH_CAMERA, promise, pickerOptions)
}
/**
* Starts the crop intent.
*
* @param promise Promise which will be rejected if something goes wrong
* @param uri Uri to file which will be cropped
* @param type Media type of source file
* @param needGenerateFile Tells if generating a new file is needed
* @param pickerOptions Additional options
*/
private fun startCropIntent(promise: Promise, uri: Uri, type: String, needGenerateFile: Boolean, pickerOptions: ImagePickerOptions) {
var extension = ".jpg"
var compressFormat = Bitmap.CompressFormat.JPEG
// if the image is created by camera intent we don't need a new path - it's been already saved
when {
type.contains("png") -> {
compressFormat = Bitmap.CompressFormat.PNG
extension = ".png"
}
type.contains("gif") -> {
// If we allow editing, the result image won't ever be a GIF as the cropper doesn't support it.
// Let's convert to PNG in such case.
extension = ".png"
compressFormat = Bitmap.CompressFormat.PNG
}
type.contains("bmp") -> {
// If we allow editing, the result image won't ever be a BMP as the cropper doesn't support it.
// Let's convert to PNG in such case.
extension = ".png"
compressFormat = Bitmap.CompressFormat.PNG
}
!type.contains("jpeg") -> {
Log.w(ImagePickerConstants.TAG, "Image type not supported. Falling back to JPEG instead.")
extension = ".jpg"
}
}
val fileUri: Uri = try {
if (needGenerateFile) {
uriFromFilePath(generateOutputPath(mContext.cacheDir, ImagePickerConstants.CACHE_DIR_NAME, extension))
} else {
uri
}
} catch (e: IOException) {
promise.reject(ImagePickerConstants.ERR_CAN_NOT_OPEN_CROP, ImagePickerConstants.CAN_NOT_OPEN_CROP_MESSAGE, e)
return
}
val cropImageBuilder = CropImage.activity(uri).apply {
pickerOptions.forceAspect?.let { (x, y) ->
setAspectRatio((x as Number).toInt(), (y as Number).toInt())
setFixAspectRatio(true)
setInitialCropWindowPaddingRatio(0f)
}
setOutputUri(fileUri)
setOutputCompressFormat(compressFormat)
setOutputCompressQuality(pickerOptions.quality)
}
exifDataHandler = ExifDataHandler(uri)
startActivityOnResult(cropImageBuilder.getIntent(context), CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE, promise, pickerOptions)
}
//endregion
// region ActivityEventListener
override fun onNewIntent(intent: Intent) = Unit
override fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) {
if (shouldHandleOnActivityResult(activity, requestCode)) {
mUIManager.unregisterActivityEventListener(this)
var pickerOptions = mPickerOptions!!
val promise = if (mWasHostDestroyed && mPromise !is PendingPromise) {
if (pickerOptions.isBase64) {
// we know that the activity was killed and we don't want to store
// base64 into `SharedPreferences`...
pickerOptions = ImagePickerOptions(
pickerOptions.quality,
pickerOptions.isAllowsEditing,
pickerOptions.forceAspect,
false,
pickerOptions.mediaTypes,
pickerOptions.isExif,
pickerOptions.videoMaxDuration
)
// ...but we need to remember to add it later.
PendingPromise(pickerResultStore, isBase64 = true)
} else {
PendingPromise(pickerResultStore)
}
} else {
mPromise!!
}
mPromise = null
mPickerOptions = null
handleOnActivityResult(promise, activity, requestCode, resultCode, data, pickerOptions)
}
}
//endregion
//region activity for result
private fun startActivityOnResult(intent: Intent, requestCode: Int, promise: Promise, pickerOptions: ImagePickerOptions) {
experienceActivity
.ifNull {
promise.reject(ImagePickerConstants.ERR_MISSING_ACTIVITY, ImagePickerConstants.MISSING_ACTIVITY_MESSAGE)
return
}
.also {
mUIManager.registerActivityEventListener(this)
mPromise = promise
mPickerOptions = pickerOptions
}
.startActivityForResult(intent, requestCode)
}
private fun shouldHandleOnActivityResult(activity: Activity, requestCode: Int): Boolean {
return experienceActivity != null &&
mPromise != null &&
mPickerOptions != null &&
// When we launched the crop tool and the android kills current activity, the references can be different.
// So, we fallback to the requestCode in this case.
(activity === experienceActivity || mWasHostDestroyed && requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
}
private fun handleOnActivityResult(promise: Promise, activity: Activity, requestCode: Int, resultCode: Int, intent: Intent?, pickerOptions: ImagePickerOptions) {
if (resultCode != Activity.RESULT_OK) {
promise.resolve(
Bundle().apply {
putBoolean("cancelled", true)
}
)
return
}
val contentResolver = activity.application.contentResolver
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
val result = CropImage.getActivityResult(intent)
val exporter = CropImageExporter(result.rotation, result.cropRect, pickerOptions.isBase64)
ImageResultTask(
promise,
result.uri,
contentResolver,
CropFileProvider(result.uri),
pickerOptions.isAllowsEditing,
pickerOptions.isExif,
exporter,
exifDataHandler,
moduleCoroutineScope
).execute()
return
}
val uri = (if (requestCode == ImagePickerConstants.REQUEST_LAUNCH_CAMERA) mCameraCaptureURI else intent?.data)
.ifNull {
promise.reject(ImagePickerConstants.ERR_MISSING_URL, ImagePickerConstants.MISSING_URL_MESSAGE)
return
}
val type = getType(contentResolver, uri).ifNull {
promise.reject(ImagePickerConstants.ERR_CAN_NOT_DEDUCE_TYPE, ImagePickerConstants.CAN_NOT_DEDUCE_TYPE_MESSAGE)
return
}
if (type.contains("image")) {
if (pickerOptions.isAllowsEditing) {
// if the image is created by camera intent we don't need a new file - it's been already saved
val needGenerateFile = requestCode != ImagePickerConstants.REQUEST_LAUNCH_CAMERA
startCropIntent(promise, uri, type, needGenerateFile, pickerOptions)
return
}
val exporter: ImageExporter = if (pickerOptions.quality == ImagePickerConstants.DEFAULT_QUALITY) {
RawImageExporter(contentResolver, pickerOptions.isBase64)
} else {
CompressionImageExporter(mImageLoader, pickerOptions.quality, pickerOptions.isBase64)
}
ImageResultTask(
promise,
uri,
contentResolver,
CacheFileProvider(mContext.cacheDir, deduceExtension(type)),
pickerOptions.isAllowsEditing,
pickerOptions.isExif,
exporter,
exifDataHandler,
moduleCoroutineScope
).execute()
return
}
try {
val metadataRetriever = MediaMetadataRetriever().apply {
setDataSource(mContext, uri)
}
VideoResultTask(promise, uri, contentResolver, CacheFileProvider(mContext.cacheDir, ".mp4"), metadataRetriever, moduleCoroutineScope).execute()
} catch (e: RuntimeException) {
e.printStackTrace()
promise.reject(ImagePickerConstants.ERR_CAN_NOT_EXTRACT_METADATA, ImagePickerConstants.CAN_NOT_EXTRACT_METADATA_MESSAGE, e)
return
}
}
//endregion
//region LifecycleEventListener
override fun onHostDestroy() {
mWasHostDestroyed = true
}
override fun onHostResume() {
if (mWasHostDestroyed) {
_experienceActivity = WeakReference(mActivityProvider.currentActivity)
mWasHostDestroyed = false
}
}
override fun onHostPause() = Unit
//endregion
}
| bsd-3-clause | 993641171f88c896ef87acec139176ce | 36.388262 | 163 | 0.732114 | 4.83168 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/helpers/SoundManager.kt | 1 | 2564 | package com.habitrpg.android.habitica.helpers
import com.habitrpg.android.habitica.HabiticaBaseApplication
import io.reactivex.rxjava3.schedulers.Schedulers
import javax.inject.Inject
class SoundManager {
@Inject
lateinit var soundFileLoader: SoundFileLoader
var soundTheme: String = SoundThemeOff
private val loadedSoundFiles: MutableMap<String, SoundFile> = HashMap()
init {
HabiticaBaseApplication.userComponent?.inject(this)
}
fun preloadAllFiles() {
loadedSoundFiles.clear()
if (soundTheme == SoundThemeOff) {
return
}
val soundFiles = ArrayList<SoundFile>()
soundFiles.add(SoundFile(soundTheme, SoundAchievementUnlocked))
soundFiles.add(SoundFile(soundTheme, SoundChat))
soundFiles.add(SoundFile(soundTheme, SoundDaily))
soundFiles.add(SoundFile(soundTheme, SoundDeath))
soundFiles.add(SoundFile(soundTheme, SoundItemDrop))
soundFiles.add(SoundFile(soundTheme, SoundLevelUp))
soundFiles.add(SoundFile(soundTheme, SoundMinusHabit))
soundFiles.add(SoundFile(soundTheme, SoundPlusHabit))
soundFiles.add(SoundFile(soundTheme, SoundReward))
soundFiles.add(SoundFile(soundTheme, SoundTodo))
soundFileLoader.download(soundFiles)
.subscribe({}, RxErrorHandler.handleEmptyError())
}
fun loadAndPlayAudio(type: String) {
if (soundTheme == SoundThemeOff) {
return
}
if (loadedSoundFiles.containsKey(type)) {
loadedSoundFiles[type]?.play()
} else {
val soundFiles = ArrayList<SoundFile>()
soundFiles.add(SoundFile(soundTheme, type))
soundFileLoader.download(soundFiles).observeOn(Schedulers.newThread()).subscribe(
{
val file = soundFiles[0]
loadedSoundFiles[type] = file
file.play()
},
RxErrorHandler.handleEmptyError()
)
}
}
companion object {
const val SoundAchievementUnlocked = "Achievement_Unlocked"
const val SoundChat = "Chat"
const val SoundDaily = "Daily"
const val SoundDeath = "Death"
const val SoundItemDrop = "Item_Drop"
const val SoundLevelUp = "Level_Up"
const val SoundMinusHabit = "Minus_Habit"
const val SoundPlusHabit = "Plus_Habit"
const val SoundReward = "Reward"
const val SoundTodo = "Todo"
const val SoundThemeOff = "off"
}
}
| gpl-3.0 | 487a781de496c25d62878e427a1a7126 | 33.186667 | 93 | 0.642356 | 4.661818 | false | false | false | false |
jorjoluiso/QuijoteLui | src/main/kotlin/com/quijotelui/electronico/comprobantes/nota/credito/Detalle.kt | 1 | 952 | package com.quijotelui.electronico.comprobantes.nota.credito
import java.math.BigDecimal
import javax.xml.bind.annotation.XmlElement
import javax.xml.bind.annotation.XmlRootElement
import javax.xml.bind.annotation.XmlType
@XmlRootElement
@XmlType(propOrder = arrayOf(
"codigoInterno",
"descripcion",
"cantidad",
"precioUnitario",
"descuento",
"precioTotalSinImpuesto",
"impuestos"))
class Detalle (
@XmlElement var codigoInterno: String? = null,
@XmlElement var descripcion: String? = null,
@XmlElement var cantidad: BigDecimal? = null,
@XmlElement var precioUnitario: BigDecimal? = null,
@XmlElement var descuento: BigDecimal? = null,
@XmlElement var precioTotalSinImpuesto: BigDecimal? = null
)
{
@XmlElement
private var impuestos = Impuestos()
fun setImpuestos(impuestos : Impuestos) {
this.impuestos = impuestos
}
} | gpl-3.0 | 868a1c6a51f370ee00f14f25cecca8cf | 27.029412 | 66 | 0.684874 | 3.823293 | false | false | false | false |
androidx/androidx | tv/tv-foundation/src/main/java/androidx/tv/foundation/ScrollableWithPivot.kt | 3 | 14722 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.tv.foundation
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.Orientation.Horizontal
import androidx.compose.foundation.gestures.Orientation.Vertical
import androidx.compose.foundation.gestures.ScrollableState
import androidx.compose.foundation.gestures.animateScrollBy
import androidx.compose.foundation.onFocusedBoundsChanged
import androidx.compose.foundation.relocation.BringIntoViewResponder
import androidx.compose.foundation.relocation.bringIntoViewResponder
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollDispatcher
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.input.pointer.PointerEvent
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.OnPlacedModifier
import androidx.compose.ui.layout.OnRemeasuredModifier
import androidx.compose.ui.modifier.ModifierLocalProvider
import androidx.compose.ui.modifier.modifierLocalOf
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.toSize
import androidx.compose.ui.util.fastForEach
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
/* Copied from
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/gestures/
Scrollable.kt and modified */
/**
* Configure touch scrolling and flinging for the UI element in a single [Orientation].
*
* Users should update their state themselves using default [ScrollableState] and its
* `consumeScrollDelta` callback or by implementing [ScrollableState] interface manually and reflect
* their own state in UI when using this component.
*
* @param state [ScrollableState] state of the scrollable. Defines how scroll events will be
* interpreted by the user land logic and contains useful information about on-going events.
* @param orientation orientation of the scrolling
* @param pivotOffsets offsets of child element within the parent and starting edge of the child
* from the pivot defined by the parentOffset.
* @param enabled whether or not scrolling in enabled
* @param reverseDirection reverse the direction of the scroll, so top to bottom scroll will
* behave like bottom to top and left to right will behave like right to left.
* drag events when this scrollable is being dragged.
*/
@OptIn(ExperimentalFoundationApi::class)
@ExperimentalTvFoundationApi
fun Modifier.scrollableWithPivot(
state: ScrollableState,
orientation: Orientation,
pivotOffsets: PivotOffsets,
enabled: Boolean = true,
reverseDirection: Boolean = false
): Modifier = composed(
inspectorInfo = debugInspectorInfo {
name = "scrollableWithPivot"
properties["orientation"] = orientation
properties["state"] = state
properties["enabled"] = enabled
properties["reverseDirection"] = reverseDirection
properties["pivotOffsets"] = pivotOffsets
},
factory = {
val coroutineScope = rememberCoroutineScope()
val keepFocusedChildInViewModifier =
remember(coroutineScope, orientation, state, reverseDirection) {
ContentInViewModifier(
coroutineScope, orientation, state, reverseDirection, pivotOffsets)
}
Modifier
.focusGroup()
.then(keepFocusedChildInViewModifier.modifier)
.pointerScrollable(
orientation,
reverseDirection,
state,
enabled
)
.then(if (enabled) ModifierLocalScrollableContainerProvider else Modifier)
}
)
internal interface ScrollConfig {
fun Density.calculateMouseWheelScroll(event: PointerEvent, bounds: IntSize): Offset
}
@Composable
internal fun platformScrollConfig(): ScrollConfig = AndroidConfig
private object AndroidConfig : ScrollConfig {
override fun Density.calculateMouseWheelScroll(event: PointerEvent, bounds: IntSize): Offset {
// 64 dp value is taken from ViewConfiguration.java, replace with better solution
return event.changes.fastFold(Offset.Zero) { acc, c -> acc + c.scrollDelta } * -64.dp.toPx()
}
}
@Suppress("ComposableModifierFactory")
@Composable
private fun Modifier.pointerScrollable(
orientation: Orientation,
reverseDirection: Boolean,
controller: ScrollableState,
enabled: Boolean
): Modifier {
val nestedScrollDispatcher = remember { mutableStateOf(NestedScrollDispatcher()) }
val scrollLogic = rememberUpdatedState(
ScrollingLogic(
orientation,
reverseDirection,
controller
)
)
val nestedScrollConnection = remember(enabled) {
scrollableNestedScrollConnection(scrollLogic, enabled)
}
return this.nestedScroll(nestedScrollConnection, nestedScrollDispatcher.value)
}
private class ScrollingLogic(
val orientation: Orientation,
val reverseDirection: Boolean,
val scrollableState: ScrollableState,
) {
private fun Float.toOffset(): Offset = when {
this == 0f -> Offset.Zero
orientation == Horizontal -> Offset(this, 0f)
else -> Offset(0f, this)
}
private fun Offset.toFloat(): Float =
if (orientation == Horizontal) this.x else this.y
private fun Float.reverseIfNeeded(): Float = if (reverseDirection) this * -1 else this
fun performRawScroll(scroll: Offset): Offset {
return if (scrollableState.isScrollInProgress) {
Offset.Zero
} else {
scrollableState.dispatchRawDelta(scroll.toFloat().reverseIfNeeded())
.reverseIfNeeded().toOffset()
}
}
}
private fun scrollableNestedScrollConnection(
scrollLogic: State<ScrollingLogic>,
enabled: Boolean
): NestedScrollConnection = object : NestedScrollConnection {
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset = if (enabled) {
scrollLogic.value.performRawScroll(available)
} else {
Offset.Zero
}
}
/**
* Handles any logic related to bringing or keeping content in view, including
* [BringIntoViewResponder] and ensuring the focused child stays in view when the scrollable area
* is shrunk.
*/
@OptIn(ExperimentalFoundationApi::class)
private class ContentInViewModifier(
private val scope: CoroutineScope,
private val orientation: Orientation,
private val scrollableState: ScrollableState,
private val reverseDirection: Boolean,
private val pivotOffsets: PivotOffsets
) : BringIntoViewResponder, OnRemeasuredModifier, OnPlacedModifier {
private var focusedChild: LayoutCoordinates? = null
private var coordinates: LayoutCoordinates? = null
private var oldSize: IntSize? = null
val modifier: Modifier = this
.onFocusedBoundsChanged { focusedChild = it }
.bringIntoViewResponder(this)
override fun onRemeasured(size: IntSize) {
val coordinates = coordinates
val oldSize = oldSize
// We only care when this node becomes smaller than it previously was, so don't care about
// the initial measurement.
if (oldSize != null && oldSize != size && coordinates?.isAttached == true) {
onSizeChanged(coordinates, oldSize)
}
this.oldSize = size
}
override fun onPlaced(coordinates: LayoutCoordinates) {
this.coordinates = coordinates
}
override fun calculateRectForParent(localRect: Rect): Rect {
val oldSize = checkNotNull(oldSize) {
"Expected BringIntoViewRequester to not be used before parents are placed."
}
// oldSize will only be null before the initial measurement.
return computeDestination(localRect, oldSize, pivotOffsets)
}
override suspend fun bringChildIntoView(localRect: () -> Rect?) {
// TODO(b/241591211) Read the request's bounds lazily in case they change.
@Suppress("NAME_SHADOWING")
val localRect = localRect() ?: return
performBringIntoView(localRect, calculateRectForParent(localRect))
}
private fun onSizeChanged(coordinates: LayoutCoordinates, oldSize: IntSize) {
val containerShrunk = if (orientation == Horizontal) {
coordinates.size.width < oldSize.width
} else {
coordinates.size.height < oldSize.height
}
// If the container is growing, then if the focused child is only partially visible it will
// soon be _more_ visible, so don't scroll.
if (!containerShrunk) return
val focusedBounds = focusedChild
?.let { coordinates.localBoundingBoxOf(it, clipBounds = false) }
?: return
val myOldBounds = Rect(Offset.Zero, oldSize.toSize())
val adjustedBounds = computeDestination(focusedBounds, coordinates.size, pivotOffsets)
val wasVisible = myOldBounds.overlaps(focusedBounds)
val isFocusedChildClipped = adjustedBounds != focusedBounds
if (wasVisible && isFocusedChildClipped) {
scope.launch {
performBringIntoView(focusedBounds, adjustedBounds)
}
}
}
/**
* Compute the destination given the source rectangle and current bounds.
*
* @param source The bounding box of the item that sent the request to be brought into view.
* @param pivotOffsets offsets of child element within the parent and starting edge of the child
* from the pivot defined by the parentOffset.
* @return the destination rectangle.
*/
private fun computeDestination(
source: Rect,
intSize: IntSize,
pivotOffsets: PivotOffsets
): Rect {
val size = intSize.toSize()
return when (orientation) {
Vertical ->
source.translate(
0f,
relocationDistance(source.top, source.bottom, size.height, pivotOffsets))
Horizontal ->
source.translate(
relocationDistance(source.left, source.right, size.width, pivotOffsets),
0f)
}
}
/**
* Using the source and destination bounds, perform an animated scroll.
*/
private suspend fun performBringIntoView(source: Rect, destination: Rect) {
val offset = when (orientation) {
Vertical -> source.top - destination.top
Horizontal -> source.left - destination.left
}
val scrollDelta = if (reverseDirection) -offset else offset
// Note that this results in weird behavior if called before the previous
// performBringIntoView finishes due to b/220119990.
scrollableState.animateScrollBy(scrollDelta)
}
/**
* Calculate the offset needed to bring one of the edges into view. The leadingEdge is the side
* closest to the origin (For the x-axis this is 'left', for the y-axis this is 'top').
* The trailing edge is the other side (For the x-axis this is 'right', for the y-axis this is
* 'bottom').
*/
private fun relocationDistance(
leadingEdgeOfItemRequestingFocus: Float,
trailingEdgeOfItemRequestingFocus: Float,
parentSize: Float,
pivotOffsets: PivotOffsets
): Float {
val totalWidthOfItemRequestingFocus =
trailingEdgeOfItemRequestingFocus - leadingEdgeOfItemRequestingFocus
val pivotOfItemRequestingFocus =
pivotOffsets.childFraction * totalWidthOfItemRequestingFocus
val intendedLocationOfItemRequestingFocus = parentSize * pivotOffsets.parentFraction
return leadingEdgeOfItemRequestingFocus - intendedLocationOfItemRequestingFocus +
pivotOfItemRequestingFocus
}
}
// TODO: b/203141462 - make this public and move it to ui
/**
* Whether this modifier is inside a scrollable container, provided by
* [Modifier.scrollableWithPivot]. Defaults to false.
*/
internal val ModifierLocalScrollableContainer = modifierLocalOf { false }
private object ModifierLocalScrollableContainerProvider : ModifierLocalProvider<Boolean> {
override val key = ModifierLocalScrollableContainer
override val value = true
}
/**
* Accumulates value starting with [initial] value and applying [operation] from left to right
* to current accumulator value and each element.
*
* Returns the specified [initial] value if the collection is empty.
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*
* @param [operation] function that takes current accumulator value and an element, and calculates the next accumulator value.
*/
@Suppress("BanInlineOptIn") // Treat Kotlin Contracts as non-experimental.
@OptIn(ExperimentalContracts::class)
internal inline fun <T, R> List<T>.fastFold(initial: R, operation: (acc: R, T) -> R): R {
contract { callsInPlace(operation) }
var accumulator = initial
fastForEach { e ->
accumulator = operation(accumulator, e)
}
return accumulator
} | apache-2.0 | 1df6bb740aba555338b21a37f80dad77 | 38.791892 | 126 | 0.719128 | 4.948571 | false | false | false | false |
mikrobi/TransitTracker_android | app/src/main/java/de/jakobclass/transittracker/MapActivity.kt | 1 | 8890 | package de.jakobclass.transittracker
import android.Manifest
import android.animation.ObjectAnimator
import android.app.AlertDialog
import android.content.pm.PackageManager
import android.graphics.Point
import android.location.Location
import android.support.v4.app.FragmentActivity
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.util.Property
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.*
import de.jakobclass.transittracker.animation.LatLngTypeEvaluator
import de.jakobclass.transittracker.models.Stop
import de.jakobclass.transittracker.factories.BitmapFactory
import de.jakobclass.transittracker.models.Vehicle
import de.jakobclass.transittracker.models.VehicleDelegate
import de.jakobclass.transittracker.services.ApiService
import de.jakobclass.transittracker.services.ApiServiceDelegate
import de.jakobclass.transittracker.utilities.BiMap
class MapActivity : FragmentActivity(), OnMapReadyCallback, ConnectionCallbacks,
OnCameraChangeListener, GoogleMap.OnMarkerClickListener, GoogleMap.OnMapClickListener,
ApiServiceDelegate, VehicleDelegate {
private val apiService: ApiService
get() = (application as Application).apiService
private var googleApiClient: GoogleApiClient? = null
private var highlightedRoute: Polyline? = null
private var map: GoogleMap? = null
private lateinit var mapFragment: SupportMapFragment
private val vehicleMarkers = BiMap<Vehicle, Marker>()
private val REQUEST_CODE_ACCESS_FINE_LOCATION = 1
private val REQUIRED_LOCATION_PERMISSION = Manifest.permission.ACCESS_FINE_LOCATION
private val screenDensity: Float
get() = resources.displayMetrics.density
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map)
mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
apiService.delegate = this
}
override fun onStop() {
googleApiClient?.disconnect()
super.onStop()
}
override fun onMapReady(googleMap: GoogleMap) {
map = googleMap
map!!.setOnCameraChangeListener(this)
map!!.setOnMarkerClickListener(this)
map!!.setOnMapClickListener(this)
addMarkersForStops(apiService.stops)
val berlinCityCenter = LatLng(52.520048, 13.404773)
map!!.moveCamera(CameraUpdateFactory.newLatLngZoom(berlinCityCenter, 16.0f))
initLocationPermission()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (requestCode == REQUEST_CODE_ACCESS_FINE_LOCATION && permissions.isNotEmpty()
&& permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
enableMyLocation()
}
}
private fun initLocationPermission() {
if (ContextCompat.checkSelfPermission(this, REQUIRED_LOCATION_PERMISSION)
== PackageManager.PERMISSION_GRANTED) {
enableMyLocation()
} else if (ActivityCompat.shouldShowRequestPermissionRationale(this, REQUIRED_LOCATION_PERMISSION)) {
AlertDialog.Builder(this).setMessage(R.string.location_usage_description)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ok) { dialog, index -> requestLocationPermission() }
.show()
} else {
requestLocationPermission()
}
}
private fun requestLocationPermission() {
ActivityCompat.requestPermissions(this, arrayOf(REQUIRED_LOCATION_PERMISSION), REQUEST_CODE_ACCESS_FINE_LOCATION)
}
private fun enableMyLocation() {
map?.isMyLocationEnabled = true
if (googleApiClient == null) {
googleApiClient = GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.build()
}
googleApiClient?.connect()
}
override fun onConnected(connectionHint: Bundle?) {
val lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient)
lastLocation?.let {
if (lastLocation.isInBerlinArea) {
val lastLocationLatLng = LatLng(lastLocation.latitude, lastLocation.longitude)
map?.animateCamera(CameraUpdateFactory.newLatLng(lastLocationLatLng))
}
}
}
override fun onConnectionSuspended(cause: Int) {
// Nothing to do
}
override fun onCameraChange(cameraPosition: CameraPosition?) {
updateBoundingBox()
}
private fun updateBoundingBox() {
var mapView = mapFragment.view
mapView?.let {
val mapWidth = mapView.width.toInt()
val mapHeight = mapView.height.toInt()
val mapX = mapView.x.toInt()
val mapY = mapView.y.toInt()
val northEastPoint = Point(mapX + 2 * mapWidth, mapY - mapHeight)
val southWestPoint = Point(mapX - mapWidth, mapY + 2 * mapHeight)
val northEast = map!!.projection.fromScreenLocation(northEastPoint)
val southWest = map!!.projection.fromScreenLocation(southWestPoint)
apiService.boundingBox = LatLngBounds(southWest, northEast)
}
}
override fun apiServiceDidAddStops(stops: List<Stop>) {
addMarkersForStops(stops)
}
private fun addMarkersForStops(stops: Collection<Stop>) {
for (stop in stops) {
val bitmap = BitmapFactory.bitmapForStop(stop, screenDensity)
val icon = BitmapDescriptorFactory.fromBitmap(bitmap)
map?.addMarker(MarkerOptions()
.position(stop.coordinate)
.title(stop.name)
.snippet(stop.lines.joinToString(", "))
.icon(icon))
}
}
override fun apiServiceDidAddVehicles(vehicles: Collection<Vehicle>) {
for (vehicle in vehicles) {
vehicle.delegate = this
val bitmap = BitmapFactory.bitmapForVehicle(vehicle, screenDensity)
val icon = BitmapDescriptorFactory.fromBitmap(bitmap)
map?.addMarker(MarkerOptions()
.position(vehicle.position.coordinate)
.title(vehicle.name)
.snippet(vehicle.destination)
.icon(icon)
.anchor(0.5f, 0.5f))
?.let { vehicleMarkers[vehicle] = it }
}
}
override fun apiServiceDidRemoveVehicles(vehicles: Collection<Vehicle>) {
for (vehicle in vehicles) {
vehicleMarkers.remove(vehicle)?.remove()
}
}
override fun onVehiclePositionUpdate(vehicle: Vehicle) {
vehicleMarkers[vehicle]?.let {
val bitmap = BitmapFactory.bitmapForVehicle(vehicle, screenDensity)
val icon = BitmapDescriptorFactory.fromBitmap(bitmap)
it.setIcon(icon)
val property = Property.of(Marker::class.java, LatLng::class.java, "position");
val animator = ObjectAnimator.ofObject(it, property, LatLngTypeEvaluator(), vehicle.position.coordinate)
animator.duration = apiService.positionUpdateIntervalInMS.toLong()
animator.interpolator = null
animator.start()
}
}
override fun onMarkerClick(marker: Marker?): Boolean {
marker?.let {
vehicleMarkers.getKey(it)?.let {
apiService.fetchRouteAndStops(it) { route ->
highlightedRoute?.remove()
val options = PolylineOptions()
.addAll(route.coordinates)
.color(route.vehicleType.color)
.width(6.0f * screenDensity)
highlightedRoute = map?.addPolyline(options)
}
}
}
return false
}
override fun onMapClick(coordinate: LatLng?) {
highlightedRoute?.remove()
highlightedRoute = null
}
}
val Location.isInBerlinArea: Boolean get() = latitude < 52.833702 && latitude > 52.250741 && longitude < 13.948642 && longitude > 12.873355 | gpl-3.0 | 6be7e2a85312c4e988549d0c3b8f5677 | 39.784404 | 139 | 0.668954 | 4.969257 | false | false | false | false |
solkin/drawa-android | app/src/main/java/com/tomclaw/drawa/play/EventsProvider.kt | 1 | 1341 | package com.tomclaw.drawa.play
import com.tomclaw.drawa.draw.Event
import com.tomclaw.drawa.draw.History
import com.tomclaw.drawa.play.di.PLAY_HEIGHT
import com.tomclaw.drawa.play.di.PLAY_WIDTH
import com.tomclaw.drawa.util.SchedulersFactory
import com.tomclaw.drawa.util.StreamDecoder
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
class EventsProvider(
private val history: History,
private val schedulers: SchedulersFactory
) : StreamDecoder<Event> {
private var events: Iterator<Event>? = null
private val subscriptions = CompositeDisposable()
override fun getWidth(): Int = PLAY_WIDTH
override fun getHeight(): Int = PLAY_HEIGHT
override fun hasFrame(): Boolean = events().hasNext()
override fun readFrame(): Event = events().next()
override fun getDelay(): Int = 10
override fun stop() {
subscriptions.clear()
}
fun reset() {
loadEvents()
}
private fun events(): Iterator<Event> {
return events ?: loadEvents()
}
private fun loadEvents(): Iterator<Event> {
subscriptions += history.load()
.subscribeOn(schedulers.trampoline())
.subscribe()
val events = history.getEvents()
this.events = events
return events
}
}
| apache-2.0 | 8633ee70abab6a171cffe2facfb62297 | 24.788462 | 57 | 0.678598 | 4.48495 | false | false | false | false |
Adonai/Man-Man | app/src/main/java/com/adonai/manman/MainPagerActivity.kt | 1 | 4584 | package com.adonai.manman
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.preference.PreferenceManager
import androidx.viewpager.widget.ViewPager
import com.adonai.manman.preferences.PreferencesActivity
import com.astuetz.PagerSlidingTabStrip
/**
* Main activity where everything takes place
*
* @author Kanedias
*/
class MainPagerActivity : AppCompatActivity() {
private lateinit var mPager: ViewPager
private lateinit var mActionBar: Toolbar
private lateinit var mDonateHelper: DonateHelper
override fun onCreate(savedInstanceState: Bundle?) {
// should set theme prior to instantiating compat actionbar etc.
Utils.setupTheme(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_pager)
mActionBar = findViewById<View>(R.id.app_toolbar) as Toolbar
mPager = findViewById<View>(R.id.page_holder) as ViewPager
setSupportActionBar(mActionBar)
mPager.adapter = ManFragmentPagerAdapter(supportFragmentManager)
val tabs = findViewById<View>(R.id.tabs) as PagerSlidingTabStrip
tabs.setViewPager(mPager)
// setting up vending
mDonateHelper = DonateHelper(this)
// applying default tab
val prefs = PreferenceManager.getDefaultSharedPreferences(this)
val index = prefs.getString("app.default.tab", "0")
mPager.currentItem = Integer.valueOf(index!!)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.global_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.about_menu_item -> {
showAbout()
return true
}
R.id.donate_menu_item -> {
mDonateHelper.donate()
return true
}
R.id.settings_menu_item -> {
startActivity(Intent(this, PreferencesActivity::class.java))
return true
}
}
return super.onOptionsItemSelected(item)
}
private inner class ManFragmentPagerAdapter(fm: FragmentManager?) : FragmentPagerAdapter(fm!!, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
override fun getItem(i: Int): Fragment {
when (i) {
0 -> return ManPageSearchFragment()
1 -> return ManChaptersFragment()
2 -> return ManCacheFragment()
3 -> return ManLocalArchiveFragment()
}
throw IllegalArgumentException(String.format("No such fragment, index was %d", i))
}
override fun getCount(): Int {
return 4
}
override fun getPageTitle(position: Int): CharSequence? {
return when (position) {
0 -> getString(R.string.search)
1 -> getString(R.string.contents)
2 -> getString(R.string.cached)
3 -> getString(R.string.local_storage)
else -> null
}
}
}
/**
* Shows about dialog, with description, author and stuff
*/
@SuppressLint("InflateParams")
private fun showAbout() {
// Inflate the about message contents
val messageView = layoutInflater.inflate(R.layout.about_dialog, null, false)
val builder = AlertDialog.Builder(this)
builder.setIcon(R.drawable.ic_launcher_notification_icon)
builder.setTitle(R.string.app_name)
builder.setView(messageView)
builder.create()
builder.show()
}
override fun onBackPressed() {
if (!LocalBroadcastManager.getInstance(this).sendBroadcast(Intent(BACK_BUTTON_NOTIFY))) {
super.onBackPressed()
}
}
companion object {
const val FOLDER_LIST_KEY = "folder.list"
const val DB_CHANGE_NOTIFY = "database.updated"
const val LOCAL_CHANGE_NOTIFY = "locals.updated"
const val BACK_BUTTON_NOTIFY = "back.button.pressed"
}
} | gpl-3.0 | 88af9abc523ae578e4095b6098b255ee | 33.216418 | 139 | 0.65445 | 4.830348 | false | false | false | false |
Adonai/Man-Man | app/src/main/java/com/adonai/manman/adapters/LocalArchiveArrayAdapter.kt | 1 | 2771 | package com.adonai.manman.adapters
import android.content.Context
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Filter
import android.widget.ImageView
import android.widget.TextView
import com.adonai.manman.R
import com.adonai.manman.ManLocalArchiveFragment
import java.io.File
import java.util.*
/**
* Array adapter for showing files in local man page archive
* The data retrieval is done through [ManLocalArchiveFragment.doLoadContent]
*
* @see ArrayAdapter
* @see File
*
* @author Kanedias
*/
class LocalArchiveArrayAdapter(context: Context, resource: Int, textViewResourceId: Int, private val originals: List<File>) : ArrayAdapter<File>(context, resource, textViewResourceId, originals) {
private var filtered: List<File> = originals
override fun getCount(): Int {
return filtered.size
}
override fun getItem(position: Int): File {
return filtered[position]
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val root = super.getView(position, convertView, parent)
val current = getItem(position)
val effectiveName = current.name.replace("\\.gz$".toRegex(), "").replace("\\.\\d$".toRegex(), "")
val command = root.findViewById<View>(R.id.command_name_label) as TextView
val url = root.findViewById<View>(R.id.command_description_label) as TextView
val popup = root.findViewById<View>(R.id.popup_menu) as ImageView
command.text = effectiveName
url.text = current.parent
popup.visibility = View.GONE // save for future, hide for now
return root
}
override fun getFilter(): Filter {
return object : Filter() {
override fun performFiltering(constraint: CharSequence): FilterResults {
val fr = FilterResults()
if (TextUtils.isEmpty(constraint)) { // special case for empty filter
fr.values = originals
fr.count = originals.size
return fr
}
val tempFilteredValues: MutableList<File> = ArrayList()
for (f in originals) {
if (f.name.startsWith(constraint.toString())) {
tempFilteredValues.add(f)
}
}
fr.values = tempFilteredValues
fr.count = tempFilteredValues.size
return fr
}
override fun publishResults(constraint: CharSequence, results: FilterResults) {
filtered = results.values as List<File>
notifyDataSetChanged()
}
}
}
} | gpl-3.0 | 1bb2e58318bd7d0d8190f5404563323b | 33.222222 | 196 | 0.634428 | 4.753002 | false | false | false | false |
googleads/googleads-mobile-android-examples | kotlin/admanager/AppOpenExample/app/src/main/java/com/google/android/gms/example/appopenexample/MyApplication.kt | 1 | 8699 | package com.google.android.gms.example.appopenexample
import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.multidex.MultiDexApplication
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.admanager.AdManagerAdRequest
import com.google.android.gms.ads.appopen.AppOpenAd
import com.google.android.gms.ads.appopen.AppOpenAd.AppOpenAdLoadCallback
import java.util.Date
private const val AD_UNIT_ID = "/6499/example/app-open"
private const val LOG_TAG = "MyApplication"
/** Application class that initializes, loads and show ads when activities change states. */
class MyApplication :
MultiDexApplication(), Application.ActivityLifecycleCallbacks, LifecycleObserver {
private lateinit var appOpenAdManager: AppOpenAdManager
private var currentActivity: Activity? = null
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(this)
// Log the Mobile Ads SDK version.
Log.d(LOG_TAG, "Google Mobile Ads SDK Version: " + MobileAds.getVersion())
MobileAds.initialize(this) {}
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
appOpenAdManager = AppOpenAdManager()
}
/** LifecycleObserver method that shows the app open ad when the app moves to foreground. */
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onMoveToForeground() {
// Show the ad (if available) when the app moves to foreground.
currentActivity?.let { appOpenAdManager.showAdIfAvailable(it) }
}
/** ActivityLifecycleCallback methods. */
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
override fun onActivityStarted(activity: Activity) {
// An ad activity is started when an ad is showing, which could be AdActivity class from Google
// SDK or another activity class implemented by a third party mediation partner. Updating the
// currentActivity only when an ad is not showing will ensure it is not an ad activity, but the
// one that shows the ad.
if (!appOpenAdManager.isShowingAd) {
currentActivity = activity
}
}
override fun onActivityResumed(activity: Activity) {}
override fun onActivityPaused(activity: Activity) {}
override fun onActivityStopped(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
override fun onActivityDestroyed(activity: Activity) {}
/**
* Shows an app open ad.
*
* @param activity the activity that shows the app open ad
* @param onShowAdCompleteListener the listener to be notified when an app open ad is complete
*/
fun showAdIfAvailable(activity: Activity, onShowAdCompleteListener: OnShowAdCompleteListener) {
// We wrap the showAdIfAvailable to enforce that other classes only interact with MyApplication
// class.
appOpenAdManager.showAdIfAvailable(activity, onShowAdCompleteListener)
}
/**
* Interface definition for a callback to be invoked when an app open ad is complete (i.e.
* dismissed or fails to show).
*/
interface OnShowAdCompleteListener {
fun onShowAdComplete()
}
/** Inner class that loads and shows app open ads. */
private inner class AppOpenAdManager {
private var appOpenAd: AppOpenAd? = null
private var isLoadingAd = false
var isShowingAd = false
/** Keep track of the time an app open ad is loaded to ensure you don't show an expired ad. */
private var loadTime: Long = 0
/**
* Load an ad.
*
* @param context the context of the activity that loads the ad
*/
fun loadAd(context: Context) {
// Do not load ad if there is an unused ad or one is already loading.
if (isLoadingAd || isAdAvailable()) {
return
}
isLoadingAd = true
val request = AdManagerAdRequest.Builder().build()
AppOpenAd.load(
context,
AD_UNIT_ID,
request,
AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT,
object : AppOpenAdLoadCallback() {
/**
* Called when an app open ad has loaded.
*
* @param ad the loaded app open ad.
*/
override fun onAdLoaded(ad: AppOpenAd) {
appOpenAd = ad
isLoadingAd = false
loadTime = Date().time
Log.d(LOG_TAG, "onAdLoaded.")
Toast.makeText(context, "onAdLoaded", Toast.LENGTH_SHORT).show()
}
/**
* Called when an app open ad has failed to load.
*
* @param loadAdError the error.
*/
override fun onAdFailedToLoad(loadAdError: LoadAdError) {
isLoadingAd = false
Log.d(LOG_TAG, "onAdFailedToLoad: " + loadAdError.message)
Toast.makeText(context, "onAdFailedToLoad", Toast.LENGTH_SHORT).show()
}
}
)
}
/** Check if ad was loaded more than n hours ago. */
private fun wasLoadTimeLessThanNHoursAgo(numHours: Long): Boolean {
val dateDifference: Long = Date().time - loadTime
val numMilliSecondsPerHour: Long = 3600000
return dateDifference < numMilliSecondsPerHour * numHours
}
/** Check if ad exists and can be shown. */
private fun isAdAvailable(): Boolean {
// Ad references in the app open beta will time out after four hours, but this time limit
// may change in future beta versions. For details, see:
// https://support.google.com/admob/answer/9341964?hl=en
return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4)
}
/**
* Show the ad if one isn't already showing.
*
* @param activity the activity that shows the app open ad
*/
fun showAdIfAvailable(activity: Activity) {
showAdIfAvailable(
activity,
object : OnShowAdCompleteListener {
override fun onShowAdComplete() {
// Empty because the user will go back to the activity that shows the ad.
}
}
)
}
/**
* Show the ad if one isn't already showing.
*
* @param activity the activity that shows the app open ad
* @param onShowAdCompleteListener the listener to be notified when an app open ad is complete
*/
fun showAdIfAvailable(activity: Activity, onShowAdCompleteListener: OnShowAdCompleteListener) {
// If the app open ad is already showing, do not show the ad again.
if (isShowingAd) {
Log.d(LOG_TAG, "The app open ad is already showing.")
return
}
// If the app open ad is not available yet, invoke the callback then load the ad.
if (!isAdAvailable()) {
Log.d(LOG_TAG, "The app open ad is not ready yet.")
onShowAdCompleteListener.onShowAdComplete()
loadAd(activity)
return
}
Log.d(LOG_TAG, "Will show ad.")
appOpenAd!!.setFullScreenContentCallback(
object : FullScreenContentCallback() {
/** Called when full screen content is dismissed. */
override fun onAdDismissedFullScreenContent() {
// Set the reference to null so isAdAvailable() returns false.
appOpenAd = null
isShowingAd = false
Log.d(LOG_TAG, "onAdDismissedFullScreenContent.")
Toast.makeText(activity, "onAdDismissedFullScreenContent", Toast.LENGTH_SHORT).show()
onShowAdCompleteListener.onShowAdComplete()
loadAd(activity)
}
/** Called when fullscreen content failed to show. */
override fun onAdFailedToShowFullScreenContent(adError: AdError) {
appOpenAd = null
isShowingAd = false
Log.d(LOG_TAG, "onAdFailedToShowFullScreenContent: " + adError.message)
Toast.makeText(activity, "onAdFailedToShowFullScreenContent", Toast.LENGTH_SHORT).show()
onShowAdCompleteListener.onShowAdComplete()
loadAd(activity)
}
/** Called when fullscreen content is shown. */
override fun onAdShowedFullScreenContent() {
Log.d(LOG_TAG, "onAdShowedFullScreenContent.")
Toast.makeText(activity, "onAdShowedFullScreenContent", Toast.LENGTH_SHORT).show()
}
}
)
isShowingAd = true
appOpenAd!!.show(activity)
}
}
}
| apache-2.0 | 33c4c3ada0c11d196b1feea6712ee44c | 35.095436 | 100 | 0.676974 | 4.53309 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osm/mapdata/WayDao.kt | 1 | 2539 | package de.westnordost.streetcomplete.data.osm.mapdata
import android.database.Cursor
import android.database.sqlite.SQLiteOpenHelper
import androidx.core.content.contentValuesOf
import de.westnordost.osmapi.map.data.Element
import java.util.ArrayList
import java.util.HashMap
import javax.inject.Inject
import de.westnordost.streetcomplete.util.Serializer
import de.westnordost.osmapi.map.data.OsmWay
import de.westnordost.osmapi.map.data.Way
import de.westnordost.streetcomplete.data.ObjectRelationalMapping
import de.westnordost.streetcomplete.data.osm.mapdata.WayTable.Columns.ID
import de.westnordost.streetcomplete.data.osm.mapdata.WayTable.Columns.NODE_IDS
import de.westnordost.streetcomplete.data.osm.mapdata.WayTable.Columns.TAGS
import de.westnordost.streetcomplete.data.osm.mapdata.WayTable.Columns.VERSION
import de.westnordost.streetcomplete.data.osm.splitway.OsmQuestSplitWayTable
import de.westnordost.streetcomplete.ktx.*
/** Stores OSM ways */
class WayDao @Inject constructor(private val dbHelper: SQLiteOpenHelper, override val mapping: WayMapping)
: AOsmElementDao<Way>(dbHelper) {
private val db get() = dbHelper.writableDatabase
override val tableName = WayTable.NAME
override val idColumnName = ID
override val elementTypeName = Element.Type.WAY.name
/** Cleans up element entries that are not referenced by any quest (or other things) anymore. */
override fun deleteUnreferenced() {
val where = """
$idColumnName NOT IN (
$selectElementIdsInQuestTable
UNION
$selectElementIdsInUndoQuestTable
UNION
$selectElementIdsInDeleteElementsTable
UNION
SELECT ${OsmQuestSplitWayTable.Columns.WAY_ID} AS $idColumnName FROM ${OsmQuestSplitWayTable.NAME}
)""".trimIndent()
db.delete(tableName, where, null)
}
}
class WayMapping @Inject constructor(private val serializer: Serializer)
: ObjectRelationalMapping<Way> {
override fun toContentValues(obj: Way) = contentValuesOf(
ID to obj.id,
VERSION to obj.version,
NODE_IDS to serializer.toBytes(ArrayList(obj.nodeIds)),
TAGS to obj.tags?.let { serializer.toBytes(HashMap(it)) }
)
override fun toObject(cursor: Cursor) = OsmWay(
cursor.getLong(ID),
cursor.getInt(VERSION),
serializer.toObject<ArrayList<Long>>(cursor.getBlob(NODE_IDS)),
cursor.getBlobOrNull(TAGS)?.let { serializer.toObject<HashMap<String, String>>(it) }
)
}
| gpl-3.0 | c44c701a294409f66a7fee37369a0a2f | 36.895522 | 110 | 0.739661 | 4.310696 | false | false | false | false |
android/performance-samples | MacrobenchmarkSample/macrobenchmark/src/main/java/com/example/macrobenchmark/frames/NestedRecyclerFrameTimingBenchmarks.kt | 1 | 4290 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.macrobenchmark.frames
import androidx.benchmark.macro.*
import androidx.benchmark.macro.junit4.MacrobenchmarkRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.uiautomator.By
import androidx.test.uiautomator.Direction
import androidx.test.uiautomator.Until
import com.example.benchmark.macro.base.util.DEFAULT_ITERATIONS
import com.example.benchmark.macro.base.util.TARGET_PACKAGE
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.TimeUnit
@ExperimentalMetricApi
@LargeTest
@RunWith(AndroidJUnit4::class)
class NestedRecyclerFrameTimingBenchmarks {
@get:Rule
val benchmarkRule = MacrobenchmarkRule()
@Test
fun scrollNestedRecyclerWithoutRecyclerPool() {
benchmarkRule.measureRepeated(
packageName = TARGET_PACKAGE,
metrics = listOf(FrameTimingMetric()),
// CompilationMode.None + StartupMode.Cold clears compilation on each iteration,
// and can represent the worst-case performance scenario.
compilationMode = CompilationMode.None(),
startupMode = StartupMode.COLD,
iterations = DEFAULT_ITERATIONS,
setupBlock = { navigateToNestedRvScreen(false) }
) { measureScrollingNestedRecycler() }
}
@Test
fun scrollNestedRecyclerWithRecyclerPool() {
benchmarkRule.measureRepeated(
packageName = TARGET_PACKAGE,
metrics = listOf(FrameTimingMetric()),
// CompilationMode.None + StartupMode.Cold clears compilation on each iteration,
// and can represent the worst-case performance scenario.
compilationMode = CompilationMode.None(),
startupMode = StartupMode.COLD,
iterations = DEFAULT_ITERATIONS,
setupBlock = { navigateToNestedRvScreen(true) }
) { measureScrollingNestedRecycler() }
}
private fun MacrobenchmarkScope.navigateToNestedRvScreen(useRecyclerViewPool: Boolean) {
startActivityAndWait()
// navigate to the activity
val buttonId =
if (useRecyclerViewPool) "nestedRecyclerWithPoolsActivity" else "nestedRecyclerActivity"
device
.findObject(By.res(packageName, buttonId))
.click()
// wait until the activity is shown
device.wait(
Until.hasObject(By.clazz("$packageName.NestedRecyclerActivity")),
TimeUnit.SECONDS.toMillis(10)
)
}
private fun MacrobenchmarkScope.measureScrollingNestedRecycler() {
val recycler = device.findObject(By.res(packageName, "recycler"))
// Set gesture margin to avoid triggering gesture navigation with input events from automation.
recycler.setGestureMargin(device.displayWidth / 5)
repeat(3) { index ->
val visibleNestedRecyclers =
recycler.findObjects(By.res(packageName, "row_recycler"))
// scroll the second recycler, because the first one may be shown just a pixel
val nestedRecyclerToScroll = visibleNestedRecyclers[1]
// Set gesture margin to avoid triggering gesture navigation with input events from automation.
nestedRecyclerToScroll.setGestureMargin(device.displayWidth / 5)
// swipe horizontally
nestedRecyclerToScroll.fling(Direction.RIGHT)
// scroll down twice and once up
recycler.swipe(if (index < 2) Direction.UP else Direction.DOWN, 0.5f)
// wait until the swipe is done
device.waitForIdle()
}
}
}
| apache-2.0 | f1cccd96a22c1a5b20c52e999218dbcb | 37.648649 | 107 | 0.695804 | 4.902857 | false | true | false | false |
Cognifide/APM | app/aem/core/src/main/kotlin/com/cognifide/apm/core/services/async/ExecutionStatus.kt | 1 | 1337 | /*-
* ========================LICENSE_START=================================
* AEM Permission Management
* %%
* Copyright (C) 2013 Wunderman Thompson Technology
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/
package com.cognifide.apm.core.services.async
import com.cognifide.apm.api.services.ExecutionResult
sealed class ExecutionStatus(val status: String)
class RunningExecution : ExecutionStatus("running")
class UnknownExecution : ExecutionStatus("unknown")
class FinishedSuccessfulExecution(val path: String, val entries: List<ExecutionResult.Entry>) : ExecutionStatus("finished")
class FinishedFailedExecution(val path: String, val entries: List<ExecutionResult.Entry>, val error: ExecutionResult.Entry) : ExecutionStatus("finished") | apache-2.0 | 484d262ae18c1d8dcdd4ff7a2f804db0 | 46.785714 | 153 | 0.70531 | 4.758007 | false | false | false | false |
zlyne0/colonization | core/src/net/sf/freecol/common/model/ai/missions/pioneer/PioneerMissionPlaner.kt | 1 | 18619 | package net.sf.freecol.common.model.ai.missions.pioneer
import net.sf.freecol.common.model.Colony
import net.sf.freecol.common.model.Game
import net.sf.freecol.common.model.Specification
import net.sf.freecol.common.model.Tile
import net.sf.freecol.common.model.Unit
import net.sf.freecol.common.model.UnitRole
import net.sf.freecol.common.model.UnitType
import net.sf.freecol.common.model.ai.ColonySupplyGoods
import net.sf.freecol.common.model.ai.missions.MissionId
import net.sf.freecol.common.model.ai.missions.PlayerMissionsContainer
import net.sf.freecol.common.model.ai.missions.foreachMission
import net.sf.freecol.common.model.colonyproduction.GoodsCollection
import net.sf.freecol.common.model.colonyproduction.amount
import net.sf.freecol.common.model.colonyproduction.type
import net.sf.freecol.common.model.map.path.PathFinder
import net.sf.freecol.common.model.player.Player
import promitech.colonization.ai.score.ObjectScoreList
import java.util.HashSet
sealed class PioneerDestination {
class TheSameIsland(val plan: ColonyTilesImprovementPlan) : PioneerDestination()
class OtherIsland(val plan: ColonyTilesImprovementPlan) : PioneerDestination()
class Lack : PioneerDestination()
fun extractColonyDestination(): Colony? {
return when (this) {
is TheSameIsland -> plan.colony
is OtherIsland -> plan.colony
is Lack -> null
}
}
}
data class PioneerBuyPlan(val buyPioneerOrder: BuyPioneerOrder, val colony: Colony)
data class ColonyHardyPioneer(val colony: Colony, val hardyPioneer: Unit)
/**
* Running up that hill.
*/
class PioneerMissionPlaner(val game: Game, val pathFinder: PathFinder) {
private val pioneerSupplyLandRange = 3
private val pioneerSupplySeaRange = 2
private val minDistanceToUseShipTransport = 5
private val improvedAllTilesInColonyToAllColonyRatio: Double = 0.7
fun createBuyPlan(player: Player, playerMissionContainer: PlayerMissionsContainer): PioneerBuyPlan? {
val colonyWithMissions = HashSet<String>(playerMissionContainer.player.settlements.size())
var hasSpecialistOnMission = false
playerMissionContainer.foreachMission(PioneerMission::class.java, { pioneerMission ->
colonyWithMissions.add(pioneerMission.colonyId)
if (pioneerMission.isSpecialist()) {
hasSpecialistOnMission = true
}
})
val improvementsPlanDestinationsScore = generateImprovementsPlanScore(player, AddImprovementPolicy.Balanced())
if (isReachMaxPioneerMissions(improvementsPlanDestinationsScore, colonyWithMissions)) {
// no missions
return null
}
// simplification: existed pioneer units without mission should handled by default colony worker
val firstDestination: ColonyTilesImprovementPlan? = firstImprovmentColonyDestination(improvementsPlanDestinationsScore, colonyWithMissions)
if (firstDestination == null) {
return null
}
val colonyHardyPioneerInRange = findColonyHardyPioneerInRange(player, firstDestination.colony.tile)
val colonyToEquiptPioneer = findColonyToEquiptPioneerInRange(player, firstDestination.colony.tile, null)
val buyPioneerOrder = calculateBuyPioneerOrder(player, hasSpecialistOnMission, colonyHardyPioneerInRange, colonyToEquiptPioneer)
if (buyPioneerOrder is BuyPioneerOrder.CanNotAfford) {
return null
}
return PioneerBuyPlan(buyPioneerOrder, firstDestination.colony)
}
fun findColonyHardyPioneerInRange(
player: Player,
sourceTile: Tile
): ColonyHardyPioneer? {
val playerMissionContainer = game.aiContainer.missionContainer(player)
val freeColonistPathUnit = pathFinder.createPathUnit(player, Specification.instance.freeColonistUnitType)
pathFinder.generateRangeMap(game.map, sourceTile, freeColonistPathUnit, PathFinder.includeUnexploredTiles, pioneerSupplyLandRange)
val colonyHardyPioneer = findHardyPioneerInPathFindRange(playerMissionContainer, pathFinder, player)
if (colonyHardyPioneer != null) {
return colonyHardyPioneer
}
val pathUnit = pathFinder.createPathUnit(player, Specification.instance.unitTypes.getById(UnitType.CARAVEL))
pathFinder.generateRangeMap(game.map, sourceTile, pathUnit, PathFinder.includeUnexploredTiles, pioneerSupplySeaRange)
return findHardyPioneerInPathFindRange(playerMissionContainer, pathFinder, player)
}
private fun findHardyPioneerInPathFindRange(
playerMissionContainer: PlayerMissionsContainer,
rangePathFinder: PathFinder,
player: Player
): ColonyHardyPioneer? {
var minDistance = Int.MAX_VALUE
var minDistanceColony: Colony? = null
var colonyHardyPioneer: Unit? = null
for (settlement in player.settlements) {
val distance = rangePathFinder.turnsCost(settlement.tile)
if (distance < minDistance) {
val colony = settlement.asColony()
val pioneer = findHardyPioneer(colony, playerMissionContainer)
if (pioneer != null) {
minDistance = distance
minDistanceColony = colony
colonyHardyPioneer = pioneer
}
}
}
if (colonyHardyPioneer != null && minDistanceColony != null) {
return ColonyHardyPioneer(minDistanceColony, colonyHardyPioneer)
}
return null
}
private fun findHardyPioneer(colony: Colony, playerMissionContainer: PlayerMissionsContainer): Unit? {
for (unit in colony.units.entities()) {
if (unit.unitType.equalsId(UnitType.HARDY_PIONEER) && !playerMissionContainer.isUnitBlockedForMission(unit)) {
return unit
}
}
return null
}
fun findColonyToEquiptPioneerInRange(player: Player, sourceTile: Tile, pioneerMissionId: MissionId?): Colony? {
val playerAiContainer = game.aiContainer.playerAiContainer(player)
val freeColonistPathUnit = pathFinder.createPathUnit(player, Specification.instance.freeColonistUnitType)
pathFinder.generateRangeMap(game.map, sourceTile, freeColonistPathUnit, PathFinder.includeUnexploredTiles, pioneerSupplyLandRange)
val pioneerRole = Specification.instance.unitRoles.getById(UnitRole.PIONEER)
val pioneerRoleRequiredGoods = pioneerRole.sumOfRequiredGoods()
val hasColonyRequiredGoodsPredicate: (Colony) -> Boolean = { colony ->
hasColonyRequiredGoods(colony, pioneerRoleRequiredGoods, playerAiContainer.findColonySupplyGoods(colony), pioneerMissionId)
}
val colonyWithToolsSupply = findToolsSupplyInPathRange(pathFinder, player, hasColonyRequiredGoodsPredicate)
if (colonyWithToolsSupply != null) {
return colonyWithToolsSupply
}
val pathUnit = pathFinder.createPathUnit(player, Specification.instance.unitTypes.getById(UnitType.CARAVEL))
pathFinder.generateRangeMap(game.map, sourceTile, pathUnit, PathFinder.includeUnexploredTiles, pioneerSupplySeaRange)
return findToolsSupplyInPathRange(pathFinder, player, hasColonyRequiredGoodsPredicate)
}
fun hasColonyRequiredGoods(
colony: Colony,
requiredGoods: GoodsCollection,
colonySupplyGoods: ColonySupplyGoods?,
pioneerMissionId: MissionId?
): Boolean {
for (requiredGood in requiredGoods) {
val reservationSum = if (colonySupplyGoods != null) colonySupplyGoods.reservationSum(requiredGood.type(), pioneerMissionId) else 0
if (colony.goodsContainer.goodsAmount(requiredGood.type()) < requiredGood.amount() + reservationSum) {
return false
}
}
return true
}
private fun findToolsSupplyInPathRange(
rangePathFinder: PathFinder,
player: Player,
colonyHasRequiredGoodsPredicate: (colony: Colony) -> Boolean
): Colony? {
var minDistance = Int.MAX_VALUE
var minDistanceColony: Colony? = null
for (settlement in player.settlements) {
val distance = rangePathFinder.turnsCost(settlement.tile)
if (distance < minDistance) {
val colony = settlement.asColony()
if (colonyHasRequiredGoodsPredicate(colony)) {
minDistance = distance
minDistanceColony = colony
}
}
}
return minDistanceColony
}
fun handlePioneerBuyPlan(pioneerBuyPlan: PioneerBuyPlan, playerMissionContainer: PlayerMissionsContainer) {
pioneerBuyPlan.buyPioneerOrder.buyAndPrepareMissions(playerMissionContainer, pioneerBuyPlan.colony, game)
}
private fun isReachMaxPioneerMissions(
improvementsPlanDestinationsScore: ObjectScoreList<ColonyTilesImprovementPlan>,
colonyWithMissions: Set<String>
): Boolean {
var potentialImprovementsDestinationCount = 0
for (objectScore in improvementsPlanDestinationsScore) {
if (objectScore.obj.hasImprovements()) {
potentialImprovementsDestinationCount++
}
}
// no more new pioneers mission then half of improvements destinations
val maxPioneersCount: Int = potentialImprovementsDestinationCount / 2
if (colonyWithMissions.size >= maxPioneersCount) {
// no missions
return true
}
return false
}
fun findImprovementDestination(mission: PioneerMission, playerMissionContainer: PlayerMissionsContainer): PioneerDestination {
val improvementsPlan = generateImprovementsPlanForColony(mission.pioneer.owner, mission.colonyId)
if (improvementsPlan.hasImprovements()) {
val firstImprovement = improvementsPlan.firstImprovement()
pathFinder.findToTile(game.map, mission.pioneer, firstImprovement.tile, PathFinder.includeUnexploredTiles)
if (pathFinder.isTurnCostAbove(firstImprovement.tile, minDistanceToUseShipTransport)) {
return PioneerDestination.OtherIsland(improvementsPlan)
}
return PioneerDestination.TheSameIsland(improvementsPlan)
} else {
return findNextColonyToImprove(mission, playerMissionContainer)
}
}
fun findNextColonyToImprove(mission: PioneerMission, playerMissionContainer: PlayerMissionsContainer): PioneerDestination {
val colonyWithMissions = HashSet<String>(playerMissionContainer.player.settlements.size())
playerMissionContainer.foreachMission(PioneerMission::class.java, { pioneerMission ->
colonyWithMissions.add(pioneerMission.colonyId)
})
val improvementsPlanDestinationsScore = generateImprovementsPlanScore(playerMissionContainer.player, AddImprovementPolicy.Balanced())
pathFinder.generateRangeMap(
game.map,
mission.pioneer.positionRelativeToMap(game.map),
mission.pioneer,
PathFinder.includeUnexploredTiles
)
val improvementDestination: ColonyTilesImprovementPlan? = findTheBestDestinationInRange(
pathFinder,
improvementsPlanDestinationsScore,
colonyWithMissions,
mission
)
if (improvementDestination == null || improvementDestination.isEmpty()) {
return PioneerDestination.Lack()
}
if (pathFinder.isTurnCostAbove(improvementDestination.colony.tile, minDistanceToUseShipTransport)) {
return PioneerDestination.OtherIsland(improvementDestination)
}
return PioneerDestination.TheSameIsland(improvementDestination)
}
private fun findTheBestDestinationInRange(
rangePathFinder: PathFinder,
improvementsPlanDestinationsScore: ObjectScoreList<ColonyTilesImprovementPlan>,
colonyWithMissions: Set<String>,
actualPioneerMission: PioneerMission
): ColonyTilesImprovementPlan? {
var improvementDestination: ColonyTilesImprovementPlan? = null
var destinationScore: Double = 0.0
for (planScore in improvementsPlanDestinationsScore) {
if (planScore.obj.colony.equalsId(actualPioneerMission.colonyId)) {
improvementDestination = planScore.obj
destinationScore = planScore.score().toDouble() / nextColonyDistanceValue(rangePathFinder, planScore.obj.colony)
}
}
for (planScore in improvementsPlanDestinationsScore) {
if (planScore.score() == 0 || colonyWithMissions.contains(planScore.obj.colony.id)) {
continue
}
val dscore: Double = planScore.score().toDouble() / nextColonyDistanceValue(rangePathFinder, planScore.obj.colony)
if (improvementDestination == null || dscore > destinationScore) {
destinationScore = dscore
improvementDestination = planScore.obj
}
}
return improvementDestination
}
private fun nextColonyDistanceValue(rangePathFinder: PathFinder, colony: Colony): Int {
var distance = rangePathFinder.turnsCost(colony.tile)
if (distance == 0) {
distance = 1
} else {
if (distance == PathFinder.INFINITY) {
distance = 10
}
}
return distance
}
private fun firstImprovmentColonyDestination(
improvementsPlanDestinationsScore: ObjectScoreList<ColonyTilesImprovementPlan>,
colonyWithMissions: Set<String>
): ColonyTilesImprovementPlan? {
for (destinationScore in improvementsPlanDestinationsScore) {
if (destinationScore.obj.hasImprovements() && !colonyWithMissions.contains(destinationScore.obj.colony.id)) {
return destinationScore.obj
}
}
return null
}
fun calculateBuyPioneerOrder(
player: Player,
hasSpecialistOnMission: Boolean,
colonyHardyPioneerInRange: ColonyHardyPioneer? = null,
colonyToEquiptPioneer: Colony? = null
): BuyPioneerOrder {
val freeColonistPrice = player.europe.aiUnitPrice(Specification.instance.freeColonistUnitType)
val pioneerRole = Specification.instance.unitRoles.getById(UnitRole.PIONEER)
if (colonyHardyPioneerInRange != null) {
if (colonyToEquiptPioneer != null) {
if (player.hasGold(freeColonistPrice * 2)) {
return BuyPioneerOrder.RecruitColonistWithToolsAndHardyPionnerLocation(colonyToEquiptPioneer, colonyHardyPioneerInRange)
}
return BuyPioneerOrder.CanNotAfford()
} else {
val pioneerSumOfRequiredGoods : GoodsCollection = pioneerRole.sumOfRequiredGoods()
val pionnerPrice = freeColonistPrice + player.market().aiBidPrice(pioneerSumOfRequiredGoods)
if (player.hasGold(pionnerPrice * 2)) {
return BuyPioneerOrder.RecruitColonistWithHardyPioneerLocation(colonyHardyPioneerInRange)
}
return BuyPioneerOrder.CanNotAfford()
}
}
val hardyPioneerUnitType = Specification.instance.unitTypes.getById(UnitType.HARDY_PIONEER)
val hardyPioneerPrice = player.europe.aiUnitPrice(hardyPioneerUnitType)
if (player.hasGold(hardyPioneerPrice * 2)) {
return BuyPioneerOrder.BuySpecialistOrder()
} else if (!hasSpecialistOnMission) {
if (colonyToEquiptPioneer != null) {
if (player.hasGold(freeColonistPrice * 2)) {
return BuyPioneerOrder.RecruitColonistWithToolsLocation(colonyToEquiptPioneer)
}
} else {
val pioneerSumOfRequiredGoods: GoodsCollection = pioneerRole.sumOfRequiredGoods()
val pionnerPrice = freeColonistPrice + player.market().aiBidPrice(pioneerSumOfRequiredGoods)
if (player.hasGold(pionnerPrice * 2)) {
return BuyPioneerOrder.RecruitColonistOrder()
}
}
}
return BuyPioneerOrder.CanNotAfford()
}
fun generateImprovementsPlanScore(player: Player, policy: AddImprovementPolicy): ObjectScoreList<ColonyTilesImprovementPlan> {
val improvementPlanScore = ObjectScoreList<ColonyTilesImprovementPlan>(player.settlements.size())
for (settlement in player.settlements) {
val colony = settlement.asColony()
val improvementPlan = policy.generateImprovements(colony)
improvementPlanScore.add(improvementPlan, calculateScore(improvementPlan))
}
// ratio of colonises without improvements to colonies with improvements
val actualRatio = calculateColoniesWithoutImprovementsToAllColoniesRatio(player, improvementPlanScore)
if (actualRatio >= improvedAllTilesInColonyToAllColonyRatio) {
for (scorePlan in improvementPlanScore) {
val plan = scorePlan.obj
policy.generateVacantForFood(plan)
scorePlan.updateScore(calculateScore(plan))
}
}
improvementPlanScore.sortDescending()
return improvementPlanScore
}
private fun calculateColoniesWithoutImprovementsToAllColoniesRatio(
player: Player,
improvementPlanScore: ObjectScoreList<ColonyTilesImprovementPlan>
): Double {
var allImprovementsCount = 0
for (scorePlan in improvementPlanScore) {
if (!scorePlan.obj.hasImprovements()) {
allImprovementsCount++
}
}
return allImprovementsCount.toDouble() / player.settlements.size()
}
fun generateImprovementsPlanForColony(player: Player, colonyId: String): ColonyTilesImprovementPlan {
val colony = player.settlements.getById(colonyId).asColony()
val improvementPolicy = AddImprovementPolicy.Balanced()
return improvementPolicy.generateImprovements(colony)
}
private fun calculateScore(improvementPlan: ColonyTilesImprovementPlan): Int {
if (improvementPlan.improvements.size == 0) {
return 0
}
var resCount = 0
for (improvement in improvementPlan.improvements) {
if (improvement.tile.hasTileResource()) {
resCount++
}
}
return improvementPlan.colony.settlementWorkers().size * 10 + resCount
}
} | gpl-2.0 | cdbf65f51a33b998525470f626d7b8b7 | 44.194175 | 147 | 0.69327 | 4.523567 | false | false | false | false |
SirLYC/Android-Gank-Share | app/src/main/java/com/lyc/gank/utils/ReactiveAdapter.kt | 1 | 2541 | package com.lyc.gank.utils
import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v7.util.ListUpdateCallback
import me.drakeet.multitype.MultiTypeAdapter
/**
* Created by Liu Yuchuan on 2018/2/17.
*/
class ReactiveAdapter(
private val dataList: ObservableList<Any>
): MultiTypeAdapter(dataList), ListUpdateCallback{
override fun onChanged(position: Int, count: Int, payload: Any?) = notifyItemChanged(position)
override fun onMoved(fromPosition: Int, toPosition: Int) = notifyItemMoved(fromPosition, toPosition)
override fun onInserted(position: Int, count: Int) = notifyItemRangeInserted(position, count)
override fun onRemoved(position: Int, count: Int) = notifyItemRangeRemoved(position, count)
fun observe(activity: Activity) {
activity.application.registerActivityLifecycleCallbacks(ReactiveActivityRegistry(activity))
dataList.addCallback(this)
}
fun observe(fragment: Fragment) {
fragment.fragmentManager!!.registerFragmentLifecycleCallbacks(ReactiveFragmentRegistry(fragment), false)
dataList.addCallback(this)
}
inner class ReactiveActivityRegistry(
private val activity: Activity
) : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?) {}
override fun onActivityStarted(activity: Activity) {}
override fun onActivityResumed(activity: Activity) {}
override fun onActivityPaused(activity: Activity) {}
override fun onActivityStopped(activity: Activity) {}
override fun onActivityDestroyed(activity: Activity) {
if (this.activity == activity) {
dataList.removeCallback(this@ReactiveAdapter)
activity.application.unregisterActivityLifecycleCallbacks(this)
}
}
}
inner class ReactiveFragmentRegistry(
private val fragment: Fragment
) : FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentViewDestroyed(fm: FragmentManager, f: Fragment) {
super.onFragmentViewDestroyed(fm, f)
if (fragment == f) {
dataList.removeCallback(this@ReactiveAdapter)
fm.unregisterFragmentLifecycleCallbacks(this)
}
}
}
} | apache-2.0 | b8cefa385c2c6b0eca636e64aaae6e3f | 40 | 112 | 0.717041 | 5.271784 | false | false | false | false |
da1z/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/DefaultListOrMapTypeCalculator.kt | 7 | 4438 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.typing
import com.intellij.openapi.util.RecursionManager.doPreventingRecursion
import com.intellij.psi.CommonClassNames
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiType
import com.intellij.psi.util.InheritanceUtil.isInheritor
import com.intellij.psi.util.PsiUtil.substituteTypeParameter
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrSpreadArgument
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.GrMapType
import org.jetbrains.plugins.groovy.lang.psi.impl.GrTupleType
import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames
class DefaultListOrMapTypeCalculator : GrTypeCalculator<GrListOrMap> {
override fun getType(expression: GrListOrMap): PsiType? {
if (expression.isMap) {
return getMapTypeFromDiamond(expression) ?: GrMapType.createFromNamedArgs(expression, expression.namedArguments)
}
else {
return getListTypeFromDiamond(expression) ?: getTupleType(expression)
}
}
private fun getMapTypeFromDiamond(expression: GrListOrMap): PsiType? {
val namedArgs = expression.namedArguments
if (namedArgs.isNotEmpty()) return null
val lType = PsiImplUtil.inferExpectedTypeForDiamond(expression) ?: return null
if (lType !is PsiClassType || !isInheritor(lType, CommonClassNames.JAVA_UTIL_MAP)) return null
val scope = expression.resolveScope
val facade = JavaPsiFacade.getInstance(expression.project)
val hashMap = facade.findClass(GroovyCommonClassNames.JAVA_UTIL_LINKED_HASH_MAP, scope) ?: return null
return facade.elementFactory.createType(
hashMap,
substituteTypeParameter(lType, CommonClassNames.JAVA_UTIL_MAP, 0, false),
substituteTypeParameter(lType, CommonClassNames.JAVA_UTIL_MAP, 1, false)
)
}
private fun getListTypeFromDiamond(expression: GrListOrMap): PsiType? {
val initializers = expression.initializers
if (initializers.isNotEmpty()) return null
val lType = PsiImplUtil.inferExpectedTypeForDiamond(expression)
if (lType !is PsiClassType) return null
val scope = expression.resolveScope
val facade = JavaPsiFacade.getInstance(expression.project)
if (isInheritor(lType, CommonClassNames.JAVA_UTIL_LIST)) {
val arrayList = facade.findClass(CommonClassNames.JAVA_UTIL_ARRAY_LIST, scope) ?:
facade.findClass(CommonClassNames.JAVA_UTIL_LIST, scope) ?: return null
return facade.elementFactory.createType(
arrayList,
substituteTypeParameter(lType, CommonClassNames.JAVA_UTIL_LIST, 0, false)
)
}
if (isInheritor(lType, CommonClassNames.JAVA_UTIL_SET)) {
val set = facade.findClass("java.util.LinkedHashSet", scope) ?:
facade.findClass(CommonClassNames.JAVA_UTIL_SET, scope) ?: return null
return facade.elementFactory.createType(
set,
substituteTypeParameter(lType, CommonClassNames.JAVA_UTIL_SET, 0, false)
)
}
return null
}
private fun getTupleType(expression: GrListOrMap): PsiType? {
val initializers = expression.initializers
return object : GrTupleType(expression.resolveScope, JavaPsiFacade.getInstance(expression.project)) {
override fun inferComponents(): Array<PsiType?> {
return initializers.flatMap {
doGetComponentTypes(it) ?: return PsiType.EMPTY_ARRAY
}.toTypedArray()
}
private fun doGetComponentTypes(initializer: GrExpression): Collection<PsiType>? {
return doPreventingRecursion(initializer, false) {
if (initializer is GrSpreadArgument) {
(initializer.argument.type as? GrTupleType)?.componentTypes?.toList()
}
else {
TypesUtil.boxPrimitiveType(initializer.type, initializer.manager, initializer.resolveScope)?.let { listOf(it) }
}
}
}
override fun isValid(): Boolean = initializers.all { it.isValid }
}
}
}
| apache-2.0 | daac64ec88bf67d7c7c728e7aa334aec | 41.266667 | 140 | 0.744029 | 4.575258 | false | false | false | false |
Heiner1/AndroidAPS | diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_1DAY.kt | 1 | 1753 | package info.nightscout.androidaps.diaconn.pumplog
import java.nio.ByteBuffer
import java.nio.ByteOrder
/*
* 당일 주입 총량 (식사, 추가)
*/
class LOG_INJECTION_1DAY private constructor(
val data: String,
val dttm: String,
typeAndKind: Byte, // 당일 식사주입 총량 47.5=4750
val mealAmount: Short, // 당일 추가주입 총량 47.5=4750
val extAmount: Short,
val batteryRemain: Byte
) {
val type: Byte = PumplogUtil.getType(typeAndKind)
val kind: Byte = PumplogUtil.getKind(typeAndKind)
override fun toString(): String {
val sb = StringBuilder("LOG_INJECTION_1DAY{")
sb.append("LOG_KIND=").append(LOG_KIND.toInt())
sb.append(", data='").append(data).append('\'')
sb.append(", dttm='").append(dttm).append('\'')
sb.append(", type=").append(type.toInt())
sb.append(", kind=").append(kind.toInt())
sb.append(", mealAmount=").append(mealAmount.toInt())
sb.append(", extAmount=").append(extAmount.toInt())
sb.append(", batteryRemain=").append(batteryRemain.toInt())
sb.append('}')
return sb.toString()
}
companion object {
const val LOG_KIND: Byte = 0x2F
fun parse(data: String): LOG_INJECTION_1DAY {
val bytes = PumplogUtil.hexStringToByteArray(data)
val buffer = ByteBuffer.wrap(bytes)
buffer.order(ByteOrder.LITTLE_ENDIAN)
return LOG_INJECTION_1DAY(
data,
PumplogUtil.getDttm(buffer),
PumplogUtil.getByte(buffer),
PumplogUtil.getShort(buffer),
PumplogUtil.getShort(buffer),
PumplogUtil.getByte(buffer)
)
}
}
} | agpl-3.0 | 14a146339cba1a468411e80d417da1a1 | 31.113208 | 67 | 0.596708 | 3.813901 | false | false | false | false |
Heiner1/AndroidAPS | wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.kt | 1 | 1489 | @file:Suppress("DEPRECATION")
package info.nightscout.androidaps.complications
import android.app.PendingIntent
import android.support.wearable.complications.ComplicationData
import android.support.wearable.complications.ComplicationText
import info.nightscout.androidaps.data.RawDisplayData
import info.nightscout.shared.logging.LTag
/*
* Created by dlvoy on 2019-11-12
*/
class IobDetailedComplication : BaseComplicationProviderService() {
override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? {
var complicationData: ComplicationData? = null
if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
val iob = displayFormat.detailedIob(raw)
val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
.setShortText(ComplicationText.plainText(iob.first))
.setTapAction(complicationPendingIntent)
if (iob.second.isNotEmpty()) {
builder.setShortTitle(ComplicationText.plainText(iob.second))
}
complicationData = builder.build()
} else {
aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
}
return complicationData
}
override fun getProviderCanonicalName(): String = IobDetailedComplication::class.java.canonicalName!!
override fun getComplicationAction(): ComplicationAction = ComplicationAction.BOLUS
} | agpl-3.0 | c177c222f23266f8939b879bba38c303 | 41.571429 | 137 | 0.732707 | 5.116838 | false | false | false | false |
Maccimo/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/FacetEntityImpl.kt | 2 | 15443 | package com.intellij.workspaceModel.storage.bridgeEntities.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableReferableWorkspaceEntity
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.SoftLinkable
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import com.intellij.workspaceModel.storage.referrersx
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class FacetEntityImpl: FacetEntity, WorkspaceEntityBase() {
companion object {
internal val MODULE_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, FacetEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false)
internal val UNDERLYINGFACET_CONNECTION_ID: ConnectionId = ConnectionId.create(FacetEntity::class.java, FacetEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
MODULE_CONNECTION_ID,
UNDERLYINGFACET_CONNECTION_ID,
)
}
@JvmField var _name: String? = null
override val name: String
get() = _name!!
override val module: ModuleEntity
get() = snapshot.extractOneToManyParent(MODULE_CONNECTION_ID, this)!!
@JvmField var _facetType: String? = null
override val facetType: String
get() = _facetType!!
@JvmField var _configurationXmlTag: String? = null
override val configurationXmlTag: String?
get() = _configurationXmlTag
@JvmField var _moduleId: ModuleId? = null
override val moduleId: ModuleId
get() = _moduleId!!
override val underlyingFacet: FacetEntity?
get() = snapshot.extractOneToManyParent(UNDERLYINGFACET_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: FacetEntityData?): ModifiableWorkspaceEntityBase<FacetEntity>(), FacetEntity.Builder {
constructor(): this(FacetEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity FacetEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isNameInitialized()) {
error("Field FacetEntity#name should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field FacetEntity#entitySource should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToManyParent<WorkspaceEntityBase>(MODULE_CONNECTION_ID, this) == null) {
error("Field FacetEntity#module should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] == null) {
error("Field FacetEntity#module should be initialized")
}
}
if (!getEntityData().isFacetTypeInitialized()) {
error("Field FacetEntity#facetType should be initialized")
}
if (!getEntityData().isModuleIdInitialized()) {
error("Field FacetEntity#moduleId should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData().name = value
changedProperty.add("name")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var module: ModuleEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(MODULE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity
} else {
this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(MODULE_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] = value
}
changedProperty.add("module")
}
override var facetType: String
get() = getEntityData().facetType
set(value) {
checkModificationAllowed()
getEntityData().facetType = value
changedProperty.add("facetType")
}
override var configurationXmlTag: String?
get() = getEntityData().configurationXmlTag
set(value) {
checkModificationAllowed()
getEntityData().configurationXmlTag = value
changedProperty.add("configurationXmlTag")
}
override var moduleId: ModuleId
get() = getEntityData().moduleId
set(value) {
checkModificationAllowed()
getEntityData().moduleId = value
changedProperty.add("moduleId")
}
override var underlyingFacet: FacetEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(UNDERLYINGFACET_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, UNDERLYINGFACET_CONNECTION_ID)] as? FacetEntity
} else {
this.entityLinks[EntityLink(false, UNDERLYINGFACET_CONNECTION_ID)] as? FacetEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(UNDERLYINGFACET_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, UNDERLYINGFACET_CONNECTION_ID)] = value
}
changedProperty.add("underlyingFacet")
}
override fun getEntityData(): FacetEntityData = result ?: super.getEntityData() as FacetEntityData
override fun getEntityClass(): Class<FacetEntity> = FacetEntity::class.java
}
}
class FacetEntityData : WorkspaceEntityData.WithCalculablePersistentId<FacetEntity>(), SoftLinkable {
lateinit var name: String
lateinit var facetType: String
var configurationXmlTag: String? = null
lateinit var moduleId: ModuleId
fun isNameInitialized(): Boolean = ::name.isInitialized
fun isFacetTypeInitialized(): Boolean = ::facetType.isInitialized
fun isModuleIdInitialized(): Boolean = ::moduleId.isInitialized
override fun getLinks(): Set<PersistentEntityId<*>> {
val result = HashSet<PersistentEntityId<*>>()
result.add(moduleId)
return result
}
override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
index.index(this, moduleId)
}
override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
// TODO verify logic
val mutablePreviousSet = HashSet(prev)
val removedItem_moduleId = mutablePreviousSet.remove(moduleId)
if (!removedItem_moduleId) {
index.index(this, moduleId)
}
for (removed in mutablePreviousSet) {
index.remove(this, removed)
}
}
override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean {
var changed = false
val moduleId_data = if (moduleId == oldLink) {
changed = true
newLink as ModuleId
}
else {
null
}
if (moduleId_data != null) {
moduleId = moduleId_data
}
return changed
}
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<FacetEntity> {
val modifiable = FacetEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): FacetEntity {
val entity = FacetEntityImpl()
entity._name = name
entity._facetType = facetType
entity._configurationXmlTag = configurationXmlTag
entity._moduleId = moduleId
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun persistentId(): PersistentEntityId<*> {
return FacetId(name, facetType, moduleId)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return FacetEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as FacetEntityData
if (this.name != other.name) return false
if (this.entitySource != other.entitySource) return false
if (this.facetType != other.facetType) return false
if (this.configurationXmlTag != other.configurationXmlTag) return false
if (this.moduleId != other.moduleId) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as FacetEntityData
if (this.name != other.name) return false
if (this.facetType != other.facetType) return false
if (this.configurationXmlTag != other.configurationXmlTag) return false
if (this.moduleId != other.moduleId) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + facetType.hashCode()
result = 31 * result + configurationXmlTag.hashCode()
result = 31 * result + moduleId.hashCode()
return result
}
} | apache-2.0 | 0df6bc0b50ae9a604ece47f6a63421da | 41.312329 | 183 | 0.604675 | 5.919126 | false | false | false | false |
android/renderscript-intrinsics-replacement-toolkit | test-app/src/main/java/com/google/android/renderscript_test/IntrinsicConvolve.kt | 1 | 4857 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.renderscript_test
import android.graphics.Bitmap
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.Script
import android.renderscript.ScriptIntrinsicConvolve3x3
import android.renderscript.ScriptIntrinsicConvolve5x5
import android.renderscript.Type
import com.google.android.renderscript.Range2d
/**
* Does a Convolve operation using the RenderScript Intrinsics.
*/
fun intrinsicConvolve(
context: RenderScript,
inputArray: ByteArray,
vectorSize: Int,
sizeX: Int,
sizeY: Int,
coefficients: FloatArray,
restriction: Range2d?
): ByteArray {
val baseElement = renderScriptVectorElementForU8(context, vectorSize)
val builder = Type.Builder(context, baseElement)
builder.setX(sizeX)
builder.setY(sizeY)
val arrayType = builder.create()
val inputAllocation = Allocation.createTyped(context, arrayType)
val outAllocation = Allocation.createTyped(context, arrayType)
inputAllocation.copyFrom(inputArray)
val intrinsicOutArray = ByteArray(sizeX * sizeY * paddedSize(vectorSize))
if (restriction != null) {
outAllocation.copyFrom(intrinsicOutArray) // To initialize to zero
}
invokeConvolveKernel(
coefficients,
context,
baseElement,
inputAllocation,
restriction,
outAllocation
)
outAllocation.copyTo(intrinsicOutArray)
inputAllocation.destroy()
outAllocation.destroy()
arrayType.destroy()
return intrinsicOutArray
}
fun intrinsicConvolve(
context: RenderScript,
bitmap: Bitmap,
coefficients: FloatArray,
restriction: Range2d?
): ByteArray {
val baseElement = renderScriptElementForBitmap(context, bitmap)
val inputAllocation = Allocation.createFromBitmap(context, bitmap)
val outAllocation = Allocation.createTyped(context, inputAllocation.type)
val intrinsicOutArray = ByteArray(bitmap.byteCount)
inputAllocation.copyFrom(bitmap)
if (restriction != null) {
outAllocation.copyFrom(intrinsicOutArray) // To initialize to zero
}
invokeConvolveKernel(
coefficients,
context,
baseElement,
inputAllocation,
restriction,
outAllocation
)
outAllocation.copyTo(intrinsicOutArray)
inputAllocation.destroy()
outAllocation.destroy()
return intrinsicOutArray
}
private fun invokeConvolveKernel(
coefficients: FloatArray,
context: RenderScript,
baseElement: Element,
inputAllocation: Allocation?,
restriction: Range2d?,
outAllocation: Allocation?
) {
when (coefficients.size) {
9 -> {
val scriptConvolve3x3 =
ScriptIntrinsicConvolve3x3.create(context, baseElement)
scriptConvolve3x3.setCoefficients(coefficients)
scriptConvolve3x3.setInput(inputAllocation)
if (restriction != null) {
val options = Script.LaunchOptions()
options.setX(restriction.startX, restriction.endX)
options.setY(restriction.startY, restriction.endY)
scriptConvolve3x3.forEach(outAllocation, options)
} else {
scriptConvolve3x3.forEach(outAllocation)
}
scriptConvolve3x3.destroy()
}
25 -> {
val scriptConvolve5x5 =
ScriptIntrinsicConvolve5x5.create(context, baseElement)
scriptConvolve5x5.setCoefficients(coefficients)
scriptConvolve5x5.setInput(inputAllocation)
if (restriction != null) {
val options = Script.LaunchOptions()
options.setX(restriction.startX, restriction.endX)
options.setY(restriction.startY, restriction.endY)
scriptConvolve5x5.forEach(outAllocation, options)
} else {
scriptConvolve5x5.forEach(outAllocation)
}
scriptConvolve5x5.destroy()
}
else -> {
throw IllegalArgumentException("RenderScriptToolkit tests. Only 3x3 and 5x5 convolutions are supported. ${coefficients.size} coefficients provided.")
}
}
}
| apache-2.0 | 2ee420f582e33e25f70913f49e8a50a4 | 33.692857 | 161 | 0.692403 | 4.621313 | false | false | false | false |
Hexworks/zircon | zircon.jvm.swing/src/main/kotlin/org/hexworks/zircon/internal/tileset/Java2DGraphicTileset.kt | 1 | 4471 | package org.hexworks.zircon.internal.tileset
import org.hexworks.cobalt.core.api.UUID
import org.hexworks.zircon.api.data.GraphicalTile
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.resource.TilesetResource
import org.hexworks.zircon.api.tileset.TileTexture
import org.hexworks.zircon.api.tileset.Tileset
import org.hexworks.zircon.internal.resource.TileType
import org.hexworks.zircon.internal.resource.TileType.*
import org.hexworks.zircon.internal.tileset.impl.DefaultTileTexture
import org.hexworks.zircon.internal.tileset.impl.GraphicTextureMetadata
import org.hexworks.zircon.internal.util.rex.unZipIt
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.constructor.Constructor
import java.awt.Graphics2D
import java.awt.image.BufferedImage
import java.io.File
import java.io.InputStream
import javax.imageio.ImageIO
@Suppress("unused", "DEPRECATION")
class Java2DGraphicTileset(private val resource: TilesetResource) : Tileset<Graphics2D> {
override val id: UUID = resource.id
override val targetType = Graphics2D::class
override val width: Int
get() = resource.width
override val height: Int
get() = resource.height
private val metadata: Map<String, GraphicTextureMetadata>
private val source: BufferedImage
init {
require(resource.tileType == GRAPHICAL_TILE) {
"Can't use a ${resource.tileType.name}-based TilesetResource for" +
" a GraphicTile-based tileset."
}
val resourceStream: InputStream = ImageLoader.readImageStream(resource)
val files: List<File> = unZipIt(resourceStream, createTempDir())
val tileInfoSource = files.first { it.name == "tileinfo.yml" }.bufferedReader().use {
it.readText()
}
val yaml = Yaml(Constructor(TileInfo::class.java))
val tileInfo: TileInfo = yaml.load(tileInfoSource) as TileInfo
// TODO: multi-file support
val imageData = tileInfo.files.first()
source = ImageIO.read(files.first { it.name == imageData.name })
metadata = imageData.tiles.mapIndexed { i, tileData: TileData ->
val (name, _, char) = tileData
val cleanName = name.toLowerCase().trim()
tileData.tags = tileData.tags
.plus(cleanName.split(" ").map { it }.toSet())
if (char == ' ') {
tileData.char = cleanName.first()
}
tileData.x = i.rem(imageData.tilesPerRow)
tileData.y = i.div(imageData.tilesPerRow)
tileData.name to GraphicTextureMetadata(
name = tileData.name,
tags = tileData.tags,
x = tileData.x,
y = tileData.y,
width = resource.width,
height = resource.height
)
}.toMap()
}
override fun drawTile(tile: Tile, surface: Graphics2D, position: Position) {
val texture = fetchTextureForTile(tile)
val x = position.x * width
val y = position.y * height
surface.drawImage(texture.texture, x, y, null)
}
private fun fetchTextureForTile(tile: Tile): TileTexture<BufferedImage> {
tile as? GraphicalTile ?: throw IllegalArgumentException("Wrong tile type")
return metadata[tile.name]?.let { meta ->
DefaultTileTexture(
width = width,
height = height,
texture = source.getSubimage(meta.x * width, meta.y * height, width, height),
cacheKey = tile.cacheKey
)
} ?: throw NoSuchElementException("No texture with name '${tile.name}'.")
}
data class TileInfo(
var name: String,
var size: Int,
var files: List<TileFile>
) {
constructor() : this(
name = "",
size = 0,
files = listOf()
)
}
data class TileFile(
var name: String,
var tilesPerRow: Int,
var tiles: List<TileData>
) {
constructor() : this(
name = "",
tilesPerRow = 0,
tiles = listOf()
)
}
data class TileData(
var name: String,
var tags: Set<String> = setOf(),
var char: Char = ' ',
var description: String = "",
var x: Int = -1,
var y: Int = -1
) {
constructor() : this(name = "")
}
}
| apache-2.0 | abdc9c8cf35c8bd32ee1b1557b8bc86e | 33.392308 | 93 | 0.616193 | 4.258095 | false | false | false | false |
DuncanCasteleyn/DiscordModBot | src/main/kotlin/be/duncanc/discordmodbot/bot/commands/RoleIds.kt | 1 | 2542 | /*
* Copyright 2018 Duncan Casteleyn
*
* 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 be.duncanc.discordmodbot.bot.commands
import be.duncanc.discordmodbot.data.services.UserBlockService
import net.dv8tion.jda.api.MessageBuilder
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.ChannelType
import net.dv8tion.jda.api.entities.Role
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import org.springframework.stereotype.Component
import java.util.concurrent.TimeUnit
/**
* Commands to get all role ids of the current guild where executed.
*/
@Component
class RoleIds(
userBlockService: UserBlockService
) : CommandModule(
ALIASES,
null,
DESCRIPTION,
userBlockService = userBlockService
) {
companion object {
private val ALIASES = arrayOf("RoleIds", "GetRoleIds")
private const val DESCRIPTION = "Get all the role ids of the guild where executed."
}
public override fun commandExec(event: MessageReceivedEvent, command: String, arguments: String?) {
if (!event.isFromType(ChannelType.TEXT)) {
event.channel.sendMessage("This command only works in a guild.")
.queue { message -> message.delete().queueAfter(1, TimeUnit.MINUTES) }
} else if (event.member?.hasPermission(Permission.MANAGE_ROLES) != true) {
event.channel.sendMessage(event.author.asMention + " you need manage roles permission to use this command.")
.queue { message -> message.delete().queueAfter(1, TimeUnit.MINUTES) }
} else {
val result = StringBuilder()
event.guild.roles.forEach { role: Role -> result.append(role.toString()).append("\n") }
event.author.openPrivateChannel().queue { privateChannel ->
val messages = MessageBuilder().append(result.toString()).buildAll(MessageBuilder.SplitPolicy.NEWLINE)
messages.forEach { message -> privateChannel.sendMessage(message).queue() }
}
}
}
}
| apache-2.0 | 250aad85284d126124d69c82454d2f2a | 40.672131 | 120 | 0.705744 | 4.35274 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/data/base/BaseTile.kt | 1 | 1582 | package org.hexworks.zircon.api.data.base
import org.hexworks.zircon.api.data.CharacterTile
import org.hexworks.zircon.api.data.GraphicalTile
import org.hexworks.zircon.api.data.ImageTile
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.modifier.Border
import org.hexworks.zircon.api.modifier.SimpleModifiers.*
/**
* Base class for all [Tile] implementations.
*/
abstract class BaseTile : Tile {
override val isOpaque: Boolean
get() = backgroundColor.isOpaque
override val isUnderlined: Boolean
get() = modifiers.contains(Underline)
override val isCrossedOut: Boolean
get() = modifiers.contains(CrossedOut)
override val isBlinking: Boolean
get() = modifiers.contains(Blink)
override val isVerticalFlipped: Boolean
get() = modifiers.contains(VerticalFlip)
override val isHorizontalFlipped: Boolean
get() = modifiers.contains(HorizontalFlip)
override val hasBorder: Boolean
get() = modifiers.any { it is Border }
override val isEmpty: Boolean
get() = this === Tile.empty()
override val isNotEmpty: Boolean
get() = this != Tile.empty()
override fun fetchBorderData(): Set<Border> = modifiers
.asSequence()
.filter { it is Border }
.map { it as Border }
.toSet()
override fun asCharacterTileOrNull(): CharacterTile? = this as? CharacterTile
override fun asImageTileOrNull(): ImageTile? = this as? ImageTile
override fun asGraphicalTileOrNull(): GraphicalTile? = this as? GraphicalTile
}
| apache-2.0 | aa3b29143c2b7bf1ffd2246c62eb751b | 27.25 | 81 | 0.701011 | 4.310627 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/prefs/categories/detail/CategoryDetailViewModel.kt | 1 | 5196 | package org.wordpress.android.ui.prefs.categories.detail
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineDispatcher
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode.MAIN
import org.wordpress.android.R
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.TaxonomyStore.OnTermUploaded
import org.wordpress.android.models.CategoryNode
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.ui.mysite.SelectedSiteRepository
import org.wordpress.android.ui.posts.AddCategoryUseCase
import org.wordpress.android.ui.posts.GetCategoriesUseCase
import org.wordpress.android.ui.prefs.categories.detail.CategoryUpdateUiState.Failure
import org.wordpress.android.ui.prefs.categories.detail.CategoryUpdateUiState.InProgress
import org.wordpress.android.ui.prefs.categories.detail.CategoryUpdateUiState.Success
import org.wordpress.android.ui.prefs.categories.detail.SubmitButtonUiState.SubmitButtonDisabledUiState
import org.wordpress.android.ui.prefs.categories.detail.SubmitButtonUiState.SubmitButtonEnabledUiState
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
import org.wordpress.android.util.NetworkUtilsWrapper
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ResourceProvider
import org.wordpress.android.viewmodel.ScopedViewModel
import javax.inject.Inject
import javax.inject.Named
class CategoryDetailViewModel @Inject constructor(
@Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher,
private val networkUtilsWrapper: NetworkUtilsWrapper,
private val getCategoriesUseCase: GetCategoriesUseCase,
private val addCategoryUseCase: AddCategoryUseCase,
resourceProvider: ResourceProvider,
private val dispatcher: Dispatcher,
selectedSiteRepository: SelectedSiteRepository
) : ScopedViewModel(bgDispatcher) {
private var isStarted = false
private val siteModel: SiteModel = requireNotNull(selectedSiteRepository.getSelectedSite())
private val topLevelCategory = CategoryNode(0, 0, resourceProvider.getString(R.string.top_level_category_name))
private val _onCategoryPush = MutableLiveData<Event<CategoryUpdateUiState>>()
val onCategoryPush: LiveData<Event<CategoryUpdateUiState>> = _onCategoryPush
private val _uiState: MutableLiveData<UiState> = MutableLiveData()
val uiState: LiveData<UiState> = _uiState
init {
dispatcher.register(this)
}
override fun onCleared() {
super.onCleared()
dispatcher.unregister(this)
}
fun start() {
if (isStarted) return
isStarted = true
initCategories()
}
private fun initCategories() {
launch {
val siteCategories = getCategoriesUseCase.getSiteCategories(siteModel)
siteCategories.add(0, topLevelCategory)
_uiState.postValue(
UiState(
categories = siteCategories,
selectedParentCategoryPosition = 0,
categoryName = ""
)
)
}
}
fun onSubmitButtonClick() {
_uiState.value?.let { state ->
addCategory(state.categoryName, state.categories[state.selectedParentCategoryPosition])
}
}
private fun addCategory(categoryText: String, parentCategory: CategoryNode) {
if (!networkUtilsWrapper.isNetworkAvailable()) {
_onCategoryPush.postValue(
Event(Failure(UiStringRes(R.string.no_network_message)))
)
return
}
launch {
_onCategoryPush.postValue(Event(InProgress))
addCategoryUseCase.addCategory(categoryText, parentCategory.categoryId, siteModel)
}
}
fun onCategoryNameUpdated(inputValue: String) {
uiState.value?.let { state ->
val submitButtonUiState = if (inputValue.isNotEmpty()) {
SubmitButtonEnabledUiState
} else {
SubmitButtonDisabledUiState
}
_uiState.value = state.copy(
categoryName = inputValue,
submitButtonUiState = submitButtonUiState
)
}
}
fun onParentCategorySelected(position: Int) {
_uiState.value?.let { state ->
_uiState.value = state.copy(selectedParentCategoryPosition = position)
}
}
@Suppress("unused")
@Subscribe(threadMode = MAIN)
fun onTermUploaded(event: OnTermUploaded) {
if (event.isError) AppLog.e(
T.SETTINGS,
"An error occurred while uploading taxonomy with type: " + event.error.type
)
val categoryUiState = if (event.isError) {
Failure(UiStringRes(R.string.adding_cat_failed))
} else {
Success(UiStringRes(R.string.adding_cat_success))
}
_onCategoryPush.postValue(Event(categoryUiState))
}
}
| gpl-2.0 | 633ba70018d9796ad95007608a6dc9b8 | 37.488889 | 115 | 0.704003 | 4.948571 | false | false | false | false |
abeemukthees/Arena | spectacle/src/main/java/com/abhi/spectacle/scrollingdetail/ScrollingDetailActivity.kt | 1 | 2271 | package com.abhi.spectacle.scrollingdetail
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.ViewTreeObserver
import android.widget.ImageView
import android.widget.TextView
import com.abhi.spectacle.R
import com.abhi.spectacle.epoxy.KotlinEpoxyModel
import com.abhi.spectacle.utilities.loadUrl
import kotlinx.android.synthetic.main.activity_scrolling_detail.*
class ScrollingDetailActivity : AppCompatActivity() {
private val TAG = ScrollingDetailActivity::class.simpleName
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_scrolling_detail)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
window.decorView.setOnApplyWindowInsetsListener { v, insets ->
val height = insets.systemWindowInsetTop // status bar height
//Log.d(TAG,"1st statusbarHeight = $height")
toolbar_layout.scrimVisibleHeightTrigger = height + 4
insets
}
collapsingToolbarLayout_image.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
val measuredHeight = collapsingToolbarLayout_image.measuredHeight
val lp = toolbar_layout.layoutParams
lp.height = measuredHeight
toolbar_layout.layoutParams = lp
collapsingToolbarLayout_image.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
})
image_hero.loadUrl("https://i.imgur.com/oHgo3o9.jpg")
epoxyRecyclerView_detail.buildModelsWith {
DetailBasicView("1234").id(1).addTo(it)
DetailBasicView("1234").id(2).addTo(it)
}
}
}
data class DetailBasicView(val price: String) : KotlinEpoxyModel(R.layout.item_scrolling_detail) {
private val priceTextView by bind<TextView>(R.id.text_price)
private val imageView by bind<ImageView>(R.id.image_hero)
override fun bind() {
priceTextView.text = price
//imageView.loadUrl("https://i.imgur.com/oHgo3o9.jpg")
}
} | apache-2.0 | ec9d3cea9c860b62240759431a96e228 | 31.927536 | 131 | 0.706737 | 4.821656 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/pisa/PisaLookup.kt | 1 | 1624 | /*
* PisaLookup.kt
*
* Copyright 2018-2019 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.pisa
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.transit.TransitCurrency
import au.id.micolous.metrodroid.transit.Trip
import au.id.micolous.metrodroid.transit.en1545.En1545LookupSTR
object PisaLookup : En1545LookupSTR("pisa") {
@Suppress("UNUSED_PARAMETER")
fun subscriptionUsesCounter(agency: Int?, contractTariff: Int?) = contractTariff !in listOf(316, 317, 385)
override fun parseCurrency(price: Int) = TransitCurrency.EUR(price)
override val timeZone get() = MetroTimeZone.ROME
override fun getMode(agency: Int?, route: Int?) = Trip.Mode.OTHER
override val subscriptionMap = mapOf(
316 to R.string.pisa_abb_ann_pers_pisa_sbe,
317 to R.string.pisa_abb_mens_pers_pisa_sbe,
322 to R.string.pisa_carnet_10_bgl_70_min_pisa,
385 to R.string.pisa_abb_trim_pers_pisa
)
}
| gpl-3.0 | 036a9da77660f63e5915be85dc7997ad | 35.909091 | 107 | 0.759236 | 3.477516 | false | false | false | false |
spinnaker/orca | keiko-redis/src/main/kotlin/com/netflix/spinnaker/q/redis/RedisQueue.kt | 1 | 13851 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.q.redis
import arrow.core.partially1
import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.databind.ObjectMapper
import com.netflix.spinnaker.KotlinOpen
import com.netflix.spinnaker.q.AttemptsAttribute
import com.netflix.spinnaker.q.DeadMessageCallback
import com.netflix.spinnaker.q.MaxAttemptsAttribute
import com.netflix.spinnaker.q.Message
import com.netflix.spinnaker.q.Queue
import com.netflix.spinnaker.q.QueueCallback
import com.netflix.spinnaker.q.metrics.EventPublisher
import com.netflix.spinnaker.q.metrics.LockFailed
import com.netflix.spinnaker.q.metrics.MessageAcknowledged
import com.netflix.spinnaker.q.metrics.MessageDead
import com.netflix.spinnaker.q.metrics.MessageDuplicate
import com.netflix.spinnaker.q.metrics.MessageNotFound
import com.netflix.spinnaker.q.metrics.MessageProcessing
import com.netflix.spinnaker.q.metrics.MessagePushed
import com.netflix.spinnaker.q.metrics.MessageRescheduled
import com.netflix.spinnaker.q.metrics.MessageRetried
import com.netflix.spinnaker.q.metrics.QueuePolled
import com.netflix.spinnaker.q.metrics.QueueState
import com.netflix.spinnaker.q.metrics.RetryPolled
import com.netflix.spinnaker.q.migration.SerializationMigrator
import java.io.IOException
import java.time.Clock
import java.time.Duration
import java.time.Instant
import java.time.temporal.TemporalAmount
import java.util.Locale
import java.util.Optional
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import redis.clients.jedis.Jedis
import redis.clients.jedis.commands.ScriptingCommands
import redis.clients.jedis.exceptions.JedisDataException
import redis.clients.jedis.params.ZAddParams.zAddParams
import redis.clients.jedis.util.Pool
@KotlinOpen
class RedisQueue(
private val queueName: String,
private val pool: Pool<Jedis>,
private val clock: Clock,
private val lockTtlSeconds: Int = 10,
private val mapper: ObjectMapper,
private val serializationMigrator: Optional<SerializationMigrator>,
override val ackTimeout: TemporalAmount = Duration.ofMinutes(1),
override val deadMessageHandlers: List<DeadMessageCallback>,
override val canPollMany: Boolean = false,
override val publisher: EventPublisher
) : AbstractRedisQueue(
clock,
lockTtlSeconds,
mapper,
serializationMigrator,
ackTimeout,
deadMessageHandlers,
canPollMany,
publisher
) {
final override val log: Logger = LoggerFactory.getLogger(javaClass)
override val queueKey = "$queueName.queue"
override val unackedKey = "$queueName.unacked"
override val messagesKey = "$queueName.messages"
override val locksKey = "$queueName.locks"
override val attemptsKey = "$queueName.attempts"
override lateinit var readMessageWithLockScriptSha: String
init {
cacheScript()
log.info("Configured $javaClass queue: $queueName")
}
final override fun cacheScript() {
pool.resource.use { redis ->
readMessageWithLockScriptSha = redis.scriptLoad(READ_MESSAGE_WITH_LOCK_SRC)
}
}
override fun poll(callback: (Message, () -> Unit) -> Unit) {
pool.resource.use { redis ->
redis.readMessageWithLock()
?.also { (fingerprint, scheduledTime, json) ->
val ack = this::ackMessage.partially1(fingerprint)
redis.readMessage(fingerprint, json) { message ->
val attempts = message.getAttribute<AttemptsAttribute>()?.attempts
?: 0
val maxAttempts = message.getAttribute<MaxAttemptsAttribute>()?.maxAttempts
?: 0
if (maxAttempts > 0 && attempts > maxAttempts) {
log.warn("Message $fingerprint with payload $message exceeded $maxAttempts retries")
handleDeadMessage(message)
redis.removeMessage(fingerprint)
fire(MessageDead)
} else {
fire(MessageProcessing(message, scheduledTime, clock.instant()))
callback(message, ack)
}
}
}
fire(QueuePolled)
}
}
override fun poll(maxMessages: Int, callback: QueueCallback) {
poll(callback)
}
override fun push(message: Message, delay: TemporalAmount) {
pool.resource.use { redis ->
redis.firstFingerprint(queueKey, message.fingerprint()).also { fingerprint ->
if (fingerprint != null) {
log.info(
"Re-prioritizing message as an identical one is already on the queue: " +
"$fingerprint, message: $message"
)
redis.zadd(queueKey, score(delay), fingerprint, zAddParams().xx())
fire(MessageDuplicate(message))
} else {
redis.queueMessage(message, delay)
fire(MessagePushed(message))
}
}
}
}
override fun reschedule(message: Message, delay: TemporalAmount) {
pool.resource.use { redis ->
val fingerprint = message.fingerprint().latest
log.debug("Re-scheduling message: $message, fingerprint: $fingerprint to deliver in $delay")
val status: Long = redis.zadd(queueKey, score(delay), fingerprint, zAddParams().xx())
if (status.toInt() == 1) {
fire(MessageRescheduled(message))
} else {
fire(MessageNotFound(message))
}
}
}
override fun ensure(message: Message, delay: TemporalAmount) {
pool.resource.use { redis ->
val fingerprint = message.fingerprint()
if (!redis.anyZismember(queueKey, fingerprint.all) &&
!redis.anyZismember(unackedKey, fingerprint.all)
) {
log.debug(
"Pushing ensured message onto queue as it does not exist in queue or unacked sets"
)
push(message, delay)
}
}
}
@Scheduled(fixedDelayString = "\${queue.retry.frequency.ms:10000}")
override fun retry() {
pool.resource.use { redis ->
redis
.zrangeByScore(unackedKey, 0.0, score())
.let { fingerprints ->
if (fingerprints.size > 0) {
fingerprints
.map { "$locksKey:$it" }
.let { redis.del(*it.toTypedArray()) }
}
fingerprints.forEach { fingerprint ->
val attempts = redis.hgetInt(attemptsKey, fingerprint)
redis.readMessageWithoutLock(fingerprint) { message ->
val maxAttempts = message.getAttribute<MaxAttemptsAttribute>()?.maxAttempts ?: 0
/* If maxAttempts attribute is set, let poll() handle max retry logic.
If not, check for attempts >= Queue.maxRetries - 1, as attemptsKey is now
only incremented when retrying unacked messages vs. by readMessage*() */
if (maxAttempts == 0 && attempts >= Queue.maxRetries - 1) {
log.warn("Message $fingerprint with payload $message exceeded max retries")
handleDeadMessage(message)
redis.removeMessage(fingerprint)
fire(MessageDead)
} else {
if (redis.zismember(queueKey, fingerprint)) {
redis
.multi {
zrem(unackedKey, fingerprint)
zadd(queueKey, score(), fingerprint)
hincrBy(attemptsKey, fingerprint, 1L)
}
log.info(
"Not retrying message $fingerprint because an identical message " +
"is already on the queue"
)
fire(MessageDuplicate(message))
} else {
log.warn("Retrying message $fingerprint after $attempts attempts")
redis.hincrBy(attemptsKey, fingerprint, 1L)
redis.requeueMessage(fingerprint)
fire(MessageRetried)
}
}
}
}
}
.also {
fire(RetryPolled)
}
}
}
override fun readState(): QueueState =
pool.resource.use { redis ->
redis.multi {
zcard(queueKey)
zcount(queueKey, 0.0, score())
zcard(unackedKey)
hlen(messagesKey)
}
.map { (it as Long).toInt() }
.let { (queued, ready, processing, messages) ->
return QueueState(
depth = queued,
ready = ready,
unacked = processing,
orphaned = messages - (queued + processing)
)
}
}
override fun containsMessage(predicate: (Message) -> Boolean): Boolean =
pool.resource.use { redis ->
var found = false
var cursor = "0"
while (!found) {
redis.hscan(messagesKey, cursor).apply {
found = result
.map { mapper.readValue<Message>(it.value) }
.any(predicate)
cursor = getCursor()
}
if (cursor == "0") break
}
return found
}
override fun toString() = "RedisQueue[$queueName]"
private fun ackMessage(fingerprint: String) {
pool.resource.use { redis ->
if (redis.zismember(queueKey, fingerprint)) {
// only remove this message from the unacked queue as a matching one has
// been put on the main queue
redis.multi {
zrem(unackedKey, fingerprint)
del("$locksKey:$fingerprint")
}
} else {
redis.removeMessage(fingerprint)
}
fire(MessageAcknowledged)
}
}
internal fun Jedis.queueMessage(message: Message, delay: TemporalAmount = Duration.ZERO) {
val fingerprint = message.fingerprint().latest
// ensure the message has the attempts tracking attribute
message.setAttribute(
message.getAttribute() ?: AttemptsAttribute()
)
multi {
hset(messagesKey, fingerprint, mapper.writeValueAsString(message))
zadd(queueKey, score(delay), fingerprint)
}
}
internal fun Jedis.requeueMessage(fingerprint: String) {
multi {
zrem(unackedKey, fingerprint)
zadd(queueKey, score(), fingerprint)
}
}
internal fun Jedis.removeMessage(fingerprint: String) {
multi {
zrem(queueKey, fingerprint)
zrem(unackedKey, fingerprint)
hdel(messagesKey, fingerprint)
del("$locksKey:$fingerprint")
hdel(attemptsKey, fingerprint)
}
}
internal fun Jedis.readMessageWithoutLock(fingerprint: String, block: (Message) -> Unit) {
try {
hget(messagesKey, fingerprint)
.let {
val message = mapper.readValue<Message>(runSerializationMigration(it))
block.invoke(message)
}
} catch (e: IOException) {
log.error("Failed to read unacked message $fingerprint, requeuing...", e)
hincrBy(attemptsKey, fingerprint, 1L)
requeueMessage(fingerprint)
} catch (e: JsonParseException) {
log.error("Payload for unacked message $fingerprint is missing or corrupt", e)
removeMessage(fingerprint)
}
}
internal fun ScriptingCommands.readMessageWithLock(): Triple<String, Instant, String?>? {
try {
val response = evalsha(
readMessageWithLockScriptSha,
listOf(
queueKey,
unackedKey,
locksKey,
messagesKey
),
listOf(
score().toString(),
10.toString(), // TODO rz - make this configurable.
lockTtlSeconds.toString(),
java.lang.String.format(Locale.US, "%f", score(ackTimeout)),
java.lang.String.format(Locale.US, "%f", score())
)
)
if (response is List<*>) {
return Triple(
response[0].toString(), // fingerprint
Instant.ofEpochMilli(response[1].toString().toLong()), // fingerprintScore
response[2]?.toString() // message
)
}
if (response == "ReadLockFailed") {
// This isn't a "bad" thing, but means there's more work than keiko can process in a cycle
// in this case, but may be a signal to tune `peekFingerprintCount`
fire(LockFailed)
}
} catch (e: JedisDataException) {
if ((e.message ?: "").startsWith("NOSCRIPT")) {
cacheScript()
return readMessageWithLock()
} else {
throw e
}
}
return null
}
/**
* Tries to read the message with the specified [fingerprint] passing it to
* [block]. If it's not accessible for whatever reason any references are
* cleaned up.
*/
internal fun Jedis.readMessage(fingerprint: String, json: String?, block: (Message) -> Unit) {
if (json == null) {
log.error("Payload for message $fingerprint is missing")
// clean up what is essentially an unrecoverable message
removeMessage(fingerprint)
} else {
try {
val message = mapper.readValue<Message>(runSerializationMigration(json))
.apply {
val currentAttempts = (getAttribute() ?: AttemptsAttribute())
.run { copy(attempts = attempts + 1) }
setAttribute(currentAttempts)
}
hset(messagesKey, fingerprint, mapper.writeValueAsString(message))
block.invoke(message)
} catch (e: IOException) {
log.error("Failed to read message $fingerprint, requeuing...", e)
hincrBy(attemptsKey, fingerprint, 1L)
requeueMessage(fingerprint)
}
}
}
}
| apache-2.0 | aa00bfca6fa09330ef25bc5806232424 | 33.369727 | 98 | 0.642264 | 4.426654 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantLetInspection.kt | 1 | 12353 | // 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.inspections
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.idea.base.psi.isMultiLine
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.base.psi.textRangeIn
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.codeinsight.utils.getLeftMostReceiverExpression
import org.jetbrains.kotlin.idea.codeinsight.utils.replaceFirstReceiver
import org.jetbrains.kotlin.idea.inspections.collections.isCalling
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.intentions.deleteFirstReceiver
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getReferenceTargets
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.isNullable
private val KOTLIN_LET_FQ_NAME = FqName("kotlin.let")
abstract class RedundantLetInspection : AbstractApplicabilityBasedInspection<KtCallExpression>(
KtCallExpression::class.java
) {
override fun inspectionText(element: KtCallExpression) = KotlinBundle.message("redundant.let.call.could.be.removed")
final override fun inspectionHighlightRangeInElement(element: KtCallExpression) = element.calleeExpression?.textRangeIn(element)
final override val defaultFixText get() = KotlinBundle.message("remove.let.call")
final override fun isApplicable(element: KtCallExpression): Boolean {
if (!element.isCalling(KOTLIN_LET_FQ_NAME)) return false
val lambdaExpression = element.lambdaArguments.firstOrNull()?.getLambdaExpression() ?: return false
val parameterName = lambdaExpression.getParameterName() ?: return false
return isApplicable(
element,
lambdaExpression.bodyExpression?.children?.singleOrNull() ?: return false,
lambdaExpression,
parameterName
)
}
protected abstract fun isApplicable(
element: KtCallExpression,
bodyExpression: PsiElement,
lambdaExpression: KtLambdaExpression,
parameterName: String
): Boolean
final override fun applyTo(element: KtCallExpression, project: Project, editor: Editor?) {
val lambdaExpression = element.lambdaArguments.firstOrNull()?.getLambdaExpression() ?: return
when (val bodyExpression = lambdaExpression.bodyExpression?.children?.singleOrNull() ?: return) {
is KtDotQualifiedExpression -> bodyExpression.applyTo(element)
is KtBinaryExpression -> bodyExpression.applyTo(element)
is KtCallExpression -> bodyExpression.applyTo(element, lambdaExpression.functionLiteral, editor)
is KtSimpleNameExpression -> deleteCall(element)
}
}
}
class SimpleRedundantLetInspection : RedundantLetInspection() {
override fun isApplicable(
element: KtCallExpression,
bodyExpression: PsiElement,
lambdaExpression: KtLambdaExpression,
parameterName: String
): Boolean = when (bodyExpression) {
is KtDotQualifiedExpression -> bodyExpression.isApplicable(parameterName)
is KtSimpleNameExpression -> bodyExpression.text == parameterName
else -> false
}
}
class ComplexRedundantLetInspection : RedundantLetInspection() {
override fun isApplicable(
element: KtCallExpression,
bodyExpression: PsiElement,
lambdaExpression: KtLambdaExpression,
parameterName: String
): Boolean = when (bodyExpression) {
is KtBinaryExpression ->
element.parent !is KtSafeQualifiedExpression && bodyExpression.isApplicable(parameterName)
is KtCallExpression ->
if (element.parent is KtSafeQualifiedExpression) {
false
} else {
val references = lambdaExpression.functionLiteral.valueParameterReferences(bodyExpression)
val destructuringDeclaration = lambdaExpression.functionLiteral.valueParameters.firstOrNull()?.destructuringDeclaration
references.isEmpty() || (references.singleOrNull()?.takeIf { expression ->
expression.parents.takeWhile { it != lambdaExpression.functionLiteral }.find { it is KtFunction } == null
} != null && destructuringDeclaration == null)
}
else ->
false
}
override fun inspectionHighlightType(element: KtCallExpression): ProblemHighlightType = if (isSingleLine(element))
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
else
ProblemHighlightType.INFORMATION
}
private fun KtBinaryExpression.applyTo(element: KtCallExpression) {
val left = left ?: return
val factory = KtPsiFactory(element.project)
when (val parent = element.parent) {
is KtQualifiedExpression -> {
val receiver = parent.receiverExpression
val newLeft = when (left) {
is KtDotQualifiedExpression -> left.replaceFirstReceiver(factory, receiver, parent is KtSafeQualifiedExpression)
else -> receiver
}
val newExpression = factory.createExpressionByPattern("$0 $1 $2", newLeft, operationReference, right!!)
parent.replace(newExpression)
}
else -> {
val newLeft = when (left) {
is KtDotQualifiedExpression -> left.deleteFirstReceiver()
else -> factory.createThisExpression()
}
val newExpression = factory.createExpressionByPattern("$0 $1 $2", newLeft, operationReference, right!!)
element.replace(newExpression)
}
}
}
private fun KtDotQualifiedExpression.applyTo(element: KtCallExpression) {
when (val parent = element.parent) {
is KtQualifiedExpression -> {
val factory = KtPsiFactory(element.project)
val receiver = parent.receiverExpression
parent.replace(replaceFirstReceiver(factory, receiver, parent is KtSafeQualifiedExpression))
}
else -> {
element.replace(deleteFirstReceiver())
}
}
}
private fun deleteCall(element: KtCallExpression) {
val parent = element.parent as? KtQualifiedExpression
if (parent != null) {
val replacement = parent.selectorExpression?.takeIf { it != element } ?: parent.receiverExpression
parent.replace(replacement)
} else {
element.delete()
}
}
private fun KtCallExpression.applyTo(element: KtCallExpression, functionLiteral: KtFunctionLiteral, editor: Editor?) {
val parent = element.parent as? KtQualifiedExpression
val reference = functionLiteral.valueParameterReferences(this).firstOrNull()
val replaced = if (parent != null) {
reference?.replace(parent.receiverExpression)
parent.replaced(this)
} else {
reference?.replace(KtPsiFactory(this).createThisExpression())
element.replaced(this)
}
editor?.caretModel?.moveToOffset(replaced.startOffset)
}
private fun KtBinaryExpression.isApplicable(parameterName: String, isTopLevel: Boolean = true): Boolean {
val left = left ?: return false
if (isTopLevel) {
when (left) {
is KtNameReferenceExpression -> if (left.text != parameterName) return false
is KtDotQualifiedExpression -> if (!left.isApplicable(parameterName)) return false
else -> return false
}
} else {
if (!left.isApplicable(parameterName)) return false
}
val right = right ?: return false
return right.isApplicable(parameterName)
}
private fun KtExpression.isApplicable(parameterName: String): Boolean = when (this) {
is KtNameReferenceExpression -> text != parameterName
is KtDotQualifiedExpression -> !hasLambdaExpression() && !nameUsed(parameterName)
is KtBinaryExpression -> isApplicable(parameterName, isTopLevel = false)
is KtCallExpression -> isApplicable(parameterName)
is KtConstantExpression -> true
else -> false
}
private fun KtCallExpression.isApplicable(parameterName: String): Boolean {
if (valueArguments.isEmpty()) return false
return valueArguments.all {
val argumentExpression = it.getArgumentExpression() ?: return@all false
argumentExpression.isApplicable(parameterName)
}
}
private fun KtDotQualifiedExpression.isApplicable(parameterName: String): Boolean {
val context by lazy { analyze(BodyResolveMode.PARTIAL) }
return !hasLambdaExpression() && getLeftMostReceiverExpression().let { receiver ->
receiver is KtNameReferenceExpression &&
receiver.getReferencedName() == parameterName &&
!nameUsed(parameterName, except = receiver)
} && callExpression?.getResolvedCall(context) !is VariableAsFunctionResolvedCall && !hasNullableReceiverExtensionCall(context)
}
private fun KtDotQualifiedExpression.hasNullableReceiverExtensionCall(context: BindingContext): Boolean {
val descriptor = selectorExpression?.getResolvedCall(context)?.resultingDescriptor as? CallableMemberDescriptor ?: return false
if (descriptor.extensionReceiverParameter?.type?.isNullable() == true) return true
return (KtPsiUtil.deparenthesize(receiverExpression) as? KtDotQualifiedExpression)?.hasNullableReceiverExtensionCall(context) == true
}
private fun KtDotQualifiedExpression.hasLambdaExpression() = selectorExpression?.anyDescendantOfType<KtLambdaExpression>() ?: false
private fun KtLambdaExpression.getParameterName(): String? {
val parameters = valueParameters
if (parameters.size > 1) return null
return if (parameters.size == 1) parameters[0].text else "it"
}
private fun KtExpression.nameUsed(name: String, except: KtNameReferenceExpression? = null): Boolean =
anyDescendantOfType<KtNameReferenceExpression> { it != except && it.getReferencedName() == name }
private fun KtFunctionLiteral.valueParameterReferences(callExpression: KtCallExpression): List<KtNameReferenceExpression> {
val context = analyze(BodyResolveMode.PARTIAL)
val parameterDescriptor = context[BindingContext.FUNCTION, this]?.valueParameters?.singleOrNull() ?: return emptyList()
val variableDescriptorByName = if (parameterDescriptor is ValueParameterDescriptorImpl.WithDestructuringDeclaration)
parameterDescriptor.destructuringVariables.associateBy { it.name }
else
mapOf(parameterDescriptor.name to parameterDescriptor)
val callee = (callExpression.calleeExpression as? KtNameReferenceExpression)?.let {
val descriptor = variableDescriptorByName[it.getReferencedNameAsName()]
if (descriptor != null && it.getReferenceTargets(context).singleOrNull() == descriptor) listOf(it) else null
} ?: emptyList()
return callee + callExpression.valueArguments.flatMap { arg ->
arg.collectDescendantsOfType<KtNameReferenceExpression>().filter {
val descriptor = variableDescriptorByName[it.getReferencedNameAsName()]
descriptor != null && it.getResolvedCall(context)?.resultingDescriptor == descriptor
}
}
}
private fun isSingleLine(element: KtCallExpression): Boolean {
val qualifiedExpression = element.getQualifiedExpressionForSelector() ?: return true
var receiver = qualifiedExpression.receiverExpression
if (receiver.isMultiLine()) return false
var count = 1
while (true) {
if (count > 2) return false
receiver = (receiver as? KtQualifiedExpression)?.receiverExpression ?: break
count++
}
return true
}
| apache-2.0 | 06fde6babb3411808bfe8f20c67a1e89 | 45.265918 | 137 | 0.730754 | 5.604809 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/ScriptTemplatesProvider.kt | 7 | 1814 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("PackageDirectoryMismatch")
package org.jetbrains.kotlin.script
import com.intellij.openapi.extensions.ExtensionPointName
import java.io.File
import kotlin.script.experimental.dependencies.DependenciesResolver
@Deprecated("Use ScriptDefinitionContributor EP and loadDefinitionsFromTemplates top level function")
internal interface ScriptTemplatesProvider {
// for resolving ambiguities
val id: String
@Deprecated("Parameter isn't used for resolving priorities anymore. " +
"com.intellij.openapi.extensions.LoadingOrder constants can be used to order providers when registered from Intellij plugin.",
ReplaceWith("0"))
val version: Int
get() = 0
val isValid: Boolean
val templateClassNames: Iterable<String>
val resolver: DependenciesResolver? get() = null
val filePattern: String? get() = null
val templateClasspath: List<File>
// TODO: need to provide a way to specify this in compiler/repl .. etc
/*
* Allows to specify additional jars needed for DependenciesResolver (and not script template).
* Script template dependencies naturally become (part of) dependencies of the script which is not always desired for resolver dependencies.
* i.e. gradle resolver may depend on some jars that 'built.gradle.kts' files should not depend on.
*/
val additionalResolverClasspath: List<File> get() = emptyList()
val environment: Map<String, Any?>?
companion object {
val EP_NAME: ExtensionPointName<ScriptTemplatesProvider> =
ExtensionPointName.create<ScriptTemplatesProvider>("org.jetbrains.kotlin.scriptTemplatesProvider")
}
}
| apache-2.0 | 92c287fba5f0f11afe67d9cc20fad65c | 37.595745 | 144 | 0.737596 | 4.997245 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/TaskResult.kt | 7 | 4506 | // 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.tools.projectWizard.core
sealed class TaskResult<out T : Any>
data class Success<T : Any>(val value: T) : TaskResult<T>()
data class Failure(val errors: List<Error>) : TaskResult<Nothing>() {
constructor(vararg errors: Error) : this(errors.toList())
}
val TaskResult<Any>.isSuccess
get() = this is Success<*>
fun <T : Any> success(value: T): TaskResult<T> =
Success(value)
fun <T : Any> failure(vararg errors: Error): TaskResult<T> =
Failure(*errors)
val <T : Any> TaskResult<T>.asNullable: T?
get() = safeAs<Success<T>>()?.value
inline fun <T : Any> TaskResult<T>.onSuccess(action: (T) -> Unit) = also {
if (this is Success<T>) {
action(value)
}
}
inline fun <T : Any> TaskResult<T>.onFailure(handler: (List<Error>) -> Unit) = apply {
if (this is Failure) {
handler(errors)
}
}
inline fun <A : Any, B : Any, R : Any> TaskResult<A>.mappend(
other: TaskResult<B>,
op: (A, B) -> R
): TaskResult<R> = mappendM(other) { a, b -> success(op(a, b)) }
@Suppress("UNCHECKED_CAST")
inline fun <A : Any, B : Any, R : Any> TaskResult<A>.mappendM(
other: TaskResult<B>,
op: (A, B) -> TaskResult<R>
): TaskResult<R> = when {
this is Success<*> && other is Success<*> -> op(value as A, other.value as B)
this is Success<*> && other is Failure -> other
this is Failure && other is Success<*> -> this
this is Failure && other is Failure -> Failure(errors + other.errors)
else -> error("Can not happen")
}
infix fun <T : Any> TaskResult<*>.andThen(other: TaskResult<T>): TaskResult<T> =
mappendM(other) { _, _ -> other }
infix fun <T : Any> TaskResult<T>.andThenIgnoring(other: TaskResult<Unit>): TaskResult<T> =
mappendM(other) { _, _ -> this }
operator fun <T : Any> TaskResult<List<T>>.plus(other: TaskResult<List<T>>): TaskResult<Unit> =
mappend(other) { _, _ -> Unit }
fun <T : Any> T?.toResult(failure: () -> Error): TaskResult<T> =
this?.let { Success(it) } ?: Failure(
failure()
)
fun <T : Any> T.asSuccess(): Success<T> =
Success(this)
inline fun <T : Any> TaskResult<T>.raise(returnExpression: (Failure) -> (Unit)): T =
when (this) {
is Failure -> {
returnExpression(this)
error("fail should return out of the function")
}
is Success -> value
}
fun <T : Any> Iterable<TaskResult<T>>.sequence(): TaskResult<List<T>> =
fold(success(emptyList())) { acc, result ->
acc.mappend(result) { a, r -> a + r }
}
fun <T : Any> Iterable<TaskResult<T>>.sequenceIgnore(): TaskResult<Unit> =
fold<TaskResult<T>, TaskResult<Unit>>(UNIT_SUCCESS) { acc, result ->
acc.mappend(result) { _, _ -> Unit }
}
fun <T : Any> Iterable<T>.mapSequenceIgnore(f: (T) -> TaskResult<*>): TaskResult<Unit> =
fold<T, TaskResult<Unit>>(UNIT_SUCCESS) { acc, result ->
acc.mappend(f(result)) { _, _ -> Unit }
}
fun <T : Any, R : Any> Iterable<T>.mapSequence(f: (T) -> TaskResult<R>): TaskResult<List<R>> =
map(f).sequence()
fun <T : Any> Sequence<TaskResult<T>>.sequenceFailFirst(): TaskResult<List<T>> =
fold(success(emptyList())) { acc, result ->
if (acc.isSuccess) acc.mappend(result) { a, r -> a + r }
else acc
}
fun <T : Any, R : Any> TaskResult<T>.map(f: (T) -> R): TaskResult<R> = when (this) {
is Failure -> this
is Success<T> -> Success(f(value))
}
fun <T : Any> TaskResult<T>.mapFailure(f: (List<Error>) -> Error): TaskResult<T> = when (this) {
is Failure -> Failure(f(errors))
is Success<T> -> this
}
fun <T : Any> TaskResult<T>.recover(f: (Failure) -> TaskResult<T>): TaskResult<T> = when (this) {
is Failure -> f(this)
is Success<T> -> this
}
fun <T : Any, R : Any> TaskResult<T>.flatMap(f: (T) -> TaskResult<R>): TaskResult<R> = when (this) {
is Failure -> this
is Success<T> -> f(value)
}
fun <T : Any> TaskResult<T>.withAssert(assertion: (T) -> Error?): TaskResult<T> = when (this) {
is Failure -> this
is Success<T> -> assertion(value)?.let { Failure(it) } ?: this
}
fun <T : Any> TaskResult<T>.getOrElse(default: () -> T): T = when (this) {
is Success<T> -> value
is Failure -> default()
}
fun <T : Any> TaskResult<T>.ignore(): TaskResult<Unit> = when (this) {
is Failure -> this
is Success<T> -> UNIT_SUCCESS
}
val UNIT_SUCCESS = Success(Unit)
| apache-2.0 | 6c8260728c01094cbc91adcdb0684d2e | 31.185714 | 120 | 0.606525 | 3.225483 | false | false | false | false |
drothmaler/kotlin-hashids | src/org/hashids/Hashids.kt | 1 | 9133 | package org.hashids
import java.util.ArrayList
import java.util.regex.Pattern
/**
* Hashids developed to generate short hashes from numbers (like YouTube).
* Can be used as forgotten password hashes, invitation codes, store shard numbers.
* This is implementation of http://hashids.org
*
* @author leprosus <[email protected]>
* @license MIT
*/
public class Hashids(salt: String = "", length: Int = 0, alphabet: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") {
private val min: Int = 16
private val sepsDiv: Double = 3.5
private val guardDiv: Int = 12
private var seps: String = "cfhistuCFHISTU"
private var guards: String
private var salt: String
private var length: Int
private var alphabet: String
private val whitespaceChars = "\\s+".toRegex()
init {
this.salt = salt
this.length = if (length > 0) length else 0
this.alphabet = alphabet.unique()
if (this.alphabet.length() < min)
throw IllegalArgumentException("Alphabet must contain at least " + min + " unique characters")
/**
* seps should contain only characters present in alphabet;
* alphabet should not contains seps
*/
for ((index, sep) in seps.withIndex()) {
val position = this.alphabet.indexOf(sep)
if (position == -1) {
seps = seps.substring(0, index) + " " + seps.substring(index + 1)
} else {
this.alphabet = this.alphabet.substring(0, position) + " " + this.alphabet.substring(position + 1)
}
}
this.alphabet = this.alphabet.replace(this.whitespaceChars, "")
seps = seps.replace(this.whitespaceChars, "")
seps = consistentShuffle(seps, this.salt)
if ((seps == "") || ((this.alphabet.length() / seps.length()) > sepsDiv)) {
var sepsCount = getCount(this.alphabet.length(), sepsDiv)
if (sepsCount == 1)
sepsCount++
if (sepsCount > seps.length()) {
val diff = sepsCount - seps.length()
seps += this.alphabet.substring(0, diff)
this.alphabet = this.alphabet.substring(diff)
} else {
seps = seps.substring(0, sepsCount)
}
}
this.alphabet = this.consistentShuffle(this.alphabet, this.salt)
val guardCount = getCount(this.alphabet.length(), guardDiv)
if (this.alphabet.length() < 3) {
guards = seps.substring(0, guardCount)
seps = seps.substring(guardCount)
} else {
guards = this.alphabet.substring(0, guardCount)
this.alphabet = this.alphabet.substring(guardCount)
}
}
/**
* Encrypt numbers to string
*
* @param numbers the numbers to encrypt
* @return The encrypt string
*/
fun encode(vararg numbers: Long): String {
if (numbers.size() == 0)
return ""
for (number in numbers)
if (number > 9007199254740992)
throw IllegalArgumentException("Number can not be greater than 9007199254740992L")
var numberHashInt: Int = 0
for (i in numbers.indices)
numberHashInt += (numbers[i] % (i + 100)).toInt()
var alphabet = this.alphabet
val retInt = alphabet[numberHashInt % alphabet.length()]
var retString = retInt + ""
for (i in numbers.indices) {
var num = numbers[i]
val buffer = retInt + salt + alphabet
alphabet = consistentShuffle(alphabet, buffer.substring(0, alphabet.length()))
val last = hash(num, alphabet)
retString += last
if (i + 1 < numbers.size()) {
num %= (last[0].toInt() + i)
val sepsIndex = (num % seps.length()).toInt()
retString += seps[sepsIndex]
}
}
if (retString.length() < length) {
var guardIndex = (numberHashInt + retString[0].toInt()) % guards.length()
var guard = guards[guardIndex]
retString = guard + retString
if (retString.length() < length) {
guardIndex = (numberHashInt + retString[2].toInt()) % guards.length()
guard = guards[guardIndex]
retString += guard
}
}
val halfLength = alphabet.length() / 2
while (retString.length() < length) {
alphabet = consistentShuffle(alphabet, alphabet)
retString = alphabet.substring(halfLength) + retString + alphabet.substring(0, halfLength)
val excess = retString.length() - length
if (excess > 0) {
val position = excess / 2
retString = retString.substring(position, position + length)
}
}
return retString
}
/**
* Decrypt string to numbers
*
* @param hash the encrypt string
* @return Decrypted numbers
*/
fun decode(hash: String): LongArray {
if (hash == "")
return longArrayOf()
var alphabet = this.alphabet
var hashBreakdown = hash.replace("[$guards]".toRegex(), " ")
var hashArray = hashBreakdown.splitBy(" ")
val i = if (hashArray.size() == 3 || hashArray.size() == 2) 1 else 0
hashBreakdown = hashArray[i]
val lottery = hashBreakdown[0]
hashBreakdown = hashBreakdown.substring(1)
hashBreakdown = hashBreakdown.replace(("[$seps]").toRegex(), " ")
hashArray = hashBreakdown.splitBy(" ")
val retArray = ArrayList<Long>()
for (subHash in hashArray) {
val buffer = lottery + salt + alphabet
alphabet = consistentShuffle(alphabet, buffer.substring(0, alphabet.length()))
retArray.add(unhash(subHash, alphabet))
}
var arr = LongArray(retArray.size())
for (index in retArray.indices) {
arr[index] = retArray[index]
}
if (encode(*arr) != hash) {
arr = LongArray(0)
}
return arr
}
/**
* Encrypt hexa to string
*
* @param hexa the hexa to encrypt
* @return The encrypt string
*/
fun encodeHex(hexa: String): String {
if (!hexa.matches("^[0-9a-fA-F]+$".toRegex()))
return ""
val matched = ArrayList<Long>()
val matcher = Pattern.compile("[\\w\\W]{1,12}").matcher(hexa)
while (matcher.find())
matched.add(java.lang.Long.parseLong("1" + matcher.group(), 16))
val result = LongArray(matched.size())
for (i in matched.indices) result[i] = matched[i]
return encode(*result)
}
/**
* Decrypt string to numbers
*
* @param hash the encrypt string
* @return Decrypted numbers
*/
fun decodeHex(hash: String): String {
var result = ""
val numbers = decode(hash)
for (number in numbers) {
result += java.lang.Long.toHexString(number).substring(1)
}
return result
}
private fun getCount(length: Int, div: Double): Int = Math.ceil(length.toDouble() / div.toDouble()).toInt()
private fun getCount(length: Int, div: Int): Int = getCount(length, div.toDouble())
private fun consistentShuffle(alphabet: String, salt: String): String {
if (salt.length() <= 0)
return alphabet
var shuffled = alphabet
val saltLength = salt.length()
var i = shuffled.length() - 1
var v = 0
var p = 0
while (i > 0) {
v %= saltLength
val integer = salt[v].toInt()
p += integer
val j = (integer + v + p) % i
val temp = shuffled[j]
shuffled = shuffled.substring(0, j) + shuffled[i] + shuffled.substring(j + 1)
shuffled = shuffled.substring(0, i) + temp + shuffled.substring(i + 1)
i--
v++
}
return shuffled
}
private fun hash(input: Long, alphabet: String): String {
var current = input
var hash = ""
val length = alphabet.length()
do {
hash = alphabet[(current % length.toLong()).toInt()] + hash
current /= length
} while (current > 0)
return hash
}
private fun unhash(input: String, alphabet: String): Long? {
var number: Long = 0
for ((i, c) in input.withIndex()) {
val position = alphabet.indexOf(c).toLong()
number += (position.toDouble() * Math.pow(alphabet.length().toDouble(), (input.length() - i - 1).toDouble())).toLong()
}
return number
}
SuppressWarnings("unused")
fun getVersion(): String {
return "1.0.0"
}
fun String.unique(): String {
var unique = ""
for (c in this) {
var current = "" + c
if (!unique.contains(current) && current != " ")
unique += current
}
return unique
}
} | mit | 9bb4c351d18be9716bffdfa9a9f542b2 | 28.849673 | 143 | 0.554363 | 4.228241 | false | false | false | false |
AsamK/TextSecure | qr/lib/src/main/java/org/signal/qr/ScannerView21.kt | 1 | 3309 | package org.signal.qr
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.ImageFormat
import android.util.Size
import android.widget.FrameLayout
import androidx.annotation.RequiresApi
import androidx.camera.core.AspectRatio
import androidx.camera.core.Camera
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.content.ContextCompat
import androidx.core.math.MathUtils.clamp
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import io.reactivex.rxjava3.subjects.PublishSubject
import org.signal.core.util.logging.Log
import org.signal.qr.kitkat.ScanListener
import java.nio.ByteBuffer
import java.util.concurrent.Executors
/**
* API21+ version of QR scanning view. Uses camerax APIs.
*/
@SuppressLint("ViewConstructor")
@RequiresApi(21)
internal class ScannerView21 constructor(
context: Context,
private val listener: ScanListener
) : FrameLayout(context), ScannerView {
private val analyzerExecutor = Executors.newSingleThreadExecutor()
private var cameraProvider: ProcessCameraProvider? = null
private var camera: Camera? = null
private var previewView: PreviewView
private val qrProcessor = QrProcessor()
init {
previewView = PreviewView(context)
previewView.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
addView(previewView)
}
override fun start(lifecycleOwner: LifecycleOwner) {
previewView.post {
Log.i(TAG, "Starting")
ProcessCameraProvider.getInstance(context).apply {
addListener({
try {
onCameraProvider(lifecycleOwner, get())
} catch (e: Exception) {
Log.w(TAG, e)
}
}, ContextCompat.getMainExecutor(context))
}
}
lifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onDestroy(owner: LifecycleOwner) {
cameraProvider = null
camera = null
analyzerExecutor.shutdown()
}
})
}
private fun onCameraProvider(lifecycle: LifecycleOwner, cameraProvider: ProcessCameraProvider?) {
if (cameraProvider == null) {
Log.w(TAG, "Camera provider is null")
return
}
Log.i(TAG, "Initializing use cases")
val preview = Preview.Builder().build()
val imageAnalysis = ImageAnalysis.Builder()
.setTargetResolution(Size(1920, 1080))
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build()
imageAnalysis.setAnalyzer(analyzerExecutor) { proxy ->
proxy.use {
val data: String? = qrProcessor.getScannedData(it)
if (data != null) {
listener.onQrDataFound(data)
}
}
}
cameraProvider.unbindAll()
camera = cameraProvider.bindToLifecycle(lifecycle, CameraSelector.DEFAULT_BACK_CAMERA, preview, imageAnalysis)
preview.setSurfaceProvider(previewView.surfaceProvider)
this.cameraProvider = cameraProvider
}
companion object {
private val TAG = Log.tag(ScannerView21::class.java)
}
}
| gpl-3.0 | 75ad9e0027b141eab8bae5f520c5e6ce | 29.357798 | 114 | 0.740707 | 4.680339 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/stories/viewer/reply/group/StoryGroupReplyItem.kt | 1 | 10693 | package org.thoughtcrime.securesms.stories.viewer.reply.group
import android.content.Context
import android.text.Spannable
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.CallSuper
import androidx.annotation.ColorInt
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.view.updateLayoutParams
import org.signal.core.util.DimensionUnit
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.AlertView
import org.thoughtcrime.securesms.components.AvatarImageView
import org.thoughtcrime.securesms.components.DeliveryStatusView
import org.thoughtcrime.securesms.components.FromTextView
import org.thoughtcrime.securesms.components.emoji.EmojiImageView
import org.thoughtcrime.securesms.components.emoji.EmojiTextView
import org.thoughtcrime.securesms.components.mention.MentionAnnotation
import org.thoughtcrime.securesms.components.menu.ActionItem
import org.thoughtcrime.securesms.components.menu.SignalContextMenu
import org.thoughtcrime.securesms.database.model.MessageRecord
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.util.AvatarUtil
import org.thoughtcrime.securesms.util.DateUtils
import org.thoughtcrime.securesms.util.ViewUtil
import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel
import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder
import org.thoughtcrime.securesms.util.changeConstraints
import org.thoughtcrime.securesms.util.padding
import org.thoughtcrime.securesms.util.visible
import java.util.Locale
typealias OnCopyClick = (CharSequence) -> Unit
typealias OnDeleteClick = (MessageRecord) -> Unit
typealias OnTapForDetailsClick = (MessageRecord) -> Unit
object StoryGroupReplyItem {
private const val NAME_COLOR_CHANGED = 1
fun register(mappingAdapter: MappingAdapter) {
mappingAdapter.registerFactory(TextModel::class.java, LayoutFactory(::TextViewHolder, R.layout.stories_group_text_reply_item))
mappingAdapter.registerFactory(ReactionModel::class.java, LayoutFactory(::ReactionViewHolder, R.layout.stories_group_text_reply_item))
mappingAdapter.registerFactory(RemoteDeleteModel::class.java, LayoutFactory(::RemoteDeleteViewHolder, R.layout.stories_group_text_reply_item))
}
sealed class Model<T : Any>(
val replyBody: ReplyBody,
@ColorInt val nameColor: Int,
val onCopyClick: OnCopyClick?,
val onDeleteClick: OnDeleteClick,
val onTapForDetailsClick: OnTapForDetailsClick
) : MappingModel<T> {
val messageRecord: MessageRecord = replyBody.messageRecord
val isPending: Boolean = messageRecord.isPending
val isFailure: Boolean = messageRecord.isFailed
val sentAtMillis: Long = replyBody.sentAtMillis
override fun areItemsTheSame(newItem: T): Boolean {
val other = newItem as Model<*>
return replyBody.sender == other.replyBody.sender &&
replyBody.sentAtMillis == other.replyBody.sentAtMillis
}
override fun areContentsTheSame(newItem: T): Boolean {
val other = newItem as Model<*>
return areNonPayloadPropertiesTheSame(other) &&
nameColor == other.nameColor
}
override fun getChangePayload(newItem: T): Any? {
val other = newItem as Model<*>
return if (nameColor != other.nameColor && areNonPayloadPropertiesTheSame(other)) {
NAME_COLOR_CHANGED
} else {
null
}
}
private fun areNonPayloadPropertiesTheSame(newItem: Model<*>): Boolean {
return replyBody.hasSameContent(newItem.replyBody) &&
isPending == newItem.isPending &&
isFailure == newItem.isFailure &&
sentAtMillis == newItem.sentAtMillis
}
}
class TextModel(
val text: ReplyBody.Text,
val onMentionClick: (RecipientId) -> Unit,
@ColorInt nameColor: Int,
onCopyClick: OnCopyClick,
onDeleteClick: OnDeleteClick,
onTapForDetailsClick: OnTapForDetailsClick
) : Model<TextModel>(
replyBody = text,
nameColor = nameColor,
onCopyClick = onCopyClick,
onDeleteClick = onDeleteClick,
onTapForDetailsClick = onTapForDetailsClick
)
class ReactionModel(
val reaction: ReplyBody.Reaction,
@ColorInt nameColor: Int,
onCopyClick: OnCopyClick,
onDeleteClick: OnDeleteClick,
onTapForDetailsClick: OnTapForDetailsClick
) : Model<ReactionModel>(
replyBody = reaction,
nameColor = nameColor,
onCopyClick = onCopyClick,
onDeleteClick = onDeleteClick,
onTapForDetailsClick = onTapForDetailsClick
)
class RemoteDeleteModel(
val remoteDelete: ReplyBody.RemoteDelete,
@ColorInt nameColor: Int,
onDeleteClick: OnDeleteClick,
onTapForDetailsClick: OnTapForDetailsClick
) : Model<RemoteDeleteModel>(
replyBody = remoteDelete,
nameColor = nameColor,
onCopyClick = null,
onDeleteClick = onDeleteClick,
onTapForDetailsClick = onTapForDetailsClick
)
private abstract class BaseViewHolder<T : Model<T>>(itemView: View) : MappingViewHolder<T>(itemView) {
protected val bubble: View = findViewById(R.id.bubble)
protected val avatar: AvatarImageView = findViewById(R.id.avatar)
protected val name: FromTextView = findViewById(R.id.name)
protected val body: EmojiTextView = findViewById(R.id.body)
protected val date: TextView = findViewById(R.id.viewed_at)
protected val dateBelow: TextView = findViewById(R.id.viewed_at_below)
protected val status: DeliveryStatusView = findViewById(R.id.delivery_status)
protected val alertView: AlertView = findViewById(R.id.alert_view)
protected val reaction: EmojiImageView = itemView.findViewById(R.id.reaction)
@CallSuper
override fun bind(model: T) {
itemView.setOnLongClickListener {
displayContextMenu(model)
true
}
name.setTextColor(model.nameColor)
if (payload.contains(NAME_COLOR_CHANGED)) {
return
}
AvatarUtil.loadIconIntoImageView(model.replyBody.sender, avatar, DimensionUnit.DP.toPixels(28f).toInt())
name.text = resolveName(context, model.replyBody.sender)
if (model.isPending) {
status.setPending()
} else {
status.setNone()
}
if (model.isFailure) {
alertView.setFailed()
itemView.setOnClickListener {
model.onTapForDetailsClick(model.messageRecord)
}
date.setText(R.string.ConversationItem_error_not_sent_tap_for_details)
dateBelow.setText(R.string.ConversationItem_error_not_sent_tap_for_details)
} else {
alertView.setNone()
itemView.setOnClickListener(null)
val dateText = DateUtils.getBriefRelativeTimeSpanString(context, Locale.getDefault(), model.sentAtMillis)
date.text = dateText
dateBelow.text = dateText
}
itemView.post {
if (alertView.visible || body.lastLineWidth + date.measuredWidth > ViewUtil.dpToPx(242)) {
date.visible = false
dateBelow.visible = true
} else {
dateBelow.visible = false
date.visible = true
}
}
}
private fun displayContextMenu(model: Model<*>) {
itemView.isSelected = true
val actions = mutableListOf<ActionItem>()
if (model.onCopyClick != null) {
actions += ActionItem(R.drawable.ic_copy_24_solid_tinted, context.getString(R.string.StoryGroupReplyItem__copy)) {
val toCopy: CharSequence = when (model) {
is TextModel -> model.text.message.getDisplayBody(context)
else -> model.messageRecord.getDisplayBody(context)
}
model.onCopyClick.invoke(toCopy)
}
}
actions += ActionItem(R.drawable.ic_trash_24_solid_tinted, context.getString(R.string.StoryGroupReplyItem__delete)) { model.onDeleteClick(model.messageRecord) }
SignalContextMenu.Builder(itemView, itemView.rootView as ViewGroup)
.preferredHorizontalPosition(SignalContextMenu.HorizontalPosition.START)
.onDismiss { itemView.isSelected = false }
.show(actions)
}
}
private class TextViewHolder(itemView: View) : BaseViewHolder<TextModel>(itemView) {
override fun bind(model: TextModel) {
super.bind(model)
body.movementMethod = LinkMovementMethod.getInstance()
body.text = model.text.message.getDisplayBody(context).apply {
linkifyBody(model, this)
}
}
private fun linkifyBody(model: TextModel, body: Spannable) {
val mentionAnnotations = MentionAnnotation.getMentionAnnotations(body)
for (annotation in mentionAnnotations) {
body.setSpan(MentionClickableSpan(model, RecipientId.from(annotation.value)), body.getSpanStart(annotation), body.getSpanEnd(annotation), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
private class MentionClickableSpan(
private val model: TextModel,
private val mentionedRecipientId: RecipientId
) : ClickableSpan() {
override fun onClick(widget: View) {
model.onMentionClick(mentionedRecipientId)
}
override fun updateDrawState(ds: TextPaint) = Unit
}
}
private class ReactionViewHolder(itemView: View) : BaseViewHolder<ReactionModel>(itemView) {
init {
reaction.visible = true
bubble.visibility = View.INVISIBLE
itemView.padding(bottom = 0)
body.setText(R.string.StoryGroupReactionReplyItem__reacted_to_the_story)
body.updateLayoutParams<ViewGroup.MarginLayoutParams> {
marginEnd = 0
}
(itemView as ConstraintLayout).changeConstraints {
connect(avatar.id, ConstraintSet.BOTTOM, body.id, ConstraintSet.BOTTOM)
}
}
override fun bind(model: ReactionModel) {
super.bind(model)
reaction.setImageEmoji(model.reaction.emoji)
}
}
private class RemoteDeleteViewHolder(itemView: View) : BaseViewHolder<RemoteDeleteModel>(itemView) {
init {
bubble.setBackgroundResource(R.drawable.rounded_outline_secondary_18)
body.setText(R.string.ThreadRecord_this_message_was_deleted)
}
}
private fun resolveName(context: Context, recipient: Recipient): String {
return if (recipient.isSelf) {
context.getString(R.string.StoryViewerPageFragment__you)
} else {
recipient.getDisplayName(context)
}
}
}
| gpl-3.0 | 312c5f6a37901b85524dacdf022f94e3 | 36 | 179 | 0.734967 | 4.529013 | false | false | false | false |
marius-m/wt4 | database2/src/main/java/lt/markmerkk/migrations/Migration4To5.kt | 1 | 1029 | package lt.markmerkk.migrations
import lt.markmerkk.DBConnProvider
import lt.markmerkk.Tags
import org.slf4j.LoggerFactory
import java.sql.Connection
import java.sql.SQLException
class Migration4To5(
private val database: DBConnProvider
) : DBMigration {
override val migrateVersionFrom: Int = 4
override val migrateVersionTo: Int = 5
override fun migrate(conn: Connection) {
val sql = "CREATE TABLE `ticket_status` (\n" +
" `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" `name` VARCHAR(100) DEFAULT '' NOT NULL\n" +
");"
try {
val createTableStatement = conn.createStatement()
logger.debug("Creating new table: $sql")
createTableStatement.execute(sql)
} catch (e: SQLException) {
logger.error("Error executing migration from $migrateVersionFrom to $migrateVersionTo", e)
}
}
companion object {
private val logger = LoggerFactory.getLogger(Tags.DB)!!
}
} | apache-2.0 | a767047428681176fbf1229d721d5d63 | 30.212121 | 102 | 0.642371 | 4.416309 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/FormsTest.kt | 1 | 1593 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.tests
import io.ktor.client.call.*
import io.ktor.client.engine.mock.*
import io.ktor.client.request.*
import io.ktor.client.request.forms.*
import io.ktor.client.tests.utils.*
import io.ktor.http.*
import io.ktor.utils.io.streams.*
import java.io.*
import kotlin.test.*
class FormsTest {
@Test
fun testEmptyFormData() = testWithEngine(MockEngine) {
config {
engine {
addHandler {
val content = it.body.toByteReadPacket()
respondOk(content.readText())
}
}
}
test { client ->
val input = object : InputStream() {
override fun read(): Int = -1
}.asInput()
val builder = HttpRequestBuilder().apply {
setBody(
MultiPartFormDataContent(
formData {
appendInput(
"file",
Headers.build {
append(HttpHeaders.ContentType, ContentType.Text.Plain.toString())
append(HttpHeaders.ContentDisposition, "filename=myfile.txt")
}
) { input }
}
)
)
}
client.request(builder).body<String>()
}
}
}
| apache-2.0 | 65b6609f762529ee9c3f6e396b2393ff | 28.5 | 119 | 0.47897 | 5.15534 | false | true | false | false |
CzBiX/v2ex-android | app/src/main/kotlin/com/czbix/v2ex/db/Member.kt | 1 | 2606 | package com.czbix.v2ex.db
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.czbix.v2ex.common.exception.FatalException
import com.czbix.v2ex.model.Avatar
import com.czbix.v2ex.model.Page
import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder
import kotlinx.android.parcel.Parcelize
import java.util.concurrent.ExecutionException
import java.util.regex.Pattern
@Entity
@Parcelize
data class Member(
@PrimaryKey
val username: String,
@Embedded
val avatar: Avatar
) : Page() {
override fun getTitle(): String? {
return username
}
override fun getUrl(): String {
return buildUrlFromName(username)
}
fun isSameUser(member: Member): Boolean {
return this.username == member.username
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
if (!super.equals(other)) return false
other as Member
if (username != other.username) return false
if (avatar != other.avatar) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + username.hashCode()
result = 31 * result + avatar.hashCode()
return result
}
companion object {
private val PATTERN = Pattern.compile("/member/(.+?)(?:\\W|$)")
@JvmStatic
fun getNameFromUrl(url: String): String {
val matcher = PATTERN.matcher(url)
if (!matcher.find()) {
throw FatalException("Match name for member failed: $url")
}
return matcher.group(1)
}
fun buildUrlFromName(username: String): String {
return "/member/$username"
}
}
class Builder {
lateinit var username: String
lateinit var avatar: Avatar
fun build(): Member {
try {
return CACHE.get(username) {
Member(username, avatar)
}
} catch (e: ExecutionException) {
throw FatalException(e)
}
}
companion object {
private val CACHE: Cache<String, Member>
init {
CACHE = CacheBuilder.newBuilder()
.initialCapacity(32)
.maximumSize(128)
.softValues()
.build<String, Member>()
}
}
}
}
| apache-2.0 | 9a2972c536a5054146a079e88e43ce44 | 25.06 | 74 | 0.571757 | 4.799263 | false | false | false | false |
android/gradle-recipes | BuildSrc/customizeAgpDslAndVariant/buildSrc/src/main/kotlin/ProviderPlugin.kt | 1 | 1916 | /*
* Copyright (C) 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.
*/
import org.gradle.api.Plugin
import org.gradle.api.Project
import java.io.File
import com.android.build.api.dsl.ApplicationExtension
import com.android.build.api.variant.AndroidComponentsExtension
abstract class ProviderPlugin: Plugin<Project> {
override fun apply(project: Project) {
val objects = project.getObjects();
val android = project.extensions.getByType(ApplicationExtension::class.java)
android.buildTypes.forEach {
it.extensions.add(
"exampleDsl",
BuildTypeExtension::class.java)
}
val androidComponents = project.extensions.getByType(AndroidComponentsExtension::class.java)
androidComponents.beforeVariants { variantBuilder ->
val variantExtension = objects.newInstance(VariantExtension::class.java)
val debug = android.buildTypes.getByName(variantBuilder.name)
val buildTypeExtension = debug.extensions.findByName("exampleDsl")
as BuildTypeExtension
variantExtension.parameters.set(
buildTypeExtension.invocationParameters ?: ""
)
variantBuilder.registerExtension(
VariantExtension::class.java,
variantExtension
)
}
}
} | apache-2.0 | 3d1c6a335ddbe70bdd354caa84f748bc | 35.865385 | 100 | 0.688413 | 4.862944 | false | false | false | false |
google/fastboot-mobile | lib/src/main/java/com/google/android/fastbootmobile/FastbootDeviceContext.kt | 1 | 1448 | /*
* 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.google.android.fastbootmobile
import com.google.android.fastbootmobile.transport.Transport
class FastbootDeviceContext internal constructor(private val transport: Transport) {
fun sendCommand(command: FastbootCommand, timeout: Int = DEFAULT_TIMEOUT,
force: Boolean = true): FastbootResponse {
if (!transport.isConnected) {
transport.connect(force)
}
val commandStr = command.toString()
transport.send(commandStr.toByteArray(), timeout)
val responseBytes = ByteArray(64)
transport.receive(responseBytes, timeout)
return FastbootResponse.fromBytes(responseBytes)
}
fun close() {
transport.disconnect()
transport.close()
}
companion object {
@JvmStatic
private val DEFAULT_TIMEOUT = 1000
}
}
| apache-2.0 | a8eb67235091018b16adbcf9c6c8b1c2 | 30.478261 | 84 | 0.695442 | 4.567823 | false | false | false | false |
iSoron/uhabits | uhabits-android/src/main/java/org/isoron/uhabits/activities/habits/list/views/EmptyListView.kt | 1 | 2689 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.activities.habits.list.views
import android.content.Context
import android.view.Gravity.CENTER
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.LinearLayout
import android.widget.TextView
import org.isoron.uhabits.R
import org.isoron.uhabits.utils.dp
import org.isoron.uhabits.utils.getFontAwesome
import org.isoron.uhabits.utils.sp
import org.isoron.uhabits.utils.sres
import org.isoron.uhabits.utils.str
class EmptyListView(context: Context) : LinearLayout(context) {
var textTextView: TextView
var iconTextView: TextView
init {
orientation = VERTICAL
gravity = CENTER
visibility = View.GONE
iconTextView = TextView(context).apply {
text = str(R.string.fa_star_half_o)
typeface = getFontAwesome()
textSize = sp(40.0f)
gravity = CENTER
setTextColor(sres.getColor(R.attr.contrast60))
}
addView(
iconTextView,
MATCH_PARENT,
WRAP_CONTENT
)
textTextView = TextView(context).apply {
text = str(R.string.no_habits_found)
gravity = CENTER
setPadding(0, dp(20.0f).toInt(), 0, 0)
setTextColor(sres.getColor(R.attr.contrast60))
}
addView(
textTextView,
MATCH_PARENT,
WRAP_CONTENT
)
}
fun showDone() {
visibility = VISIBLE
iconTextView.text = str(R.string.fa_umbrella_beach)
textTextView.text = str(R.string.no_habits_left_to_do)
}
fun showEmpty() {
visibility = VISIBLE
iconTextView.text = str(R.string.fa_star_half_o)
textTextView.text = str(R.string.no_habits_found)
}
fun hide() {
visibility = GONE
}
}
| gpl-3.0 | 23be5628baacfa9fdcede70144028112 | 29.896552 | 78 | 0.667039 | 4.085106 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/VerboseNullabilityAndEmptinessInspection.kt | 1 | 17304 | // 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.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.psi2ir.deparenthesize
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.findOriginalTopMostOverriddenDescriptors
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.isError
class VerboseNullabilityAndEmptinessInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = binaryExpressionVisitor(fun(unwrappedNullCheckExpression) {
val nullCheckExpression = findNullCheckExpression(unwrappedNullCheckExpression)
val nullCheck = getNullCheck(nullCheckExpression) ?: return
val binaryExpression = findBinaryExpression(nullCheckExpression) ?: return
val operationToken = binaryExpression.operationToken
val isPositiveCheck = when {
!nullCheck.isEqualNull && operationToken == KtTokens.ANDAND -> true // a != null && a.isNotEmpty()
nullCheck.isEqualNull && operationToken == KtTokens.OROR -> false // a == null || a.isEmpty()
else -> return
}
val contentCheckExpression = findContentCheckExpression(nullCheckExpression, binaryExpression) ?: return
val contentCheck = getContentCheck(contentCheckExpression) ?: return
if (isPositiveCheck != contentCheck.isPositiveCheck) return
if (!isSimilar(nullCheck.target, contentCheck.target, ::psiOnlyTargetCheck)) return
val bindingContext = binaryExpression.analyze(BodyResolveMode.PARTIAL)
if (!isSimilar(nullCheck.target, contentCheck.target, resolutionTargetCheckFactory(bindingContext))) return
// Lack of smart-cast in 'a != null && <<a>>.isNotEmpty()' means it's rather some complex expression. Skip those for now
if (!contentCheck.target.last().hasSmartCast(bindingContext)) return
val contentCheckCall = contentCheck.call.getResolvedCall(bindingContext) ?: return
val contentCheckFunction = contentCheckCall.resultingDescriptor as? SimpleFunctionDescriptor ?: return
if (!checkTargetFunctionReceiver(contentCheckFunction)) return
val overriddenFunctions = contentCheckFunction.findOriginalTopMostOverriddenDescriptors()
if (overriddenFunctions.none { it.fqNameOrNull()?.asString() in contentCheck.data.callableNames }) return
val hasExplicitReceiver = contentCheck.target.singleOrNull() !is TargetChunk.ImplicitThis
val replacementName = contentCheck.data.replacementName
holder.registerProblem(
nullCheckExpression,
KotlinBundle.message("inspection.verbose.nullability.and.emptiness.call", (if (isPositiveCheck) "!" else "") + replacementName),
ReplaceFix(replacementName, hasExplicitReceiver, isPositiveCheck)
)
})
private fun checkTargetFunctionReceiver(function: SimpleFunctionDescriptor): Boolean {
val type = getSingleReceiver(function.dispatchReceiverParameter?.value, function.extensionReceiverParameter?.value)?.type
return type != null && !type.isError && !type.isMarkedNullable && !KotlinBuiltIns.isPrimitiveArray(type)
}
private fun psiOnlyTargetCheck(left: TargetChunk, right: TargetChunk) = left.kind == right.kind && left.name == right.name
private fun resolutionTargetCheckFactory(bindingContext: BindingContext): (TargetChunk, TargetChunk) -> Boolean = r@ { left, right ->
val leftValue = left.resolve(bindingContext) ?: return@r false
val rightValue = right.resolve(bindingContext) ?: return@r false
return@r leftValue == rightValue
}
private fun getTargetChain(targetExpression: KtExpression): TargetChain? {
val result = mutableListOf<TargetChunk>()
fun processDepthFirst(expression: KtExpression): Boolean {
when (val unwrapped = expression.deparenthesize()) {
is KtNameReferenceExpression -> result += TargetChunk.Name(unwrapped)
is KtDotQualifiedExpression -> {
if (!processDepthFirst(unwrapped.receiverExpression)) return false
val selectorExpression = unwrapped.selectorExpression as? KtNameReferenceExpression ?: return false
result += TargetChunk.Name(selectorExpression)
}
is KtThisExpression -> result += TargetChunk.ExplicitThis(unwrapped)
else -> return false
}
return true
}
return if (processDepthFirst(targetExpression)) result.takeIf { it.isNotEmpty() } else null
}
private fun isSimilar(left: TargetChain, right: TargetChain, checker: (TargetChunk, TargetChunk) -> Boolean): Boolean {
return left.size == right.size && left.indices.all { index -> checker(left[index], right[index]) }
}
private fun <T: Any> unwrapNegation(expression: KtExpression, block: (KtExpression, Boolean) -> T?): T? {
if (expression is KtPrefixExpression && expression.operationToken == KtTokens.EXCL) {
val baseExpression = expression.baseExpression?.deparenthesize() as? KtExpression ?: return null
return block(baseExpression, true)
}
return block(expression, false)
}
private class NullCheck(val target: TargetChain, val isEqualNull: Boolean)
private fun getNullCheck(expression: KtExpression) = unwrapNegation(expression, fun(expression, isNegated): NullCheck? {
if (expression !is KtBinaryExpression) return null
val isNull = when (expression.operationToken) {
KtTokens.EQEQ -> true
KtTokens.EXCLEQ -> false
else -> return null
} xor isNegated
val left = expression.left ?: return null
val right = expression.right ?: return null
fun createTarget(targetExpression: KtExpression, isNull: Boolean): NullCheck? {
val targetReferenceExpression = getTargetChain(targetExpression) ?: return null
return NullCheck(targetReferenceExpression, isNull)
}
return when {
left.isNullLiteral() -> createTarget(right, isNull)
right.isNullLiteral() -> createTarget(left, isNull)
else -> null
}
})
private class ContentCheck(val target: TargetChain, val call: KtCallExpression, val data: ContentFunction, val isPositiveCheck: Boolean)
private fun getContentCheck(expression: KtExpression) = unwrapNegation(expression, fun(expression, isNegated): ContentCheck? {
val (callExpression, target) = when (expression) {
is KtCallExpression -> expression to listOf(TargetChunk.ImplicitThis(expression))
is KtDotQualifiedExpression -> {
val targetChain = getTargetChain(expression.receiverExpression) ?: return null
(expression.selectorExpression as? KtCallExpression) to targetChain
}
else -> return null
}
val calleeText = callExpression?.calleeExpression?.text ?: return null
val contentFunction = contentCheckingFunctions[calleeText] ?: return null
return ContentCheck(target, callExpression, contentFunction, contentFunction.isPositiveCheck xor isNegated)
})
private class ReplaceFix(
private val functionName: String,
private val hasExplicitReceiver: Boolean,
private val isPositiveCheck: Boolean
) : LocalQuickFix {
override fun getFamilyName() = KotlinBundle.message("replace.with.0.call", functionName)
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val nullCheckExpression = descriptor.psiElement as? KtExpression ?: return
val binaryExpression = findBinaryExpression(nullCheckExpression) ?: return
val parenthesizedParent = binaryExpression.getTopmostParenthesizedParent() as? KtParenthesizedExpression
val expressionText = buildString {
if (isPositiveCheck) append("!")
if (hasExplicitReceiver) {
val receiverExpression = getReceiver(nullCheckExpression) ?: return
append(receiverExpression.text).append(".")
}
append(functionName).append("()")
}
val callExpression = KtPsiFactory(project).createExpression(expressionText)
when (nullCheckExpression.parenthesize()) {
binaryExpression.left -> binaryExpression.replace(callExpression)
binaryExpression.right -> {
val outerBinaryExpression = binaryExpression.parent as? KtBinaryExpression ?: return
val leftExpression = binaryExpression.left ?: return
binaryExpression.replace(leftExpression) // flag && a != null && a.isNotEmpty() -> flag && a.isNotEmpty()
outerBinaryExpression.right?.replace(callExpression) // flag && a.isNotEmpty() -> flag && !a.isNullOrEmpty()
}
}
if (parenthesizedParent != null && KtPsiUtil.areParenthesesUseless(parenthesizedParent)) {
parenthesizedParent.replace(parenthesizedParent.deparenthesize())
}
}
private fun getReceiver(expression: KtExpression?): KtExpression? = when {
expression is KtPrefixExpression && expression.operationToken == KtTokens.EXCL -> {
val baseExpression = expression.baseExpression?.deparenthesize()
if (baseExpression is KtExpression) getReceiver(baseExpression) else null
}
expression is KtBinaryExpression -> when {
expression.left?.isNullLiteral() == true -> expression.right
expression.right?.isNullLiteral() == true -> expression.left
else -> null
}
else -> null
}
}
private class ContentFunction(val isPositiveCheck: Boolean, val replacementName: String, vararg val callableNames: String)
companion object {
private val contentCheckingFunctions = mapOf(
"isEmpty" to ContentFunction(
isPositiveCheck = false, replacementName = "isNullOrEmpty",
"kotlin.collections.Collection.isEmpty",
"kotlin.collections.Map.isEmpty",
"kotlin.collections.isEmpty",
"kotlin.text.isEmpty"
),
"isBlank" to ContentFunction(
isPositiveCheck = false, replacementName = "isNullOrBlank",
"kotlin.text.isBlank"
),
"isNotEmpty" to ContentFunction(
isPositiveCheck = true, replacementName = "isNullOrEmpty",
"kotlin.collections.isNotEmpty",
"kotlin.text.isNotEmpty"
),
"isNotBlank" to ContentFunction(
isPositiveCheck = true, replacementName = "isNullOrBlank",
"kotlin.text.isNotBlank"
)
)
private fun findNullCheckExpression(unwrappedNullCheckExpression: KtExpression): KtExpression {
// Find topmost binary negation (!a), skipping intermediate parentheses, annotations and other miscellaneous expressions
var result = unwrappedNullCheckExpression
for (parent in unwrappedNullCheckExpression.parents) {
when (parent) {
!is KtExpression -> break
is KtPrefixExpression -> if (parent.operationToken != KtTokens.EXCL) break
else -> if (KtPsiUtil.deparenthesizeOnce(parent) === result) continue else break
}
result = parent
}
return result
}
private fun findBinaryExpression(nullCheckExpression: KtExpression): KtBinaryExpression? {
return nullCheckExpression.parenthesize().parent as? KtBinaryExpression
}
private fun findContentCheckExpression(nullCheckExpression: KtExpression, binaryExpression: KtBinaryExpression): KtExpression? {
// There's no polyadic expression in Kotlin, so nullability and emptiness checks might be in different 'KtBinaryExpression's
when (nullCheckExpression.parenthesize()) {
binaryExpression.left -> {
// [[a != null && a.isNotEmpty()] && flag] && flag2
return binaryExpression.right?.deparenthesize() as? KtExpression
}
binaryExpression.right -> {
// [[flag && flag2] && a != null] && a.isNotEmpty()
val outerBinaryExpression = binaryExpression.parent as? KtBinaryExpression
if (outerBinaryExpression != null && outerBinaryExpression.operationToken == binaryExpression.operationToken) {
return outerBinaryExpression.right?.deparenthesize() as? KtExpression
}
}
}
return null
}
}
}
private typealias TargetChain = List<TargetChunk>
private sealed class TargetChunk(val kind: Kind) {
enum class Kind { THIS, NAME }
class ExplicitThis(val expression: KtThisExpression) : TargetChunk(Kind.THIS) {
override val name: String?
get() = null
override fun resolve(bindingContext: BindingContext): Any? {
val descriptor = expression.getResolvedCall(bindingContext)?.resultingDescriptor
return (descriptor as? ReceiverParameterDescriptor)?.value ?: descriptor
}
override fun hasSmartCast(bindingContext: BindingContext): Boolean {
return bindingContext[BindingContext.SMARTCAST, expression] != null
}
}
class ImplicitThis(val expression: KtCallExpression) : TargetChunk(Kind.THIS) {
override val name: String?
get() = null
override fun resolve(bindingContext: BindingContext): Any? {
val resolvedCall = expression.getResolvedCall(bindingContext) ?: return null
return getSingleReceiver(resolvedCall.dispatchReceiver, resolvedCall.extensionReceiver)
}
override fun hasSmartCast(bindingContext: BindingContext): Boolean {
return bindingContext[BindingContext.IMPLICIT_RECEIVER_SMARTCAST, expression.calleeExpression] != null
}
}
class Name(val expression: KtNameReferenceExpression) : TargetChunk(Kind.NAME) {
override val name: String
get() = expression.getReferencedName()
override fun resolve(bindingContext: BindingContext) = bindingContext[BindingContext.REFERENCE_TARGET, expression]
override fun hasSmartCast(bindingContext: BindingContext): Boolean {
var current = expression.getQualifiedExpressionForSelectorOrThis()
while (true) {
if (bindingContext[BindingContext.SMARTCAST, current] != null) return true
current = current.getParenthesizedParent() ?: return false
}
}
}
abstract val name: String?
abstract fun resolve(bindingContext: BindingContext): Any?
abstract fun hasSmartCast(bindingContext: BindingContext): Boolean
}
private fun getSingleReceiver(dispatchReceiver: ReceiverValue?, extensionReceiver: ReceiverValue?): ReceiverValue? {
if (dispatchReceiver != null && extensionReceiver != null) {
// Sic! Functions such as 'isEmpty()' never have both dispatch and extension receivers
return null
}
return dispatchReceiver ?: extensionReceiver
}
private fun KtExpression.isNullLiteral(): Boolean {
return (deparenthesize() as? KtConstantExpression)?.text == KtTokens.NULL_KEYWORD.value
}
private fun KtExpression.getParenthesizedParent(): KtExpression? {
return (parent as? KtExpression)?.takeIf { KtPsiUtil.deparenthesizeOnce(it) === this }
}
private fun KtExpression.getTopmostParenthesizedParent(): KtExpression? {
var current = getParenthesizedParent() ?: return null
while (true) {
current = current.getParenthesizedParent() ?: break
}
return current
}
private fun KtExpression.parenthesize(): KtExpression {
return getTopmostParenthesizedParent() ?: this
} | apache-2.0 | 3e07446985d0ca817dc019db2a8bbd21 | 47.337989 | 140 | 0.680883 | 5.640156 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/base/db/migrations/Migration15.kt | 1 | 1086 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.base.db.migrations
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.room.migration.Migration
object Migration15 : Migration(14, 15) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("UPDATE SHOOT SET arrow = NULL WHERE arrow = '-1'")
database.execSQL(
"UPDATE PASSE SET exact = 1 WHERE _id IN (SELECT DISTINCT p._id " +
"FROM PASSE p, SHOOT s " +
"WHERE p._id = s.passe " +
"AND s.x != 0)"
)
}
}
| gpl-2.0 | 445d4027c7f9e0d7d3ea2aacc6f2fb39 | 34.032258 | 79 | 0.668508 | 4.225681 | false | false | false | false |
android/location-samples | LocationUpdatesBackgroundKotlin/app/src/main/java/com/google/android/gms/location/sample/locationupdatesbackgroundkotlin/viewmodels/LocationUpdateViewModel.kt | 2 | 1681 | /*
* Copyright (C) 2020 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.gms.location.sample.locationupdatesbackgroundkotlin.viewmodels
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import com.google.android.gms.location.sample.locationupdatesbackgroundkotlin.data.LocationRepository
import java.util.concurrent.Executors
/**
* Allows Fragment to observer {@link MyLocation} database, follow the state of location updates,
* and start/stop receiving location updates.
*/
class LocationUpdateViewModel(application: Application) : AndroidViewModel(application) {
private val locationRepository = LocationRepository.getInstance(
application.applicationContext,
Executors.newSingleThreadExecutor()
)
val receivingLocationUpdates: LiveData<Boolean> = locationRepository.receivingLocationUpdates
val locationListLiveData = locationRepository.getLocations()
fun startLocationUpdates() = locationRepository.startLocationUpdates()
fun stopLocationUpdates() = locationRepository.stopLocationUpdates()
}
| apache-2.0 | 56cd0efd122703e4873d3c5ba029346f | 39.02381 | 101 | 0.787626 | 4.858382 | false | false | false | false |
androidx/gcp-gradle-build-cache | gcpbuildcache/src/functionalTest/kotlin/androidx/build/gradle/gcpbuildcache/GcpGradleBuildCachePluginFunctionalTest.kt | 1 | 2025 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*
* This Kotlin source file was generated by the Gradle 'init' task.
*/
package androidx.build.gradle.gcpbuildcache
import org.gradle.testkit.runner.GradleRunner
import org.junit.Rule
import org.junit.rules.TemporaryFolder
import kotlin.test.Test
/**
* A simple functional test for the 'androidx.build.gradle.gcpbuildcache.GcpBuildCache' plugin.
*/
class GcpGradleBuildCachePluginFunctionalTest {
@get:Rule val tempFolder = TemporaryFolder()
private fun getProjectDir() = tempFolder.root
private fun getBuildFile() = getProjectDir().resolve("build.gradle.kts")
private fun getSettingsFile() = getProjectDir().resolve("settings.gradle.kts")
@Test
fun `can run tasks task`() {
// Setup the test build
getSettingsFile().writeText("""
plugins {
id("androidx.build.gradle.gcpbuildcache")
}
buildCache {
remote(androidx.build.gradle.gcpbuildcache.GcpBuildCache::class) {
projectId = "foo"
bucketName = "bar"
}
}
""".trimIndent())
getBuildFile().writeText("")
// Run the build
val runner = GradleRunner.create()
runner.forwardOutput()
runner.withPluginClasspath()
runner.withArguments("tasks")
runner.withProjectDir(getProjectDir())
runner.build();
}
}
| apache-2.0 | 376c938e6bdc6f49ac72e5408c9f7551 | 31.66129 | 95 | 0.664691 | 4.540359 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.